1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/01/29 11:43:05 $
7 Version: $Revision: 1.122 $
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"
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
60 * \brief Constructor : creates an empty DicomDir
65 Initialize(); // sets all private fields to NULL
70 * \brief Constructor Parses recursively the directory and creates the DicomDir
71 * or uses an already built DICOMDIR, depending on 'parseDir' value.
72 * @param fileName name
73 * - of the root directory (parseDir = true)
74 * - of the DICOMDIR (parseDir = false)
75 * @param parseDir boolean
76 * - true if user passed an entry point
77 * and wants to explore recursively the directories
78 * - false if user passed an already built DICOMDIR file
81 DicomDir::DicomDir(std::string const &fileName, bool parseDir ):
84 // At this step, Document constructor is already executed,
85 // whatever user passed (a root directory or a DICOMDIR)
86 // and whatever the value of parseDir was.
87 // (nothing is cheked in Document constructor, to avoid overhead)
89 Initialize(); // sets all private fields to NULL
91 // if user passed a root directory, sure we didn't get anything
93 if ( GetFirstEntry() == 0 ) // when user passed a Directory to parse
96 gdcmVerboseMacro( "Entry HT empty for file: "<<fileName);
98 // Only if user passed a root directory
99 // ------------------------------------
100 if ( fileName == "." )
102 // user passed '.' as Name
103 // we get current directory name
105 getcwd(dummy, (size_t)1000);
106 SetFileName( dummy ); // will be converted into a string
109 if ( parseDir ) // user asked for a recursive parsing of a root directory
113 gdcmVerboseMacro( "Parse directory and create the DicomDir");
118 /// \todo if parseDir == false, it should be tagged as an error
119 // NO ! user may just call ParseDirectory() *after* constructor
122 // Only if user passed a DICOMDIR
123 // ------------------------------
126 // Directory record sequence
127 DocEntry *e = GetDocEntry(0x0004, 0x1220);
130 gdcmVerboseMacro( "NO 'Directory record sequence' (0x0004,0x1220)"
131 << " in file " << fileName);
132 /// \todo FIXME : what do we do when the parsed file IS NOT a
141 * \brief Canonical destructor
143 DicomDir::~DicomDir()
145 SetStartMethod(NULL);
146 SetProgressMethod(NULL);
156 //-----------------------------------------------------------------------------
159 * \brief Canonical Printer
160 * @param os ostream we want to print in
161 * @param indent Indentation string to be prepended during printing
163 void DicomDir::Print(std::ostream &os, std::string const & )
167 MetaElems->SetPrintLevel(PrintLevel);
168 MetaElems->Print(os);
170 for(ListDicomDirPatient::iterator cc = Patients.begin();
171 cc != Patients.end();
174 (*cc)->SetPrintLevel(PrintLevel);
179 //-----------------------------------------------------------------------------
182 * \brief This predicate, based on hopefully reasonable heuristics,
183 * decides whether or not the current document was properly parsed
184 * and contains the mandatory information for being considered as
185 * a well formed and usable DicomDir.
186 * @return true when Document is the one of a reasonable DicomDir,
189 bool DicomDir::IsReadable()
191 if( Filetype == Unknown)
193 gdcmVerboseMacro( "Wrong filetype");
198 gdcmVerboseMacro( "Meta Elements missing in DicomDir");
201 if( Patients.size() <= 0 )
203 gdcmVerboseMacro( "NO Patient in DicomDir");
211 * \brief fills the whole structure, starting from a root Directory
213 void DicomDir::ParseDirectory()
215 CreateDicomDirChainedList( GetFileName() );
220 * \brief Set the start method to call when the parsing of the
222 * @param method Method to call
223 * @param arg Argument to pass to the method
224 * @param argDelete Argument
225 * \warning In python : the arg parameter isn't considered
227 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
228 DicomDir::Method *argDelete )
230 if( StartArg && StartMethodArgDelete )
232 StartMethodArgDelete( StartArg );
235 StartMethod = method;
237 StartMethodArgDelete = argDelete;
241 * \brief Set the method to delete the argument
242 * The argument is destroyed when the method is changed or when the
244 * @param method Method to call to delete the argument
246 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
248 StartMethodArgDelete = method;
252 * \brief Set the progress method to call when the parsing of the
254 * @param method Method to call
255 * @param arg Argument to pass to the method
256 * @param argDelete Argument
257 * \warning In python : the arg parameter isn't considered
259 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
260 DicomDir::Method *argDelete )
262 if( ProgressArg && ProgressMethodArgDelete )
264 ProgressMethodArgDelete( ProgressArg );
267 ProgressMethod = method;
269 ProgressMethodArgDelete = argDelete;
273 * \brief Set the method to delete the argument
274 * The argument is destroyed when the method is changed or when the
276 * @param method Method to call to delete the argument
278 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
280 ProgressMethodArgDelete = method;
284 * \brief Set the end method to call when the parsing of the directory ends
285 * @param method Method to call
286 * @param arg Argument to pass to the method
287 * @param argDelete Argument
288 * \warning In python : the arg parameter isn't considered
290 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
291 DicomDir::Method *argDelete )
293 if( EndArg && EndMethodArgDelete )
295 EndMethodArgDelete( EndArg );
300 EndMethodArgDelete = argDelete;
304 * \brief Set the method to delete the argument
305 * The argument is destroyed when the method is changed or when
306 * the class is destroyed
307 * @param method Method to call to delete the argument
309 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
311 EndMethodArgDelete = method;
315 * \brief Get the first entry while visiting the DicomDirPatients
316 * \return The first DicomDirPatient if found, otherwhise NULL
318 DicomDirPatient *DicomDir::GetFirstPatient()
320 ItPatient = Patients.begin();
321 if ( ItPatient != Patients.end() )
327 * \brief Get the next entry while visiting the DicomDirPatients
328 * \note : meaningfull only if GetFirstEntry already called
329 * \return The next DicomDirPatient if found, otherwhise NULL
331 DicomDirPatient *DicomDir::GetNextPatient()
333 gdcmAssertMacro (ItPatient != Patients.end());
336 if ( ItPatient != Patients.end() )
342 * \brief writes on disc a DICOMDIR
343 * \ warning does NOT add the missing elements in the header :
344 * it's up to the user doing it !
345 * \todo : to be re-written using the DICOMDIR tree-like structure
346 * *not* the chained list
347 * (does NOT exist if the DICOMDIR is user-forged !)
348 * @param fileName file to be written to
349 * @return false only when fail to open
352 bool DicomDir::WriteDicomDir(std::string const &fileName)
355 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
356 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
358 std::ofstream *fp = new std::ofstream(fileName.c_str(),
359 std::ios::out | std::ios::binary);
362 gdcmVerboseMacro("Failed to open(write) File: " << fileName.c_str());
366 char filePreamble[128];
367 memset(filePreamble, 0, 128);
368 fp->write(filePreamble, 128); //FIXME
369 binary_write( *fp, "DICM");
371 DicomDirMeta *ptrMeta = GetMeta();
372 ptrMeta->WriteContent(fp, ExplicitVR);
374 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
377 binary_write(*fp, sq[i]);
380 for(ListDicomDirPatient::iterator cc = Patients.begin();
381 cc != Patients.end();
384 (*cc)->WriteContent( fp, ExplicitVR );
387 // force writing Sequence Delimitation Item
390 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
399 //-----------------------------------------------------------------------------
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 dirList(path,1); // gets recursively the file list
410 unsigned int count = 0;
414 DirListType fileList = dirList.GetFilenames();
416 for( DirListType::iterator it = fileList.begin();
417 it != fileList.end();
420 Progress = (float)(count+1)/(float)fileList.size();
421 CallProgressMethod();
427 header = new File( it->c_str() );
430 gdcmVerboseMacro( "Failure in new gdcm::File " << it->c_str() );
434 if( header->IsReadable() )
436 // Add the file to the chained list:
437 list.push_back(header);
438 gdcmVerboseMacro( "Readable " << it->c_str() );
446 // sorts Patient/Study/Serie/
447 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
449 std::string tmp = dirList.GetDirName();
450 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
451 SetElements(tmp, list);
454 for(VectDocument::iterator itDoc=list.begin();
458 delete dynamic_cast<File *>(*itDoc);
463 * \brief adds *the* Meta to a partially created DICOMDIR
465 DicomDirMeta *DicomDir::NewMeta()
470 DocEntry *entry = GetFirstEntry();
473 MetaElems = new DicomDirMeta(true);
475 entry = GetFirstEntry();
478 if( dynamic_cast<SeqEntry *>(entry) )
481 RemoveEntryNoDestroy(entry);
482 MetaElems->AddEntry(entry);
484 entry = GetFirstEntry();
487 else // after root directory parsing
489 MetaElems = new DicomDirMeta(false);
491 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
496 * \brief adds a new Patient (with the basic elements) to a partially created
499 DicomDirPatient *DicomDir::NewPatient()
501 DicomDirPatient *p = new DicomDirPatient();
502 AddPatientToEnd( p );
507 * \brief Remove all Patients
509 void DicomDir::ClearPatient()
511 for(ListDicomDirPatient::iterator cc = Patients.begin();
521 * \brief adds to the HTable
522 * the Entries (Dicom Elements) corresponding to the given type
523 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
524 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
525 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
526 * @param header Header of the current file
528 void DicomDir::SetElement(std::string const &path, DicomDirType type,
531 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
532 ListDicomDirElem::const_iterator it;
533 uint16_t tmpGr, tmpEl;
534 DictEntry *dictEntry;
541 case GDCM_DICOMDIR_IMAGE:
542 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
543 si = new DicomDirImage(true);
544 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
547 gdcmErrorMacro( "Add ImageToEnd failed");
550 case GDCM_DICOMDIR_SERIE:
551 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
552 si = new DicomDirSerie(true);
553 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
556 gdcmErrorMacro( "Add SerieToEnd failed");
559 case GDCM_DICOMDIR_STUDY:
560 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
561 si = new DicomDirStudy(true);
562 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
565 gdcmErrorMacro( "Add StudyToEnd failed");
568 case GDCM_DICOMDIR_PATIENT:
569 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
570 si = new DicomDirPatient(true);
571 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
574 gdcmErrorMacro( "Add PatientToEnd failed");
577 case GDCM_DICOMDIR_META:
578 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
579 si = new DicomDirMeta(true);
583 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
585 MetaElems = static_cast<DicomDirMeta *>(si);
590 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
591 // to avoid further troubles
592 // imageElem 0008 1140 "" // Referenced Image Sequence
593 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
594 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
595 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
596 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
597 // for all the relevant elements found in their own spot of the DicomDir.dic
598 // FIXME : troubles found when it's a SeqEntry
600 for( it = elemList.begin(); it != elemList.end(); ++it)
604 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
606 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
608 entry->SetOffset(0); // just to avoid further missprinting
612 // NULL when we Build Up (ex nihilo) a DICOMDIR
613 // or when we add the META elems
614 val = header->GetEntryValue(tmpGr, tmpEl);
621 if( val == GDCM_UNFOUND)
623 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
625 // force to the *end* File Name
626 val = Util::GetName( path );
628 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
630 if( header->GetFileName().substr(0, path.length()) != path )
632 gdcmVerboseMacro( "The base path of file name is incorrect");
633 val = header->GetFileName();
637 val = &(header->GetFileName().c_str()[path.length()]);
647 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
651 entry->SetValue( val ); // troubles expected when vr=SQ ...
653 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
655 gdcmVerboseMacro("GDCM_DICOMDIR_META ?!? should never print that");
661 //-----------------------------------------------------------------------------
663 * \brief CallStartMethod
665 void DicomDir::CallStartMethod()
671 StartMethod( StartArg );
675 //-----------------------------------------------------------------------------
677 * \brief CallProgressMethod
679 void DicomDir::CallProgressMethod()
683 ProgressMethod( ProgressArg );
687 //-----------------------------------------------------------------------------
689 * \brief CallEndMethod
691 void DicomDir::CallEndMethod()
700 //-----------------------------------------------------------------------------
703 * \brief Sets all fields to NULL
705 void DicomDir::Initialize()
708 ProgressMethod = NULL;
710 StartMethodArgDelete = NULL;
711 ProgressMethodArgDelete = NULL;
712 EndMethodArgDelete = NULL;
724 * \brief create a 'DicomDir' from a DICOMDIR Header
726 void DicomDir::CreateDicomDir()
728 // The SeqEntries of "Directory Record Sequence" are parsed.
729 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
730 // 1 - we save the beginning iterator
731 // 2 - we continue to parse
732 // 3 - we find an other tag
733 // + we create the object for the precedent tag
736 // Directory record sequence
737 DocEntry *e = GetDocEntry(0x0004, 0x1220);
740 gdcmVerboseMacro( "No Directory Record Sequence (0004,1220) found");
741 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
745 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
748 gdcmVerboseMacro( "Element (0004,1220) is not a Sequence ?!?");
758 SQItem *tmpSI=s->GetFirstSQItem();
761 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
762 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
764 v = valEntry->GetValue();
768 gdcmVerboseMacro( "Not a ValEntry.");
772 if( v == "PATIENT " )
774 si = new DicomDirPatient(true);
775 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
779 gdcmErrorMacro( "Add PatientToEnd failed");
782 else if( v == "STUDY " )
784 si = new DicomDirStudy(true);
785 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
789 gdcmErrorMacro( "Add AddStudyToEnd failed");
792 else if( v == "SERIES" )
794 si = new DicomDirSerie(true);
795 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
799 gdcmErrorMacro( "Add AddSerieToEnd failed");
802 else if( v == "IMAGE " )
804 si = new DicomDirImage(true);
805 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
809 gdcmErrorMacro( "Add AddImageToEnd failed");
814 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
815 // neither an 'IMAGE' SQItem. Skip to next item.
819 MoveSQItem(si,tmpSI);
821 tmpSI=s->GetNextSQItem();
827 * \brief AddPatientToEnd
828 * @param dd SQ Item to enqueue to the DicomPatient chained List
830 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
832 Patients.push_back(dd);
837 * \brief AddStudyToEnd
838 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
840 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
842 if( Patients.size() > 0 )
844 ListDicomDirPatient::iterator itp = Patients.end();
846 (*itp)->AddStudy(dd);
853 * \brief AddSerieToEnd
854 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
856 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
858 if( Patients.size() > 0 )
860 ListDicomDirPatient::iterator itp = Patients.end();
863 DicomDirStudy *study = (*itp)->GetLastStudy();
874 * \brief AddImageToEnd
875 * @param dd SQ Item to enqueue to the DicomDirImage chained List
877 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
879 if( Patients.size() > 0 )
881 ListDicomDirPatient::iterator itp = Patients.end();
884 DicomDirStudy *study = (*itp)->GetLastStudy();
887 DicomDirSerie *serie = study->GetLastSerie();
899 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
900 * @param path path of the root directory
901 * @param list chained list of Headers
903 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
908 std::string patPrevName = "", patPrevID = "";
909 std::string studPrevInstanceUID = "", studPrevID = "";
910 std::string serPrevInstanceUID = "", serPrevID = "";
912 std::string patCurName, patCurID;
913 std::string studCurInstanceUID, studCurID;
914 std::string serCurInstanceUID, serCurID;
917 for( VectDocument::const_iterator it = list.begin();
918 it != list.end(); ++it )
920 // get the current file characteristics
921 patCurName = (*it)->GetEntryValue(0x0010,0x0010);
922 patCurID = (*it)->GetEntryValue(0x0010,0x0011);
923 studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
924 studCurID = (*it)->GetEntryValue(0x0020,0x0010);
925 serCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000e);
926 serCurID = (*it)->GetEntryValue(0x0020,0x0011);
928 if( patCurName != patPrevName || patCurID != patPrevID || first )
930 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
934 // if new Study Deal with 'STUDY' Elements
935 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
938 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
942 // if new Serie Deal with 'SERIE' Elements
943 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
946 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
950 // Always Deal with 'IMAGE' Elements
951 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
953 patPrevName = patCurName;
954 patPrevID = patCurID;
955 studPrevInstanceUID = studCurInstanceUID;
956 studPrevID = studCurID;
957 serPrevInstanceUID = serCurInstanceUID;
958 serPrevID = serCurID;
964 * \brief Move the content of the source SQItem to the destination SQItem
965 * Only DocEntry's are moved
966 * @param dst destination SQItem
967 * @param src source SQItem
969 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
973 entry = src->GetFirstEntry();
976 src->RemoveEntryNoDestroy(entry);
977 dst->AddEntry(entry);
978 // we destroyed -> the current iterator is not longer valid
979 entry = src->GetFirstEntry();
984 * \brief compares two files
986 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
988 return *header1 < *header2;
991 } // end namespace gdcm
993 //-----------------------------------------------------------------------------