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