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