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/mutex.h"
26 #include "support/os.h"
27 #include "support/PathChanger.h"
28 #include "support/Systemcall.h"
29 #include "support/textutils.h"
30 #include "support/Translator.h"
36 // FIXME: Q_WS_MACX is not available, it's in Qt
37 #ifdef USE_MACOSX_PACKAGING
38 #include "support/linkback/LinkBackProxy.h"
46 using namespace lyx::support;
50 namespace Alert = frontend::Alert;
51 namespace os = support::os;
55 string const token_from_format("$$i");
56 string const token_path_format("$$p");
57 string const token_socket_format("$$a");
60 class FormatNamesEqual : public unary_function<Format, bool> {
62 FormatNamesEqual(string const & name)
65 bool operator()(Format const & f) const
67 return f.name() == name_;
74 class FormatExtensionsEqual : public unary_function<Format, bool> {
76 FormatExtensionsEqual(string const & extension)
77 : extension_(extension)
79 bool operator()(Format const & f) const
81 return f.hasExtension(extension_);
88 class FormatMimeEqual : public unary_function<Format, bool> {
90 FormatMimeEqual(string const & mime)
93 bool operator()(Format const & f) const
95 // The test for empty mime strings is needed since we allow
96 // formats with empty mime types.
97 return f.mime() == mime_ && !mime_.empty();
106 bool Format::formatSorter(Format const * lhs, Format const * rhs)
108 return compare_locale(_(lhs->prettyname()), _(rhs->prettyname())) < 0;
111 bool operator<(Format const & a, Format const & b)
113 return compare_locale(_(a.prettyname()), _(b.prettyname())) < 0;
117 Format::Format(string const & n, string const & e, string const & p,
118 string const & s, string const & v, string const & ed,
119 string const & m, int flags)
120 : name_(n), prettyname_(p), shortcut_(s), viewer_(v),
121 editor_(ed), mime_(m), flags_(flags)
123 extension_list_ = getVectorFromString(e, ",");
124 LYXERR(Debug::GRAPHICS, "New Format: n=" << n << ", flags=" << flags);
128 bool Format::dummy() const
130 return extension().empty();
134 string const Format::extensions() const
136 return getStringFromVector(extension_list_, ", ");
140 bool Format::hasExtension(string const & e) const
142 return (find(extension_list_.begin(), extension_list_.end(), e)
143 != extension_list_.end());
147 bool Format::isChildFormat() const
151 return isDigitASCII(name_[name_.length() - 1]);
155 string const Format::parentFormat() const
157 return name_.substr(0, name_.length() - 1);
161 void Format::setExtensions(string const & e)
163 extension_list_ = getVectorFromString(e, ",");
167 // This method should return a reference, and throw an exception
168 // if the format named name cannot be found (Lgb)
169 Format const * Formats::getFormat(string const & name) const
171 FormatList::const_iterator cit =
172 find_if(formatlist.begin(), formatlist.end(),
173 FormatNamesEqual(name));
174 if (cit != formatlist.end())
183 /** Guess the file format name (as in Format::name()) from contents.
184 * Normally you don't want to use this directly, but rather
185 * Formats::getFormatFromFile().
187 string guessFormatFromContents(FileName const & fn)
189 // the different filetypes and what they contain in one of the first lines
190 // (dots are any characters). (Herbert 20020131)
193 // EPS %!PS-Adobe-3.0 EPSF...
197 // JPG \377\330... (0xFFD8)
200 // PBM P1... or P4 (B/W)
201 // PGM P2... or P5 (Grayscale)
202 // PPM P3... or P6 (color)
203 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
204 // SGI \001\332... (decimal 474)
206 // TIFF II... or MM...
208 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
209 // ...static char *...
210 // XWD \000\000\000\151 (0x00006900) decimal 105
212 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
213 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
214 // Z \037\235 UNIX compress
217 if (fn.empty() || !fn.isReadableFile())
220 ifstream ifs(fn.toFilesystemEncoding().c_str());
222 // Couldn't open file...
226 static string const gzipStamp = "\037\213";
229 static string const zipStamp = "PK";
231 // ZIP containers (koffice, openoffice.org etc).
232 static string const nonzipStamp = "\008\0\0\0mimetypeapplication/";
235 static string const compressStamp = "\037\235";
237 // DOS binary EPS according to Adobe TN-5002
238 static string const binEPSStamp = "\xC5\xD0\xD3\xC6";
241 // Maximum strings to read
242 int const max_count = 50;
247 bool firstLine = true;
248 bool backslash = false;
249 bool maybelatex = false;
251 while ((count++ < max_count) && format.empty() && !maybelatex) {
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 == "\377\330") {
279 } else if (stamp == "\001\332") {
281 } else if (prefixIs(str, binEPSStamp)) {
285 // Don't need to use str.at(0), str.at(1) because
286 // we already know that str.size() >= 2
287 } else if (str[0] == 'P') {
303 } else if ((stamp == "II") || (stamp == "MM")) {
306 } else if (prefixIs(str,"%TGIF")) {
309 } else if (prefixIs(str,"#FIG")) {
312 } else if (prefixIs(str,"GIF")) {
315 } else if (str.size() > 3) {
316 int const c = ((str[0] << 24) & (str[1] << 16) &
317 (str[2] << 8) & str[3]);
328 else if (contains(str,"EPSF"))
329 // dummy, if we have wrong file description like
330 // %!PS-Adobe-2.0EPSF"
333 else if (contains(str, "Grace"))
336 else if (contains(str, "%PDF"))
337 // autodetect pdf format for graphics inclusion
340 else if (contains(str, "PNG"))
343 else if (contains(str, "%!PS-Adobe")) {
346 if (contains(str,"EPSF"))
352 else if (contains(str, "_bits[]"))
355 else if (contains(str, "XPM") || contains(str, "static char *"))
358 else if (contains(str, "BITPIX"))
361 else if (contains(str, "\\documentclass") ||
362 contains(str, "\\chapter") ||
363 contains(str, "\\section") ||
364 contains(str, "\\begin") ||
365 contains(str, "\\end") ||
366 contains(str, "$$") ||
367 contains(str, "\\[") ||
368 contains(str, "\\]"))
371 if (contains(str, '\\'))
373 dollars += count_char(str, '$');
374 if (backslash && dollars > 1)
380 if (format.empty() && maybelatex && !isBinaryFile(fn))
383 if (format.empty()) {
385 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
386 "\tFile type not recognised before EOF!");
388 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
392 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
393 << "\tCouldn't find a known format!");
400 string Formats::getFormatFromFile(FileName const & filename) const
402 if (filename.empty())
407 if (filename.exists()) {
408 magic_t magic_cookie = magic_open(MAGIC_MIME);
411 if (magic_load(magic_cookie, NULL) != 0) {
412 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
413 << "\tCouldn't load magic database - "
414 << magic_error(magic_cookie));
416 char const * result = magic_file(magic_cookie,
417 filename.toFilesystemEncoding().c_str());
420 mime = token(result, ';', 0);
422 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
423 << "\tCouldn't query magic database - "
424 << magic_error(magic_cookie));
426 // our own detection is better for binary files (can be anything)
427 // and different plain text formats
428 if (!mime.empty() && mime != "application/octet-stream" &&
429 mime != "text/plain") {
430 Formats::const_iterator cit =
431 find_if(formatlist.begin(), formatlist.end(),
432 FormatMimeEqual(mime));
433 if (cit != formats.end()) {
434 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
435 << mime << " -> " << cit->name());
436 // See special eps/ps handling below
437 if (mime == "application/postscript")
438 psformat = cit->name();
440 format = cit->name();
444 magic_close(magic_cookie);
451 // libmagic does not distinguish eps and ps.
452 // Therefore we need to use our own detection here, but only if it
453 // recognizes either ps or eps. Otherwise the libmagic guess will
454 // be better (bug 9146).
455 string const format = guessFormatFromContents(filename);
456 if (!psformat.empty()) {
457 if (isPostScriptFileFormat(format))
463 string const ext = getExtension(filename.absFileName());
464 if (isZippedFileFormat(format) && !ext.empty()) {
465 string const & fmt_name = formats.getFormatFromExtension(ext);
466 if (!fmt_name.empty()) {
467 Format const * p_format = formats.getFormat(fmt_name);
468 if (p_format && p_format->zippedNative())
469 return p_format->name();
475 // try to find a format from the file extension.
476 return getFormatFromExtension(ext);
480 string Formats::getFormatFromExtension(string const & ext) const
483 // this is ambigous if two formats have the same extension,
484 // but better than nothing
485 Formats::const_iterator cit =
486 find_if(formatlist.begin(), formatlist.end(),
487 FormatExtensionsEqual(ext));
488 if (cit != formats.end()) {
489 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
490 << ext << " -> " << cit->name());
498 /// Used to store last timestamp of file and whether it is (was) zipped
501 std::time_t timestamp;
502 ZippedInfo(bool zipped, std::time_t timestamp)
503 : zipped(zipped), timestamp(timestamp) { }
507 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
508 static std::map<std::string, ZippedInfo> zipped_;
509 static Mutex zipped_mutex;
512 bool Formats::isZippedFile(support::FileName const & filename) const {
513 string const & fname = filename.absFileName();
514 time_t timestamp = filename.lastModified();
515 Mutex::Locker lock(&zipped_mutex);
516 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
517 if (it != zipped_.end() && it->second.timestamp == timestamp)
518 return it->second.zipped;
519 string const & format = getFormatFromFile(filename);
520 bool zipped = (format == "gzip" || format == "zip");
521 zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
526 bool Formats::isZippedFileFormat(string const & format)
528 return contains("gzip zip compress", format) && !format.empty();
532 bool Formats::isPostScriptFileFormat(string const & format)
534 return format == "ps" || format == "eps";
537 static string fixCommand(string const & cmd, string const & ext,
538 os::auto_open_mode mode)
540 // configure.py says we do not want a viewer/editor
544 // Does the OS manage this format?
545 if (os::canAutoOpenFile(ext, mode))
548 // if configure.py found nothing, clear the command
549 if (token(cmd, ' ', 0) == "auto")
552 // use the command found by configure.py
557 void Formats::setAutoOpen()
559 FormatList::iterator fit = formatlist.begin();
560 FormatList::iterator const fend = formatlist.end();
561 for ( ; fit != fend ; ++fit) {
562 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
563 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
568 int Formats::getNumber(string const & name) const
570 FormatList::const_iterator cit =
571 find_if(formatlist.begin(), formatlist.end(),
572 FormatNamesEqual(name));
573 if (cit != formatlist.end())
574 return distance(formatlist.begin(), cit);
580 void Formats::add(string const & name)
582 if (!getFormat(name))
583 add(name, name, name, string(), string(), string(),
584 string(), Format::document);
588 void Formats::add(string const & name, string const & extensions,
589 string const & prettyname, string const & shortcut,
590 string const & viewer, string const & editor,
591 string const & mime, int flags)
593 FormatList::iterator it =
594 find_if(formatlist.begin(), formatlist.end(),
595 FormatNamesEqual(name));
596 if (it == formatlist.end())
597 formatlist.push_back(Format(name, extensions, prettyname,
598 shortcut, viewer, editor, mime, flags));
600 *it = Format(name, extensions, prettyname, shortcut, viewer,
601 editor, mime, flags);
605 void Formats::erase(string const & name)
607 FormatList::iterator it =
608 find_if(formatlist.begin(), formatlist.end(),
609 FormatNamesEqual(name));
610 if (it != formatlist.end())
611 formatlist.erase(it);
617 std::sort(formatlist.begin(), formatlist.end());
621 void Formats::setViewer(string const & name, string const & command)
624 FormatList::iterator it =
625 find_if(formatlist.begin(), formatlist.end(),
626 FormatNamesEqual(name));
627 if (it != formatlist.end())
628 it->setViewer(command);
632 void Formats::setEditor(string const & name, string const & command)
635 FormatList::iterator it =
636 find_if(formatlist.begin(), formatlist.end(),
637 FormatNamesEqual(name));
638 if (it != formatlist.end())
639 it->setEditor(command);
643 bool Formats::view(Buffer const & buffer, FileName const & filename,
644 string const & format_name) const
646 if (filename.empty() || !filename.exists()) {
647 Alert::error(_("Cannot view file"),
648 bformat(_("File does not exist: %1$s"),
649 from_utf8(filename.absFileName())));
653 Format const * format = getFormat(format_name);
654 if (format && format->viewer().empty() &&
655 format->isChildFormat())
656 format = getFormat(format->parentFormat());
657 if (!format || format->viewer().empty()) {
658 // FIXME: I believe this is the wrong place to show alerts, it should be done
659 // by the caller (this should be "utility" code)
660 Alert::error(_("Cannot view file"),
661 bformat(_("No information for viewing %1$s"),
662 prettyName(format_name)));
666 if (format->viewer() == "auto") {
667 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
670 Alert::error(_("Cannot view file"),
671 bformat(_("Auto-view file %1$s failed"),
672 from_utf8(filename.absFileName())));
677 string command = format->viewer();
679 if (format_name == "dvi" &&
680 !lyxrc.view_dvi_paper_option.empty()) {
681 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
682 if (!paper_size.empty()) {
683 command += ' ' + lyxrc.view_dvi_paper_option;
684 command += ' ' + paper_size;
685 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
686 buffer.params().papersize != PAPER_CUSTOM)
691 if (!contains(command, token_from_format))
692 command += ' ' + token_from_format;
694 command = subst(command, token_from_format, quoteName(onlyFileName(filename.toFilesystemEncoding())));
695 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
696 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
697 LYXERR(Debug::FILES, "Executing command: " << command);
698 // FIXME UNICODE utf8 can be wrong for files
699 buffer.message(_("Executing command: ") + from_utf8(command));
701 PathChanger p(filename.onlyPath());
703 one.startscript(Systemcall::DontWait, command, buffer.filePath());
705 // we can't report any sort of error, since we aren't waiting
710 bool Formats::edit(Buffer const & buffer, FileName const & filename,
711 string const & format_name) const
713 if (filename.empty() || !filename.exists()) {
714 Alert::error(_("Cannot edit file"),
715 bformat(_("File does not exist: %1$s"),
716 from_utf8(filename.absFileName())));
720 // LinkBack files look like PDF, but have the .linkback extension
721 string const ext = getExtension(filename.absFileName());
722 if (format_name == "pdf6" && ext == "linkback") {
723 #ifdef USE_MACOSX_PACKAGING
724 return editLinkBackFile(filename.absFileName().c_str());
726 Alert::error(_("Cannot edit file"),
727 _("LinkBack files can only be edited on Apple Mac OSX."));
729 #endif // USE_MACOSX_PACKAGING
732 Format const * format = getFormat(format_name);
733 if (format && format->editor().empty() &&
734 format->isChildFormat())
735 format = getFormat(format->parentFormat());
736 if (!format || format->editor().empty()) {
737 // FIXME: I believe this is the wrong place to show alerts, it should
738 // be done by the caller (this should be "utility" code)
739 Alert::error(_("Cannot edit file"),
740 bformat(_("No information for editing %1$s"),
741 prettyName(format_name)));
746 if (format->editor() == "auto") {
747 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
750 Alert::error(_("Cannot edit file"),
751 bformat(_("Auto-edit file %1$s failed"),
752 from_utf8(filename.absFileName())));
757 string command = format->editor();
759 if (!contains(command, token_from_format))
760 command += ' ' + token_from_format;
762 command = subst(command, token_from_format, quoteName(filename.toFilesystemEncoding()));
763 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
764 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
765 LYXERR(Debug::FILES, "Executing command: " << command);
766 // FIXME UNICODE utf8 can be wrong for files
767 buffer.message(_("Executing command: ") + from_utf8(command));
770 one.startscript(Systemcall::DontWait, command, buffer.filePath());
772 // we can't report any sort of error, since we aren't waiting
777 docstring const Formats::prettyName(string const & name) const
779 Format const * format = getFormat(name);
781 return from_utf8(format->prettyname());
783 return from_utf8(name);
787 string const Formats::extension(string const & name) const
789 Format const * format = getFormat(name);
791 return format->extension();
797 string const Formats::extensions(string const & name) const
799 Format const * format = getFormat(name);
801 return format->extensions();
809 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
812 FlavorTranslator initFlavorTranslator()
814 FlavorTranslator f(OutputParams::LATEX, "latex");
815 f.addPair(OutputParams::DVILUATEX, "dviluatex");
816 f.addPair(OutputParams::LUATEX, "luatex");
817 f.addPair(OutputParams::PDFLATEX, "pdflatex");
818 f.addPair(OutputParams::XETEX, "xetex");
819 f.addPair(OutputParams::XML, "docbook-xml");
820 f.addPair(OutputParams::HTML, "xhtml");
821 f.addPair(OutputParams::TEXT, "text");
826 FlavorTranslator const & flavorTranslator()
828 static FlavorTranslator const translator = initFlavorTranslator();
835 std::string flavor2format(OutputParams::FLAVOR flavor)
837 return flavorTranslator().find(flavor);
841 /* Not currently needed, but I'll leave the code in case it is.
842 OutputParams::FLAVOR format2flavor(std::string fmt)
844 return flavorTranslator().find(fmt);
849 Formats system_formats;