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);
350 std::pair<CopyStatus, string> const
351 copyFileIfNeeded(string const & file_in, string const & file_out)
353 BOOST_ASSERT(AbsolutePath(file_in));
354 BOOST_ASSERT(AbsolutePath(file_out));
356 unsigned long const checksum_in = support::sum(file_in);
357 unsigned long const checksum_out = support::sum(file_out);
359 if (checksum_in == checksum_out)
361 return std::make_pair(IDENTICAL_CONTENTS, file_out);
363 bool const success = support::copy(file_in, file_out);
365 lyxerr[Debug::GRAPHICS]
366 << support::bformat(_("Could not copy the file\n%1$s\n"
367 "into the temporary directory."),
372 CopyStatus status = success ? SUCCESS : FAILURE;
373 return std::make_pair(status, file_out);
377 std::pair<CopyStatus, string> const
378 copyToDirIfNeeded(string const & file_in, string const & dir, bool zipped)
380 using support::rtrim;
382 BOOST_ASSERT(AbsolutePath(file_in));
384 string const only_path = support::OnlyPath(file_in);
385 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
386 return std::make_pair(IDENTICAL_PATHS, file_in);
388 string mangled = FileName(file_in).mangledFilename();
390 // We need to change _eps.gz to .eps.gz. The mangled name is
391 // still unique because of the counter in mangledFilename().
392 // We can't just call mangledFilename() with the zip
393 // extension removed, because base.eps and base.eps.gz may
394 // have different content but would get the same mangled
395 // name in this case.
396 string const base = RemoveExtension(unzippedFileName(file_in));
397 string::size_type const ext_len = file_in.length() - base.length();
398 mangled[mangled.length() - ext_len] = '.';
400 string const file_out = support::MakeAbsPath(mangled, dir);
402 return copyFileIfNeeded(file_in, file_out);
406 string const stripExtension(string const & file)
408 // Remove the extension so the LaTeX will use whatever
409 // is appropriate (when there are several versions in
410 // different formats)
411 // This works only if the filename contains no dots besides
412 // the just removed one. We can fool here by replacing all
413 // dots with a macro whose definition is just a dot ;-)
414 return subst(RemoveExtension(file), ".", "\\lyxdot ");
418 string const stripExtensionIfPossible(string const & file, string const & to)
420 // No conversion is needed. LaTeX can handle the graphic file as is.
421 // This is true even if the orig_file is compressed.
422 string const to_format = formats.getFormat(to)->extension();
423 string const file_format = GetExtension(file);
424 // for latex .ps == .eps
425 if (to_format == file_format ||
426 (to_format == "eps" && file_format == "ps") ||
427 (to_format == "ps" && file_format == "eps"))
428 return stripExtension(file);
435 string const InsetGraphics::prepareFile(Buffer const & buf,
436 OutputParams const & runparams) const
438 // We assume that the file exists (the caller checks this)
439 string const orig_file = params().filename.absFilename();
440 string const rel_file = params().filename.relFilename(buf.filePath());
442 // If the file is compressed and we have specified that it
443 // should not be uncompressed, then just return its name and
444 // let LaTeX do the rest!
445 bool const zipped = params().filename.isZipped();
447 // temp_file will contain the file for LaTeX to act on if, for example,
448 // we move it to a temp dir or uncompress it.
449 string temp_file = orig_file;
451 // The master buffer. This is useful when there are multiple levels
453 Buffer const * m_buffer = buf.getMasterBuffer();
455 // We place all temporary files in the master buffer's temp dir.
456 // This is possible because we use mangled file names.
457 // This is necessary for DVI export.
458 string const temp_path = m_buffer->temppath();
461 boost::tie(status, temp_file) =
462 copyToDirIfNeeded(orig_file, temp_path, zipped);
464 if (status == FAILURE)
467 // a relative filename should be relative to the master
469 // "nice" means that the buffer is exported to LaTeX format but not
470 // run through the LaTeX compiler.
471 string const output_file = os::external_path(runparams.nice ?
472 params().filename.outputFilename(m_buffer->filePath()) :
473 OnlyFilename(temp_file));
474 string const source_file = runparams.nice ? orig_file : temp_file;
477 if (params().noUnzip) {
478 // We don't know whether latex can actually handle
479 // this file, but we can't check, because that would
480 // mean to unzip the file and thereby making the
481 // noUnzip parameter meaningless.
482 lyxerr[Debug::GRAPHICS]
483 << "\tpass zipped file to LaTeX.\n";
485 string const bb_orig_file = ChangeExtension(orig_file, "bb");
486 if (runparams.nice) {
487 runparams.exportdata->addExternalFile("latex",
489 ChangeExtension(output_file, "bb"));
491 // LaTeX needs the bounding box file in the
493 string bb_file = ChangeExtension(temp_file, "bb");
494 boost::tie(status, bb_file) =
495 copyFileIfNeeded(bb_orig_file, bb_file);
496 if (status == FAILURE)
498 runparams.exportdata->addExternalFile("latex",
501 runparams.exportdata->addExternalFile("latex",
502 source_file, output_file);
503 runparams.exportdata->addExternalFile("dvi",
504 source_file, output_file);
505 // We can't strip the extension, because we don't know
506 // the unzipped file format
510 string const unzipped_temp_file = unzippedFileName(temp_file);
511 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
512 // temp_file has been unzipped already and
513 // orig_file has not changed in the meantime.
514 temp_file = unzipped_temp_file;
515 lyxerr[Debug::GRAPHICS]
516 << "\twas already unzipped to " << temp_file
519 // unzipped_temp_file does not exist or is too old
520 temp_file = unzipFile(temp_file);
521 lyxerr[Debug::GRAPHICS]
522 << "\tunzipped to " << temp_file << endl;
526 string const from = getExtFromContents(temp_file);
527 string const to = findTargetFormat(from, runparams);
528 lyxerr[Debug::GRAPHICS]
529 << "\t we have: from " << from << " to " << to << '\n';
531 // We're going to be running the exported buffer through the LaTeX
532 // compiler, so must ensure that LaTeX can cope with the graphics
535 lyxerr[Debug::GRAPHICS]
536 << "\tthe orig file is: " << orig_file << endl;
539 // The extension of temp_file might be != to!
540 runparams.exportdata->addExternalFile("latex", source_file,
542 runparams.exportdata->addExternalFile("dvi", source_file,
544 return stripExtensionIfPossible(output_file, to);
547 string const to_file = ChangeExtension(temp_file, to);
548 string const output_to_file = ChangeExtension(output_file, to);
550 // Do we need to perform the conversion?
551 // Yes if to_file does not exist or if temp_file is newer than to_file
552 if (compare_timestamps(temp_file, to_file) < 0) {
553 lyxerr[Debug::GRAPHICS]
554 << bformat(_("No conversion of %1$s is needed after all"),
557 runparams.exportdata->addExternalFile("latex", to_file,
559 runparams.exportdata->addExternalFile("dvi", to_file,
561 return stripExtension(output_file);
564 lyxerr[Debug::GRAPHICS]
565 << "\tThe original file is " << orig_file << "\n"
566 << "\tA copy has been made and convert is to be called with:\n"
567 << "\tfile to convert = " << temp_file << '\n'
568 << "\t from " << from << " to " << to << '\n';
570 // if no special converter defined, then we take the default one
571 // from ImageMagic: convert from:inname.from to:outname.to
572 if (!converters.convert(&buf, temp_file, temp_file, from, to)) {
573 string const command =
574 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
575 ' ' + from + ':' + temp_file + ' ' +
577 lyxerr[Debug::GRAPHICS]
578 << "No converter defined! I use convertDefault.sh:\n\t"
581 one.startscript(Systemcall::Wait, command);
582 if (IsFileReadable(to_file)) {
583 runparams.exportdata->addExternalFile("latex",
584 to_file, output_to_file);
585 runparams.exportdata->addExternalFile("dvi",
586 to_file, output_to_file);
588 string str = bformat(_("No information for converting %1$s "
589 "format files to %2$s.\n"
590 "Try defining a convertor in the preferences."), from, to);
591 Alert::error(_("Could not convert image"), str);
595 return stripExtension(output_file);
599 int InsetGraphics::latex(Buffer const & buf, ostream & os,
600 OutputParams const & runparams) const
602 // If there is no file specified or not existing,
603 // just output a message about it in the latex output.
604 lyxerr[Debug::GRAPHICS]
605 << "insetgraphics::latex: Filename = "
606 << params().filename.absFilename() << endl;
608 string const relative_file =
609 params().filename.relFilename(buf.filePath());
611 string const file_ = params().filename.absFilename();
612 bool const file_exists = !file_.empty() && IsFileReadable(file_);
613 string const message = file_exists ?
614 string() : string("bb = 0 0 200 100, draft, type=eps");
615 // if !message.empty() then there was no existing file
616 // "filename" found. In this case LaTeX
617 // draws only a rectangle with the above bb and the
618 // not found filename in it.
619 lyxerr[Debug::GRAPHICS]
620 << "\tMessage = \"" << message << '\"' << endl;
622 // These variables collect all the latex code that should be before and
623 // after the actual includegraphics command.
626 // Do we want subcaptions?
627 if (params().subcaption) {
628 before += "\\subfigure[" + params().subcaptionText + "]{";
631 // We never use the starred form, we use the "clip" option instead.
632 before += "\\includegraphics";
634 // Write the options if there are any.
635 string const opts = createLatexOptions();
636 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
638 if (!opts.empty() && !message.empty())
639 before += ("[%\n" + opts + ',' + message + ']');
640 else if (!opts.empty() || !message.empty())
641 before += ("[%\n" + opts + message + ']');
643 lyxerr[Debug::GRAPHICS]
644 << "\tBefore = " << before
645 << "\n\tafter = " << after << endl;
648 string latex_str = before + '{';
650 // Convert the file if necessary.
651 // Remove the extension so the LaTeX will use whatever
652 // is appropriate (when there are several versions in
653 // different formats)
654 latex_str += prepareFile(buf, runparams);
656 latex_str += relative_file + " not found!";
658 latex_str += '}' + after;
661 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
662 << latex_str << endl;
663 // Return how many newlines we issued.
664 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
668 int InsetGraphics::plaintext(Buffer const &, ostream & os,
669 OutputParams const &) const
671 // No graphics in ascii output. Possible to use gifscii to convert
672 // images to ascii approximation.
673 // 1. Convert file to ascii using gifscii
674 // 2. Read ascii output file and add it to the output stream.
675 // at least we send the filename
676 os << '<' << bformat(_("Graphics file: %1$s"),
677 params().filename.absFilename()) << ">\n";
682 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os,
683 OutputParams const & runparams) const
685 string const file_name = runparams.nice ?
686 params().filename.relFilename(buf.filePath()):
687 params().filename.absFilename();
689 runparams.exportdata->addExternalFile("linuxdoc",
690 params().filename.absFilename());
691 os << "<eps file=\"" << file_name << "\">\n";
692 os << "<img src=\"" << file_name << "\">";
697 // For explanation on inserting graphics into DocBook checkout:
698 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
699 // See also the docbook guide at http://www.docbook.org/
700 int InsetGraphics::docbook(Buffer const &, ostream & os,
701 OutputParams const & runparams) const
703 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
704 // need to switch to MediaObject. However, for now this is sufficient and
706 runparams.exportdata->addExternalFile("docbook",
707 params().filename.absFilename());
708 runparams.exportdata->addExternalFile("docbook-xml",
709 params().filename.absFilename());
710 os << "<graphic fileref=\"&" << graphic_label << ";\">";
715 void InsetGraphics::validate(LaTeXFeatures & features) const
717 // If we have no image, we should not require anything.
718 if (params().filename.empty())
721 features.includeFile(graphic_label,
722 RemoveExtension(params().filename.absFilename()));
724 features.require("graphicx");
726 if (features.nice()) {
727 Buffer const * m_buffer = features.buffer().getMasterBuffer();
729 params().filename.outputFilename(m_buffer->filePath());
730 basename = RemoveExtension(basename);
731 if(params().filename.isZipped())
732 basename = RemoveExtension(basename);
733 if (contains(basename, "."))
734 features.require("lyxdot");
737 if (params().subcaption)
738 features.require("subfigure");
742 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
744 // If nothing is changed, just return and say so.
745 if (params() == p && !p.filename.empty())
748 // Copy the new parameters.
751 // Update the display using the new parameters.
752 graphic_->update(params().as_grfxParams());
754 // We have changed data, report it.
759 InsetGraphicsParams const & InsetGraphics::params() const
765 void InsetGraphics::editGraphics(InsetGraphicsParams const & p, Buffer const & buffer) const
767 string const file_with_path = p.filename.absFilename();
768 formats.edit(buffer, file_with_path, getExtFromContents(file_with_path));
772 string const InsetGraphicsMailer::name_("graphics");
774 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
779 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
781 return params2string(inset_.params(), buffer);
785 void InsetGraphicsMailer::string2params(string const & in,
786 Buffer const & buffer,
787 InsetGraphicsParams & params)
789 params = InsetGraphicsParams();
793 istringstream data(in);
799 if (!lex || name != name_)
800 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
803 inset.readInsetGraphics(lex, buffer.filePath());
804 params = inset.params();
809 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
810 Buffer const & buffer)
813 data << name_ << ' ';
814 params.Write(data, buffer.filePath());
815 data << "\\end_inset\n";