1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/02/11 16:36:52 $
7 Version: $Revision: 1.131 $
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 //-----------------------------------------------------------------------------
20 // For full DICOMDIR description, see:
21 // PS 3.3-2003, pages 731-750
22 //-----------------------------------------------------------------------------
23 #include "gdcmDicomDir.h"
24 #include "gdcmDicomDirStudy.h"
25 #include "gdcmDicomDirSerie.h"
26 #include "gdcmDicomDirImage.h"
27 #include "gdcmDicomDirPatient.h"
28 #include "gdcmDicomDirMeta.h"
29 #include "gdcmDicomDirElement.h"
30 #include "gdcmDirList.h"
32 #include "gdcmDebug.h"
33 #include "gdcmGlobal.h"
35 #include "gdcmSeqEntry.h"
36 #include "gdcmSQItem.h"
37 #include "gdcmValEntry.h"
42 #include <sys/types.h>
45 # define getcwd _getcwd
48 #if defined(_MSC_VER) || defined(__BORLANDC__)
53 // ----------------------------------------------------------------------------
54 // Note for future developpers
55 // ----------------------------------------------------------------------------
57 // Dicom PS 3.3 describes the relationship between Directory Records, as follow
59 // Directory Record Type Directory Record Types which may be included
60 // in the next lower-level directory Entity
62 // (Root directory Entity) PATIENT
66 // STUDY SERIES, VISIT, RESULTS, STUDY COMPONENT
68 // SERIES IMAGE, OVERLAYS, MODALITY LUT, VOI LUT,
69 // CURVE, STORED PRINT, RT DOSE, RT STRUCTURE SET
70 // RT PLAN, RT TREAT RECORD, PRESENTATION, WAVEFORM,
71 // SR DOCUMENT, KEY OBJECT DOC, SPECTROSCOPY,
72 // RAW DATA, REGISTRATION, FIDUCIAL
92 // ----------------------
93 // The current gdcm version only deals with :
95 // (Root directory Entity) PATIENT
101 // DicomDir::CreateDicomDir will have to be completed
102 // Treelike structure management will have to be upgraded
103 // ----------------------------------------------------------------------------
107 //-----------------------------------------------------------------------------
108 // Constructor / Destructor
110 * \brief Constructor : creates an empty DicomDir
115 Initialize(); // sets all private fields to NULL
120 * \brief Constructor Parses recursively the directory and creates the DicomDir
121 * or uses an already built DICOMDIR, depending on 'parseDir' value.
122 * @param fileName name
123 * - of the root directory (parseDir = true)
124 * - of the DICOMDIR (parseDir = false)
125 * @param parseDir boolean
126 * - true if user passed an entry point
127 * and wants to explore recursively the directories
128 * - false if user passed an already built DICOMDIR file
129 * and wants to use it
131 DicomDir::DicomDir(std::string const &fileName, bool parseDir ):
134 // At this step, Document constructor is already executed,
135 // whatever user passed (a root directory or a DICOMDIR)
136 // and whatever the value of parseDir was.
137 // (nothing is cheked in Document constructor, to avoid overhead)
139 Initialize(); // sets all private fields to NULL
141 // if user passed a root directory, sure we didn't get anything
143 if ( GetFirstEntry() == 0 ) // when user passed a Directory to parse
146 gdcmWarningMacro( "Entry HT empty for file: "<<fileName);
148 // Only if user passed a root directory
149 // ------------------------------------
150 if ( fileName == "." )
152 // user passed '.' as Name
153 // we get current directory name
155 getcwd(dummy, (size_t)1000);
156 SetFileName( dummy ); // will be converted into a string
159 if ( parseDir ) // user asked for a recursive parsing of a root directory
163 gdcmWarningMacro( "Parse directory and create the DicomDir");
168 // user may just call ParseDirectory() *after* constructor
171 // Only if user passed a DICOMDIR
172 // ------------------------------
175 // Directory record sequence
176 DocEntry *e = GetDocEntry(0x0004, 0x1220);
179 gdcmWarningMacro( "NO 'Directory record sequence' (0x0004,0x1220)"
180 << " in file " << fileName);
188 * \brief Canonical destructor
190 DicomDir::~DicomDir()
192 SetStartMethod(NULL);
193 SetProgressMethod(NULL);
203 //-----------------------------------------------------------------------------
206 * \brief This predicate, based on hopefully reasonable heuristics,
207 * decides whether or not the current document was properly parsed
208 * and contains the mandatory information for being considered as
209 * a well formed and usable DicomDir.
210 * @return true when Document is the one of a reasonable DicomDir,
213 bool DicomDir::IsReadable()
215 if( Filetype == Unknown)
217 gdcmWarningMacro( "Wrong filetype");
222 gdcmWarningMacro( "Meta Elements missing in DicomDir");
225 if( Patients.size() <= 0 )
227 gdcmWarningMacro( "NO Patient in DicomDir");
235 * \brief adds *the* Meta to a partially created DICOMDIR
237 DicomDirMeta *DicomDir::NewMeta()
242 DocEntry *entry = GetFirstEntry();
245 MetaElems = new DicomDirMeta(true);
247 entry = GetFirstEntry();
250 if( dynamic_cast<SeqEntry *>(entry) )
253 RemoveEntryNoDestroy(entry);
254 MetaElems->AddEntry(entry);
256 entry = GetFirstEntry();
259 else // after root directory parsing
261 MetaElems = new DicomDirMeta(false);
263 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
268 * \brief adds a new Patient (with the basic elements) to a partially created
271 DicomDirPatient *DicomDir::NewPatient()
273 DicomDirPatient *p = new DicomDirPatient();
274 AddPatientToEnd( p );
279 * \brief Remove all Patients
281 void DicomDir::ClearPatient()
283 for(ListDicomDirPatient::iterator cc = Patients.begin();
293 * \brief Get the first entry while visiting the DicomDirPatients
294 * \return The first DicomDirPatient if found, otherwhise NULL
296 DicomDirPatient *DicomDir::GetFirstPatient()
298 ItPatient = Patients.begin();
299 if ( ItPatient != Patients.end() )
305 * \brief Get the next entry while visiting the DicomDirPatients
306 * \note : meaningfull only if GetFirstEntry already called
307 * \return The next DicomDirPatient if found, otherwhise NULL
309 DicomDirPatient *DicomDir::GetNextPatient()
311 gdcmAssertMacro (ItPatient != Patients.end());
314 if ( ItPatient != Patients.end() )
320 * \brief fills the whole structure, starting from a root Directory
322 void DicomDir::ParseDirectory()
324 CreateDicomDirChainedList( GetFileName() );
329 * \brief Set the start method to call when the parsing of the
331 * @param method Method to call
332 * @param arg Argument to pass to the method
333 * @param argDelete Argument
334 * \warning In python : the arg parameter isn't considered
336 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
337 DicomDir::Method *argDelete )
339 if( StartArg && StartMethodArgDelete )
341 StartMethodArgDelete( StartArg );
344 StartMethod = method;
346 StartMethodArgDelete = argDelete;
350 * \brief Set the progress method to call when the parsing of the
352 * @param method Method to call
353 * @param arg Argument to pass to the method
354 * @param argDelete Argument
355 * \warning In python : the arg parameter isn't considered
357 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
358 DicomDir::Method *argDelete )
360 if( ProgressArg && ProgressMethodArgDelete )
362 ProgressMethodArgDelete( ProgressArg );
365 ProgressMethod = method;
367 ProgressMethodArgDelete = argDelete;
371 * \brief Set the end method to call when the parsing of the directory ends
372 * @param method Method to call
373 * @param arg Argument to pass to the method
374 * @param argDelete Argument
375 * \warning In python : the arg parameter isn't considered
377 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
378 DicomDir::Method *argDelete )
380 if( EndArg && EndMethodArgDelete )
382 EndMethodArgDelete( EndArg );
387 EndMethodArgDelete = argDelete;
391 * \brief Set the method to delete the argument
392 * The argument is destroyed when the method is changed or when the
394 * @param method Method to call to delete the argument
396 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
398 StartMethodArgDelete = method;
402 * \brief Set the method to delete the argument
403 * The argument is destroyed when the method is changed or when the
405 * @param method Method to call to delete the argument
407 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
409 ProgressMethodArgDelete = method;
413 * \brief Set the method to delete the argument
414 * The argument is destroyed when the method is changed or when
415 * the class is destroyed
416 * @param method Method to call to delete the argument
418 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
420 EndMethodArgDelete = method;
424 * \brief writes on disc a DICOMDIR
425 * \ warning does NOT add the missing elements in the header :
426 * it's up to the user doing it !
427 * \todo : to be re-written using the DICOMDIR tree-like structure
428 * *not* the chained list
429 * (does NOT exist if the DICOMDIR is user-forged !)
430 * @param fileName file to be written to
431 * @return false only when fail to open
434 bool DicomDir::WriteDicomDir(std::string const &fileName)
437 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
438 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
440 std::ofstream *fp = new std::ofstream(fileName.c_str(),
441 std::ios::out | std::ios::binary);
444 gdcmWarningMacro("Failed to open(write) File: " << fileName.c_str());
448 char filePreamble[128];
449 memset(filePreamble, 0, 128);
450 fp->write(filePreamble, 128); //FIXME
451 binary_write( *fp, "DICM");
453 DicomDirMeta *ptrMeta = GetMeta();
454 ptrMeta->WriteContent(fp, ExplicitVR);
456 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
459 binary_write(*fp, sq[i]);
462 for(ListDicomDirPatient::iterator cc = Patients.begin();
463 cc != Patients.end();
466 (*cc)->WriteContent( fp, ExplicitVR );
469 // force writing Sequence Delimitation Item
472 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
481 //-----------------------------------------------------------------------------
484 * \brief create a Document-like chained list from a root Directory
485 * @param path entry point of the tree-like structure
487 void DicomDir::CreateDicomDirChainedList(std::string const &path)
490 DirList dirList(path,1); // gets recursively the file list
491 unsigned int count = 0;
495 DirListType fileList = dirList.GetFilenames();
497 for( DirListType::iterator it = fileList.begin();
498 it != fileList.end();
501 Progress = (float)(count+1)/(float)fileList.size();
502 CallProgressMethod();
508 header = new File( it->c_str() );
511 gdcmWarningMacro( "Failure in new gdcm::File " << it->c_str() );
515 if( header->IsReadable() )
517 // Add the file to the chained list:
518 list.push_back(header);
519 gdcmWarningMacro( "Readable " << it->c_str() );
527 // sorts Patient/Study/Serie/
528 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
530 std::string tmp = dirList.GetDirName();
531 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
532 SetElements(tmp, list);
535 for(VectDocument::iterator itDoc=list.begin();
539 delete dynamic_cast<File *>(*itDoc);
544 * \brief CallStartMethod
546 void DicomDir::CallStartMethod()
552 StartMethod( StartArg );
557 * \brief CallProgressMethod
559 void DicomDir::CallProgressMethod()
563 ProgressMethod( ProgressArg );
568 * \brief CallEndMethod
570 void DicomDir::CallEndMethod()
579 //-----------------------------------------------------------------------------
582 * \brief Sets all fields to NULL
584 void DicomDir::Initialize()
587 ProgressMethod = NULL;
589 StartMethodArgDelete = NULL;
590 ProgressMethodArgDelete = NULL;
591 EndMethodArgDelete = NULL;
603 * \brief create a 'DicomDir' from a DICOMDIR Header
605 void DicomDir::CreateDicomDir()
607 // The SeqEntries of "Directory Record Sequence" are parsed.
608 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
609 // 1 - we save the beginning iterator
610 // 2 - we continue to parse
611 // 3 - we find an other tag
612 // + we create the object for the precedent tag
615 // Directory record sequence
616 DocEntry *e = GetDocEntry(0x0004, 0x1220);
619 gdcmWarningMacro( "No Directory Record Sequence (0004,1220) found");
623 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
626 gdcmWarningMacro( "Element (0004,1220) is not a Sequence ?!?");
636 SQItem *tmpSI=s->GetFirstSQItem();
639 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
640 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
642 v = valEntry->GetValue();
646 gdcmWarningMacro( "Not a ValEntry.");
650 if( v == "PATIENT " )
652 si = new DicomDirPatient(true);
653 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
657 gdcmErrorMacro( "Add PatientToEnd failed");
660 else if( v == "STUDY " )
662 si = new DicomDirStudy(true);
663 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
667 gdcmErrorMacro( "Add AddStudyToEnd failed");
670 else if( v == "SERIES" )
672 si = new DicomDirSerie(true);
673 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
677 gdcmErrorMacro( "Add AddSerieToEnd failed");
680 else if( v == "IMAGE " )
682 si = new DicomDirImage(true);
683 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
687 gdcmErrorMacro( "Add AddImageToEnd failed");
692 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
693 // neither an 'IMAGE' SQItem. Skip to next item.
697 MoveSQItem(si,tmpSI);
699 tmpSI=s->GetNextSQItem();
705 * \brief AddPatientToEnd
706 * @param dd SQ Item to enqueue to the DicomPatient chained List
708 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
710 Patients.push_back(dd);
715 * \brief AddStudyToEnd
716 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
718 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
720 if( Patients.size() > 0 )
722 ListDicomDirPatient::iterator itp = Patients.end();
724 (*itp)->AddStudy(dd);
731 * \brief AddSerieToEnd
732 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
734 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
736 if( Patients.size() > 0 )
738 ListDicomDirPatient::iterator itp = Patients.end();
741 DicomDirStudy *study = (*itp)->GetLastStudy();
752 * \brief AddImageToEnd
753 * @param dd SQ Item to enqueue to the DicomDirImage chained List
755 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
757 if( Patients.size() > 0 )
759 ListDicomDirPatient::iterator itp = Patients.end();
762 DicomDirStudy *study = (*itp)->GetLastStudy();
765 DicomDirSerie *serie = study->GetLastSerie();
777 * \brief for each Header of the chained list,
778 * add/update the Patient/Study/Serie/Image info
779 * @param path path of the root directory
780 * @param list chained list of Headers
782 void DicomDir::SetElements(std::string const &path, VectDocument const &list)
787 std::string patPrevName = "", patPrevID = "";
788 std::string studPrevInstanceUID = "", studPrevID = "";
789 std::string serPrevInstanceUID = "", serPrevID = "";
791 std::string patCurName, patCurID;
792 std::string studCurInstanceUID, studCurID;
793 std::string serCurInstanceUID, serCurID;
796 for( VectDocument::const_iterator it = list.begin();
800 // get the current file characteristics
801 patCurName = (*it)->GetEntryValue(0x0010,0x0010);
802 patCurID = (*it)->GetEntryValue(0x0010,0x0011);
803 studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
804 studCurID = (*it)->GetEntryValue(0x0020,0x0010);
805 serCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000e);
806 serCurID = (*it)->GetEntryValue(0x0020,0x0011);
808 if( patCurName != patPrevName || patCurID != patPrevID || first )
810 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
814 // if new Study Deal with 'STUDY' Elements
815 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
818 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
822 // if new Serie Deal with 'SERIE' Elements
823 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
826 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
830 // Always Deal with 'IMAGE' Elements
831 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
833 patPrevName = patCurName;
834 patPrevID = patCurID;
835 studPrevInstanceUID = studCurInstanceUID;
836 studPrevID = studCurID;
837 serPrevInstanceUID = serCurInstanceUID;
838 serPrevID = serCurID;
844 * \brief adds to the HTable
845 * the Entries (Dicom Elements) corresponding to the given type
846 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
847 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
848 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
849 * @param header Header of the current file
851 void DicomDir::SetElement(std::string const &path, DicomDirType type,
854 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
855 ListDicomDirElem::const_iterator it;
856 uint16_t tmpGr, tmpEl;
857 DictEntry *dictEntry;
864 case GDCM_DICOMDIR_IMAGE:
865 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
866 si = new DicomDirImage(true);
867 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
870 gdcmErrorMacro( "Add ImageToEnd failed");
873 case GDCM_DICOMDIR_SERIE:
874 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
875 si = new DicomDirSerie(true);
876 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
879 gdcmErrorMacro( "Add SerieToEnd failed");
882 case GDCM_DICOMDIR_STUDY:
883 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
884 si = new DicomDirStudy(true);
885 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
888 gdcmErrorMacro( "Add StudyToEnd failed");
891 case GDCM_DICOMDIR_PATIENT:
892 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
893 si = new DicomDirPatient(true);
894 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
897 gdcmErrorMacro( "Add PatientToEnd failed");
900 case GDCM_DICOMDIR_META:
901 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
902 si = new DicomDirMeta(true);
906 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
908 MetaElems = static_cast<DicomDirMeta *>(si);
913 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
914 // to avoid further troubles
915 // imageElem 0008 1140 "" // Referenced Image Sequence
916 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
917 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
918 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
919 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
921 // FIXME : troubles found when it's a SeqEntry
923 // for all the relevant elements found in their own spot of the DicomDir.dic
924 for( it = elemList.begin(); it != elemList.end(); ++it)
928 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
930 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
932 entry->SetOffset(0); // just to avoid further missprinting
936 // NULL when we Build Up (ex nihilo) a DICOMDIR
937 // or when we add the META elems
938 val = header->GetEntryValue(tmpGr, tmpEl);
945 if( val == GDCM_UNFOUND)
947 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
949 // force to the *end* File Name
950 val = Util::GetName( path );
952 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
954 if( header->GetFileName().substr(0, path.length()) != path )
956 gdcmWarningMacro( "The base path of file name is incorrect");
957 val = header->GetFileName();
961 val = &(header->GetFileName().c_str()[path.length()]);
971 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
975 entry->SetValue( val ); // troubles expected when vr=SQ ...
977 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
979 gdcmWarningMacro("GDCM_DICOMDIR_META ?!? should never print that");
986 * \brief Move the content of the source SQItem to the destination SQItem
987 * Only DocEntry's are moved
988 * @param dst destination SQItem
989 * @param src source SQItem
991 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
995 entry = src->GetFirstEntry();
998 src->RemoveEntryNoDestroy(entry);
999 dst->AddEntry(entry);
1000 // we destroyed -> the current iterator is not longer valid
1001 entry = src->GetFirstEntry();
1006 * \brief compares two files
1008 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1010 return *header1 < *header2;
1013 //-----------------------------------------------------------------------------
1016 * \brief Canonical Printer
1017 * @param os ostream we want to print in
1018 * @param indent Indentation string to be prepended during printing
1020 void DicomDir::Print(std::ostream &os, std::string const & )
1024 MetaElems->SetPrintLevel(PrintLevel);
1025 MetaElems->Print(os);
1027 for(ListDicomDirPatient::iterator cc = Patients.begin();
1028 cc != Patients.end();
1031 (*cc)->SetPrintLevel(PrintLevel);
1036 //-----------------------------------------------------------------------------
1037 } // end namespace gdcm