Debian Codegraph @

plugins/dm.gui/XData.cpp

raw
1 #include "XData.h"
2
3 #include "i18n.h"
4 #include "itextstream.h"
5 #include <fstream>
6 #include "os/fs.h"
7 #include "os/file.h"
8
9 namespace XData
10 {
11
12 //XData implementations:
13 //->export:
14 FileStatus XData::xport( const std::string& filename, ExporterCommand cmd )
15 {
16 fs::path Path(filename);
17
18 fs::path parent = Path.parent_path();
19
20 // Ensure the parent path exists
21 fs::create_directories(parent);
22
23 if (os::fileOrDirExists(Path.string()))
24 {
25 switch (cmd)
26 {
27 case Merge:
28 {
29 //Check if definition already exists and return DefinitionExists. If it does not, append the definition to the file.
30 std::fstream file(Path.string(), std::ios_base::in | std::ios_base::out | std::ios_base::app);
31 if (!file.is_open())
32 return OpenFailed;
33 std::stringstream ss;
34 ss << file.rdbuf();
35 std::string String = ss.str();
36 std::size_t DefPos = String.find(_name);
37 while (DefPos != std::string::npos) //A name of a XData could be contained in another XData's name. Check that...
38 {
39 char before = String[DefPos > 0 ? DefPos-1 : 0];
40 char after = String[DefPos+_name.length() < String.size() ? DefPos+_name.length() : 0];
41 if ((DefPos == 0 || before == ' ' || before == '\t' || before == '\n') && (DefPos+_name.length() == String.size() || after == ' ' || after == '\t' || after == '\n')) //other delimiters necessary?
42 {
43 _definitionStart = 0;
44 //Definition found. But we want to have it clean, so let's see how many spaces are before the definition begin.
45 while (DefPos > 0)
46 {
47 if (String[--DefPos] != ' ' && String[DefPos] != '\t' && String[DefPos] != '\n')
48 {
49 _definitionStart = DefPos+1;
50 break;
51 }
52 }
53
54 file.close();
55 return DefinitionExists;
56 }
57 DefPos = String.find(_name,DefPos+_name.length());
58 }
59 file << "\n\n\n" << generateXDataDef();
60 file.close();
61 return AllOk;
62 }
63 case MergeOverwriteExisting:
64 {
65 //Find the old definition in the target file and delete it. Append the new definition.
66 //_definitionStart has been set in the first iteration of this method.
67 std::fstream file(Path.string(), std::ios_base::in);
68 if (!file.is_open())
69 return OpenFailed;
70 std::stringstream ss;
71 ss << file.rdbuf();
72 std::string OutString = ss.str();
73 file.close();
74 std::size_t DefLength = getDefLength(OutString.substr(_definitionStart));
75 if (DefLength == 0) //If the definitionlength can't be obtained, the merge fails.
76 return MergeFailed;
77 OutString.erase(_definitionStart, DefLength);
78 std::string insString = std::string( (_definitionStart != 0) ? "\n\n\n" : "" ) //No new lines in the first line
79 + generateXDataDef()
80 + std::string( (_definitionStart == OutString.size()) ? "" : "\n\n\n" ); //No new lines at the end of file
81 OutString.insert(_definitionStart, insString);
82 file.open(Path.string(), std::ios_base::out | std::ios_base::trunc);
83 if (!file.is_open())
84 return OpenFailed;
85 file << OutString;
86 file.close();
87 return AllOk;
88 }
89 case Overwrite:
90 {
91 //Warn if the target file contains multiple definitions: return MultipleDefinitions.
92 //Warn if the definition in the target file does not match the current definition: return DefinitionMisMatch
93 //else overwrite existing file.
94 std::string DefName;
95 std::ifstream file(Path.string(), std::ios_base::in);
96 if (!file.is_open())
97 return OpenFailed;
98 try { DefName = getDefinitionNameFromXD(file); }
99 catch (...)
100 {
101 rConsoleError() << "[XData::xport] Syntax error in file " << filename
102 << ". Overwriting the file..." << std::endl;
103 break;
104 }
105 if (DefName == _name) //Definition will be overwritten...
106 break;
107 else if (DefName == "") //MultipleDefinitions exist
108 return MultipleDefinitions;
109 return DefinitionMismatch;
110 }
111 case OverwriteMultDef:
112 //Replace the file no matter what.
113 break;
114 default: return FileExists;
115 }
116 }
117
118 //Write the definition into the file.
119 std::ofstream file(Path.string(), std::ios_base::out | std::ios_base::trunc);
120 if (!file.is_open())
121 return OpenFailed;
122 file << generateXDataDef();
123 file.close();
124
125 return AllOk;
126 }
127
128
129 const std::string XData::generateXDataDef() const
130 {
131 std::stringstream xDataDef;
132 xDataDef << _name << "\n" << "{" << "\n" << "\tprecache" << "\n" << "\t\"num_pages\"\t: \"" << _numPages << "\"\n";
133
134 std::stringstream ss;
135 std::string TempString;
136
137 xDataDef << getContentDef();
138
139 for (std::size_t n=0; n<_numPages; n++)
140 {
141 xDataDef << "\t\"gui_page" << n+1 << "\"\t: \"" << _guiPage[n] << "\"\n";
142 }
143 xDataDef << "\t\"snd_page_turn\"\t: \"" << _sndPageTurn << "\"\n}";//*/
144
145 return xDataDef.str();
146 }
147
148 const std::size_t XData::getDefLength(const std::string& def) const
149 {
150 std::size_t charIndex = 0;
151 while (def[charIndex] != '\0')
152 {
153 if (def[++charIndex] == '{')
154 {
155 int BracketCount = 1;
156 while (def[++charIndex] != '\0' && BracketCount > 0)
157 {
158 // Move out of brackets
159 if (def[charIndex] == '{')
160 ++BracketCount;
161 else if (def[charIndex] == '}')
162 --BracketCount;
163 }
164 if (BracketCount > 0)
165 break;
166 while (def[charIndex] != '\0')
167 {
168 // The definitionlength also expands over trailing spaces
169 if ( (def[charIndex] != ' ') && (def[charIndex] != '\t') && (def[charIndex] != '\n') )
170 break;
171 ++charIndex;
172 }
173 return charIndex;
174 }
175 }
176 return 0; //no appropriate bracketstructure was found.
177 }
178
179 const std::string XData::getDefinitionNameFromXD(std::ifstream& file) const
180 {
181 std::string ReturnString;
182 parser::BasicDefTokeniser<std::istream> tok(file);
183 bool FirstDef = true;
184 while (tok.hasMoreTokens())
185 {
186 if (FirstDef)
187 ReturnString = tok.nextToken();
188 else
189 return "";
190 FirstDef = false;
191 tok.assertNextToken("{");
192 jumpOutOfBrackets(tok, 1);
193 }
194 return ReturnString;
195 }
196
197 const std::string XData::generateTextDef(const std::string& rawString) const
198 {
199 std::stringstream ss;
200 std::stringstream xDataDef;
201 std::string TempString;
202 xDataDef << "\t{\n";
203 if (rawString != "")
204 {
205 ss << rawString;
206 while ( std::getline(ss, TempString) ) //replace "\n" and add an escape-character before quotes.
207 {
208 std::size_t QuotePos = TempString.find("\"",0);
209 while ( QuotePos != std::string::npos )
210 {
211 TempString.insert(QuotePos, "\\");
212 QuotePos = TempString.find("\"",QuotePos+2);
213 }
214 xDataDef << "\t\t\"" << TempString << "\"\n";
215 }
216 xDataDef << "\t}\n";
217 }
218 else
219 xDataDef << "\t\t\"\"\n\t}\n";
220 return xDataDef.str();
221 }
222 //->general:
223 void XData::resizeVectors(std::size_t targetSize)
224 {
225 std::string fill = "";
226 if (_guiPage.size() > 0)
227 fill = _guiPage[_guiPage.size()-1];
228 _guiPage.resize(targetSize, fill);
229 }
230
231 void XData::jumpOutOfBrackets(parser::DefTokeniser& tok, int currentDepth) const
232 {
233 while ( tok.hasMoreTokens() && currentDepth > 0)
234 {
235 std::string token = tok.nextToken();
236 if (token == "{")
237 currentDepth += 1;
238 else if (token == "}")
239 currentDepth -= 1;
240 }
241 }
242
243 //TwoSidedXData implementations:
244
245 void TwoSidedXData::resizeVectors(std::size_t targetSize)
246 {
247 XData::resizeVectors(targetSize);
248 _pageLeftBody.resize(targetSize, "");
249 _pageLeftTitle.resize(targetSize, "");
250 _pageRightBody.resize(targetSize, "");
251 _pageRightTitle.resize(targetSize, "");
252 }
253
254 void TwoSidedXData::setPageContent(ContentType cc, std::size_t pageIndex, Side side, const std::string& content)
255 {
256 if (pageIndex >= _numPages)
257 throw std::runtime_error(_("Page Index out of bounds."));
258 switch (cc)
259 {
260 case Title:
261 switch (side)
262 {
263 case Left:
264 _pageLeftTitle[pageIndex] = content;
265 break;
266 default:
267 _pageRightTitle[pageIndex] = content;
268 }
269 break;
270 default:
271 switch (side)
272 {
273 case Left:
274 _pageLeftBody[pageIndex] = content;
275 break;
276 default:
277 _pageRightBody[pageIndex] = content;
278 }
279 }
280 }
281
282 const std::string& TwoSidedXData::getPageContent(ContentType cc, std::size_t pageIndex, Side side) const
283 {
284 if (pageIndex >= _numPages)
285 throw std::runtime_error(_("Page Index out of bounds."));
286 switch (cc)
287 {
288 case Title:
289 switch (side)
290 {
291 case Left:
292 return _pageLeftTitle[pageIndex];
293 default:
294 return _pageRightTitle[pageIndex];
295 }
296 default:
297 switch (side)
298 {
299 case Left:
300 return _pageLeftBody[pageIndex];
301 default:
302 return _pageRightBody[pageIndex];
303 }
304 }
305 }
306
307 const std::string TwoSidedXData::getContentDef() const
308 {
309 std::stringstream xDataDef;
310 for (std::size_t n = 0; n < _numPages; n++)
311 {
312 //Page Left Title
313 xDataDef << "\t\"page" << n+1 << "_left_title\"\t:\n";
314 xDataDef << generateTextDef(_pageLeftTitle[n]);
315
316 //Page Left Body
317 xDataDef << "\t\"page" << n+1 << "_left_body\"\t:\n";
318 xDataDef << generateTextDef(_pageLeftBody[n]);
319
320 //Page Right Title
321 xDataDef << "\t\"page" << n+1 << "_right_title\"\t:\n";
322 xDataDef << generateTextDef(_pageRightTitle[n]);
323
324 //Page Right Body
325 xDataDef << "\t\"page" << n+1 << "_right_body\"\t:\n";
326 xDataDef << generateTextDef(_pageRightBody[n]);
327 }
328 return xDataDef.str();
329 }
330
331 void TwoSidedXData::togglePageLayout(XDataPtr& target) const
332 {
333 XDataPtr newXData(new OneSidedXData(_name));
334 newXData->setNumPages(_numPages*2); //delete last page if no content later.
335 newXData->setSndPageTurn(_sndPageTurn);
336
337 // Add default guiPage to all guiPage-entries.
338 newXData->setGuiPage( StringList( newXData->getNumPages(), DEFAULT_ONESIDED_GUI) );
339
340 // Reshuffle the TwoSided pages contents into the OneSided page contents.
341 for (std::size_t n = 0; n < _numPages; n++)
342 {
343 newXData->setPageContent(Title, 2*n, Left, _pageLeftTitle[n] );
344 newXData->setPageContent(Body, 2*n, Left, _pageLeftBody[n] );
345 newXData->setPageContent(Title, 2*n+1, Left, _pageRightTitle[n] );
346 newXData->setPageContent(Body, 2*n+1, Left, _pageRightBody[n] );
347 }
348
349 if ( (_pageRightTitle[_numPages-1] == "") && (_pageRightBody[_numPages-1] == "") )
350 // Last page is empty. Set new numpages accordingly.
351 newXData->setNumPages(newXData->getNumPages()-1);
352
353 target = newXData;
354 }
355 //OneSidedXData implementations:
356
357 void OneSidedXData::resizeVectors(std::size_t targetSize)
358 {
359 XData::resizeVectors(targetSize);
360 _pageBody.resize(targetSize, "");
361 _pageTitle.resize(targetSize, "");
362 }
363
364 void OneSidedXData::setPageContent(ContentType cc, std::size_t pageIndex, Side side, const std::string& content)
365 {
366 if (pageIndex >= _numPages)
367 throw std::runtime_error(_("Page Index out of bounds."));
368 switch (cc)
369 {
370 case Title:
371 _pageTitle[pageIndex] = content;
372 break;
373 case Body:
374 default:
375 _pageBody[pageIndex] = content;
376 }
377 }
378
379 const std::string& OneSidedXData::getPageContent(ContentType cc, std::size_t pageIndex, Side side) const
380 {
381 if (pageIndex >= _numPages)
382 throw std::runtime_error(_("Page Index out of bounds."));
383 switch (cc)
384 {
385 case Title:
386 return _pageTitle[pageIndex];
387 default:
388 return _pageBody[pageIndex];
389 }
390 }
391
392 const std::string OneSidedXData::getContentDef() const
393 {
394 std::stringstream xDataDef;
395
396 for (std::size_t n = 0; n < _numPages; n++)
397 {
398 //Title
399 xDataDef << "\t\"page" << n+1 << "_title\"\t:\n";
400 xDataDef << generateTextDef(_pageTitle[n]);
401
402 //Body
403 xDataDef << "\t\"page" << n+1 << "_body\"\t:\n";
404 xDataDef << generateTextDef(_pageBody[n]);
405 }
406
407 return xDataDef.str();
408 }
409
410 void OneSidedXData::togglePageLayout(XDataPtr& target) const
411 {
412 XDataPtr newXData(new TwoSidedXData(_name));
413 newXData->setNumPages( (_numPages+1)/2);
414 newXData->setSndPageTurn(_sndPageTurn);
415
416 // Add default guiPage to all guiPage-entries.
417 newXData->setGuiPage( StringList( newXData->getNumPages(), DEFAULT_TWOSIDED_GUI) );
418
419 // Reshuffle the TwoSided pages contents into the OneSided page contents.
420 for (std::size_t n = 0; n < newXData->getNumPages()-1; n++)
421 {
422 newXData->setPageContent(Title, n, Left, _pageTitle[2*n] );
423 newXData->setPageContent(Body, n, Left, _pageBody[2*n] );
424 newXData->setPageContent(Title, n, Right, _pageTitle[2*n+1] );
425 newXData->setPageContent(Body, n, Right, _pageBody[2*n+1] );
426 }
427 newXData->setPageContent(Title, newXData->getNumPages()-1, Left, _pageTitle[2*(newXData->getNumPages()-1)] );
428 newXData->setPageContent(Body, newXData->getNumPages()-1, Left, _pageBody[2*(newXData->getNumPages()-1)] );
429 if ( (_numPages % 2) == 0)
430 {
431 // Prevent vector subscript exceeded.
432 newXData->setPageContent(Title, newXData->getNumPages()-1, Right, _pageTitle[_numPages-1] );
433 newXData->setPageContent(Body, newXData->getNumPages()-1, Right, _pageBody[_numPages-1] );
434 }
435
436 target = newXData;
437 }
438
439 } // namespace XData