]> Creatis software - gdcm.git/blob - src/gdcmDocument.h
Doxygen (1.5.2) doen't want \\ref option.
[gdcm.git] / src / gdcmDocument.h
1 /*=========================================================================
2  
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.h,v $
5   Language:  C++
6   Date:      $Date: 2007/09/17 12:16:02 $
7   Version:   $Revision: 1.147 $
8  
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.
12  
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.
16  
17 =========================================================================*/
18
19 #ifndef _GDCMDOCUMENT_H_
20 #define _GDCMDOCUMENT_H_
21
22 #include "gdcmVR.h"
23 #include "gdcmDict.h"
24 #include "gdcmElementSet.h"
25 #include "gdcmException.h"
26 #include "gdcmDebug.h"  // for LEGACY
27 #include "gdcmCommandManager.h"
28
29 #include <map>
30 #include <list>
31 #include <fstream>
32
33 namespace GDCM_NAME_SPACE 
34 {
35 class SeqEntry;
36 class Dict;
37
38 //-----------------------------------------------------------------------------
39 /**
40  * \brief Derived by both gdcm::File and gdcm::DicomDir
41  */
42 class GDCM_EXPORT Document : public ElementSet
43 {
44    gdcmTypeMacro(Document);
45
46 public:
47    typedef std::list<DicomElement> ListElements;
48
49 // Loading
50    //Deprecated : use SetFileName() + Load()
51 //#ifndef GDCM_LEGACY_REMOVE 
52 //   virtual bool Load( std::string const &filename ); 
53 //#endif
54    virtual bool Load( ); 
55
56 // Dictionaries
57    Dict *GetPubDict();
58    Dict *GetShaDict();
59    bool SetShaDict(Dict *dict);
60    bool SetShaDict(DictKey const &dictName);
61
62 // Informations contained in the gdcm::Document
63    bool IsParsable();
64    virtual bool IsReadable();
65    bool IsDicomV3();
66    bool IsPapyrus();
67    FileType GetFileType();
68    std::string GetTransferSyntax();
69    /// Return the Transfer Syntax as a string
70    std::string GetTransferSyntaxName();
71
72 // Swap code
73    /// 'Swap code' accessor (see  SwapCode )
74    int GetSwapCode() { return SwapCode; }
75    
76 // File I/O
77    /// Accessor to  Filename
78    const std::string &GetFileName() const { return Filename; }
79    /// Accessor to  Filename
80    virtual void SetFileName(std::string const &fileName) 
81                    { if (Filename != fileName)
82                         Filename = fileName, IsDocumentModified = true; }
83
84    std::ifstream *OpenFile();
85    bool CloseFile();
86    void WriteContent( std::ofstream *fp, FileType type );
87
88 // Data entries
89    virtual void LoadEntryBinArea(uint16_t group, uint16_t elem);
90    virtual void LoadEntryBinArea(DataEntry *entry);
91
92    void SetMaxSizeLoadEntry(long);
93    void AddForceLoadElement(uint16_t group, uint16_t elem);
94  
95 // Ordering of Documents
96    bool operator<(Document &document);
97
98 /**
99  * \brief Sets the LoadMode as a boolean string. 
100  *        LD_NOSEQ, LD_NOSHADOW, LD_NOSHADOWSEQ
101  ... (nothing more, right now)
102  *        WARNING : before using NO_SHADOW, be sure *all* your files
103  *        contain accurate values in the 0x0000 element (if any) 
104  *        of *each* Shadow Group. The parser will fail if the size is wrong !
105  * @param   mode Load mode to be used    
106  */
107    void SetLoadMode (int mode) { if (LoadMode != mode) 
108                                      LoadMode=mode, IsDocumentModified = true; }
109
110 protected:
111 // Methods
112    // Constructor and destructor are protected to forbid end user 
113    // to instanciate from this class Document (only gdcm::File and
114    // gdcm::DicomDir are meaningfull).
115    Document();
116    virtual ~Document();
117
118    virtual void CallStartMethod();
119    virtual void CallProgressMethod();
120    virtual void CallEndMethod();
121       
122    uint16_t ReadInt16() throw ( FormatError );
123    uint32_t ReadInt32() throw ( FormatError );
124    
125    /// \brief skips bytes inside the source file
126    void     SkipBytes(uint32_t nBytes) { Fp->seekg((long)nBytes, std::ios::cur);} 
127    int ComputeGroup0002Length( );
128
129 // Variables
130    /// Refering underlying filename.
131    std::string Filename;
132
133    /// \brief Swap code gives an information on the byte order of a 
134    ///  supposed to be an int32, as it's read on disc 
135    /// (depending on the image Transfer Syntax *and* on the processor endianess)
136    /// as opposed as it should in memory to be dealt as an int32.
137    /// For instance :
138    /// - a 'Little Endian' image, read with a little endian processor
139    /// will have a SwapCode= 1234 (the order is OK; nothing to do)
140    /// - a 'Little Endian' image, read with a big endian procesor
141    /// will have a SwapCode= 4321 (the order is wrong; int32 an int16 must be
142    /// swapped)
143    /// note : values 2143, 4321, 3412 remain for the ACR-NEMA time, and
144    /// the well known 'Bad Big Endian' and 'Bad Little Endian' codes
145    int SwapCode;
146
147    ///\brief whether we already parsed group 0002 (Meta Elements)
148    bool Group0002Parsed;
149
150    ///\brief whether file has a DCM Preamble
151    bool HasDCMPreamble;
152
153    /// File Pointer, opened during Document parsing.
154    std::ifstream *Fp;
155
156    /// ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown
157    FileType Filetype;  
158
159    /// After opening the file, we read HEADER_LENGTH_TO_READ bytes.
160    static const unsigned int HEADER_LENGTH_TO_READ; 
161    /// \brief Elements whose value is longer than MAX_SIZE_LOAD_ELEMENT_VALUE
162    /// are NOT loaded.
163    static const unsigned int MAX_SIZE_LOAD_ELEMENT_VALUE;
164
165    /// User supplied list of elements to Anonymize
166    ListElements UserAnonymizeList;
167
168    /// User supplied list of elements to force Load
169    ListElements UserForceLoadList;
170
171    /// \brief Bit string integer (each one considered as a boolean)
172    ///        Bit 0 : Skip Sequences,    if possible
173    ///        Bit 1 : Skip Shadow Groups if possible
174    ///        Probabely, some more to add
175    int LoadMode;
176    
177    /// \brief Whether the gdcm::Document is already parsed/loaded :
178    /// False from the creation of the gdcm::Document untill 
179    ///   gdcm::Document:Load()
180    bool IsDocumentAlreadyLoaded; // FIXME : probabely useless now
181
182    /// Whether the gdcm::Document was modified since the last Load()
183    bool IsDocumentModified;
184
185 private:
186 // Methods
187    void Initialize();
188    bool DoTheLoadingDocumentJob();
189      
190       // System access (meaning endian related !?)
191    void ReadBegBuffer(size_t l) throw ( FormatError );
192    uint16_t SwapShort(uint16_t);
193    uint32_t SwapLong(uint32_t);
194    double SwapDouble(double);
195    /// \brief  Unswaps back the bytes of 2-bytes long integer 
196    ///         so they agree with the processor order.
197    uint16_t UnswapShort(uint16_t a) { return SwapShort(a);}
198    /// \brief  Unswaps back the bytes of 4-byte long integer 
199    ///         so they agree with the processor order.
200    uint32_t UnswapLong(uint32_t a) { return SwapLong(a);}
201    
202    // Read
203    void ParseDES(DocEntrySet *set, long offset, long l_max, bool delim_mode);
204    bool ParseSQ (SeqEntry *seq,    long offset, long l_max, bool delim_mode);
205
206    void LoadDocEntry         (DocEntry *e, bool forceLoad = false);
207    void FindDocEntryLength   (DocEntry *e) throw ( FormatError );
208    uint32_t FindDocEntryLengthOBOrOW() throw( FormatUnexpected );
209    VRKey FindDocEntryVR();
210    bool CheckDocEntryVR      (const VRKey &k);
211
212    void SkipDocEntry          (DocEntry *entry);
213    void SkipToNextDocEntry    (DocEntry *entry);
214
215    void FixDocEntryFoundLength(DocEntry *entry, uint32_t l);
216    bool IsDocEntryAnInteger   (DocEntry *entry);
217
218    bool CheckSwap();
219    void SwitchByteSwapCode();
220
221    // DocEntry related utilities
222    DocEntry *ReadNextDocEntry();
223    uint16_t GetInt16();
224    uint32_t GetInt32();
225    
226    void HandleBrokenEndian  (uint16_t &group, uint16_t &elem);
227    void HandleOutOfGroup0002(uint16_t &group, uint16_t &elem);
228    DocEntry *Backtrack(DocEntry *docEntry);
229
230
231 // Variables
232 protected:
233    /// value of the ??? for any progress bar
234    float Progress;
235    mutable bool Abort;
236    
237    /// Public dictionary used to parse this header
238    Dict *RefPubDict;
239    /// \brief Optional "shadow dictionary" (private elements) used to parse
240    /// this header
241    Dict *RefShaDict;
242
243    /// \brief Size threshold above which an element value will NOT be loaded
244    /// in memory (to avoid loading the image/volume itself). By default,
245    /// this upper bound is fixed to 1024 bytes (which might look reasonable
246    /// when one considers the definition of the various VR contents).
247    uint32_t MaxSizeLoadEntry;
248
249    /// \brief to allow any inner method to know current tag Group number 
250    uint16_t CurrentGroup;
251    /// \brief to allow any inner method to know current tag Element number 
252    uint16_t CurrentElem; 
253      
254 //  uint32_t GenerateFreeTagKeyInGroup(uint16_t group);
255 //  void BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
256 //                                  DocEntrySet *set );
257
258 private:
259    /// \brief buffer to avoid some freads
260    char BegBuffer[8];
261    char *PtrBegBuffer;
262    /// \brief to avoid time consuming ftellg
263    size_t CurrentOffsetPosition;
264    /// \brief to indicate if last supposed to be UN DataElement is not
265    ///        (according to a private Dicom dictionary) 
266    bool changeFromUN;
267    /// \brief whether an unexpected EOF was encountered
268    bool UnexpectedEOF;
269 };
270
271 } // end namespace gdcm
272
273 //-----------------------------------------------------------------------------
274 #endif