]> git.lyx.org Git - lyx.git/blob - src/insets/ExternalTemplate.cpp
Loop refactoring
[lyx.git] / src / insets / ExternalTemplate.cpp
1 /**
2  * \file ExternalTemplate.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup Nielsen
7  * \author Angus Leeming
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "ExternalTemplate.h"
15
16 #include "Lexer.h"
17
18 #include "support/debug.h"
19 #include "support/filetools.h"
20 #include "support/lstrings.h"
21 #include "support/Package.h"
22 #include "support/PathChanger.h"
23 #include "support/Translator.h"
24
25 #include <algorithm>
26 #include <ostream>
27
28 using namespace std;
29 using namespace lyx::support;
30
31 namespace lyx {
32 namespace external {
33
34
35 typedef Translator<TransformID, string> TransformIDTranslator;
36
37 static TransformIDTranslator const initIDTranslator()
38 {
39         TransformIDTranslator translator(TransformID(-1), "");
40         translator.addPair(Rotate, "Rotate");
41         translator.addPair(Resize, "Resize");
42         translator.addPair(Clip,   "Clip");
43         translator.addPair(Extra,  "Extra");
44         return translator;
45 }
46
47 static TransformIDTranslator const & transformIDTranslator()
48 {
49         static TransformIDTranslator const translator = initIDTranslator();
50         return translator;
51 }
52
53 // We have to have dummy default commands for security reasons!
54 Template::Template()
55         : inputFormat("*"), automaticProduction(false), preview_mode(PREVIEW_OFF)
56 {}
57
58
59 Template::Format::Format()
60 {}
61
62
63 TemplateManager::TemplateManager()
64 {
65         readTemplates(package().user_support());
66         if (lyxerr.debugging(Debug::EXTERNAL)) {
67                 dumpPreambleDefs(lyxerr);
68                 lyxerr << '\n';
69                 dumpTemplates(lyxerr);
70         }
71 }
72
73
74 std::function<void (TemplateManager::PreambleDefs::value_type const &)>
75         DumpPreambleDef(ostream & os)
76 {
77         return [&os](TemplateManager::PreambleDefs::value_type const & vt)
78         {
79                 os << "PreambleDef " << vt.first << '\n'
80                    << to_utf8(vt.second)
81                    << "PreambleDefEnd" << endl;
82         };
83 }
84
85
86 std::function<void (TemplateManager::Templates::value_type const &) >
87         DumpTemplate(ostream & os)
88 {
89         return [&os](TemplateManager::Templates::value_type const & vt) {
90                 Template const & et = vt.second;
91
92                 os << "Template " << et.lyxName << '\n'
93                     << "\tGuiName " << et.guiName << '\n'
94                     << "\tHelpText\n"
95                     << to_utf8(et.helpText)
96                     << "\tHelpTextEnd\n"
97                     << "\tInputFormat " << et.inputFormat << '\n'
98                     << "\tFileFilter " << et.fileRegExp << '\n'
99                     << "\tAutomaticProduction " << et.automaticProduction << '\n'
100                     << "\tPreview ";
101                 switch (et.preview_mode) {
102                         case PREVIEW_OFF:
103                                 os << "Off\n";
104                                 break;
105                         case PREVIEW_GRAPHICS:
106                                 os << "Graphics\n";
107                                 break;
108                         case PREVIEW_INSTANT:
109                                 os << "InstantPreview\n";
110                                 break;
111                 }
112                 typedef vector<TransformID> IDs;
113                 IDs::const_iterator it  = et.transformIds.begin();
114                 IDs::const_iterator end = et.transformIds.end();
115                 for (; it != end; ++it) {
116                         os << "\tTransform "
117                             << transformIDTranslator().find(*it) << '\n';
118                 }
119
120                 et.dumpFormats(os);
121                 os << "TemplateEnd" << endl;
122
123         };
124 }
125
126
127 std::function<void (Template::Formats::value_type const &) >
128         DumpFormat (ostream & os)
129 {
130         return [&os](Template::Formats::value_type const & vt)
131         {
132                 Template::Format const & ft = vt.second;
133                 os << "\tFormat " << vt.first << '\n'
134                     << "\t\tProduct " << ft.product << '\n'
135                     << "\t\tUpdateFormat " << ft.updateFormat << '\n'
136                     << "\t\tUpdateResult " << ft.updateResult << '\n';
137
138                 vector<string>::const_iterator qit = ft.requirements.begin();
139                 vector<string>::const_iterator qend = ft.requirements.end();
140                 for (; qit != qend; ++qit) {
141                         lyxerr << "req:" << *qit << endl;
142                         os << "\t\tRequirement " << *qit << '\n';
143                 }
144
145                 typedef vector<Template::Option> Options;
146                 Options::const_iterator oit  = ft.options.begin();
147                 Options::const_iterator oend = ft.options.end();
148                 for (; oit != oend; ++oit) {
149                         os << "\t\tOption "
150                             << oit->name
151                             << ": "
152                             << oit->option
153                             << '\n';
154                 }
155
156                 vector<string>::const_iterator pit  = ft.preambleNames.begin();
157                 vector<string>::const_iterator pend = ft.preambleNames.end();
158                 for (; pit != pend; ++pit) {
159                         os << "\t\tPreamble " << *pit << '\n';
160                 }
161
162                 typedef Template::Format::FileMap FileMap;
163                 FileMap::const_iterator rit  = ft.referencedFiles.begin();
164                 FileMap::const_iterator rend = ft.referencedFiles.end();
165                 for (; rit != rend; ++rit) {
166                         vector<string>::const_iterator fit  = rit->second.begin();
167                         vector<string>::const_iterator fend = rit->second.end();
168                         for (; fit != fend; ++fit) {
169                                 os << "\t\tReferencedFile " << rit->first
170                                     << " \"" << *fit << "\"\n";
171                         }
172                 }
173
174                 os << "\tFormatEnd\n";
175         };
176 }
177
178
179 void Template::dumpFormats(ostream & os) const
180 {
181         for_each(formats.begin(), formats.end(), DumpFormat(os));
182 }
183
184
185 void TemplateManager::dumpPreambleDefs(ostream & os) const
186 {
187         for_each(preambledefs.begin(), preambledefs.end(), DumpPreambleDef(os));
188 }
189
190
191 void TemplateManager::dumpTemplates(ostream & os) const
192 {
193         for_each(templates.begin(), templates.end(), DumpTemplate(os));
194 }
195
196
197 TemplateManager & TemplateManager::get()
198 {
199         static TemplateManager externalTemplateManager;
200         return externalTemplateManager;
201 }
202
203
204 TemplateManager::Templates const & TemplateManager::getTemplates() const
205 {
206         return templates;
207 }
208
209
210 Template const *
211 TemplateManager::getTemplateByName(string const & name) const
212 {
213         Templates::const_iterator it = templates.find(name);
214         return (it == templates.end()) ? 0 : &it->second;
215 }
216
217
218 docstring TemplateManager::getPreambleDefByName(string const & name) const
219 {
220         string const trimmed_name = trim(name);
221         if (trimmed_name.empty())
222                 return docstring();
223
224         PreambleDefs::const_iterator it = preambledefs.find(trimmed_name);
225         if (it == preambledefs.end())
226                 return docstring();
227
228         return it->second;
229 }
230
231
232 void TemplateManager::readTemplates(FileName const & path)
233 {
234         PathChanger p(path);
235
236         enum {
237                 TM_PREAMBLEDEF = 1,
238                 TM_PREAMBLEDEF_END,
239                 TM_TEMPLATE,
240                 TM_TEMPLATE_END
241         };
242
243         LexerKeyword templatetags[] = {
244                 { "preambledef", TM_PREAMBLEDEF },
245                 { "preambledefend", TM_PREAMBLEDEF_END },
246                 { "template", TM_TEMPLATE },
247                 { "templateend", TM_TEMPLATE_END }
248         };
249
250         // Read the templates list
251         vector<string> templateslist;
252         FileName const real_file = libFileSearch("", "xtemplates.lst");
253         LYXERR(Debug::EXTERNAL, "Reading external templates from `" << real_file << '\'');
254
255         if (real_file.empty()) {
256                 LYXERR0("unable to find external templates file `xtemplates.lst'.\n"
257                         << "No external templates will be available.");
258                 return;
259         }
260
261         Lexer tlex;
262         if (!tlex.setFile(real_file)) {
263                 LYXERR0("lyxlex was not able to set file: "
264                         << real_file << ".\nNo external templates will be available.");
265                 return;
266         }
267
268         if (!tlex.isOK()) {
269                 LYXERR0("unable to open external templates file  `"
270                         << to_utf8(makeDisplayPath(real_file.absFileName(), 1000))
271                         << "'\nNo external templates will be available.");
272                 return;
273         }
274
275         bool finished = false;
276         // Parse external templates files
277         LYXERR(Debug::EXTERNAL, "Starting parsing of xtemplates.lst");
278         while (tlex.isOK() && !finished) {
279                 LYXERR(Debug::EXTERNAL, "\tline by line");
280                 switch (tlex.lex()) {
281                 case Lexer::LEX_FEOF:
282                         finished = true;
283                         break;
284                 default:
285                         string const name = tlex.getString();
286                         LYXERR(Debug::EXTERNAL, "Template name: " << name);
287                         templateslist.push_back(name);
288                         break;
289                 }
290         }
291
292         LYXERR(Debug::EXTERNAL, "End of parsing of xtemplates.lst");
293
294         for (vector<string>::const_iterator it = templateslist.begin(); it != templateslist.end(); ++it) {
295                 FileName const filename = libFileSearch("xtemplates", *it);
296                 LYXERR(Debug::EXTERNAL, "Reading template file " << filename.absFileName());
297                 Lexer lex(templatetags);
298                 if (filename.empty() || !lex.setFile(filename)) {
299                         lex.printError("external::TemplateManager::readTemplates: "
300                                        "No template file");
301                         return;
302                 }
303
304                 char const * const preamble_end_tag =
305                         templatetags[TM_PREAMBLEDEF_END-1].tag;
306
307                 while (lex.isOK()) {
308                         switch (lex.lex()) {
309                         case TM_PREAMBLEDEF: {
310                                 lex.next();
311                                 string const name = lex.getString();
312                                 preambledefs[name] = lex.getLongString(from_ascii(preamble_end_tag));
313                                 break;
314                         }
315
316                         case TM_TEMPLATE: {
317                                 lex.next();
318                                 string const name = lex.getString();
319                                 Template & tmp = templates[name];
320                                 tmp.lyxName = name;
321                                 tmp.readTemplate(lex);
322                                 break;
323                         }
324
325                         case TM_TEMPLATE_END:
326                                 lex.printError("Warning: End outside Template.");
327                                 break;
328
329                         case TM_PREAMBLEDEF_END:
330                                 lex.printError("Warning: End outside PreambleDef.");
331                                 break;
332                         default:
333                                 break;
334                         }
335                 }
336         }
337 }
338
339
340 void Template::readTemplate(Lexer & lex)
341 {
342         enum {
343                 TO_GUINAME = 1,
344                 TO_HELPTEXT,
345                 TO_INPUTFORMAT,
346                 TO_FILTER,
347                 TO_AUTOMATIC,
348                 TO_PREVIEW,
349                 TO_TRANSFORM,
350                 TO_FORMAT,
351                 TO_END
352         };
353
354         LexerKeyword templateoptiontags[] = {
355                 { "automaticproduction", TO_AUTOMATIC },
356                 { "filefilter", TO_FILTER },
357                 { "format", TO_FORMAT },
358                 { "guiname", TO_GUINAME },
359                 { "helptext", TO_HELPTEXT },
360                 { "inputformat", TO_INPUTFORMAT },
361                 { "preview", TO_PREVIEW },
362                 { "templateend", TO_END },
363                 { "transform", TO_TRANSFORM }
364         };
365
366         PushPopHelper pph(lex, templateoptiontags);
367         lex.setContext("Template::readTemplate");
368
369         string token;
370         while (lex.isOK()) {
371                 switch (lex.lex()) {
372                 case TO_GUINAME:
373                         lex.next(true);
374                         guiName = lex.getString();
375                         break;
376
377                 case TO_HELPTEXT:
378                         helpText = lex.getLongString(from_ascii("HelpTextEnd"));
379                         break;
380
381                 case TO_INPUTFORMAT:
382                         lex.next(true);
383                         inputFormat = lex.getString();
384                         break;
385
386                 case TO_FILTER:
387                         lex.next(true);
388                         fileRegExp = lex.getString();
389                         break;
390
391                 case TO_AUTOMATIC:
392                         lex.next();
393                         automaticProduction = lex.getBool();
394                         break;
395
396                 case TO_PREVIEW:
397                         lex >> token;
398                         if (token == "InstantPreview")
399                                 preview_mode = PREVIEW_INSTANT;
400                         else if (token == "Graphics")
401                                 preview_mode = PREVIEW_GRAPHICS;
402                         else
403                                 preview_mode = PREVIEW_OFF;
404                         break;
405
406                 case TO_TRANSFORM: {
407                         lex >> token;
408                         TransformID id = transformIDTranslator().find(token);
409                         if (int(id) == -1)
410                                 LYXERR0("Transform " << token << " is not recognized");
411                         else
412                                 transformIds.push_back(id);
413                         break;
414                 }
415
416                 case TO_FORMAT:
417                         lex.next(true);
418                         formats[lex.getString()].readFormat(lex);
419                         break;
420
421                 case TO_END:
422                         return;
423                 }
424         }
425 }
426
427
428 namespace {
429
430 void transform_not_found(ostream & os, string const & transform)
431 {
432         os << "external::Format::readFormat. Transformation \""
433            << transform << "\" is unrecognized." << endl;
434 }
435
436
437 void transform_class_not_found(ostream & os, string const & tclass)
438 {
439         os << "external::Format::readFormat. Transformation class \""
440            << tclass << "\" is unrecognized." << endl;
441 }
442
443
444 void setCommandFactory(Template::Format & format, string const & transform,
445                        string const & transformer_class)
446 {
447         bool class_found = false;
448         if (transform == "Resize" && transformer_class == "ResizeLatexCommand") {
449                 class_found = true;
450                 ResizeCommandFactory factory = ResizeLatexCommand::factory;
451                 format.command_transformers[Resize] =
452                         TransformStore(Resize, factory);
453
454         } else if (transform == "Rotate" &&
455                    transformer_class == "RotationLatexCommand") {
456                 class_found = true;
457                 RotationCommandFactory factory = RotationLatexCommand::factory;
458                 format.command_transformers[Rotate] =
459                         TransformStore(Rotate, factory);
460
461         } else
462                 transform_not_found(lyxerr, transform);
463
464         if (!class_found)
465                 transform_class_not_found(lyxerr, transformer_class);
466 }
467
468
469 void setOptionFactory(Template::Format & format, string const & transform,
470                 string const & transformer_class)
471 {
472         bool class_found = false;
473         if (transform == "Clip" && transformer_class == "ClipLatexOption") {
474                 class_found = true;
475                 ClipOptionFactory factory = ClipLatexOption::factory;
476                 format.option_transformers[Clip] =
477                                 TransformStore(Clip, factory);
478
479         } else if (transform == "Extra" && transformer_class == "ExtraOption") {
480                 class_found = true;
481                 ExtraOptionFactory factory = ExtraOption::factory;
482                 format.option_transformers[Extra] =
483                         TransformStore(Extra, factory);
484
485         } else if (transform == "Resize" &&
486                    transformer_class == "ResizeLatexOption") {
487                 class_found = true;
488                 ResizeOptionFactory factory = ResizeLatexOption::factory;
489                 format.option_transformers[Resize] =
490                         TransformStore(Resize, factory);
491
492         } else if (transform == "Rotate" &&
493                    transformer_class == "RotationLatexOption") {
494                 class_found = true;
495                 RotationOptionFactory factory = RotationLatexOption::factory;
496                 format.option_transformers[Rotate] =
497                         TransformStore(Rotate, factory);
498
499         } else
500                 transform_not_found(lyxerr, transform);
501
502         if (!class_found)
503                 transform_class_not_found(lyxerr, transformer_class);
504 }
505
506 } // namespace
507
508
509 void Template::Format::readFormat(Lexer & lex)
510 {
511         enum {
512                 FO_PRODUCT = 1,
513                 FO_UPDATEFORMAT,
514                 FO_UPDATERESULT,
515                 FO_REQUIREMENT,
516                 FO_OPTION,
517                 FO_PREAMBLE,
518                 FO_TRANSFORMCOMMAND,
519                 FO_TRANSFORMOPTION,
520                 FO_REFERENCEDFILE,
521                 FO_END
522         };
523
524         LexerKeyword formattags[] = {
525                 { "formatend", FO_END },
526                 { "option", FO_OPTION },
527                 { "preamble", FO_PREAMBLE },
528                 { "product", FO_PRODUCT },
529                 { "referencedfile", FO_REFERENCEDFILE },
530                 { "requirement", FO_REQUIREMENT },
531                 { "transformcommand", FO_TRANSFORMCOMMAND },
532                 { "transformoption", FO_TRANSFORMOPTION },
533                 { "updateformat", FO_UPDATEFORMAT },
534                 { "updateresult", FO_UPDATERESULT }
535         };
536
537         PushPopHelper pph(lex, formattags);
538
539         while (lex.isOK()) {
540                 switch (lex.lex()) {
541                 case FO_PRODUCT:
542                         lex.next(true);
543                         product = lex.getString();
544                         break;
545
546                 case FO_UPDATEFORMAT:
547                         lex.next(true);
548                         updateFormat = lex.getString();
549                         break;
550
551                 case FO_UPDATERESULT:
552                         lex.next(true);
553                         updateResult = lex.getString();
554                         break;
555
556                 case FO_REQUIREMENT:
557                         lex.next(true);
558                         requirements.push_back(lex.getString());
559                         break;
560
561                 case FO_PREAMBLE:
562                         lex.next(true);
563                         preambleNames.push_back(lex.getString());
564                         break;
565
566                 case FO_TRANSFORMCOMMAND: {
567                         lex.next(true);
568                         string const name = lex.getString();
569                         lex.next(true);
570                         setCommandFactory(*this, name, lex.getString());
571                         break;
572                 }
573
574                 case FO_TRANSFORMOPTION: {
575                         lex.next(true);
576                         string const name = lex.getString();
577                         lex.next(true);
578                         setOptionFactory(*this, name, lex.getString());
579                         break;
580                 }
581
582                 case FO_OPTION: {
583                         lex.next(true);
584                         string const name = lex.getString();
585                         lex.next(true);
586                         string const opt = lex.getString();
587                         options.push_back(Option(name, opt));
588                         break;
589                 }
590
591                 case FO_REFERENCEDFILE: {
592                         lex.next(true);
593                         string const format = lex.getString();
594                         lex.next(true);
595                         string const file = lex.getString();
596                         referencedFiles[format].push_back(file);
597                         break;
598                 }
599
600                 case FO_END:
601                         return;
602                 }
603         }
604 }
605
606 } // namespace external
607 } // namespace lyx