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/PathChanger.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)
64 bool operator()(Format const & f) const
66 return f.name() == name_;
73 class FormatExtensionsEqual : public unary_function<Format, bool> {
75 FormatExtensionsEqual(string const & extension)
76 : extension_(extension)
78 bool operator()(Format const & f) const
80 return f.hasExtension(extension_);
87 class FormatMimeEqual : public unary_function<Format, bool> {
89 FormatMimeEqual(string const & mime)
92 bool operator()(Format const & f) const
94 // The test for empty mime strings is needed since we allow
95 // formats with empty mime types.
96 return f.mime() == mime_ && !mime_.empty();
103 class FormatPrettyNameEqual : public unary_function<Format, bool> {
105 FormatPrettyNameEqual(string const & prettyname)
106 : prettyname_(prettyname)
108 bool operator()(Format const & f) const
110 return f.prettyname() == prettyname_;
119 bool operator<(Format const & a, Format const & b)
121 return _(a.prettyname()) < _(b.prettyname());
125 Format::Format(string const & n, string const & e, string const & p,
126 string const & s, string const & v, string const & ed,
127 string const & m, int flags)
128 : name_(n), prettyname_(p), shortcut_(s), viewer_(v),
129 editor_(ed), mime_(m), flags_(flags)
131 extension_list_ = getVectorFromString(e, ",");
132 LYXERR(Debug::GRAPHICS, "New Format: n=" << n << ", flags=" << flags);
136 bool Format::dummy() const
138 return extension().empty();
142 string const Format::extensions() const
144 return getStringFromVector(extension_list_, ", ");
148 bool Format::hasExtension(string const & e) const
150 return (find(extension_list_.begin(), extension_list_.end(), e)
151 != extension_list_.end());
155 bool Format::isChildFormat() const
159 return isDigitASCII(name_[name_.length() - 1]);
163 string const Format::parentFormat() const
165 return name_.substr(0, name_.length() - 1);
169 void Format::setExtensions(string const & e)
171 extension_list_ = getVectorFromString(e, ",");
175 // This method should return a reference, and throw an exception
176 // if the format named name cannot be found (Lgb)
177 Format const * Formats::getFormat(string const & name) const
179 FormatList::const_iterator cit =
180 find_if(formatlist.begin(), formatlist.end(),
181 FormatNamesEqual(name));
182 if (cit != formatlist.end())
191 /** Guess the file format name (as in Format::name()) from contents.
192 * Normally you don't want to use this directly, but rather
193 * Formats::getFormatFromFile().
195 string guessFormatFromContents(FileName const & fn)
197 // the different filetypes and what they contain in one of the first lines
198 // (dots are any characters). (Herbert 20020131)
201 // EPS %!PS-Adobe-3.0 EPSF...
208 // PBM P1... or P4 (B/W)
209 // PGM P2... or P5 (Grayscale)
210 // PPM P3... or P6 (color)
211 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
212 // SGI \001\332... (decimal 474)
214 // TIFF II... or MM...
216 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
217 // ...static char *...
218 // XWD \000\000\000\151 (0x00006900) decimal 105
220 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
221 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
222 // Z \037\235 UNIX compress
225 if (fn.empty() || !fn.isReadableFile())
228 ifstream ifs(fn.toFilesystemEncoding().c_str());
230 // Couldn't open file...
234 static string const gzipStamp = "\037\213";
237 static string const zipStamp = "PK";
239 // ZIP containers (koffice, openoffice.org etc).
240 static string const nonzipStamp = "\008\0\0\0mimetypeapplication/";
243 static string const compressStamp = "\037\235";
245 // Maximum strings to read
246 int const max_count = 50;
251 bool firstLine = true;
252 while ((count++ < max_count) && format.empty()) {
254 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
255 << "\tFile type not recognised before EOF!");
260 string const stamp = str.substr(0, 2);
261 if (firstLine && str.size() >= 2) {
262 // at first we check for a zipped file, because this
263 // information is saved in the first bytes of the file!
264 // also some graphic formats which save the information
265 // in the first line, too.
266 if (prefixIs(str, gzipStamp)) {
269 } else if (stamp == zipStamp &&
270 !contains(str, nonzipStamp)) {
273 } else if (stamp == compressStamp) {
277 } else if (stamp == "BM") {
280 } else if (stamp == "\001\332") {
284 // Don't need to use str.at(0), str.at(1) because
285 // we already know that str.size() >= 2
286 } else if (str[0] == 'P') {
302 } else if ((stamp == "II") || (stamp == "MM")) {
305 } else if (prefixIs(str,"%TGIF")) {
308 } else if (prefixIs(str,"#FIG")) {
311 } else if (prefixIs(str,"GIF")) {
314 } else if (str.size() > 3) {
315 int const c = ((str[0] << 24) & (str[1] << 16) &
316 (str[2] << 8) & str[3]);
327 else if (contains(str,"EPSF"))
328 // dummy, if we have wrong file description like
329 // %!PS-Adobe-2.0EPSF"
332 else if (contains(str, "Grace"))
335 else if (contains(str, "JFIF"))
338 else if (contains(str, "%PDF"))
341 else if (contains(str, "PNG"))
344 else if (contains(str, "%!PS-Adobe")) {
347 if (contains(str,"EPSF"))
353 else if (contains(str, "_bits[]"))
356 else if (contains(str, "XPM") || contains(str, "static char *"))
359 else if (contains(str, "BITPIX"))
363 if (!format.empty()) {
364 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
368 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
369 << "\tCouldn't find a known format!");
376 string Formats::getFormatFromFile(FileName const & filename) const
378 if (filename.empty())
382 if (filename.exists()) {
383 magic_t magic_cookie = magic_open(MAGIC_MIME);
386 if (magic_load(magic_cookie, NULL) != 0) {
387 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
388 << "\tCouldn't load magic database - "
389 << magic_error(magic_cookie));
391 string mime = magic_file(magic_cookie,
392 filename.toFilesystemEncoding().c_str());
393 mime = token(mime, ';', 0);
394 // we need our own ps/eps detection
395 if ((mime != "application/postscript") && (mime != "text/plain")) {
396 Formats::const_iterator cit =
397 find_if(formatlist.begin(), formatlist.end(),
398 FormatMimeEqual(mime));
399 if (cit != formats.end()) {
400 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
401 << mime << " -> " << cit->name());
402 format = cit->name();
406 magic_close(magic_cookie);
413 string const format = guessFormatFromContents(filename);
414 string const ext = getExtension(filename.absFileName());
415 if (isZippedFileFormat(format) && !ext.empty()) {
416 string const & fmt_name = formats.getFormatFromExtension(ext);
417 if (!fmt_name.empty()) {
418 Format const * p_format = formats.getFormat(fmt_name);
419 if (p_format && p_format->zippedNative())
420 return p_format->name();
426 // try to find a format from the file extension.
427 return getFormatFromExtension(ext);
431 string Formats::getFormatFromExtension(string const & ext) const
434 // this is ambigous if two formats have the same extension,
435 // but better than nothing
436 Formats::const_iterator cit =
437 find_if(formatlist.begin(), formatlist.end(),
438 FormatExtensionsEqual(ext));
439 if (cit != formats.end()) {
440 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
441 << ext << " -> " << cit->name());
449 string Formats::getFormatFromPrettyName(string const & prettyname) const
451 if (!prettyname.empty()) {
452 Formats::const_iterator cit =
453 find_if(formatlist.begin(), formatlist.end(),
454 FormatPrettyNameEqual(prettyname));
455 if (cit != formats.end())
462 /// Used to store last timestamp of file and whether it is (was) zipped
465 std::time_t timestamp;
466 ZippedInfo(bool zipped, std::time_t timestamp)
467 : zipped(zipped), timestamp(timestamp) { }
471 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
472 static std::map<std::string, ZippedInfo> zipped_;
475 bool Formats::isZippedFile(support::FileName const & filename) const {
476 string const & fname = filename.absFileName();
477 time_t timestamp = filename.lastModified();
478 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
479 if (it != zipped_.end() && it->second.timestamp == timestamp)
480 return it->second.zipped;
481 string const & format = getFormatFromFile(filename);
482 bool zipped = (format == "gzip" || format == "zip");
483 zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
488 bool Formats::isZippedFileFormat(string const & format)
490 return contains("gzip zip compress", format) && !format.empty();
494 bool Formats::isPostScriptFileFormat(string const & format)
496 return format == "ps" || format == "eps";
499 static string fixCommand(string const & cmd, string const & ext,
500 os::auto_open_mode mode)
502 // configure.py says we do not want a viewer/editor
506 // Does the OS manage this format?
507 if (os::canAutoOpenFile(ext, mode))
510 // if configure.py found nothing, clear the command
511 if (token(cmd, ' ', 0) == "auto")
514 // use the command found by configure.py
519 void Formats::setAutoOpen()
521 FormatList::iterator fit = formatlist.begin();
522 FormatList::iterator const fend = formatlist.end();
523 for ( ; fit != fend ; ++fit) {
524 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
525 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
530 int Formats::getNumber(string const & name) const
532 FormatList::const_iterator cit =
533 find_if(formatlist.begin(), formatlist.end(),
534 FormatNamesEqual(name));
535 if (cit != formatlist.end())
536 return distance(formatlist.begin(), cit);
542 void Formats::add(string const & name)
544 if (!getFormat(name))
545 add(name, name, name, string(), string(), string(),
546 string(), Format::document);
550 void Formats::add(string const & name, string const & extensions,
551 string const & prettyname, string const & shortcut,
552 string const & viewer, string const & editor,
553 string const & mime, int flags)
555 FormatList::iterator it =
556 find_if(formatlist.begin(), formatlist.end(),
557 FormatNamesEqual(name));
558 if (it == formatlist.end())
559 formatlist.push_back(Format(name, extensions, prettyname,
560 shortcut, viewer, editor, mime, flags));
562 *it = Format(name, extensions, prettyname, shortcut, viewer,
563 editor, mime, flags);
567 void Formats::erase(string const & name)
569 FormatList::iterator it =
570 find_if(formatlist.begin(), formatlist.end(),
571 FormatNamesEqual(name));
572 if (it != formatlist.end())
573 formatlist.erase(it);
579 std::sort(formatlist.begin(), formatlist.end());
583 void Formats::setViewer(string const & name, string const & command)
586 FormatList::iterator it =
587 find_if(formatlist.begin(), formatlist.end(),
588 FormatNamesEqual(name));
589 if (it != formatlist.end())
590 it->setViewer(command);
594 void Formats::setEditor(string const & name, string const & command)
597 FormatList::iterator it =
598 find_if(formatlist.begin(), formatlist.end(),
599 FormatNamesEqual(name));
600 if (it != formatlist.end())
601 it->setEditor(command);
605 bool Formats::view(Buffer const & buffer, FileName const & filename,
606 string const & format_name) const
608 if (filename.empty() || !filename.exists()) {
609 Alert::error(_("Cannot view file"),
610 bformat(_("File does not exist: %1$s"),
611 from_utf8(filename.absFileName())));
615 Format const * format = getFormat(format_name);
616 if (format && format->viewer().empty() &&
617 format->isChildFormat())
618 format = getFormat(format->parentFormat());
619 if (!format || format->viewer().empty()) {
620 // FIXME: I believe this is the wrong place to show alerts, it should be done
621 // by the caller (this should be "utility" code)
622 Alert::error(_("Cannot view file"),
623 bformat(_("No information for viewing %1$s"),
624 prettyName(format_name)));
628 if (format->viewer() == "auto") {
629 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
632 Alert::error(_("Cannot view file"),
633 bformat(_("Auto-view file %1$s failed"),
634 from_utf8(filename.absFileName())));
639 string command = libScriptSearch(format->viewer());
641 if (format_name == "dvi" &&
642 !lyxrc.view_dvi_paper_option.empty()) {
643 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
644 if (!paper_size.empty()) {
645 command += ' ' + lyxrc.view_dvi_paper_option;
646 command += ' ' + paper_size;
647 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
648 buffer.params().papersize != PAPER_CUSTOM)
653 if (!contains(command, token_from_format))
654 command += ' ' + token_from_format;
656 command = subst(command, token_from_format, quoteName(onlyFileName(filename.toFilesystemEncoding())));
657 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
658 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
659 LYXERR(Debug::FILES, "Executing command: " << command);
660 // FIXME UNICODE utf8 can be wrong for files
661 buffer.message(_("Executing command: ") + from_utf8(command));
663 PathChanger p(filename.onlyPath());
665 one.startscript(Systemcall::DontWait, command, buffer.filePath());
667 // we can't report any sort of error, since we aren't waiting
672 bool Formats::edit(Buffer const & buffer, FileName const & filename,
673 string const & format_name) const
675 if (filename.empty() || !filename.exists()) {
676 Alert::error(_("Cannot edit file"),
677 bformat(_("File does not exist: %1$s"),
678 from_utf8(filename.absFileName())));
682 // LinkBack files look like PDF, but have the .linkback extension
683 string const ext = getExtension(filename.absFileName());
684 if (format_name == "pdf" && ext == "linkback") {
685 #ifdef USE_MACOSX_PACKAGING
686 return editLinkBackFile(filename.absFileName().c_str());
688 Alert::error(_("Cannot edit file"),
689 _("LinkBack files can only be edited on Apple Mac OSX."));
691 #endif // USE_MACOSX_PACKAGING
694 Format const * format = getFormat(format_name);
695 if (format && format->editor().empty() &&
696 format->isChildFormat())
697 format = getFormat(format->parentFormat());
698 if (!format || format->editor().empty()) {
699 // FIXME: I believe this is the wrong place to show alerts, it should
700 // be done by the caller (this should be "utility" code)
701 Alert::error(_("Cannot edit file"),
702 bformat(_("No information for editing %1$s"),
703 prettyName(format_name)));
708 if (format->editor() == "auto") {
709 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
712 Alert::error(_("Cannot edit file"),
713 bformat(_("Auto-edit file %1$s failed"),
714 from_utf8(filename.absFileName())));
719 string command = format->editor();
721 if (!contains(command, token_from_format))
722 command += ' ' + token_from_format;
724 command = subst(command, token_from_format, quoteName(filename.toFilesystemEncoding()));
725 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
726 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
727 LYXERR(Debug::FILES, "Executing command: " << command);
728 // FIXME UNICODE utf8 can be wrong for files
729 buffer.message(_("Executing command: ") + from_utf8(command));
732 one.startscript(Systemcall::DontWait, command, buffer.filePath());
734 // we can't report any sort of error, since we aren't waiting
739 docstring const Formats::prettyName(string const & name) const
741 Format const * format = getFormat(name);
743 return from_utf8(format->prettyname());
745 return from_utf8(name);
749 string const Formats::extension(string const & name) const
751 Format const * format = getFormat(name);
753 return format->extension();
759 string const Formats::extensions(string const & name) const
761 Format const * format = getFormat(name);
763 return format->extensions();
771 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
774 FlavorTranslator initFlavorTranslator()
776 FlavorTranslator f(OutputParams::LATEX, "latex");
777 f.addPair(OutputParams::DVILUATEX, "dviluatex");
778 f.addPair(OutputParams::LUATEX, "luatex");
779 f.addPair(OutputParams::PDFLATEX, "pdflatex");
780 f.addPair(OutputParams::XETEX, "xetex");
781 f.addPair(OutputParams::XML, "docbook-xml");
782 f.addPair(OutputParams::HTML, "xhtml");
783 f.addPair(OutputParams::TEXT, "text");
788 FlavorTranslator const & flavorTranslator()
790 static FlavorTranslator translator = initFlavorTranslator();
797 std::string flavor2format(OutputParams::FLAVOR flavor)
799 return flavorTranslator().find(flavor);
803 /* Not currently needed, but I'll leave the code in case it is.
804 OutputParams::FLAVOR format2flavor(std::string fmt)
806 return flavorTranslator().find(fmt);
811 Formats system_formats;