1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2004/12/07 13:39:33 $
7 Version: $Revision: 1.88 $
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 "gdcmDicomDirPatient.h"
24 #include "gdcmDicomDirMeta.h"
25 #include "gdcmDicomDirElement.h"
26 #include "gdcmDirList.h"
28 #include "gdcmDebug.h"
29 #include "gdcmGlobal.h"
30 #include "gdcmHeader.h"
31 #include "gdcmSeqEntry.h"
32 #include "gdcmSQItem.h"
33 #include "gdcmValEntry.h"
38 #include <sys/types.h>
41 #define getcwd _getcwd
44 #if defined( _MSC_VER) || defined(__BORLANDC__)
53 //-----------------------------------------------------------------------------
54 // For full DICOMDIR description, see:
55 // PS 3.3-2003, pages 731-750
56 //-----------------------------------------------------------------------------
57 // Constructor / Destructor
61 * \brief Constructor : creates an empty DicomDir
66 Initialize(); // sets all private fields to NULL
67 MetaElems = NewMeta();
71 * \brief Constructor Parses recursively the directory and creates the DicomDir
72 * or uses an already built DICOMDIR, depending on 'parseDir' value.
73 * @param fileName name
74 * - of the root directory (parseDir = true)
75 * - of the DICOMDIR (parseDir = false)
76 * @param parseDir boolean
77 * - true if user passed an entry point
78 * and wants to explore recursively the directories
79 * - false if user passed an already built DICOMDIR file
82 DicomDir::DicomDir(std::string const & fileName, bool parseDir ):
85 // Whatever user passed (a root directory or a DICOMDIR)
86 // and whatever the value of parseDir was,
87 // Document is already executed
88 Initialize(); // sets all private fields to NULL
90 // if user passed a root directory, sure we didn't get anything
91 if ( TagHT.begin() == TagHT.end() ) // when user passed a Directory to parse
93 dbg.Verbose(0, "DicomDir::DicomDir : entry HT empty");
95 if ( fileName.size() == 1 && fileName[0] == '.' )
97 // user passed '.' as Name
98 // we get current directory name
100 getcwd(dummy, (size_t)1000);
101 SetFileName( dummy ); // will be converted into a string
104 if ( parseDir ) // user asked for a recursive parsing of a root directory
106 MetaElems = NewMeta();
108 dbg.Verbose(0, "DicomDir::DicomDir : Parse directory"
109 " and create the DicomDir");
114 /// \todo if parseDir == false, it should be tagged as an error
115 // NON ! il suffit d'appeler ParseDirectory()
116 // apres le constructeur
119 else // Only if user passed a DICOMDIR
121 // Directory record sequence
122 DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
125 dbg.Verbose(0, "DicomDir::DicomDir : NO Directory record"
126 " sequence (0x0004,0x1220)");
127 /// \todo FIXME : what do we do when the parsed file IS NOT a
136 * \brief Canonical destructor
138 DicomDir::~DicomDir()
140 SetStartMethod(NULL);
141 SetProgressMethod(NULL);
144 for(ListDicomDirPatient::iterator cc = Patients.begin();
156 //-----------------------------------------------------------------------------
159 * \brief Canonical Printer
161 void DicomDir::Print(std::ostream &os)
165 MetaElems->SetPrintLevel(PrintLevel);
166 MetaElems->Print(os);
168 for(ListDicomDirPatient::iterator cc = Patients.begin();
169 cc != Patients.end();
172 (*cc)->SetPrintLevel( PrintLevel );
177 //-----------------------------------------------------------------------------
180 * \brief This predicate, based on hopefully reasonable heuristics,
181 * decides whether or not the current header was properly parsed
182 * and contains the mandatory information for being considered as
183 * a well formed and usable DicomDir.
184 * @return true when Document is the one of a reasonable DicomDir,
187 bool DicomDir::IsReadable()
189 if( !Document::IsReadable() )
197 if( Patients.size() <= 0 )
206 * \brief Sets all fields to NULL
209 void DicomDir::Initialize()
212 ProgressMethod = NULL;
214 StartMethodArgDelete = NULL;
215 ProgressMethodArgDelete = NULL;
216 EndMethodArgDelete = NULL;
230 * \brief fills the whole structure, starting from a root Directory
232 void DicomDir::ParseDirectory()
234 CreateDicomDirChainedList( GetFileName() );
240 * \brief Set the start method to call when the parsing of the
242 * @param method Method to call
243 * @param arg Argument to pass to the method
244 * @param argDelete Argument
245 * \warning In python : the arg parameter isn't considered
247 void DicomDir::SetStartMethod( DicomDir::Method* method, void* arg,
248 DicomDir::Method* argDelete )
250 if( StartArg && StartMethodArgDelete )
252 StartMethodArgDelete( StartArg );
255 StartMethod = method;
257 StartMethodArgDelete = argDelete;
262 * \brief Set the method to delete the argument
263 * The argument is destroyed when the method is changed or when the
265 * @param method Method to call to delete the argument
267 void DicomDir::SetStartMethodArgDelete( DicomDir::Method* method )
269 StartMethodArgDelete = method;
274 * \brief Set the progress method to call when the parsing of the
276 * @param method Method to call
277 * @param arg Argument to pass to the method
278 * @param argDelete Argument
279 * \warning In python : the arg parameter isn't considered
281 void DicomDir::SetProgressMethod( DicomDir::Method* method, void* arg,
282 DicomDir::Method* argDelete )
284 if( ProgressArg && ProgressMethodArgDelete )
286 ProgressMethodArgDelete( ProgressArg );
289 ProgressMethod = method;
291 ProgressMethodArgDelete = argDelete;
296 * \brief Set the method to delete the argument
297 * The argument is destroyed when the method is changed or when the
299 * @param method Method to call to delete the argument
301 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method* method )
303 ProgressMethodArgDelete = method;
308 * \brief Set the end method to call when the parsing of the directory ends
309 * @param method Method to call
310 * @param arg Argument to pass to the method
311 * @param argDelete Argument
312 * \warning In python : the arg parameter isn't considered
314 void DicomDir::SetEndMethod( DicomDir::Method* method, void* arg,
315 DicomDir::Method* argDelete )
317 if( EndArg && EndMethodArgDelete )
319 EndMethodArgDelete( EndArg );
324 EndMethodArgDelete = argDelete;
329 * \brief Set the method to delete the argument
330 * The argument is destroyed when the method is changed or when
331 * the class is destroyed
332 * @param method Method to call to delete the argument
334 void DicomDir::SetEndMethodArgDelete( DicomDir::Method* method )
336 EndMethodArgDelete = method;
341 * \brief writes on disc a DICOMDIR
342 * \ warning does NOT add the missing elements in the header :
343 * it's up to the user doing it !
344 * \todo : to be re-written using the DICOMDIR tree-like structure
345 * *not* the chained list
346 * (does NOT exist if the DICOMDIR is user-forged !)
347 * @param fileName file to be written to
348 * @return false only when fail to open
351 bool DicomDir::WriteDicomDir(std::string const& fileName)
354 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
355 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
357 std::ofstream* fp = new std::ofstream(fileName.c_str(),
358 std::ios::out | std::ios::binary);
361 dbg.Verbose(2, "Failed to open(write) File: ", fileName.c_str());
365 char filePreamble[128];
366 memset(filePreamble, 0, 128);
367 fp->write(filePreamble, 128); //FIXME
368 binary_write( *fp, "DICM");
370 DicomDirMeta *ptrMeta = GetDicomDirMeta();
371 ptrMeta->WriteContent(fp, ExplicitVR);
373 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
376 binary_write(*fp, sq[i]);
379 for(ListDicomDirPatient::iterator cc = Patients.begin();
380 cc != Patients.end();
383 (*cc)->WriteContent( fp, ExplicitVR );
386 // force writing Sequence Delimitation Item
389 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
398 //-----------------------------------------------------------------------------
403 * \brief create a Document-like chained list from a root Directory
404 * @param path entry point of the tree-like structure
406 void DicomDir::CreateDicomDirChainedList(std::string const & path)
409 DirList fileList(path,1); // gets recursively the file list
410 unsigned int count = 0;
414 for( DirList::iterator it = fileList.begin();
415 it != fileList.end();
418 Progress = (float)(count+1)/(float)fileList.size();
419 CallProgressMethod();
425 std::cerr<<"File : "<<it->c_str()<<std::endl;
426 header = new Header( it->c_str() );
430 "DicomDir::CreateDicomDirChainedList: "
431 "failure in new Header ",
436 if( header->IsReadable() )
438 // Add the file header to the chained list:
439 list.push_back(header);
441 "DicomDir::CreateDicomDirChainedList: readable ",
450 // sorts Patient/Study/Serie/
451 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
453 std::string tmp = fileList.GetDirName();
454 //for each Header of the chained list, add/update the Patient/Study/Serie/Image info
455 SetElements(tmp, list);
458 for(VectDocument::iterator itDoc=list.begin();
462 delete dynamic_cast<Header *>(*itDoc);
468 * \brief adds *the* Meta to a partially created DICOMDIR
471 DicomDirMeta * DicomDir::NewMeta()
473 DicomDirMeta *m = new DicomDirMeta();
475 if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
477 TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
478 lastOneButSequence --;
479 // ALL the 'out of Sequence' Tags belong to Meta Elems
480 // (we skip 0004|1220 [Directory record sequence] )
481 for ( TagDocEntryHT::iterator cc = TagHT.begin();
482 cc != lastOneButSequence;
485 m->AddEntry( cc->second );
488 else // after root directory parsing
490 ListDicomDirMetaElem const & elemList =
491 Global::GetDicomDirElements()->GetDicomDirMetaElements();
492 m->FillObject(elemList);
494 m->SetSQItemNumber(0); // To avoid further missprinting
499 * \brief adds a new Patient (with the basic elements) to a partially created DICOMDIR
501 DicomDirPatient * DicomDir::NewPatient()
503 ListDicomDirPatientElem::const_iterator it;
504 uint16_t tmpGr,tmpEl;
505 DictEntry *dictEntry;
508 ListDicomDirPatientElem const & elemList =
509 Global::GetDicomDirElements()->GetDicomDirPatientElements();
510 DicomDirPatient *p = new DicomDirPatient();
512 // for all the DicomDirPatient Elements
513 for( it = elemList.begin(); it != elemList.end(); ++it )
517 dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
518 entry = new ValEntry( dictEntry );
519 entry->SetOffset(0); // just to avoid further missprinting
520 entry->SetValue( it->Value );
522 p->AddEntry( entry );
525 Patients.push_front( p );
531 * \brief adds to the HTable
532 * the Entries (Dicom Elements) corresponding to the given type
533 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
534 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
535 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
536 * @param header Header of the current file
538 void DicomDir::SetElement(std::string const & path, DicomDirType type,
541 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
542 ListDicomDirElem::const_iterator it;
543 uint16_t tmpGr, tmpEl;
544 DictEntry *dictEntry;
551 case GDCM_DICOMDIR_IMAGE:
552 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
553 si = new DicomDirImage();
554 if( !AddDicomDirImageToEnd(static_cast<DicomDirImage *>(si)) )
556 dbg.Verbose(0,"DicomDir::SetElement:",
557 "Add DicomDirImageToEnd failed");
560 case GDCM_DICOMDIR_SERIE:
561 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
562 si = new DicomDirSerie();
563 if( !AddDicomDirSerieToEnd(static_cast<DicomDirSerie *>(si)) )
565 dbg.Verbose(0,"DicomDir::SetElement:",
566 "Add DicomDirSerieToEnd failed");
569 case GDCM_DICOMDIR_STUDY:
570 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
571 si = new DicomDirStudy();
572 if( !AddDicomDirStudyToEnd(static_cast<DicomDirStudy *>(si)) )
574 dbg.Verbose(0,"DicomDir::SetElement:",
575 "Add DicomDirStudyToEnd failed");
578 case GDCM_DICOMDIR_PATIENT:
579 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
580 si = new DicomDirPatient();
581 if( !AddDicomDirPatientToEnd(static_cast<DicomDirPatient *>(si)) )
583 dbg.Verbose(0,"DicomDir::SetElement:",
584 "Add DicomDirPatientToEnd failed");
587 case GDCM_DICOMDIR_META:
588 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
589 si = new DicomDirMeta();
592 dbg.Verbose(0,"DicomDir::SetElement:",
593 "MetaElements already exist, they will be destroyed");
596 MetaElems = static_cast<DicomDirMeta *>(si);
601 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
602 // to avoid further troubles
603 // imageElem 0008 1140 "" // Referenced Image Sequence
604 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
605 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
606 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
607 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
608 // for all the relevant elements found in their own spot of the DicomDir.dic
609 // FIXME : troubles found when it's a SeqEntry
611 for( it = elemList.begin(); it != elemList.end(); ++it)
615 dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
617 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
619 entry->SetOffset(0); // just to avoid further missprinting
623 // NULL when we Build Up (ex nihilo) a DICOMDIR
624 // or when we add the META elems
625 val = header->GetEntryByNumber(tmpGr, tmpEl);
632 if( val == GDCM_UNFOUND)
634 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
636 // force to the *end* File Name
637 val = Util::GetName( path );
639 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
641 if( header->GetFileName().substr(0, path.length()) != path )
643 dbg.Verbose(0, "DicomDir::SetElement : the base path"
644 " of file name is incorrect");
645 val = header->GetFileName();
649 val = &(header->GetFileName().c_str()[path.length()]);
659 if ( header->GetEntryLengthByNumber(tmpGr,tmpEl) == 0 )
663 entry->SetValue( val ); // troubles expected when vr=SQ ...
665 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
667 std::cout << "GDCM_DICOMDIR_META ?!? should never print that"
674 //-----------------------------------------------------------------------------
676 * \brief CallStartMethod
678 void DicomDir::CallStartMethod()
684 StartMethod( StartArg );
688 //-----------------------------------------------------------------------------
691 * \brief CallProgressMethod
693 void DicomDir::CallProgressMethod()
697 ProgressMethod( ProgressArg );
701 //-----------------------------------------------------------------------------
704 * \brief CallEndMethod
706 void DicomDir::CallEndMethod()
715 //-----------------------------------------------------------------------------
719 * \brief create a 'DicomDir' from a DICOMDIR Header
721 void DicomDir::CreateDicomDir()
723 // The list is parsed.
724 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
725 // 1 - we save the beginning iterator
726 // 2 - we continue to parse
727 // 3 - we find an other tag
728 // + we create the object for the precedent tag
731 // Directory record sequence
732 DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
735 dbg.Verbose(0, "DicomDir::DicomDir : NO Directory record"
736 " sequence (0x0004,0x1220)");
737 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
741 SeqEntry* s = dynamic_cast<SeqEntry*>(e);
744 dbg.Verbose(0, "DicomDir::CreateDicomDir: no SeqEntry present");
745 // useless : (0x0004,0x1220) IS a Sequence !
749 DicomDirType type; // = DicomDir::GDCM_DICOMDIR_META;
750 MetaElems = NewMeta();
752 ListSQItem listItems = s->GetSQItems();
757 for( ListSQItem::iterator i = listItems.begin();
758 i !=listItems.end(); ++i )
760 d = (*i)->GetDocEntryByNumber(0x0004, 0x1430); // Directory Record Type
761 if ( ValEntry* valEntry = dynamic_cast< ValEntry* >(d) )
763 v = valEntry->GetValue();
767 dbg.Verbose(0, "DicomDir::CreateDicomDir: not a ValEntry.");
771 if( v == "PATIENT " )
773 si = new DicomDirPatient();
774 AddDicomDirPatientToEnd( static_cast<DicomDirPatient *>(si) );
775 type = DicomDir::GDCM_DICOMDIR_PATIENT;
777 else if( v == "STUDY " )
779 si = new DicomDirStudy();
780 AddDicomDirStudyToEnd( static_cast<DicomDirStudy *>(si) );
781 type = DicomDir::GDCM_DICOMDIR_STUDY;
783 else if( v == "SERIES" )
785 si = new DicomDirSerie();
786 AddDicomDirSerieToEnd( static_cast<DicomDirSerie *>(si) );
787 type = DicomDir::GDCM_DICOMDIR_SERIE;
789 else if( v == "IMAGE " )
791 si = new DicomDirImage();
792 AddDicomDirImageToEnd( static_cast<DicomDirImage *>(si) );
793 type = DicomDir::GDCM_DICOMDIR_IMAGE;
797 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
798 // neither an 'IMAGE' SQItem. Skip to next item.
808 * \brief Well ... there is only one occurence
810 bool DicomDir::AddDicomDirMeta()
816 MetaElems = new DicomDirMeta();
822 * \brief AddDicomDirPatientToEnd
823 * @param s SQ Item to enqueue to the DicomPatient chained List
825 bool DicomDir::AddDicomDirPatientToEnd(DicomDirPatient *dd)
827 Patients.push_back(dd);
833 * \brief AddDicomDirStudyToEnd
834 * @param s SQ Item to enqueue to the DicomDirStudy chained List
836 bool DicomDir::AddDicomDirStudyToEnd(DicomDirStudy *dd)
838 if( Patients.size() > 0 )
840 ListDicomDirPatient::iterator itp = Patients.end();
842 (*itp)->AddDicomDirStudy(dd);
850 * \brief AddDicomDirSerieToEnd
851 * @param s SQ Item to enqueue to the DicomDirSerie chained List
853 bool DicomDir::AddDicomDirSerieToEnd(DicomDirSerie *dd)
855 if( Patients.size() > 0 )
857 ListDicomDirPatient::iterator itp = Patients.end();
860 if( (*itp)->GetDicomDirStudies().size() > 0 )
862 ListDicomDirStudy::const_iterator itst =
863 (*itp)->GetDicomDirStudies().end();
865 (*itst)->AddDicomDirSerie(dd);
874 * \brief AddDicomDirImageToEnd
875 * @param s SQ Item to enqueue to the DicomDirImage chained List
877 bool DicomDir::AddDicomDirImageToEnd(DicomDirImage *dd)
879 if( Patients.size() > 0 )
881 ListDicomDirPatient::iterator itp = Patients.end();
884 if( (*itp)->GetDicomDirStudies().size() > 0 )
886 ListDicomDirStudy::const_iterator itst =
887 (*itp)->GetDicomDirStudies().end();
890 if( (*itst)->GetDicomDirSeries().size() > 0 )
892 ListDicomDirSerie::const_iterator its = (*itst)->GetDicomDirSeries().end();
894 (*its)->AddDicomDirImage(dd);
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 const & path, VectDocument const &list)
913 std::string patPrevName = "", patPrevID = "";
914 std::string studPrevInstanceUID = "", studPrevID = "";
915 std::string serPrevInstanceUID = "", serPrevID = "";
917 std::string patCurName, patCurID;
918 std::string studCurInstanceUID, studCurID;
919 std::string serCurInstanceUID, serCurID;
922 for( VectDocument::const_iterator it = list.begin();
923 it != list.end(); ++it )
925 // get the current file characteristics
926 patCurName = (*it)->GetEntryByNumber(0x0010,0x0010);
927 patCurID = (*it)->GetEntryByNumber(0x0010,0x0011);
928 studCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000d);
929 studCurID = (*it)->GetEntryByNumber(0x0020,0x0010);
930 serCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000e);
931 serCurID = (*it)->GetEntryByNumber(0x0020,0x0011);
933 if( patCurName != patPrevName || patCurID != patPrevID || first )
935 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
939 // if new Study Deal with 'STUDY' Elements
940 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
943 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
947 // if new Serie Deal with 'SERIE' Elements
948 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
951 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
955 // Always Deal with 'IMAGE' Elements
956 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
958 patPrevName = patCurName;
959 patPrevID = patCurID;
960 studPrevInstanceUID = studCurInstanceUID;
961 studPrevID = studCurID;
962 serPrevInstanceUID = serCurInstanceUID;
963 serPrevID = serCurID;
970 * \brief Move the content of the src SQItem to the dst SQItem
971 * Only DocEntry's are moved
974 void DicomDir::MoveSQItem(SQItem* dst,SQItem *src)
979 entry = src->GetNextEntry();
982 src->RemoveEntryNoDestroy(entry);
983 dst->AddEntry(entry);
986 entry = src->GetNextEntry();
992 * \brief compares two dgcmHeaders
994 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
996 return *header1 < *header2;
998 } // end namespace gdcm
1000 //-----------------------------------------------------------------------------