1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2004/11/16 10:25:52 $
7 Version: $Revision: 1.80 $
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 "gdcmDirList.h"
25 #include "gdcmDebug.h"
26 #include "gdcmGlobal.h"
27 #include "gdcmHeader.h"
28 #include "gdcmSeqEntry.h"
29 #include "gdcmSQItem.h"
30 #include "gdcmValEntry.h"
35 #include <sys/types.h>
37 #if defined( _MSC_VER) || defined(__BORLANDC__)
45 //-----------------------------------------------------------------------------
46 // For full DICOMDIR description, see:
47 // PS 3.3-2003, pages 731-750
48 //-----------------------------------------------------------------------------
49 // Constructor / Destructor
53 * \brief Constructor : creates an empty DicomDir
58 Initialize(); // sets all private fields to NULL
59 std::string pathBidon = "Bidon"; // Sorry, NULL not allowed ...
60 MetaElems = NewMeta();
64 * \brief Constructor Parses recursively the directory and creates the DicomDir
65 * or uses an already built DICOMDIR, depending on 'parseDir' value.
66 * @param fileName name
67 * - of the root directory (parseDir = true)
68 * - of the DICOMDIR (parseDir = false)
69 * @param parseDir boolean
70 * - true if user passed an entry point
71 * and wants to explore recursively the directories
72 * - false if user passed an already built DICOMDIR file
75 DicomDir::DicomDir(std::string const & fileName, bool parseDir ):
78 // Whatever user passed (a root directory or a DICOMDIR)
79 // and whatever the value of parseDir was,
80 // Document is already executed
81 Initialize(); // sets all private fields to NULL
83 // if user passed a root directory, sure we didn't get anything
85 if ( TagHT.begin() == TagHT.end() ) // when user passed a Directory to parse
87 dbg.Verbose(0, "DicomDir::DicomDir : entry HT empty");
89 if ( fileName.size() == 1 && fileName[0] == '.' )
91 // user passed '.' as Name
92 // we get current directory name
94 getcwd(dummy, (size_t)1000);
95 SetFileName( dummy ); // will be converted into a string
98 if ( parseDir ) // user asked for a recursive parsing of a root directory
100 MetaElems = NewMeta();
102 dbg.Verbose(0, "DicomDir::DicomDir : Parse directory"
103 " and create the DicomDir");
108 /// \todo if parseDir == false, it should be tagged as an error
109 // NON ! il suffit d'appeler ParseDirectory()
110 // apres le constructeur
113 else // Only if user passed a DICOMDIR
115 // Directory record sequence
116 DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
119 dbg.Verbose(0, "DicomDir::DicomDir : NO Directory record"
120 " sequence (0x0004,0x1220)");
121 /// \todo FIXME : what do we do when the parsed file IS NOT a
129 * \brief Canonical destructor
131 DicomDir::~DicomDir()
133 SetStartMethod(NULL);
134 SetProgressMethod(NULL);
136 for(ListDicomDirPatient::iterator cc = Patients.begin();
148 //-----------------------------------------------------------------------------
151 * \brief Canonical Printer
153 void DicomDir::Print(std::ostream &os)
157 MetaElems->SetPrintLevel(PrintLevel);
158 MetaElems->Print(os);
160 for(ListDicomDirPatient::iterator cc = Patients.begin();
161 cc != Patients.end();
164 (*cc)->SetPrintLevel( PrintLevel );
169 //-----------------------------------------------------------------------------
172 * \brief This predicate, based on hopefully reasonable heuristics,
173 * decides whether or not the current header was properly parsed
174 * and contains the mandatory information for being considered as
175 * a well formed and usable DicomDir.
176 * @return true when Document is the one of a reasonable DicomDir,
179 bool DicomDir::IsReadable()
181 if( !Document::IsReadable() )
189 if( Patients.size() <= 0 )
198 * \brief Sets all fields to NULL
201 void DicomDir::Initialize()
204 ProgressMethod = NULL;
206 StartMethodArgDelete = NULL;
207 ProgressMethodArgDelete = NULL;
208 EndMethodArgDelete = NULL;
222 * \brief fills the whole structure, starting from a root Directory
224 void DicomDir::ParseDirectory()
226 CreateDicomDirChainedList( GetFileName() );
232 * \brief Set the start method to call when the parsing of the
234 * @param method Method to call
235 * @param arg Argument to pass to the method
236 * @param argDelete Argument
237 * \warning In python : the arg parameter isn't considered
239 void DicomDir::SetStartMethod( DicomDir::Method* method, void* arg,
240 DicomDir::Method* argDelete )
242 if( StartArg && StartMethodArgDelete )
244 StartMethodArgDelete( StartArg );
247 StartMethod = method;
249 StartMethodArgDelete = argDelete;
254 * \brief Set the method to delete the argument
255 * The argument is destroyed when the method is changed or when the
257 * @param method Method to call to delete the argument
259 void DicomDir::SetStartMethodArgDelete( DicomDir::Method* method )
261 StartMethodArgDelete = method;
266 * \brief Set the progress method to call when the parsing of the
268 * @param method Method to call
269 * @param arg Argument to pass to the method
270 * @param argDelete Argument
271 * \warning In python : the arg parameter isn't considered
273 void DicomDir::SetProgressMethod( DicomDir::Method* method, void* arg,
274 DicomDir::Method* argDelete )
276 if( ProgressArg && ProgressMethodArgDelete )
278 ProgressMethodArgDelete( ProgressArg );
281 ProgressMethod = method;
283 ProgressMethodArgDelete = argDelete;
288 * \brief Set the method to delete the argument
289 * The argument is destroyed when the method is changed or when the
291 * @param method Method to call to delete the argument
293 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method* method )
295 ProgressMethodArgDelete = method;
300 * \brief Set the end method to call when the parsing of the directory ends
301 * @param method Method to call
302 * @param arg Argument to pass to the method
303 * @param argDelete Argument
304 * \warning In python : the arg parameter isn't considered
306 void DicomDir::SetEndMethod( DicomDir::Method* method, void* arg,
307 DicomDir::Method* argDelete )
309 if( EndArg && EndMethodArgDelete )
311 EndMethodArgDelete( EndArg );
316 EndMethodArgDelete = argDelete;
321 * \brief Set the method to delete the argument
322 * The argument is destroyed when the method is changed or when
323 * the class is destroyed
324 * @param method Method to call to delete the argument
326 void DicomDir::SetEndMethodArgDelete( DicomDir::Method* method )
328 EndMethodArgDelete = method;
333 * \brief writes on disc a DICOMDIR
334 * \ warning does NOT add the missing elements in the header :
335 * it's up to the user doing it !
336 * \todo : to be re-written using the DICOMDIR tree-like structure
337 * *not* the chained list
338 * (does NOT exist if the DICOMDIR is user-forged !)
339 * @param fileName file to be written to
340 * @return false only when fail to open
343 bool DicomDir::WriteDicomDir(std::string const& fileName)
346 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
347 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
349 std::ofstream* fp = new std::ofstream(fileName.c_str(),
350 std::ios::out | std::ios::binary);
353 dbg.Verbose(2, "Failed to open(write) File: ", fileName.c_str());
357 char filePreamble[128];
358 memset(filePreamble, 0, 128);
359 fp->write(filePreamble, 128); //FIXME
360 binary_write( *fp, "DICM");
362 DicomDirMeta *ptrMeta = GetDicomDirMeta();
363 ptrMeta->Write(fp, ExplicitVR);
365 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
368 binary_write(*fp, sq[i]);
371 for(ListDicomDirPatient::iterator cc = Patients.begin();
372 cc != Patients.end();
375 (*cc)->Write( fp, ExplicitVR );
378 // force writing Sequence Delimitation Item
381 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
388 //-----------------------------------------------------------------------------
393 * \brief create a Document-like chained list from a root Directory
394 * @param path entry point of the tree-like structure
396 void DicomDir::CreateDicomDirChainedList(std::string const & path)
399 DirList fileList(path,1); // gets recursively the file list
400 unsigned int count = 0;
407 for( DirList::iterator it = fileList.begin();
408 it != fileList.end();
411 Progress = (float)(count+1)/(float)fileList.size();
412 CallProgressMethod();
418 header = new Header( it->c_str() );
422 "DicomDir::CreateDicomDirChainedList: "
423 "failure in new Header ",
427 if( header->IsReadable() )
429 // Add the file header to the chained list:
430 list.push_back(header);
432 "DicomDir::CreateDicomDirChainedList: readable ",
442 // sorts Patient/Study/Serie/
443 std::sort(list.begin(), list.end(), DicomDir::HeaderLessThan );
445 std::string tmp = fileList.GetDirName();
446 //for each Header of the chained list, add/update the Patient/Study/Serie/Image info
447 SetElements(tmp, list);
453 * \brief adds *the* Meta to a partially created DICOMDIR
456 DicomDirMeta * DicomDir::NewMeta()
458 DicomDirMeta *m = new DicomDirMeta( &TagHT );
460 if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
462 TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
463 lastOneButSequence --;
464 // ALL the 'out of Sequence' Tags belong to Meta Elems
465 // (we skip 0004|1220 [Directory record sequence] )
466 for ( TagDocEntryHT::iterator cc = TagHT.begin();
467 cc != lastOneButSequence;
470 m->AddDocEntry( cc->second );
473 else // after root directory parsing
475 ListDicomDirMetaElem const & elemList =
476 Global::GetDicomDirElements()->GetDicomDirMetaElements();
477 m->FillObject(elemList);
479 m->SetSQItemNumber(0); // To avoid further missprinting
484 * \brief adds a new Patient (with the basic elements) to a partially created DICOMDIR
486 DicomDirPatient * DicomDir::NewPatient()
488 ListDicomDirPatientElem::const_iterator it;
489 uint16_t tmpGr,tmpEl;
490 DictEntry *dictEntry;
493 ListDicomDirPatientElem const & elemList =
494 Global::GetDicomDirElements()->GetDicomDirPatientElements();
495 SQItem *s = new SQItem(0);
497 // for all the DicomDirPatient Elements
498 for( it = elemList.begin(); it != elemList.end(); ++it )
502 dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
503 entry = new ValEntry( dictEntry );
504 entry->SetOffset(0); // just to avoid further missprinting
505 entry->SetValue( it->Value );
507 // dealing with value length ...
509 if( dictEntry->GetGroup() == 0xfffe)
511 entry->SetLength(entry->GetValue().length());
513 else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
515 entry->SetLength( 4 );
517 else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
521 else if( dictEntry->GetVR() == "SQ" )
523 entry->SetLength( 0xffffffff );
527 entry->SetLength( entry->GetValue().length() );
529 s->AddDocEntry( entry );
532 DicomDirPatient *p = new DicomDirPatient(s, &TagHT);
533 Patients.push_front( p );
539 * \brief adds to the HTable
540 * the Entries (Dicom Elements) corresponding to the given type
541 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
542 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
543 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
544 * @param header Header of the current file
546 void DicomDir::SetElement(std::string const & path, DicomDirType type,
549 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
550 ListDicomDirElem::const_iterator it;
551 uint16_t tmpGr, tmpEl;
552 DictEntry *dictEntry;
555 SQItem *si = new SQItem(0); // all the items will be at level 1
558 case GDCM_DICOMDIR_IMAGE:
559 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
562 case GDCM_DICOMDIR_SERIE:
563 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
566 case GDCM_DICOMDIR_STUDY:
567 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
570 case GDCM_DICOMDIR_PATIENT:
571 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
574 case GDCM_DICOMDIR_META:
575 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
581 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
582 // to avoid further troubles
583 // imageElem 0008 1140 "" // Referenced Image Sequence
584 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
585 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
586 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
587 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
588 // for all the relevant elements found in their own spot of the DicomDir.dic
589 // FIXME : troubles found when it's a SeqEntry
591 for( it = elemList.begin(); it != elemList.end(); ++it)
595 dictEntry = GetPubDict()->GetDictEntryByNumber(tmpGr, tmpEl);
597 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
599 entry->SetOffset(0); // just to avoid further missprinting
600 entry->SetLength(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->GetEntryByNumber(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 dbg.Verbose(0, "DicomDir::SetElement : the base path"
625 " of file name is incorrect");
626 val = header->GetFileName();
630 val = &(header->GetFileName().c_str()[path.length()]);
640 if ( header->GetEntryLengthByNumber(tmpGr,tmpEl) == 0 )
644 // GDCM_UNFOUND or not !
646 entry->SetValue( val ); // troubles expected when vr=SQ ...
650 if( dictEntry->GetGroup() == 0xfffe )
652 entry->SetLength( entry->GetValue().length() ); // FIXME
654 else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
658 else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
662 else if( dictEntry->GetVR() == "SQ" )
664 entry->SetLength( 0xffffffff );
668 entry->SetLength( entry->GetValue().length() );
672 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
674 std::cout << "GDCM_DICOMDIR_META ?!? should never print that"
681 case GDCM_DICOMDIR_IMAGE:
682 AddDicomDirImageToEnd(si);
685 case GDCM_DICOMDIR_SERIE:
686 AddDicomDirSerieToEnd(si);
689 case GDCM_DICOMDIR_STUDY:
690 AddDicomDirStudyToEnd(si);
693 case GDCM_DICOMDIR_PATIENT:
694 AddDicomDirPatientToEnd(si);
700 //int count=1; // find a trick to increment
701 //s->AddEntry(si, count); // Seg Faults
705 //-----------------------------------------------------------------------------
707 * \brief CallStartMethod
709 void DicomDir::CallStartMethod()
715 StartMethod( StartArg );
719 //-----------------------------------------------------------------------------
722 * \brief CallProgressMethod
724 void DicomDir::CallProgressMethod()
728 ProgressMethod( ProgressArg );
732 //-----------------------------------------------------------------------------
735 * \brief CallEndMethod
737 void DicomDir::CallEndMethod()
746 //-----------------------------------------------------------------------------
750 * \brief create a 'DicomDir' from a DICOMDIR Header
752 void DicomDir::CreateDicomDir()
754 // The list is parsed.
755 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
756 // 1 - we save the beginning iterator
757 // 2 - we continue to parse
758 // 3 - we find an other tag
759 // + we create the object for the precedent tag
762 // Directory record sequence
763 DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
766 dbg.Verbose(0, "DicomDir::DicomDir : NO Directory record"
767 " sequence (0x0004,0x1220)");
768 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
772 SeqEntry* s = dynamic_cast<SeqEntry*>(e);
775 dbg.Verbose(0, "DicomDir::CreateDicomDir: no SeqEntry present");
776 // useless : (0x0004,0x1220) IS a Sequence !
780 DicomDirType type; // = DicomDir::GDCM_DICOMDIR_META;
781 MetaElems = NewMeta();
783 ListSQItem listItems = s->GetSQItems();
787 for( ListSQItem::iterator i = listItems.begin();
788 i !=listItems.end(); ++i )
790 d = (*i)->GetDocEntryByNumber(0x0004, 0x1430); // Directory Record Type
791 if ( ValEntry* valEntry = dynamic_cast< ValEntry* >(d) )
793 v = valEntry->GetValue();
797 dbg.Verbose(0, "DicomDir::CreateDicomDir: not a ValEntry.");
801 if( v == "PATIENT " )
803 AddDicomDirPatientToEnd( *i );
804 type = DicomDir::GDCM_DICOMDIR_PATIENT;
806 else if( v == "STUDY " )
808 AddDicomDirStudyToEnd( *i );
809 type = DicomDir::GDCM_DICOMDIR_STUDY;
811 else if( v == "SERIES" )
813 AddDicomDirSerieToEnd( *i );
814 type = DicomDir::GDCM_DICOMDIR_SERIE;
816 else if( v == "IMAGE " )
818 AddDicomDirImageToEnd( *i );
819 type = DicomDir::GDCM_DICOMDIR_IMAGE;
823 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
824 // neither an 'IMAGE' SQItem. Skip to next item.
832 * \brief Well ... there is only one occurence
834 void DicomDir::AddDicomDirMeta()
840 MetaElems = new DicomDirMeta( &TagHT );
845 * \brief AddDicomDirPatientToEnd
846 * @param s SQ Item to enqueue to the DicomPatient chained List
848 void DicomDir::AddDicomDirPatientToEnd(SQItem *s)
850 Patients.push_back(new DicomDirPatient(s, &TagHT));
855 * \brief AddDicomDirStudyToEnd
856 * @param s SQ Item to enqueue to the DicomDirStudy chained List
858 void DicomDir::AddDicomDirStudyToEnd(SQItem *s)
860 if( Patients.size() > 0 )
862 ListDicomDirPatient::iterator itp = Patients.end();
864 (*itp)->AddDicomDirStudy(new DicomDirStudy(s, &TagHT));
870 * \brief AddDicomDirSerieToEnd
871 * @param s SQ Item to enqueue to the DicomDirSerie chained List
873 void DicomDir::AddDicomDirSerieToEnd(SQItem *s)
875 if( Patients.size() > 0 )
877 ListDicomDirPatient::iterator itp = Patients.end();
880 if( (*itp)->GetDicomDirStudies().size() > 0 )
882 ListDicomDirStudy::const_iterator itst =
883 (*itp)->GetDicomDirStudies().end();
885 (*itst)->AddDicomDirSerie(new DicomDirSerie(s, &TagHT));
892 * \brief AddDicomDirImageToEnd
893 * @param s SQ Item to enqueue to the DicomDirImage chained List
895 void DicomDir::AddDicomDirImageToEnd(SQItem *s)
897 if( Patients.size() > 0 )
899 ListDicomDirPatient::iterator itp = Patients.end();
902 if( (*itp)->GetDicomDirStudies().size() > 0 )
904 ListDicomDirStudy::const_iterator itst =
905 (*itp)->GetDicomDirStudies().end();
908 if( (*itst)->GetDicomDirSeries().size() > 0 )
910 ListDicomDirSerie::const_iterator its = (*itst)->GetDicomDirSeries().end();
912 (*its)->AddDicomDirImage(new DicomDirImage(s, &TagHT));
920 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
921 * @param path path of the root directory
922 * @param list chained list of Headers
924 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
926 std::string patPrevName = "", patPrevID = "";
927 std::string studPrevInstanceUID = "", studPrevID = "";
928 std::string serPrevInstanceUID = "", serPrevID = "";
930 std::string patCurName, patCurID;
931 std::string studCurInstanceUID, studCurID;
932 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)->GetEntryByNumber(0x0010,0x0010);
939 patCurID = (*it)->GetEntryByNumber(0x0010,0x0011);
940 studCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000d);
941 studCurID = (*it)->GetEntryByNumber(0x0020,0x0010);
942 serCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000e);
943 serCurID = (*it)->GetEntryByNumber(0x0020,0x0011);
945 if( patCurName != patPrevName || patCurID != patPrevID)
947 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
950 // if new Study Deal with 'STUDY' Elements
951 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID )
953 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
956 // if new Serie Deal with 'SERIE' Elements
957 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID )
959 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
962 // Always Deal with 'IMAGE' Elements
963 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
965 patPrevName = patCurName;
966 patPrevID = patCurID;
967 studPrevInstanceUID = studCurInstanceUID;
968 studPrevID = studCurID;
969 serPrevInstanceUID = serCurInstanceUID;
970 serPrevID = serCurID;
976 * \brief compares two dgcmHeaders
978 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
980 return *header1 < *header2;
982 } // end namespace gdcm
984 //-----------------------------------------------------------------------------