Debian Codegraph @

plugins/dm.gui/XDataLoader.cpp

raw
1 #include "XDataLoader.h"
2
3 #include "string/convert.h"
4 #include "iarchive.h"
5
6 namespace XData
7 {
8
9 const bool XDataLoader::importDef( const std::string& definitionName, XDataMap& target, const std::string& filename )
10 {
11 // Initialization:
12 _errorList.clear();
13 _newXData.reset();
14 target.clear();
15 StringList files;
16
17 if (filename != "")
18 {
19 //Check fileextension:
20 if (filename.substr( filename.rfind(".")+1 ) != "xd")
21 return reportError("[XDataLoader::import] Error: File-extension is not .xd: " + filename + "\n");
22 files.push_back(filename);
23 }
24 else
25 {
26 //Find the files in which the definition can be found.
27 retrieveXdInfo();
28 StringVectorMap::iterator it = _defMap.find(definitionName);
29 if (it == _defMap.end())
30 return reportError("[XDataLoader::importDef] Error: Specified definition " + definitionName + " not found.\n");
31 files = it->second;
32 if (files.size() > 1) //Definition contained in multiple files.
33 reportError("[XData::import] Warning: The requested definition " + definitionName + " exists in multiple files.\n");
34 }
35
36 // Parse the requested definition from all files:
37 for (std::size_t n = 0; n < files.size(); n++)
38 {
39 // Attempt to open the file in text mode and retrieve DefTokeniser
40 ArchiveTextFilePtr file =
41 GlobalFileSystem().openTextFile(files[n]);
42
43 if (file == NULL)
44 return reportError("[XDataLoader::importDef] Error: Failed to open file " + files[n] + "\n");
45 std::istream is(&(file->getInputStream()));
46 parser::BasicDefTokeniser<std::istream> tok(is);
47
48 // Parse the desired definition:
49 while (tok.hasMoreTokens() && !parseXDataDef(tok,definitionName)) {}
50 if (_newXData)
51 target.insert(XDataMap::value_type(file->getModName() + "/" + file->getName(),_newXData));
52 else
53 reportError("[XDataLoader::importDef] Error: Failed to load " + definitionName + " from file " + files[n] + ".\n");
54 }
55
56 //Summarizing report:
57 if (target.size() == 0)
58 {
59 if (filename == "")
60 reportError("[XDataLoader::importDef] Error: Failed to load " + definitionName + ".\n");
61 return false;
62 }
63 else
64 {
65 _errorList.push_back("[XDataLoader::importDef] " + definitionName + " loaded successfully with "
66 + string::to_string(_errorList.size()) + " error(s)/warning(s).\n");
67 //Summary output:
68 if (_errorList.size() > 1)
69 rConsoleError() << _errorList[_errorList.size() - 1];
70 else
71 rMessage() << _errorList[0];
72 }
73
74 return true;
75 }
76
77 const bool XDataLoader::import( const std::string& filename, XDataMap& target )
78 {
79 //initialization:
80 _errorList.clear();
81 target.clear();
82 unsigned int ErrorCount = 0;
83
84 //Check fileextension:
85 if (filename.substr( filename.rfind(".")+1 ) != "xd")
86 return reportError("[XDataLoader::import] Fileextension is not .xd: " + filename + "\n");
87
88 // Attempt to open the file in text mode and retrieve DefTokeniser
89 ArchiveTextFilePtr file =
90 GlobalFileSystem().openTextFile(filename);
91 if (file == NULL)
92 return reportError("[XDataLoader::import] Failed to open file: " + filename + "\n");
93
94 std::istream is(&(file->getInputStream()));
95 parser::BasicDefTokeniser<std::istream> tok(is);
96
97 //Parse Loop:
98 while (tok.hasMoreTokens())
99 {
100 if (parseXDataDef(tok))
101 target.insert(XDataMap::value_type(_newXData->getName(),_newXData));
102 else
103 ErrorCount += 1;
104 }
105
106 //Write summary
107 _errorList.push_back(
108 "[XDataLoader::import] Import finished with " + string::to_string(_errorList.size())
109 + " error(s)/warning(s). " + string::to_string(target.size())
110 + " XData-definition(s) successfully imported, but failed to import at least "
111 + string::to_string(ErrorCount) + " definitions.\n"
112 );
113
114 //Summary output:
115 if (_errorList.size() == 1) //No errors.
116 rMessage() << _errorList[0];
117 else
118 rConsoleError() << _errorList[_errorList.size() - 1];
119
120 if (target.size() == 0)
121 return false;
122
123 return true;
124 } // XDataLoader::import
125
126 const bool XDataLoader::parseXDataDef(parser::DefTokeniser& tok, const std::string& definitionName)
127 {
128 _name = tok.nextToken();
129 _newXData.reset();
130
131 //Check Syntax:
132 try { tok.assertNextToken("{"); }
133 catch (...)
134 {
135 while (tok.hasMoreTokens() && (tok.nextToken() != "{")) {}
136 jumpOutOfBrackets(tok);
137 return reportError(tok, "[XDataLoader::import] Syntaxerror in definition: " + _name + ". '{' expected. Undefined behavior!\n\tTrying to Jump to next XData definition. Might lead to furthers errors.\n");
138 }
139
140 //Check if every definition shall be parsed or only a specific one:
141 if (!definitionName.empty() && _name != definitionName)
142 {
143 jumpOutOfBrackets(tok);
144 return false;
145 }
146
147 //Initialization:
148 _guiPageError.clear();
149 _maxPageCount = 0;
150 _maxGuiNumber = 0;
151 _guiPageDef = "";
152 _numPages = 0;
153 _sndPageTurn = "";
154 _guiPage.clear();
155 _guiPage.resize(MAX_PAGE_COUNT,""); //see MAX_PAGE_COUNT declaration in XData.h for explanation.
156
157 //Parse-Loop:
158 while (tok.hasMoreTokens())
159 {
160 std::string token = tok.nextToken();
161 if (token == "}")
162 break;
163 if (!storeContent(token, &tok, _name))
164 return false;
165 }
166
167 //cleaning up:
168 if ( _maxGuiNumber+1 > _numPages) //Append missing GUI-errormessages... Until now, it wasn't clear how many guipages are actually discarded.
169 {
170 auto diff = _maxGuiNumber + 1 - _maxPageCount;
171 for (auto n = _guiPageError.size()-diff; n<_guiPageError.size(); n++)
172 {
173 reportError(_guiPageError[n]);
174 }
175 }
176
177 // Check if _guiPage-statements for all pages are available.
178 if (_guiPageDef.empty())
179 {
180 reportError("[XDataLoader::import] Warning for definition: " + _name
181 + ". _guiPage-statement(s) missing. Setting default value...\n");
182 if (_newXData->getPageLayout() == TwoSided)
183 _guiPageDef = DEFAULT_TWOSIDED_GUI;
184 else
185 _guiPageDef = DEFAULT_ONESIDED_GUI;
186 }
187 for (std::size_t n=0; n<_numPages; n++ )
188 {
189 if (_guiPage[n].empty())
190 _guiPage[n] = _guiPageDef;
191 }
192
193 //Store values:
194 _newXData->setGuiPage(_guiPage);
195 _newXData->setNumPages(_numPages);
196
197 //Use default sndPageTurn if the statement was missing:
198 if (_sndPageTurn.empty())
199 {
200 _newXData->setSndPageTurn(DEFAULT_SNDPAGETURN);
201 reportError("[XDataLoader::import] Warning for definition: " + _name
202 + ". _sndPageTurn-statement missing. Setting default value...\n");
203 }
204 else
205 _newXData->setSndPageTurn(_sndPageTurn);
206
207 return true;
208 }
209
210 const bool XDataLoader::storeContent(const std::string& statement, parser::DefTokeniser* tok, const std::string& defName, const std::string& content)
211 {
212 //page-statement:
213 if (statement.substr(0,4) == "page")
214 {
215 //Now that it is known, whether we are dealing with a Two- or OneSidedXDataObject, create the XData object.
216 if (!_newXData)
217 {
218 if (statement.find("left",6) != std::string::npos || statement.find("right",6) != std::string::npos) //TwoSided
219 _newXData = XDataPtr(new TwoSidedXData(_name));
220 else
221 _newXData = XDataPtr(new OneSidedXData(_name));
222 }
223
224 //Acquire PageIndex
225 std::size_t PageIndex;
226 std::size_t numEnd = 4;
227 while (statement[numEnd++] != '_') {}
228 std::string number = statement.substr(4,numEnd-5);
229 try { PageIndex = std::stoi(number)-1; }
230 catch (...)
231 {
232 if (tok != NULL)
233 {
234 _newXData.reset();
235 return reportError(*tok, "[XDataLoader::import] Error in definition: " + defName + ", "
236 + statement + " statement. '" + number
237 + "' is not a number.\n\tTrying to Jump to next XData definition. Might lead to furthers errors.\n"
238 );
239 }
240 _newXData.reset();
241 return reportError("[XDataLoader::import] Error in definition: " + defName + ", " + statement + " statement. '"
242 + number + "' is not a number.\n"
243 );
244 }
245
246 //Read content
247 std::string readContent;
248 if (tok != NULL)
249 {
250 if (!readLines(*tok, readContent))
251 {
252 _newXData.reset();
253 return reportError(*tok, "[XDataLoader::import] Error in definition: " + defName + ". Failed to read content of "
254 + statement + " statement.\n\tTrying to Jump to next XData definition. Might lead to furthers errors.\n"
255 );
256 }
257 }
258 else
259 readContent = content;
260
261 // Check whether readContent actually has content. (There might be space, linebreaks and tabs that can be discarded)
262 bool hasContent = false;
263 for (std::size_t n = 0; n < readContent.size(); n++)
264 {
265 if ( (readContent[n] != ' ') && (readContent[n] != '\t') && (readContent[n] != '\n') )
266 {
267 hasContent = true;
268 break;
269 }
270 }
271
272 //Check PageIndex-Range
273 if (PageIndex >= _numPages )
274 {
275 if (hasContent) //_numPages is raised automatically, if a page with content is detected...
276 {
277 _numPages = PageIndex+1;
278 reportError("[XDataLoader::import] Warning for definition: " + defName + ", " + statement
279 + " statement.\n\tnumPages not (yet) specified or too low. Raising _numPages to " + number +"...\n"
280 );
281 }
282 else
283 {
284 reportError("[XDataLoader::import] Warning for definition: " + defName + ", " + statement
285 + " statement.\n\tnumPages not (yet) specified or too low. However, this page does not contain any text and is discarded...\n"
286 );
287 return true;
288 }
289 }
290
291 //Refresh the _maxPageCount variable if this page has content.
292 if (hasContent)
293 {
294 if (_maxPageCount < PageIndex+1)
295 _maxPageCount = PageIndex+1;
296
297 //Write the content into the XData object
298 Side side;
299 if (statement.find("left",6) != std::string::npos) //Side is discarded on OneSidedXData...
300 side = Left;
301 else
302 side = Right;
303 if (statement.find("body",6) != std::string::npos)
304 _newXData->setPageContent(Body, PageIndex, side, readContent); //could throw if PageIndex >= MAX_PAGE_COUNT. Unlikely!
305 else
306 _newXData->setPageContent(Title, PageIndex, side, readContent);
307 }
308
309 return true;
310 }
311 //gui_page statement
312 else if (statement.substr(0,8) == "gui_page")
313 {
314 //Acquire gui_page number:
315 std::string number = statement.substr(8);
316 std::size_t guiNumber;
317 try { guiNumber = std::stoi(number)-1; }
318 catch (...)
319 {
320 if (tok != NULL)
321 {
322 _newXData.reset();
323 return reportError(*tok, "[XDataLoader::import] Error in definition: " + defName + ", gui_page statement. '" + number
324 + "' is not a number.\n\tTrying to Jump to next XData definition. Might lead to furthers errors.\n"
325 );
326 }
327 _newXData.reset();
328 return reportError("[XDataLoader::import] Error in definition: " + defName + ", gui_page statement. '" + number + "' is not a number.\n");
329 }
330 if (_maxGuiNumber < guiNumber)
331 _maxGuiNumber = guiNumber;
332
333 //Get the GuiPageDef:
334 if (tok != NULL)
335 {
336 if (!readLines(*tok, _guiPageDef))
337 {
338 _newXData.reset();
339 return reportError(*tok, "[XDataLoader::import] Error in definition: " + defName + ". Failed to read content of " + statement
340 + " statement.\n\tTrying to Jump to next XData definition. Might lead to furthers errors.\n"
341 );
342 }
343 }
344 else
345 _guiPageDef = content;
346 _guiPage[ guiNumber ] = _guiPageDef; //could throw if guiNumber >= MAX_PAGE_COUNT
347
348 //Append error-message if _numPages is exceeded.
349 if (guiNumber >= _numPages)
350 _guiPageError.push_back("[XDataLoader::import] Warning for definition: " + defName
351 + ". More _guiPage statements, than pages. Discarding statement for Page " + number + ".\n"
352 );
353
354 return true;
355 }
356 //num_pages statement
357 else if (statement == "num_pages")
358 {
359 //Get num_pages:
360 if (tok != NULL)
361 {
362 std::string number;
363 if (!readLines(*tok, number))
364 {
365 _newXData.reset();
366 return reportError(*tok, "[XDataLoader::import] Error in definition: " + defName + ". Failed to read content of "
367 + statement + " statement.\n\tTrying to Jump to next XData definition. Might lead to furthers errors.\n"
368 );
369 }
370 try { _numPages = std::stoi(number); }
371 catch(...)
372 {
373 _newXData.reset();
374 return reportError(*tok, "[XDataLoader::import] Error in definition: " + defName + ", num_pages statement. '" + number
375 + "' is not a number.\n\tTrying to Jump to next XData definition. Might lead to furthers errors.\n"
376 );
377 }
378 }
379 else
380 {
381 try { _numPages = std::stoi(content); }
382 catch (...)
383 {
384 return reportError("[XDataLoader::import] Error in definition: " + defName + ", num_pages statement. '" + content
385 + "' is not a number.\n"
386 );
387 }
388 }
389
390 //Correct a faulty _numPages value
391 if (_maxPageCount > _numPages)
392 {
393 _numPages = _maxPageCount;
394 reportError("[XDataLoader::import] Warning for definition: " + defName
395 + ". The specified _numPages statement did not match the amount of pages with content.\n\tnumPages is set to "
396 + string::to_string(_numPages) + ".\n");
397 }
398
399 return true;
400 }
401 //snd_page_turn statement
402 else if (statement == "snd_page_turn")
403 {
404 if (tok != NULL)
405 {
406 if (!readLines(*tok, _sndPageTurn))
407 {
408 _newXData.reset();
409 return reportError(*tok, "[XDataLoader::import] Error in definition: " + defName + ". Failed to read content of " + statement
410 + " statement.\n\tTrying to Jump to next XData definition. Might lead to furthers errors.\n"
411 );
412 }
413 }
414 else
415 _sndPageTurn = content;
416
417 return true;
418 }
419 //import statement
420 else if (statement == "import")
421 {
422 StringPairList importedData;
423 std::string SourceDef;
424 StringMap statements;
425
426 if (tok == NULL) //Only works with def tokeniser.
427 {
428 _newXData.reset();
429 return false;
430 }
431
432 if (!getImportParameters(*tok, statements, SourceDef, defName))
433 {
434 _newXData.reset();
435 return false;
436 }
437
438 retrieveXdInfo(); //refresh defmap. Prevents faulty imports.
439 if (!recursiveImport(SourceDef, statements, defName, importedData))
440 {
441 _errorList[_errorList.size()-1] += "\tTrying to Jump to next XData definition. Might lead to furthers errors.\n";
442 jumpOutOfBrackets(*tok);
443 _newXData.reset();
444 return false;
445 }
446
447 for (std::size_t n=0; n < importedData.size(); n++)
448 {
449 if (!storeContent(importedData[n].first, NULL, defName, importedData[n].second))
450 {
451 _newXData.reset();
452 return reportError(*tok, "[XDataLoader::import] Error in definition: " + defName
453 + ". Import-statement failed.\n\tTrying to Jump to next XData definition. Might lead to furthers errors.\n"
454 );
455 }
456 }
457
458 return true;
459 }
460 else if (statement == "precache")
461 {
462 return true;
463 }
464
465 _newXData.reset();
466 jumpOutOfBrackets(*tok);
467 return false;
468 }
469
470 const bool XDataLoader::recursiveImport( const std::string& sourceDef, const StringMap& statements, const std::string& defName, StringPairList& importContent)
471 {
472 //Check where the Definition is stored in the _defMap
473 StringVectorMap::iterator it = _defMap.find(sourceDef);
474 if (it == _defMap.end()) //Definition not found!!
475 return reportError("[XData::import] Error in definition: " + defName + ". Found an import-statement, but not the corresponding definition.\n");
476 std::size_t FileCount = it->second.size();
477 if (FileCount > 1) //Definition contained in multiple files.
478 reportError(
479 "[XData::import] Warning for definition: " + defName
480 + ". Found an import-statement and the referenced definition exists multiple times.\n"
481 );
482
483 //Try every file the definition is stored in. If import of none succeeded, the import failed.
484 for (std::size_t k = 0; k < FileCount; k++)
485 {
486 //Init
487 StringMap StmtsCpy = statements;
488 StringMap ImpStmts;
489 std::string ImpSrcDef = "";
490 int BracketDepth = 1;
491
492 //Open the file
493 ArchiveTextFilePtr file =
494 GlobalFileSystem().openTextFile(it->second[k]);
495 if (file == NULL)
496 return reportError(
497 "[XData::import] Error in definition: " + defName
498 + ". Found an import-statement, but failed to open the corresponding file: " + it->second[k] + ".\n"
499 );
500
501 //Find the Source-Definition in the File:
502 std::istream is(&(file->getInputStream()));
503 parser::BasicDefTokeniser<std::istream> ImpTok(is);
504 while (true)
505 {
506 while ( ImpTok.nextToken() != sourceDef) {}
507 if ( ImpTok.nextToken() == "{")
508 break;
509 }
510
511 //Import-Loop: Find the SourceStatements in the definition and parse the contents.
512 //Further Import-directives possibly have to be handled recursively...
513 while (ImpTok.hasMoreTokens())
514 {
515 //Find SourceStatements or further import-statements. Count entering and leaving brackets to identify definition end.
516 std::string token = ImpTok.nextToken();
517 StringMap::iterator StIt = StmtsCpy.find(token);
518 if (StIt != StmtsCpy.end())
519 {
520 //Token found that matches the Source statement. Parse it and delete statement from StmtsCpy afterwards.
521 std::string StmtCtnt;
522 if (readLines(ImpTok, StmtCtnt))
523 {
524 importContent.push_back( StringPairList::value_type(
525 StIt->second,
526 StmtCtnt
527 ));
528 StmtsCpy.erase(StIt);
529 }
530 else if (!ImpTok.hasMoreTokens())
531 {
532 //Syntaxerror!
533 std::string errMSG = "[XData::import] Error in definition: " + defName
534 + ". Found an import-statement, but an sytax-error occurred in the definition "
535 + sourceDef + ", in sourcefile " + it->second[k] + ".\n";
536 if ( (FileCount > 1) && (k+1 < FileCount) )
537 errMSG += "\tThe referenced definition has been found in multiple files. Trying next file...\n";
538 reportError(errMSG);
539 break;
540 }
541 else
542 //The found token was not an actual statement.
543 continue;
544 }
545 else if (token == "{")
546 BracketDepth += 1;
547 else if (token == "}")
548 BracketDepth -= 1;
549 else if (token == "import")
550 {
551 //getImportParameters fails on syntax errors or EOF (which is an syntax-error as well), so go on with next file.
552 if (!getImportParameters(ImpTok, ImpStmts, ImpSrcDef, defName))
553 {
554 std::string errMSG = "[XData::import] Error in definition: " + defName
555 + ". Found an import-statement, but an sytax-error occurred in the definition "
556 + sourceDef + ", in sourcefile " + it->second[k] + ".\n";
557 if ( (FileCount > 1) && (k < FileCount-1) )
558 errMSG += "\tThe referenced definition has been found in multiple files. Trying next file...\n";
559 reportError(errMSG);
560 break;
561 }
562 }
563 if (StmtsCpy.size() == 0)
564 //Success: Return!
565 return true;
566 if (BracketDepth == 0)
567 {
568 //Not all Source-statements have been found in the definition. If an import statement has been found
569 //check if all requested statements would be imported by it.
570 if (ImpSrcDef != "")
571 {
572 StringMap ChkStmts = StmtsCpy;
573 StringMap RecoverStatements;
574 for (StringMap::iterator impCheck = ImpStmts.begin(); impCheck != ImpStmts.end(); impCheck++)
575 {
576 StringMap::iterator temp = ChkStmts.find(impCheck->second);
577 if (temp != ChkStmts.end())
578 {
579 ChkStmts.erase(temp);
580 RecoverStatements.insert(*impCheck);
581 }
582 }
583 if (ChkStmts.size() == 0)
584 {
585 //All necessary statements found in import-directive.
586 StringPairList imported;
587 if (recursiveImport(ImpSrcDef,RecoverStatements,sourceDef,imported))
588 {
589 //Success! Store imported contents and return!
590 for (std::size_t u = 0; u < imported.size(); u++)
591 {
592 importContent.push_back( StringPairList::value_type(
593 StmtsCpy.find(imported[u].first)->second,
594 imported[u].second
595 ));
596 }
597 return true;
598 }
599 else
600 {
601 std::string errMSG = "[XData::import] Error in definition: " + defName
602 + ". Found an import-statement, but failed to import the requested statements of definition "
603 + sourceDef + ", in sourcefile " + it->second[k] + ".\n";
604 if ( (FileCount > 1) && (k < FileCount-1) )
605 errMSG += "\tThe referenced definition has been found in multiple files. Trying next file...\n";
606 reportError(errMSG);
607 break;
608 }
609 }
610 }
611 //No import-statement found or not all requested definitions in import statement. Move on with next file.
612 std::string errMSG = "[XData::import] Error in definition: " + defName
613 + ". Found an import-statement, but couldn't find all referenced statements in the definition "
614 + sourceDef + ", in sourcefile " + it->second[k] + ".\n";
615 if ( (FileCount > 1) && (k < FileCount-1) )
616 errMSG += "\tThe referenced definition has been found in multiple files. Trying next file...\n";
617 reportError(errMSG);
618 break;
619 } //End of definition was reached!
620 } //End of Import-Loop
621 } //End of File-duplicate-Loop
622
623 return reportError("[XData::import] Error in definition: " + defName + ". Import-statement failed.\n");
624 }
625
626 const bool XDataLoader::getImportParameters(parser::DefTokeniser& tok, StringMap& statements, std::string& sourceDef, const std::string& defName)
627 {
628 std::string token;
629
630 //Enter content brackets
631 try { tok.assertNextToken("{"); }
632 catch(...)
633 {
634 return reportError(tok, "[XDataLoader::import] Syntax error in definition: " + defName
635 + ", import-statement. '{' expected. Undefined behavior!\n"
636 );
637 }
638
639 //Get Source- and DestStatements
640 try
641 {
642 token = tok.nextToken();
643 while (token != "}")
644 {
645 tok.skipTokens(1); //Skip "->"
646 statements.insert( StringMap::value_type(token,tok.nextToken()) );
647 token = tok.nextToken();
648 }
649 }
650 catch (...)
651 {
652 return reportError(tok, "[XDataLoader::import] Error in definition: " + defName
653 + ". Failed to read content of import-statement. Probably Syntax-error.\n"
654 + "\tTrying to Jump to next XData definition. Might lead to furthers errors.\n",
655 2 );
656 }
657
658 //Get Name of Source-Definition
659 try { tok.assertNextToken("from"); }
660 catch (...)
661 {
662 return reportError(tok, "[XDataLoader::import] Syntax error in definition: " + defName
663 + ", import-statement. 'from' expected. Undefined behavior!\n"
664 + "\tTrying to Jump to next XData definition. Might lead to furthers errors.\n"
665 );
666 }
667 try { sourceDef = tok.nextToken(); }
668 catch (...)
669 {
670 return reportError(tok, "[XDataLoader::import] Error in definition: " + defName
671 + ". Failed to read content of import-statement.\n"
672 + "\tTrying to Jump to next XData definition. Might lead to furthers errors.\n"
673 );
674 }
675
676 return true;
677 }
678
679 inline const bool XDataLoader::readLines(parser::DefTokeniser& tok, std::string& what) const
680 {
681 std::stringstream out;
682 std::string token;
683
684 //Check Syntax
685 try
686 {
687 tok.assertNextToken(":");
688 what = tok.nextToken();
689 if (what != "{" ) //Parsing SingleLine Content
690 return true;
691
692 //Parse MultiLine Content.
693 token = tok.nextToken();
694 while (token != "}")
695 {
696 if (token == "/") //newlines can also be signalized by slashed. Ignore them
697 {
698 token = tok.nextToken();
699 continue;
700 }
701 else if (token.c_str()[token.length()-1] == '\\') //support for escaped quotes in texts...
702 token = token.substr(0,token.length()-1) + "\"";
703 else
704 token = token + "\n";
705 out << token;
706 token = tok.nextToken();
707 }
708 }
709 catch (...) { return false; }
710 what = out.str();
711 return true;
712 }
713
714 void XDataLoader::jumpOutOfBrackets(parser::DefTokeniser& tok, std::size_t currentDepth) const
715 {
716 while ( tok.hasMoreTokens() && currentDepth > 0)
717 {
718 std::string token = tok.nextToken();
719 if (token == "{")
720 currentDepth += 1;
721 else if (token == "}")
722 currentDepth -= 1;
723 }
724 }
725
726 void XDataLoader::retrieveXdInfo()
727 {
728 _defMap.clear();
729 _fileSet.clear();
730 _duplicatedDefs.clear();
731 //ScopedDebugTimer timer("XData definitions parsed: ");
732 GlobalFileSystem().forEachFile(
733 XDATA_DIR, XDATA_EXT,
734 [&](const vfs::FileInfo& fileInfo) { loadFromFile(fileInfo.name); },
735 99
736 );
737 }
738
739 void XDataLoader::loadFromFile(const std::string& filename)
740 {
741 // Attempt to open the file in text mode
742 ArchiveTextFilePtr file =
743 GlobalFileSystem().openTextFile(XDATA_DIR + filename);
744
745 if (file != NULL) {
746 // File is open, so add the file to the _fileSet-set and parse the tokens
747 _fileSet.insert(file->getModName() + "/" + file->getName());
748 try
749 {
750 std::istream is(&(file->getInputStream()));
751 parser::BasicDefTokeniser<std::istream> tok(is);
752 //grab all names from stream:
753 while (tok.hasMoreTokens())
754 {
755 std::string tempstring = tok.nextToken();
756 tok.assertNextToken("{");
757 std::pair<StringVectorMap::iterator,bool> ret = _defMap.insert( StringVectorMap::value_type(tempstring, StringList(1, XDATA_DIR + filename) ) );
758 if (!ret.second) //Definition already exists.
759 {
760 ret.first->second.push_back(XDATA_DIR + filename);
761 rError() << "[XDataLoader] The definition " << tempstring << " of the file " << filename << " already exists. It was defined at least once. First in " << ret.first->second[0] << ".\n";
762 //Create an entry in the _duplicatedDefs map with the original file. If entry already exists, insert will fail.
763 std::pair<StringVectorMap::iterator,bool> duplRet = _duplicatedDefs.insert( StringVectorMap::value_type(tempstring, StringList(1,ret.first->second[0]) ) );
764 //The new file is appended to the vector.
765 duplRet.first->second.push_back(XDATA_DIR + filename);
766 }
767 jumpOutOfBrackets(tok);
768 }
769 }
770 catch (parser::ParseException& e)
771 {
772 rError() << "[XDataLoader] Failed to parse " << filename
773 << ": " << e.what() << std::endl;
774 }
775 }
776 else
777 {
778 rError() << "[XDataLoader] Unable to open " << filename << std::endl;
779 }
780 }
781
782 } // namespace XData