]> git.lyx.org Git - lyx.git/blob - src/format.C
New auto-open feature from Bo Peng (with help from Jean-Marc and Enrico)
[lyx.git] / src / format.C
1 /**
2  * \file format.C
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 "debug.h"
18 #include "gettext.h"
19 #include "lyxsocket.h"
20
21 #include "frontends/Alert.h" //to be removed?
22
23 #include "support/filetools.h"
24 #include "support/lstrings.h"
25 #include "support/os.h"
26 #include "support/path.h"
27 #include "support/systemcall.h"
28
29 #include <boost/filesystem/operations.hpp>
30
31 using lyx::support::bformat;
32 using lyx::support::compare_ascii_no_case;
33 using lyx::support::contains;
34 using lyx::support::libScriptSearch;
35 using lyx::support::makeDisplayPath;
36 using lyx::support::onlyFilename;
37 using lyx::support::onlyPath;
38 using lyx::support::Path;
39 using lyx::support::quoteName;
40 using lyx::support::subst;
41 using lyx::support::Systemcall;
42 using lyx::support::token;
43
44 using std::string;
45 using std::distance;
46
47 namespace fs = boost::filesystem;
48 namespace os = lyx::support::os;
49
50 extern LyXServerSocket * lyxsocket;
51
52 namespace {
53
54 string const token_from("$$i");
55 string const token_path("$$p");
56 string const token_socket("$$a");
57
58
59 class FormatNamesEqual : public std::unary_function<Format, bool> {
60 public:
61         FormatNamesEqual(string const & name)
62                 : name_(name) {}
63         bool operator()(Format const & f) const
64         {
65                 return f.name() == name_;
66         }
67 private:
68         string name_;
69 };
70
71
72 class FormatExtensionsEqual : public std::unary_function<Format, bool> {
73 public:
74         FormatExtensionsEqual(string const & extension)
75                 : extension_(extension) {}
76         bool operator()(Format const & f) const
77         {
78                 return f.extension() == extension_;
79         }
80 private:
81         string extension_;
82 };
83
84 } //namespace anon
85
86 bool operator<(Format const & a, Format const & b)
87 {
88         // use the compare_ascii_no_case instead of compare_no_case,
89         // because in turkish, 'i' is not the lowercase version of 'I',
90         // and thus turkish locale breaks parsing of tags.
91
92         return compare_ascii_no_case(a.prettyname(), b.prettyname()) < 0;
93 }
94
95 Format::Format(string const & n, string const & e, string const & p,
96                string const & s, string const & v, string const & ed)
97         : name_(n), extension_(e), prettyname_(p), shortcut_(s), viewer_(v), editor_(ed)
98 {}
99
100
101 bool Format::dummy() const
102 {
103         return extension().empty();
104 }
105
106
107 bool Format::isChildFormat() const
108 {
109         if (name_.empty())
110                 return false;
111         return isdigit(name_[name_.length() - 1]);
112 }
113
114
115 string const Format::parentFormat() const
116 {
117         return name_.substr(0, name_.length() - 1);
118 }
119
120
121 // This method should return a reference, and throw an exception
122 // if the format named name cannot be found (Lgb)
123 Format const * Formats::getFormat(string const & name) const
124 {
125         FormatList::const_iterator cit =
126                 find_if(formatlist.begin(), formatlist.end(),
127                         FormatNamesEqual(name));
128         if (cit != formatlist.end())
129                 return &(*cit);
130         else
131                 return 0;
132 }
133
134
135 string Formats::getFormatFromFile(string const & filename) const
136 {
137         if (filename.empty())
138                 return string();
139
140         string const format = lyx::support::getFormatFromContents(filename);
141         if (!format.empty())
142                 return format;
143
144         // try to find a format from the file extension.
145         string const ext(lyx::support::getExtension(filename));
146         if (!ext.empty()) {
147                 // this is ambigous if two formats have the same extension,
148                 // but better than nothing
149                 Formats::const_iterator cit =
150                         find_if(formatlist.begin(), formatlist.end(),
151                                 FormatExtensionsEqual(ext));
152                 if (cit != formats.end()) {
153                         lyxerr[Debug::GRAPHICS]
154                                 << "\twill guess format from file extension: "
155                                 << ext << " -> " << cit->name() << std::endl;
156                         return cit->name();
157                 }
158         }
159         return string();
160 }
161
162 namespace {
163
164 string fixCommand(string const & cmd, string const & ext, 
165                   os::auto_open_mode mode)
166 {
167         // configure.py says we do not want a viewer/editor
168         if (cmd.empty())
169                 return cmd;
170
171         // Does the OS manage this format?
172         if (os::canAutoOpenFile(ext, mode))
173                 return "auto";
174
175         // if configure.py found nothing, clear the command
176         if (token(cmd, ' ', 0) == "none")
177                 return string();
178
179         // use the command found by configure.py
180         return cmd;
181 }
182
183 }
184
185 void Formats::setAutoOpen()
186 {
187         FormatList::iterator fit = formatlist.begin();
188         FormatList::iterator const fend = formatlist.end();
189         for ( ; fit != fend ; ++fit) {
190                 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
191                 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
192         }
193 }
194
195
196 int Formats::getNumber(string const & name) const
197 {
198         FormatList::const_iterator cit =
199                 find_if(formatlist.begin(), formatlist.end(),
200                         FormatNamesEqual(name));
201         if (cit != formatlist.end())
202                 return distance(formatlist.begin(), cit);
203         else
204                 return -1;
205 }
206
207
208 void Formats::add(string const & name)
209 {
210         if (!getFormat(name))
211                 add(name, name, name, string(), string(), string());
212 }
213
214
215 void Formats::add(string const & name, string const & extension,
216                   string const & prettyname, string const & shortcut,
217                   string const & viewer, string const & editor)
218 {
219         FormatList::iterator it =
220                 find_if(formatlist.begin(), formatlist.end(),
221                         FormatNamesEqual(name));
222         if (it == formatlist.end())
223                 formatlist.push_back(Format(name, extension, prettyname,
224                                             shortcut, viewer, editor));
225         else
226                 *it = Format(name, extension, prettyname, shortcut, viewer, editor);
227 }
228
229
230 void Formats::erase(string const & name)
231 {
232         FormatList::iterator it =
233                 find_if(formatlist.begin(), formatlist.end(),
234                         FormatNamesEqual(name));
235         if (it != formatlist.end())
236                 formatlist.erase(it);
237 }
238
239
240 void Formats::sort()
241 {
242         std::sort(formatlist.begin(), formatlist.end());
243 }
244
245
246 void Formats::setViewer(string const & name, string const & command)
247 {
248         add(name);
249         FormatList::iterator it =
250                 find_if(formatlist.begin(), formatlist.end(),
251                         FormatNamesEqual(name));
252         if (it != formatlist.end())
253                 it->setViewer(command);
254 }
255
256
257 bool Formats::view(Buffer const & buffer, string const & filename,
258                    string const & format_name) const
259 {
260         if (filename.empty() || !fs::exists(filename)) {
261                 Alert::error(_("Cannot view file"),
262                         bformat(_("File does not exist: %1$s"),
263                                 filename));
264                 return false;
265         }
266
267         Format const * format = getFormat(format_name);
268         if (format && format->viewer().empty() &&
269             format->isChildFormat())
270                 format = getFormat(format->parentFormat());
271         if (!format || format->viewer().empty()) {
272 // FIXME: I believe this is the wrong place to show alerts, it should be done
273 // by the caller (this should be "utility" code)
274                 Alert::error(_("Cannot view file"),
275                         bformat(_("No information for viewing %1$s"),
276                                 prettyName(format_name)));
277                 return false;
278         }
279         // viewer is 'auto'
280         if (format->viewer() == "auto") {
281                 if (os::autoOpenFile(filename, os::VIEW))
282                         return true;
283                 else {
284                         Alert::error(_("Cannot view file"),
285                                 bformat(_("Auto-view file %1$s failed"),
286                                         filename));
287                         return false;
288                 }
289         }
290
291         string command = libScriptSearch(format->viewer());
292
293         if (format_name == "dvi" &&
294             !lyxrc.view_dvi_paper_option.empty()) {
295                 command += ' ' + lyxrc.view_dvi_paper_option;
296                 string paper_size = buffer.params().paperSizeName();
297                 if (paper_size == "letter")
298                         paper_size = "us";
299                 command += ' ' + paper_size;
300                 if (buffer.params().orientation == ORIENTATION_LANDSCAPE)
301                         command += 'r';
302         }
303
304         if (!contains(command, token_from))
305                 command += ' ' + token_from;
306
307         command = subst(command, token_from,
308                         quoteName(onlyFilename(filename)));
309         command = subst(command, token_path, quoteName(onlyPath(filename)));
310         command = subst(command, token_socket, quoteName(lyxsocket->address()));
311         lyxerr[Debug::FILES] << "Executing command: " << command << std::endl;
312         buffer.message(_("Executing command: ") + command);
313
314         Path p(onlyPath(filename));
315         Systemcall one;
316         int const res = one.startscript(Systemcall::DontWait, command);
317
318         if (res) {
319                 Alert::error(_("Cannot view file"),
320                              bformat(_("An error occurred whilst running %1$s"),
321                                makeDisplayPath(command, 50)));
322                 return false;
323         }
324         return true;
325 }
326
327
328 bool Formats::edit(Buffer const & buffer, string const & filename,
329                          string const & format_name) const
330 {
331         if (filename.empty() || !fs::exists(filename)) {
332                 Alert::error(_("Cannot edit file"),
333                         bformat(_("File does not exist: %1$s"),
334                                 filename));
335                 return false;
336         }
337
338         Format const * format = getFormat(format_name);
339         if (format && format->editor().empty() &&
340             format->isChildFormat())
341                 format = getFormat(format->parentFormat());
342         if (!format || format->editor().empty()) {
343 // FIXME: I believe this is the wrong place to show alerts, it should
344 // be done by the caller (this should be "utility" code)
345                 Alert::error(_("Cannot edit file"),
346                         bformat(_("No information for editing %1$s"),
347                                 prettyName(format_name)));
348                 return false;
349         }
350         // editor is 'auto'
351         if (format->editor() == "auto") {
352                 if (os::autoOpenFile(filename, os::EDIT))
353                         return true;
354                 else {
355                         Alert::error(_("Cannot edit file"),
356                                 bformat(_("Auto-edit file %1$s failed"),
357                                         filename));
358                         return false;
359                 }
360         }
361
362         string command = format->editor();
363
364         if (!contains(command, token_from))
365                 command += ' ' + token_from;
366
367         command = subst(command, token_from,
368                         quoteName(onlyFilename(filename)));
369         command = subst(command, token_path, quoteName(onlyPath(filename)));
370         command = subst(command, token_socket, quoteName(lyxsocket->address()));
371         lyxerr[Debug::FILES] << "Executing command: " << command << std::endl;
372         buffer.message(_("Executing command: ") + command);
373
374         Path p(onlyPath(filename));
375         Systemcall one;
376         int const res = one.startscript(Systemcall::DontWait, command);
377
378         if (res) {
379                 Alert::error(_("Cannot edit file"),
380                              bformat(_("An error occurred whilst running %1$s"),
381                                makeDisplayPath(command, 50)));
382                 return false;
383         }
384         return true;
385 }
386
387
388 string const Formats::prettyName(string const & name) const
389 {
390         Format const * format = getFormat(name);
391         if (format)
392                 return format->prettyname();
393         else
394                 return name;
395 }
396
397
398 string const Formats::extension(string const & name) const
399 {
400         Format const * format = getFormat(name);
401         if (format)
402                 return format->extension();
403         else
404                 return name;
405 }
406
407
408
409
410 Formats formats;
411
412 Formats system_formats;