1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/01/24 16:10:52 $
7 Version: $Revision: 1.116 $
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);
149 for(ListDicomDirPatient::iterator cc = Patients.begin();
161 //-----------------------------------------------------------------------------
164 * \brief Canonical Printer
165 * @param os ostream we want to print in
166 * @param indent Indentation string to be prepended during printing
168 void DicomDir::Print(std::ostream &os, std::string const & )
172 MetaElems->SetPrintLevel(PrintLevel);
173 MetaElems->Print(os);
175 for(ListDicomDirPatient::iterator cc = Patients.begin();
176 cc != Patients.end();
179 (*cc)->SetPrintLevel(PrintLevel);
184 //-----------------------------------------------------------------------------
187 * \brief This predicate, based on hopefully reasonable heuristics,
188 * decides whether or not the current document was properly parsed
189 * and contains the mandatory information for being considered as
190 * a well formed and usable DicomDir.
191 * @return true when Document is the one of a reasonable DicomDir,
194 bool DicomDir::IsReadable()
196 if( Filetype == Unknown)
198 gdcmVerboseMacro( "Wrong filetype");
203 gdcmVerboseMacro( "Meta Elements missing in DicomDir");
206 if( Patients.size() <= 0 )
208 gdcmVerboseMacro( "NO Patient in DicomDir");
216 * \brief fills the whole structure, starting from a root Directory
218 void DicomDir::ParseDirectory()
220 CreateDicomDirChainedList( GetFileName() );
225 * \brief Set the start method to call when the parsing of the
227 * @param method Method to call
228 * @param arg Argument to pass to the method
229 * @param argDelete Argument
230 * \warning In python : the arg parameter isn't considered
232 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
233 DicomDir::Method *argDelete )
235 if( StartArg && StartMethodArgDelete )
237 StartMethodArgDelete( StartArg );
240 StartMethod = method;
242 StartMethodArgDelete = argDelete;
246 * \brief Set the method to delete the argument
247 * The argument is destroyed when the method is changed or when the
249 * @param method Method to call to delete the argument
251 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
253 StartMethodArgDelete = method;
257 * \brief Set the progress method to call when the parsing of the
259 * @param method Method to call
260 * @param arg Argument to pass to the method
261 * @param argDelete Argument
262 * \warning In python : the arg parameter isn't considered
264 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
265 DicomDir::Method *argDelete )
267 if( ProgressArg && ProgressMethodArgDelete )
269 ProgressMethodArgDelete( ProgressArg );
272 ProgressMethod = method;
274 ProgressMethodArgDelete = argDelete;
278 * \brief Set the method to delete the argument
279 * The argument is destroyed when the method is changed or when the
281 * @param method Method to call to delete the argument
283 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
285 ProgressMethodArgDelete = method;
289 * \brief Set the end method to call when the parsing of the directory ends
290 * @param method Method to call
291 * @param arg Argument to pass to the method
292 * @param argDelete Argument
293 * \warning In python : the arg parameter isn't considered
295 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
296 DicomDir::Method *argDelete )
298 if( EndArg && EndMethodArgDelete )
300 EndMethodArgDelete( EndArg );
305 EndMethodArgDelete = argDelete;
309 * \brief Set the method to delete the argument
310 * The argument is destroyed when the method is changed or when
311 * the class is destroyed
312 * @param method Method to call to delete the argument
314 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
316 EndMethodArgDelete = method;
320 * \brief Get the first entry while visiting the DicomDirPatients
321 * \return The first DicomDirPatient if found, otherwhise NULL
323 DicomDirPatient *DicomDir::GetFirstPatient()
325 ItPatient = Patients.begin();
326 if ( ItPatient != Patients.end() )
332 * \brief Get the next entry while visiting the DicomDirPatients
333 * \note : meaningfull only if GetFirstEntry already called
334 * \return The next DicomDirPatient if found, otherwhise NULL
336 DicomDirPatient *DicomDir::GetNextPatient()
338 gdcmAssertMacro (ItPatient != Patients.end());
341 if ( ItPatient != Patients.end() )
348 * \brief writes on disc a DICOMDIR
349 * \ warning does NOT add the missing elements in the header :
350 * it's up to the user doing it !
351 * \todo : to be re-written using the DICOMDIR tree-like structure
352 * *not* the chained list
353 * (does NOT exist if the DICOMDIR is user-forged !)
354 * @param fileName file to be written to
355 * @return false only when fail to open
358 bool DicomDir::WriteDicomDir(std::string const &fileName)
361 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
362 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
364 std::ofstream *fp = new std::ofstream(fileName.c_str(),
365 std::ios::out | std::ios::binary);
368 gdcmVerboseMacro("Failed to open(write) File: " << fileName.c_str());
372 char filePreamble[128];
373 memset(filePreamble, 0, 128);
374 fp->write(filePreamble, 128); //FIXME
375 binary_write( *fp, "DICM");
377 DicomDirMeta *ptrMeta = GetMeta();
378 ptrMeta->WriteContent(fp, ExplicitVR);
380 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
383 binary_write(*fp, sq[i]);
386 for(ListDicomDirPatient::iterator cc = Patients.begin();
387 cc != Patients.end();
390 (*cc)->WriteContent( fp, ExplicitVR );
393 // force writing Sequence Delimitation Item
396 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
405 //-----------------------------------------------------------------------------
409 * \brief create a Document-like chained list from a root Directory
410 * @param path entry point of the tree-like structure
412 void DicomDir::CreateDicomDirChainedList(std::string const & path)
415 DirList dirList(path,1); // gets recursively the file list
416 unsigned int count = 0;
420 DirListType fileList = dirList.GetFilenames();
422 for( DirListType::iterator it = fileList.begin();
423 it != fileList.end();
426 Progress = (float)(count+1)/(float)fileList.size();
427 CallProgressMethod();
433 header = new File( it->c_str() );
436 gdcmVerboseMacro( "Failure in new gdcm::File " << it->c_str() );
440 if( header->IsReadable() )
442 // Add the file to the chained list:
443 list.push_back(header);
444 gdcmVerboseMacro( "Readable " << it->c_str() );
452 // sorts Patient/Study/Serie/
453 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
455 std::string tmp = dirList.GetDirName();
456 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
457 SetElements(tmp, list);
460 for(VectDocument::iterator itDoc=list.begin();
464 delete dynamic_cast<File *>(*itDoc);
469 * \brief adds *the* Meta to a partially created DICOMDIR
472 DicomDirMeta *DicomDir::NewMeta()
477 // friend class hunting : we miss GetLastEntry and GetPreviousEntry
478 // to be able to remove any direct reference to TagHT
480 DocEntry *e = GetFirstEntry();
482 //if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
484 MetaElems = new DicomDirMeta(true);
486 TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
487 lastOneButSequence --;
488 // ALL the 'out of Sequence' Tags belong to Meta Elems
489 // (we skip 0004|1220 [Directory record sequence] )
490 for ( TagDocEntryHT::iterator cc = TagHT.begin();
491 cc != lastOneButSequence;
494 MetaElems->AddEntry( cc->second );
497 else // after root directory parsing
499 MetaElems = new DicomDirMeta(false);
501 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
506 * \brief adds a new Patient (with the basic elements) to a partially created DICOMDIR
508 DicomDirPatient *DicomDir::NewPatient()
510 DicomDirPatient *p = new DicomDirPatient();
511 AddPatientToEnd( p );
516 * \brief adds to the HTable
517 * the Entries (Dicom Elements) corresponding to the given type
518 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
519 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
520 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
521 * @param header Header of the current file
523 void DicomDir::SetElement(std::string const &path, DicomDirType type,
526 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
527 ListDicomDirElem::const_iterator it;
528 uint16_t tmpGr, tmpEl;
529 DictEntry *dictEntry;
536 case GDCM_DICOMDIR_IMAGE:
537 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
538 si = new DicomDirImage(true);
539 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
542 gdcmErrorMacro( "Add ImageToEnd failed");
545 case GDCM_DICOMDIR_SERIE:
546 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
547 si = new DicomDirSerie(true);
548 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
551 gdcmErrorMacro( "Add SerieToEnd failed");
554 case GDCM_DICOMDIR_STUDY:
555 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
556 si = new DicomDirStudy(true);
557 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
560 gdcmErrorMacro( "Add StudyToEnd failed");
563 case GDCM_DICOMDIR_PATIENT:
564 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
565 si = new DicomDirPatient(true);
566 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
569 gdcmErrorMacro( "Add PatientToEnd failed");
572 case GDCM_DICOMDIR_META:
573 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
574 si = new DicomDirMeta(true);
578 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
580 MetaElems = static_cast<DicomDirMeta *>(si);
585 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
586 // to avoid further troubles
587 // imageElem 0008 1140 "" // Referenced Image Sequence
588 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
589 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
590 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
591 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
592 // for all the relevant elements found in their own spot of the DicomDir.dic
593 // FIXME : troubles found when it's a SeqEntry
595 for( it = elemList.begin(); it != elemList.end(); ++it)
599 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
601 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
603 entry->SetOffset(0); // just to avoid further missprinting
607 // NULL when we Build Up (ex nihilo) a DICOMDIR
608 // or when we add the META elems
609 val = header->GetEntryValue(tmpGr, tmpEl);
616 if( val == GDCM_UNFOUND)
618 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
620 // force to the *end* File Name
621 val = Util::GetName( path );
623 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
625 if( header->GetFileName().substr(0, path.length()) != path )
627 gdcmVerboseMacro( "The base path of file name is incorrect");
628 val = header->GetFileName();
632 val = &(header->GetFileName().c_str()[path.length()]);
642 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
646 entry->SetValue( val ); // troubles expected when vr=SQ ...
648 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
650 gdcmVerboseMacro("GDCM_DICOMDIR_META ?!? should never print that");
656 //-----------------------------------------------------------------------------
658 * \brief CallStartMethod
660 void DicomDir::CallStartMethod()
666 StartMethod( StartArg );
670 //-----------------------------------------------------------------------------
672 * \brief CallProgressMethod
674 void DicomDir::CallProgressMethod()
678 ProgressMethod( ProgressArg );
682 //-----------------------------------------------------------------------------
684 * \brief CallEndMethod
686 void DicomDir::CallEndMethod()
695 //-----------------------------------------------------------------------------
698 * \brief Sets all fields to NULL
700 void DicomDir::Initialize()
703 ProgressMethod = NULL;
705 StartMethodArgDelete = NULL;
706 ProgressMethodArgDelete = NULL;
707 EndMethodArgDelete = NULL;
719 * \brief create a 'DicomDir' from a DICOMDIR Header
721 void DicomDir::CreateDicomDir()
723 // The list is parsed.
724 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
725 // 1 - we save the beginning iterator
726 // 2 - we continue to parse
727 // 3 - we find an other tag
728 // + we create the object for the precedent tag
731 // Directory record sequence
732 DocEntry *e = GetDocEntry(0x0004, 0x1220);
735 gdcmVerboseMacro( "NO Directory record sequence (0x0004,0x1220)");
736 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
740 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
743 gdcmVerboseMacro( "No SeqEntry present");
744 // useless : (0x0004,0x1220) IS a Sequence !
754 SQItem *tmpSI=s->GetFirstSQItem();
757 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
758 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
760 v = valEntry->GetValue();
764 gdcmVerboseMacro( "Not a ValEntry.");
768 if( v == "PATIENT " )
770 si = new DicomDirPatient(true);
771 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
775 gdcmErrorMacro( "Add PatientToEnd failed");
778 else if( v == "STUDY " )
780 si = new DicomDirStudy(true);
781 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
785 gdcmErrorMacro( "Add AddStudyToEnd failed");
788 else if( v == "SERIES" )
790 si = new DicomDirSerie(true);
791 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
795 gdcmErrorMacro( "Add AddSerieToEnd failed");
798 else if( v == "IMAGE " )
800 si = new DicomDirImage(true);
801 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
805 gdcmErrorMacro( "Add AddImageToEnd failed");
810 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
811 // neither an 'IMAGE' SQItem. Skip to next item.
816 MoveSQItem(si,tmpSI);
817 tmpSI=s->GetNextSQItem();
819 // friend hunting : this one will be difficult to remove !
824 * \brief AddPatientToEnd
825 * @param dd SQ Item to enqueue to the DicomPatient chained List
827 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
829 Patients.push_back(dd);
834 * \brief AddStudyToEnd
835 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
837 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
839 if( Patients.size() > 0 )
841 ListDicomDirPatient::iterator itp = Patients.end();
843 (*itp)->AddStudy(dd);
850 * \brief AddSerieToEnd
851 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
853 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
855 if( Patients.size() > 0 )
857 ListDicomDirPatient::iterator itp = Patients.end();
860 DicomDirStudy *study = (*itp)->GetLastStudy();
866 /* if( (*itp)->GetDicomDirStudies().size() > 0 )
868 ListDicomDirStudy::const_iterator itst =
869 (*itp)->GetDicomDirStudies().end();
871 (*itst)->AddSerie(dd);
879 * \brief AddImageToEnd
880 * @param dd SQ Item to enqueue to the DicomDirImage chained List
882 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
884 if( Patients.size() > 0 )
886 ListDicomDirPatient::iterator itp = Patients.end();
889 DicomDirStudy *study = (*itp)->GetLastStudy();
892 DicomDirSerie *serie = study->GetLastSerie();
899 /* if( (*itp)->GetDicomDirStudies().size() > 0 )
901 ListDicomDirStudy::const_iterator itst =
902 (*itp)->GetDicomDirStudies().end();
905 if( (*itst)->GetDicomDirSeries().size() > 0 )
907 ListDicomDirSerie::const_iterator its = (*itst)->GetDicomDirSeries().end();
909 (*its)->AddImage(dd);
918 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
919 * @param path path of the root directory
920 * @param list chained list of Headers
922 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
927 std::string patPrevName = "", patPrevID = "";
928 std::string studPrevInstanceUID = "", studPrevID = "";
929 std::string serPrevInstanceUID = "", serPrevID = "";
931 std::string patCurName, patCurID;
932 std::string studCurInstanceUID, studCurID;
933 std::string serCurInstanceUID, serCurID;
936 for( VectDocument::const_iterator it = list.begin();
937 it != list.end(); ++it )
939 // get the current file characteristics
940 patCurName = (*it)->GetEntryValue(0x0010,0x0010);
941 patCurID = (*it)->GetEntryValue(0x0010,0x0011);
942 studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
943 studCurID = (*it)->GetEntryValue(0x0020,0x0010);
944 serCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000e);
945 serCurID = (*it)->GetEntryValue(0x0020,0x0011);
947 if( patCurName != patPrevName || patCurID != patPrevID || first )
949 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
953 // if new Study Deal with 'STUDY' Elements
954 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
957 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
961 // if new Serie Deal with 'SERIE' Elements
962 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
965 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
969 // Always Deal with 'IMAGE' Elements
970 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
972 patPrevName = patCurName;
973 patPrevID = patCurID;
974 studPrevInstanceUID = studCurInstanceUID;
975 studPrevID = studCurID;
976 serPrevInstanceUID = serCurInstanceUID;
977 serPrevID = serCurID;
983 * \brief Move the content of the source SQItem to the destination SQItem
984 * Only DocEntry's are moved
985 * @param dst destination SQItem
986 * @param src source SQItem
988 void DicomDir::MoveSQItem(SQItem *dst,SQItem *src)
992 entry = src->GetFirstEntry();
995 src->RemoveEntryNoDestroy(entry);
996 dst->AddEntry(entry);
997 // we destroyed -> the current iterator is not longer valid
998 entry = src->GetFirstEntry();
1003 * \brief compares two files
1005 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1007 return *header1 < *header2;
1010 } // end namespace gdcm
1012 //-----------------------------------------------------------------------------