]> git.lyx.org Git - lyx.git/blob - src/Format.cpp
Small improvement for bug #7509 as suggested by JMarc
[lyx.git] / src / Format.cpp
1 /**
2  * \file Format.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Dekel Tsur
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Format.h"
14 #include "Buffer.h"
15 #include "BufferParams.h"
16 #include "LyXRC.h"
17 #include "ServerSocket.h"
18
19 #include "frontends/alert.h" //to be removed?
20
21 #include "support/debug.h"
22 #include "support/filetools.h"
23 #include "support/gettext.h"
24 #include "support/lstrings.h"
25 #include "support/os.h"
26 #include "support/Systemcall.h"
27 #include "support/textutils.h"
28 #include "support/Translator.h"
29
30 #include <algorithm>
31
32 // FIXME: Q_WS_MACX is not available, it's in Qt
33 #ifdef USE_MACOSX_PACKAGING
34 #include "support/linkback/LinkBackProxy.h"
35 #endif
36
37 using namespace std;
38 using namespace lyx::support;
39
40 namespace lyx {
41
42 namespace Alert = frontend::Alert;
43 namespace os = support::os;
44
45 namespace {
46
47 string const token_from_format("$$i");
48 string const token_path_format("$$p");
49 string const token_socket_format("$$a");
50
51
52 class FormatNamesEqual : public unary_function<Format, bool> {
53 public:
54         FormatNamesEqual(string const & name)
55                 : name_(name) {}
56         bool operator()(Format const & f) const
57         {
58                 return f.name() == name_;
59         }
60 private:
61         string name_;
62 };
63
64
65 class FormatExtensionsEqual : public unary_function<Format, bool> {
66 public:
67         FormatExtensionsEqual(string const & extension)
68                 : extension_(extension) {}
69         bool operator()(Format const & f) const
70         {
71                 return f.extension() == extension_;
72         }
73 private:
74         string extension_;
75 };
76
77 } //namespace anon
78
79 bool operator<(Format const & a, Format const & b)
80 {
81         // use the compare_ascii_no_case instead of compare_no_case,
82         // because in turkish, 'i' is not the lowercase version of 'I',
83         // and thus turkish locale breaks parsing of tags.
84
85         return compare_ascii_no_case(a.prettyname(), b.prettyname()) < 0;
86 }
87
88
89 Format::Format(string const & n, string const & e, string const & p,
90                string const & s, string const & v, string const & ed,
91                int flags)
92         : name_(n), extension_(e), prettyname_(p), shortcut_(s), viewer_(v),
93           editor_(ed), flags_(flags)
94 {}
95
96
97 bool Format::dummy() const
98 {
99         return extension().empty();
100 }
101
102
103 bool Format::isChildFormat() const
104 {
105         if (name_.empty())
106                 return false;
107         return isDigitASCII(name_[name_.length() - 1]);
108 }
109
110
111 string const Format::parentFormat() const
112 {
113         return name_.substr(0, name_.length() - 1);
114 }
115
116
117 // This method should return a reference, and throw an exception
118 // if the format named name cannot be found (Lgb)
119 Format const * Formats::getFormat(string const & name) const
120 {
121         FormatList::const_iterator cit =
122                 find_if(formatlist.begin(), formatlist.end(),
123                         FormatNamesEqual(name));
124         if (cit != formatlist.end())
125                 return &(*cit);
126         else
127                 return 0;
128 }
129
130
131 string Formats::getFormatFromFile(FileName const & filename) const
132 {
133         if (filename.empty())
134                 return string();
135
136         string const format = filename.guessFormatFromContents();
137         if (!format.empty())
138                 return format;
139
140         // try to find a format from the file extension.
141         string const ext = getExtension(filename.absFileName());
142         if (!ext.empty()) {
143                 // this is ambigous if two formats have the same extension,
144                 // but better than nothing
145                 Formats::const_iterator cit =
146                         find_if(formatlist.begin(), formatlist.end(),
147                                 FormatExtensionsEqual(ext));
148                 if (cit != formats.end()) {
149                         LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
150                                 << ext << " -> " << cit->name());
151                         return cit->name();
152                 }
153         }
154         return string();
155 }
156
157
158 static string fixCommand(string const & cmd, string const & ext,
159                   os::auto_open_mode mode)
160 {
161         // configure.py says we do not want a viewer/editor
162         if (cmd.empty())
163                 return cmd;
164
165         // Does the OS manage this format?
166         if (os::canAutoOpenFile(ext, mode))
167                 return "auto";
168
169         // if configure.py found nothing, clear the command
170         if (token(cmd, ' ', 0) == "auto")
171                 return string();
172
173         // use the command found by configure.py
174         return cmd;
175 }
176
177
178 void Formats::setAutoOpen()
179 {
180         FormatList::iterator fit = formatlist.begin();
181         FormatList::iterator const fend = formatlist.end();
182         for ( ; fit != fend ; ++fit) {
183                 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
184                 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
185         }
186 }
187
188
189 int Formats::getNumber(string const & name) const
190 {
191         FormatList::const_iterator cit =
192                 find_if(formatlist.begin(), formatlist.end(),
193                         FormatNamesEqual(name));
194         if (cit != formatlist.end())
195                 return distance(formatlist.begin(), cit);
196         else
197                 return -1;
198 }
199
200
201 void Formats::add(string const & name)
202 {
203         if (!getFormat(name))
204                 add(name, name, name, string(), string(), string(),
205                     Format::document);
206 }
207
208
209 void Formats::add(string const & name, string const & extension,
210                   string const & prettyname, string const & shortcut,
211                   string const & viewer, string const & editor,
212                   int flags)
213 {
214         FormatList::iterator it =
215                 find_if(formatlist.begin(), formatlist.end(),
216                         FormatNamesEqual(name));
217         if (it == formatlist.end())
218                 formatlist.push_back(Format(name, extension, prettyname,
219                                             shortcut, viewer, editor, flags));
220         else
221                 *it = Format(name, extension, prettyname, shortcut, viewer,
222                              editor, flags);
223 }
224
225
226 void Formats::erase(string const & name)
227 {
228         FormatList::iterator it =
229                 find_if(formatlist.begin(), formatlist.end(),
230                         FormatNamesEqual(name));
231         if (it != formatlist.end())
232                 formatlist.erase(it);
233 }
234
235
236 void Formats::sort()
237 {
238         std::sort(formatlist.begin(), formatlist.end());
239 }
240
241
242 void Formats::setViewer(string const & name, string const & command)
243 {
244         add(name);
245         FormatList::iterator it =
246                 find_if(formatlist.begin(), formatlist.end(),
247                         FormatNamesEqual(name));
248         if (it != formatlist.end())
249                 it->setViewer(command);
250 }
251
252
253 void Formats::setEditor(string const & name, string const & command)
254 {
255         add(name);
256         FormatList::iterator it =
257                 find_if(formatlist.begin(), formatlist.end(),
258                         FormatNamesEqual(name));
259         if (it != formatlist.end())
260                 it->setEditor(command);
261 }
262
263
264 bool Formats::view(Buffer const & buffer, FileName const & filename,
265                    string const & format_name) const
266 {
267         if (filename.empty() || !filename.exists()) {
268                 Alert::error(_("Cannot view file"),
269                         bformat(_("File does not exist: %1$s"),
270                                 from_utf8(filename.absFileName())));
271                 return false;
272         }
273
274         Format const * format = getFormat(format_name);
275         if (format && format->viewer().empty() &&
276             format->isChildFormat())
277                 format = getFormat(format->parentFormat());
278         if (!format || format->viewer().empty()) {
279 // FIXME: I believe this is the wrong place to show alerts, it should be done
280 // by the caller (this should be "utility" code)
281                 Alert::error(_("Cannot view file"),
282                         bformat(_("No information for viewing %1$s"),
283                                 prettyName(format_name)));
284                 return false;
285         }
286         // viewer is 'auto'
287         if (format->viewer() == "auto") {
288                 if (os::autoOpenFile(filename.absFileName(), os::VIEW))
289                         return true;
290                 else {
291                         Alert::error(_("Cannot view file"),
292                                 bformat(_("Auto-view file %1$s failed"),
293                                         from_utf8(filename.absFileName())));
294                         return false;
295                 }
296         }
297
298         string command = libScriptSearch(format->viewer());
299
300         if (format_name == "dvi" &&
301             !lyxrc.view_dvi_paper_option.empty()) {
302                 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
303                 if (!paper_size.empty()) {
304                         command += ' ' + lyxrc.view_dvi_paper_option;
305                         command += ' ' + paper_size;
306                         if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
307                             buffer.params().papersize != PAPER_CUSTOM)
308                                 command += 'r';
309                 }
310         }
311
312         if (!contains(command, token_from_format))
313                 command += ' ' + token_from_format;
314
315         command = subst(command, token_from_format, quoteName(filename.toFilesystemEncoding()));
316         command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
317         command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
318         LYXERR(Debug::FILES, "Executing command: " << command);
319         // FIXME UNICODE utf8 can be wrong for files
320         buffer.message(_("Executing command: ") + from_utf8(command));
321
322         Systemcall one;
323         one.startscript(Systemcall::DontWait, command);
324
325         // we can't report any sort of error, since we aren't waiting
326         return true;
327 }
328
329
330 bool Formats::edit(Buffer const & buffer, FileName const & filename,
331                          string const & format_name) const
332 {
333         if (filename.empty() || !filename.exists()) {
334                 Alert::error(_("Cannot edit file"),
335                         bformat(_("File does not exist: %1$s"),
336                                 from_utf8(filename.absFileName())));
337                 return false;
338         }
339
340         // LinkBack files look like PDF, but have the .linkback extension
341         string const ext = getExtension(filename.absFileName());
342         if (format_name == "pdf" && ext == "linkback") {
343 #ifdef USE_MACOSX_PACKAGING
344                 return editLinkBackFile(filename.absFileName().c_str());
345 #else
346                 Alert::error(_("Cannot edit file"),
347                              _("LinkBack files can only be edited on Apple Mac OSX."));
348                 return false;
349 #endif // USE_MACOSX_PACKAGING
350         }
351
352         Format const * format = getFormat(format_name);
353         if (format && format->editor().empty() &&
354             format->isChildFormat())
355                 format = getFormat(format->parentFormat());
356         if (!format || format->editor().empty()) {
357 // FIXME: I believe this is the wrong place to show alerts, it should
358 // be done by the caller (this should be "utility" code)
359                 Alert::error(_("Cannot edit file"),
360                         bformat(_("No information for editing %1$s"),
361                                 prettyName(format_name)));
362                 return false;
363         }
364
365         // editor is 'auto'
366         if (format->editor() == "auto") {
367                 if (os::autoOpenFile(filename.absFileName(), os::EDIT))
368                         return true;
369                 else {
370                         Alert::error(_("Cannot edit file"),
371                                 bformat(_("Auto-edit file %1$s failed"),
372                                         from_utf8(filename.absFileName())));
373                         return false;
374                 }
375         }
376
377         string command = format->editor();
378
379         if (!contains(command, token_from_format))
380                 command += ' ' + token_from_format;
381
382         command = subst(command, token_from_format, quoteName(filename.toFilesystemEncoding()));
383         command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
384         command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
385         LYXERR(Debug::FILES, "Executing command: " << command);
386         // FIXME UNICODE utf8 can be wrong for files
387         buffer.message(_("Executing command: ") + from_utf8(command));
388
389         Systemcall one;
390         one.startscript(Systemcall::DontWait, command);
391
392         // we can't report any sort of error, since we aren't waiting
393         return true;
394 }
395
396
397 docstring const Formats::prettyName(string const & name) const
398 {
399         Format const * format = getFormat(name);
400         if (format)
401                 return from_utf8(format->prettyname());
402         else
403                 return from_utf8(name);
404 }
405
406
407 string const Formats::extension(string const & name) const
408 {
409         Format const * format = getFormat(name);
410         if (format)
411                 return format->extension();
412         else
413                 return name;
414 }
415
416
417 namespace {
418 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
419
420 FlavorTranslator initFlavorTranslator()
421 {
422         FlavorTranslator f(OutputParams::LATEX, "latex");
423         f.addPair(OutputParams::LUATEX, "luatex");
424         f.addPair(OutputParams::PDFLATEX, "pdflatex");
425         f.addPair(OutputParams::XETEX, "xetex");
426         f.addPair(OutputParams::XML, "docbook-xml");
427         f.addPair(OutputParams::HTML, "xhtml");
428         f.addPair(OutputParams::TEXT, "text");
429         return f;
430 }
431
432
433 FlavorTranslator const & flavorTranslator()
434 {
435         static FlavorTranslator translator = initFlavorTranslator();
436         return translator;
437 }
438 }
439
440
441 std::string flavor2format(OutputParams::FLAVOR flavor)
442 {
443         return flavorTranslator().find(flavor);
444 }
445
446
447 /* Not currently needed, but I'll leave the code in case it is.
448 OutputParams::FLAVOR format2flavor(std::string fmt)
449 {
450         return flavorTranslator().find(fmt);
451 } */
452
453 Formats formats;
454
455 Formats system_formats;
456
457
458 } // namespace lyx