]> Creatis software - gdcm.git/blob - src/gdcmDicomDir.cxx
* FIX : memory leaks and the set of ArgDelete methods in gdcmDicomDir
[gdcm.git] / src / gdcmDicomDir.cxx
1 // gdcmDicomDir.cxx
2 //-----------------------------------------------------------------------------
3 #include "gdcmDicomDir.h"
4 #include "gdcmStudy.h"
5 #include "gdcmSerie.h"
6 #include "gdcmImage.h"
7 #include "gdcmDirList.h"
8 #include "gdcmUtil.h"
9
10 #include <string>
11 #include <algorithm>
12
13 #include <sys/types.h>
14 #include <errno.h>
15
16 //-----------------------------------------------------------------------------
17 //  For full DICOMDIR description, see:
18 //  PS 3.3-2003, pages 731-750
19 //-----------------------------------------------------------------------------
20 // Constructor / Destructor
21 /*
22  * \ingroup gdcmDicomDir
23  * \brief   Constructor
24  * @param   Filename
25  * @param   exception_on_error
26  */
27 gdcmDicomDir::gdcmDicomDir(const char *FileName, bool parseDir,
28                            bool exception_on_error):
29    gdcmParser(FileName,exception_on_error,true)
30 {
31    startMethod=NULL;
32    progressMethod=NULL;
33    endMethod=NULL;
34    startMethodArgDelete=NULL;
35    progressMethodArgDelete=NULL;
36    endMethodArgDelete=NULL;
37    startArg=NULL;
38    progressArg=NULL;
39    endArg=NULL;
40
41    progress=NULL;
42    abort=false;
43
44    metaElems=NULL;
45
46    if( GetListEntry().begin()==GetListEntry().end() ) 
47    {
48       dbg.Verbose(0, "gdcmDicomDir::gdcmDicomDir : entry list empty");
49
50       if(parseDir)
51       {
52          dbg.Verbose(0, "gdcmDicomDir::gdcmDicomDir : Parse directory and create the DicomDir");
53          ParseDirectory();
54       }
55    }
56    else
57       CreateDicomDir();
58 }
59
60 /*
61  * \ingroup gdcmDicomDir
62  * \brief  Canonical destructor 
63  */
64 gdcmDicomDir::~gdcmDicomDir() 
65 {
66    SetStartMethod(NULL);
67    SetProgressMethod(NULL);
68    SetEndMethod(NULL);
69
70    if(metaElems)
71       delete metaElems;
72    
73    for(ListPatient::iterator cc=patients.begin();cc!=patients.end();++cc)
74    {
75       delete *cc;
76    }
77 }
78
79 //-----------------------------------------------------------------------------
80 // Print
81 /*
82  * \ingroup gdcmDicomDir
83  * \brief  Canonical Printer 
84  */
85 void gdcmDicomDir::Print(std::ostream &os)
86 {
87    if(metaElems)
88    {
89       metaElems->SetPrintLevel(printLevel);
90       metaElems->Print(os);   
91    }
92    
93    for(ListPatient::iterator cc=patients.begin();cc!=patients.end();++cc)
94    {
95      (*cc)->SetPrintLevel(printLevel);
96      (*cc)->Print(os);
97    }
98 }
99
100 //-----------------------------------------------------------------------------
101 // Public
102 /*
103  * \ingroup gdcmDicomDir
104  * \brief  This predicate, based on hopefully reasonable heuristics,
105  *         decides whether or not the current gdcmParser was properly parsed
106  *         and contains the mandatory information for being considered as
107  *         a well formed and usable DicomDir.
108  * @return true when gdcmParser is the one of a reasonable DicomDir,
109  *         false otherwise. 
110  */
111 bool gdcmDicomDir::IsReadable(void)
112 {
113    if(!gdcmParser::IsReadable())
114       return(false);
115    if(!metaElems)
116       return(false);
117    if(patients.size()<=0)
118       return(false);
119
120    return(true);
121 }
122
123 /*
124  * \ingroup gdcmDicomDir
125  * \brief  fills whole the structure
126  */
127 void gdcmDicomDir::ParseDirectory(void)
128 {
129    NewDicomDir(GetPath());
130    CreateDicomDir();
131 }
132
133 /*
134  * \ingroup gdcmDicomDir
135  * \brief   Set the start method to call when the parsing of the directory starts
136  * @param   method Method to call
137  * @param   arg    Argument to pass to the method
138  * \warning In python : the arg parameter isn't considered
139  */
140 void gdcmDicomDir::SetStartMethod(gdcmMethod *method,void *arg,gdcmMethod *argDelete)
141 {
142    if((startArg)&&(startMethodArgDelete))
143       startMethodArgDelete(startArg);
144
145    startMethod=method;
146    startArg=arg;
147    startMethodArgDelete=argDelete;
148 }
149
150 /*
151  * \ingroup gdcmDicomDir
152  * \brief   Set the method to delete the argument
153  *          The argument is destroyed when the method is changed or when the class
154  *          is destroyed
155  * @param   method Method to call to delete the argument
156  */
157 void gdcmDicomDir::SetStartMethodArgDelete(gdcmMethod *method) 
158 {
159    startMethodArgDelete=method;
160 }
161
162 /*
163  * \ingroup gdcmDicomDir
164  * \brief   Set the progress method to call when the parsing of the directory progress
165  * @param   method Method to call
166  * @param   arg    Argument to pass to the method
167  * \warning In python : the arg parameter isn't considered
168  */
169 void gdcmDicomDir::SetProgressMethod(gdcmMethod *method,void *arg,gdcmMethod *argDelete)
170 {
171    if((progressArg)&&(progressMethodArgDelete))
172       progressMethodArgDelete(progressArg);
173
174    progressMethod=method;
175    progressArg=arg;
176    progressMethodArgDelete=argDelete;
177 }
178
179 /*
180  * \ingroup gdcmDicomDir
181  * \brief   Set the method to delete the argument
182  *          The argument is destroyed when the method is changed or when the class
183  *          is destroyed
184  * @param   method Method to call to delete the argument
185  */
186 void gdcmDicomDir::SetProgressMethodArgDelete(gdcmMethod *method)
187 {
188    progressMethodArgDelete=method;
189 }
190
191 /*
192  * \ingroup gdcmDicomDir
193  * \brief   Set the end method to call when the parsing of the directory ends
194  * @param   method Method to call
195  * @param   arg    Argument to pass to the method
196  * \warning In python : the arg parameter isn't considered
197  */
198 void gdcmDicomDir::SetEndMethod(gdcmMethod *method,void *arg,gdcmMethod *argDelete)
199 {
200    if((endArg)&&(endMethodArgDelete))
201       endMethodArgDelete(endArg);
202
203    endMethod=method;
204    endArg=arg;
205    endMethodArgDelete=argDelete;
206 }
207
208 /*
209  * \ingroup gdcmDicomDir
210  * \brief   Set the method to delete the argument
211  *          The argument is destroyed when the method is changed or when the class
212  *          is destroyed
213  * @param   method Method to call to delete the argument
214  */
215 void gdcmDicomDir::SetEndMethodArgDelete(gdcmMethod *method)
216 {
217    endMethodArgDelete=method;
218 }
219
220 /**
221  * \ingroup gdcmDicomDir
222  * \brief   writes on disc a DICOMDIR
223  * \ warning does NOT add the missing elements in the header :
224  *           it's up to the user doing it !
225  * @param  fileName file to be written to 
226  * @return false only when fail to open
227  */
228 bool gdcmDicomDir::Write(std::string fileName) 
229 {
230    FILE * fp1;
231
232    fp1=fopen(fileName.c_str(),"wb");
233    if(fp1==NULL) 
234    {
235       printf("Failed to open(write) File [%s] \n",fileName.c_str());
236       return(false);
237    }
238
239    char * filePreamble;
240    filePreamble=(char*)calloc(128,1);
241    fwrite(filePreamble,128,1,fp1);
242    fwrite("DICM",4,1,fp1);
243    free(filePreamble);
244
245    WriteEntries(fp1,DICOMDIR);
246
247    fclose(fp1);
248
249    return true;
250 }
251
252 //-----------------------------------------------------------------------------
253 // Protected
254 /*
255  * \ingroup gdcmDicomDir
256  * \brief create a gdcmDicomDir from a root Directory 
257  * @param path entry point of the stree-like structure
258  */
259 void gdcmDicomDir::NewDicomDir(std::string path)
260 {
261    CallStartMethod();
262
263    gdcmDirList fileList(path,1);
264    unsigned int count=0;
265    ListHeader list;
266    gdcmHeader *header;
267
268    listEntries.clear();
269    patients.clear();
270
271    for(gdcmDirList::iterator it=fileList.begin(); 
272        it!=fileList.end(); ++it) 
273    {
274       progress=(float)(count+1)/(float)fileList.size();
275       CallProgressMethod();
276       if(abort)
277          break;
278
279       header=new gdcmHeader(it->c_str());
280       if(header->IsReadable())
281          list.push_back(header);
282       else
283          delete header;
284
285       count++;
286    }
287
288    std::sort(list.begin(),list.end(),gdcmDicomDir::HeaderLessThan);
289
290    std::string tmp=fileList.GetDirName();
291    SetElements(tmp,list);
292
293    CallEndMethod();
294 }
295
296 /*
297  * \ingroup gdcmDicomDir
298  * \brief   Get the DicomDir path
299  * @param   
300  */
301 std::string gdcmDicomDir::GetPath(void)
302 {
303    std::string path=GetFileName();
304
305    int pos1=path.rfind("/");
306    int pos2=path.rfind("\\");
307    if(pos1>pos2)
308       path.resize(pos1);
309    else
310       path.resize(pos2);
311
312    return(path);
313 }
314
315 void gdcmDicomDir::CallStartMethod(void)
316 {
317    progress=0.0f;
318    abort=false;
319    if(startMethod)
320       startMethod(startArg);
321 }
322
323 void gdcmDicomDir::CallProgressMethod(void)
324 {
325    if(progressMethod)
326       progressMethod(progressArg);
327 }
328
329 void gdcmDicomDir::CallEndMethod(void)
330 {
331    progress=1.0f;
332    if(endMethod)
333       endMethod(endArg);
334 }
335
336 //-----------------------------------------------------------------------------
337 // Private
338 /*
339  * \ingroup gdcmDicomDir
340  * \brief create a 'gdcmDicomDir' from a DICOMDIR gdcmHeader 
341  */
342 void gdcmDicomDir::CreateDicomDir()
343 {
344    // The list is parsed. When a tag is found :
345    //  1 - we save the beginning iterator
346    //  2 - we continue to parse
347    //  3 - we find an other tag
348    //       + we create the object for the precedent tag
349    //       + loop to 1 -
350
351    gdcmDicomDirType type=gdcmDicomDir::GDCM_META;
352    ListTag::iterator begin;
353    ListTag::iterator end;
354
355    begin=listEntries.begin();
356    end=begin;
357    for(ListTag::iterator i=end;i !=listEntries.end();++i) 
358    {
359       std::string v=(*i)->GetValue();
360       if(v=="PATIENT ") 
361       {
362          end=i;
363          AddObjectToEnd(type,begin,end);
364
365          type=gdcmDicomDir::GDCM_PATIENT;
366          begin=end;
367       } 
368
369       if(v=="STUDY ")
370       {
371          end=i;
372          AddObjectToEnd(type,begin,end);
373
374          type=gdcmDicomDir::GDCM_STUDY;
375          begin=end;
376       }
377
378       if(v=="SERIES") 
379       {
380          end=i;
381          AddObjectToEnd(type,begin,end);
382
383          type=gdcmDicomDir::GDCM_SERIE;
384          begin=end;
385       }
386
387       if(v=="IMAGE ") 
388       {
389          end=i;
390          AddObjectToEnd(type,begin,end);
391
392          type=gdcmDicomDir::GDCM_IMAGE;
393          begin=end;
394       }
395    }
396
397    end=GetListEntry().end();
398    if(begin!=end)
399       AddObjectToEnd(type,begin,end);
400 }
401 /*
402  * \ingroup gdcmDicomDir
403  * \brief   
404  * @param   type
405  * @param   begin
406  * @param   end
407  */
408 void gdcmDicomDir::AddObjectToEnd(gdcmDicomDirType type,ListTag::iterator begin,ListTag::iterator end)
409 {
410    if(begin==end)
411       return;
412
413    switch(type)
414    {
415       case gdcmDicomDir::GDCM_META:
416          AddMetaToEnd(begin,end);
417          break;      
418       case gdcmDicomDir::GDCM_PATIENT:
419          AddPatientToEnd(begin,end);
420          break;
421       case gdcmDicomDir::GDCM_STUDY:
422          AddStudyToEnd(begin,end);
423          break;
424       case gdcmDicomDir::GDCM_SERIE:
425          AddSerieToEnd(begin,end);
426          break;
427       case gdcmDicomDir::GDCM_IMAGE:
428          AddImageToEnd(begin,end);
429          break;
430    }
431 }
432
433 /*
434  * \ingroup gdcmDicomDir
435  * \brief Well ... Not realy to end, there is only one occurence  
436  * @param   begin
437  * @param   end
438 */
439 void gdcmDicomDir::AddMetaToEnd(ListTag::iterator begin,ListTag::iterator end)
440 {
441    if(metaElems)
442       delete metaElems;
443    metaElems = new gdcmMeta(begin,end);
444 }
445
446 /*
447  * \ingroup gdcmDicomDir
448  * \brief   
449  * @param   begin
450  * @param   end
451 */
452 void gdcmDicomDir::AddPatientToEnd(ListTag::iterator begin,ListTag::iterator end)
453 {
454    patients.push_back(new gdcmPatient(begin,end));
455 }
456
457 /*
458  * \ingroup gdcmDicomDir
459  * \brief   
460  * @param   begin
461  * @param   end
462  */
463  void gdcmDicomDir::AddStudyToEnd(ListTag::iterator begin,ListTag::iterator end)
464 {
465    if(patients.size()>0)
466    {
467       ListPatient::iterator itp=patients.end();
468       itp--;
469      (*itp)->AddStudy(new gdcmStudy(begin,end));
470    }
471 }
472 /*
473  * \ingroup gdcmDicomDir
474  * \brief   
475  * @param   begin
476  * @param   end
477  */
478 void gdcmDicomDir::AddSerieToEnd(ListTag::iterator begin,ListTag::iterator end)
479 {
480    if(patients.size()>0)
481    {
482       ListPatient::iterator itp=patients.end();
483       itp--;
484
485       if((*itp)->GetStudies().size()>0)
486       {
487          ListStudy::iterator itst=(*itp)->GetStudies().end();
488          itst--;
489         (*itst)->AddSerie(new gdcmSerie(begin,end));
490       }
491    }
492 }
493
494 /*
495  * \ingroup gdcmDicomDir
496  * @param   begin
497  * @param   end
498  * @param   
499  */
500  void gdcmDicomDir::AddImageToEnd(ListTag::iterator begin,ListTag::iterator end)
501 {
502    if(patients.size()>0)
503    {
504       ListPatient::iterator itp=patients.end();
505       itp--;
506
507       if((*itp)->GetStudies().size()>0)
508       {
509          ListStudy::iterator itst=(*itp)->GetStudies().end();
510          itst--;
511
512          if((*itst)->GetSeries().size()>0)
513          {
514             ListSerie::iterator its=(*itst)->GetSeries().end();
515             its--;
516            (*its)->AddImage(new gdcmImage(begin,end));
517          }
518       }
519    }
520 }
521
522 /*
523  * \ingroup gdcmDicomDir
524  * \brief   
525  * @param   path
526  * @param   list
527  */
528 void gdcmDicomDir::SetElements(std::string &path,ListHeader &list)
529 {
530    std::string patPrevName="", patPrevID="";
531    std::string studPrevInstanceUID="", studPrevID="";
532    std::string serPrevInstanceUID="", serPrevID="";
533
534    std::string patCurName, patCurID;
535    std::string studCurInstanceUID, studCurID;
536    std::string serCurInstanceUID, serCurID;
537
538    SetElement(path,GDCM_NONE,NULL);
539
540    ListTag::iterator debPat=listEntries.begin();
541    for(ListHeader::iterator it=list.begin();it!=list.end();++it) 
542    {
543       // get the current file characteristics
544       patCurName=(*it)->GetEntryByNumber(0x0010,0x0010); 
545       patCurID=(*it)->GetEntryByNumber(0x0010,0x0011); 
546       studCurInstanceUID=(*it)->GetEntryByNumber(0x0020,0x000d);            
547       studCurID=(*it)->GetEntryByNumber(0x0020,0x0010);            
548       serCurInstanceUID=(*it)->GetEntryByNumber(0x0020,0x000e);            
549       serCurID=(*it)->GetEntryByNumber(0x0020,0x0011);
550
551       if(patCurName!=patPrevName || patCurID!=patPrevID) 
552          SetElement(path,GDCM_PATIENT,*it);
553
554       // if new Study Deal with 'STUDY' Elements   
555       if(studCurInstanceUID!=studPrevInstanceUID || studCurID!=studPrevID) 
556          SetElement(path,GDCM_STUDY,*it);
557
558       // if new Serie Deal with 'SERIE' Elements   
559       if(serCurInstanceUID!=serPrevInstanceUID || serCurID!=serPrevID) 
560          SetElement(path,GDCM_SERIE,*it);
561       
562       // Always Deal with 'IMAGE' Elements  
563       SetElement(path,GDCM_IMAGE,*it);
564
565       patPrevName=patCurName;
566       patPrevID=patCurID;
567       studPrevInstanceUID=studCurInstanceUID;
568       studPrevID=studCurID;
569       serPrevInstanceUID=serCurInstanceUID;
570       serPrevID=serCurID;
571    }
572 }
573
574 /*
575  * \ingroup gdcmDicomDir
576  * \brief   
577  * @param   path
578  * @param   type
579  * @param   header
580  */
581 void gdcmDicomDir::SetElement(std::string &path,gdcmDicomDirType type,gdcmHeader *header)
582 {
583    std::list<gdcmElement> elemList;
584    std::list<gdcmElement>::iterator it;
585    guint16 tmpGr, tmpEl;
586    gdcmDictEntry *dictEntry;
587    gdcmHeaderEntry *entry;
588    std::string val;
589
590    switch(type)
591    {
592       case GDCM_PATIENT:
593          elemList=gdcmGlobal::GetDicomDirElements()->GetPatientElements();
594          break;
595       case GDCM_STUDY:
596          elemList=gdcmGlobal::GetDicomDirElements()->GetStudyElements();
597          break;
598       case GDCM_SERIE:
599          elemList=gdcmGlobal::GetDicomDirElements()->GetSerieElements();
600          break;
601       case GDCM_IMAGE:
602          elemList=gdcmGlobal::GetDicomDirElements()->GetImageElements();
603          break;
604       case GDCM_NONE:
605          elemList=gdcmGlobal::GetDicomDirElements()->GetMetaElements();
606          break;
607       default:
608          return;
609    }
610
611    for(it=elemList.begin();it!=elemList.end();++it)
612    {
613       tmpGr=it->group;
614       tmpEl=it->elem;
615
616       dictEntry=GetPubDict()->GetDictEntryByNumber(tmpGr,tmpEl);
617       entry=new gdcmHeaderEntry(dictEntry);
618       entry->SetOffset(0); // just to avoid missprinting
619
620       if(header)
621          val=header->GetEntryByNumber(tmpGr,tmpEl);
622       else
623          val=GDCM_UNFOUND;
624
625       if(val==GDCM_UNFOUND) 
626       {
627          if((tmpGr==0x0004) &&(tmpEl==0x1130) )
628          {
629             // TODO force the *end* File Name(remove path)
630             val=path;
631          }
632          else if( (tmpGr==0x0004) && (tmpEl==0x1500) ) // Only used for image
633          {
634             if(header->GetFileName().substr(0,path.length())!=path)
635             {
636                dbg.Verbose(0, "gdcmDicomDir::SetElement : the base path of file name is incorrect");
637                val=header->GetFileName();
638             }
639             else
640                val=&(header->GetFileName()[path.length()]);
641          }
642          else
643          {
644             val=it->value;
645          }
646       }
647       entry->SetValue(val);
648
649       if(dictEntry)
650       {
651          if( (dictEntry->GetVR()=="UL") || (dictEntry->GetVR()=="SL") ) 
652          {
653             entry->SetLength(4);
654          } 
655          else if( (dictEntry->GetVR()=="US") || (dictEntry->GetVR()=="SS") ) 
656          {
657             entry->SetLength(2); 
658          } 
659          else if(dictEntry->GetVR()=="SQ") 
660          {
661             entry->SetLength(0xffffffff);
662          }
663          else
664          {
665             entry->SetLength(entry->GetValue().length());        
666          }
667       }
668
669       listEntries.push_back(entry);
670    }     
671 }
672
673 bool gdcmDicomDir::HeaderLessThan(gdcmHeader *header1,gdcmHeader *header2)
674 {
675    return(*header1<*header2);
676 }
677
678 //-----------------------------------------------------------------------------