2 * \file insetgraphics.C
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
9 * Full author contact details are available in file CREDITS.
15 * What advanced features the users want to do?
16 Implement them in a non latex dependent way, but a logical way.
17 LyX should translate it to latex or any other fitting format.
18 * Add a way to roll the image file into the file format.
19 * When loading, if the image is not found in the expected place, try
20 to find it in the clipart, or in the same directory with the image.
21 * The image choosing dialog could show thumbnails of the image formats
22 it knows of, thus selection based on the image instead of based on
24 * Add support for the 'picins' package.
25 * Add support for the 'picinpar' package.
26 * Improve support for 'subfigure' - Allow to set the various options
32 * The filename is kept in the lyx file in a relative way, so as to allow
33 * moving the document file and its images with no problem.
37 * Postscript output means EPS figures.
39 * PDF output is best done with PDF figures if it's a direct conversion
40 * or PNG figures otherwise.
52 #include "insets/insetgraphics.h"
53 #include "insets/render_graphic.h"
56 #include "BufferView.h"
57 #include "converter.h"
60 #include "dispatchresult.h"
63 #include "funcrequest.h"
65 #include "LaTeXFeatures.h"
68 #include "metricsinfo.h"
69 #include "outputparams.h"
71 #include "frontends/Alert.h"
72 #include "frontends/LyXView.h"
74 #include "support/filetools.h"
75 #include "support/lyxalgo.h" // lyx::count
76 #include "support/lyxlib.h" // float_equal
77 #include "support/os.h"
78 #include "support/systemcall.h"
79 #include "support/tostr.h"
81 #include <boost/bind.hpp>
82 #include <boost/tuple/tuple.hpp>
86 namespace support = lyx::support;
88 using lyx::support::AbsolutePath;
89 using lyx::support::bformat;
90 using lyx::support::ChangeExtension;
91 using lyx::support::compare_timestamps;
92 using lyx::support::contains;
93 using lyx::support::FileName;
94 using lyx::support::float_equal;
95 using lyx::support::GetExtension;
96 using lyx::support::getExtFromContents;
97 using lyx::support::IsFileReadable;
98 using lyx::support::LibFileSearch;
99 using lyx::support::OnlyFilename;
100 using lyx::support::rtrim;
101 using lyx::support::subst;
102 using lyx::support::Systemcall;
103 using lyx::support::unzipFile;
104 using lyx::support::unzippedFileName;
106 namespace os = lyx::support::os;
111 using std::istringstream;
113 using std::ostringstream;
118 // This function is a utility function
119 // ... that should be with ChangeExtension ...
121 string const RemoveExtension(string const & filename)
123 return ChangeExtension(filename, string());
127 string const uniqueID()
129 static unsigned int seed = 1000;
130 return "graph" + tostr(++seed);
134 string findTargetFormat(string const & suffix, OutputParams const & runparams)
136 // Are we using latex or pdflatex).
137 if (runparams.flavor == OutputParams::PDFLATEX) {
138 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
139 if (contains(suffix, "ps") || suffix == "pdf")
141 if (suffix == "jpg") // pdflatex can use jpeg
143 return "png"; // and also png
145 // If it's postscript, we always do eps.
146 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
147 if (suffix != "ps") // any other than ps
148 return "eps"; // is changed to eps
149 return suffix; // let ps untouched
155 InsetGraphics::InsetGraphics()
156 : graphic_label(uniqueID()),
157 graphic_(new RenderGraphic(this))
161 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
163 boost::signals::trackable(),
164 graphic_label(uniqueID()),
165 graphic_(new RenderGraphic(*ig.graphic_, this))
167 setParams(ig.params());
171 auto_ptr<InsetBase> InsetGraphics::clone() const
173 return auto_ptr<InsetBase>(new InsetGraphics(*this));
177 InsetGraphics::~InsetGraphics()
179 InsetGraphicsMailer(*this).hideDialog();
183 void InsetGraphics::priv_dispatch(LCursor & cur, FuncRequest & cmd)
185 switch (cmd.action) {
186 case LFUN_GRAPHICS_EDIT: {
187 Buffer const & buffer = *cur.bv().buffer();
188 InsetGraphicsParams p;
189 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
190 editGraphics(p, buffer);
194 case LFUN_INSET_MODIFY: {
195 Buffer const & buffer = cur.buffer();
196 InsetGraphicsParams p;
197 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
198 if (!p.filename.empty()) {
205 case LFUN_INSET_DIALOG_UPDATE:
206 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
209 case LFUN_MOUSE_RELEASE:
210 InsetGraphicsMailer(*this).showDialog(&cur.bv());
214 InsetOld::priv_dispatch(cur, cmd);
220 void InsetGraphics::edit(LCursor & cur, bool)
222 InsetGraphicsMailer(*this).showDialog(&cur.bv());
226 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
228 graphic_->metrics(mi, dim);
233 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
235 setPosCache(pi, x, y);
236 graphic_->draw(pi, x, y);
240 InsetOld::EDITABLE InsetGraphics::editable() const
246 void InsetGraphics::write(Buffer const & buf, ostream & os) const
249 params().Write(os, buf.filePath());
253 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
255 string const token = lex.getString();
257 if (token == "Graphics")
258 readInsetGraphics(lex, buf.filePath());
260 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
262 graphic_->update(params().as_grfxParams());
266 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
268 bool finished = false;
270 while (lex.isOK() && !finished) {
273 string const token = lex.getString();
274 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
279 } else if (token == "\\end_inset") {
282 if (!params_.Read(lex, token, bufpath))
283 lyxerr << "Unknown token, " << token << ", skipping."
290 string const InsetGraphics::createLatexOptions() const
292 // Calculate the options part of the command, we must do it to a string
293 // stream since we might have a trailing comma that we would like to remove
294 // before writing it to the output stream.
295 ostringstream options;
296 if (!params().bb.empty())
297 options << " bb=" << rtrim(params().bb) << ",\n";
299 options << " draft,\n";
301 options << " clip,\n";
302 if (!float_equal(params().scale, 0.0, 0.05)) {
303 if (!float_equal(params().scale, 100.0, 0.05))
304 options << " scale=" << params().scale / 100.0
307 if (!params().width.zero())
308 options << " width=" << params().width.asLatexString() << ",\n";
309 if (!params().height.zero())
310 options << " height=" << params().height.asLatexString() << ",\n";
311 if (params().keepAspectRatio)
312 options << " keepaspectratio,\n";
315 // Make sure rotation angle is not very close to zero;
316 // a float can be effectively zero but not exactly zero.
317 if (!float_equal(params().rotateAngle, 0, 0.001)) {
318 options << " angle=" << params().rotateAngle << ",\n";
319 if (!params().rotateOrigin.empty()) {
320 options << " origin=" << params().rotateOrigin[0];
321 if (contains(params().rotateOrigin,"Top"))
323 else if (contains(params().rotateOrigin,"Bottom"))
325 else if (contains(params().rotateOrigin,"Baseline"))
331 if (!params().special.empty())
332 options << params().special << ",\n";
334 string opts = options.str();
336 return opts.substr(0, opts.size() - 2);
340 string const InsetGraphics::createDocBookAttributes() const
342 // Calculate the options part of the command, we must do it to a string
343 // stream since we copied the code from createLatexParams()
345 // FIXME: av: need to translate spec -> Docbook XSL spec (http://www.sagehill.net/docbookxsl/ImageSizing.html)
346 // Right now it only works with my version of db2latex :-)
348 ostringstream options;
349 if (!float_equal(params().scale, 0.0, 0.05)) {
350 if (!float_equal(params().scale, 100.0, 0.05))
351 options << " scale=\"" << params().scale / 100.0
354 if (!params().width.zero())
355 options << " width=\"" << params().width.asLatexString() << "\" ";
356 if (!params().height.zero())
357 options << " depth=\"" << params().height.asLatexString() << "\" ";
360 if (!params().special.empty())
361 options << params().special << " ";
363 string opts = options.str();
364 // trailing blanks are ok ...
379 std::pair<CopyStatus, string> const
380 copyFileIfNeeded(string const & file_in, string const & file_out)
382 BOOST_ASSERT(AbsolutePath(file_in));
383 BOOST_ASSERT(AbsolutePath(file_out));
385 unsigned long const checksum_in = support::sum(file_in);
386 unsigned long const checksum_out = support::sum(file_out);
388 if (checksum_in == checksum_out)
390 return std::make_pair(IDENTICAL_CONTENTS, file_out);
392 bool const success = support::copy(file_in, file_out);
394 lyxerr[Debug::GRAPHICS]
395 << support::bformat(_("Could not copy the file\n%1$s\n"
396 "into the temporary directory."),
401 CopyStatus status = success ? SUCCESS : FAILURE;
402 return std::make_pair(status, file_out);
406 std::pair<CopyStatus, string> const
407 copyToDirIfNeeded(string const & file_in, string const & dir, bool zipped)
409 using support::rtrim;
411 BOOST_ASSERT(AbsolutePath(file_in));
413 string const only_path = support::OnlyPath(file_in);
414 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
415 return std::make_pair(IDENTICAL_PATHS, file_in);
417 string mangled = FileName(file_in).mangledFilename();
419 // We need to change _eps.gz to .eps.gz. The mangled name is
420 // still unique because of the counter in mangledFilename().
421 // We can't just call mangledFilename() with the zip
422 // extension removed, because base.eps and base.eps.gz may
423 // have different content but would get the same mangled
424 // name in this case.
425 string const base = RemoveExtension(unzippedFileName(file_in));
426 string::size_type const ext_len = file_in.length() - base.length();
427 mangled[mangled.length() - ext_len] = '.';
429 string const file_out = support::MakeAbsPath(mangled, dir);
431 return copyFileIfNeeded(file_in, file_out);
435 string const stripExtension(string const & file)
437 // Remove the extension so the LaTeX will use whatever
438 // is appropriate (when there are several versions in
439 // different formats)
440 // This works only if the filename contains no dots besides
441 // the just removed one. We can fool here by replacing all
442 // dots with a macro whose definition is just a dot ;-)
443 return subst(RemoveExtension(file), ".", "\\lyxdot ");
447 string const stripExtensionIfPossible(string const & file, string const & to)
449 // No conversion is needed. LaTeX can handle the graphic file as is.
450 // This is true even if the orig_file is compressed.
451 string const to_format = formats.getFormat(to)->extension();
452 string const file_format = GetExtension(file);
453 // for latex .ps == .eps
454 if (to_format == file_format ||
455 (to_format == "eps" && file_format == "ps") ||
456 (to_format == "ps" && file_format == "eps"))
457 return stripExtension(file);
464 string const InsetGraphics::prepareFile(Buffer const & buf,
465 OutputParams const & runparams) const
467 // We assume that the file exists (the caller checks this)
468 string const orig_file = params().filename.absFilename();
469 string const rel_file = params().filename.relFilename(buf.filePath());
471 // If the file is compressed and we have specified that it
472 // should not be uncompressed, then just return its name and
473 // let LaTeX do the rest!
474 bool const zipped = params().filename.isZipped();
476 // temp_file will contain the file for LaTeX to act on if, for example,
477 // we move it to a temp dir or uncompress it.
478 string temp_file = orig_file;
480 // The master buffer. This is useful when there are multiple levels
482 Buffer const * m_buffer = buf.getMasterBuffer();
484 // We place all temporary files in the master buffer's temp dir.
485 // This is possible because we use mangled file names.
486 // This is necessary for DVI export.
487 string const temp_path = m_buffer->temppath();
490 boost::tie(status, temp_file) =
491 copyToDirIfNeeded(orig_file, temp_path, zipped);
493 if (status == FAILURE)
496 // a relative filename should be relative to the master
498 // "nice" means that the buffer is exported to LaTeX format but not
499 // run through the LaTeX compiler.
500 string const output_file = os::external_path(runparams.nice ?
501 params().filename.outputFilename(m_buffer->filePath()) :
502 OnlyFilename(temp_file));
503 string const source_file = runparams.nice ? orig_file : temp_file;
506 if (params().noUnzip) {
507 // We don't know whether latex can actually handle
508 // this file, but we can't check, because that would
509 // mean to unzip the file and thereby making the
510 // noUnzip parameter meaningless.
511 lyxerr[Debug::GRAPHICS]
512 << "\tpass zipped file to LaTeX.\n";
514 string const bb_orig_file = ChangeExtension(orig_file, "bb");
515 if (runparams.nice) {
516 runparams.exportdata->addExternalFile("latex",
518 ChangeExtension(output_file, "bb"));
520 // LaTeX needs the bounding box file in the
522 string bb_file = ChangeExtension(temp_file, "bb");
523 boost::tie(status, bb_file) =
524 copyFileIfNeeded(bb_orig_file, bb_file);
525 if (status == FAILURE)
527 runparams.exportdata->addExternalFile("latex",
530 runparams.exportdata->addExternalFile("latex",
531 source_file, output_file);
532 runparams.exportdata->addExternalFile("dvi",
533 source_file, output_file);
534 // We can't strip the extension, because we don't know
535 // the unzipped file format
539 string const unzipped_temp_file = unzippedFileName(temp_file);
540 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
541 // temp_file has been unzipped already and
542 // orig_file has not changed in the meantime.
543 temp_file = unzipped_temp_file;
544 lyxerr[Debug::GRAPHICS]
545 << "\twas already unzipped to " << temp_file
548 // unzipped_temp_file does not exist or is too old
549 temp_file = unzipFile(temp_file);
550 lyxerr[Debug::GRAPHICS]
551 << "\tunzipped to " << temp_file << endl;
555 string const from = getExtFromContents(temp_file);
556 string const to = findTargetFormat(from, runparams);
557 lyxerr[Debug::GRAPHICS]
558 << "\t we have: from " << from << " to " << to << '\n';
560 // We're going to be running the exported buffer through the LaTeX
561 // compiler, so must ensure that LaTeX can cope with the graphics
564 lyxerr[Debug::GRAPHICS]
565 << "\tthe orig file is: " << orig_file << endl;
568 // The extension of temp_file might be != to!
569 runparams.exportdata->addExternalFile("latex", source_file,
571 runparams.exportdata->addExternalFile("dvi", source_file,
573 return stripExtensionIfPossible(output_file, to);
576 string const to_file = ChangeExtension(temp_file, to);
577 string const output_to_file = ChangeExtension(output_file, to);
579 // Do we need to perform the conversion?
580 // Yes if to_file does not exist or if temp_file is newer than to_file
581 if (compare_timestamps(temp_file, to_file) < 0) {
582 lyxerr[Debug::GRAPHICS]
583 << bformat(_("No conversion of %1$s is needed after all"),
586 runparams.exportdata->addExternalFile("latex", to_file,
588 runparams.exportdata->addExternalFile("dvi", to_file,
590 return stripExtension(output_file);
593 lyxerr[Debug::GRAPHICS]
594 << "\tThe original file is " << orig_file << "\n"
595 << "\tA copy has been made and convert is to be called with:\n"
596 << "\tfile to convert = " << temp_file << '\n'
597 << "\t from " << from << " to " << to << '\n';
599 // if no special converter defined, then we take the default one
600 // from ImageMagic: convert from:inname.from to:outname.to
601 if (!converters.convert(&buf, temp_file, temp_file, from, to)) {
602 string const command =
603 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
604 ' ' + from + ':' + temp_file + ' ' +
606 lyxerr[Debug::GRAPHICS]
607 << "No converter defined! I use convertDefault.sh:\n\t"
610 one.startscript(Systemcall::Wait, command);
611 if (IsFileReadable(to_file)) {
612 runparams.exportdata->addExternalFile("latex",
613 to_file, output_to_file);
614 runparams.exportdata->addExternalFile("dvi",
615 to_file, output_to_file);
617 string str = bformat(_("No information for converting %1$s "
618 "format files to %2$s.\n"
619 "Try defining a convertor in the preferences."), from, to);
620 Alert::error(_("Could not convert image"), str);
624 return stripExtension(output_file);
628 int InsetGraphics::latex(Buffer const & buf, ostream & os,
629 OutputParams const & runparams) const
631 // If there is no file specified or not existing,
632 // just output a message about it in the latex output.
633 lyxerr[Debug::GRAPHICS]
634 << "insetgraphics::latex: Filename = "
635 << params().filename.absFilename() << endl;
637 string const relative_file =
638 params().filename.relFilename(buf.filePath());
640 string const file_ = params().filename.absFilename();
641 bool const file_exists = !file_.empty() && IsFileReadable(file_);
642 string const message = file_exists ?
643 string() : string("bb = 0 0 200 100, draft, type=eps");
644 // if !message.empty() then there was no existing file
645 // "filename" found. In this case LaTeX
646 // draws only a rectangle with the above bb and the
647 // not found filename in it.
648 lyxerr[Debug::GRAPHICS]
649 << "\tMessage = \"" << message << '\"' << endl;
651 // These variables collect all the latex code that should be before and
652 // after the actual includegraphics command.
655 // Do we want subcaptions?
656 if (params().subcaption) {
657 before += "\\subfigure[" + params().subcaptionText + "]{";
660 // We never use the starred form, we use the "clip" option instead.
661 before += "\\includegraphics";
663 // Write the options if there are any.
664 string const opts = createLatexOptions();
665 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
667 if (!opts.empty() && !message.empty())
668 before += ("[%\n" + opts + ',' + message + ']');
669 else if (!opts.empty() || !message.empty())
670 before += ("[%\n" + opts + message + ']');
672 lyxerr[Debug::GRAPHICS]
673 << "\tBefore = " << before
674 << "\n\tafter = " << after << endl;
677 string latex_str = before + '{';
679 // Convert the file if necessary.
680 // Remove the extension so the LaTeX will use whatever
681 // is appropriate (when there are several versions in
682 // different formats)
683 latex_str += prepareFile(buf, runparams);
685 latex_str += relative_file + " not found!";
687 latex_str += '}' + after;
690 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
691 << latex_str << endl;
692 // Return how many newlines we issued.
693 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
697 int InsetGraphics::plaintext(Buffer const &, ostream & os,
698 OutputParams const &) const
700 // No graphics in ascii output. Possible to use gifscii to convert
701 // images to ascii approximation.
702 // 1. Convert file to ascii using gifscii
703 // 2. Read ascii output file and add it to the output stream.
704 // at least we send the filename
705 os << '<' << bformat(_("Graphics file: %1$s"),
706 params().filename.absFilename()) << ">\n";
711 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os,
712 OutputParams const & runparams) const
714 string const file_name = runparams.nice ?
715 params().filename.relFilename(buf.filePath()):
716 params().filename.absFilename();
718 runparams.exportdata->addExternalFile("linuxdoc",
719 params().filename.absFilename());
720 os << "<eps file=\"" << file_name << "\">\n";
721 os << "<img src=\"" << file_name << "\">";
726 // For explanation on inserting graphics into DocBook checkout:
727 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
728 // See also the docbook guide at http://www.docbook.org/
729 int InsetGraphics::docbook(Buffer const &, ostream & os,
730 OutputParams const & runparams) const
732 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
733 // need to switch to MediaObject. However, for now this is sufficient and
735 if (runparams.flavor == OutputParams::XML) {
736 runparams.exportdata->addExternalFile("docbook-xml",
737 params().filename.absFilename());
738 os << "<inlinegraphic fileref=\"&" << graphic_label << ";\" " + createDocBookAttributes() + "/>";
740 runparams.exportdata->addExternalFile("docbook",
741 params().filename.absFilename());
742 os << "<inlinegraphic fileref=\"&" << graphic_label << ";\" " + createDocBookAttributes() + "/>";
748 void InsetGraphics::validate(LaTeXFeatures & features) const
750 // If we have no image, we should not require anything.
751 if (params().filename.empty())
754 features.includeFile(graphic_label,
755 RemoveExtension(params().filename.absFilename()));
757 features.require("graphicx");
759 if (features.nice()) {
760 Buffer const * m_buffer = features.buffer().getMasterBuffer();
762 params().filename.outputFilename(m_buffer->filePath());
763 basename = RemoveExtension(basename);
764 if(params().filename.isZipped())
765 basename = RemoveExtension(basename);
766 if (contains(basename, "."))
767 features.require("lyxdot");
770 if (params().subcaption)
771 features.require("subfigure");
775 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
777 // If nothing is changed, just return and say so.
778 if (params() == p && !p.filename.empty())
781 // Copy the new parameters.
784 // Update the display using the new parameters.
785 graphic_->update(params().as_grfxParams());
787 // We have changed data, report it.
792 InsetGraphicsParams const & InsetGraphics::params() const
798 void InsetGraphics::editGraphics(InsetGraphicsParams const & p, Buffer const & buffer) const
800 string const file_with_path = p.filename.absFilename();
801 formats.edit(buffer, file_with_path, getExtFromContents(file_with_path));
805 string const InsetGraphicsMailer::name_("graphics");
807 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
812 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
814 return params2string(inset_.params(), buffer);
818 void InsetGraphicsMailer::string2params(string const & in,
819 Buffer const & buffer,
820 InsetGraphicsParams & params)
822 params = InsetGraphicsParams();
826 istringstream data(in);
832 if (!lex || name != name_)
833 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
836 inset.readInsetGraphics(lex, buffer.filePath());
837 params = inset.params();
842 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
843 Buffer const & buffer)
846 data << name_ << ' ';
847 params.Write(data, buffer.filePath());
848 data << "\\end_inset\n";