1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2004/11/25 15:46:10 $
7 Version: $Revision: 1.82 $
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
130 * \brief Canonical destructor
132 DicomDir::~DicomDir()
134 SetStartMethod(NULL);
135 SetProgressMethod(NULL);
139 for(ListDicomDirPatient::iterator cc = Patients.begin();
151 //-----------------------------------------------------------------------------
154 * \brief Canonical Printer
156 void DicomDir::Print(std::ostream &os)
160 MetaElems->SetPrintLevel(PrintLevel);
161 MetaElems->Print(os);
163 for(ListDicomDirPatient::iterator cc = Patients.begin();
164 cc != Patients.end();
167 (*cc)->SetPrintLevel( PrintLevel );
172 //-----------------------------------------------------------------------------
175 * \brief This predicate, based on hopefully reasonable heuristics,
176 * decides whether or not the current header was properly parsed
177 * and contains the mandatory information for being considered as
178 * a well formed and usable DicomDir.
179 * @return true when Document is the one of a reasonable DicomDir,
182 bool DicomDir::IsReadable()
184 if( !Document::IsReadable() )
192 if( Patients.size() <= 0 )
201 * \brief Sets all fields to NULL
204 void DicomDir::Initialize()
207 ProgressMethod = NULL;
209 StartMethodArgDelete = NULL;
210 ProgressMethodArgDelete = NULL;
211 EndMethodArgDelete = NULL;
225 * \brief fills the whole structure, starting from a root Directory
227 void DicomDir::ParseDirectory()
229 CreateDicomDirChainedList( GetFileName() );
235 * \brief Set the start method to call when the parsing of the
237 * @param method Method to call
238 * @param arg Argument to pass to the method
239 * @param argDelete Argument
240 * \warning In python : the arg parameter isn't considered
242 void DicomDir::SetStartMethod( DicomDir::Method* method, void* arg,
243 DicomDir::Method* argDelete )
245 if( StartArg && StartMethodArgDelete )
247 StartMethodArgDelete( StartArg );
250 StartMethod = method;
252 StartMethodArgDelete = argDelete;
257 * \brief Set the method to delete the argument
258 * The argument is destroyed when the method is changed or when the
260 * @param method Method to call to delete the argument
262 void DicomDir::SetStartMethodArgDelete( DicomDir::Method* method )
264 StartMethodArgDelete = method;
269 * \brief Set the progress method to call when the parsing of the
271 * @param method Method to call
272 * @param arg Argument to pass to the method
273 * @param argDelete Argument
274 * \warning In python : the arg parameter isn't considered
276 void DicomDir::SetProgressMethod( DicomDir::Method* method, void* arg,
277 DicomDir::Method* argDelete )
279 if( ProgressArg && ProgressMethodArgDelete )
281 ProgressMethodArgDelete( ProgressArg );
284 ProgressMethod = method;
286 ProgressMethodArgDelete = argDelete;
291 * \brief Set the method to delete the argument
292 * The argument is destroyed when the method is changed or when the
294 * @param method Method to call to delete the argument
296 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method* method )
298 ProgressMethodArgDelete = method;
303 * \brief Set the end method to call when the parsing of the directory ends
304 * @param method Method to call
305 * @param arg Argument to pass to the method
306 * @param argDelete Argument
307 * \warning In python : the arg parameter isn't considered
309 void DicomDir::SetEndMethod( DicomDir::Method* method, void* arg,
310 DicomDir::Method* argDelete )
312 if( EndArg && EndMethodArgDelete )
314 EndMethodArgDelete( EndArg );
319 EndMethodArgDelete = argDelete;
324 * \brief Set the method to delete the argument
325 * The argument is destroyed when the method is changed or when
326 * the class is destroyed
327 * @param method Method to call to delete the argument
329 void DicomDir::SetEndMethodArgDelete( DicomDir::Method* method )
331 EndMethodArgDelete = method;
336 * \brief writes on disc a DICOMDIR
337 * \ warning does NOT add the missing elements in the header :
338 * it's up to the user doing it !
339 * \todo : to be re-written using the DICOMDIR tree-like structure
340 * *not* the chained list
341 * (does NOT exist if the DICOMDIR is user-forged !)
342 * @param fileName file to be written to
343 * @return false only when fail to open
346 bool DicomDir::WriteDicomDir(std::string const& fileName)
349 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
350 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
352 std::ofstream* fp = new std::ofstream(fileName.c_str(),
353 std::ios::out | std::ios::binary);
356 dbg.Verbose(2, "Failed to open(write) File: ", fileName.c_str());
360 char filePreamble[128];
361 memset(filePreamble, 0, 128);
362 fp->write(filePreamble, 128); //FIXME
363 binary_write( *fp, "DICM");
365 DicomDirMeta *ptrMeta = GetDicomDirMeta();
366 ptrMeta->WriteContent(fp, ExplicitVR);
368 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
371 binary_write(*fp, sq[i]);
374 for(ListDicomDirPatient::iterator cc = Patients.begin();
375 cc != Patients.end();
378 (*cc)->WriteContent( fp, ExplicitVR );
381 // force writing Sequence Delimitation Item
384 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
391 //-----------------------------------------------------------------------------
396 * \brief create a Document-like chained list from a root Directory
397 * @param path entry point of the tree-like structure
399 void DicomDir::CreateDicomDirChainedList(std::string const & path)
402 DirList fileList(path,1); // gets recursively the file list
403 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
559 case GDCM_DICOMDIR_IMAGE:
560 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
563 case GDCM_DICOMDIR_SERIE:
564 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
567 case GDCM_DICOMDIR_STUDY:
568 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
571 case GDCM_DICOMDIR_PATIENT:
572 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
575 case GDCM_DICOMDIR_META:
576 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
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()->GetDictEntryByNumber(tmpGr, tmpEl);
598 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
600 entry->SetOffset(0); // just to avoid further missprinting
601 entry->SetLength(0); // just to avoid further missprinting
605 // NULL when we Build Up (ex nihilo) a DICOMDIR
606 // or when we add the META elems
607 val = header->GetEntryByNumber(tmpGr, tmpEl);
614 if( val == GDCM_UNFOUND)
616 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
618 // force to the *end* File Name
619 val = Util::GetName( path );
621 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
623 if( header->GetFileName().substr(0, path.length()) != path )
625 dbg.Verbose(0, "DicomDir::SetElement : the base path"
626 " of file name is incorrect");
627 val = header->GetFileName();
631 val = &(header->GetFileName().c_str()[path.length()]);
641 if ( header->GetEntryLengthByNumber(tmpGr,tmpEl) == 0 )
645 // GDCM_UNFOUND or not !
647 entry->SetValue( val ); // troubles expected when vr=SQ ...
651 if( dictEntry->GetGroup() == 0xfffe )
653 entry->SetLength( entry->GetValue().length() ); // FIXME
655 else if( dictEntry->GetVR() == "UL" || dictEntry->GetVR() == "SL" )
659 else if( dictEntry->GetVR() == "US" || dictEntry->GetVR() == "SS" )
663 else if( dictEntry->GetVR() == "SQ" )
665 entry->SetLength( 0xffffffff );
669 entry->SetLength( entry->GetValue().length() );
673 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
675 std::cout << "GDCM_DICOMDIR_META ?!? should never print that"
682 case GDCM_DICOMDIR_IMAGE:
683 AddDicomDirImageToEnd(si);
686 case GDCM_DICOMDIR_SERIE:
687 AddDicomDirSerieToEnd(si);
690 case GDCM_DICOMDIR_STUDY:
691 AddDicomDirStudyToEnd(si);
694 case GDCM_DICOMDIR_PATIENT:
695 AddDicomDirPatientToEnd(si);
701 //int count=1; // find a trick to increment
702 //s->AddEntry(si, count); // Seg Faults
706 //-----------------------------------------------------------------------------
708 * \brief CallStartMethod
710 void DicomDir::CallStartMethod()
716 StartMethod( StartArg );
720 //-----------------------------------------------------------------------------
723 * \brief CallProgressMethod
725 void DicomDir::CallProgressMethod()
729 ProgressMethod( ProgressArg );
733 //-----------------------------------------------------------------------------
736 * \brief CallEndMethod
738 void DicomDir::CallEndMethod()
747 //-----------------------------------------------------------------------------
751 * \brief create a 'DicomDir' from a DICOMDIR Header
753 void DicomDir::CreateDicomDir()
755 // The list is parsed.
756 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
757 // 1 - we save the beginning iterator
758 // 2 - we continue to parse
759 // 3 - we find an other tag
760 // + we create the object for the precedent tag
763 // Directory record sequence
764 DocEntry *e = GetDocEntryByNumber(0x0004, 0x1220);
767 dbg.Verbose(0, "DicomDir::DicomDir : NO Directory record"
768 " sequence (0x0004,0x1220)");
769 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
773 SeqEntry* s = dynamic_cast<SeqEntry*>(e);
776 dbg.Verbose(0, "DicomDir::CreateDicomDir: no SeqEntry present");
777 // useless : (0x0004,0x1220) IS a Sequence !
781 DicomDirType type; // = DicomDir::GDCM_DICOMDIR_META;
782 MetaElems = NewMeta();
784 ListSQItem listItems = s->GetSQItems();
788 for( ListSQItem::iterator i = listItems.begin();
789 i !=listItems.end(); ++i )
791 d = (*i)->GetDocEntryByNumber(0x0004, 0x1430); // Directory Record Type
792 if ( ValEntry* valEntry = dynamic_cast< ValEntry* >(d) )
794 v = valEntry->GetValue();
798 dbg.Verbose(0, "DicomDir::CreateDicomDir: not a ValEntry.");
802 if( v == "PATIENT " )
804 AddDicomDirPatientToEnd( *i );
805 type = DicomDir::GDCM_DICOMDIR_PATIENT;
807 else if( v == "STUDY " )
809 AddDicomDirStudyToEnd( *i );
810 type = DicomDir::GDCM_DICOMDIR_STUDY;
812 else if( v == "SERIES" )
814 AddDicomDirSerieToEnd( *i );
815 type = DicomDir::GDCM_DICOMDIR_SERIE;
817 else if( v == "IMAGE " )
819 AddDicomDirImageToEnd( *i );
820 type = DicomDir::GDCM_DICOMDIR_IMAGE;
824 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
825 // neither an 'IMAGE' SQItem. Skip to next item.
833 * \brief Well ... there is only one occurence
835 void DicomDir::AddDicomDirMeta()
841 MetaElems = new DicomDirMeta( &TagHT );
846 * \brief AddDicomDirPatientToEnd
847 * @param s SQ Item to enqueue to the DicomPatient chained List
849 void DicomDir::AddDicomDirPatientToEnd(SQItem *s)
851 Patients.push_back(new DicomDirPatient(s, &TagHT));
856 * \brief AddDicomDirStudyToEnd
857 * @param s SQ Item to enqueue to the DicomDirStudy chained List
859 void DicomDir::AddDicomDirStudyToEnd(SQItem *s)
861 if( Patients.size() > 0 )
863 ListDicomDirPatient::iterator itp = Patients.end();
865 (*itp)->AddDicomDirStudy(new DicomDirStudy(s, &TagHT));
871 * \brief AddDicomDirSerieToEnd
872 * @param s SQ Item to enqueue to the DicomDirSerie chained List
874 void DicomDir::AddDicomDirSerieToEnd(SQItem *s)
876 if( Patients.size() > 0 )
878 ListDicomDirPatient::iterator itp = Patients.end();
881 if( (*itp)->GetDicomDirStudies().size() > 0 )
883 ListDicomDirStudy::const_iterator itst =
884 (*itp)->GetDicomDirStudies().end();
886 (*itst)->AddDicomDirSerie(new DicomDirSerie(s, &TagHT));
893 * \brief AddDicomDirImageToEnd
894 * @param s SQ Item to enqueue to the DicomDirImage chained List
896 void DicomDir::AddDicomDirImageToEnd(SQItem *s)
898 if( Patients.size() > 0 )
900 ListDicomDirPatient::iterator itp = Patients.end();
903 if( (*itp)->GetDicomDirStudies().size() > 0 )
905 ListDicomDirStudy::const_iterator itst =
906 (*itp)->GetDicomDirStudies().end();
909 if( (*itst)->GetDicomDirSeries().size() > 0 )
911 ListDicomDirSerie::const_iterator its = (*itst)->GetDicomDirSeries().end();
913 (*its)->AddDicomDirImage(new DicomDirImage(s, &TagHT));
921 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
922 * @param path path of the root directory
923 * @param list chained list of Headers
925 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
930 std::string patPrevName = "", patPrevID = "";
931 std::string studPrevInstanceUID = "", studPrevID = "";
932 std::string serPrevInstanceUID = "", serPrevID = "";
934 std::string patCurName, patCurID;
935 std::string studCurInstanceUID, studCurID;
936 std::string serCurInstanceUID, serCurID;
938 for( VectDocument::const_iterator it = list.begin();
939 it != list.end(); ++it )
941 // get the current file characteristics
942 patCurName = (*it)->GetEntryByNumber(0x0010,0x0010);
943 patCurID = (*it)->GetEntryByNumber(0x0010,0x0011);
944 studCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000d);
945 studCurID = (*it)->GetEntryByNumber(0x0020,0x0010);
946 serCurInstanceUID = (*it)->GetEntryByNumber(0x0020,0x000e);
947 serCurID = (*it)->GetEntryByNumber(0x0020,0x0011);
949 if( patCurName != patPrevName || patCurID != patPrevID)
951 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
954 // if new Study Deal with 'STUDY' Elements
955 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID )
957 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
960 // if new Serie Deal with 'SERIE' Elements
961 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID )
963 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
966 // Always Deal with 'IMAGE' Elements
967 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
969 patPrevName = patCurName;
970 patPrevID = patCurID;
971 studPrevInstanceUID = studCurInstanceUID;
972 studPrevID = studCurID;
973 serPrevInstanceUID = serCurInstanceUID;
974 serPrevID = serCurID;
980 * \brief compares two dgcmHeaders
982 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
984 return *header1 < *header2;
986 } // end namespace gdcm
988 //-----------------------------------------------------------------------------