3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
15 #include "BufferParams.h"
17 #include "ServerSocket.h"
19 #include "frontends/alert.h" //to be removed?
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"
35 // FIXME: Q_WS_MACX is not available, it's in Qt
36 #ifdef USE_MACOSX_PACKAGING
37 #include "support/linkback/LinkBackProxy.h"
45 using namespace lyx::support;
49 namespace Alert = frontend::Alert;
50 namespace os = support::os;
54 string const token_from_format("$$i");
55 string const token_path_format("$$p");
56 string const token_socket_format("$$a");
59 class FormatNamesEqual : public unary_function<Format, bool> {
61 FormatNamesEqual(string const & name)
63 bool operator()(Format const & f) const
65 return f.name() == name_;
72 class FormatExtensionsEqual : public unary_function<Format, bool> {
74 FormatExtensionsEqual(string const & extension)
75 : extension_(extension) {}
76 bool operator()(Format const & f) const
78 return f.hasExtension(extension_);
85 class FormatMimeEqual : public unary_function<Format, bool> {
87 FormatMimeEqual(string const & mime)
89 bool operator()(Format const & f) const
91 // The test for empty mime strings is needed since we allow
92 // formats with empty mime types.
93 return f.mime() == mime_ && !mime_.empty();
100 class FormatPrettyNameEqual : public unary_function<Format, bool> {
102 FormatPrettyNameEqual(string const & prettyname)
103 : prettyname_(prettyname) {}
104 bool operator()(Format const & f) const
106 return f.prettyname() == prettyname_;
115 bool operator<(Format const & a, Format const & b)
117 return _(a.prettyname()) < _(b.prettyname());
121 Format::Format(string const & n, string const & e, string const & p,
122 string const & s, string const & v, string const & ed,
123 string const & m, int flags)
124 : name_(n), prettyname_(p), shortcut_(s), viewer_(v),
125 editor_(ed), mime_(m), flags_(flags)
127 extension_list_ = getVectorFromString(e, ",");
128 LYXERR(Debug::GRAPHICS, "New Format: n=" << n << ", flags=" << flags);
132 bool Format::dummy() const
134 return extension().empty();
138 string const Format::extensions() const
140 return getStringFromVector(extension_list_, ", ");
144 bool Format::hasExtension(string const & e) const
146 return (find(extension_list_.begin(), extension_list_.end(), e)
147 != extension_list_.end());
151 bool Format::isChildFormat() const
155 return isDigitASCII(name_[name_.length() - 1]);
159 string const Format::parentFormat() const
161 return name_.substr(0, name_.length() - 1);
165 void Format::setExtensions(string const & e)
167 extension_list_ = getVectorFromString(e, ",");
171 // This method should return a reference, and throw an exception
172 // if the format named name cannot be found (Lgb)
173 Format const * Formats::getFormat(string const & name) const
175 FormatList::const_iterator cit =
176 find_if(formatlist.begin(), formatlist.end(),
177 FormatNamesEqual(name));
178 if (cit != formatlist.end())
187 /** Guess the file format name (as in Format::name()) from contents.
188 * Normally you don't want to use this directly, but rather
189 * Formats::getFormatFromFile().
191 string guessFormatFromContents(FileName const & fn)
193 // the different filetypes and what they contain in one of the first lines
194 // (dots are any characters). (Herbert 20020131)
197 // EPS %!PS-Adobe-3.0 EPSF...
204 // PBM P1... or P4 (B/W)
205 // PGM P2... or P5 (Grayscale)
206 // PPM P3... or P6 (color)
207 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
208 // SGI \001\332... (decimal 474)
210 // TIFF II... or MM...
212 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
213 // ...static char *...
214 // XWD \000\000\000\151 (0x00006900) decimal 105
216 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
217 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
218 // Z \037\235 UNIX compress
221 if (fn.empty() || !fn.isReadableFile())
224 ifstream ifs(fn.toFilesystemEncoding().c_str());
226 // Couldn't open file...
230 static string const gzipStamp = "\037\213";
233 static string const zipStamp = "PK";
235 // ZIP containers (koffice, openoffice.org etc).
236 static string const nonzipStamp = "\008\0\0\0mimetypeapplication/";
239 static string const compressStamp = "\037\235";
241 // Maximum strings to read
242 int const max_count = 50;
247 bool firstLine = true;
248 while ((count++ < max_count) && format.empty()) {
250 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
251 << "\tFile type not recognised before EOF!");
256 string const stamp = str.substr(0, 2);
257 if (firstLine && str.size() >= 2) {
258 // at first we check for a zipped file, because this
259 // information is saved in the first bytes of the file!
260 // also some graphic formats which save the information
261 // in the first line, too.
262 if (prefixIs(str, gzipStamp)) {
265 } else if (stamp == zipStamp &&
266 !contains(str, nonzipStamp)) {
269 } else if (stamp == compressStamp) {
273 } else if (stamp == "BM") {
276 } else if (stamp == "\001\332") {
280 // Don't need to use str.at(0), str.at(1) because
281 // we already know that str.size() >= 2
282 } else if (str[0] == 'P') {
298 } else if ((stamp == "II") || (stamp == "MM")) {
301 } else if (prefixIs(str,"%TGIF")) {
304 } else if (prefixIs(str,"#FIG")) {
307 } else if (prefixIs(str,"GIF")) {
310 } else if (str.size() > 3) {
311 int const c = ((str[0] << 24) & (str[1] << 16) &
312 (str[2] << 8) & str[3]);
323 else if (contains(str,"EPSF"))
324 // dummy, if we have wrong file description like
325 // %!PS-Adobe-2.0EPSF"
328 else if (contains(str, "Grace"))
331 else if (contains(str, "JFIF"))
334 else if (contains(str, "%PDF"))
337 else if (contains(str, "PNG"))
340 else if (contains(str, "%!PS-Adobe")) {
343 if (contains(str,"EPSF"))
349 else if (contains(str, "_bits[]"))
352 else if (contains(str, "XPM") || contains(str, "static char *"))
355 else if (contains(str, "BITPIX"))
359 if (!format.empty()) {
360 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
364 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
365 << "\tCouldn't find a known format!");
372 string Formats::getFormatFromFile(FileName const & filename) const
374 if (filename.empty())
378 magic_t magic_cookie = magic_open(MAGIC_MIME);
381 if (magic_load(magic_cookie, NULL) != 0) {
382 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
383 << "\tCouldn't load magic database - "
384 << magic_error(magic_cookie));
386 string mime = magic_file(magic_cookie,
387 filename.toFilesystemEncoding().c_str());
388 mime = token(mime, ';', 0);
389 // we need our own ps/eps detection
390 if (mime != "application/postscript") {
391 Formats::const_iterator cit =
392 find_if(formatlist.begin(), formatlist.end(),
393 FormatMimeEqual(mime));
394 if (cit != formats.end()) {
395 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
396 << mime << " -> " << cit->name());
397 format = cit->name();
401 magic_close(magic_cookie);
407 string const format = guessFormatFromContents(filename);
408 string const ext = getExtension(filename.absFileName());
409 if (isZippedFileFormat(format) && !ext.empty()) {
410 string const & fmt_name = formats.getFormatFromExtension(ext);
411 if (!fmt_name.empty()) {
412 Format const * p_format = formats.getFormat(fmt_name);
413 if (p_format && p_format->zippedNative())
414 return p_format->name();
420 // try to find a format from the file extension.
421 return getFormatFromExtension(ext);
425 string Formats::getFormatFromExtension(string const & ext) const
428 // this is ambigous if two formats have the same extension,
429 // but better than nothing
430 Formats::const_iterator cit =
431 find_if(formatlist.begin(), formatlist.end(),
432 FormatExtensionsEqual(ext));
433 if (cit != formats.end()) {
434 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
435 << ext << " -> " << cit->name());
443 string Formats::getFormatFromPrettyName(string const & prettyname) const
445 if (!prettyname.empty()) {
446 Formats::const_iterator cit =
447 find_if(formatlist.begin(), formatlist.end(),
448 FormatPrettyNameEqual(prettyname));
449 if (cit != formats.end())
456 /// Used to store last timestamp of file and whether it is (was) zipped
459 std::time_t timestamp;
460 ZippedInfo(bool zipped, std::time_t timestamp)
461 : zipped(zipped), timestamp(timestamp) { }
465 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
466 static std::map<std::string, ZippedInfo> zipped_;
469 bool Formats::isZippedFile(support::FileName const & filename) const {
470 string const & fname = filename.absFileName();
471 time_t timestamp = filename.lastModified();
472 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
473 if (it != zipped_.end() && it->second.timestamp == timestamp)
474 return it->second.zipped;
475 string const & format = getFormatFromFile(filename);
476 bool zipped = (format == "gzip" || format == "zip");
477 zipped_.insert(pair<string, ZippedInfo>(fname, ZippedInfo(zipped, timestamp)));
482 bool Formats::isZippedFileFormat(string const & format)
484 return contains("gzip zip compress", format) && !format.empty();
488 bool Formats::isPostScriptFileFormat(string const & format)
490 return format == "ps" || format == "eps";
493 static string fixCommand(string const & cmd, string const & ext,
494 os::auto_open_mode mode)
496 // configure.py says we do not want a viewer/editor
500 // Does the OS manage this format?
501 if (os::canAutoOpenFile(ext, mode))
504 // if configure.py found nothing, clear the command
505 if (token(cmd, ' ', 0) == "auto")
508 // use the command found by configure.py
513 void Formats::setAutoOpen()
515 FormatList::iterator fit = formatlist.begin();
516 FormatList::iterator const fend = formatlist.end();
517 for ( ; fit != fend ; ++fit) {
518 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
519 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
524 int Formats::getNumber(string const & name) const
526 FormatList::const_iterator cit =
527 find_if(formatlist.begin(), formatlist.end(),
528 FormatNamesEqual(name));
529 if (cit != formatlist.end())
530 return distance(formatlist.begin(), cit);
536 void Formats::add(string const & name)
538 if (!getFormat(name))
539 add(name, name, name, string(), string(), string(),
540 string(), Format::document);
544 void Formats::add(string const & name, string const & extensions,
545 string const & prettyname, string const & shortcut,
546 string const & viewer, string const & editor,
547 string const & mime, int flags)
549 FormatList::iterator it =
550 find_if(formatlist.begin(), formatlist.end(),
551 FormatNamesEqual(name));
552 if (it == formatlist.end())
553 formatlist.push_back(Format(name, extensions, prettyname,
554 shortcut, viewer, editor, mime, flags));
556 *it = Format(name, extensions, prettyname, shortcut, viewer,
557 editor, mime, flags);
561 void Formats::erase(string const & name)
563 FormatList::iterator it =
564 find_if(formatlist.begin(), formatlist.end(),
565 FormatNamesEqual(name));
566 if (it != formatlist.end())
567 formatlist.erase(it);
573 std::sort(formatlist.begin(), formatlist.end());
577 void Formats::setViewer(string const & name, string const & command)
580 FormatList::iterator it =
581 find_if(formatlist.begin(), formatlist.end(),
582 FormatNamesEqual(name));
583 if (it != formatlist.end())
584 it->setViewer(command);
588 void Formats::setEditor(string const & name, string const & command)
591 FormatList::iterator it =
592 find_if(formatlist.begin(), formatlist.end(),
593 FormatNamesEqual(name));
594 if (it != formatlist.end())
595 it->setEditor(command);
599 bool Formats::view(Buffer const & buffer, FileName const & filename,
600 string const & format_name) const
602 if (filename.empty() || !filename.exists()) {
603 Alert::error(_("Cannot view file"),
604 bformat(_("File does not exist: %1$s"),
605 from_utf8(filename.absFileName())));
609 Format const * format = getFormat(format_name);
610 if (format && format->viewer().empty() &&
611 format->isChildFormat())
612 format = getFormat(format->parentFormat());
613 if (!format || format->viewer().empty()) {
614 // FIXME: I believe this is the wrong place to show alerts, it should be done
615 // by the caller (this should be "utility" code)
616 Alert::error(_("Cannot view file"),
617 bformat(_("No information for viewing %1$s"),
618 prettyName(format_name)));
622 if (format->viewer() == "auto") {
623 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
626 Alert::error(_("Cannot view file"),
627 bformat(_("Auto-view file %1$s failed"),
628 from_utf8(filename.absFileName())));
633 string command = libScriptSearch(format->viewer());
635 if (format_name == "dvi" &&
636 !lyxrc.view_dvi_paper_option.empty()) {
637 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
638 if (!paper_size.empty()) {
639 command += ' ' + lyxrc.view_dvi_paper_option;
640 command += ' ' + paper_size;
641 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
642 buffer.params().papersize != PAPER_CUSTOM)
647 if (!contains(command, token_from_format))
648 command += ' ' + token_from_format;
650 command = subst(command, token_from_format, quoteName(onlyFileName(filename.toFilesystemEncoding())));
651 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
652 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
653 LYXERR(Debug::FILES, "Executing command: " << command);
654 // FIXME UNICODE utf8 can be wrong for files
655 buffer.message(_("Executing command: ") + from_utf8(command));
657 PathChanger p(filename.onlyPath());
659 one.startscript(Systemcall::DontWait, command, buffer.filePath());
661 // we can't report any sort of error, since we aren't waiting
666 bool Formats::edit(Buffer const & buffer, FileName const & filename,
667 string const & format_name) const
669 if (filename.empty() || !filename.exists()) {
670 Alert::error(_("Cannot edit file"),
671 bformat(_("File does not exist: %1$s"),
672 from_utf8(filename.absFileName())));
676 // LinkBack files look like PDF, but have the .linkback extension
677 string const ext = getExtension(filename.absFileName());
678 if (format_name == "pdf" && ext == "linkback") {
679 #ifdef USE_MACOSX_PACKAGING
680 return editLinkBackFile(filename.absFileName().c_str());
682 Alert::error(_("Cannot edit file"),
683 _("LinkBack files can only be edited on Apple Mac OSX."));
685 #endif // USE_MACOSX_PACKAGING
688 Format const * format = getFormat(format_name);
689 if (format && format->editor().empty() &&
690 format->isChildFormat())
691 format = getFormat(format->parentFormat());
692 if (!format || format->editor().empty()) {
693 // FIXME: I believe this is the wrong place to show alerts, it should
694 // be done by the caller (this should be "utility" code)
695 Alert::error(_("Cannot edit file"),
696 bformat(_("No information for editing %1$s"),
697 prettyName(format_name)));
702 if (format->editor() == "auto") {
703 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
706 Alert::error(_("Cannot edit file"),
707 bformat(_("Auto-edit file %1$s failed"),
708 from_utf8(filename.absFileName())));
713 string command = format->editor();
715 if (!contains(command, token_from_format))
716 command += ' ' + token_from_format;
718 command = subst(command, token_from_format, quoteName(filename.toFilesystemEncoding()));
719 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
720 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
721 LYXERR(Debug::FILES, "Executing command: " << command);
722 // FIXME UNICODE utf8 can be wrong for files
723 buffer.message(_("Executing command: ") + from_utf8(command));
726 one.startscript(Systemcall::DontWait, command, buffer.filePath());
728 // we can't report any sort of error, since we aren't waiting
733 docstring const Formats::prettyName(string const & name) const
735 Format const * format = getFormat(name);
737 return from_utf8(format->prettyname());
739 return from_utf8(name);
743 string const Formats::extension(string const & name) const
745 Format const * format = getFormat(name);
747 return format->extension();
753 string const Formats::extensions(string const & name) const
755 Format const * format = getFormat(name);
757 return format->extensions();
764 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
766 FlavorTranslator initFlavorTranslator()
768 FlavorTranslator f(OutputParams::LATEX, "latex");
769 f.addPair(OutputParams::DVILUATEX, "dviluatex");
770 f.addPair(OutputParams::LUATEX, "luatex");
771 f.addPair(OutputParams::PDFLATEX, "pdflatex");
772 f.addPair(OutputParams::XETEX, "xetex");
773 f.addPair(OutputParams::XML, "docbook-xml");
774 f.addPair(OutputParams::HTML, "xhtml");
775 f.addPair(OutputParams::TEXT, "text");
780 FlavorTranslator const & flavorTranslator()
782 static FlavorTranslator translator = initFlavorTranslator();
788 std::string flavor2format(OutputParams::FLAVOR flavor)
790 return flavorTranslator().find(flavor);
794 /* Not currently needed, but I'll leave the code in case it is.
795 OutputParams::FLAVOR format2flavor(std::string fmt)
797 return flavorTranslator().find(fmt);
802 Formats system_formats;