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