Debian Codegraph @

src/Base/Writer.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /***************************************************************************
4 * Copyright (c) 2011 Jürgen Riegel <[email protected]> *
5 * *
6 * This file is part of the FreeCAD CAx development system. *
7 * *
8 * This library is free software; you can redistribute it and/or *
9 * modify it under the terms of the GNU Library General Public *
10 * License as published by the Free Software Foundation; either *
11 * version 2 of the License, or (at your option) any later version. *
12 * *
13 * This library is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU Library General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Library General Public *
19 * License along with this library; see the file COPYING.LIB. If not, *
20 * write to the Free Software Foundation, Inc., 59 Temple Place, *
21 * Suite 330, Boston, MA 02111-1307, USA *
22 * *
23 ***************************************************************************/
24
25
26 #include <memory>
27 #include <set>
28 #include <vector>
29 #include <string>
30
31 #include <limits>
32 #include <locale>
33 #include <iomanip>
34
35 #include "Writer.h"
36 #include "Base64.h"
37 #include "Base64Filter.h"
38 #include "Exception.h"
39 #include "FileInfo.h"
40 #include "Persistence.h"
41 #include "Stream.h"
42 #include "Tools.h"
43
44 #include <boost/iostreams/filtering_stream.hpp>
45 #include <zipios++/zipinputstream.h>
46
47 using namespace Base;
48
49 // boost iostream filter to escape ']]>' in text file saved into CDATA section.
50 // It does not check if the character is valid utf8 or not.
51 struct cdata_filter
52 {
53
54 using char_type = char;
55 using category = boost::iostreams::output_filter_tag;
56
57 template<typename Device>
58 inline bool put(Device& dev, char ch)
59 {
60 switch (state) {
61 case 0:
62 case 1:
63 if (ch == ']') {
64 ++state;
65 }
66 else {
67 state = 0;
68 }
69 break;
70 case 2:
71 if (ch == '>') {
72 static const char escape[] = "]]><![CDATA[";
73 boost::iostreams::write(dev, escape, sizeof(escape) - 1);
74 }
75 state = 0;
76 break;
77 }
78 return boost::iostreams::put(dev, ch);
79 }
80
81 int state = 0;
82 };
83
84 // ---------------------------------------------------------------------------
85 // Writer: Constructors and Destructor
86 // ---------------------------------------------------------------------------
87
88 Writer::Writer()
89 {
90 indBuf[0] = '\0';
91 }
92
93 Writer::~Writer() = default;
94
95 std::ostream& Writer::beginCharStream(CharStreamFormat format)
96 {
97 if (CharStream) {
98 throw Base::RuntimeError("Writer::beginCharStream(): invalid state");
99 }
100 charStreamFormat = format;
101 if (format == CharStreamFormat::Base64Encoded) {
102 CharStream = create_base64_encoder(Stream(), Base::base64DefaultBufferSize);
103 }
104 else {
105 Stream() << "<![CDATA[";
106 CharStream = std::make_unique<boost::iostreams::filtering_ostream>();
107 auto* filteredStream = dynamic_cast<boost::iostreams::filtering_ostream*>(CharStream.get());
108 filteredStream->push(cdata_filter());
109 filteredStream->push(Stream());
110 *filteredStream << std::setprecision(std::numeric_limits<double>::digits10 + 1);
111 }
112
113 checkErrNo();
114
115 return *CharStream;
116 }
117
118 std::ostream& Writer::endCharStream()
119 {
120 if (CharStream) {
121 CharStream.reset();
122 if (charStreamFormat == CharStreamFormat::Raw) {
123 Stream() << "]]>";
124 }
125 }
126
127 checkErrNo();
128
129 return Stream();
130 }
131
132 std::ostream& Writer::charStream()
133 {
134 if (!CharStream) {
135 throw Base::RuntimeError("Writer::endCharStream(): no current character stream");
136 }
137 return *CharStream;
138 }
139
140 void Writer::insertText(const std::string& str)
141 {
142 beginCharStream() << str;
143 endCharStream();
144 }
145
146 void Writer::insertAsciiFile(const char* FileName)
147 {
148 Base::FileInfo fi(FileName);
149 Base::ifstream from(fi);
150 if (!from) {
151 throw Base::FileException("Writer::insertAsciiFile() Could not open file!");
152 }
153
154 Stream() << "<![CDATA[";
155 char ch {};
156 while (from.get(ch)) {
157 Stream().put(ch);
158 }
159 Stream() << "]]>" << std::endl;
160
161 checkErrNo();
162 }
163
164 void Writer::insertBinFile(const char* FileName)
165 {
166 Base::FileInfo fi(FileName);
167 Base::ifstream from(fi, std::ios::in | std::ios::binary | std::ios::ate);
168 if (!from) {
169 throw Base::FileException("Writer::insertAsciiFile() Could not open file!");
170 }
171
172 Stream() << "<![CDATA[";
173 std::ifstream::pos_type fileSize = from.tellg();
174 from.seekg(0, std::ios::beg);
175 std::vector<unsigned char> bytes(static_cast<size_t>(fileSize));
176 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
177 from.read(reinterpret_cast<char*>(bytes.data()), fileSize);
178 Stream() << Base::base64_encode(bytes.data(), static_cast<unsigned int>(fileSize));
179 Stream() << "]]>" << std::endl;
180
181 checkErrNo();
182 }
183
184 void Writer::setForceXML(bool on)
185 {
186 forceXML = on;
187 }
188
189 bool Writer::isForceXML() const
190 {
191 return forceXML;
192 }
193
194 void Writer::setFileVersion(int version)
195 {
196 fileVersion = version;
197 }
198
199 int Writer::getFileVersion() const
200 {
201 return fileVersion;
202 }
203
204 void Writer::setMode(const std::string& mode)
205 {
206 Modes.insert(mode);
207 }
208
209 void Writer::setModes(const std::set<std::string>& modes)
210 {
211 Modes = modes;
212 }
213
214 bool Writer::getMode(const std::string& mode) const
215 {
216 std::set<std::string>::const_iterator it = Modes.find(mode);
217 return (it != Modes.end());
218 }
219
220 std::set<std::string> Writer::getModes() const
221 {
222 return Modes;
223 }
224
225 void Writer::clearMode(const std::string& mode)
226 {
227 std::set<std::string>::iterator it = Modes.find(mode);
228 if (it != Modes.end()) {
229 Modes.erase(it);
230 }
231 }
232
233 void Writer::clearModes()
234 {
235 Modes.clear();
236 }
237
238 void Writer::addError(const std::string& msg)
239 {
240 Errors.push_back(msg);
241 }
242
243 void Writer::checkErrNo()
244 {
245 switch (errno) {
246 case ENOSPC: // No space left
247 case EROFS: // Read only
248 case ENODEV: // No such device
249 case EACCES: // Access denied
250 addError(strerror(errno));
251 }
252 }
253
254 bool Writer::hasErrors() const
255 {
256 return (!Errors.empty());
257 }
258
259 void Writer::clearErrors()
260 {
261 Errors.clear();
262 }
263
264 std::vector<std::string> Writer::getErrors() const
265 {
266 return Errors;
267 }
268
269 std::string Writer::addFile(const char* Name, const Base::Persistence* Object)
270 {
271 // always check isForceXML() before requesting a file!
272 // assert(!isForceXML()); Changes introduced in 1.0 differ from LS3 (TNP), so this assertion is
273 // not valid anymore.
274
275 FileEntry temp;
276 temp.FileName = Name ? Name : "";
277 if (FileNameManager.containsName(temp.FileName)) {
278 temp.FileName = FileNameManager.makeUniqueName(temp.FileName);
279 }
280 temp.Object = Object;
281
282 FileList.push_back(temp);
283 FileNameManager.addExactName(temp.FileName);
284
285 // return the unique file name
286 return temp.FileName;
287 }
288
289 void Writer::incInd()
290 {
291 if (indent < 1020) {
292 indBuf[indent] = ' ';
293 indBuf[indent + 1] = ' ';
294 indBuf[indent + 2] = ' ';
295 indBuf[indent + 3] = ' ';
296 indBuf[indent + 4] = '\0';
297 indent += 4;
298 }
299 }
300
301 void Writer::decInd()
302 {
303 if (indent >= 4) {
304 indent -= 4;
305 }
306 else {
307 indent = 0;
308 }
309 indBuf[indent] = '\0';
310 }
311
312 void Writer::putNextEntry(const char* file, const char* obj)
313 {
314 ObjectName = obj ? obj : file;
315 }
316
317 // ----------------------------------------------------------------------------
318
319 ZipWriter::ZipWriter(const char* FileName)
320 : ZipStream(FileName)
321 {
322 ZipStream.imbue(std::locale::classic());
323 ZipStream.precision(std::numeric_limits<double>::digits10 + 1);
324 ZipStream.setf(std::ios::fixed, std::ios::floatfield);
325 }
326
327 ZipWriter::ZipWriter(std::ostream& os)
328 : ZipStream(os)
329 {
330 ZipStream.imbue(std::locale::classic());
331 ZipStream.precision(std::numeric_limits<double>::digits10 + 1);
332 ZipStream.setf(std::ios::fixed, std::ios::floatfield);
333 }
334
335 void ZipWriter::putNextEntry(const char* file, const char* obj)
336 {
337 Writer::putNextEntry(file, obj);
338
339 ZipStream.putNextEntry(file);
340
341 Writer::checkErrNo();
342 }
343
344 void ZipWriter::writeFiles()
345 {
346 // use a while loop because it is possible that while
347 // processing the files new ones can be added
348 size_t index = 0;
349 while (index < FileList.size()) {
350 FileEntry entry = FileList[index];
351 putNextEntry(entry.FileName.c_str());
352 indent = 0;
353 indBuf[0] = 0;
354 entry.Object->SaveDocFile(*this);
355 index++;
356 }
357 }
358
359 ZipWriter::~ZipWriter()
360 {
361 ZipStream.close();
362 }
363
364 // ----------------------------------------------------------------------------
365
366 FileWriter::FileWriter(const char* DirName)
367 : DirName(DirName)
368 {}
369
370 FileWriter::~FileWriter() = default;
371
372 void FileWriter::putNextEntry(const char* file, const char* obj)
373 {
374 Writer::putNextEntry(file, obj);
375
376 std::string fileName = DirName + "/" + file;
377 this->FileStream.open(fileName.c_str(), std::ios::out | std::ios::binary);
378
379 Writer::checkErrNo();
380 }
381
382 bool FileWriter::shouldWrite(const std::string& /*name*/, const Base::Persistence* /*obj*/) const
383 {
384 return true;
385 }
386
387 void FileWriter::writeFiles()
388 {
389 // use a while loop because it is possible that while
390 // processing the files new ones can be added
391 size_t index = 0;
392 this->FileStream.close();
393 while (index < FileList.size()) {
394 FileEntry entry = FileList[index];
395
396 if (shouldWrite(entry.FileName, entry.Object)) {
397 std::string filePath = entry.FileName;
398 std::string::size_type pos = 0;
399 while ((pos = filePath.find('/', pos)) != std::string::npos) {
400 std::string dirName = DirName + "/" + filePath.substr(0, pos);
401 pos++;
402 Base::FileInfo fi(dirName);
403 fi.createDirectory();
404 }
405
406 putNextEntry(entry.FileName.c_str());
407 indent = 0;
408 indBuf[0] = 0;
409 entry.Object->SaveDocFile(*this);
410 this->FileStream.close();
411 }
412
413 index++;
414 }
415
416 Writer::checkErrNo();
417 }