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 string mime = magic_file(magic_cookie,
406 filename.toFilesystemEncoding().c_str());
407 mime = token(mime, ';', 0);
408 // we need our own ps/eps detection
409 if ((mime != "application/postscript") && (mime != "text/plain")) {
410 Formats::const_iterator cit =
411 find_if(formatlist.begin(), formatlist.end(),
412 FormatMimeEqual(mime));
413 if (cit != formats.end()) {
414 LYXERR(Debug::GRAPHICS, "\tgot format from MIME type: "
415 << mime << " -> " << cit->name());
416 format = cit->name();
420 magic_close(magic_cookie);
427 string const format = guessFormatFromContents(filename);
428 string const ext = getExtension(filename.absFileName());
429 if (isZippedFileFormat(format) && !ext.empty()) {
430 string const & fmt_name = formats.getFormatFromExtension(ext);
431 if (!fmt_name.empty()) {
432 Format const * p_format = formats.getFormat(fmt_name);
433 if (p_format && p_format->zippedNative())
434 return p_format->name();
440 // try to find a format from the file extension.
441 return getFormatFromExtension(ext);
445 string Formats::getFormatFromExtension(string const & ext) const
448 // this is ambigous if two formats have the same extension,
449 // but better than nothing
450 Formats::const_iterator cit =
451 find_if(formatlist.begin(), formatlist.end(),
452 FormatExtensionsEqual(ext));
453 if (cit != formats.end()) {
454 LYXERR(Debug::GRAPHICS, "\twill guess format from file extension: "
455 << ext << " -> " << cit->name());
463 /// Used to store last timestamp of file and whether it is (was) zipped
466 std::time_t timestamp;
467 ZippedInfo(bool zipped, std::time_t timestamp)
468 : zipped(zipped), timestamp(timestamp) { }
472 /// Mapping absolute pathnames of files to their ZippedInfo metadata.
473 static std::map<std::string, ZippedInfo> zipped_;
476 bool Formats::isZippedFile(support::FileName const & filename) const {
477 string const & fname = filename.absFileName();
478 time_t timestamp = filename.lastModified();
479 map<string, ZippedInfo>::iterator it = zipped_.find(fname);
480 if (it != zipped_.end() && it->second.timestamp == timestamp)
481 return it->second.zipped;
482 string const & format = getFormatFromFile(filename);
483 bool zipped = (format == "gzip" || format == "zip");
484 zipped_.insert(make_pair(fname, ZippedInfo(zipped, timestamp)));
489 bool Formats::isZippedFileFormat(string const & format)
491 return contains("gzip zip compress", format) && !format.empty();
495 bool Formats::isPostScriptFileFormat(string const & format)
497 return format == "ps" || format == "eps";
500 static string fixCommand(string const & cmd, string const & ext,
501 os::auto_open_mode mode)
503 // configure.py says we do not want a viewer/editor
507 // Does the OS manage this format?
508 if (os::canAutoOpenFile(ext, mode))
511 // if configure.py found nothing, clear the command
512 if (token(cmd, ' ', 0) == "auto")
515 // use the command found by configure.py
520 void Formats::setAutoOpen()
522 FormatList::iterator fit = formatlist.begin();
523 FormatList::iterator const fend = formatlist.end();
524 for ( ; fit != fend ; ++fit) {
525 fit->setViewer(fixCommand(fit->viewer(), fit->extension(), os::VIEW));
526 fit->setEditor(fixCommand(fit->editor(), fit->extension(), os::EDIT));
531 int Formats::getNumber(string const & name) const
533 FormatList::const_iterator cit =
534 find_if(formatlist.begin(), formatlist.end(),
535 FormatNamesEqual(name));
536 if (cit != formatlist.end())
537 return distance(formatlist.begin(), cit);
543 void Formats::add(string const & name)
545 if (!getFormat(name))
546 add(name, name, name, string(), string(), string(),
547 string(), Format::document);
551 void Formats::add(string const & name, string const & extensions,
552 string const & prettyname, string const & shortcut,
553 string const & viewer, string const & editor,
554 string const & mime, int flags)
556 FormatList::iterator it =
557 find_if(formatlist.begin(), formatlist.end(),
558 FormatNamesEqual(name));
559 if (it == formatlist.end())
560 formatlist.push_back(Format(name, extensions, prettyname,
561 shortcut, viewer, editor, mime, flags));
563 *it = Format(name, extensions, prettyname, shortcut, viewer,
564 editor, mime, flags);
568 void Formats::erase(string const & name)
570 FormatList::iterator it =
571 find_if(formatlist.begin(), formatlist.end(),
572 FormatNamesEqual(name));
573 if (it != formatlist.end())
574 formatlist.erase(it);
580 std::sort(formatlist.begin(), formatlist.end());
584 void Formats::setViewer(string const & name, string const & command)
587 FormatList::iterator it =
588 find_if(formatlist.begin(), formatlist.end(),
589 FormatNamesEqual(name));
590 if (it != formatlist.end())
591 it->setViewer(command);
595 void Formats::setEditor(string const & name, string const & command)
598 FormatList::iterator it =
599 find_if(formatlist.begin(), formatlist.end(),
600 FormatNamesEqual(name));
601 if (it != formatlist.end())
602 it->setEditor(command);
606 bool Formats::view(Buffer const & buffer, FileName const & filename,
607 string const & format_name) const
609 if (filename.empty() || !filename.exists()) {
610 Alert::error(_("Cannot view file"),
611 bformat(_("File does not exist: %1$s"),
612 from_utf8(filename.absFileName())));
616 Format const * format = getFormat(format_name);
617 if (format && format->viewer().empty() &&
618 format->isChildFormat())
619 format = getFormat(format->parentFormat());
620 if (!format || format->viewer().empty()) {
621 // FIXME: I believe this is the wrong place to show alerts, it should be done
622 // by the caller (this should be "utility" code)
623 Alert::error(_("Cannot view file"),
624 bformat(_("No information for viewing %1$s"),
625 prettyName(format_name)));
629 if (format->viewer() == "auto") {
630 if (os::autoOpenFile(filename.absFileName(), os::VIEW, buffer.filePath()))
633 Alert::error(_("Cannot view file"),
634 bformat(_("Auto-view file %1$s failed"),
635 from_utf8(filename.absFileName())));
640 string command = libScriptSearch(format->viewer());
642 if (format_name == "dvi" &&
643 !lyxrc.view_dvi_paper_option.empty()) {
644 string paper_size = buffer.params().paperSizeName(BufferParams::XDVI);
645 if (!paper_size.empty()) {
646 command += ' ' + lyxrc.view_dvi_paper_option;
647 command += ' ' + paper_size;
648 if (buffer.params().orientation == ORIENTATION_LANDSCAPE &&
649 buffer.params().papersize != PAPER_CUSTOM)
654 if (!contains(command, token_from_format))
655 command += ' ' + token_from_format;
657 command = subst(command, token_from_format, quoteName(onlyFileName(filename.toFilesystemEncoding())));
658 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
659 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
660 LYXERR(Debug::FILES, "Executing command: " << command);
661 // FIXME UNICODE utf8 can be wrong for files
662 buffer.message(_("Executing command: ") + from_utf8(command));
664 PathChanger p(filename.onlyPath());
666 one.startscript(Systemcall::DontWait, command, buffer.filePath());
668 // we can't report any sort of error, since we aren't waiting
673 bool Formats::edit(Buffer const & buffer, FileName const & filename,
674 string const & format_name) const
676 if (filename.empty() || !filename.exists()) {
677 Alert::error(_("Cannot edit file"),
678 bformat(_("File does not exist: %1$s"),
679 from_utf8(filename.absFileName())));
683 // LinkBack files look like PDF, but have the .linkback extension
684 string const ext = getExtension(filename.absFileName());
685 if (format_name == "pdf6" && ext == "linkback") {
686 #ifdef USE_MACOSX_PACKAGING
687 return editLinkBackFile(filename.absFileName().c_str());
689 Alert::error(_("Cannot edit file"),
690 _("LinkBack files can only be edited on Apple Mac OSX."));
692 #endif // USE_MACOSX_PACKAGING
695 Format const * format = getFormat(format_name);
696 if (format && format->editor().empty() &&
697 format->isChildFormat())
698 format = getFormat(format->parentFormat());
699 if (!format || format->editor().empty()) {
700 // FIXME: I believe this is the wrong place to show alerts, it should
701 // be done by the caller (this should be "utility" code)
702 Alert::error(_("Cannot edit file"),
703 bformat(_("No information for editing %1$s"),
704 prettyName(format_name)));
709 if (format->editor() == "auto") {
710 if (os::autoOpenFile(filename.absFileName(), os::EDIT, buffer.filePath()))
713 Alert::error(_("Cannot edit file"),
714 bformat(_("Auto-edit file %1$s failed"),
715 from_utf8(filename.absFileName())));
720 string command = format->editor();
722 if (!contains(command, token_from_format))
723 command += ' ' + token_from_format;
725 command = subst(command, token_from_format, quoteName(filename.toFilesystemEncoding()));
726 command = subst(command, token_path_format, quoteName(onlyPath(filename.toFilesystemEncoding())));
727 command = subst(command, token_socket_format, quoteName(theServerSocket().address()));
728 LYXERR(Debug::FILES, "Executing command: " << command);
729 // FIXME UNICODE utf8 can be wrong for files
730 buffer.message(_("Executing command: ") + from_utf8(command));
733 one.startscript(Systemcall::DontWait, command, buffer.filePath());
735 // we can't report any sort of error, since we aren't waiting
740 docstring const Formats::prettyName(string const & name) const
742 Format const * format = getFormat(name);
744 return from_utf8(format->prettyname());
746 return from_utf8(name);
750 string const Formats::extension(string const & name) const
752 Format const * format = getFormat(name);
754 return format->extension();
760 string const Formats::extensions(string const & name) const
762 Format const * format = getFormat(name);
764 return format->extensions();
772 typedef Translator<OutputParams::FLAVOR, string> FlavorTranslator;
775 FlavorTranslator initFlavorTranslator()
777 FlavorTranslator f(OutputParams::LATEX, "latex");
778 f.addPair(OutputParams::DVILUATEX, "dviluatex");
779 f.addPair(OutputParams::LUATEX, "luatex");
780 f.addPair(OutputParams::PDFLATEX, "pdflatex");
781 f.addPair(OutputParams::XETEX, "xetex");
782 f.addPair(OutputParams::XML, "docbook-xml");
783 f.addPair(OutputParams::HTML, "xhtml");
784 f.addPair(OutputParams::TEXT, "text");
789 FlavorTranslator const & flavorTranslator()
791 static FlavorTranslator translator = initFlavorTranslator();
798 std::string flavor2format(OutputParams::FLAVOR flavor)
800 return flavorTranslator().find(flavor);
804 /* Not currently needed, but I'll leave the code in case it is.
805 OutputParams::FLAVOR format2flavor(std::string fmt)
807 return flavorTranslator().find(fmt);
812 Formats system_formats;