]> Creatis software - gdcm.git/blob - src/gdcmDataEntry.cxx
* Minor coding-style clean up
[gdcm.git] / src / gdcmDataEntry.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDataEntry.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/10/18 08:35:51 $
7   Version:   $Revision: 1.1 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19 #include "gdcmDataEntry.h"
20 #include "gdcmVR.h"
21 #include "gdcmTS.h"
22 #include "gdcmGlobal.h"
23 #include "gdcmUtil.h"
24 #include "gdcmDebug.h"
25
26 #include <fstream>
27
28 namespace gdcm 
29 {
30 //-----------------------------------------------------------------------------
31 #define MAX_SIZE_PRINT_ELEMENT_VALUE 0x7fffffff
32 uint32_t DataEntry::MaxSizePrintEntry = MAX_SIZE_PRINT_ELEMENT_VALUE;
33
34 //-----------------------------------------------------------------------------
35 // Constructor / Destructor
36 /**
37  * \brief   Constructor for a given DictEntry
38  * @param   e Pointer to existing dictionary entry
39  */
40 DataEntry::DataEntry(DictEntry *e) 
41             : DocEntry(e)
42 {
43    State = STATE_LOADED;
44    Flag = FLAG_NONE;
45
46    BinArea = 0;
47    SelfArea = true;
48 }
49
50 /**
51  * \brief   Constructor for a given DocEntry
52  * @param   e Pointer to existing Doc entry
53  */
54 DataEntry::DataEntry(DocEntry *e)
55             : DocEntry(e->GetDictEntry())
56 {
57    Flag = 0;
58    BinArea = 0;
59    SelfArea = true;
60
61    Copy(e);
62 }
63
64 /**
65  * \brief   Canonical destructor.
66  */
67 DataEntry::~DataEntry ()
68 {
69    DeleteBinArea();
70 }
71
72 //-----------------------------------------------------------------------------
73 // Print
74
75 //-----------------------------------------------------------------------------
76 // Public
77 /**
78  * \brief Sets the value (non string) of the current Dicom Header Entry
79  */
80 void DataEntry::SetBinArea( uint8_t *area, bool self )  
81
82    DeleteBinArea();
83
84    BinArea = area;
85    SelfArea = self;
86
87    State = STATE_LOADED;
88 }
89
90 void DataEntry::CopyBinArea( uint8_t *area, uint32_t length )
91 {
92    DeleteBinArea();
93
94    uint32_t lgh = length + length%2;
95    SetLength(lgh);
96
97    if( area && length > 0 )
98    {
99       NewBinArea();
100       memcpy(BinArea,area,length);
101       if( length!=lgh )
102          BinArea[length]=0;
103
104       State = STATE_LOADED;
105    }
106 }
107
108 void DataEntry::SetValue(const uint32_t &id,const double &val)
109 {
110    if( !BinArea )
111       NewBinArea();
112    State = STATE_LOADED;
113
114    if( id > GetValueCount() )
115    {
116       gdcmErrorMacro("Index (" << id << ")is greater than the data size");
117       return;
118    }
119
120    const VRKey &vr = GetVR();
121    if( vr == "US" || vr == "SS" )
122    {
123       uint16_t *data = (uint16_t *)BinArea;
124       data[id] = (uint16_t)val;
125    }
126    else if( vr == "UL" || vr == "SL" )
127    {
128       uint32_t *data = (uint32_t *)BinArea;
129       data[id] = (uint32_t)val;
130    }
131    else if( vr == "FL" )
132    {
133       float *data = (float *)BinArea;
134       data[id] = (float)val;
135    }
136    else if( vr == "FD" )
137    {
138       double *data = (double *)BinArea;
139       data[id] = (double)val;
140    }
141    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
142    {
143       gdcmErrorMacro("SetValue on String representable not implemented yet");
144    }
145    else
146    {
147       BinArea[id] = (uint8_t)val;
148    }
149 }
150
151 double DataEntry::GetValue(const uint32_t &id) const
152 {
153    if( !BinArea )
154    {
155       gdcmErrorMacro("BinArea not set. Can't get the value");
156       return 0;
157    }
158
159    uint32_t count = GetValueCount();
160    if( id > count )
161    {
162       gdcmErrorMacro("Index (" << id << ")is greater than the data size");
163       return 0;
164    }
165
166    const VRKey &vr = GetVR();
167    if( vr == "US" || vr == "SS" )
168       return ((uint16_t *)BinArea)[id];
169    else if( vr == "UL" || vr == "SL" )
170       return ((uint32_t *)BinArea)[id];
171    else if( vr == "FL" )
172       return ((float *)BinArea)[id];
173    else if( vr == "FD" )
174       return ((double *)BinArea)[id];
175    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
176    {
177       if( GetLength() )
178       {
179          // Don't use std::string to accelerate processing
180          double val = 0.0;
181          char *tmp = new char[GetLength()+1];
182          memcpy(tmp,BinArea,GetLength());
183          tmp[GetLength()]=0;
184
185          if( count == 0 )
186          {
187             val = atof(tmp);
188          }
189          else
190          {
191             count = id;
192             char *beg = tmp;
193             for(uint32_t i=0;i<GetLength();i++)
194             {
195                if( tmp[i] == '\\' )
196                {
197                   if( count == 0 )
198                   {
199                      tmp[i] = NULL;
200                      break;
201                   }
202                   else
203                   {
204                      count--;
205                      beg = &(tmp[i+1]);
206                   }
207                }
208             }
209             val = atof(beg);
210          }
211
212          delete[] tmp;
213          return val;
214       }
215       else 
216          return 0.0;
217    }
218    else
219       return BinArea[id];
220 }
221
222 uint32_t DataEntry::GetValueCount(void) const
223 {
224    const VRKey &vr = GetVR();
225    if( vr == "US" || vr == "SS" )
226       return GetLength()/sizeof(uint16_t);
227    else if( vr == "UL" || vr == "SL" )
228       return GetLength()/sizeof(uint32_t);
229    else if( vr == "FL" )
230       return GetLength()/sizeof(float);
231    else if( vr == "FD" )
232       return GetLength()/sizeof(double);
233    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
234    {
235       // Don't use std::string to accelerate processing
236       uint32_t count = 1;
237       for(uint32_t i=0;i<GetLength();i++)
238       {
239          if( BinArea[i] == '\\')
240             count++;
241       }
242       return count;
243    }
244    else
245       return GetLength();
246 }
247
248 void DataEntry::SetString(std::string const &value)
249 {
250    DeleteBinArea();
251
252    const VRKey &vr = GetVR();
253    if ( vr == "US" || vr == "SS" )
254    {
255       std::vector<std::string> tokens;
256       Util::Tokenize (value, tokens, "\\");
257       SetLength(tokens.size()*sizeof(uint16_t));
258       NewBinArea();
259
260       uint16_t *data = (uint16_t *)BinArea;
261       for (unsigned int i=0; i<tokens.size();i++)
262          data[i] = atoi(tokens[i].c_str());
263       tokens.clear();
264    }
265    else if ( vr == "UL" || vr == "SL" )
266    {
267       std::vector<std::string> tokens;
268       Util::Tokenize (value, tokens, "\\");
269       SetLength(tokens.size()*sizeof(uint32_t));
270       NewBinArea();
271
272       uint32_t *data = (uint32_t *)BinArea;
273       for (unsigned int i=0; i<tokens.size();i++)
274          data[i] = atoi(tokens[i].c_str());
275       tokens.clear();
276    }
277    else if ( vr == "FL" )
278    {
279       std::vector<std::string> tokens;
280       Util::Tokenize (value, tokens, "\\");
281       SetLength(tokens.size()*sizeof(float));
282       NewBinArea();
283
284       float *data = (float *)BinArea;
285       for (unsigned int i=0; i<tokens.size();i++)
286          data[i] = (float)atof(tokens[i].c_str());
287       tokens.clear();
288    }
289    else if ( vr == "FD" )
290    {
291       std::vector<std::string> tokens;
292       Util::Tokenize (value, tokens, "\\");
293       SetLength(tokens.size()*sizeof(double));
294       NewBinArea();
295
296       double *data = (double *)BinArea;
297       for (unsigned int i=0; i<tokens.size();i++)
298          data[i] = atof(tokens[i].c_str());
299       tokens.clear();
300    }
301    else
302    {
303       if( value.size() > 0 )
304       {
305          std::string finalVal = Util::DicomString( value.c_str() );
306          SetLength(finalVal.size());
307          NewBinArea();
308
309          memcpy(BinArea, &(finalVal[0]), finalVal.size());
310       }
311    }
312    State = STATE_LOADED;
313 }
314
315 std::string const &DataEntry::GetString() const
316 {
317    static std::ostringstream s;
318    const VRKey &vr = GetVR();
319
320    s.str("");
321    StrArea="";
322
323    if( !BinArea )
324       return StrArea;
325
326    if( vr == "US" || vr == "SS" )
327    {
328       uint16_t *data=(uint16_t *)BinArea;
329
330       for (int i=0; i < GetValueCount(); i++)
331       {
332          if( i!=0 )
333             s << '\\';
334          s << data[i];
335       }
336       StrArea=s.str();
337    }
338    // See above comment on multiple integers (mutatis mutandis).
339    else if( vr == "UL" || vr == "SL" )
340    {
341       uint32_t *data=(uint32_t *)BinArea;
342
343       for (int i=0; i < GetValueCount(); i++)
344       {
345          if( i!=0 )
346             s << '\\';
347          s << data[i];
348       }
349       StrArea=s.str();
350    }
351    else if( vr == "FL" )
352    {
353       float *data=(float *)BinArea;
354
355       for (int i=0; i < GetValueCount(); i++)
356       {
357          if( i!=0 )
358             s << '\\';
359          s << data[i];
360       }
361       StrArea=s.str();
362    }
363    else if( vr == "FD" )
364    {
365       double *data=(double *)BinArea;
366
367       for (int i=0; i < GetValueCount(); i++)
368       {
369          if( i!=0 )
370             s << '\\';
371          s << data[i];
372       }
373       StrArea=s.str();
374    }
375    else
376       StrArea.append((const char *)BinArea,GetLength());
377
378    return StrArea;
379 }
380
381 void DataEntry::Copy(DocEntry *doc)
382 {
383    DocEntry::Copy(doc);
384
385    DataEntry *entry = dynamic_cast<DataEntry *>(doc);
386    if ( entry )
387    {
388       State = entry->State;
389       Flag = entry->Flag;
390       CopyBinArea(entry->BinArea,entry->GetLength());
391    }
392 }
393
394 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype)
395
396    DocEntry::WriteContent(fp, filetype);
397
398    if ( GetGroup() == 0xfffe )
399    {
400       return; //delimitors have NO value
401    }
402
403    uint8_t *binArea8 = BinArea; //safe notation
404    size_t lgr = GetLength();
405    if (BinArea) // the binArea was *actually* loaded
406    {
407
408    //  The same operation should be done if we wanted 
409    //  to write image with Big Endian Transfer Syntax, 
410    //  while working on Little Endian Processor
411    // --> forget Big Endian Transfer Syntax writting!
412    //     Next DICOM version will give it up ...
413
414    // --> FIXME 
415    //    The stuff looks nice, but it's probably bugged,
416    //    since troubles occur on big endian processors (SunSparc, Motorola)
417    //    while reading the pixels of a 
418    //    gdcm-written Little-Endian 16 bits per pixel image
419
420 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
421
422       /// \todo FIXME : Right now, we only care of Pixels element
423       ///       we should deal with *all* the BinEntries
424       ///       Well, not really since we are not interpreting values read...
425
426       // 8 Bits Pixels *are* OB, 16 Bits Pixels *are* OW
427       // -value forced while Reading process-
428       
429       // -->  WARNING
430       // -->        the following lines *looked* very clever, 
431       // -->        but they don't work on big endian processors.
432       // -->        since I've no access for the moment to a big endian proc :-(
433       // -->        I comment them out, to see the result on the dash board 
434       // -->     
435       
436       // --> Revert to initial code : TestWriteSimple hangs on Darwin :-(     
437       if (GetGroup() == 0x7fe0 && GetVR() == "OW")
438       {  
439          uint16_t *binArea16 = (uint16_t*)binArea8;
440          binary_write (*fp, binArea16, lgr );
441       }
442       else
443       { 
444          // For any other VR, DataEntry is re-written as-is
445          binary_write (*fp, binArea8, lgr );
446       }
447
448       // -->  WARNING      
449       // -->         remove the following line, an uncomment the previous ones, 
450       // -->         if it doesn't work better
451       // -->     
452       /*binary_write ( *fp, binArea8, lgr ); // Elem value*/
453       
454 #else
455       binary_write ( *fp, binArea8, lgr ); // Elem value
456 #endif //GDCM_WORDS_BIGENDIAN
457    }
458    else
459    {
460       // nothing was loaded, but we need to skip space on disc
461       
462       //  --> WARNING : nothing is written; 
463       //  --> the initial data (on the the source image) is lost
464       //  --> user is *not* informed !
465       
466       fp->seekp(lgr, std::ios::cur);
467    }
468 }
469
470 //-----------------------------------------------------------------------------
471 // Protected
472 void DataEntry::NewBinArea(void)
473 {
474    DeleteBinArea();
475    if( GetLength() > 0 )
476       BinArea = new uint8_t[GetLength()];
477    SelfArea = true;
478 }
479
480 void DataEntry::DeleteBinArea(void)
481 {
482    if (BinArea && SelfArea)
483    {
484       delete[] BinArea;
485       BinArea = NULL;
486    }
487 }
488
489 //-----------------------------------------------------------------------------
490 // Private
491
492 //-----------------------------------------------------------------------------
493 // Print
494 /**
495  * \brief   Prints a DataEntry (Dicom entry)
496  * @param   os ostream we want to print in
497  * @param indent Indentation string to be prepended during printing
498  */
499 void DataEntry::Print(std::ostream &os, std::string const & )
500 {
501    os << "D ";
502    DocEntry::Print(os);
503
504    std::ostringstream s;
505    TSAtr v;
506
507    if( BinArea )
508    {
509       v = GetString();
510       const VRKey &vr = GetVR();
511
512       if( vr == "US" || vr == "SS" )
513          s << " [" << GetString() << "]";
514       else if( vr == "UL" || vr == "SL" )
515          s << " [" << GetString() << "]";
516       else if ( vr == "FL" )
517          s << " [" << GetString() << "]";
518       else if ( vr == "FD" )
519          s << " [" << GetString() << "]";
520       else
521       { 
522          if(Global::GetVR()->IsVROfStringRepresentable(vr))
523          {
524             std::string cleanString = Util::CreateCleanString(v);  // replace non printable characters by '.'
525             if ( cleanString.length() <= GetMaxSizePrintEntry()
526             || PrintLevel >= 3
527             || IsNotLoaded() )
528             {
529                s << " [" << cleanString << "]";
530             }
531             else
532             {
533                s << " [gdcm::too long for print (" << cleanString.length() << ") ]";
534             }
535          }
536          else
537          {
538             if ( Util::IsCleanArea( GetBinArea(),GetLength()  ) )
539             {
540                std::string cleanString = 
541                      Util::CreateCleanString( BinArea,GetLength()  );
542                s << " [" << cleanString << "]";
543             }
544             else
545             {
546                s << " [" << GDCM_BINLOADED << ";"
547                << "length = " << GetLength() << "]";
548             }
549          }
550       }
551    }
552    else
553    {
554       if( IsNotLoaded() )
555          s << " [" << GDCM_NOTLOADED << "]";
556       else if( IsUnfound() )
557          s << " [" << GDCM_UNFOUND << "]";
558       else if( IsUnread() )
559          s << " [" << GDCM_UNREAD << "]";
560       else if ( GetLength() == 0 )
561          s << " []";
562    }
563
564    if( IsPixelData() )
565       s << " (" << GDCM_PIXELDATA << ")";
566
567    // Display the UID value (instead of displaying only the rough code)
568    // First 'clean' trailing character (space or zero) 
569    if(BinArea)
570    {
571       const uint16_t &gr = GetGroup();
572       const uint16_t &elt = GetElement();
573       TS *ts = Global::GetTS();
574
575       if (gr == 0x0002)
576       {
577          // Any more to be displayed ?
578          if ( elt == 0x0010 || elt == 0x0002 )
579          {
580             if ( v.length() != 0 )  // for brain damaged headers
581             {
582                if ( ! isdigit((unsigned char)v[v.length()-1]) )
583                {
584                   v.erase(v.length()-1, 1);
585                }
586             }
587             s << "  ==>\t[" << ts->GetValue(v) << "]";
588          }
589       }
590       else if (gr == 0x0008)
591       {
592          if ( elt == 0x0016 || elt == 0x1150 )
593          {
594             if ( v.length() != 0 )  // for brain damaged headers
595             {
596                if ( ! isdigit((unsigned char)v[v.length()-1]) )
597                {
598                   v.erase(v.length()-1, 1);
599                }
600             }
601             s << "  ==>\t[" << ts->GetValue(v) << "]";
602          }
603       }
604       else if (gr == 0x0004)
605       {
606          if ( elt == 0x1510 || elt == 0x1512  )
607          {
608             if ( v.length() != 0 )  // for brain damaged headers  
609             {
610                if ( ! isdigit((unsigned char)v[v.length()-1]) )
611                {
612                   v.erase(v.length()-1, 1);  
613                }
614             }
615             s << "  ==>\t[" << ts->GetValue(v) << "]";
616          }
617       }
618    }
619
620    os << s.str();
621 }
622
623 //-----------------------------------------------------------------------------
624 } // end namespace gdcm
625