1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/01/26 09:49:53 $
7 Version: $Revision: 1.119 $
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
466 DicomDirMeta *DicomDir::NewMeta()
471 // friend class hunting : we miss GetLastEntry and GetPreviousEntry
472 // to be able to remove any direct reference to TagHT
473 DocEntry *entry = GetFirstEntry();
476 MetaElems = new DicomDirMeta(true);
478 entry = GetFirstEntry();
481 if( dynamic_cast<SeqEntry *>(entry) )
484 RemoveEntryNoDestroy(entry);
485 MetaElems->AddEntry(entry);
487 entry = GetFirstEntry();
490 else // after root directory parsing
492 MetaElems = new DicomDirMeta(false);
494 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
499 * \brief adds a new Patient (with the basic elements) to a partially created
502 DicomDirPatient *DicomDir::NewPatient()
504 DicomDirPatient *p = new DicomDirPatient();
505 AddPatientToEnd( p );
510 * \brief Remove all Patients
512 void DicomDir::ClearPatient()
514 for(ListDicomDirPatient::iterator cc = Patients.begin();
524 * \brief adds to the HTable
525 * the Entries (Dicom Elements) corresponding to the given type
526 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
527 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
528 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
529 * @param header Header of the current file
531 void DicomDir::SetElement(std::string const &path, DicomDirType type,
534 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
535 ListDicomDirElem::const_iterator it;
536 uint16_t tmpGr, tmpEl;
537 DictEntry *dictEntry;
544 case GDCM_DICOMDIR_IMAGE:
545 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
546 si = new DicomDirImage(true);
547 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
550 gdcmErrorMacro( "Add ImageToEnd failed");
553 case GDCM_DICOMDIR_SERIE:
554 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
555 si = new DicomDirSerie(true);
556 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
559 gdcmErrorMacro( "Add SerieToEnd failed");
562 case GDCM_DICOMDIR_STUDY:
563 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
564 si = new DicomDirStudy(true);
565 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
568 gdcmErrorMacro( "Add StudyToEnd failed");
571 case GDCM_DICOMDIR_PATIENT:
572 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
573 si = new DicomDirPatient(true);
574 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
577 gdcmErrorMacro( "Add PatientToEnd failed");
580 case GDCM_DICOMDIR_META:
581 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
582 si = new DicomDirMeta(true);
586 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
588 MetaElems = static_cast<DicomDirMeta *>(si);
593 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
594 // to avoid further troubles
595 // imageElem 0008 1140 "" // Referenced Image Sequence
596 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
597 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
598 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
599 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
600 // for all the relevant elements found in their own spot of the DicomDir.dic
601 // FIXME : troubles found when it's a SeqEntry
603 for( it = elemList.begin(); it != elemList.end(); ++it)
607 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
609 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
611 entry->SetOffset(0); // just to avoid further missprinting
615 // NULL when we Build Up (ex nihilo) a DICOMDIR
616 // or when we add the META elems
617 val = header->GetEntryValue(tmpGr, tmpEl);
624 if( val == GDCM_UNFOUND)
626 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
628 // force to the *end* File Name
629 val = Util::GetName( path );
631 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
633 if( header->GetFileName().substr(0, path.length()) != path )
635 gdcmVerboseMacro( "The base path of file name is incorrect");
636 val = header->GetFileName();
640 val = &(header->GetFileName().c_str()[path.length()]);
650 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
654 entry->SetValue( val ); // troubles expected when vr=SQ ...
656 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
658 gdcmVerboseMacro("GDCM_DICOMDIR_META ?!? should never print that");
664 //-----------------------------------------------------------------------------
666 * \brief CallStartMethod
668 void DicomDir::CallStartMethod()
674 StartMethod( StartArg );
678 //-----------------------------------------------------------------------------
680 * \brief CallProgressMethod
682 void DicomDir::CallProgressMethod()
686 ProgressMethod( ProgressArg );
690 //-----------------------------------------------------------------------------
692 * \brief CallEndMethod
694 void DicomDir::CallEndMethod()
703 //-----------------------------------------------------------------------------
706 * \brief Sets all fields to NULL
708 void DicomDir::Initialize()
711 ProgressMethod = NULL;
713 StartMethodArgDelete = NULL;
714 ProgressMethodArgDelete = NULL;
715 EndMethodArgDelete = NULL;
727 * \brief create a 'DicomDir' from a DICOMDIR Header
729 void DicomDir::CreateDicomDir()
731 // The list is parsed.
732 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
733 // 1 - we save the beginning iterator
734 // 2 - we continue to parse
735 // 3 - we find an other tag
736 // + we create the object for the precedent tag
739 // Directory record sequence
740 DocEntry *e = GetDocEntry(0x0004, 0x1220);
743 gdcmVerboseMacro( "NO Directory record sequence (0x0004,0x1220)");
744 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
748 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
751 gdcmVerboseMacro( "No SeqEntry present");
752 // useless : (0x0004,0x1220) IS a Sequence !
762 SQItem *tmpSI=s->GetFirstSQItem();
765 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
766 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
768 v = valEntry->GetValue();
772 gdcmVerboseMacro( "Not a ValEntry.");
776 if( v == "PATIENT " )
778 si = new DicomDirPatient(true);
779 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
783 gdcmErrorMacro( "Add PatientToEnd failed");
786 else if( v == "STUDY " )
788 si = new DicomDirStudy(true);
789 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
793 gdcmErrorMacro( "Add AddStudyToEnd failed");
796 else if( v == "SERIES" )
798 si = new DicomDirSerie(true);
799 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
803 gdcmErrorMacro( "Add AddSerieToEnd failed");
806 else if( v == "IMAGE " )
808 si = new DicomDirImage(true);
809 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
813 gdcmErrorMacro( "Add AddImageToEnd failed");
818 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
819 // neither an 'IMAGE' SQItem. Skip to next item.
822 tmpSI=s->GetNextSQItem();
824 // friend hunting : this one will be difficult to remove !
829 * \brief AddPatientToEnd
830 * @param dd SQ Item to enqueue to the DicomPatient chained List
832 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
834 Patients.push_back(dd);
839 * \brief AddStudyToEnd
840 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
842 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
844 if( Patients.size() > 0 )
846 ListDicomDirPatient::iterator itp = Patients.end();
848 (*itp)->AddStudy(dd);
855 * \brief AddSerieToEnd
856 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
858 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
860 if( Patients.size() > 0 )
862 ListDicomDirPatient::iterator itp = Patients.end();
865 DicomDirStudy *study = (*itp)->GetLastStudy();
876 * \brief AddImageToEnd
877 * @param dd SQ Item to enqueue to the DicomDirImage chained List
879 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
881 if( Patients.size() > 0 )
883 ListDicomDirPatient::iterator itp = Patients.end();
886 DicomDirStudy *study = (*itp)->GetLastStudy();
889 DicomDirSerie *serie = study->GetLastSerie();
901 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
902 * @param path path of the root directory
903 * @param list chained list of Headers
905 void DicomDir::SetElements(std::string const & path, VectDocument const &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;
919 for( VectDocument::const_iterator it = list.begin();
920 it != list.end(); ++it )
922 // get the current file characteristics
923 patCurName = (*it)->GetEntryValue(0x0010,0x0010);
924 patCurID = (*it)->GetEntryValue(0x0010,0x0011);
925 studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
926 studCurID = (*it)->GetEntryValue(0x0020,0x0010);
927 serCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000e);
928 serCurID = (*it)->GetEntryValue(0x0020,0x0011);
930 if( patCurName != patPrevName || patCurID != patPrevID || first )
932 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
936 // if new Study Deal with 'STUDY' Elements
937 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
940 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
944 // if new Serie Deal with 'SERIE' Elements
945 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
948 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
952 // Always Deal with 'IMAGE' Elements
953 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
955 patPrevName = patCurName;
956 patPrevID = patCurID;
957 studPrevInstanceUID = studCurInstanceUID;
958 studPrevID = studCurID;
959 serPrevInstanceUID = serCurInstanceUID;
960 serPrevID = serCurID;
966 * \brief Move the content of the source SQItem to the destination SQItem
967 * Only DocEntry's are moved
968 * @param dst destination SQItem
969 * @param src source SQItem
971 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
975 entry = src->GetFirstEntry();
978 src->RemoveEntryNoDestroy(entry);
979 dst->AddEntry(entry);
980 // we destroyed -> the current iterator is not longer valid
981 entry = src->GetFirstEntry();
986 * \brief compares two files
988 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
990 return *header1 < *header2;
993 } // end namespace gdcm
995 //-----------------------------------------------------------------------------