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