1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/01/25 11:11:58 $
7 Version: $Revision: 1.117 $
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() )
343 * \brief writes on disc a DICOMDIR
344 * \ warning does NOT add the missing elements in the header :
345 * it's up to the user doing it !
346 * \todo : to be re-written using the DICOMDIR tree-like structure
347 * *not* the chained list
348 * (does NOT exist if the DICOMDIR is user-forged !)
349 * @param fileName file to be written to
350 * @return false only when fail to open
353 bool DicomDir::WriteDicomDir(std::string const &fileName)
356 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
357 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
359 std::ofstream *fp = new std::ofstream(fileName.c_str(),
360 std::ios::out | std::ios::binary);
363 gdcmVerboseMacro("Failed to open(write) File: " << fileName.c_str());
367 char filePreamble[128];
368 memset(filePreamble, 0, 128);
369 fp->write(filePreamble, 128); //FIXME
370 binary_write( *fp, "DICM");
372 DicomDirMeta *ptrMeta = GetMeta();
373 ptrMeta->WriteContent(fp, ExplicitVR);
375 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
378 binary_write(*fp, sq[i]);
381 for(ListDicomDirPatient::iterator cc = Patients.begin();
382 cc != Patients.end();
385 (*cc)->WriteContent( fp, ExplicitVR );
388 // force writing Sequence Delimitation Item
391 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
400 //-----------------------------------------------------------------------------
404 * \brief create a Document-like chained list from a root Directory
405 * @param path entry point of the tree-like structure
407 void DicomDir::CreateDicomDirChainedList(std::string const & path)
410 DirList dirList(path,1); // gets recursively the file list
411 unsigned int count = 0;
415 DirListType fileList = dirList.GetFilenames();
417 for( DirListType::iterator it = fileList.begin();
418 it != fileList.end();
421 Progress = (float)(count+1)/(float)fileList.size();
422 CallProgressMethod();
428 header = new File( it->c_str() );
431 gdcmVerboseMacro( "Failure in new gdcm::File " << it->c_str() );
435 if( header->IsReadable() )
437 // Add the file to the chained list:
438 list.push_back(header);
439 gdcmVerboseMacro( "Readable " << it->c_str() );
447 // sorts Patient/Study/Serie/
448 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
450 std::string tmp = dirList.GetDirName();
451 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
452 SetElements(tmp, list);
455 for(VectDocument::iterator itDoc=list.begin();
459 delete dynamic_cast<File *>(*itDoc);
464 * \brief adds *the* Meta to a partially created DICOMDIR
467 DicomDirMeta *DicomDir::NewMeta()
472 // friend class hunting : we miss GetLastEntry and GetPreviousEntry
473 // to be able to remove any direct reference to TagHT
474 DocEntry *entry = GetFirstEntry();
476 //if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
478 MetaElems = new DicomDirMeta(true);
480 entry = GetFirstEntry();
483 if( dynamic_cast<SeqEntry *>(entry) )
486 RemoveEntryNoDestroy(entry);
487 MetaElems->AddEntry(entry);
489 entry = GetFirstEntry();
491 /*TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
492 lastOneButSequence --;
493 // ALL the 'out of Sequence' Tags belong to Meta Elems
494 // (we skip 0004|1220 [Directory record sequence] )
495 for ( TagDocEntryHT::iterator cc = TagHT.begin();
496 cc != lastOneButSequence;
499 MetaElems->AddEntry( cc->second );
502 else // after root directory parsing
504 MetaElems = new DicomDirMeta(false);
506 MetaElems->SetSQItemNumber(0); // To avoid further missprinting
511 * \brief adds a new Patient (with the basic elements) to a partially created
514 DicomDirPatient *DicomDir::NewPatient()
516 DicomDirPatient *p = new DicomDirPatient();
517 AddPatientToEnd( p );
522 * \brief Remove all Patients
524 void DicomDir::ClearPatient()
526 for(ListDicomDirPatient::iterator cc = Patients.begin();
536 * \brief adds to the HTable
537 * the Entries (Dicom Elements) corresponding to the given type
538 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
539 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
540 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
541 * @param header Header of the current file
543 void DicomDir::SetElement(std::string const &path, DicomDirType type,
546 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
547 ListDicomDirElem::const_iterator it;
548 uint16_t tmpGr, tmpEl;
549 DictEntry *dictEntry;
556 case GDCM_DICOMDIR_IMAGE:
557 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
558 si = new DicomDirImage(true);
559 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
562 gdcmErrorMacro( "Add ImageToEnd failed");
565 case GDCM_DICOMDIR_SERIE:
566 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
567 si = new DicomDirSerie(true);
568 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
571 gdcmErrorMacro( "Add SerieToEnd failed");
574 case GDCM_DICOMDIR_STUDY:
575 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
576 si = new DicomDirStudy(true);
577 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
580 gdcmErrorMacro( "Add StudyToEnd failed");
583 case GDCM_DICOMDIR_PATIENT:
584 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
585 si = new DicomDirPatient(true);
586 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
589 gdcmErrorMacro( "Add PatientToEnd failed");
592 case GDCM_DICOMDIR_META:
593 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
594 si = new DicomDirMeta(true);
598 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
600 MetaElems = static_cast<DicomDirMeta *>(si);
605 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
606 // to avoid further troubles
607 // imageElem 0008 1140 "" // Referenced Image Sequence
608 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
609 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
610 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
611 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
612 // for all the relevant elements found in their own spot of the DicomDir.dic
613 // FIXME : troubles found when it's a SeqEntry
615 for( it = elemList.begin(); it != elemList.end(); ++it)
619 dictEntry = GetPubDict()->GetEntry(tmpGr, tmpEl);
621 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
623 entry->SetOffset(0); // just to avoid further missprinting
627 // NULL when we Build Up (ex nihilo) a DICOMDIR
628 // or when we add the META elems
629 val = header->GetEntryValue(tmpGr, tmpEl);
636 if( val == GDCM_UNFOUND)
638 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
640 // force to the *end* File Name
641 val = Util::GetName( path );
643 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
645 if( header->GetFileName().substr(0, path.length()) != path )
647 gdcmVerboseMacro( "The base path of file name is incorrect");
648 val = header->GetFileName();
652 val = &(header->GetFileName().c_str()[path.length()]);
662 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
666 entry->SetValue( val ); // troubles expected when vr=SQ ...
668 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
670 gdcmVerboseMacro("GDCM_DICOMDIR_META ?!? should never print that");
676 //-----------------------------------------------------------------------------
678 * \brief CallStartMethod
680 void DicomDir::CallStartMethod()
686 StartMethod( StartArg );
690 //-----------------------------------------------------------------------------
692 * \brief CallProgressMethod
694 void DicomDir::CallProgressMethod()
698 ProgressMethod( ProgressArg );
702 //-----------------------------------------------------------------------------
704 * \brief CallEndMethod
706 void DicomDir::CallEndMethod()
715 //-----------------------------------------------------------------------------
718 * \brief Sets all fields to NULL
720 void DicomDir::Initialize()
723 ProgressMethod = NULL;
725 StartMethodArgDelete = NULL;
726 ProgressMethodArgDelete = NULL;
727 EndMethodArgDelete = NULL;
739 * \brief create a 'DicomDir' from a DICOMDIR Header
741 void DicomDir::CreateDicomDir()
743 // The list is parsed.
744 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
745 // 1 - we save the beginning iterator
746 // 2 - we continue to parse
747 // 3 - we find an other tag
748 // + we create the object for the precedent tag
751 // Directory record sequence
752 DocEntry *e = GetDocEntry(0x0004, 0x1220);
755 gdcmVerboseMacro( "NO Directory record sequence (0x0004,0x1220)");
756 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
760 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
763 gdcmVerboseMacro( "No SeqEntry present");
764 // useless : (0x0004,0x1220) IS a Sequence !
774 SQItem *tmpSI=s->GetFirstSQItem();
777 d = tmpSI->GetDocEntry(0x0004, 0x1430); // Directory Record Type
778 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
780 v = valEntry->GetValue();
784 gdcmVerboseMacro( "Not a ValEntry.");
788 if( v == "PATIENT " )
790 si = new DicomDirPatient(true);
791 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
795 gdcmErrorMacro( "Add PatientToEnd failed");
798 else if( v == "STUDY " )
800 si = new DicomDirStudy(true);
801 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
805 gdcmErrorMacro( "Add AddStudyToEnd failed");
808 else if( v == "SERIES" )
810 si = new DicomDirSerie(true);
811 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
815 gdcmErrorMacro( "Add AddSerieToEnd failed");
818 else if( v == "IMAGE " )
820 si = new DicomDirImage(true);
821 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
825 gdcmErrorMacro( "Add AddImageToEnd failed");
830 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
831 // neither an 'IMAGE' SQItem. Skip to next item.
836 //MoveSQItem(si,tmpSI);
837 tmpSI=s->GetNextSQItem();
839 // friend hunting : this one will be difficult to remove !
844 * \brief AddPatientToEnd
845 * @param dd SQ Item to enqueue to the DicomPatient chained List
847 bool DicomDir::AddPatientToEnd(DicomDirPatient *dd)
849 Patients.push_back(dd);
854 * \brief AddStudyToEnd
855 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
857 bool DicomDir::AddStudyToEnd(DicomDirStudy *dd)
859 if( Patients.size() > 0 )
861 ListDicomDirPatient::iterator itp = Patients.end();
863 (*itp)->AddStudy(dd);
870 * \brief AddSerieToEnd
871 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
873 bool DicomDir::AddSerieToEnd(DicomDirSerie *dd)
875 if( Patients.size() > 0 )
877 ListDicomDirPatient::iterator itp = Patients.end();
880 DicomDirStudy *study = (*itp)->GetLastStudy();
891 * \brief AddImageToEnd
892 * @param dd SQ Item to enqueue to the DicomDirImage chained List
894 bool DicomDir::AddImageToEnd(DicomDirImage *dd)
896 if( Patients.size() > 0 )
898 ListDicomDirPatient::iterator itp = Patients.end();
901 DicomDirStudy *study = (*itp)->GetLastStudy();
904 DicomDirSerie *serie = study->GetLastSerie();
916 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
917 * @param path path of the root directory
918 * @param list chained list of Headers
920 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
925 std::string patPrevName = "", patPrevID = "";
926 std::string studPrevInstanceUID = "", studPrevID = "";
927 std::string serPrevInstanceUID = "", serPrevID = "";
929 std::string patCurName, patCurID;
930 std::string studCurInstanceUID, studCurID;
931 std::string serCurInstanceUID, serCurID;
934 for( VectDocument::const_iterator it = list.begin();
935 it != list.end(); ++it )
937 // get the current file characteristics
938 patCurName = (*it)->GetEntryValue(0x0010,0x0010);
939 patCurID = (*it)->GetEntryValue(0x0010,0x0011);
940 studCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000d);
941 studCurID = (*it)->GetEntryValue(0x0020,0x0010);
942 serCurInstanceUID = (*it)->GetEntryValue(0x0020,0x000e);
943 serCurID = (*it)->GetEntryValue(0x0020,0x0011);
945 if( patCurName != patPrevName || patCurID != patPrevID || first )
947 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
951 // if new Study Deal with 'STUDY' Elements
952 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
955 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
959 // if new Serie Deal with 'SERIE' Elements
960 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
963 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
967 // Always Deal with 'IMAGE' Elements
968 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
970 patPrevName = patCurName;
971 patPrevID = patCurID;
972 studPrevInstanceUID = studCurInstanceUID;
973 studPrevID = studCurID;
974 serPrevInstanceUID = serCurInstanceUID;
975 serPrevID = serCurID;
981 * \brief Move the content of the source SQItem to the destination SQItem
982 * Only DocEntry's are moved
983 * @param dst destination SQItem
984 * @param src source SQItem
986 void DicomDir::MoveSQItem(DocEntrySet *dst,DocEntrySet *src)
990 entry = src->GetFirstEntry();
993 src->RemoveEntryNoDestroy(entry);
994 dst->AddEntry(entry);
995 // we destroyed -> the current iterator is not longer valid
996 entry = src->GetFirstEntry();
1001 * \brief compares two files
1003 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1005 return *header1 < *header2;
1008 } // end namespace gdcm
1010 //-----------------------------------------------------------------------------