1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/02/01 13:00:16 $
7 Version: $Revision: 1.125 $
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 fills the whole structure, starting from a root Directory
189 void DicomDir::ParseDirectory()
191 CreateDicomDirChainedList( GetFileName() );
196 * \brief Set the start method to call when the parsing of the
198 * @param method Method to call
199 * @param arg Argument to pass to the method
200 * @param argDelete Argument
201 * \warning In python : the arg parameter isn't considered
203 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
204 DicomDir::Method *argDelete )
206 if( StartArg && StartMethodArgDelete )
208 StartMethodArgDelete( StartArg );
211 StartMethod = method;
213 StartMethodArgDelete = argDelete;
217 * \brief Set the method to delete the argument
218 * The argument is destroyed when the method is changed or when the
220 * @param method Method to call to delete the argument
222 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
224 StartMethodArgDelete = method;
228 * \brief Set the progress method to call when the parsing of the
230 * @param method Method to call
231 * @param arg Argument to pass to the method
232 * @param argDelete Argument
233 * \warning In python : the arg parameter isn't considered
235 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
236 DicomDir::Method *argDelete )
238 if( ProgressArg && ProgressMethodArgDelete )
240 ProgressMethodArgDelete( ProgressArg );
243 ProgressMethod = method;
245 ProgressMethodArgDelete = argDelete;
249 * \brief Set the method to delete the argument
250 * The argument is destroyed when the method is changed or when the
252 * @param method Method to call to delete the argument
254 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
256 ProgressMethodArgDelete = method;
260 * \brief Set the end method to call when the parsing of the directory ends
261 * @param method Method to call
262 * @param arg Argument to pass to the method
263 * @param argDelete Argument
264 * \warning In python : the arg parameter isn't considered
266 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
267 DicomDir::Method *argDelete )
269 if( EndArg && EndMethodArgDelete )
271 EndMethodArgDelete( EndArg );
276 EndMethodArgDelete = argDelete;
280 * \brief Set the method to delete the argument
281 * The argument is destroyed when the method is changed or when
282 * the class is destroyed
283 * @param method Method to call to delete the argument
285 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
287 EndMethodArgDelete = method;
291 * \brief Get the first entry while visiting the DicomDirPatients
292 * \return The first DicomDirPatient if found, otherwhise NULL
294 DicomDirPatient *DicomDir::GetFirstPatient()
296 ItPatient = Patients.begin();
297 if ( ItPatient != Patients.end() )
303 * \brief Get the next entry while visiting the DicomDirPatients
304 * \note : meaningfull only if GetFirstEntry already called
305 * \return The next DicomDirPatient if found, otherwhise NULL
307 DicomDirPatient *DicomDir::GetNextPatient()
309 gdcmAssertMacro (ItPatient != Patients.end());
312 if ( ItPatient != Patients.end() )
318 * \brief writes on disc a DICOMDIR
319 * \ warning does NOT add the missing elements in the header :
320 * it's up to the user doing it !
321 * \todo : to be re-written using the DICOMDIR tree-like structure
322 * *not* the chained list
323 * (does NOT exist if the DICOMDIR is user-forged !)
324 * @param fileName file to be written to
325 * @return false only when fail to open
328 bool DicomDir::WriteDicomDir(std::string const &fileName)
331 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
332 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
334 std::ofstream *fp = new std::ofstream(fileName.c_str(),
335 std::ios::out | std::ios::binary);
338 gdcmVerboseMacro("Failed to open(write) File: " << fileName.c_str());
342 char filePreamble[128];
343 memset(filePreamble, 0, 128);
344 fp->write(filePreamble, 128); //FIXME
345 binary_write( *fp, "DICM");
347 DicomDirMeta *ptrMeta = GetMeta();
348 ptrMeta->WriteContent(fp, ExplicitVR);
350 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
353 binary_write(*fp, sq[i]);
356 for(ListDicomDirPatient::iterator cc = Patients.begin();
357 cc != Patients.end();
360 (*cc)->WriteContent( fp, ExplicitVR );
363 // force writing Sequence Delimitation Item
366 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
375 //-----------------------------------------------------------------------------
378 * \brief create a Document-like chained list from a root Directory
379 * @param path entry point of the tree-like structure
381 void DicomDir::CreateDicomDirChainedList(std::string const & path)
384 DirList dirList(path,1); // gets recursively the file list
385 unsigned int count = 0;
389 DirListType fileList = dirList.GetFilenames();
391 for( DirListType::iterator it = fileList.begin();
392 it != fileList.end();
395 Progress = (float)(count+1)/(float)fileList.size();
396 CallProgressMethod();
402 header = new File( it->c_str() );
405 gdcmVerboseMacro( "Failure in new gdcm::File " << it->c_str() );
409 if( header->IsReadable() )
411 // Add the file to the chained list:
412 list.push_back(header);
413 gdcmVerboseMacro( "Readable " << it->c_str() );
421 // sorts Patient/Study/Serie/
422 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
424 std::string tmp = dirList.GetDirName();
425 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
426 SetElements(tmp, list);
429 for(VectDocument::iterator itDoc=list.begin();
433 delete dynamic_cast<File *>(*itDoc);
438 * \brief adds *the* Meta to a partially created DICOMDIR
440 DicomDirMeta *DicomDir::NewMeta()
445 DocEntry *entry = GetFirstEntry();
448 MetaElems = new DicomDirMeta(true);
450 entry = GetFirstEntry();
453 if( dynamic_cast<SeqEntry *>(entry) )
456 RemoveEntryNoDestroy(entry);
457 MetaElems->AddEntry(entry);
459 entry = GetFirstEntry();
462 else // after root directory parsing
464 MetaElems = new DicomDirMeta(false);
466 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
471 * \brief adds a new Patient (with the basic elements) to a partially created
474 DicomDirPatient *DicomDir::NewPatient()
476 DicomDirPatient *p = new DicomDirPatient();
477 AddPatientToEnd( p );
482 * \brief Remove all Patients
484 void DicomDir::ClearPatient()
486 for(ListDicomDirPatient::iterator cc = Patients.begin();
496 * \brief adds to the HTable
497 * the Entries (Dicom Elements) corresponding to the given type
498 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
499 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
500 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
501 * @param header Header of the current file
503 void DicomDir::SetElement(std::string const &path, DicomDirType type,
506 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
507 ListDicomDirElem::const_iterator it;
508 uint16_t tmpGr, tmpEl;
509 DictEntry *dictEntry;
516 case GDCM_DICOMDIR_IMAGE:
517 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
518 si = new DicomDirImage(true);
519 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
522 gdcmErrorMacro( "Add ImageToEnd failed");
525 case GDCM_DICOMDIR_SERIE:
526 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
527 si = new DicomDirSerie(true);
528 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
531 gdcmErrorMacro( "Add SerieToEnd failed");
534 case GDCM_DICOMDIR_STUDY:
535 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
536 si = new DicomDirStudy(true);
537 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
540 gdcmErrorMacro( "Add StudyToEnd failed");
543 case GDCM_DICOMDIR_PATIENT:
544 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
545 si = new DicomDirPatient(true);
546 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
549 gdcmErrorMacro( "Add PatientToEnd failed");
552 case GDCM_DICOMDIR_META:
553 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
554 si = new DicomDirMeta(true);
558 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
560 MetaElems = static_cast<DicomDirMeta *>(si);
565 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
566 // to avoid further troubles
567 // imageElem 0008 1140 "" // Referenced Image Sequence
568 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
569 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
570 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
571 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
572 // for all the relevant elements found in their own spot of the DicomDir.dic
574 // FIXME : troubles found when it's a SeqEntry
576 for( it = elemList.begin(); it != elemList.end(); ++it)
580 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
582 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
584 entry->SetOffset(0); // just to avoid further missprinting
588 // NULL when we Build Up (ex nihilo) a DICOMDIR
589 // or when we add the META elems
590 val = header->GetEntryValue(tmpGr, tmpEl);
597 if( val == GDCM_UNFOUND)
599 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
601 // force to the *end* File Name
602 val = Util::GetName( path );
604 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
606 if( header->GetFileName().substr(0, path.length()) != path )
608 gdcmVerboseMacro( "The base path of file name is incorrect");
609 val = header->GetFileName();
613 val = &(header->GetFileName().c_str()[path.length()]);
623 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
627 entry->SetValue( val ); // troubles expected when vr=SQ ...
629 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
631 gdcmVerboseMacro("GDCM_DICOMDIR_META ?!? should never print that");
638 * \brief CallStartMethod
640 void DicomDir::CallStartMethod()
646 StartMethod( StartArg );
651 * \brief CallProgressMethod
653 void DicomDir::CallProgressMethod()
657 ProgressMethod( ProgressArg );
662 * \brief CallEndMethod
664 void DicomDir::CallEndMethod()
673 //-----------------------------------------------------------------------------
676 * \brief Sets all fields to NULL
678 void DicomDir::Initialize()
681 ProgressMethod = NULL;
683 StartMethodArgDelete = NULL;
684 ProgressMethodArgDelete = NULL;
685 EndMethodArgDelete = NULL;
697 * \brief create a 'DicomDir' from a DICOMDIR Header
699 void DicomDir::CreateDicomDir()
701 // The SeqEntries of "Directory Record Sequence" are parsed.
702 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
703 // 1 - we save the beginning iterator
704 // 2 - we continue to parse
705 // 3 - we find an other tag
706 // + we create the object for the precedent tag
709 // Directory record sequence
710 DocEntry *e = GetDocEntry(0x0004, 0x1220);
713 gdcmVerboseMacro( "No Directory Record Sequence (0004,1220) found");
714 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
718 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
721 gdcmVerboseMacro( "Element (0004,1220) is not a Sequence ?!?");
731 SQItem *tmpSI=s->GetFirstSQItem();
734 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
735 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
737 v = valEntry->GetValue();
741 gdcmVerboseMacro( "Not a ValEntry.");
745 if( v == "PATIENT " )
747 si = new DicomDirPatient(true);
748 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
752 gdcmErrorMacro( "Add PatientToEnd failed");
755 else if( v == "STUDY " )
757 si = new DicomDirStudy(true);
758 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
762 gdcmErrorMacro( "Add AddStudyToEnd failed");
765 else if( v == "SERIES" )
767 si = new DicomDirSerie(true);
768 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
772 gdcmErrorMacro( "Add AddSerieToEnd failed");
775 else if( v == "IMAGE " )
777 si = new DicomDirImage(true);
778 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
782 gdcmErrorMacro( "Add AddImageToEnd failed");
787 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
788 // neither an 'IMAGE' SQItem. Skip to next item.
792 MoveSQItem(si,tmpSI);
794 tmpSI=s->GetNextSQItem();
800 * \brief AddPatientToEnd
801 * @param dd SQ Item to enqueue to the DicomPatient chained List
803 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
805 Patients.push_back(dd);
810 * \brief AddStudyToEnd
811 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
813 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
815 if( Patients.size() > 0 )
817 ListDicomDirPatient::iterator itp = Patients.end();
819 (*itp)->AddStudy(dd);
826 * \brief AddSerieToEnd
827 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
829 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
831 if( Patients.size() > 0 )
833 ListDicomDirPatient::iterator itp = Patients.end();
836 DicomDirStudy *study = (*itp)->GetLastStudy();
847 * \brief AddImageToEnd
848 * @param dd SQ Item to enqueue to the DicomDirImage chained List
850 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
852 if( Patients.size() > 0 )
854 ListDicomDirPatient::iterator itp = Patients.end();
857 DicomDirStudy *study = (*itp)->GetLastStudy();
860 DicomDirSerie *serie = study->GetLastSerie();
872 * \brief for each Header of the chained list,
873 * add/update the Patient/Study/Serie/Image info
874 * @param path path of the root directory
875 * @param list chained list of Headers
877 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
882 std::string patPrevName = "", patPrevID = "";
883 std::string studPrevInstanceUID = "", studPrevID = "";
884 std::string serPrevInstanceUID = "", serPrevID = "";
886 std::string patCurName, patCurID;
887 std::string studCurInstanceUID, studCurID;
888 std::string serCurInstanceUID, serCurID;
891 for( VectDocument::const_iterator it = list.begin();
892 it != list.end(); ++it )
894 // get the current file characteristics
895 patCurName = (*it)->GetEntryValue(0x0010,0x0010);
896 patCurID = (*it)->GetEntryValue(0x0010,0x0011);
897 studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
898 studCurID = (*it)->GetEntryValue(0x0020,0x0010);
899 serCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000e);
900 serCurID = (*it)->GetEntryValue(0x0020,0x0011);
902 if( patCurName != patPrevName || patCurID != patPrevID || first )
904 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
908 // if new Study Deal with 'STUDY' Elements
909 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
912 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
916 // if new Serie Deal with 'SERIE' Elements
917 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
920 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
924 // Always Deal with 'IMAGE' Elements
925 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
927 patPrevName = patCurName;
928 patPrevID = patCurID;
929 studPrevInstanceUID = studCurInstanceUID;
930 studPrevID = studCurID;
931 serPrevInstanceUID = serCurInstanceUID;
932 serPrevID = serCurID;
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