1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/01/21 15:28:18 $
7 Version: $Revision: 1.113 $
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
92 if ( GetFirstEntry() != 0 ) // 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
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 document 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 fills the whole structure, starting from a root Directory
215 void DicomDir::ParseDirectory()
217 CreateDicomDirChainedList( GetFileName() );
222 * \brief Set the start method to call when the parsing of the
224 * @param method Method to call
225 * @param arg Argument to pass to the method
226 * @param argDelete Argument
227 * \warning In python : the arg parameter isn't considered
229 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
230 DicomDir::Method *argDelete )
232 if( StartArg && StartMethodArgDelete )
234 StartMethodArgDelete( StartArg );
237 StartMethod = method;
239 StartMethodArgDelete = argDelete;
243 * \brief Set the method to delete the argument
244 * The argument is destroyed when the method is changed or when the
246 * @param method Method to call to delete the argument
248 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
250 StartMethodArgDelete = method;
254 * \brief Set the progress method to call when the parsing of the
256 * @param method Method to call
257 * @param arg Argument to pass to the method
258 * @param argDelete Argument
259 * \warning In python : the arg parameter isn't considered
261 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
262 DicomDir::Method *argDelete )
264 if( ProgressArg && ProgressMethodArgDelete )
266 ProgressMethodArgDelete( ProgressArg );
269 ProgressMethod = method;
271 ProgressMethodArgDelete = argDelete;
275 * \brief Set the method to delete the argument
276 * The argument is destroyed when the method is changed or when the
278 * @param method Method to call to delete the argument
280 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
282 ProgressMethodArgDelete = method;
286 * \brief Set the end method to call when the parsing of the directory ends
287 * @param method Method to call
288 * @param arg Argument to pass to the method
289 * @param argDelete Argument
290 * \warning In python : the arg parameter isn't considered
292 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
293 DicomDir::Method *argDelete )
295 if( EndArg && EndMethodArgDelete )
297 EndMethodArgDelete( EndArg );
302 EndMethodArgDelete = argDelete;
306 * \brief Set the method to delete the argument
307 * The argument is destroyed when the method is changed or when
308 * the class is destroyed
309 * @param method Method to call to delete the argument
311 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
313 EndMethodArgDelete = method;
317 * \brief Get the first entry while visiting the DicomDirPatients
318 * \return The first DicomDirPatient if found, otherwhise NULL
320 DicomDirPatient *DicomDir::GetFirstPatient()
322 ItPatient = Patients.begin();
323 if ( ItPatient != Patients.end() )
329 * \brief Get the next entry while visiting the DicomDirPatients
330 * \note : meaningfull only if GetFirstEntry already called
331 * \return The next DicomDirPatient if found, otherwhise NULL
333 DicomDirPatient *DicomDir::GetNextPatient()
335 gdcmAssertMacro (ItPatient != Patients.end());
338 if ( ItPatient != Patients.end() )
345 * \brief writes on disc a DICOMDIR
346 * \ warning does NOT add the missing elements in the header :
347 * it's up to the user doing it !
348 * \todo : to be re-written using the DICOMDIR tree-like structure
349 * *not* the chained list
350 * (does NOT exist if the DICOMDIR is user-forged !)
351 * @param fileName file to be written to
352 * @return false only when fail to open
355 bool DicomDir::WriteDicomDir(std::string const &fileName)
358 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
359 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
361 std::ofstream *fp = new std::ofstream(fileName.c_str(),
362 std::ios::out | std::ios::binary);
365 gdcmVerboseMacro("Failed to open(write) File: " << fileName.c_str());
369 char filePreamble[128];
370 memset(filePreamble, 0, 128);
371 fp->write(filePreamble, 128); //FIXME
372 binary_write( *fp, "DICM");
374 DicomDirMeta *ptrMeta = GetMeta();
375 ptrMeta->WriteContent(fp, ExplicitVR);
377 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
380 binary_write(*fp, sq[i]);
383 for(ListDicomDirPatient::iterator cc = Patients.begin();
384 cc != Patients.end();
387 (*cc)->WriteContent( fp, ExplicitVR );
390 // force writing Sequence Delimitation Item
393 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
402 //-----------------------------------------------------------------------------
406 * \brief create a Document-like chained list from a root Directory
407 * @param path entry point of the tree-like structure
409 void DicomDir::CreateDicomDirChainedList(std::string const & path)
412 DirList dirList(path,1); // gets recursively the file list
413 unsigned int count = 0;
417 DirListType fileList = dirList.GetFilenames();
419 for( DirListType::iterator it = fileList.begin();
420 it != fileList.end();
423 Progress = (float)(count+1)/(float)fileList.size();
424 CallProgressMethod();
430 header = new File( it->c_str() );
433 gdcmVerboseMacro( "Failure in new gdcm::File " << it->c_str() );
437 if( header->IsReadable() )
439 // Add the file to the chained list:
440 list.push_back(header);
441 gdcmVerboseMacro( "Readable " << it->c_str() );
449 // sorts Patient/Study/Serie/
450 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
452 std::string tmp = dirList.GetDirName();
453 //for each File of the chained list, add/update the Patient/Study/Serie/Image info
454 SetElements(tmp, list);
457 for(VectDocument::iterator itDoc=list.begin();
461 delete dynamic_cast<File *>(*itDoc);
466 * \brief adds *the* Meta to a partially created DICOMDIR
469 DicomDirMeta *DicomDir::NewMeta()
474 // friend hunting : we miss GetLastEntry and GetPreviousEntry
475 // to be able to remove any direct reference to TagHT
477 DocEntry *e = GetFirstEntry();
479 //if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
481 MetaElems = new DicomDirMeta(true);
483 TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
484 lastOneButSequence --;
485 // ALL the 'out of Sequence' Tags belong to Meta Elems
486 // (we skip 0004|1220 [Directory record sequence] )
487 for ( TagDocEntryHT::iterator cc = TagHT.begin();
488 cc != lastOneButSequence;
491 MetaElems->AddEntry( cc->second );
494 else // after root directory parsing
496 MetaElems = new DicomDirMeta(false);
498 MetaElems->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 DicomDirPatient *p = new DicomDirPatient();
508 AddPatientToEnd( p );
513 * \brief adds to the HTable
514 * the Entries (Dicom Elements) corresponding to the given type
515 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
516 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
517 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
518 * @param header Header of the current file
520 void DicomDir::SetElement(std::string const &path, DicomDirType type,
523 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
524 ListDicomDirElem::const_iterator it;
525 uint16_t tmpGr, tmpEl;
526 DictEntry *dictEntry;
533 case GDCM_DICOMDIR_IMAGE:
534 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
535 si = new DicomDirImage(true);
536 if( !AddImageToEnd(static_cast<DicomDirImage *>(si)) )
539 gdcmErrorMacro( "Add ImageToEnd failed");
542 case GDCM_DICOMDIR_SERIE:
543 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
544 si = new DicomDirSerie(true);
545 if( !AddSerieToEnd(static_cast<DicomDirSerie *>(si)) )
548 gdcmErrorMacro( "Add SerieToEnd failed");
551 case GDCM_DICOMDIR_STUDY:
552 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
553 si = new DicomDirStudy(true);
554 if( !AddStudyToEnd(static_cast<DicomDirStudy *>(si)) )
557 gdcmErrorMacro( "Add StudyToEnd failed");
560 case GDCM_DICOMDIR_PATIENT:
561 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
562 si = new DicomDirPatient(true);
563 if( !AddPatientToEnd(static_cast<DicomDirPatient *>(si)) )
566 gdcmErrorMacro( "Add PatientToEnd failed");
569 case GDCM_DICOMDIR_META:
570 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
571 si = new DicomDirMeta(true);
575 gdcmErrorMacro( "MetaElements already exist, they will be destroyed");
577 MetaElems = static_cast<DicomDirMeta *>(si);
582 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
583 // to avoid further troubles
584 // imageElem 0008 1140 "" // Referenced Image Sequence
585 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
586 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
587 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
588 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
589 // for all the relevant elements found in their own spot of the DicomDir.dic
590 // FIXME : troubles found when it's a SeqEntry
592 for( it = elemList.begin(); it != elemList.end(); ++it)
596 dictEntry = GetPubDict()->GetDictEntry(tmpGr, tmpEl);
598 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
600 entry->SetOffset(0); // just to avoid further missprinting
604 // NULL when we Build Up (ex nihilo) a DICOMDIR
605 // or when we add the META elems
606 val = header->GetEntry(tmpGr, tmpEl);
613 if( val == GDCM_UNFOUND)
615 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
617 // force to the *end* File Name
618 val = Util::GetName( path );
620 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
622 if( header->GetFileName().substr(0, path.length()) != path )
624 gdcmVerboseMacro( "The base path of file name is incorrect");
625 val = header->GetFileName();
629 val = &(header->GetFileName().c_str()[path.length()]);
639 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
643 entry->SetValue( val ); // troubles expected when vr=SQ ...
645 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
647 gdcmVerboseMacro("GDCM_DICOMDIR_META ?!? should never print that");
653 //-----------------------------------------------------------------------------
655 * \brief CallStartMethod
657 void DicomDir::CallStartMethod()
663 StartMethod( StartArg );
667 //-----------------------------------------------------------------------------
669 * \brief CallProgressMethod
671 void DicomDir::CallProgressMethod()
675 ProgressMethod( ProgressArg );
679 //-----------------------------------------------------------------------------
681 * \brief CallEndMethod
683 void DicomDir::CallEndMethod()
692 //-----------------------------------------------------------------------------
695 * \brief Sets all fields to NULL
697 void DicomDir::Initialize()
700 ProgressMethod = NULL;
702 StartMethodArgDelete = NULL;
703 ProgressMethodArgDelete = NULL;
704 EndMethodArgDelete = NULL;
716 * \brief create a 'DicomDir' from a DICOMDIR Header
718 void DicomDir::CreateDicomDir()
720 // The list is parsed.
721 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
722 // 1 - we save the beginning iterator
723 // 2 - we continue to parse
724 // 3 - we find an other tag
725 // + we create the object for the precedent tag
728 // Directory record sequence
729 DocEntry *e = GetDocEntry(0x0004, 0x1220);
732 gdcmVerboseMacro( "NO Directory record sequence (0x0004,0x1220)");
733 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
737 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
740 gdcmVerboseMacro( "No SeqEntry present");
741 // useless : (0x0004,0x1220) IS a Sequence !
747 //ListSQItem listItems = s->GetSQItems();
753 SQItem *tmpSI=s->GetFirstSQItem();
756 d = tmpSI->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(true);
770 if( !AddPatientToEnd( static_cast<DicomDirPatient *>(si)) )
774 gdcmErrorMacro( "Add PatientToEnd failed");
777 else if( v == "STUDY " )
779 si = new DicomDirStudy(true);
780 if( !AddStudyToEnd( static_cast<DicomDirStudy *>(si)) )
784 gdcmErrorMacro( "Add AddStudyToEnd failed");
787 else if( v == "SERIES" )
789 si = new DicomDirSerie(true);
790 if( !AddSerieToEnd( static_cast<DicomDirSerie *>(si)) )
794 gdcmErrorMacro( "Add AddSerieToEnd failed");
797 else if( v == "IMAGE " )
799 si = new DicomDirImage(true);
800 if( !AddImageToEnd( static_cast<DicomDirImage *>(si)) )
804 gdcmErrorMacro( "Add AddImageToEnd failed");
809 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
810 // neither an 'IMAGE' SQItem. Skip to next item.
815 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)->GetEntry(0x0010,0x0010);
941 patCurID = (*it)->GetEntry(0x0010,0x0011);
942 studCurInstanceUID = (*it)->GetEntry(0x0020,0x000d);
943 studCurID = (*it)->GetEntry(0x0020,0x0010);
944 serCurInstanceUID = (*it)->GetEntry(0x0020,0x000e);
945 serCurID = (*it)->GetEntry(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 dgcmHeaders
1005 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
1007 return *header1 < *header2;
1010 } // end namespace gdcm
1012 //-----------------------------------------------------------------------------