]> Creatis software - gdcm.git/blob - src/gdcmDataEntry.cxx
* Add the Copy method in all datas
[gdcm.git] / src / gdcmDataEntry.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDataEntry.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/11/29 12:48:45 $
7   Version:   $Revision: 1.24 $
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 = FLAG_NONE;
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   uint32_t vm;
238   const std::string &strVM = GetVM();
239   uint32_t vc = GetValueCount();
240   bool valid = vc == 0;
241   if( valid )
242     return true;
243   
244   // FIXME : what shall we do with VM = "2-n", "3-n", etc
245   
246   if( strVM == "1-n" )
247   {
248     // make sure there is at least one ??? FIXME
249     valid = vc >= 1;
250   }
251   else
252   {
253     std::istringstream os;
254     os.str( strVM );
255     os >> vm;
256     // Two cases:
257     // vm respects the one from the dict
258     // vm is 0 (we need to check if this element is allowed to be empty) FIXME
259
260     // note  (JPR)
261     // ----    
262     // Entries whose type is 1 are mandatory, with a mandatory value.
263     // Entries whose type is 1c are mandatory-inside-a-Sequence,
264     //                          with a mandatory value.
265     // Entries whose type is 2 are mandatory, with an optional value.
266     // Entries whose type is 2c are mandatory-inside-a-Sequence,
267     //                          with an optional value.
268     // Entries whose type is 3 are optional.
269
270     // case vc == 0 is only applicable for 'type 2' entries.
271     // Problem : entry type may depend on the modality and/or the Sequence
272     //           it's embedded in !
273     //          (Get the information in the 'Conformance Statements' ...)  
274     valid = vc == vm;
275   }
276   return valid;
277 }
278
279 /**
280  * \brief returns the number of elementary values
281  */ 
282 uint32_t DataEntry::GetValueCount( ) const
283 {
284    const VRKey &vr = GetVR();
285    if( vr == "US" || vr == "SS" )
286       return GetLength()/sizeof(uint16_t);
287    else if( vr == "UL" || vr == "SL" )
288       return GetLength()/sizeof(uint32_t);
289    else if( vr == "FL" || vr == "OF" )
290       return GetLength()/4 ; // FL has a *4* length! sizeof(float);
291    else if( vr == "FD" )
292       return GetLength()/8;  // FD has a *8* length! sizeof(double);
293    else if( Global::GetVR()->IsVROfStringRepresentable(vr) )
294    {
295       // Some element in DICOM are allowed to be empty
296       if( !GetLength() ) 
297          return 0;
298       // Don't use std::string to accelerate processing
299       uint32_t count = 1;
300       for(uint32_t i=0;i<GetLength();i++)
301       {
302          if( BinArea[i] == '\\')
303             count++;
304       }
305       return count;
306    }
307    return GetLength();
308 }
309 /**
310  * \brief Sets the 'value' of an Entry, passed as a std::string
311  * @param value string representation of the value to be set
312  */ 
313 void DataEntry::SetString(std::string const &value)
314 {
315    DeleteBinArea();
316
317    const VRKey &vr = GetVR();
318    if ( vr == "US" || vr == "SS" )
319    {
320       std::vector<std::string> tokens;
321       Util::Tokenize (value, tokens, "\\");
322       SetLength(tokens.size()*sizeof(uint16_t));
323       NewBinArea();
324
325       uint16_t *data = (uint16_t *)BinArea;
326       for (unsigned int i=0; i<tokens.size();i++)
327          data[i] = atoi(tokens[i].c_str());
328       tokens.clear();
329    }
330    else if ( vr == "UL" || vr == "SL" )
331    {
332       std::vector<std::string> tokens;
333       Util::Tokenize (value, tokens, "\\");
334       SetLength(tokens.size()*sizeof(uint32_t));
335       NewBinArea();
336
337       uint32_t *data = (uint32_t *)BinArea;
338       for (unsigned int i=0; i<tokens.size();i++)
339          data[i] = atoi(tokens[i].c_str());
340       tokens.clear();
341    }
342    else if ( vr == "FL" )
343    {
344       std::vector<std::string> tokens;
345       Util::Tokenize (value, tokens, "\\");
346       SetLength(tokens.size()*sizeof(float));
347       NewBinArea();
348
349       float *data = (float *)BinArea;
350       for (unsigned int i=0; i<tokens.size();i++)
351          data[i] = (float)atof(tokens[i].c_str());
352       tokens.clear();
353    }
354    else if ( vr == "FD" )
355    {
356       std::vector<std::string> tokens;
357       Util::Tokenize (value, tokens, "\\");
358       SetLength(tokens.size()*sizeof(double));
359       NewBinArea();
360
361       double *data = (double *)BinArea;
362       for (unsigned int i=0; i<tokens.size();i++)
363          data[i] = atof(tokens[i].c_str());
364       tokens.clear();
365    }
366    else
367    {
368       if( value.size() > 0 )
369       {
370          size_t l =  value.size();    
371          SetLength(l + l%2);
372          NewBinArea();
373          memcpy(BinArea, value.c_str(), l);
374          if (l%2)
375             BinArea[l] = '\0';
376       }
377    }
378    State = STATE_LOADED;
379 }
380 /**
381  * \brief   returns as a string (when possible) the value of the DataEntry
382  */
383 std::string const &DataEntry::GetString() const
384 {
385    static std::ostringstream s;
386    const VRKey &vr = GetVR();
387
388    s.str("");
389    StrArea="";
390
391    if( !BinArea )
392       return StrArea;
393       
394    // When short integer(s) are stored, convert the following (n * 2) characters 
395    // as a displayable string, the values being separated by a back-slash
396
397    if( vr == "US" || vr == "SS" )
398    {
399       uint16_t *data=(uint16_t *)BinArea;
400
401       for (unsigned int i=0; i < GetValueCount(); i++)
402       {
403          if( i!=0 )
404             s << '\\';
405          s << data[i];
406       }
407       StrArea=s.str();
408    }
409    // See above comment on multiple short integers (mutatis mutandis).
410    else if( vr == "UL" || vr == "SL" )
411    {
412       uint32_t *data=(uint32_t *)BinArea;
413
414       for (unsigned int i=0; i < GetValueCount(); i++)
415       {
416          if( i!=0 )
417             s << '\\';
418          s << data[i];
419       }
420       StrArea=s.str();
421    }
422    else if( vr == "FL" )
423    {
424       float *data=(float *)BinArea;
425
426       for (unsigned int i=0; i < GetValueCount(); i++)
427       {
428          if( i!=0 )
429             s << '\\';
430          s << data[i];
431       }
432       StrArea=s.str();
433    }
434    else if( vr == "FD" )
435    {
436       double *data=(double *)BinArea;
437
438       for (unsigned int i=0; i < GetValueCount(); i++)
439       {
440          if( i!=0 )
441             s << '\\';
442          s << data[i];
443       }
444       StrArea=s.str();
445    }
446    else
447    {
448       StrArea.append((const char *)BinArea,GetLength());
449       // to avoid gdcm propagate oddities in lengthes
450       if ( GetLength()%2)
451          StrArea.append(" ",1);  
452    }
453    return StrArea;
454 }
455
456 /**
457  * \brief Copies all the attributes from an other DocEntry 
458  * @param doc entry to copy from
459  * @remarks The content BinArea is copied too
460  */
461 void DataEntry::Copy(DocEntry *doc)
462 {
463    DocEntry::Copy(doc);
464
465    DataEntry *entry = dynamic_cast<DataEntry *>(doc);
466    if ( entry )
467    {
468       State = entry->State;
469       Flag = entry->Flag;
470       CopyBinArea(entry->BinArea,entry->GetLength());
471    }
472 }
473
474 /**
475  * \brief   Writes the 'value' area of a DataEntry
476  * @param fp already open ofstream pointer
477  * @param filetype type of the file (ACR, ImplicitVR, ExplicitVR, ...)
478  */
479 void DataEntry::WriteContent(std::ofstream *fp, FileType filetype)
480
481    DocEntry::WriteContent(fp, filetype);
482
483    if ( GetGroup() == 0xfffe )
484    {
485       return; //delimitors have NO value
486    }
487    
488    // --> We only deal with Little Endian writting
489    // --> forget Big Endian Transfer Syntax writting!
490    //     Next DICOM version will give it up ...
491  
492    // WARNING - For Implicit VR private element,
493    //           we have *no choice* but considering them as
494    //           something like 'OB' values.
495    //           we rewrite them as we found them on disc.
496    //           Some trouble will occur if element was 
497    //           *actually* OW, if image was produced 
498    //           on Big endian based processor, read and writen 
499    //           on Little endian based processor
500    //           and, later on, somebody needs
501    //           this 'OW' Implicit VR private element (?!?)
502    //           (Same stuff, mutatis mutandis, for Little/Big)
503  
504    // 8/16 bits Pixels problem should be solved automatiquely,
505    // since we ensure the VR (OB vs OW) is conform to Pixel size.
506         
507    uint8_t *data = BinArea; //safe notation
508    size_t l = GetLength(); 
509    gdcmDebugMacro ("in DataEntry::WriteContent " << GetKey() 
510              << " : " << Global::GetVR()->GetAtomicElementLength(this->GetVR())
511              );
512    if (BinArea) // the binArea was *actually* loaded
513    {
514 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
515       unsigned short vrLgth = 
516                         Global::GetVR()->GetAtomicElementLength(this->GetVR());
517       unsigned int i;
518       switch(vrLgth)
519       {
520          case 1:
521          {
522             binary_write (*fp, data, l );           
523             break;
524          }     
525          case 2:
526          {
527 gdcmDebugMacro ("AtomicLength = 2 found; lgt =" << l); 
528             uint16_t *data16 = (uint16_t *)data;
529             for(i=0;i<l/vrLgth;i++)
530                binary_write( *fp, data16[i]);
531             break;
532          }
533          case 4:
534          {
535             uint32_t *data32 = (uint32_t *)data;
536             for(i=0;i<l/vrLgth;i++)
537                binary_write( *fp, data32[i]);
538             break;
539          }
540          case 8:
541          {
542             double *data64 = (double *)data;
543             for(i=0;i<l/vrLgth;i++)
544                binary_write( *fp, data64[i]);
545             break;
546          }
547       }
548 #else
549    binary_write (*fp, data, l );
550 #endif //GDCM_WORDS_BIGENDIAN
551
552    }
553    else
554    {
555       // nothing was loaded, but we need to skip space on disc
556       
557       //  --> WARNING : nothing is written; 
558       //  --> the initial data (on the the source image) is lost
559       //  --> user is *not* informed !
560       
561       fp->seekp(l, std::ios::cur);
562    }
563    // to avoid gdcm to propagate oddities
564    // (length was already modified)  
565    if (l%2)
566       fp->seekp(1, std::ios::cur);  
567 }
568
569 /**
570  * \brief   Compute the full length of the elementary DataEntry (not only value
571  *          length) depending on the VR.
572  */
573 uint32_t DataEntry::ComputeFullLength()
574 {
575    return GetFullLength();
576 }
577
578 //-----------------------------------------------------------------------------
579 // Protected
580 /// \brief Creates a DataEntry owned BinArea (remove previous one if any)
581 void DataEntry::NewBinArea(void)
582 {
583    DeleteBinArea();
584    if( GetLength() > 0 )
585       BinArea = new uint8_t[GetLength()];
586    SelfArea = true;
587 }
588 /// \brief Removes the BinArea, if owned by the DataEntry
589 void DataEntry::DeleteBinArea(void)
590 {
591    if (BinArea && SelfArea)
592    {
593       delete[] BinArea;
594       BinArea = NULL;
595    }
596 }
597
598 //-----------------------------------------------------------------------------
599 // Private
600
601 //-----------------------------------------------------------------------------
602 // Print
603 /**
604  * \brief   Prints a DataEntry (Dicom entry)
605  * @param   os ostream we want to print in
606  * @param indent Indentation string to be prepended during printing
607  */
608 void DataEntry::Print(std::ostream &os, std::string const & )
609 {
610    os << "D ";
611    DocEntry::Print(os);
612
613    uint16_t g = GetGroup();
614    if (g == 0xfffe) // delimiters have NO value
615    {          
616       return; // just to avoid identing all the remaining code 
617    }
618
619    std::ostringstream s;
620    TSAtr v;
621
622    if( BinArea )
623    {
624       v = GetString();
625       const VRKey &vr = GetVR();
626
627       if( vr == "US" || vr == "SS" )
628          s << " [" << GetString() << "]";
629       else if( vr == "UL" || vr == "SL" )
630          s << " [" << GetString() << "]";
631       else if ( vr == "FL" )
632          s << " [" << GetString() << "]";
633       else if ( vr == "FD" )
634          s << " [" << GetString() << "]";
635       else
636       { 
637          if(Global::GetVR()->IsVROfStringRepresentable(vr))
638          {
639             // replace non printable characters by '.'
640             std::string cleanString = Util::CreateCleanString(v);
641             if ( cleanString.length() <= GetMaxSizePrintEntry()
642               || PrintLevel >= 3
643               || IsNotLoaded() )
644            // FIXME : when IsNotLoaded(), you create a Clean String ?!?
645            // FIXME : PrintLevel<2 *does* print the values 
646            //        (3 is only for extra offsets printing)
647            // What do you wanted to do ? JPR
648             {
649                s << " [" << cleanString << "]";
650             }
651             else
652             {
653                s << " [gdcm::too long for print (" << cleanString.length() << ") ]";
654             }
655          }
656          else
657          {
658             // A lot of Private elements (with no VR) contain actually 
659             // only printable characters;
660             // Let's deal with them as is they were VR std::string representable
661     
662             if ( Util::IsCleanArea( GetBinArea(), GetLength()  ) )
663             {
664                // FIXME : since the 'Area' *is* clean, just use
665                //         a 'CreateString' method, to save CPU time.
666                std::string cleanString = 
667                      Util::CreateCleanString( BinArea,GetLength()  );
668                s << " [" << cleanString << "]";
669             }
670             else
671             {
672                s << " [" << GDCM_BINLOADED << ";"
673                << "length = " << GetLength() << "]";
674             }
675          }
676       }
677    }
678    else
679    {
680       if( IsNotLoaded() )
681          s << " [" << GDCM_NOTLOADED << "]";
682       else if( IsUnfound() )
683          s << " [" << GDCM_UNFOUND << "]";
684       else if( IsUnread() )
685          s << " [" << GDCM_UNREAD << "]";
686       else if ( GetLength() == 0 )
687          s << " []";
688    }
689
690    if( IsPixelData() )
691       s << " (" << GDCM_PIXELDATA << ")";
692
693    // Display the UID value (instead of displaying only the rough code)
694    // First 'clean' trailing character (space or zero) 
695    if(BinArea)
696    {
697       const uint16_t &gr = GetGroup();
698       const uint16_t &elt = GetElement();
699       TS *ts = Global::GetTS();
700
701       if (gr == 0x0002)
702       {
703          // Any more to be displayed ?
704          if ( elt == 0x0010 || elt == 0x0002 )
705          {
706             if ( v.length() != 0 )  // for brain damaged headers
707             {
708                if ( ! isdigit((unsigned char)v[v.length()-1]) )
709                {
710                   v.erase(v.length()-1, 1);
711                }
712             }
713             s << "  ==>\t[" << ts->GetValue(v) << "]";
714          }
715       }
716       else if (gr == 0x0008)
717       {
718          if ( elt == 0x0016 || elt == 0x1150 )
719          {
720             if ( v.length() != 0 )  // for brain damaged headers
721             {
722                if ( ! isdigit((unsigned char)v[v.length()-1]) )
723                {
724                   v.erase(v.length()-1, 1);
725                }
726             }
727             s << "  ==>\t[" << ts->GetValue(v) << "]";
728          }
729       }
730       else if (gr == 0x0004)
731       {
732          if ( elt == 0x1510 || elt == 0x1512  )
733          {
734             if ( v.length() != 0 )  // for brain damaged headers  
735             {
736                if ( ! isdigit((unsigned char)v[v.length()-1]) )
737                {
738                   v.erase(v.length()-1, 1);  
739                }
740             }
741             s << "  ==>\t[" << ts->GetValue(v) << "]";
742          }
743       }
744    }
745
746    os << s.str();
747 }
748
749 //-----------------------------------------------------------------------------
750 } // end namespace gdcm
751