1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/01/18 11:39:59 $
7 Version: $Revision: 1.105 $
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"
30 #include "gdcmHeader.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
66 MetaElems = NewMeta();
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
92 if ( TagHT.begin() == TagHT.end() ) // 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
110 MetaElems = NewMeta();
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);
148 for(ListDicomDirPatient::iterator cc = Patients.begin();
160 //-----------------------------------------------------------------------------
163 * \brief Canonical Printer
165 void DicomDir::Print(std::ostream &os, std::string const & )
169 MetaElems->SetPrintLevel(PrintLevel);
170 MetaElems->Print(os);
172 for(ListDicomDirPatient::iterator cc = Patients.begin();
173 cc != Patients.end();
176 (*cc)->SetPrintLevel(PrintLevel);
181 //-----------------------------------------------------------------------------
184 * \brief This predicate, based on hopefully reasonable heuristics,
185 * decides whether or not the current header was properly parsed
186 * and contains the mandatory information for being considered as
187 * a well formed and usable DicomDir.
188 * @return true when Document is the one of a reasonable DicomDir,
191 bool DicomDir::IsReadable()
193 if( Filetype == Unknown)
195 gdcmVerboseMacro( "Wrong filetype");
200 gdcmVerboseMacro( "Meta Elements missing in DicomDir");
203 if( Patients.size() <= 0 )
205 gdcmVerboseMacro( "NO Patient in DicomDir");
213 * \brief Sets all fields to NULL
216 void DicomDir::Initialize()
219 ProgressMethod = NULL;
221 StartMethodArgDelete = NULL;
222 ProgressMethodArgDelete = NULL;
223 EndMethodArgDelete = NULL;
236 * \brief fills the whole structure, starting from a root Directory
238 void DicomDir::ParseDirectory()
240 CreateDicomDirChainedList( GetFileName() );
245 * \brief Set the start method to call when the parsing of the
247 * @param method Method to call
248 * @param arg Argument to pass to the method
249 * @param argDelete Argument
250 * \warning In python : the arg parameter isn't considered
252 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
253 DicomDir::Method *argDelete )
255 if( StartArg && StartMethodArgDelete )
257 StartMethodArgDelete( StartArg );
260 StartMethod = method;
262 StartMethodArgDelete = argDelete;
266 * \brief Set the method to delete the argument
267 * The argument is destroyed when the method is changed or when the
269 * @param method Method to call to delete the argument
271 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
273 StartMethodArgDelete = method;
277 * \brief Set the progress method to call when the parsing of the
279 * @param method Method to call
280 * @param arg Argument to pass to the method
281 * @param argDelete Argument
282 * \warning In python : the arg parameter isn't considered
284 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
285 DicomDir::Method *argDelete )
287 if( ProgressArg && ProgressMethodArgDelete )
289 ProgressMethodArgDelete( ProgressArg );
292 ProgressMethod = method;
294 ProgressMethodArgDelete = argDelete;
298 * \brief Set the method to delete the argument
299 * The argument is destroyed when the method is changed or when the
301 * @param method Method to call to delete the argument
303 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
305 ProgressMethodArgDelete = method;
309 * \brief Set the end method to call when the parsing of the directory ends
310 * @param method Method to call
311 * @param arg Argument to pass to the method
312 * @param argDelete Argument
313 * \warning In python : the arg parameter isn't considered
315 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
316 DicomDir::Method *argDelete )
318 if( EndArg && EndMethodArgDelete )
320 EndMethodArgDelete( EndArg );
325 EndMethodArgDelete = argDelete;
329 * \brief Set the method to delete the argument
330 * The argument is destroyed when the method is changed or when
331 * the class is destroyed
332 * @param method Method to call to delete the argument
334 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
336 EndMethodArgDelete = method;
340 * \brief writes on disc a DICOMDIR
341 * \ warning does NOT add the missing elements in the header :
342 * it's up to the user doing it !
343 * \todo : to be re-written using the DICOMDIR tree-like structure
344 * *not* the chained list
345 * (does NOT exist if the DICOMDIR is user-forged !)
346 * @param fileName file to be written to
347 * @return false only when fail to open
350 bool DicomDir::WriteDicomDir(std::string const &fileName)
353 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
354 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
356 std::ofstream *fp = new std::ofstream(fileName.c_str(),
357 std::ios::out | std::ios::binary);
360 gdcmVerboseMacro("Failed to open(write) File: " << fileName.c_str());
364 char filePreamble[128];
365 memset(filePreamble, 0, 128);
366 fp->write(filePreamble, 128); //FIXME
367 binary_write( *fp, "DICM");
369 DicomDirMeta *ptrMeta = GetDicomDirMeta();
370 ptrMeta->WriteContent(fp, ExplicitVR);
372 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
375 binary_write(*fp, sq[i]);
378 for(ListDicomDirPatient::iterator cc = Patients.begin();
379 cc != Patients.end();
382 (*cc)->WriteContent( fp, ExplicitVR );
385 // force writing Sequence Delimitation Item
388 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
397 //-----------------------------------------------------------------------------
401 * \brief create a Document-like chained list from a root Directory
402 * @param path entry point of the tree-like structure
404 void DicomDir::CreateDicomDirChainedList(std::string const & path)
407 DirList dirList(path,1); // gets recursively the file list
408 unsigned int count = 0;
412 DirListType fileList = dirList.GetFilenames();
414 for( DirListType::iterator it = fileList.begin();
415 it != fileList.end();
418 Progress = (float)(count+1)/(float)fileList.size();
419 CallProgressMethod();
425 header = new Header( it->c_str() );
428 gdcmVerboseMacro( "Failure in new Header " << it->c_str() );
432 if( header->IsReadable() )
434 // Add the file header to the chained list:
435 list.push_back(header);
436 gdcmVerboseMacro( "Readable " << it->c_str() );
444 // sorts Patient/Study/Serie/
445 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
447 std::string tmp = dirList.GetDirName();
448 //for each Header of the chained list, add/update the Patient/Study/Serie/Image info
449 SetElements(tmp, list);
452 for(VectDocument::iterator itDoc=list.begin();
456 delete dynamic_cast<Header *>(*itDoc);
461 * \brief adds *the* Meta to a partially created DICOMDIR
464 DicomDirMeta * DicomDir::NewMeta()
466 DicomDirMeta *m = new DicomDirMeta();
468 if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
470 TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
471 lastOneButSequence --;
472 // ALL the 'out of Sequence' Tags belong to Meta Elems
473 // (we skip 0004|1220 [Directory record sequence] )
474 for ( TagDocEntryHT::iterator cc = TagHT.begin();
475 cc != lastOneButSequence;
478 m->AddEntry( cc->second );
481 else // after root directory parsing
483 ListDicomDirMetaElem const &elemList =
484 Global::GetDicomDirElements()->GetDicomDirMetaElements();
485 m->FillObject(elemList);
487 m->SetSQItemNumber(0); // To avoid further missprinting
492 * \brief adds a new Patient (with the basic elements) to a partially created DICOMDIR
494 DicomDirPatient *DicomDir::NewPatient()
496 ListDicomDirPatientElem::const_iterator it;
497 uint16_t tmpGr,tmpEl;
498 DictEntry *dictEntry;
501 ListDicomDirPatientElem const & elemList =
502 Global::GetDicomDirElements()->GetDicomDirPatientElements();
503 DicomDirPatient *p = new DicomDirPatient();
505 // for all the DicomDirPatient Elements
506 for( it = elemList.begin(); it != elemList.end(); ++it )
510 dictEntry = GetPubDict()->GetDictEntry(tmpGr, tmpEl);
511 entry = new ValEntry( dictEntry );
512 entry->SetOffset(0); // just to avoid further missprinting
513 entry->SetValue( it->Value );
515 p->AddEntry( entry );
518 Patients.push_front( p );
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();
547 if( !AddDicomDirImageToEnd(static_cast<DicomDirImage *>(si)) )
549 gdcmVerboseMacro( "Add DicomDirImageToEnd failed");
552 case GDCM_DICOMDIR_SERIE:
553 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
554 si = new DicomDirSerie();
555 if( !AddDicomDirSerieToEnd(static_cast<DicomDirSerie *>(si)) )
557 gdcmVerboseMacro( "Add DicomDirSerieToEnd failed");
560 case GDCM_DICOMDIR_STUDY:
561 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
562 si = new DicomDirStudy();
563 if( !AddDicomDirStudyToEnd(static_cast<DicomDirStudy *>(si)) )
565 gdcmVerboseMacro( "Add DicomDirStudyToEnd failed");
568 case GDCM_DICOMDIR_PATIENT:
569 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
570 si = new DicomDirPatient();
571 if( !AddDicomDirPatientToEnd(static_cast<DicomDirPatient *>(si)) )
573 gdcmVerboseMacro( "Add DicomDirPatientToEnd failed");
576 case GDCM_DICOMDIR_META:
577 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
578 si = new DicomDirMeta();
581 gdcmVerboseMacro( "MetaElements already exist, they will be destroyed");
584 MetaElems = static_cast<DicomDirMeta *>(si);
589 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
590 // to avoid further troubles
591 // imageElem 0008 1140 "" // Referenced Image Sequence
592 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
593 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
594 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
595 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
596 // for all the relevant elements found in their own spot of the DicomDir.dic
597 // FIXME : troubles found when it's a SeqEntry
599 for( it = elemList.begin(); it != elemList.end(); ++it)
603 dictEntry = GetPubDict()->GetDictEntry(tmpGr, tmpEl);
605 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
607 entry->SetOffset(0); // just to avoid further missprinting
611 // NULL when we Build Up (ex nihilo) a DICOMDIR
612 // or when we add the META elems
613 val = header->GetEntry(tmpGr, tmpEl);
620 if( val == GDCM_UNFOUND)
622 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
624 // force to the *end* File Name
625 val = Util::GetName( path );
627 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
629 if( header->GetFileName().substr(0, path.length()) != path )
631 gdcmVerboseMacro( "The base path of file name is incorrect");
632 val = header->GetFileName();
636 val = &(header->GetFileName().c_str()[path.length()]);
646 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
650 entry->SetValue( val ); // troubles expected when vr=SQ ...
652 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
654 std::cout << "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 create a 'DicomDir' from a DICOMDIR Header
705 void DicomDir::CreateDicomDir()
707 // The list is parsed.
708 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
709 // 1 - we save the beginning iterator
710 // 2 - we continue to parse
711 // 3 - we find an other tag
712 // + we create the object for the precedent tag
715 // Directory record sequence
716 DocEntry *e = GetDocEntry(0x0004, 0x1220);
719 gdcmVerboseMacro( "NO Directory record sequence (0x0004,0x1220)");
720 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
724 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
727 gdcmVerboseMacro( "No SeqEntry present");
728 // useless : (0x0004,0x1220) IS a Sequence !
732 MetaElems = NewMeta();
734 ListSQItem listItems = s->GetSQItems();
739 for( ListSQItem::iterator i = listItems.begin();
740 i !=listItems.end(); ++i )
742 d = (*i)->GetDocEntry(0x0004, 0x1430); // Directory Record Type
743 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
745 v = valEntry->GetValue();
749 gdcmVerboseMacro( "Not a ValEntry.");
753 if( v == "PATIENT " )
755 si = new DicomDirPatient();
756 AddDicomDirPatientToEnd( static_cast<DicomDirPatient *>(si) );
758 else if( v == "STUDY " )
760 si = new DicomDirStudy();
761 AddDicomDirStudyToEnd( static_cast<DicomDirStudy *>(si) );
763 else if( v == "SERIES" )
765 si = new DicomDirSerie();
766 AddDicomDirSerieToEnd( static_cast<DicomDirSerie *>(si) );
768 else if( v == "IMAGE " )
770 si = new DicomDirImage();
771 AddDicomDirImageToEnd( static_cast<DicomDirImage *>(si) );
775 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
776 // neither an 'IMAGE' SQItem. Skip to next item.
785 * \brief Well ... there is only one occurence
787 bool DicomDir::AddDicomDirMeta()
793 MetaElems = new DicomDirMeta();
798 * \brief AddDicomDirPatientToEnd
799 * @param dd SQ Item to enqueue to the DicomPatient chained List
801 bool DicomDir::AddDicomDirPatientToEnd(DicomDirPatient *dd)
803 Patients.push_back(dd);
808 * \brief AddDicomDirStudyToEnd
809 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
811 bool DicomDir::AddDicomDirStudyToEnd(DicomDirStudy *dd)
813 if( Patients.size() > 0 )
815 ListDicomDirPatient::iterator itp = Patients.end();
817 (*itp)->AddDicomDirStudy(dd);
824 * \brief AddDicomDirSerieToEnd
825 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
827 bool DicomDir::AddDicomDirSerieToEnd(DicomDirSerie *dd)
829 if( Patients.size() > 0 )
831 ListDicomDirPatient::iterator itp = Patients.end();
834 if( (*itp)->GetDicomDirStudies().size() > 0 )
836 ListDicomDirStudy::const_iterator itst =
837 (*itp)->GetDicomDirStudies().end();
839 (*itst)->AddDicomDirSerie(dd);
847 * \brief AddDicomDirImageToEnd
848 * @param dd SQ Item to enqueue to the DicomDirImage chained List
850 bool DicomDir::AddDicomDirImageToEnd(DicomDirImage *dd)
852 if( Patients.size() > 0 )
854 ListDicomDirPatient::iterator itp = Patients.end();
857 if( (*itp)->GetDicomDirStudies().size() > 0 )
859 ListDicomDirStudy::const_iterator itst =
860 (*itp)->GetDicomDirStudies().end();
863 if( (*itst)->GetDicomDirSeries().size() > 0 )
865 ListDicomDirSerie::const_iterator its = (*itst)->GetDicomDirSeries().end();
867 (*its)->AddDicomDirImage(dd);
876 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
877 * @param path path of the root directory
878 * @param list chained list of Headers
880 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
885 std::string patPrevName = "", patPrevID = "";
886 std::string studPrevInstanceUID = "", studPrevID = "";
887 std::string serPrevInstanceUID = "", serPrevID = "";
889 std::string patCurName, patCurID;
890 std::string studCurInstanceUID, studCurID;
891 std::string serCurInstanceUID, serCurID;
894 for( VectDocument::const_iterator it = list.begin();
895 it != list.end(); ++it )
897 // get the current file characteristics
898 patCurName = (*it)->GetEntry(0x0010,0x0010);
899 patCurID = (*it)->GetEntry(0x0010,0x0011);
900 studCurInstanceUID = (*it)->GetEntry(0x0020,0x000d);
901 studCurID = (*it)->GetEntry(0x0020,0x0010);
902 serCurInstanceUID = (*it)->GetEntry(0x0020,0x000e);
903 serCurID = (*it)->GetEntry(0x0020,0x0011);
905 if( patCurName != patPrevName || patCurID != patPrevID || first )
907 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
911 // if new Study Deal with 'STUDY' Elements
912 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
915 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
919 // if new Serie Deal with 'SERIE' Elements
920 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
923 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
927 // Always Deal with 'IMAGE' Elements
928 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
930 patPrevName = patCurName;
931 patPrevID = patCurID;
932 studPrevInstanceUID = studCurInstanceUID;
933 studPrevID = studCurID;
934 serPrevInstanceUID = serCurInstanceUID;
935 serPrevID = serCurID;
941 * \brief Move the content of the src SQItem to the dst SQItem
942 * Only DocEntry's are moved
945 void DicomDir::MoveSQItem(SQItem *dst,SQItem *src)
950 entry = src->GetNextEntry();
953 src->RemoveEntryNoDestroy(entry);
954 dst->AddEntry(entry);
957 entry = src->GetNextEntry();
962 * \brief compares two dgcmHeaders
964 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
966 return *header1 < *header2;
971 * \brief Get the first entry while visiting the DicomDirPatients
972 * \return The next DicomDirPatient if found, otherwhise NULL
974 DicomDirPatient *DicomDir::GetFirstEntry()
976 ItDicomDirPatient = Patients.begin();
977 if ( ItDicomDirPatient != Patients.end() )
978 return *ItDicomDirPatient;
983 * \brief Get the next entry while visiting the DicomDirPatients
984 * \note : meaningfull only if GetFirstEntry already called
985 * \return The next DicomDirPatient if found, otherwhise NULL
987 DicomDirPatient *DicomDir::GetNextEntry()
989 gdcmAssertMacro (ItDicomDirPatient != Patients.end());
992 if ( ItDicomDirPatient != Patients.end() )
993 return *ItDicomDirPatient;
999 } // end namespace gdcm
1001 //-----------------------------------------------------------------------------