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();
105 bool Format::formatSorter(Format const * lhs, Format const * rhs)
107 return _(lhs->prettyname()) < _(rhs->prettyname());
110 bool operator<(Format const & a, Format const & b)
112 return _(a.prettyname()) < _(b.prettyname());
116 Format::Format(string const & n, string const & e, string const & p,
117 string const & s, string const & v, string const & ed,
118 string const & m, int flags)
119 : name_(n), prettyname_(p), shortcut_(s), viewer_(v),
120 editor_(ed), mime_(m), flags_(flags)
122 extension_list_ = getVectorFromString(e, ",");
123 LYXERR(Debug::GRAPHICS, "New Format: n=" << n << ", flags=" << flags);
127 bool Format::dummy() const
129 return extension().empty();
133 string const Format::extensions() const
135 return getStringFromVector(extension_list_, ", ");
139 bool Format::hasExtension(string const & e) const
141 return (find(extension_list_.begin(), extension_list_.end(), e)
142 != extension_list_.end());
146 bool Format::isChildFormat() const
150 return isDigitASCII(name_[name_.length() - 1]);
154 string const Format::parentFormat() const
156 return name_.substr(0, name_.length() - 1);
160 void Format::setExtensions(string const & e)
162 extension_list_ = getVectorFromString(e, ",");
166 // This method should return a reference, and throw an exception
167 // if the format named name cannot be found (Lgb)
168 Format const * Formats::getFormat(string const & name) const
170 FormatList::const_iterator cit =
171 find_if(formatlist.begin(), formatlist.end(),
172 FormatNamesEqual(name));
173 if (cit != formatlist.end())
182 /** Guess the file format name (as in Format::name()) from contents.
183 * Normally you don't want to use this directly, but rather
184 * Formats::getFormatFromFile().
186 string guessFormatFromContents(FileName const & fn)
188 // the different filetypes and what they contain in one of the first lines
189 // (dots are any characters). (Herbert 20020131)
192 // EPS %!PS-Adobe-3.0 EPSF...
196 // JPG \377\330... (0xFFD8)
199 // PBM P1... or P4 (B/W)
200 // PGM P2... or P5 (Grayscale)
201 // PPM P3... or P6 (color)
202 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
203 // SGI \001\332... (decimal 474)
205 // TIFF II... or MM...
207 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
208 // ...static char *...
209 // XWD \000\000\000\151 (0x00006900) decimal 105
211 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
212 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
213 // Z \037\235 UNIX compress
216 if (fn.empty() || !fn.isReadableFile())
219 ifstream ifs(fn.toFilesystemEncoding().c_str());
221 // Couldn't open file...
225 static string const gzipStamp = "\037\213";
228 static string const zipStamp = "PK";
230 // ZIP containers (koffice, openoffice.org etc).
231 static string const nonzipStamp = "\008\0\0\0mimetypeapplication/";
234 static string const compressStamp = "\037\235";
236 // Maximum strings to read
237 int const max_count = 50;
242 bool firstLine = true;
243 bool backslash = false;
245 while ((count++ < max_count) && format.empty()) {
250 string const stamp = str.substr(0, 2);
251 if (firstLine && str.size() >= 2) {
252 // at first we check for a zipped file, because this
253 // information is saved in the first bytes of the file!
254 // also some graphic formats which save the information
255 // in the first line, too.
256 if (prefixIs(str, gzipStamp)) {
259 } else if (stamp == zipStamp &&
260 !contains(str, nonzipStamp)) {
263 } else if (stamp == compressStamp) {
267 } else if (stamp == "BM") {
270 } else if (stamp == "\377\330") {
273 } else if (stamp == "\001\332") {
277 // Don't need to use str.at(0), str.at(1) because
278 // we already know that str.size() >= 2
279 } else if (str[0] == 'P') {
295 } else if ((stamp == "II") || (stamp == "MM")) {
298 } else if (prefixIs(str,"%TGIF")) {
301 } else if (prefixIs(str,"#FIG")) {
304 } else if (prefixIs(str,"GIF")) {
307 } else if (str.size() > 3) {
308 int const c = ((str[0] << 24) & (str[1] << 16) &
309 (str[2] << 8) & str[3]);
320 else if (contains(str,"EPSF"))
321 // dummy, if we have wrong file description like
322 // %!PS-Adobe-2.0EPSF"
325 else if (contains(str, "Grace"))
328 else if (contains(str, "%PDF"))
329 // autodetect pdf format for graphics inclusion
332 else if (contains(str, "PNG"))
335 else if (contains(str, "%!PS-Adobe")) {
338 if (contains(str,"EPSF"))
344 else if (contains(str, "_bits[]"))
347 else if (contains(str, "XPM") || contains(str, "static char *"))
350 else if (contains(str, "BITPIX"))
353 else if (contains(str, "\\documentclass") ||
354 contains(str, "\\chapter") ||
355 contains(str, "\\section") ||
356 contains(str, "\\begin") ||
357 contains(str, "\\end") ||
358 contains(str, "$$") ||
359 contains(str, "\\[") ||
360 contains(str, "\\]"))
363 if (contains(str, '\\'))
365 dollars += count_char(str, '$');
369 if (format.empty() && backslash && dollars > 1)
373 if (format.empty()) {
375 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
376 "\tFile type not recognised before EOF!");
378 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
382 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
383 << "\tCouldn't find a known format!");
390 string Formats::getFormatFromFile(FileName const & filename) const
392 if (filename.empty())
396 if (filename.exists()) {
397 magic_t magic_cookie = magic_open(MAGIC_MIME);
400 if (magic_load(magic_cookie, NULL) != 0) {
401 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
402 << "\tCouldn't load magic database - "
403 << magic_error(magic_cookie));
405 char const * result = magic_file(magic_cookie,
406 filename.toFilesystemEncoding().c_str());
409 mime = token(result, ';', 0);
411 LYXERR(Debug::GRAPHICS, "Formats::getFormatFromFile\n"
412 << "\tCouldn't query magic database - "
413 << magic_error(magic_cookie));
415 // we need our own ps/eps detection
416 if (!mime.empty() && mime != "application/postscript" &&
417 mime != "text/plain") {
418 Formats::const_iterator cit =
419 find_if(formatlist.begin(), formatlist.end(),
420 FormatMimeEqual(mime));
421 if (cit != formats.end()) {
422 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
423 << mime << " -> " << cit->name());
424 format = cit->name();
428 magic_close(magic_cookie);
435 string const format = guessFormatFromContents(filename);
436 string const ext = getExtension(filename.absFileName());
437 if (isZippedFileFormat(format) && !ext.empty()) {
438 string const & fmt_name = formats.getFormatFromExtension(ext);
439 if (!fmt_name.empty()) {
440 Format const * p_format = formats.getFormat(fmt_name);
441 if (p_format && p_format->zippedNative())
442 return p_format->name();
448 // try to find a format from the file extension.
449 return getFormatFromExtension(ext);
453 string Formats::getFormatFromExtension(string const & ext) const
456 // this is ambigous if two formats have the same extension,
457 // but better than nothing
458 Formats::const_iterator cit =
459 find_if(formatlist.begin(), formatlist.end(),
460 FormatExtensionsEqual(ext));
461 if (cit != formats.end()) {
462 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
463 << ext << " -> " << cit->name());
471 /// Used to store last timestamp of file and whether it is (was) zipped
474 std::time_t timestamp;
475 ZippedInfo(bool zipped, std::time_t timestamp)
476 : zipped(zipped), timestamp(timestamp) { }
481 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
482 static std::map<std::string, ZippedInfo> zipped_;
485 bool Formats::isZippedFile(support::FileName const & filename) const {
486 string const & fname = filename.absFileName();
487 time_t timestamp = filename.lastModified();
488 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
489 if (it != zipped_.end() && it->second.timestamp == timestamp)
490 return it->second.zipped;
491 string const & format = getFormatFromFile(filename);
492 bool zipped = (format == "gzip" || format == "zip");
493 zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
498 bool Formats::isZippedFileFormat(string const & format)
500 return contains("gzip zip compress", format) && !format.empty();
504 bool Formats::isPostScriptFileFormat(string const & format)
506 return format == "ps" || format == "eps";
509 static string fixCommand(string const & cmd, string const & ext,
510 os::auto_open_mode mode)
512 // configure.py says we do not want a viewer/editor
516 // Does the OS manage this format?
517 if (os::canAutoOpenFile(ext, mode))
520 // if configure.py found nothing, clear the command
521 if (token(cmd, ' ', 0) == "auto")
524 // use the command found by configure.py
529 void Formats::setAutoOpen()
531 FormatList::iterator fit = formatlist.begin();
532 FormatList::iterator const fend = formatlist.end();
533 for ( ; fit != fend ; ++fit) {
534 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
535 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
540 int Formats::getNumber(string const & name) const
542 FormatList::const_iterator cit =
543 find_if(formatlist.begin(), formatlist.end(),
544 FormatNamesEqual(name));
545 if (cit != formatlist.end())
546 return distance(formatlist.begin(), cit);
552 void Formats::add(string const & name)
554 if (!getFormat(name))
555 add(name, name, name, string(), string(), string(),
556 string(), Format::document);
560 void Formats::add(string const & name, string const & extensions,
561 string const & prettyname, string const & shortcut,
562 string const & viewer, string const & editor,
563 string const & mime, int flags)
565 FormatList::iterator it =
566 find_if(formatlist.begin(), formatlist.end(),
567 FormatNamesEqual(name));
568 if (it == formatlist.end())
569 formatlist.push_back(Format(name, extensions, prettyname,
570 shortcut, viewer, editor, mime, flags));
572 *it = Format(name, extensions, prettyname, shortcut, viewer,
573 editor, mime, flags);
577 void Formats::erase(string const & name)
579 FormatList::iterator it =
580 find_if(formatlist.begin(), formatlist.end(),
581 FormatNamesEqual(name));
582 if (it != formatlist.end())
583 formatlist.erase(it);
589 std::sort(formatlist.begin(), formatlist.end());
593 void Formats::setViewer(string const & name, string const & command)
596 FormatList::iterator it =
597 find_if(formatlist.begin(), formatlist.end(),
598 FormatNamesEqual(name));
599 if (it != formatlist.end())
600 it->setViewer(command);
604 void Formats::setEditor(string const & name, string const & command)
607 FormatList::iterator it =
608 find_if(formatlist.begin(), formatlist.end(),
609 FormatNamesEqual(name));
610 if (it != formatlist.end())
611 it->setEditor(command);
615 bool Formats::view(Buffer const & buffer, FileName const & filename,
616 string const & format_name) const
618 if (filename.empty() || !filename.exists()) {
619 Alert::error(_("Cannot view file"),
620 bformat(_("File does not exist: %1$s"),
621 from_utf8(filename.absFileName())));
625 Format const * format = getFormat(format_name);
626 if (format && format->viewer().empty() &&
627 format->isChildFormat())
628 format = getFormat(format->parentFormat());
629 if (!format || format->viewer().empty()) {
630 // FIXME: I believe this is the wrong place to show alerts, it should be done
631 // by the caller (this should be "utility" code)
632 Alert::error(_("Cannot view file"),
633 bformat(_("No information for viewing %1$s"),
634 prettyName(format_name)));
638 if (format->viewer() == "auto") {
639 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
642 Alert::error(_("Cannot view file"),
643 bformat(_("Auto-view file %1$s failed"),
644 from_utf8(filename.absFileName())));
649 string command = libScriptSearch(format->viewer());
651 if (format_name == "dvi" &&
652 !lyxrc.view_dvi_paper_option.empty()) {
653 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
654 if (!paper_size.empty()) {
655 command += ' ' + lyxrc.view_dvi_paper_option;
656 command += ' ' + paper_size;
657 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
658 buffer.params().papersize != PAPER_CUSTOM)
663 if (!contains(command, token_from_format))
664 command += ' ' + token_from_format;
666 command = subst(command, token_from_format, quoteName(onlyFileName(filename.toFilesystemEncoding())));
667 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
668 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
669 LYXERR(Debug::FILES, "Executing command: " << command);
670 // FIXME UNICODE utf8 can be wrong for files
671 buffer.message(_("Executing command: ") + from_utf8(command));
673 PathChanger p(filename.onlyPath());
675 one.startscript(Systemcall::DontWait, command, buffer.filePath());
677 // we can't report any sort of error, since we aren't waiting
682 bool Formats::edit(Buffer const & buffer, FileName const & filename,
683 string const & format_name) const
685 if (filename.empty() || !filename.exists()) {
686 Alert::error(_("Cannot edit file"),
687 bformat(_("File does not exist: %1$s"),
688 from_utf8(filename.absFileName())));
692 // LinkBack files look like PDF, but have the .linkback extension
693 string const ext = getExtension(filename.absFileName());
694 if (format_name == "pdf6" && ext == "linkback") {
695 #ifdef USE_MACOSX_PACKAGING
696 return editLinkBackFile(filename.absFileName().c_str());
698 Alert::error(_("Cannot edit file"),
699 _("LinkBack files can only be edited on Apple Mac OSX."));
701 #endif // USE_MACOSX_PACKAGING
704 Format const * format = getFormat(format_name);
705 if (format && format->editor().empty() &&
706 format->isChildFormat())
707 format = getFormat(format->parentFormat());
708 if (!format || format->editor().empty()) {
709 // FIXME: I believe this is the wrong place to show alerts, it should
710 // be done by the caller (this should be "utility" code)
711 Alert::error(_("Cannot edit file"),
712 bformat(_("No information for editing %1$s"),
713 prettyName(format_name)));
718 if (format->editor() == "auto") {
719 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
722 Alert::error(_("Cannot edit file"),
723 bformat(_("Auto-edit file %1$s failed"),
724 from_utf8(filename.absFileName())));
729 string command = format->editor();
731 if (!contains(command, token_from_format))
732 command += ' ' + token_from_format;
734 command = subst(command, token_from_format, quoteName(filename.toFilesystemEncoding()));
735 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
736 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
737 LYXERR(Debug::FILES, "Executing command: " << command);
738 // FIXME UNICODE utf8 can be wrong for files
739 buffer.message(_("Executing command: ") + from_utf8(command));
742 one.startscript(Systemcall::DontWait, command, buffer.filePath());
744 // we can't report any sort of error, since we aren't waiting
749 docstring const Formats::prettyName(string const & name) const
751 Format const * format = getFormat(name);
753 return from_utf8(format->prettyname());
755 return from_utf8(name);
759 string const Formats::extension(string const & name) const
761 Format const * format = getFormat(name);
763 return format->extension();
769 string const Formats::extensions(string const & name) const
771 Format const * format = getFormat(name);
773 return format->extensions();
781 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
784 FlavorTranslator initFlavorTranslator()
786 FlavorTranslator f(OutputParams::LATEX, "latex");
787 f.addPair(OutputParams::DVILUATEX, "dviluatex");
788 f.addPair(OutputParams::LUATEX, "luatex");
789 f.addPair(OutputParams::PDFLATEX, "pdflatex");
790 f.addPair(OutputParams::XETEX, "xetex");
791 f.addPair(OutputParams::XML, "docbook-xml");
792 f.addPair(OutputParams::HTML, "xhtml");
793 f.addPair(OutputParams::TEXT, "text");
798 FlavorTranslator const & flavorTranslator()
800 static FlavorTranslator const translator = initFlavorTranslator();
807 std::string flavor2format(OutputParams::FLAVOR flavor)
809 return flavorTranslator().find(flavor);
813 /* Not currently needed, but I'll leave the code in case it is.
814 OutputParams::FLAVOR format2flavor(std::string fmt)
816 return flavorTranslator().find(fmt);
821 Formats system_formats;