1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/02/02 14:52:24 $
7 Version: $Revision: 1.127 $
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__)
56 //-----------------------------------------------------------------------------
57 // Constructor / Destructor
59 * \brief Constructor : creates an empty DicomDir
64 Initialize(); // sets all private fields to NULL
69 * \brief Constructor Parses recursively the directory and creates the DicomDir
70 * or uses an already built DICOMDIR, depending on 'parseDir' value.
71 * @param fileName name
72 * - of the root directory (parseDir = true)
73 * - of the DICOMDIR (parseDir = false)
74 * @param parseDir boolean
75 * - true if user passed an entry point
76 * and wants to explore recursively the directories
77 * - false if user passed an already built DICOMDIR file
80 DicomDir::DicomDir(std::string const &fileName, bool parseDir ):
83 // At this step, Document constructor is already executed,
84 // whatever user passed (a root directory or a DICOMDIR)
85 // and whatever the value of parseDir was.
86 // (nothing is cheked in Document constructor, to avoid overhead)
88 Initialize(); // sets all private fields to NULL
90 // if user passed a root directory, sure we didn't get anything
92 if ( GetFirstEntry() == 0 ) // when user passed a Directory to parse
95 gdcmVerboseMacro( "Entry HT empty for file: "<<fileName);
97 // Only if user passed a root directory
98 // ------------------------------------
99 if ( fileName == "." )
101 // user passed '.' as Name
102 // we get current directory name
104 getcwd(dummy, (size_t)1000);
105 SetFileName( dummy ); // will be converted into a string
108 if ( parseDir ) // user asked for a recursive parsing of a root directory
112 gdcmVerboseMacro( "Parse directory and create the DicomDir");
117 /// \todo if parseDir == false, it should be tagged as an error
118 // NO ! user may just call ParseDirectory() *after* constructor
121 // Only if user passed a DICOMDIR
122 // ------------------------------
125 // Directory record sequence
126 DocEntry *e = GetDocEntry(0x0004, 0x1220);
129 gdcmVerboseMacro( "NO 'Directory record sequence' (0x0004,0x1220)"
130 << " in file " << fileName);
131 /// \todo FIXME : what do we do when the parsed file IS NOT a
140 * \brief Canonical destructor
142 DicomDir::~DicomDir()
144 SetStartMethod(NULL);
145 SetProgressMethod(NULL);
155 //-----------------------------------------------------------------------------
158 * \brief This predicate, based on hopefully reasonable heuristics,
159 * decides whether or not the current document was properly parsed
160 * and contains the mandatory information for being considered as
161 * a well formed and usable DicomDir.
162 * @return true when Document is the one of a reasonable DicomDir,
165 bool DicomDir::IsReadable()
167 if( Filetype == Unknown)
169 gdcmVerboseMacro( "Wrong filetype");
174 gdcmVerboseMacro( "Meta Elements missing in DicomDir");
177 if( Patients.size() <= 0 )
179 gdcmVerboseMacro( "NO Patient in DicomDir");
187 * \brief adds *the* Meta to a partially created DICOMDIR
189 DicomDirMeta *DicomDir::NewMeta()
194 DocEntry *entry = GetFirstEntry();
197 MetaElems = new DicomDirMeta(true);
199 entry = GetFirstEntry();
202 if( dynamic_cast<SeqEntry *>(entry) )
205 RemoveEntryNoDestroy(entry);
206 MetaElems->AddEntry(entry);
208 entry = GetFirstEntry();
211 else // after root directory parsing
213 MetaElems = new DicomDirMeta(false);
215 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
220 * \brief adds a new Patient (with the basic elements) to a partially created
223 DicomDirPatient *DicomDir::NewPatient()
225 DicomDirPatient *p = new DicomDirPatient();
226 AddPatientToEnd( p );
231 * \brief Remove all Patients
233 void DicomDir::ClearPatient()
235 for(ListDicomDirPatient::iterator cc = Patients.begin();
245 * \brief Get the first entry while visiting the DicomDirPatients
246 * \return The first DicomDirPatient if found, otherwhise NULL
248 DicomDirPatient *DicomDir::GetFirstPatient()
250 ItPatient = Patients.begin();
251 if ( ItPatient != Patients.end() )
257 * \brief Get the next entry while visiting the DicomDirPatients
258 * \note : meaningfull only if GetFirstEntry already called
259 * \return The next DicomDirPatient if found, otherwhise NULL
261 DicomDirPatient *DicomDir::GetNextPatient()
263 gdcmAssertMacro (ItPatient != Patients.end());
266 if ( ItPatient != Patients.end() )
272 * \brief fills the whole structure, starting from a root Directory
274 void DicomDir::ParseDirectory()
276 CreateDicomDirChainedList( GetFileName() );
281 * \brief Set the start method to call when the parsing of the
283 * @param method Method to call
284 * @param arg Argument to pass to the method
285 * @param argDelete Argument
286 * \warning In python : the arg parameter isn't considered
288 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
289 DicomDir::Method *argDelete )
291 if( StartArg && StartMethodArgDelete )
293 StartMethodArgDelete( StartArg );
296 StartMethod = method;
298 StartMethodArgDelete = argDelete;
302 * \brief Set the progress method to call when the parsing of the
304 * @param method Method to call
305 * @param arg Argument to pass to the method
306 * @param argDelete Argument
307 * \warning In python : the arg parameter isn't considered
309 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
310 DicomDir::Method *argDelete )
312 if( ProgressArg && ProgressMethodArgDelete )
314 ProgressMethodArgDelete( ProgressArg );
317 ProgressMethod = method;
319 ProgressMethodArgDelete = argDelete;
323 * \brief Set the end method to call when the parsing of the directory ends
324 * @param method Method to call
325 * @param arg Argument to pass to the method
326 * @param argDelete Argument
327 * \warning In python : the arg parameter isn't considered
329 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
330 DicomDir::Method *argDelete )
332 if( EndArg && EndMethodArgDelete )
334 EndMethodArgDelete( EndArg );
339 EndMethodArgDelete = argDelete;
343 * \brief Set the method to delete the argument
344 * The argument is destroyed when the method is changed or when the
346 * @param method Method to call to delete the argument
348 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
350 StartMethodArgDelete = method;
354 * \brief Set the method to delete the argument
355 * The argument is destroyed when the method is changed or when the
357 * @param method Method to call to delete the argument
359 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
361 ProgressMethodArgDelete = method;
365 * \brief Set the method to delete the argument
366 * The argument is destroyed when the method is changed or when
367 * the class is destroyed
368 * @param method Method to call to delete the argument
370 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
372 EndMethodArgDelete = method;
376 * \brief writes on disc a DICOMDIR
377 * \ warning does NOT add the missing elements in the header :
378 * it's up to the user doing it !
379 * \todo : to be re-written using the DICOMDIR tree-like structure
380 * *not* the chained list
381 * (does NOT exist if the DICOMDIR is user-forged !)
382 * @param fileName file to be written to
383 * @return false only when fail to open
386 bool DicomDir::WriteDicomDir(std::string const &fileName)
389 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
390 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
392 std::ofstream *fp = new std::ofstream(fileName.c_str(),
393 std::ios::out | std::ios::binary);
396 gdcmVerboseMacro("Failed to open(write) File: " << fileName.c_str());
400 char filePreamble[128];
401 memset(filePreamble, 0, 128);
402 fp->write(filePreamble, 128); //FIXME
403 binary_write( *fp, "DICM");
405 DicomDirMeta *ptrMeta = GetMeta();
406 ptrMeta->WriteContent(fp, ExplicitVR);
408 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
411 binary_write(*fp, sq[i]);
414 for(ListDicomDirPatient::iterator cc = Patients.begin();
415 cc != Patients.end();
418 (*cc)->WriteContent( fp, ExplicitVR );
421 // force writing Sequence Delimitation Item
424 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
433 //-----------------------------------------------------------------------------
436 * \brief create a Document-like chained list from a root Directory
437 * @param path entry point of the tree-like structure
439 void DicomDir::CreateDicomDirChainedList(std::string const &path)
442 DirList dirList(path,1); // gets recursively the file list
443 unsigned int count = 0;
447 DirListType fileList = dirList.GetFilenames();
449 for( DirListType::iterator it = fileList.begin();
450 it != fileList.end();
453 Progress = (float)(count+1)/(float)fileList.size();
454 CallProgressMethod();
460 header = new File( it->c_str() );
463 gdcmVerboseMacro( "Failure in new gdcm::File " << it->c_str() );
467 if( header->IsReadable() )
469 // Add the file to the chained list:
470 list.push_back(header);
471 gdcmVerboseMacro( "Readable " << it->c_str() );
479 // sorts Patient/Study/Serie/
480 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
482 std::string tmp = dirList.GetDirName();
483 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
484 SetElements(tmp, list);
487 for(VectDocument::iterator itDoc=list.begin();
491 delete dynamic_cast<File *>(*itDoc);
496 * \brief CallStartMethod
498 void DicomDir::CallStartMethod()
504 StartMethod( StartArg );
509 * \brief CallProgressMethod
511 void DicomDir::CallProgressMethod()
515 ProgressMethod( ProgressArg );
520 * \brief CallEndMethod
522 void DicomDir::CallEndMethod()
531 //-----------------------------------------------------------------------------
534 * \brief Sets all fields to NULL
536 void DicomDir::Initialize()
539 ProgressMethod = NULL;
541 StartMethodArgDelete = NULL;
542 ProgressMethodArgDelete = NULL;
543 EndMethodArgDelete = NULL;
555 * \brief create a 'DicomDir' from a DICOMDIR Header
557 void DicomDir::CreateDicomDir()
559 // The SeqEntries of "Directory Record Sequence" are parsed.
560 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
561 // 1 - we save the beginning iterator
562 // 2 - we continue to parse
563 // 3 - we find an other tag
564 // + we create the object for the precedent tag
567 // Directory record sequence
568 DocEntry *e = GetDocEntry(0x0004, 0x1220);
571 gdcmVerboseMacro( "No Directory Record Sequence (0004,1220) found");
572 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
576 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
579 gdcmVerboseMacro( "Element (0004,1220) is not a Sequence ?!?");
589 SQItem *tmpSI=s->GetFirstSQItem();
592 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
593 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
595 v = valEntry->GetValue();
599 gdcmVerboseMacro( "Not a ValEntry.");
603 if( v == "PATIENT " )
605 si = new DicomDirPatient(true);
606 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
610 gdcmErrorMacro( "Add PatientToEnd failed");
613 else if( v == "STUDY " )
615 si = new DicomDirStudy(true);
616 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
620 gdcmErrorMacro( "Add AddStudyToEnd failed");
623 else if( v == "SERIES" )
625 si = new DicomDirSerie(true);
626 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
630 gdcmErrorMacro( "Add AddSerieToEnd failed");
633 else if( v == "IMAGE " )
635 si = new DicomDirImage(true);
636 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
640 gdcmErrorMacro( "Add AddImageToEnd failed");
645 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
646 // neither an 'IMAGE' SQItem. Skip to next item.
650 MoveSQItem(si,tmpSI);
652 tmpSI=s->GetNextSQItem();
658 * \brief AddPatientToEnd
659 * @param dd SQ Item to enqueue to the DicomPatient chained List
661 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
663 Patients.push_back(dd);
668 * \brief AddStudyToEnd
669 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
671 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
673 if( Patients.size() > 0 )
675 ListDicomDirPatient::iterator itp = Patients.end();
677 (*itp)->AddStudy(dd);
684 * \brief AddSerieToEnd
685 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
687 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
689 if( Patients.size() > 0 )
691 ListDicomDirPatient::iterator itp = Patients.end();
694 DicomDirStudy *study = (*itp)->GetLastStudy();
705 * \brief AddImageToEnd
706 * @param dd SQ Item to enqueue to the DicomDirImage chained List
708 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
710 if( Patients.size() > 0 )
712 ListDicomDirPatient::iterator itp = Patients.end();
715 DicomDirStudy *study = (*itp)->GetLastStudy();
718 DicomDirSerie *serie = study->GetLastSerie();
730 * \brief for each Header of the chained list,
731 * add/update the Patient/Study/Serie/Image info
732 * @param path path of the root directory
733 * @param list chained list of Headers
735 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
740 std::string patPrevName = "", patPrevID = "";
741 std::string studPrevInstanceUID = "", studPrevID = "";
742 std::string serPrevInstanceUID = "", serPrevID = "";
744 std::string patCurName, patCurID;
745 std::string studCurInstanceUID, studCurID;
746 std::string serCurInstanceUID, serCurID;
749 for( VectDocument::const_iterator it = list.begin();
750 it != list.end(); ++it )
752 // get the current file characteristics
753 patCurName = (*it)->GetEntryValue(0x0010,0x0010);
754 patCurID = (*it)->GetEntryValue(0x0010,0x0011);
755 studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
756 studCurID = (*it)->GetEntryValue(0x0020,0x0010);
757 serCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000e);
758 serCurID = (*it)->GetEntryValue(0x0020,0x0011);
760 if( patCurName != patPrevName || patCurID != patPrevID || first )
762 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
766 // if new Study Deal with 'STUDY' Elements
767 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
770 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
774 // if new Serie Deal with 'SERIE' Elements
775 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
778 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
782 // Always Deal with 'IMAGE' Elements
783 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
785 patPrevName = patCurName;
786 patPrevID = patCurID;
787 studPrevInstanceUID = studCurInstanceUID;
788 studPrevID = studCurID;
789 serPrevInstanceUID = serCurInstanceUID;
790 serPrevID = serCurID;
796 * \brief adds to the HTable
797 * the Entries (Dicom Elements) corresponding to the given type
798 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
799 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
800 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
801 * @param header Header of the current file
803 void DicomDir::SetElement(std::string const &path, DicomDirType type,
806 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
807 ListDicomDirElem::const_iterator it;
808 uint16_t tmpGr, tmpEl;
809 DictEntry *dictEntry;
816 case GDCM_DICOMDIR_IMAGE:
817 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
818 si = new DicomDirImage(true);
819 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
822 gdcmErrorMacro( "Add ImageToEnd failed");
825 case GDCM_DICOMDIR_SERIE:
826 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
827 si = new DicomDirSerie(true);
828 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
831 gdcmErrorMacro( "Add SerieToEnd failed");
834 case GDCM_DICOMDIR_STUDY:
835 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
836 si = new DicomDirStudy(true);
837 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
840 gdcmErrorMacro( "Add StudyToEnd failed");
843 case GDCM_DICOMDIR_PATIENT:
844 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
845 si = new DicomDirPatient(true);
846 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
849 gdcmErrorMacro( "Add PatientToEnd failed");
852 case GDCM_DICOMDIR_META:
853 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
854 si = new DicomDirMeta(true);
858 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
860 MetaElems = static_cast<DicomDirMeta *>(si);
865 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
866 // to avoid further troubles
867 // imageElem 0008 1140 "" // Referenced Image Sequence
868 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
869 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
870 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
871 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
872 // for all the relevant elements found in their own spot of the DicomDir.dic
874 // FIXME : troubles found when it's a SeqEntry
876 for( it = elemList.begin(); it != elemList.end(); ++it)
880 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
882 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
884 entry->SetOffset(0); // just to avoid further missprinting
888 // NULL when we Build Up (ex nihilo) a DICOMDIR
889 // or when we add the META elems
890 val = header->GetEntryValue(tmpGr, tmpEl);
897 if( val == GDCM_UNFOUND)
899 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
901 // force to the *end* File Name
902 val = Util::GetName( path );
904 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
906 if( header->GetFileName().substr(0, path.length()) != path )
908 gdcmVerboseMacro( "The base path of file name is incorrect");
909 val = header->GetFileName();
913 val = &(header->GetFileName().c_str()[path.length()]);
923 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
927 entry->SetValue( val ); // troubles expected when vr=SQ ...
929 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
931 gdcmVerboseMacro("GDCM_DICOMDIR_META ?!? should never print that");
938 * \brief Move the content of the source SQItem to the destination SQItem
939 * Only DocEntry's are moved
940 * @param dst destination SQItem
941 * @param src source SQItem
943 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
947 entry = src->GetFirstEntry();
950 src->RemoveEntryNoDestroy(entry);
951 dst->AddEntry(entry);
952 // we destroyed -> the current iterator is not longer valid
953 entry = src->GetFirstEntry();
958 * \brief compares two files
960 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
962 return *header1 < *header2;
965 //-----------------------------------------------------------------------------
968 * \brief Canonical Printer
969 * @param os ostream we want to print in
970 * @param indent Indentation string to be prepended during printing
972 void DicomDir::Print(std::ostream &os, std::string const & )
976 MetaElems->SetPrintLevel(PrintLevel);
977 MetaElems->Print(os);
979 for(ListDicomDirPatient::iterator cc = Patients.begin();
980 cc != Patients.end();
983 (*cc)->SetPrintLevel(PrintLevel);
988 //-----------------------------------------------------------------------------
989 } // end namespace gdcm