1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/01/17 10:59:52 $
7 Version: $Revision: 1.103 $
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
61 * \brief Constructor : creates an empty DicomDir
66 Initialize(); // sets all private fields to NULL
67 MetaElems = NewMeta();
71 * \brief Constructor Parses recursively the directory and creates the DicomDir
72 * or uses an already built DICOMDIR, depending on 'parseDir' value.
73 * @param fileName name
74 * - of the root directory (parseDir = true)
75 * - of the DICOMDIR (parseDir = false)
76 * @param parseDir boolean
77 * - true if user passed an entry point
78 * and wants to explore recursively the directories
79 * - false if user passed an already built DICOMDIR file
82 DicomDir::DicomDir(std::string const &fileName, bool parseDir ):
85 // At this step, Document constructor is already executed,
86 // whatever user passed (a root directory or a DICOMDIR)
87 // and whatever the value of parseDir was.
88 // (nothing is cheked in Document constructor, to avoid overhead)
90 Initialize(); // sets all private fields to NULL
92 // if user passed a root directory, sure we didn't get anything
93 if ( TagHT.begin() == TagHT.end() ) // 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
111 MetaElems = NewMeta();
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
166 void DicomDir::Print(std::ostream &os, std::string const & )
170 MetaElems->SetPrintLevel(PrintLevel);
171 MetaElems->Print(os);
173 for(ListDicomDirPatient::iterator cc = Patients.begin();
174 cc != Patients.end();
177 (*cc)->SetPrintLevel(PrintLevel);
182 //-----------------------------------------------------------------------------
185 * \brief This predicate, based on hopefully reasonable heuristics,
186 * decides whether or not the current header was properly parsed
187 * and contains the mandatory information for being considered as
188 * a well formed and usable DicomDir.
189 * @return true when Document is the one of a reasonable DicomDir,
192 bool DicomDir::IsReadable()
194 if( Filetype == Unknown)
196 gdcmVerboseMacro( "Wrong filetype");
201 gdcmVerboseMacro( "Meta Elements missing in DicomDir");
204 if( Patients.size() <= 0 )
206 gdcmVerboseMacro( "NO Patient in DicomDir");
214 * \brief Sets all fields to NULL
217 void DicomDir::Initialize()
220 ProgressMethod = NULL;
222 StartMethodArgDelete = NULL;
223 ProgressMethodArgDelete = NULL;
224 EndMethodArgDelete = NULL;
238 * \brief fills the whole structure, starting from a root Directory
240 void DicomDir::ParseDirectory()
242 CreateDicomDirChainedList( GetFileName() );
248 * \brief Set the start method to call when the parsing of the
250 * @param method Method to call
251 * @param arg Argument to pass to the method
252 * @param argDelete Argument
253 * \warning In python : the arg parameter isn't considered
255 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
256 DicomDir::Method *argDelete )
258 if( StartArg && StartMethodArgDelete )
260 StartMethodArgDelete( StartArg );
263 StartMethod = method;
265 StartMethodArgDelete = argDelete;
270 * \brief Set the method to delete the argument
271 * The argument is destroyed when the method is changed or when the
273 * @param method Method to call to delete the argument
275 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
277 StartMethodArgDelete = method;
282 * \brief Set the progress method to call when the parsing of the
284 * @param method Method to call
285 * @param arg Argument to pass to the method
286 * @param argDelete Argument
287 * \warning In python : the arg parameter isn't considered
289 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
290 DicomDir::Method *argDelete )
292 if( ProgressArg && ProgressMethodArgDelete )
294 ProgressMethodArgDelete( ProgressArg );
297 ProgressMethod = method;
299 ProgressMethodArgDelete = argDelete;
304 * \brief Set the method to delete the argument
305 * The argument is destroyed when the method is changed or when the
307 * @param method Method to call to delete the argument
309 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
311 ProgressMethodArgDelete = method;
316 * \brief Set the end method to call when the parsing of the directory ends
317 * @param method Method to call
318 * @param arg Argument to pass to the method
319 * @param argDelete Argument
320 * \warning In python : the arg parameter isn't considered
322 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
323 DicomDir::Method *argDelete )
325 if( EndArg && EndMethodArgDelete )
327 EndMethodArgDelete( EndArg );
332 EndMethodArgDelete = argDelete;
337 * \brief Set the method to delete the argument
338 * The argument is destroyed when the method is changed or when
339 * the class is destroyed
340 * @param method Method to call to delete the argument
342 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
344 EndMethodArgDelete = method;
349 * \brief writes on disc a DICOMDIR
350 * \ warning does NOT add the missing elements in the header :
351 * it's up to the user doing it !
352 * \todo : to be re-written using the DICOMDIR tree-like structure
353 * *not* the chained list
354 * (does NOT exist if the DICOMDIR is user-forged !)
355 * @param fileName file to be written to
356 * @return false only when fail to open
359 bool DicomDir::WriteDicomDir(std::string const &fileName)
362 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
363 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
365 std::ofstream *fp = new std::ofstream(fileName.c_str(),
366 std::ios::out | std::ios::binary);
369 gdcmVerboseMacro("Failed to open(write) File: " << fileName.c_str());
373 char filePreamble[128];
374 memset(filePreamble, 0, 128);
375 fp->write(filePreamble, 128); //FIXME
376 binary_write( *fp, "DICM");
378 DicomDirMeta *ptrMeta = GetDicomDirMeta();
379 ptrMeta->WriteContent(fp, ExplicitVR);
381 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
384 binary_write(*fp, sq[i]);
387 for(ListDicomDirPatient::iterator cc = Patients.begin();
388 cc != Patients.end();
391 (*cc)->WriteContent( fp, ExplicitVR );
394 // force writing Sequence Delimitation Item
397 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
406 //-----------------------------------------------------------------------------
411 * \brief create a Document-like chained list from a root Directory
412 * @param path entry point of the tree-like structure
414 void DicomDir::CreateDicomDirChainedList(std::string const & path)
417 DirList dirList(path,1); // gets recursively the file list
418 unsigned int count = 0;
422 DirListType fileList = dirList.GetFilenames();
424 for( DirListType::iterator it = fileList.begin();
425 it != fileList.end();
428 Progress = (float)(count+1)/(float)fileList.size();
429 CallProgressMethod();
435 header = new Header( it->c_str() );
438 gdcmVerboseMacro( "Failure in new Header " << it->c_str() );
442 if( header->IsReadable() )
444 // Add the file header to the chained list:
445 list.push_back(header);
446 gdcmVerboseMacro( "Readable " << it->c_str() );
454 // sorts Patient/Study/Serie/
455 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
457 std::string tmp = dirList.GetDirName();
458 //for each Header of the chained list, add/update the Patient/Study/Serie/Image info
459 SetElements(tmp, list);
462 for(VectDocument::iterator itDoc=list.begin();
466 delete dynamic_cast<Header *>(*itDoc);
472 * \brief adds *the* Meta to a partially created DICOMDIR
475 DicomDirMeta * DicomDir::NewMeta()
477 DicomDirMeta *m = new DicomDirMeta();
479 if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
481 TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
482 lastOneButSequence --;
483 // ALL the 'out of Sequence' Tags belong to Meta Elems
484 // (we skip 0004|1220 [Directory record sequence] )
485 for ( TagDocEntryHT::iterator cc = TagHT.begin();
486 cc != lastOneButSequence;
489 m->AddEntry( cc->second );
492 else // after root directory parsing
494 ListDicomDirMetaElem const &elemList =
495 Global::GetDicomDirElements()->GetDicomDirMetaElements();
496 m->FillObject(elemList);
498 m->SetSQItemNumber(0); // To avoid further missprinting
503 * \brief adds a new Patient (with the basic elements) to a partially created DICOMDIR
505 DicomDirPatient *DicomDir::NewPatient()
507 ListDicomDirPatientElem::const_iterator it;
508 uint16_t tmpGr,tmpEl;
509 DictEntry *dictEntry;
512 ListDicomDirPatientElem const & elemList =
513 Global::GetDicomDirElements()->GetDicomDirPatientElements();
514 DicomDirPatient *p = new DicomDirPatient();
516 // for all the DicomDirPatient Elements
517 for( it = elemList.begin(); it != elemList.end(); ++it )
521 dictEntry = GetPubDict()->GetDictEntry(tmpGr, tmpEl);
522 entry = new ValEntry( dictEntry );
523 entry->SetOffset(0); // just to avoid further missprinting
524 entry->SetValue( it->Value );
526 p->AddEntry( entry );
529 Patients.push_front( p );
535 * \brief adds to the HTable
536 * the Entries (Dicom Elements) corresponding to the given type
537 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
538 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
539 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
540 * @param header Header of the current file
542 void DicomDir::SetElement(std::string const &path, DicomDirType type,
545 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
546 ListDicomDirElem::const_iterator it;
547 uint16_t tmpGr, tmpEl;
548 DictEntry *dictEntry;
555 case GDCM_DICOMDIR_IMAGE:
556 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
557 si = new DicomDirImage();
558 if( !AddDicomDirImageToEnd(static_cast<DicomDirImage *>(si)) )
560 gdcmVerboseMacro( "Add DicomDirImageToEnd failed");
563 case GDCM_DICOMDIR_SERIE:
564 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
565 si = new DicomDirSerie();
566 if( !AddDicomDirSerieToEnd(static_cast<DicomDirSerie *>(si)) )
568 gdcmVerboseMacro( "Add DicomDirSerieToEnd failed");
571 case GDCM_DICOMDIR_STUDY:
572 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
573 si = new DicomDirStudy();
574 if( !AddDicomDirStudyToEnd(static_cast<DicomDirStudy *>(si)) )
576 gdcmVerboseMacro( "Add DicomDirStudyToEnd failed");
579 case GDCM_DICOMDIR_PATIENT:
580 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
581 si = new DicomDirPatient();
582 if( !AddDicomDirPatientToEnd(static_cast<DicomDirPatient *>(si)) )
584 gdcmVerboseMacro( "Add DicomDirPatientToEnd failed");
587 case GDCM_DICOMDIR_META:
588 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
589 si = new DicomDirMeta();
592 gdcmVerboseMacro( "MetaElements already exist, they will be destroyed");
595 MetaElems = static_cast<DicomDirMeta *>(si);
600 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
601 // to avoid further troubles
602 // imageElem 0008 1140 "" // Referenced Image Sequence
603 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
604 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
605 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
606 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
607 // for all the relevant elements found in their own spot of the DicomDir.dic
608 // FIXME : troubles found when it's a SeqEntry
610 for( it = elemList.begin(); it != elemList.end(); ++it)
614 dictEntry = GetPubDict()->GetDictEntry(tmpGr, tmpEl);
616 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
618 entry->SetOffset(0); // just to avoid further missprinting
622 // NULL when we Build Up (ex nihilo) a DICOMDIR
623 // or when we add the META elems
624 val = header->GetEntry(tmpGr, tmpEl);
631 if( val == GDCM_UNFOUND)
633 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
635 // force to the *end* File Name
636 val = Util::GetName( path );
638 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
640 if( header->GetFileName().substr(0, path.length()) != path )
642 gdcmVerboseMacro( "The base path of file name is incorrect");
643 val = header->GetFileName();
647 val = &(header->GetFileName().c_str()[path.length()]);
657 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
661 entry->SetValue( val ); // troubles expected when vr=SQ ...
663 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
665 std::cout << "GDCM_DICOMDIR_META ?!? should never print that"
672 //-----------------------------------------------------------------------------
674 * \brief CallStartMethod
676 void DicomDir::CallStartMethod()
682 StartMethod( StartArg );
686 //-----------------------------------------------------------------------------
689 * \brief CallProgressMethod
691 void DicomDir::CallProgressMethod()
695 ProgressMethod( ProgressArg );
699 //-----------------------------------------------------------------------------
702 * \brief CallEndMethod
704 void DicomDir::CallEndMethod()
713 //-----------------------------------------------------------------------------
717 * \brief create a 'DicomDir' from a DICOMDIR Header
719 void DicomDir::CreateDicomDir()
721 // The list is parsed.
722 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
723 // 1 - we save the beginning iterator
724 // 2 - we continue to parse
725 // 3 - we find an other tag
726 // + we create the object for the precedent tag
729 // Directory record sequence
730 DocEntry *e = GetDocEntry(0x0004, 0x1220);
733 gdcmVerboseMacro( "NO Directory record sequence (0x0004,0x1220)");
734 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
738 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
741 gdcmVerboseMacro( "No SeqEntry present");
742 // useless : (0x0004,0x1220) IS a Sequence !
746 MetaElems = NewMeta();
748 ListSQItem listItems = s->GetSQItems();
753 for( ListSQItem::iterator i = listItems.begin();
754 i !=listItems.end(); ++i )
756 d = (*i)->GetDocEntry(0x0004, 0x1430); // Directory Record Type
757 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
759 v = valEntry->GetValue();
763 gdcmVerboseMacro( "Not a ValEntry.");
767 if( v == "PATIENT " )
769 si = new DicomDirPatient();
770 AddDicomDirPatientToEnd( static_cast<DicomDirPatient *>(si) );
772 else if( v == "STUDY " )
774 si = new DicomDirStudy();
775 AddDicomDirStudyToEnd( static_cast<DicomDirStudy *>(si) );
777 else if( v == "SERIES" )
779 si = new DicomDirSerie();
780 AddDicomDirSerieToEnd( static_cast<DicomDirSerie *>(si) );
782 else if( v == "IMAGE " )
784 si = new DicomDirImage();
785 AddDicomDirImageToEnd( static_cast<DicomDirImage *>(si) );
789 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
790 // neither an 'IMAGE' SQItem. Skip to next item.
800 * \brief Well ... there is only one occurence
802 bool DicomDir::AddDicomDirMeta()
808 MetaElems = new DicomDirMeta();
814 * \brief AddDicomDirPatientToEnd
815 * @param dd SQ Item to enqueue to the DicomPatient chained List
817 bool DicomDir::AddDicomDirPatientToEnd(DicomDirPatient *dd)
819 Patients.push_back(dd);
825 * \brief AddDicomDirStudyToEnd
826 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
828 bool DicomDir::AddDicomDirStudyToEnd(DicomDirStudy *dd)
830 if( Patients.size() > 0 )
832 ListDicomDirPatient::iterator itp = Patients.end();
834 (*itp)->AddDicomDirStudy(dd);
842 * \brief AddDicomDirSerieToEnd
843 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
845 bool DicomDir::AddDicomDirSerieToEnd(DicomDirSerie *dd)
847 if( Patients.size() > 0 )
849 ListDicomDirPatient::iterator itp = Patients.end();
852 if( (*itp)->GetDicomDirStudies().size() > 0 )
854 ListDicomDirStudy::const_iterator itst =
855 (*itp)->GetDicomDirStudies().end();
857 (*itst)->AddDicomDirSerie(dd);
866 * \brief AddDicomDirImageToEnd
867 * @param dd SQ Item to enqueue to the DicomDirImage chained List
869 bool DicomDir::AddDicomDirImageToEnd(DicomDirImage *dd)
871 if( Patients.size() > 0 )
873 ListDicomDirPatient::iterator itp = Patients.end();
876 if( (*itp)->GetDicomDirStudies().size() > 0 )
878 ListDicomDirStudy::const_iterator itst =
879 (*itp)->GetDicomDirStudies().end();
882 if( (*itst)->GetDicomDirSeries().size() > 0 )
884 ListDicomDirSerie::const_iterator its = (*itst)->GetDicomDirSeries().end();
886 (*its)->AddDicomDirImage(dd);
896 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
897 * @param path path of the root directory
898 * @param list chained list of Headers
900 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
905 std::string patPrevName = "", patPrevID = "";
906 std::string studPrevInstanceUID = "", studPrevID = "";
907 std::string serPrevInstanceUID = "", serPrevID = "";
909 std::string patCurName, patCurID;
910 std::string studCurInstanceUID, studCurID;
911 std::string serCurInstanceUID, serCurID;
914 for( VectDocument::const_iterator it = list.begin();
915 it != list.end(); ++it )
917 // get the current file characteristics
918 patCurName = (*it)->GetEntry(0x0010,0x0010);
919 patCurID = (*it)->GetEntry(0x0010,0x0011);
920 studCurInstanceUID = (*it)->GetEntry(0x0020,0x000d);
921 studCurID = (*it)->GetEntry(0x0020,0x0010);
922 serCurInstanceUID = (*it)->GetEntry(0x0020,0x000e);
923 serCurID = (*it)->GetEntry(0x0020,0x0011);
925 if( patCurName != patPrevName || patCurID != patPrevID || first )
927 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
931 // if new Study Deal with 'STUDY' Elements
932 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
935 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
939 // if new Serie Deal with 'SERIE' Elements
940 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
943 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
947 // Always Deal with 'IMAGE' Elements
948 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
950 patPrevName = patCurName;
951 patPrevID = patCurID;
952 studPrevInstanceUID = studCurInstanceUID;
953 studPrevID = studCurID;
954 serPrevInstanceUID = serCurInstanceUID;
955 serPrevID = serCurID;
962 * \brief Move the content of the src SQItem to the dst SQItem
963 * Only DocEntry's are moved
966 void DicomDir::MoveSQItem(SQItem *dst,SQItem *src)
971 entry = src->GetNextEntry();
974 src->RemoveEntryNoDestroy(entry);
975 dst->AddEntry(entry);
978 entry = src->GetNextEntry();
984 * \brief compares two dgcmHeaders
986 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
988 return *header1 < *header2;
992 * \brief Initialise the visit of the DicomDirPatients of the DicomDir
994 void DicomDir::InitTraversal()
996 ItDicomDirPatient = Patients.begin();
1000 * \brief Get the next entry while visiting the DicomDirPatients
1001 * \return The next DicomDirPatient if found, otherwhise NULL
1003 DicomDirPatient *DicomDir::GetNextEntry()
1005 if (ItDicomDirPatient != Patients.end())
1007 DicomDirPatient *tmp = *ItDicomDirPatient;
1008 ++ItDicomDirPatient;
1018 } // end namespace gdcm
1020 //-----------------------------------------------------------------------------