1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/01/08 15:03:59 $
7 Version: $Revision: 1.97 $
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 // Whatever user passed (a root directory or a DICOMDIR)
86 // and whatever the value of parseDir was,
87 // Document is already executed
88 Initialize(); // sets all private fields to NULL
90 // if user passed a root directory, sure we didn't get anything
91 if ( TagHT.begin() == TagHT.end() ) // when user passed a Directory to parse
93 gdcmVerboseMacro( "Entry HT empty");
95 if ( fileName == "." )
97 // user passed '.' as Name
98 // we get current directory name
100 getcwd(dummy, (size_t)1000);
101 SetFileName( dummy ); // will be converted into a string
104 if ( parseDir ) // user asked for a recursive parsing of a root directory
106 MetaElems = NewMeta();
108 gdcmVerboseMacro( "Parse directory and create the DicomDir");
113 /// \todo if parseDir == false, it should be tagged as an error
114 // NON ! il suffit d'appeler ParseDirectory()
115 // apres le constructeur
118 else // Only if user passed a DICOMDIR
120 // Directory record sequence
121 DocEntry *e = GetDocEntry(0x0004, 0x1220);
124 gdcmVerboseMacro( "NO Directory record sequence (0x0004,0x1220)");
125 /// \todo FIXME : what do we do when the parsed file IS NOT a
134 * \brief Canonical destructor
136 DicomDir::~DicomDir()
138 SetStartMethod(NULL);
139 SetProgressMethod(NULL);
142 for(ListDicomDirPatient::iterator cc = Patients.begin();
154 //-----------------------------------------------------------------------------
157 * \brief Canonical Printer
159 void DicomDir::Print(std::ostream &os)
163 MetaElems->SetPrintLevel(PrintLevel);
164 MetaElems->Print(os);
166 for(ListDicomDirPatient::iterator cc = Patients.begin();
167 cc != Patients.end();
170 (*cc)->SetPrintLevel(PrintLevel);
175 //-----------------------------------------------------------------------------
178 * \brief This predicate, based on hopefully reasonable heuristics,
179 * decides whether or not the current header was properly parsed
180 * and contains the mandatory information for being considered as
181 * a well formed and usable DicomDir.
182 * @return true when Document is the one of a reasonable DicomDir,
185 bool DicomDir::IsReadable()
187 if( !Document::IsReadable() )
195 if( Patients.size() <= 0 )
204 * \brief Sets all fields to NULL
207 void DicomDir::Initialize()
210 ProgressMethod = NULL;
212 StartMethodArgDelete = NULL;
213 ProgressMethodArgDelete = NULL;
214 EndMethodArgDelete = NULL;
228 * \brief fills the whole structure, starting from a root Directory
230 void DicomDir::ParseDirectory()
232 CreateDicomDirChainedList( GetFileName() );
238 * \brief Set the start method to call when the parsing of the
240 * @param method Method to call
241 * @param arg Argument to pass to the method
242 * @param argDelete Argument
243 * \warning In python : the arg parameter isn't considered
245 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
246 DicomDir::Method *argDelete )
248 if( StartArg && StartMethodArgDelete )
250 StartMethodArgDelete( StartArg );
253 StartMethod = method;
255 StartMethodArgDelete = argDelete;
260 * \brief Set the method to delete the argument
261 * The argument is destroyed when the method is changed or when the
263 * @param method Method to call to delete the argument
265 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
267 StartMethodArgDelete = method;
272 * \brief Set the progress method to call when the parsing of the
274 * @param method Method to call
275 * @param arg Argument to pass to the method
276 * @param argDelete Argument
277 * \warning In python : the arg parameter isn't considered
279 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
280 DicomDir::Method *argDelete )
282 if( ProgressArg && ProgressMethodArgDelete )
284 ProgressMethodArgDelete( ProgressArg );
287 ProgressMethod = method;
289 ProgressMethodArgDelete = argDelete;
294 * \brief Set the method to delete the argument
295 * The argument is destroyed when the method is changed or when the
297 * @param method Method to call to delete the argument
299 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
301 ProgressMethodArgDelete = method;
306 * \brief Set the end method to call when the parsing of the directory ends
307 * @param method Method to call
308 * @param arg Argument to pass to the method
309 * @param argDelete Argument
310 * \warning In python : the arg parameter isn't considered
312 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
313 DicomDir::Method *argDelete )
315 if( EndArg && EndMethodArgDelete )
317 EndMethodArgDelete( EndArg );
322 EndMethodArgDelete = argDelete;
327 * \brief Set the method to delete the argument
328 * The argument is destroyed when the method is changed or when
329 * the class is destroyed
330 * @param method Method to call to delete the argument
332 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
334 EndMethodArgDelete = method;
339 * \brief writes on disc a DICOMDIR
340 * \ warning does NOT add the missing elements in the header :
341 * it's up to the user doing it !
342 * \todo : to be re-written using the DICOMDIR tree-like structure
343 * *not* the chained list
344 * (does NOT exist if the DICOMDIR is user-forged !)
345 * @param fileName file to be written to
346 * @return false only when fail to open
349 bool DicomDir::WriteDicomDir(std::string const &fileName)
352 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
353 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
355 std::ofstream *fp = new std::ofstream(fileName.c_str(),
356 std::ios::out | std::ios::binary);
359 gdcmVerboseMacro("Failed to open(write) File: " << fileName.c_str());
363 char filePreamble[128];
364 memset(filePreamble, 0, 128);
365 fp->write(filePreamble, 128); //FIXME
366 binary_write( *fp, "DICM");
368 DicomDirMeta *ptrMeta = GetDicomDirMeta();
369 ptrMeta->WriteContent(fp, ExplicitVR);
371 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
374 binary_write(*fp, sq[i]);
377 for(ListDicomDirPatient::iterator cc = Patients.begin();
378 cc != Patients.end();
381 (*cc)->WriteContent( fp, ExplicitVR );
384 // force writing Sequence Delimitation Item
387 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
396 //-----------------------------------------------------------------------------
401 * \brief create a Document-like chained list from a root Directory
402 * @param path entry point of the tree-like structure
404 void DicomDir::CreateDicomDirChainedList(std::string const & path)
407 DirList fileList(path,1); // gets recursively the file list
408 unsigned int count = 0;
412 for( DirList::iterator it = fileList.begin();
413 it != fileList.end();
416 Progress = (float)(count+1)/(float)fileList.size();
417 CallProgressMethod();
423 header = new Header( it->c_str() );
426 gdcmVerboseMacro( "Failure in new Header " << it->c_str() );
430 if( header->IsReadable() )
432 // Add the file header to the chained list:
433 list.push_back(header);
434 gdcmVerboseMacro( "Readable " << it->c_str() );
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);
450 for(VectDocument::iterator itDoc=list.begin();
454 delete dynamic_cast<Header *>(*itDoc);
460 * \brief adds *the* Meta to a partially created DICOMDIR
463 DicomDirMeta * DicomDir::NewMeta()
465 DicomDirMeta *m = new DicomDirMeta();
467 if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
469 TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
470 lastOneButSequence --;
471 // ALL the 'out of Sequence' Tags belong to Meta Elems
472 // (we skip 0004|1220 [Directory record sequence] )
473 for ( TagDocEntryHT::iterator cc = TagHT.begin();
474 cc != lastOneButSequence;
477 m->AddEntry( cc->second );
480 else // after root directory parsing
482 ListDicomDirMetaElem const &elemList =
483 Global::GetDicomDirElements()->GetDicomDirMetaElements();
484 m->FillObject(elemList);
486 m->SetSQItemNumber(0); // To avoid further missprinting
491 * \brief adds a new Patient (with the basic elements) to a partially created DICOMDIR
493 DicomDirPatient *DicomDir::NewPatient()
495 ListDicomDirPatientElem::const_iterator it;
496 uint16_t tmpGr,tmpEl;
497 DictEntry *dictEntry;
500 ListDicomDirPatientElem const & elemList =
501 Global::GetDicomDirElements()->GetDicomDirPatientElements();
502 DicomDirPatient *p = new DicomDirPatient();
504 // for all the DicomDirPatient Elements
505 for( it = elemList.begin(); it != elemList.end(); ++it )
509 dictEntry = GetPubDict()->GetDictEntry(tmpGr, tmpEl);
510 entry = new ValEntry( dictEntry );
511 entry->SetOffset(0); // just to avoid further missprinting
512 entry->SetValue( it->Value );
514 p->AddEntry( entry );
517 Patients.push_front( p );
523 * \brief adds to the HTable
524 * the Entries (Dicom Elements) corresponding to the given type
525 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
526 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
527 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
528 * @param header Header of the current file
530 void DicomDir::SetElement(std::string const &path, DicomDirType type,
533 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
534 ListDicomDirElem::const_iterator it;
535 uint16_t tmpGr, tmpEl;
536 DictEntry *dictEntry;
543 case GDCM_DICOMDIR_IMAGE:
544 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
545 si = new DicomDirImage();
546 if( !AddDicomDirImageToEnd(static_cast<DicomDirImage *>(si)) )
548 gdcmVerboseMacro( "Add DicomDirImageToEnd failed");
551 case GDCM_DICOMDIR_SERIE:
552 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
553 si = new DicomDirSerie();
554 if( !AddDicomDirSerieToEnd(static_cast<DicomDirSerie *>(si)) )
556 gdcmVerboseMacro( "Add DicomDirSerieToEnd failed");
559 case GDCM_DICOMDIR_STUDY:
560 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
561 si = new DicomDirStudy();
562 if( !AddDicomDirStudyToEnd(static_cast<DicomDirStudy *>(si)) )
564 gdcmVerboseMacro( "Add DicomDirStudyToEnd failed");
567 case GDCM_DICOMDIR_PATIENT:
568 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
569 si = new DicomDirPatient();
570 if( !AddDicomDirPatientToEnd(static_cast<DicomDirPatient *>(si)) )
572 gdcmVerboseMacro( "Add DicomDirPatientToEnd failed");
575 case GDCM_DICOMDIR_META:
576 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
577 si = new DicomDirMeta();
580 gdcmVerboseMacro( "MetaElements already exist, they will be destroyed");
583 MetaElems = static_cast<DicomDirMeta *>(si);
588 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
589 // to avoid further troubles
590 // imageElem 0008 1140 "" // Referenced Image Sequence
591 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
592 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
593 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
594 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
595 // for all the relevant elements found in their own spot of the DicomDir.dic
596 // FIXME : troubles found when it's a SeqEntry
598 for( it = elemList.begin(); it != elemList.end(); ++it)
602 dictEntry = GetPubDict()->GetDictEntry(tmpGr, tmpEl);
604 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
606 entry->SetOffset(0); // just to avoid further missprinting
610 // NULL when we Build Up (ex nihilo) a DICOMDIR
611 // or when we add the META elems
612 val = header->GetEntry(tmpGr, tmpEl);
619 if( val == GDCM_UNFOUND)
621 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
623 // force to the *end* File Name
624 val = Util::GetName( path );
626 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
628 if( header->GetFileName().substr(0, path.length()) != path )
630 gdcmVerboseMacro( "The base path of file name is incorrect");
631 val = header->GetFileName();
635 val = &(header->GetFileName().c_str()[path.length()]);
645 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
649 entry->SetValue( val ); // troubles expected when vr=SQ ...
651 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
653 std::cout << "GDCM_DICOMDIR_META ?!? should never print that"
660 //-----------------------------------------------------------------------------
662 * \brief CallStartMethod
664 void DicomDir::CallStartMethod()
670 StartMethod( StartArg );
674 //-----------------------------------------------------------------------------
677 * \brief CallProgressMethod
679 void DicomDir::CallProgressMethod()
683 ProgressMethod( ProgressArg );
687 //-----------------------------------------------------------------------------
690 * \brief CallEndMethod
692 void DicomDir::CallEndMethod()
701 //-----------------------------------------------------------------------------
705 * \brief create a 'DicomDir' from a DICOMDIR Header
707 void DicomDir::CreateDicomDir()
709 // The list is parsed.
710 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
711 // 1 - we save the beginning iterator
712 // 2 - we continue to parse
713 // 3 - we find an other tag
714 // + we create the object for the precedent tag
717 // Directory record sequence
718 DocEntry *e = GetDocEntry(0x0004, 0x1220);
721 gdcmVerboseMacro( "NO Directory record sequence (0x0004,0x1220)");
722 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
726 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
729 gdcmVerboseMacro( "No SeqEntry present");
730 // useless : (0x0004,0x1220) IS a Sequence !
734 DicomDirType type; // = DicomDir::GDCM_DICOMDIR_META;
735 MetaElems = NewMeta();
737 ListSQItem listItems = s->GetSQItems();
742 for( ListSQItem::iterator i = listItems.begin();
743 i !=listItems.end(); ++i )
745 d = (*i)->GetDocEntry(0x0004, 0x1430); // Directory Record Type
746 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
748 v = valEntry->GetValue();
752 gdcmVerboseMacro( "Not a ValEntry.");
756 if( v == "PATIENT " )
758 si = new DicomDirPatient();
759 AddDicomDirPatientToEnd( static_cast<DicomDirPatient *>(si) );
760 type = DicomDir::GDCM_DICOMDIR_PATIENT;
762 else if( v == "STUDY " )
764 si = new DicomDirStudy();
765 AddDicomDirStudyToEnd( static_cast<DicomDirStudy *>(si) );
766 type = DicomDir::GDCM_DICOMDIR_STUDY;
768 else if( v == "SERIES" )
770 si = new DicomDirSerie();
771 AddDicomDirSerieToEnd( static_cast<DicomDirSerie *>(si) );
772 type = DicomDir::GDCM_DICOMDIR_SERIE;
774 else if( v == "IMAGE " )
776 si = new DicomDirImage();
777 AddDicomDirImageToEnd( static_cast<DicomDirImage *>(si) );
778 type = DicomDir::GDCM_DICOMDIR_IMAGE;
782 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
783 // neither an 'IMAGE' SQItem. Skip to next item.
793 * \brief Well ... there is only one occurence
795 bool DicomDir::AddDicomDirMeta()
801 MetaElems = new DicomDirMeta();
807 * \brief AddDicomDirPatientToEnd
808 * @param dd SQ Item to enqueue to the DicomPatient chained List
810 bool DicomDir::AddDicomDirPatientToEnd(DicomDirPatient *dd)
812 Patients.push_back(dd);
818 * \brief AddDicomDirStudyToEnd
819 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
821 bool DicomDir::AddDicomDirStudyToEnd(DicomDirStudy *dd)
823 if( Patients.size() > 0 )
825 ListDicomDirPatient::iterator itp = Patients.end();
827 (*itp)->AddDicomDirStudy(dd);
835 * \brief AddDicomDirSerieToEnd
836 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
838 bool DicomDir::AddDicomDirSerieToEnd(DicomDirSerie *dd)
840 if( Patients.size() > 0 )
842 ListDicomDirPatient::iterator itp = Patients.end();
845 if( (*itp)->GetDicomDirStudies().size() > 0 )
847 ListDicomDirStudy::const_iterator itst =
848 (*itp)->GetDicomDirStudies().end();
850 (*itst)->AddDicomDirSerie(dd);
859 * \brief AddDicomDirImageToEnd
860 * @param dd SQ Item to enqueue to the DicomDirImage chained List
862 bool DicomDir::AddDicomDirImageToEnd(DicomDirImage *dd)
864 if( Patients.size() > 0 )
866 ListDicomDirPatient::iterator itp = Patients.end();
869 if( (*itp)->GetDicomDirStudies().size() > 0 )
871 ListDicomDirStudy::const_iterator itst =
872 (*itp)->GetDicomDirStudies().end();
875 if( (*itst)->GetDicomDirSeries().size() > 0 )
877 ListDicomDirSerie::const_iterator its = (*itst)->GetDicomDirSeries().end();
879 (*its)->AddDicomDirImage(dd);
889 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
890 * @param path path of the root directory
891 * @param list chained list of Headers
893 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
898 std::string patPrevName = "", patPrevID = "";
899 std::string studPrevInstanceUID = "", studPrevID = "";
900 std::string serPrevInstanceUID = "", serPrevID = "";
902 std::string patCurName, patCurID;
903 std::string studCurInstanceUID, studCurID;
904 std::string serCurInstanceUID, serCurID;
907 for( VectDocument::const_iterator it = list.begin();
908 it != list.end(); ++it )
910 // get the current file characteristics
911 patCurName = (*it)->GetEntry(0x0010,0x0010);
912 patCurID = (*it)->GetEntry(0x0010,0x0011);
913 studCurInstanceUID = (*it)->GetEntry(0x0020,0x000d);
914 studCurID = (*it)->GetEntry(0x0020,0x0010);
915 serCurInstanceUID = (*it)->GetEntry(0x0020,0x000e);
916 serCurID = (*it)->GetEntry(0x0020,0x0011);
918 if( patCurName != patPrevName || patCurID != patPrevID || first )
920 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
924 // if new Study Deal with 'STUDY' Elements
925 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
928 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
932 // if new Serie Deal with 'SERIE' Elements
933 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
936 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
940 // Always Deal with 'IMAGE' Elements
941 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
943 patPrevName = patCurName;
944 patPrevID = patCurID;
945 studPrevInstanceUID = studCurInstanceUID;
946 studPrevID = studCurID;
947 serPrevInstanceUID = serCurInstanceUID;
948 serPrevID = serCurID;
955 * \brief Move the content of the src SQItem to the dst SQItem
956 * Only DocEntry's are moved
959 void DicomDir::MoveSQItem(SQItem *dst,SQItem *src)
964 entry = src->GetNextEntry();
967 src->RemoveEntryNoDestroy(entry);
968 dst->AddEntry(entry);
971 entry = src->GetNextEntry();
977 * \brief compares two dgcmHeaders
979 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
981 return *header1 < *header2;
983 } // end namespace gdcm
985 //-----------------------------------------------------------------------------