]> Creatis software - gdcm.git/blob - src/gdcmDataEntry.cxx
COMP: Fix bcc55 warnings
[gdcm.git] / src / gdcmDataEntry.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDataEntry.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/10/25 14:27:37 $
7   Version:   $Revision: 1.11 $
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  * \brief Inserts the value (non string) into the current Dicom Header Entry
91  */
92 void DataEntry::CopyBinArea( uint8_t *area, uint32_t length )
93 {
94    DeleteBinArea();
95
96    uint32_t lgh = length + length%2;
97    SetLength(lgh);
98
99    if( area && length > 0 )
100    {
101       NewBinArea();
102       memcpy(BinArea,area,length);
103       if( length!=lgh )
104          BinArea[length]=0;
105
106       State = STATE_LOADED;
107    }
108 }
109
110 void DataEntry::SetValue(const uint32_t &id, const double &val)
111 {
112    if( !BinArea )
113       NewBinArea();
114    State = STATE_LOADED;
115
116    if( id > GetValueCount() )
117    {
118       gdcmErrorMacro("Index (" << id << ")is greater than the data size");
119       return;
120    }
121
122    const VRKey &vr = GetVR();
123    if( vr == "US" || vr == "SS" )
124    {
125       uint16_t *data = (uint16_t *)BinArea;
126       data[id] = (uint16_t)val;
127    }
128    else if( vr == "UL" || vr == "SL" )
129    {
130       uint32_t *data = (uint32_t *)BinArea;
131       data[id] = (uint32_t)val;
132    }
133    else if( vr == "FL" )
134    {
135       float *data = (float *)BinArea;
136       data[id] = (float)val;
137    }
138    else if( vr == "FD" )
139    {
140       double *data = (double *)BinArea;
141       data[id] = (double)val;
142    }
143    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
144    {
145       gdcmErrorMacro("SetValue on String representable not implemented yet");
146    }
147    else
148    {
149       BinArea[id] = (uint8_t)val;
150    }
151 }
152 /**
153  * \brief returns, as a double (?!?) one of the values 
154  //      (when entry is multivaluated), identified by its index.
155  //      Returns 0.0 if index is wrong
156  //     FIXME : warn the user there was a problem ! 
157  */
158 double DataEntry::GetValue(const uint32_t &id) const
159 {
160    if( !BinArea )
161    {
162       gdcmErrorMacro("BinArea not set. Can't get the value");
163       return 0.0;
164    }
165
166    uint32_t count = GetValueCount();
167    if( id > count )
168    {
169       gdcmErrorMacro("Index (" << id << ")is greater than the data size");
170       return 0.0;
171    }
172
173    // FIX the API : user *knows* that entry contains a US
174    //               and he receives a double ?!?
175    
176    const VRKey &vr = GetVR();
177    if( vr == "US" || vr == "SS" )
178       return ((uint16_t *)BinArea)[id];
179    else if( vr == "UL" || vr == "SL" )
180       return ((uint32_t *)BinArea)[id];
181    else if( vr == "FL" )
182       return ((float *)BinArea)[id];
183    else if( vr == "FD" )
184       return ((double *)BinArea)[id];
185    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
186    {
187       if( GetLength() )
188       {
189          // Don't use std::string to accelerate processing
190          double val;
191          char *tmp = new char[GetLength()+1];
192          memcpy(tmp,BinArea,GetLength());
193          tmp[GetLength()]=0;
194
195          if( count == 0 )
196          {
197             val = atof(tmp);
198          }
199          else
200          {
201             count = id;
202             char *beg = tmp;
203             for(uint32_t i=0;i<GetLength();i++)
204             {
205                if( tmp[i] == '\\' )
206                {
207                   if( count == 0 )
208                   {
209                      tmp[i] = 0;
210                      break;
211                   }
212                   else
213                   {
214                      count--;
215                      beg = &(tmp[i+1]);
216                   }
217                }
218             }
219             val = atof(beg);
220          }
221
222          delete[] tmp;
223          return val;
224       }
225       else 
226          return 0.0;
227    }
228    else
229       return BinArea[id];
230 }
231
232 /**
233  * \brief Checks if the multiplicity of the value follows Dictionary VM
234  */
235 bool DataEntry::IsValueCountValid() const
236 {
237   bool valid;
238   uint32_t vm;
239   const std::string &strVM = GetVM();
240   uint32_t vc = GetValueCount();
241   
242   // FIXME : what shall we do with VM = "2-n", "3-n", etc
243   
244   if( strVM == "1-n" )
245   {
246     // make sure it is at least one ??? FIXME
247     valid = vc >= 1 || vc == 0;
248   }
249   else
250   {
251     std::istringstream os;
252     os.str( strVM );
253     os >> vm;
254     // Two cases:
255     // vm respect the one from the dict
256     // vm is 0 (we need to check if this element is allowed to be empty) FIXME
257
258     // note  (JPR)
259     // ----    
260     // Entries whose type is 1 are mandatory, with a mandatory value.
261     // Entries whose type is 1c are mandatory-inside-a-Sequence,
262     //                          with a mandatory value.
263     // Entries whose type is 2 are mandatory, with an optional value.
264     // Entries whose type is 2c are mandatory-inside-a-Sequence,
265     //                          with an optional value.
266     // Entries whose type is 3 are optional.
267
268     // case vc == 0 is only applicable for 'type 2' entries.
269     // Problem : entry type may depend on the modality and/or the Sequence
270     //           it's embedded in !
271     //          (Get the information in the 'Conformance Statements' ...)  
272     valid = vc == vm || vc == 0;
273   }
274   return valid;
275 }
276
277 /**
278  * \brief returns the number of elementary values
279  */ 
280 uint32_t DataEntry::GetValueCount( ) const
281 {
282    const VRKey &vr = GetVR();
283    if( vr == "US" || vr == "SS" )
284       return GetLength()/sizeof(uint16_t);
285    else if( vr == "UL" || vr == "SL" )
286       return GetLength()/sizeof(uint32_t);
287    else if( vr == "FL" )
288       return GetLength()/sizeof(float);
289    else if( vr == "FD" )
290       return GetLength()/sizeof(double);
291    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
292    {
293       // Some element in DICOM are allowed to be empty
294       if( !GetLength() ) return 0;
295       // Don't use std::string to accelerate processing
296       uint32_t count = 1;
297       for(uint32_t i=0;i<GetLength();i++)
298       {
299          if( BinArea[i] == '\\')
300             count++;
301       }
302       return count;
303    }
304
305    return GetLength();
306 }
307 /**
308  * \brief Sets the 'value' of an Entry, passed as a std::string
309  * @param value string representation of the value to be set
310  */ 
311 void DataEntry::SetString(std::string const &value)
312 {
313    DeleteBinArea();
314
315    const VRKey &vr = GetVR();
316    if ( vr == "US" || vr == "SS" )
317    {
318       std::vector<std::string> tokens;
319       Util::Tokenize (value, tokens, "\\");
320       SetLength(tokens.size()*sizeof(uint16_t));
321       NewBinArea();
322
323       uint16_t *data = (uint16_t *)BinArea;
324       for (unsigned int i=0; i<tokens.size();i++)
325          data[i] = atoi(tokens[i].c_str());
326       tokens.clear();
327    }
328    else if ( vr == "UL" || vr == "SL" )
329    {
330       std::vector<std::string> tokens;
331       Util::Tokenize (value, tokens, "\\");
332       SetLength(tokens.size()*sizeof(uint32_t));
333       NewBinArea();
334
335       uint32_t *data = (uint32_t *)BinArea;
336       for (unsigned int i=0; i<tokens.size();i++)
337          data[i] = atoi(tokens[i].c_str());
338       tokens.clear();
339    }
340    else if ( vr == "FL" )
341    {
342       std::vector<std::string> tokens;
343       Util::Tokenize (value, tokens, "\\");
344       SetLength(tokens.size()*sizeof(float));
345       NewBinArea();
346
347       float *data = (float *)BinArea;
348       for (unsigned int i=0; i<tokens.size();i++)
349          data[i] = (float)atof(tokens[i].c_str());
350       tokens.clear();
351    }
352    else if ( vr == "FD" )
353    {
354       std::vector<std::string> tokens;
355       Util::Tokenize (value, tokens, "\\");
356       SetLength(tokens.size()*sizeof(double));
357       NewBinArea();
358
359       double *data = (double *)BinArea;
360       for (unsigned int i=0; i<tokens.size();i++)
361          data[i] = atof(tokens[i].c_str());
362       tokens.clear();
363    }
364    else
365    {
366       if( value.size() > 0 )
367       {
368          // FIXME : should be quicker if we don't create one more std::string
369          //         just to make even the length of a char array ...
370
371          /*
372          std::string finalVal = Util::DicomString( value.c_str() );
373          SetLength(finalVal.size());
374          NewBinArea();
375
376          memcpy(BinArea, &(finalVal[0]), finalVal.size());
377          */
378
379          size_t l =  value.size();    
380          SetLength(l + l%2);
381          NewBinArea();
382          memcpy(BinArea, &(value[0]), l);
383          if (l%2)
384             BinArea[l] = '\0';
385       }
386    }
387    State = STATE_LOADED;
388 }
389 /**
390  * \brief   returns as a string (when possible) the value of the DataEntry
391  */
392 std::string const &DataEntry::GetString() const
393 {
394    static std::ostringstream s;
395    const VRKey &vr = GetVR();
396
397    s.str("");
398    StrArea="";
399
400    if( !BinArea )
401       return StrArea;
402       
403    // When short integer(s) are stored, convert the following (n * 2) characters 
404    // as a displayable string, the values being separated by a back-slash
405
406    if( vr == "US" || vr == "SS" )
407    {
408       uint16_t *data=(uint16_t *)BinArea;
409
410       for (unsigned int i=0; i < GetValueCount(); i++)
411       {
412          if( i!=0 )
413             s << '\\';
414          s << data[i];
415       }
416       StrArea=s.str();
417    }
418    // See above comment on multiple short integers (mutatis mutandis).
419    else if( vr == "UL" || vr == "SL" )
420    {
421       uint32_t *data=(uint32_t *)BinArea;
422
423       for (unsigned int i=0; i < GetValueCount(); i++)
424       {
425          if( i!=0 )
426             s << '\\';
427          s << data[i];
428       }
429       StrArea=s.str();
430    }
431    else if( vr == "FL" )
432    {
433       float *data=(float *)BinArea;
434
435       for (unsigned int i=0; i < GetValueCount(); i++)
436       {
437          if( i!=0 )
438             s << '\\';
439          s << data[i];
440       }
441       StrArea=s.str();
442    }
443    else if( vr == "FD" )
444    {
445       double *data=(double *)BinArea;
446
447       for (unsigned int i=0; i < GetValueCount(); i++)
448       {
449          if( i!=0 )
450             s << '\\';
451          s << data[i];
452       }
453       StrArea=s.str();
454    }
455    else
456       StrArea.append((const char *)BinArea,GetLength());
457
458    return StrArea;
459 }
460 /**
461  * \brief   Copies all the attributes from an other DocEntry 
462  * @param doc entry to copy from
463  */
464 void DataEntry::Copy(DocEntry *doc)
465 {
466    DocEntry::Copy(doc);
467
468    DataEntry *entry = dynamic_cast<DataEntry *>(doc);
469    if ( entry )
470    {
471       State = entry->State;
472       Flag = entry->Flag;
473       CopyBinArea(entry->BinArea,entry->GetLength());
474    }
475 }
476 /**
477  * \brief   Writes the value of a DataEntry
478  * @param fp already open ofstream pointer
479  * @param filetype type of the file (ACR, ImplicitVR, ExplicitVR, ...)
480  */
481 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype)
482
483    DocEntry::WriteContent(fp, filetype);
484
485    if ( GetGroup() == 0xfffe )
486    {
487       return; //delimitors have NO value
488    }
489
490    uint8_t *binArea8 = BinArea; //safe notation
491    size_t lgr = GetLength();
492    if (BinArea) // the binArea was *actually* loaded
493    {
494
495    //  The same operation should be done if we wanted 
496    //  to write image with Big Endian Transfer Syntax, 
497    //  while working on Little Endian Processor
498    // --> forget Big Endian Transfer Syntax writting!
499    //     Next DICOM version will give it up ...
500
501    // --> FIXME 
502    //    The stuff looks nice, but it's probably bugged,
503    //    since troubles occur on big endian processors (SunSparc, Motorola)
504    //    while reading the pixels of a 
505    //    gdcm-written Little-Endian 16 bits per pixel image
506
507 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
508
509       /// \todo FIXME : Right now, we only care of Pixels element
510       ///       we should deal with *all* the BinEntries
511       ///       Well, not really since we are not interpreting values read...
512
513       // 8 Bits Pixels *are* OB, 16 Bits Pixels *are* OW
514       // -value forced while Reading process-
515       
516       // -->  WARNING
517       // -->        the following lines *looked* very clever, 
518       // -->        but they don't work on big endian processors.
519       // -->        since I've no access for the moment to a big endian proc :-(
520       // -->        I comment them out, to see the result on the dash board 
521       // -->     
522       
523       // --> Revert to initial code : TestWriteSimple hangs on Darwin :-(     
524       if (GetGroup() == 0x7fe0 && GetVR() == "OW")
525       {  
526          uint16_t *binArea16 = (uint16_t*)binArea8;
527          binary_write (*fp, binArea16, lgr );
528       }
529       else
530       { 
531          // For any other VR, DataEntry is re-written as-is
532          binary_write (*fp, binArea8, lgr );
533       }
534
535       // -->  WARNING      
536       // -->         remove the following line, an uncomment the previous ones, 
537       // -->         if it doesn't work better
538       // -->     
539       /*binary_write ( *fp, binArea8, lgr ); // Elem value*/
540       
541 #else
542       binary_write ( *fp, binArea8, lgr ); // Elem value
543 #endif //GDCM_WORDS_BIGENDIAN
544    }
545    else
546    {
547       // nothing was loaded, but we need to skip space on disc
548       
549       //  --> WARNING : nothing is written; 
550       //  --> the initial data (on the the source image) is lost
551       //  --> user is *not* informed !
552       
553       fp->seekp(lgr, std::ios::cur);
554    }
555 }
556
557 //-----------------------------------------------------------------------------
558 // Protected
559 void DataEntry::NewBinArea(void)
560 {
561    DeleteBinArea();
562    if( GetLength() > 0 )
563       BinArea = new uint8_t[GetLength()];
564    SelfArea = true;
565 }
566
567 void DataEntry::DeleteBinArea(void)
568 {
569    if (BinArea && SelfArea)
570    {
571       delete[] BinArea;
572       BinArea = NULL;
573    }
574 }
575
576 //-----------------------------------------------------------------------------
577 // Private
578
579 //-----------------------------------------------------------------------------
580 // Print
581 /**
582  * \brief   Prints a DataEntry (Dicom entry)
583  * @param   os ostream we want to print in
584  * @param indent Indentation string to be prepended during printing
585  */
586 void DataEntry::Print(std::ostream &os, std::string const & )
587 {
588    os << "D ";
589    DocEntry::Print(os);
590
591    uint16_t g = GetGroup();
592    if (g == 0xfffe) // delimiters have NO value
593    {          
594       return; // just to avoid identing all the remaining code 
595    }
596
597    std::ostringstream s;
598    TSAtr v;
599
600    if( BinArea )
601    {
602       v = GetString();
603       const VRKey &vr = GetVR();
604
605       if( vr == "US" || vr == "SS" )
606          s << " [" << GetString() << "]";
607       else if( vr == "UL" || vr == "SL" )
608          s << " [" << GetString() << "]";
609       else if ( vr == "FL" )
610          s << " [" << GetString() << "]";
611       else if ( vr == "FD" )
612          s << " [" << GetString() << "]";
613       else
614       { 
615          if(Global::GetVR()->IsVROfStringRepresentable(vr))
616          {
617             // replace non printable characters by '.'
618             std::string cleanString = Util::CreateCleanString(v);
619             if ( cleanString.length() <= GetMaxSizePrintEntry()
620               || PrintLevel >= 3
621               || IsNotLoaded() )
622            // FIXME : when IsNotLoaded(), you create a Clean String ?!?
623            // FIXME : PrintLevel<2 *does* print the values 
624            //        (3 is only for extra offsets printing)
625            // What do you wanted to do ? JPR
626             {
627                s << " [" << cleanString << "]";
628             }
629             else
630             {
631                s << " [gdcm::too long for print (" << cleanString.length() << ") ]";
632             }
633          }
634          else
635          {
636             // A lot of Private elements (with no VR) contain actually 
637             // only printable characters;
638             // Let's deal with them as is they were VR std::string representable
639     
640             if ( Util::IsCleanArea( GetBinArea(), GetLength()  ) )
641             {
642                // FIXME : since the 'Area' *is* clean, just use
643                //         a 'CreateString' method, to save CPU time.
644                std::string cleanString = 
645                      Util::CreateCleanString( BinArea,GetLength()  );
646                s << " [" << cleanString << "]";
647             }
648             else
649             {
650                s << " [" << GDCM_BINLOADED << ";"
651                << "length = " << GetLength() << "]";
652             }
653          }
654       }
655    }
656    else
657    {
658       if( IsNotLoaded() )
659          s << " [" << GDCM_NOTLOADED << "]";
660       else if( IsUnfound() )
661          s << " [" << GDCM_UNFOUND << "]";
662       else if( IsUnread() )
663          s << " [" << GDCM_UNREAD << "]";
664       else if ( GetLength() == 0 )
665          s << " []";
666    }
667
668    if( IsPixelData() )
669       s << " (" << GDCM_PIXELDATA << ")";
670
671    // Display the UID value (instead of displaying only the rough code)
672    // First 'clean' trailing character (space or zero) 
673    if(BinArea)
674    {
675       const uint16_t &gr = GetGroup();
676       const uint16_t &elt = GetElement();
677       TS *ts = Global::GetTS();
678
679       if (gr == 0x0002)
680       {
681          // Any more to be displayed ?
682          if ( elt == 0x0010 || elt == 0x0002 )
683          {
684             if ( v.length() != 0 )  // for brain damaged headers
685             {
686                if ( ! isdigit((unsigned char)v[v.length()-1]) )
687                {
688                   v.erase(v.length()-1, 1);
689                }
690             }
691             s << "  ==>\t[" << ts->GetValue(v) << "]";
692          }
693       }
694       else if (gr == 0x0008)
695       {
696          if ( elt == 0x0016 || elt == 0x1150 )
697          {
698             if ( v.length() != 0 )  // for brain damaged headers
699             {
700                if ( ! isdigit((unsigned char)v[v.length()-1]) )
701                {
702                   v.erase(v.length()-1, 1);
703                }
704             }
705             s << "  ==>\t[" << ts->GetValue(v) << "]";
706          }
707       }
708       else if (gr == 0x0004)
709       {
710          if ( elt == 0x1510 || elt == 0x1512  )
711          {
712             if ( v.length() != 0 )  // for brain damaged headers  
713             {
714                if ( ! isdigit((unsigned char)v[v.length()-1]) )
715                {
716                   v.erase(v.length()-1, 1);  
717                }
718             }
719             s << "  ==>\t[" << ts->GetValue(v) << "]";
720          }
721       }
722    }
723
724    os << s.str();
725 }
726
727 //-----------------------------------------------------------------------------
728 } // end namespace gdcm
729