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 * Current version is 1 (inset file format version), when changing it
33 * it should be changed in the Write() function when writing in one place
34 * and when reading one should change the version check and the error message.
35 * The filename is kept in the lyx file in a relative way, so as to allow
36 * moving the document file and its images with no problem.
40 * Postscript output means EPS figures.
42 * PDF output is best done with PDF figures if it's a direct conversion
43 * or PNG figures otherwise.
55 #include "insets/insetgraphics.h"
56 #include "insets/renderers.h"
59 #include "BufferView.h"
60 #include "converter.h"
63 #include "funcrequest.h"
65 #include "LaTeXFeatures.h"
66 #include "latexrunparams.h"
70 #include "frontends/Alert.h"
72 #include "support/filetools.h"
73 #include "support/lyxalgo.h" // lyx::count
74 #include "support/lyxlib.h" // float_equal
75 #include "support/os.h"
76 #include "support/systemcall.h"
77 #include "support/tostr.h"
79 #include <boost/bind.hpp>
80 #include <boost/tuple/tuple.hpp>
82 #include "support/std_sstream.h"
84 namespace support = lyx::support;
85 using namespace lyx::support;
89 using std::istringstream;
91 using std::ostringstream;
96 ///////////////////////////////////////////////////////////////////////////
97 int const VersionNumber = 1;
98 ///////////////////////////////////////////////////////////////////////////
100 // This function is a utility function
101 // ... that should be with ChangeExtension ...
103 string const RemoveExtension(string const & filename)
105 return ChangeExtension(filename, string());
109 string const uniqueID()
111 static unsigned int seed = 1000;
112 return "graph" + tostr(++seed);
116 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
118 // Are we using latex or pdflatex).
119 if (runparams.flavor == LatexRunParams::PDFLATEX) {
120 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
121 if (contains(suffix, "ps") || suffix == "pdf")
123 if (suffix == "jpg") // pdflatex can use jpeg
125 return "png"; // and also png
127 // If it's postscript, we always do eps.
128 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
129 if (suffix != "ps") // any other than ps
130 return "eps"; // is changed to eps
131 return suffix; // let ps untouched
137 InsetGraphics::InsetGraphics()
138 : graphic_label(uniqueID()),
139 graphic_(new GraphicRenderer)
141 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
145 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
147 boost::signals::trackable(),
148 graphic_label(uniqueID()),
149 graphic_(new GraphicRenderer(*ig.graphic_))
151 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
152 setParams(ig.params());
156 auto_ptr<InsetBase> InsetGraphics::clone() const
158 return auto_ptr<InsetBase>(new InsetGraphics(*this));
162 InsetGraphics::~InsetGraphics()
164 InsetGraphicsMailer(*this).hideDialog();
168 void InsetGraphics::statusChanged()
170 BufferView * bv = graphic_->view();
172 bv->updateInset(this);
176 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
178 switch (cmd.action) {
179 case LFUN_INSET_MODIFY: {
180 Buffer const & buffer = *cmd.view()->buffer();
181 InsetGraphicsParams p;
182 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
183 if (!p.filename.empty()) {
185 cmd.view()->updateInset(this);
190 case LFUN_INSET_DIALOG_UPDATE:
191 InsetGraphicsMailer(*this).updateDialog(cmd.view());
194 case LFUN_INSET_EDIT:
195 case LFUN_MOUSE_RELEASE:
196 InsetGraphicsMailer(*this).showDialog(cmd.view());
200 return InsetOld::localDispatch(cmd);
205 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
207 graphic_->metrics(mi, dim);
212 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
214 graphic_->draw(pi, x, y);
218 InsetOld::EDITABLE InsetGraphics::editable() const
224 void InsetGraphics::write(Buffer const & buf, ostream & os) const
227 params().Write(os, buf.filePath());
231 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
233 string const token = lex.getString();
235 if (token == "Graphics")
236 readInsetGraphics(lex, buf.filePath());
238 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
240 graphic_->update(params().as_grfxParams());
244 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
246 bool finished = false;
248 while (lex.isOK() && !finished) {
251 string const token = lex.getString();
252 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
257 } else if (token == "\\end_inset") {
259 } else if (token == "FormatVersion") {
261 int version = lex.getInteger();
262 if (version > VersionNumber)
264 << "This document was created with a newer Graphics widget"
265 ", You should use a newer version of LyX to read this"
268 // TODO: Possibly open up a dialog?
271 if (!params_.Read(lex, token, bufpath))
272 lyxerr << "Unknown token, " << token << ", skipping."
279 string const InsetGraphics::createLatexOptions() const
281 // Calculate the options part of the command, we must do it to a string
282 // stream since we might have a trailing comma that we would like to remove
283 // before writing it to the output stream.
284 ostringstream options;
285 if (!params().bb.empty())
286 options << " bb=" << rtrim(params().bb) << ",\n";
288 options << " draft,\n";
290 options << " clip,\n";
291 if (!float_equal(params().scale, 0.0, 0.05)) {
292 if (!float_equal(params().scale, 100.0, 0.05))
293 options << " scale=" << params().scale / 100.0
296 if (!params().width.zero())
297 options << " width=" << params().width.asLatexString() << ",\n";
298 if (!params().height.zero())
299 options << " height=" << params().height.asLatexString() << ",\n";
300 if (params().keepAspectRatio)
301 options << " keepaspectratio,\n";
304 // Make sure rotation angle is not very close to zero;
305 // a float can be effectively zero but not exactly zero.
306 if (!float_equal(params().rotateAngle, 0, 0.001)) {
307 options << " angle=" << params().rotateAngle << ",\n";
308 if (!params().rotateOrigin.empty()) {
309 options << " origin=" << params().rotateOrigin[0];
310 if (contains(params().rotateOrigin,"Top"))
312 else if (contains(params().rotateOrigin,"Bottom"))
314 else if (contains(params().rotateOrigin,"Baseline"))
320 if (!params().special.empty())
321 options << params().special << ",\n";
323 string opts = STRCONV(options.str());
325 return opts.substr(0, opts.size() - 2);
339 std::pair<CopyStatus, string> const
340 copyToDirIfNeeded(string const & file_in, string const & dir)
342 using support::rtrim;
344 BOOST_ASSERT(AbsolutePath(file_in));
346 string const only_path = support::OnlyPath(file_in);
347 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
348 return std::make_pair(IDENTICAL_PATHS, file_in);
351 if (support::zippedFile(file_in)) {
352 string const ext = GetExtension(file_in);
353 string const unzipped = support::unzippedFileName(file_in);
354 mangled = FileName(unzipped).mangledFilename();
355 mangled += "." + ext;
357 mangled = FileName(file_in).mangledFilename();
359 string const file_out = support::MakeAbsPath(mangled, dir);
361 unsigned long const checksum_in = support::sum(file_in);
362 unsigned long const checksum_out = support::sum(file_out);
364 if (checksum_in == checksum_out)
366 return std::make_pair(IDENTICAL_CONTENTS, file_out);
368 bool const success = support::copy(file_in, file_out);
370 lyxerr[Debug::GRAPHICS]
371 << support::bformat(_("Could not copy the file\n%1$s\n"
372 "into the temporary directory."),
377 CopyStatus status = success ? SUCCESS : FAILURE;
378 return std::make_pair(status, file_out);
382 string const stripExtensionIfPossible(string const & file, string const & to)
384 // No conversion is needed. LaTeX can handle the graphic file as is.
385 // This is true even if the orig_file is compressed.
386 if (formats.getFormat(to)->extension() == GetExtension(file))
387 return RemoveExtension(file);
394 string const InsetGraphics::prepareFile(Buffer const & buf,
395 LatexRunParams const & runparams) const
397 string orig_file = params().filename.absFilename();
398 string const rel_file = params().filename.relFilename(buf.filePath());
400 // LaTeX can cope if the graphics file doesn't exist, so just return the
402 if (!IsFileReadable(orig_file)) {
403 lyxerr[Debug::GRAPHICS]
404 << "InsetGraphics::prepareFile\n"
405 << "No file '" << orig_file << "' can be found!" << endl;
409 // If the file is compressed and we have specified that it
410 // should not be uncompressed, then just return its name and
411 // let LaTeX do the rest!
412 bool const zipped = params().filename.isZipped();
414 if (zipped && params().noUnzip) {
415 lyxerr[Debug::GRAPHICS]
416 << "\tpass zipped file to LaTeX but with full path.\n";
417 // LaTeX needs an absolute path, otherwise the
418 // coresponding *.eps.bb file isn't found
422 // temp_file will contain the file for LaTeX to act on if, for example,
423 // we move it to a temp dir or uncompress it.
424 string temp_file = orig_file;
428 boost::tie(status, temp_file) =
429 copyToDirIfNeeded(orig_file, buf.temppath());
431 if (status == FAILURE)
434 orig_file = unzippedFileName(temp_file);
435 if (!IsFileReadable(orig_file)) {
436 unzipFile(temp_file);
437 lyxerr[Debug::GRAPHICS]
438 << "\tunzipped to " << orig_file << endl;
442 string const from = getExtFromContents(orig_file);
443 string const to = findTargetFormat(from, runparams);
444 lyxerr[Debug::GRAPHICS]
445 << "\t we have: from " << from << " to " << to << '\n';
447 if (from == to && !lyxrc.use_tempdir)
448 return stripExtensionIfPossible(orig_file, to);
450 // We're going to be running the exported buffer through the LaTeX
451 // compiler, so must ensure that LaTeX can cope with the graphics
454 lyxerr[Debug::GRAPHICS]
455 << "\tthe orig file is: " << orig_file << endl;
457 bool conversion_needed = true;
458 if (lyxrc.use_tempdir) {
460 boost::tie(status, temp_file) =
461 copyToDirIfNeeded(orig_file, buf.temppath());
463 if (status == FAILURE)
465 else if (status == IDENTICAL_CONTENTS)
466 conversion_needed = false;
470 return stripExtensionIfPossible(temp_file, to);
472 string const to_file_base = RemoveExtension(temp_file);
473 string const to_file = ChangeExtension(to_file_base, to);
475 // Do we need to perform the conversion?
476 // Yes if to_file does not exist or if temp_file is newer than to_file
477 if (!conversion_needed ||
478 support::compare_timestamps(temp_file, to_file) < 0) {
479 lyxerr[Debug::GRAPHICS]
480 << bformat(_("No conversion of %1$s is needed after all"),
486 lyxerr[Debug::GRAPHICS]
487 << "\tThe original file is " << orig_file << "\n"
488 << "\tA copy has been made and convert is to be called with:\n"
489 << "\tfile to convert = " << temp_file << '\n'
490 << "\tto_file_base = " << to_file_base << '\n'
491 << "\t from " << from << " to " << to << '\n';
493 // if no special converter defined, than we take the default one
494 // from ImageMagic: convert from:inname.from to:outname.to
495 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
496 string const command =
497 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
498 ' ' + from + ':' + temp_file + ' ' +
499 to + ':' + to_file_base + '.' + to;
500 lyxerr[Debug::GRAPHICS]
501 << "No converter defined! I use convertDefault.sh:\n\t"
504 one.startscript(Systemcall::Wait, command);
505 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
506 string str = bformat(_("No information for converting %1$s "
507 "format files to %2$s.\n"
508 "Try defining a convertor in the preferences."), from, to);
509 Alert::error(_("Could not convert image"), str);
517 int InsetGraphics::latex(Buffer const & buf, ostream & os,
518 LatexRunParams const & runparams) const
520 // If there is no file specified or not existing,
521 // just output a message about it in the latex output.
522 lyxerr[Debug::GRAPHICS]
523 << "insetgraphics::latex: Filename = "
524 << params().filename.absFilename() << endl;
526 string const relative_file =
527 params().filename.relFilename(buf.filePath());
529 // A missing (e)ps-extension is no problem for LaTeX, so
530 // we have to test three different cases
531 #warning uh, but can our cache handle it ? no.
532 string const file_ = params().filename.absFilename();
533 bool const file_exists =
535 (IsFileReadable(file_) || // original
536 IsFileReadable(file_ + ".eps") || // original.eps
537 IsFileReadable(file_ + ".ps")); // original.ps
538 string const message = file_exists ?
539 string() : string("bb = 0 0 200 100, draft, type=eps");
540 // if !message.empty() than there was no existing file
541 // "filename(.(e)ps)" found. In this case LaTeX
542 // draws only a rectangle with the above bb and the
543 // not found filename in it.
544 lyxerr[Debug::GRAPHICS]
545 << "\tMessage = \"" << message << '\"' << endl;
547 // These variables collect all the latex code that should be before and
548 // after the actual includegraphics command.
551 // Do we want subcaptions?
552 if (params().subcaption) {
553 before += "\\subfigure[" + params().subcaptionText + "]{";
556 // We never use the starred form, we use the "clip" option instead.
557 before += "\\includegraphics";
559 // Write the options if there are any.
560 string const opts = createLatexOptions();
561 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
563 if (!opts.empty() && !message.empty())
564 before += ("[%\n" + opts + ',' + message + ']');
565 else if (!opts.empty() || !message.empty())
566 before += ("[%\n" + opts + message + ']');
568 lyxerr[Debug::GRAPHICS]
569 << "\tBefore = " << before
570 << "\n\tafter = " << after << endl;
573 // "nice" means that the buffer is exported to LaTeX format but not
574 // run through the LaTeX compiler.
575 if (runparams.nice) {
576 os << before <<'{' << relative_file << '}' << after;
580 // Make the filename relative to the lyx file
581 // and remove the extension so the LaTeX will use whatever is
582 // appropriate (when there are several versions in different formats)
583 string const latex_str = message.empty() ?
584 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
585 (before + '{' + relative_file + " not found!}" + after);
588 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
589 << latex_str << endl;
590 // Return how many newlines we issued.
591 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
595 int InsetGraphics::ascii(Buffer const &, ostream & os, int) const
597 // No graphics in ascii output. Possible to use gifscii to convert
598 // images to ascii approximation.
599 // 1. Convert file to ascii using gifscii
600 // 2. Read ascii output file and add it to the output stream.
601 // at least we send the filename
602 os << '<' << bformat(_("Graphics file: %1$s"),
603 params().filename.absFilename()) << ">\n";
608 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os) const
610 string const file_name = buf.niceFile() ?
611 params().filename.relFilename(buf.filePath()):
612 params().filename.absFilename();
614 os << "<eps file=\"" << file_name << "\">\n";
615 os << "<img src=\"" << file_name << "\">";
620 // For explanation on inserting graphics into DocBook checkout:
621 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
622 // See also the docbook guide at http://www.docbook.org/
623 int InsetGraphics::docbook(Buffer const &, ostream & os,
624 bool /*mixcont*/) const
626 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
627 // need to switch to MediaObject. However, for now this is sufficient and
629 os << "<graphic fileref=\"&" << graphic_label << ";\">";
634 void InsetGraphics::validate(LaTeXFeatures & features) const
636 // If we have no image, we should not require anything.
637 if (params().filename.empty())
640 features.includeFile(graphic_label,
641 RemoveExtension(params().filename.absFilename()));
643 features.require("graphicx");
645 if (params().subcaption)
646 features.require("subfigure");
650 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
652 // If nothing is changed, just return and say so.
653 if (params() == p && !p.filename.empty())
656 // Copy the new parameters.
659 // Update the display using the new parameters.
660 graphic_->update(params().as_grfxParams());
662 // We have changed data, report it.
667 InsetGraphicsParams const & InsetGraphics::params() const
673 string const InsetGraphicsMailer::name_("graphics");
675 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
680 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
682 return params2string(inset_.params(), buffer);
686 void InsetGraphicsMailer::string2params(string const & in,
687 Buffer const & buffer,
688 InsetGraphicsParams & params)
690 params = InsetGraphicsParams();
695 istringstream data(STRCONV(in));
701 string const token = lex.getString();
708 inset.readInsetGraphics(lex, buffer.filePath());
709 params = inset.params();
715 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
716 Buffer const & buffer)
719 data << name_ << ' ';
720 params.Write(data, buffer.filePath());
721 data << "\\end_inset\n";
722 return STRCONV(data.str());