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