1 /*=========================================================================
4 Module: $RCSfile: gdcmDicomDir.cxx,v $
6 Date: $Date: 2005/01/13 09:46:54 $
7 Version: $Revision: 1.99 $
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( !Document::IsReadable() )
202 if( Patients.size() <= 0 )
211 * \brief Sets all fields to NULL
214 void DicomDir::Initialize()
217 ProgressMethod = NULL;
219 StartMethodArgDelete = NULL;
220 ProgressMethodArgDelete = NULL;
221 EndMethodArgDelete = NULL;
235 * \brief fills the whole structure, starting from a root Directory
237 void DicomDir::ParseDirectory()
239 CreateDicomDirChainedList( GetFileName() );
245 * \brief Set the start method to call when the parsing of the
247 * @param method Method to call
248 * @param arg Argument to pass to the method
249 * @param argDelete Argument
250 * \warning In python : the arg parameter isn't considered
252 void DicomDir::SetStartMethod( DicomDir::Method *method, void *arg,
253 DicomDir::Method *argDelete )
255 if( StartArg && StartMethodArgDelete )
257 StartMethodArgDelete( StartArg );
260 StartMethod = method;
262 StartMethodArgDelete = argDelete;
267 * \brief Set the method to delete the argument
268 * The argument is destroyed when the method is changed or when the
270 * @param method Method to call to delete the argument
272 void DicomDir::SetStartMethodArgDelete( DicomDir::Method *method )
274 StartMethodArgDelete = method;
279 * \brief Set the progress method to call when the parsing of the
281 * @param method Method to call
282 * @param arg Argument to pass to the method
283 * @param argDelete Argument
284 * \warning In python : the arg parameter isn't considered
286 void DicomDir::SetProgressMethod( DicomDir::Method *method, void *arg,
287 DicomDir::Method *argDelete )
289 if( ProgressArg && ProgressMethodArgDelete )
291 ProgressMethodArgDelete( ProgressArg );
294 ProgressMethod = method;
296 ProgressMethodArgDelete = argDelete;
301 * \brief Set the method to delete the argument
302 * The argument is destroyed when the method is changed or when the
304 * @param method Method to call to delete the argument
306 void DicomDir::SetProgressMethodArgDelete( DicomDir::Method *method )
308 ProgressMethodArgDelete = method;
313 * \brief Set the end method to call when the parsing of the directory ends
314 * @param method Method to call
315 * @param arg Argument to pass to the method
316 * @param argDelete Argument
317 * \warning In python : the arg parameter isn't considered
319 void DicomDir::SetEndMethod( DicomDir::Method *method, void *arg,
320 DicomDir::Method *argDelete )
322 if( EndArg && EndMethodArgDelete )
324 EndMethodArgDelete( EndArg );
329 EndMethodArgDelete = argDelete;
334 * \brief Set the method to delete the argument
335 * The argument is destroyed when the method is changed or when
336 * the class is destroyed
337 * @param method Method to call to delete the argument
339 void DicomDir::SetEndMethodArgDelete( DicomDir::Method *method )
341 EndMethodArgDelete = method;
346 * \brief writes on disc a DICOMDIR
347 * \ warning does NOT add the missing elements in the header :
348 * it's up to the user doing it !
349 * \todo : to be re-written using the DICOMDIR tree-like structure
350 * *not* the chained list
351 * (does NOT exist if the DICOMDIR is user-forged !)
352 * @param fileName file to be written to
353 * @return false only when fail to open
356 bool DicomDir::WriteDicomDir(std::string const &fileName)
359 uint16_t sq[4] = { 0x0004, 0x1220, 0xffff, 0xffff };
360 uint16_t sqt[4]= { 0xfffe, 0xe0dd, 0xffff, 0xffff };
362 std::ofstream *fp = new std::ofstream(fileName.c_str(),
363 std::ios::out | std::ios::binary);
366 gdcmVerboseMacro("Failed to open(write) File: " << fileName.c_str());
370 char filePreamble[128];
371 memset(filePreamble, 0, 128);
372 fp->write(filePreamble, 128); //FIXME
373 binary_write( *fp, "DICM");
375 DicomDirMeta *ptrMeta = GetDicomDirMeta();
376 ptrMeta->WriteContent(fp, ExplicitVR);
378 // force writing 0004|1220 [SQ ], that CANNOT exist within DicomDirMeta
381 binary_write(*fp, sq[i]);
384 for(ListDicomDirPatient::iterator cc = Patients.begin();
385 cc != Patients.end();
388 (*cc)->WriteContent( fp, ExplicitVR );
391 // force writing Sequence Delimitation Item
394 binary_write(*fp, sqt[i]); // fffe e0dd ffff ffff
403 //-----------------------------------------------------------------------------
408 * \brief create a Document-like chained list from a root Directory
409 * @param path entry point of the tree-like structure
411 void DicomDir::CreateDicomDirChainedList(std::string const & path)
414 DirList fileList(path,1); // gets recursively the file list
415 unsigned int count = 0;
419 for( DirList::iterator it = fileList.begin();
420 it != fileList.end();
423 Progress = (float)(count+1)/(float)fileList.size();
424 CallProgressMethod();
430 header = new Header( it->c_str() );
433 gdcmVerboseMacro( "Failure in new Header " << it->c_str() );
437 if( header->IsReadable() )
439 // Add the file header 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 = fileList.GetDirName();
453 //for each Header 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<Header *>(*itDoc);
467 * \brief adds *the* Meta to a partially created DICOMDIR
470 DicomDirMeta * DicomDir::NewMeta()
472 DicomDirMeta *m = new DicomDirMeta();
474 if ( TagHT.begin() != TagHT.end() ) // after Document Parsing
476 TagDocEntryHT::iterator lastOneButSequence = TagHT.end();
477 lastOneButSequence --;
478 // ALL the 'out of Sequence' Tags belong to Meta Elems
479 // (we skip 0004|1220 [Directory record sequence] )
480 for ( TagDocEntryHT::iterator cc = TagHT.begin();
481 cc != lastOneButSequence;
484 m->AddEntry( cc->second );
487 else // after root directory parsing
489 ListDicomDirMetaElem const &elemList =
490 Global::GetDicomDirElements()->GetDicomDirMetaElements();
491 m->FillObject(elemList);
493 m->SetSQItemNumber(0); // To avoid further missprinting
498 * \brief adds a new Patient (with the basic elements) to a partially created DICOMDIR
500 DicomDirPatient *DicomDir::NewPatient()
502 ListDicomDirPatientElem::const_iterator it;
503 uint16_t tmpGr,tmpEl;
504 DictEntry *dictEntry;
507 ListDicomDirPatientElem const & elemList =
508 Global::GetDicomDirElements()->GetDicomDirPatientElements();
509 DicomDirPatient *p = new DicomDirPatient();
511 // for all the DicomDirPatient Elements
512 for( it = elemList.begin(); it != elemList.end(); ++it )
516 dictEntry = GetPubDict()->GetDictEntry(tmpGr, tmpEl);
517 entry = new ValEntry( dictEntry );
518 entry->SetOffset(0); // just to avoid further missprinting
519 entry->SetValue( it->Value );
521 p->AddEntry( entry );
524 Patients.push_front( p );
530 * \brief adds to the HTable
531 * the Entries (Dicom Elements) corresponding to the given type
532 * @param path full path file name (only used when type = GDCM_DICOMDIR_IMAGE
533 * @param type DicomDirObject type to create (GDCM_DICOMDIR_PATIENT,
534 * GDCM_DICOMDIR_STUDY, GDCM_DICOMDIR_SERIE ...)
535 * @param header Header of the current file
537 void DicomDir::SetElement(std::string const &path, DicomDirType type,
540 ListDicomDirElem elemList; //FIXME this is going to be a by copy operation
541 ListDicomDirElem::const_iterator it;
542 uint16_t tmpGr, tmpEl;
543 DictEntry *dictEntry;
550 case GDCM_DICOMDIR_IMAGE:
551 elemList = Global::GetDicomDirElements()->GetDicomDirImageElements();
552 si = new DicomDirImage();
553 if( !AddDicomDirImageToEnd(static_cast<DicomDirImage *>(si)) )
555 gdcmVerboseMacro( "Add DicomDirImageToEnd failed");
558 case GDCM_DICOMDIR_SERIE:
559 elemList = Global::GetDicomDirElements()->GetDicomDirSerieElements();
560 si = new DicomDirSerie();
561 if( !AddDicomDirSerieToEnd(static_cast<DicomDirSerie *>(si)) )
563 gdcmVerboseMacro( "Add DicomDirSerieToEnd failed");
566 case GDCM_DICOMDIR_STUDY:
567 elemList = Global::GetDicomDirElements()->GetDicomDirStudyElements();
568 si = new DicomDirStudy();
569 if( !AddDicomDirStudyToEnd(static_cast<DicomDirStudy *>(si)) )
571 gdcmVerboseMacro( "Add DicomDirStudyToEnd failed");
574 case GDCM_DICOMDIR_PATIENT:
575 elemList = Global::GetDicomDirElements()->GetDicomDirPatientElements();
576 si = new DicomDirPatient();
577 if( !AddDicomDirPatientToEnd(static_cast<DicomDirPatient *>(si)) )
579 gdcmVerboseMacro( "Add DicomDirPatientToEnd failed");
582 case GDCM_DICOMDIR_META:
583 elemList = Global::GetDicomDirElements()->GetDicomDirMetaElements();
584 si = new DicomDirMeta();
587 gdcmVerboseMacro( "MetaElements already exist, they will be destroyed");
590 MetaElems = static_cast<DicomDirMeta *>(si);
595 // removed all the seems-to-be-useless stuff about Referenced Image Sequence
596 // to avoid further troubles
597 // imageElem 0008 1140 "" // Referenced Image Sequence
598 // imageElem fffe e000 "" // 'no length' item : length to be set to 0xffffffff later
599 // imageElem 0008 1150 "" // Referenced SOP Class UID : to be set/forged later
600 // imageElem 0008 1155 "" // Referenced SOP Instance UID : to be set/forged later
601 // imageElem fffe e00d "" // Item delimitation : length to be set to ZERO later
602 // for all the relevant elements found in their own spot of the DicomDir.dic
603 // FIXME : troubles found when it's a SeqEntry
605 for( it = elemList.begin(); it != elemList.end(); ++it)
609 dictEntry = GetPubDict()->GetDictEntry(tmpGr, tmpEl);
611 entry = new ValEntry( dictEntry ); // Be sure it's never a BinEntry !
613 entry->SetOffset(0); // just to avoid further missprinting
617 // NULL when we Build Up (ex nihilo) a DICOMDIR
618 // or when we add the META elems
619 val = header->GetEntry(tmpGr, tmpEl);
626 if( val == GDCM_UNFOUND)
628 if( tmpGr == 0x0004 && tmpEl == 0x1130 ) // File-set ID
630 // force to the *end* File Name
631 val = Util::GetName( path );
633 else if( tmpGr == 0x0004 && tmpEl == 0x1500 ) // Only used for image
635 if( header->GetFileName().substr(0, path.length()) != path )
637 gdcmVerboseMacro( "The base path of file name is incorrect");
638 val = header->GetFileName();
642 val = &(header->GetFileName().c_str()[path.length()]);
652 if ( header->GetEntryLength(tmpGr,tmpEl) == 0 )
656 entry->SetValue( val ); // troubles expected when vr=SQ ...
658 if ( type == GDCM_DICOMDIR_META ) // fusible : should never print !
660 std::cout << "GDCM_DICOMDIR_META ?!? should never print that"
667 //-----------------------------------------------------------------------------
669 * \brief CallStartMethod
671 void DicomDir::CallStartMethod()
677 StartMethod( StartArg );
681 //-----------------------------------------------------------------------------
684 * \brief CallProgressMethod
686 void DicomDir::CallProgressMethod()
690 ProgressMethod( ProgressArg );
694 //-----------------------------------------------------------------------------
697 * \brief CallEndMethod
699 void DicomDir::CallEndMethod()
708 //-----------------------------------------------------------------------------
712 * \brief create a 'DicomDir' from a DICOMDIR Header
714 void DicomDir::CreateDicomDir()
716 // The list is parsed.
717 // When a DicomDir tag ("PATIENT", "STUDY", "SERIE", "IMAGE") is found :
718 // 1 - we save the beginning iterator
719 // 2 - we continue to parse
720 // 3 - we find an other tag
721 // + we create the object for the precedent tag
724 // Directory record sequence
725 DocEntry *e = GetDocEntry(0x0004, 0x1220);
728 gdcmVerboseMacro( "NO Directory record sequence (0x0004,0x1220)");
729 /// \todo FIXME: what to do when the parsed file IS NOT a DICOMDIR file ?
733 SeqEntry *s = dynamic_cast<SeqEntry *>(e);
736 gdcmVerboseMacro( "No SeqEntry present");
737 // useless : (0x0004,0x1220) IS a Sequence !
741 MetaElems = NewMeta();
743 ListSQItem listItems = s->GetSQItems();
748 for( ListSQItem::iterator i = listItems.begin();
749 i !=listItems.end(); ++i )
751 d = (*i)->GetDocEntry(0x0004, 0x1430); // Directory Record Type
752 if ( ValEntry* valEntry = dynamic_cast<ValEntry *>(d) )
754 v = valEntry->GetValue();
758 gdcmVerboseMacro( "Not a ValEntry.");
762 if( v == "PATIENT " )
764 si = new DicomDirPatient();
765 AddDicomDirPatientToEnd( static_cast<DicomDirPatient *>(si) );
767 else if( v == "STUDY " )
769 si = new DicomDirStudy();
770 AddDicomDirStudyToEnd( static_cast<DicomDirStudy *>(si) );
772 else if( v == "SERIES" )
774 si = new DicomDirSerie();
775 AddDicomDirSerieToEnd( static_cast<DicomDirSerie *>(si) );
777 else if( v == "IMAGE " )
779 si = new DicomDirImage();
780 AddDicomDirImageToEnd( static_cast<DicomDirImage *>(si) );
784 // It was not a 'PATIENT', nor a 'STUDY', nor a 'SERIE',
785 // neither an 'IMAGE' SQItem. Skip to next item.
795 * \brief Well ... there is only one occurence
797 bool DicomDir::AddDicomDirMeta()
803 MetaElems = new DicomDirMeta();
809 * \brief AddDicomDirPatientToEnd
810 * @param dd SQ Item to enqueue to the DicomPatient chained List
812 bool DicomDir::AddDicomDirPatientToEnd(DicomDirPatient *dd)
814 Patients.push_back(dd);
820 * \brief AddDicomDirStudyToEnd
821 * @param dd SQ Item to enqueue to the DicomDirStudy chained List
823 bool DicomDir::AddDicomDirStudyToEnd(DicomDirStudy *dd)
825 if( Patients.size() > 0 )
827 ListDicomDirPatient::iterator itp = Patients.end();
829 (*itp)->AddDicomDirStudy(dd);
837 * \brief AddDicomDirSerieToEnd
838 * @param dd SQ Item to enqueue to the DicomDirSerie chained List
840 bool DicomDir::AddDicomDirSerieToEnd(DicomDirSerie *dd)
842 if( Patients.size() > 0 )
844 ListDicomDirPatient::iterator itp = Patients.end();
847 if( (*itp)->GetDicomDirStudies().size() > 0 )
849 ListDicomDirStudy::const_iterator itst =
850 (*itp)->GetDicomDirStudies().end();
852 (*itst)->AddDicomDirSerie(dd);
861 * \brief AddDicomDirImageToEnd
862 * @param dd SQ Item to enqueue to the DicomDirImage chained List
864 bool DicomDir::AddDicomDirImageToEnd(DicomDirImage *dd)
866 if( Patients.size() > 0 )
868 ListDicomDirPatient::iterator itp = Patients.end();
871 if( (*itp)->GetDicomDirStudies().size() > 0 )
873 ListDicomDirStudy::const_iterator itst =
874 (*itp)->GetDicomDirStudies().end();
877 if( (*itst)->GetDicomDirSeries().size() > 0 )
879 ListDicomDirSerie::const_iterator its = (*itst)->GetDicomDirSeries().end();
881 (*its)->AddDicomDirImage(dd);
891 * \brief for each Header of the chained list, add/update the Patient/Study/Serie/Image info
892 * @param path path of the root directory
893 * @param list chained list of Headers
895 void DicomDir::SetElements(std::string const & path, VectDocument const &list)
900 std::string patPrevName = "", patPrevID = "";
901 std::string studPrevInstanceUID = "", studPrevID = "";
902 std::string serPrevInstanceUID = "", serPrevID = "";
904 std::string patCurName, patCurID;
905 std::string studCurInstanceUID, studCurID;
906 std::string serCurInstanceUID, serCurID;
909 for( VectDocument::const_iterator it = list.begin();
910 it != list.end(); ++it )
912 // get the current file characteristics
913 patCurName = (*it)->GetEntry(0x0010,0x0010);
914 patCurID = (*it)->GetEntry(0x0010,0x0011);
915 studCurInstanceUID = (*it)->GetEntry(0x0020,0x000d);
916 studCurID = (*it)->GetEntry(0x0020,0x0010);
917 serCurInstanceUID = (*it)->GetEntry(0x0020,0x000e);
918 serCurID = (*it)->GetEntry(0x0020,0x0011);
920 if( patCurName != patPrevName || patCurID != patPrevID || first )
922 SetElement(path, GDCM_DICOMDIR_PATIENT, *it);
926 // if new Study Deal with 'STUDY' Elements
927 if( studCurInstanceUID != studPrevInstanceUID || studCurID != studPrevID
930 SetElement(path, GDCM_DICOMDIR_STUDY, *it);
934 // if new Serie Deal with 'SERIE' Elements
935 if( serCurInstanceUID != serPrevInstanceUID || serCurID != serPrevID
938 SetElement(path, GDCM_DICOMDIR_SERIE, *it);
942 // Always Deal with 'IMAGE' Elements
943 SetElement(path, GDCM_DICOMDIR_IMAGE, *it);
945 patPrevName = patCurName;
946 patPrevID = patCurID;
947 studPrevInstanceUID = studCurInstanceUID;
948 studPrevID = studCurID;
949 serPrevInstanceUID = serCurInstanceUID;
950 serPrevID = serCurID;
957 * \brief Move the content of the src SQItem to the dst SQItem
958 * Only DocEntry's are moved
961 void DicomDir::MoveSQItem(SQItem *dst,SQItem *src)
966 entry = src->GetNextEntry();
969 src->RemoveEntryNoDestroy(entry);
970 dst->AddEntry(entry);
973 entry = src->GetNextEntry();
979 * \brief compares two dgcmHeaders
981 bool DicomDir::HeaderLessThan(Document *header1, Document *header2)
983 return *header1 < *header2;
985 } // end namespace gdcm
987 //-----------------------------------------------------------------------------