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