1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/01/13 12:19:58 $
7 Version: $Revision: 1.100 $
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)
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 fileList(path,1); // gets recursively the file list
418 unsigned int count = 0;
422 for( DirList::iterator it = fileList.begin();
423 it != fileList.end();
426 Progress = (float)(count+1)/(float)fileList.size();
427 CallProgressMethod();
433 header = new Header( it->c_str() );
436 gdcmVerboseMacro( "Failure in new Header " << it->c_str() );
440 if( header->IsReadable() )
442 // Add the file header 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 = fileList.GetDirName();
456 //for each Header 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<Header *>(*itDoc);
470 * \brief adds *the* Meta to a partially created DICOMDIR
473 DicomDirMeta * DicomDir::NewMeta()
475 DicomDirMeta *m = new DicomDirMeta();
477 if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
479 TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
480 lastOneButSequence --;
481 // ALL the 'out of Sequence' Tags belong to Meta Elems
482 // (we skip 0004|1220 [Directory record sequence] )
483 for ( TagDocEntryHT::iterator cc = TagHT.begin();
484 cc != lastOneButSequence;
487 m->AddEntry( cc->second );
490 else // after root directory parsing
492 ListDicomDirMetaElem const &elemList =
493 Global::GetDicomDirElements()->GetDicomDirMetaElements();
494 m->FillObject(elemList);
496 m->SetSQItemNumber(0); // To avoid further missprinting
501 * \brief adds a new Patient (with the basic elements) to a partially created DICOMDIR
503 DicomDirPatient *DicomDir::NewPatient()
505 ListDicomDirPatientElem::const_iterator it;
506 uint16_t tmpGr,tmpEl;
507 DictEntry *dictEntry;
510 ListDicomDirPatientElem const & elemList =
511 Global::GetDicomDirElements()->GetDicomDirPatientElements();
512 DicomDirPatient *p = new DicomDirPatient();
514 // for all the DicomDirPatient Elements
515 for( it = elemList.begin(); it != elemList.end(); ++it )
519 dictEntry = GetPubDict()->GetDictEntry(tmpGr, tmpEl);
520 entry = new ValEntry( dictEntry );
521 entry->SetOffset(0); // just to avoid further missprinting
522 entry->SetValue( it->Value );
524 p->AddEntry( entry );
527 Patients.push_front( p );
533 * \brief adds to the HTable
534 * the Entries (Dicom Elements) corresponding to the given type
535 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
536 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
537 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
538 * @param header Header of the current file
540 void DicomDir::SetElement(std::string const &path, DicomDirType type,
543 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
544 ListDicomDirElem::const_iterator it;
545 uint16_t tmpGr, tmpEl;
546 DictEntry *dictEntry;
553 case GDCM_DICOMDIR_IMAGE:
554 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
555 si = new DicomDirImage();
556 if( !AddDicomDirImageToEnd(static_cast<DicomDirImage *>(si)) )
558 gdcmVerboseMacro( "Add DicomDirImageToEnd failed");
561 case GDCM_DICOMDIR_SERIE:
562 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
563 si = new DicomDirSerie();
564 if( !AddDicomDirSerieToEnd(static_cast<DicomDirSerie *>(si)) )
566 gdcmVerboseMacro( "Add DicomDirSerieToEnd failed");
569 case GDCM_DICOMDIR_STUDY:
570 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
571 si = new DicomDirStudy();
572 if( !AddDicomDirStudyToEnd(static_cast<DicomDirStudy *>(si)) )
574 gdcmVerboseMacro( "Add DicomDirStudyToEnd failed");
577 case GDCM_DICOMDIR_PATIENT:
578 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
579 si = new DicomDirPatient();
580 if( !AddDicomDirPatientToEnd(static_cast<DicomDirPatient *>(si)) )
582 gdcmVerboseMacro( "Add DicomDirPatientToEnd failed");
585 case GDCM_DICOMDIR_META:
586 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
587 si = new DicomDirMeta();
590 gdcmVerboseMacro( "MetaElements already exist, they will be destroyed");
593 MetaElems = static_cast<DicomDirMeta *>(si);
598 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
599 // to avoid further troubles
600 // imageElem 0008 1140 "" // Referenced Image Sequence
601 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
602 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
603 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
604 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
605 // for all the relevant elements found in their own spot of the DicomDir.dic
606 // FIXME : troubles found when it's a SeqEntry
608 for( it = elemList.begin(); it != elemList.end(); ++it)
612 dictEntry = GetPubDict()->GetDictEntry(tmpGr, tmpEl);
614 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
616 entry->SetOffset(0); // just to avoid further missprinting
620 // NULL when we Build Up (ex nihilo) a DICOMDIR
621 // or when we add the META elems
622 val = header->GetEntry(tmpGr, tmpEl);
629 if( val == GDCM_UNFOUND)
631 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
633 // force to the *end* File Name
634 val = Util::GetName( path );
636 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
638 if( header->GetFileName().substr(0, path.length()) != path )
640 gdcmVerboseMacro( "The base path of file name is incorrect");
641 val = header->GetFileName();
645 val = &(header->GetFileName().c_str()[path.length()]);
655 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
659 entry->SetValue( val ); // troubles expected when vr=SQ ...
661 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
663 std::cout << "GDCM_DICOMDIR_META ?!? should never print that"
670 //-----------------------------------------------------------------------------
672 * \brief CallStartMethod
674 void DicomDir::CallStartMethod()
680 StartMethod( StartArg );
684 //-----------------------------------------------------------------------------
687 * \brief CallProgressMethod
689 void DicomDir::CallProgressMethod()
693 ProgressMethod( ProgressArg );
697 //-----------------------------------------------------------------------------
700 * \brief CallEndMethod
702 void DicomDir::CallEndMethod()
711 //-----------------------------------------------------------------------------
715 * \brief create a 'DicomDir' from a DICOMDIR Header
717 void DicomDir::CreateDicomDir()
719 // The list is parsed.
720 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
721 // 1 - we save the beginning iterator
722 // 2 - we continue to parse
723 // 3 - we find an other tag
724 // + we create the object for the precedent tag
727 // Directory record sequence
728 DocEntry *e = GetDocEntry(0x0004, 0x1220);
731 gdcmVerboseMacro( "NO Directory record sequence (0x0004,0x1220)");
732 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
736 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
739 gdcmVerboseMacro( "No SeqEntry present");
740 // useless : (0x0004,0x1220) IS a Sequence !
744 MetaElems = NewMeta();
746 ListSQItem listItems = s->GetSQItems();
751 for( ListSQItem::iterator i = listItems.begin();
752 i !=listItems.end(); ++i )
754 d = (*i)->GetDocEntry(0x0004, 0x1430); // Directory Record Type
755 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
757 v = valEntry->GetValue();
761 gdcmVerboseMacro( "Not a ValEntry.");
765 if( v == "PATIENT " )
767 si = new DicomDirPatient();
768 AddDicomDirPatientToEnd( static_cast<DicomDirPatient *>(si) );
770 else if( v == "STUDY " )
772 si = new DicomDirStudy();
773 AddDicomDirStudyToEnd( static_cast<DicomDirStudy *>(si) );
775 else if( v == "SERIES" )
777 si = new DicomDirSerie();
778 AddDicomDirSerieToEnd( static_cast<DicomDirSerie *>(si) );
780 else if( v == "IMAGE " )
782 si = new DicomDirImage();
783 AddDicomDirImageToEnd( static_cast<DicomDirImage *>(si) );
787 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
788 // neither an 'IMAGE' SQItem. Skip to next item.
798 * \brief Well ... there is only one occurence
800 bool DicomDir::AddDicomDirMeta()
806 MetaElems = new DicomDirMeta();
812 * \brief AddDicomDirPatientToEnd
813 * @param dd SQ Item to enqueue to the DicomPatient chained List
815 bool DicomDir::AddDicomDirPatientToEnd(DicomDirPatient *dd)
817 Patients.push_back(dd);
823 * \brief AddDicomDirStudyToEnd
824 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
826 bool DicomDir::AddDicomDirStudyToEnd(DicomDirStudy *dd)
828 if( Patients.size() > 0 )
830 ListDicomDirPatient::iterator itp = Patients.end();
832 (*itp)->AddDicomDirStudy(dd);
840 * \brief AddDicomDirSerieToEnd
841 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
843 bool DicomDir::AddDicomDirSerieToEnd(DicomDirSerie *dd)
845 if( Patients.size() > 0 )
847 ListDicomDirPatient::iterator itp = Patients.end();
850 if( (*itp)->GetDicomDirStudies().size() > 0 )
852 ListDicomDirStudy::const_iterator itst =
853 (*itp)->GetDicomDirStudies().end();
855 (*itst)->AddDicomDirSerie(dd);
864 * \brief AddDicomDirImageToEnd
865 * @param dd SQ Item to enqueue to the DicomDirImage chained List
867 bool DicomDir::AddDicomDirImageToEnd(DicomDirImage *dd)
869 if( Patients.size() > 0 )
871 ListDicomDirPatient::iterator itp = Patients.end();
874 if( (*itp)->GetDicomDirStudies().size() > 0 )
876 ListDicomDirStudy::const_iterator itst =
877 (*itp)->GetDicomDirStudies().end();
880 if( (*itst)->GetDicomDirSeries().size() > 0 )
882 ListDicomDirSerie::const_iterator its = (*itst)->GetDicomDirSeries().end();
884 (*its)->AddDicomDirImage(dd);
894 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
895 * @param path path of the root directory
896 * @param list chained list of Headers
898 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
903 std::string patPrevName = "", patPrevID = "";
904 std::string studPrevInstanceUID = "", studPrevID = "";
905 std::string serPrevInstanceUID = "", serPrevID = "";
907 std::string patCurName, patCurID;
908 std::string studCurInstanceUID, studCurID;
909 std::string serCurInstanceUID, serCurID;
912 for( VectDocument::const_iterator it = list.begin();
913 it != list.end(); ++it )
915 // get the current file characteristics
916 patCurName = (*it)->GetEntry(0x0010,0x0010);
917 patCurID = (*it)->GetEntry(0x0010,0x0011);
918 studCurInstanceUID = (*it)->GetEntry(0x0020,0x000d);
919 studCurID = (*it)->GetEntry(0x0020,0x0010);
920 serCurInstanceUID = (*it)->GetEntry(0x0020,0x000e);
921 serCurID = (*it)->GetEntry(0x0020,0x0011);
923 if( patCurName != patPrevName || patCurID != patPrevID || first )
925 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
929 // if new Study Deal with 'STUDY' Elements
930 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
933 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
937 // if new Serie Deal with 'SERIE' Elements
938 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
941 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
945 // Always Deal with 'IMAGE' Elements
946 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
948 patPrevName = patCurName;
949 patPrevID = patCurID;
950 studPrevInstanceUID = studCurInstanceUID;
951 studPrevID = studCurID;
952 serPrevInstanceUID = serCurInstanceUID;
953 serPrevID = serCurID;
960 * \brief Move the content of the src SQItem to the dst SQItem
961 * Only DocEntry's are moved
964 void DicomDir::MoveSQItem(SQItem *dst,SQItem *src)
969 entry = src->GetNextEntry();
972 src->RemoveEntryNoDestroy(entry);
973 dst->AddEntry(entry);
976 entry = src->GetNextEntry();
982 * \brief compares two dgcmHeaders
984 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
986 return *header1 < *header2;
988 } // end namespace gdcm
990 //-----------------------------------------------------------------------------