1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2004/10/12 04:35:44 $
7 Version: $Revision: 1.73 $
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.
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.
17 =========================================================================*/
19 #include "gdcmDicomDir.h"
20 #include "gdcmDicomDirStudy.h"
21 #include "gdcmDicomDirSerie.h"
22 #include "gdcmDicomDirImage.h"
23 #include "gdcmDirList.h"
25 #include "gdcmDebug.h"
26 #include "gdcmGlobal.h"
27 #include "gdcmHeader.h"
28 #include "gdcmSeqEntry.h"
29 #include "gdcmSQItem.h"
30 #include "gdcmValEntry.h"
34 #include <sys/types.h>
44 //-----------------------------------------------------------------------------
45 // For full DICOMDIR description, see:
46 // PS 3.3-2003, pages 731-750
47 //-----------------------------------------------------------------------------
48 // Constructor / Destructor
52 * \brief Constructor : creates an empty DicomDir
57 Initialize(); // sets all private fields to NULL
58 std::string pathBidon = "Bidon"; // Sorry, NULL not allowed ...
59 MetaElems = NewMeta();
63 * \brief Constructor Parses recursively the directory and creates the DicomDir
64 * or uses an already built DICOMDIR, depending on 'parseDir' value.
65 * @param fileName name
66 * - of the root directory (parseDir = true)
67 * - of the DICOMDIR (parseDir = false)
68 * @param parseDir boolean
69 * - true if user passed an entry point
70 * and wants to explore recursively the directories
71 * - false if user passed an already built DICOMDIR file
74 DicomDir::DicomDir(std::string const & fileName, bool parseDir ):
77 // Whatever user passed (a root directory or a DICOMDIR)
78 // and whatever the value of parseDir was,
79 // Document is already executed
80 Initialize(); // sets all private fields to NULL
82 // if user passed a root directory, sure we didn't get anything
84 if ( TagHT.begin() == TagHT.end() ) // when user passed a Directory to parse
86 dbg.Verbose(0, "DicomDir::DicomDir : entry HT empty");
88 if ( fileName.size() == 1 && fileName[0] == '.' )
90 // user passed '.' as Name
91 // we get current directory name
93 getcwd(dummy, (size_t)1000);
94 SetFileName( dummy ); // will be converted into a string
97 if ( parseDir ) // user asked for a recursive parsing of a root directory
99 MetaElems = NewMeta();
101 dbg.Verbose(0, "DicomDir::DicomDir : Parse directory"
102 " and create the DicomDir");
107 /// \todo if parseDir == false, it should be tagged as an error
108 // NON ! il suffit d'appeler ParseDirectory()
109 // apres le constructeur
112 else // Only if user passed a DICOMDIR
114 // Directory record sequence
115 DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
118 dbg.Verbose(0, "DicomDir::DicomDir : NO Directory record"
119 " sequence (0x0004,0x1220)");
120 /// \todo FIXME : what do we do when the parsed file IS NOT a
128 * \brief Canonical destructor
130 DicomDir::~DicomDir()
132 SetStartMethod(NULL);
133 SetProgressMethod(NULL);
135 for(ListDicomDirPatient::iterator cc = Patients.begin();
147 //-----------------------------------------------------------------------------
150 * \brief Canonical Printer
152 void DicomDir::Print(std::ostream &os)
156 MetaElems->SetPrintLevel(PrintLevel);
157 MetaElems->Print(os);
159 for(ListDicomDirPatient::iterator cc = Patients.begin();
160 cc != Patients.end();
163 (*cc)->SetPrintLevel( PrintLevel );
168 //-----------------------------------------------------------------------------
171 * \brief This predicate, based on hopefully reasonable heuristics,
172 * decides whether or not the current header was properly parsed
173 * and contains the mandatory information for being considered as
174 * a well formed and usable DicomDir.
175 * @return true when Document is the one of a reasonable DicomDir,
178 bool DicomDir::IsReadable()
180 if( !Document::IsReadable() )
188 if( Patients.size() <= 0 )
197 * \brief Sets all fields to NULL
200 void DicomDir::Initialize()
203 ProgressMethod = NULL;
205 StartMethodArgDelete = NULL;
206 ProgressMethodArgDelete = NULL;
207 EndMethodArgDelete = NULL;
221 * \brief fills the whole structure, starting from a root Directory
223 void DicomDir::ParseDirectory()
225 CreateDicomDirChainedList( GetFileName() );
231 * \brief Set the start method to call when the parsing of the directory starts
232 * @param method Method to call
233 * @param arg Argument to pass to the method
234 * @param argDelete Argument
235 * \warning In python : the arg parameter isn't considered
237 void DicomDir::SetStartMethod(Method* method, void* arg,
240 if( StartArg && StartMethodArgDelete )
242 StartMethodArgDelete( StartArg );
245 StartMethod = method;
247 StartMethodArgDelete = argDelete;
252 * \brief Set the method to delete the argument
253 * The argument is destroyed when the method is changed or when the
255 * @param method Method to call to delete the argument
257 void DicomDir::SetStartMethodArgDelete(Method* method)
259 StartMethodArgDelete = method;
264 * \brief Set the progress method to call when the parsing of the directory progress
265 * @param method Method to call
266 * @param arg Argument to pass to the method
267 * @param argDelete Argument
268 * \warning In python : the arg parameter isn't considered
270 void DicomDir::SetProgressMethod(Method* method, void* arg,
273 if( ProgressArg && ProgressMethodArgDelete )
275 ProgressMethodArgDelete( ProgressArg );
278 ProgressMethod = method;
280 ProgressMethodArgDelete = argDelete;
285 * \brief Set the method to delete the argument
286 * The argument is destroyed when the method is changed or when the
288 * @param method Method to call to delete the argument
290 void DicomDir::SetProgressMethodArgDelete(Method* method)
292 ProgressMethodArgDelete = method;
297 * \brief Set the end method to call when the parsing of the directory ends
298 * @param method Method to call
299 * @param arg Argument to pass to the method
300 * @param argDelete Argument
301 * \warning In python : the arg parameter isn't considered
303 void DicomDir::SetEndMethod(Method* method, void* arg,
306 if( EndArg && EndMethodArgDelete )
308 EndMethodArgDelete( EndArg );
313 EndMethodArgDelete = argDelete;
318 * \brief Set the method to delete the argument
319 * The argument is destroyed when the method is changed or when the class
321 * @param method Method to call to delete the argument
323 void DicomDir::SetEndMethodArgDelete(Method* method)
325 EndMethodArgDelete = method;
330 * \brief writes on disc a DICOMDIR
331 * \ warning does NOT add the missing elements in the header :
332 * it's up to the user doing it !
333 * \todo : to be re-written using the DICOMDIR tree-like structure
334 * *not* the chained list
335 * (does NOT exist if the DICOMDIR is user-forged !)
336 * @param fileName file to be written to
337 * @return false only when fail to open
340 bool DicomDir::WriteDicomDir(std::string const& fileName)
342 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
343 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
345 FILE* fp = fopen(fileName.c_str(), "wb");
348 printf("Failed to open(write) File [%s] \n", fileName.c_str());
352 uint8_t filePreamble[128];
353 memset(filePreamble, 0, 128);
354 fwrite(filePreamble,128,1,fp);
355 fwrite("DICM",4,1,fp);
357 DicomDirMeta *ptrMeta = GetDicomDirMeta();
358 ptrMeta->Write(fp, ExplicitVR);
360 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
361 fwrite(&sq[0],8,1,fp); // 0004 1220 ffff ffff
363 for(ListDicomDirPatient::iterator cc = Patients.begin();
364 cc != Patients.end();
367 (*cc)->Write( fp, ExplicitVR );
370 // force writing Sequence Delimitation Item
371 fwrite(&sqt[0],8,1,fp); // fffe e0dd ffff ffff
377 //-----------------------------------------------------------------------------
382 * \brief create a Document-like chained list from a root Directory
383 * @param path entry point of the tree-like structure
385 void DicomDir::CreateDicomDirChainedList(std::string const & path)
388 DirList fileList(path,1); // gets recursively the file list
389 unsigned int count = 0;
396 for( DirList::iterator it = fileList.begin();
397 it != fileList.end();
400 Progress = (float)(count+1)/(float)fileList.size();
401 CallProgressMethod();
407 header = new Header( it->c_str() );
411 "DicomDir::CreateDicomDirChainedList: "
412 "failure in new Header ",
416 if( header->IsReadable() )
418 // Add the file header to the chained list:
419 list.push_back(header);
421 "DicomDir::CreateDicomDirChainedList: readable ",
431 // sorts Patient/Study/Serie/
432 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
434 std::string tmp = fileList.GetDirName();
435 //for each Header of the chained list, add/update the Patient/Study/Serie/Image info
436 SetElements(tmp, list);
442 * \brief adds *the* Meta to a partially created DICOMDIR
445 DicomDirMeta * DicomDir::NewMeta()
447 DicomDirMeta *m = new DicomDirMeta( &TagHT );
449 if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
451 TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
452 lastOneButSequence --;
453 // ALL the 'out of Sequence' Tags belong to Meta Elems
454 // (we skip 0004|1220 [Directory record sequence] )
455 for ( TagDocEntryHT::iterator cc = TagHT.begin();
456 cc != lastOneButSequence;
459 m->AddDocEntry( cc->second );
462 else // after root directory parsing
464 std::list<Element> elemList;
465 elemList=Global::GetDicomDirElements()->GetDicomDirMetaElements();
466 m->FillObject(elemList);
468 m->SetSQItemNumber(0); // To avoid further missprinting
473 * \brief adds a new Patient (with the basic elements) to a partially created DICOMDIR
475 DicomDirPatient * DicomDir::NewPatient()
477 std::list<Element>::iterator it;
478 uint16_t tmpGr,tmpEl;
479 DictEntry *dictEntry;
482 std::list<Element> elemList;
483 elemList=Global::GetDicomDirElements()->GetDicomDirPatientElements();
484 SQItem *s = new SQItem(0);
486 // for all the DicomDirPatient Elements
487 for( it = elemList.begin(); it != elemList.end(); ++it )
491 dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
492 entry = new ValEntry( dictEntry );
493 entry->SetOffset(0); // just to avoid further missprinting
494 entry->SetValue( it->Value );
496 // dealing with value length ...
498 if( dictEntry->GetGroup() == 0xfffe)
500 entry->SetLength(entry->GetValue().length());
502 else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
504 entry->SetLength( 4 );
506 else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
510 else if( dictEntry->GetVR() == "SQ" )
512 entry->SetLength( 0xffffffff );
516 entry->SetLength( entry->GetValue().length() );
518 s->AddDocEntry( entry );
521 DicomDirPatient *p = new DicomDirPatient(s, &TagHT);
522 Patients.push_front( p );
528 * \brief adds to the HTable
529 * the Entries (Dicom Elements) corresponding to the given type
530 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
531 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
532 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
533 * @param header Header of the current file
535 void DicomDir::SetElement(std::string &path,DicomDirType type,
538 std::list<Element> elemList;
539 std::list<Element>::iterator it;
540 uint16_t tmpGr, tmpEl;
541 DictEntry *dictEntry;
544 SQItem *si = new SQItem(0); // all the items will be at level 1
547 case GDCM_DICOMDIR_IMAGE:
548 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
551 case GDCM_DICOMDIR_SERIE:
552 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
555 case GDCM_DICOMDIR_STUDY:
556 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
559 case GDCM_DICOMDIR_PATIENT:
560 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
563 case GDCM_DICOMDIR_META:
564 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
570 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
571 // to avoid further troubles
572 // imageElem 0008 1140 "" // Referenced Image Sequence
573 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
574 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
575 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
576 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
577 // for all the relevant elements found in their own spot of the DicomDir.dic
578 // FIXME : troubles found when it's a SeqEntry
580 for( it = elemList.begin(); it != elemList.end(); ++it)
584 dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
586 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
588 entry->SetOffset(0); // just to avoid further missprinting
589 entry->SetLength(0); // just to avoid further missprinting
593 // NULL when we Build Up (ex nihilo) a DICOMDIR
594 // or when we add the META elems
595 val = header->GetEntryByNumber(tmpGr, tmpEl);
602 if( val == GDCM_UNFOUND)
604 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
606 // force to the *end* File Name
607 val = Util::GetName( path );
609 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
611 if( header->GetFileName().substr(0, path.length()) != path )
613 dbg.Verbose(0, "DicomDir::SetElement : the base path"
614 " of file name is incorrect");
615 val = header->GetFileName();
619 val = &(header->GetFileName().c_str()[path.length()]);
629 if ( header->GetEntryLengthByNumber(tmpGr,tmpEl) == 0 )
633 // GDCM_UNFOUND or not !
635 entry->SetValue( val ); // troubles expected when vr=SQ ...
639 if( dictEntry->GetGroup() == 0xfffe )
641 entry->SetLength( entry->GetValue().length() ); // FIXME
643 else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
647 else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
651 else if( dictEntry->GetVR() == "SQ" )
653 entry->SetLength( 0xffffffff );
657 entry->SetLength( entry->GetValue().length() );
661 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
663 std::cout << "GDCM_DICOMDIR_META ?!? should never print that"
670 case GDCM_DICOMDIR_IMAGE:
671 AddDicomDirImageToEnd(si);
674 case GDCM_DICOMDIR_SERIE:
675 AddDicomDirSerieToEnd(si);
678 case GDCM_DICOMDIR_STUDY:
679 AddDicomDirStudyToEnd(si);
682 case GDCM_DICOMDIR_PATIENT:
683 AddDicomDirPatientToEnd(si);
689 //int count=1; // find a trick to increment
690 //s->AddEntry(si, count); // Seg Faults
695 * \brief CallStartMethod
697 void DicomDir::CallStartMethod()
703 StartMethod( StartArg );
709 * \brief CallProgressMethod
711 void DicomDir::CallProgressMethod()
715 ProgressMethod( ProgressArg );
721 * \brief CallEndMethod
723 void DicomDir::CallEndMethod()
732 //-----------------------------------------------------------------------------
736 * \brief create a 'DicomDir' from a DICOMDIR Header
738 void DicomDir::CreateDicomDir()
740 // The list is parsed.
741 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
742 // 1 - we save the beginning iterator
743 // 2 - we continue to parse
744 // 3 - we find an other tag
745 // + we create the object for the precedent tag
748 // Directory record sequence
749 DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
752 dbg.Verbose(0, "DicomDir::DicomDir : NO Directory record"
753 " sequence (0x0004,0x1220)");
754 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
758 SeqEntry* s = dynamic_cast<SeqEntry*>(e);
761 dbg.Verbose(0, "DicomDir::CreateDicomDir: no SeqEntry present");
762 // useless : (0x0004,0x1220) IS a Sequence !
766 DicomDirType type = DicomDir::GDCM_DICOMDIR_META;
767 MetaElems = NewMeta();
769 ListSQItem listItems = s->GetSQItems();
773 for( ListSQItem::iterator i = listItems.begin();
774 i !=listItems.end(); ++i )
776 d = (*i)->GetDocEntryByNumber(0x0004, 0x1430); // Directory Record Type
777 if ( ValEntry* valEntry = dynamic_cast< ValEntry* >(d) )
779 v = valEntry->GetValue();
783 dbg.Verbose(0, "DicomDir::CreateDicomDir: not a ValEntry.");
787 if( v == "PATIENT " )
789 AddDicomDirPatientToEnd( *i );
790 type = DicomDir::GDCM_DICOMDIR_PATIENT;
792 else if( v == "STUDY " )
794 AddDicomDirStudyToEnd( *i );
795 type = DicomDir::GDCM_DICOMDIR_STUDY;
797 else if( v == "SERIES" )
799 AddDicomDirSerieToEnd( *i );
800 type = DicomDir::GDCM_DICOMDIR_SERIE;
802 else if( v == "IMAGE " )
804 AddDicomDirImageToEnd( *i );
805 type = DicomDir::GDCM_DICOMDIR_IMAGE;
809 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
810 // neither an 'IMAGE' SQItem. Skip to next item.
818 * \brief Well ... there is only one occurence
820 void DicomDir::AddDicomDirMeta()
826 MetaElems = new DicomDirMeta( &TagHT );
831 * \brief AddDicomDirPatientToEnd
832 * @param s SQ Item to enqueue to the DicomPatient chained List
834 void DicomDir::AddDicomDirPatientToEnd(SQItem *s)
836 Patients.push_back(new DicomDirPatient(s, &TagHT));
841 * \brief AddDicomDirStudyToEnd
842 * @param s SQ Item to enqueue to the DicomDirStudy chained List
844 void DicomDir::AddDicomDirStudyToEnd(SQItem *s)
846 if( Patients.size() > 0 )
848 ListDicomDirPatient::iterator itp = Patients.end();
850 (*itp)->AddDicomDirStudy(new DicomDirStudy(s, &TagHT));
856 * \brief AddDicomDirSerieToEnd
857 * @param s SQ Item to enqueue to the DicomDirSerie chained List
859 void DicomDir::AddDicomDirSerieToEnd(SQItem *s)
861 if( Patients.size() > 0 )
863 ListDicomDirPatient::iterator itp = Patients.end();
866 if( (*itp)->GetDicomDirStudies().size() > 0 )
868 ListDicomDirStudy::iterator itst=(*itp)->GetDicomDirStudies().end();
870 (*itst)->AddDicomDirSerie(new DicomDirSerie(s, &TagHT));
877 * \brief AddDicomDirImageToEnd
878 * @param s SQ Item to enqueue to the DicomDirImage chained List
880 void DicomDir::AddDicomDirImageToEnd(SQItem *s)
882 if( Patients.size() > 0 )
884 ListDicomDirPatient::iterator itp = Patients.end();
887 if( (*itp)->GetDicomDirStudies().size() > 0 )
889 ListDicomDirStudy::iterator itst = (*itp)->GetDicomDirStudies().end();
892 if( (*itst)->GetDicomDirSeries().size() > 0 )
894 ListDicomDirSerie::iterator its = (*itst)->GetDicomDirSeries().end();
896 (*its)->AddDicomDirImage(new DicomDirImage(s, &TagHT));
904 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
905 * @param path path of the root directory
906 * @param list chained list of Headers
908 void DicomDir::SetElements(std::string &path, VectDocument &list)
910 std::string patPrevName = "", patPrevID = "";
911 std::string studPrevInstanceUID = "", studPrevID = "";
912 std::string serPrevInstanceUID = "", serPrevID = "";
914 std::string patCurName, patCurID;
915 std::string studCurInstanceUID, studCurID;
916 std::string serCurInstanceUID, serCurID;
918 for( VectDocument::iterator it = list.begin();
919 it != list.end(); ++it )
921 // get the current file characteristics
922 patCurName = (*it)->GetEntryByNumber(0x0010,0x0010);
923 patCurID = (*it)->GetEntryByNumber(0x0010,0x0011);
924 studCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000d);
925 studCurID = (*it)->GetEntryByNumber(0x0020,0x0010);
926 serCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000e);
927 serCurID = (*it)->GetEntryByNumber(0x0020,0x0011);
929 if( patCurName != patPrevName || patCurID != patPrevID)
931 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
934 // if new Study Deal with 'STUDY' Elements
935 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID )
937 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
940 // if new Serie Deal with 'SERIE' Elements
941 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID )
943 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
946 // Always Deal with 'IMAGE' Elements
947 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
949 patPrevName = patCurName;
950 patPrevID = patCurID;
951 studPrevInstanceUID = studCurInstanceUID;
952 studPrevID = studCurID;
953 serPrevInstanceUID = serCurInstanceUID;
954 serPrevID = serCurID;
960 * \brief compares two dgcmHeaders
962 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
964 return *header1 < *header2;
966 } // end namespace gdcm
968 //-----------------------------------------------------------------------------