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 lyx::support::AbsolutePath;
86 using lyx::support::bformat;
87 using lyx::support::ChangeExtension;
88 using lyx::support::contains;
89 using lyx::support::FileName;
90 using lyx::support::float_equal;
91 using lyx::support::GetExtension;
92 using lyx::support::getExtFromContents;
93 using lyx::support::IsFileReadable;
94 using lyx::support::LibFileSearch;
95 using lyx::support::os;
96 using lyx::support::rtrim;
97 using lyx::support::Systemcall;
98 using lyx::support::unzipFile;
99 using lyx::support::unzippedFileName;
104 using std::istringstream;
106 using std::ostringstream;
111 ///////////////////////////////////////////////////////////////////////////
112 int const VersionNumber = 1;
113 ///////////////////////////////////////////////////////////////////////////
115 // This function is a utility function
116 // ... that should be with ChangeExtension ...
118 string const RemoveExtension(string const & filename)
120 return ChangeExtension(filename, string());
124 string const uniqueID()
126 static unsigned int seed = 1000;
127 return "graph" + tostr(++seed);
131 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
133 // Are we using latex or pdflatex).
134 if (runparams.flavor == LatexRunParams::PDFLATEX) {
135 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
136 if (contains(suffix, "ps") || suffix == "pdf")
138 if (suffix == "jpg") // pdflatex can use jpeg
140 return "png"; // and also png
142 // If it's postscript, we always do eps.
143 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
144 if (suffix != "ps") // any other than ps
145 return "eps"; // is changed to eps
146 return suffix; // let ps untouched
152 InsetGraphics::InsetGraphics()
153 : graphic_label(uniqueID()),
154 graphic_(new GraphicRenderer)
156 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
160 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
162 boost::signals::trackable(),
163 graphic_label(uniqueID()),
164 graphic_(new GraphicRenderer(*ig.graphic_))
166 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, 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::statusChanged()
185 BufferView * bv = graphic_->view();
187 bv->updateInset(this);
191 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
193 switch (cmd.action) {
194 case LFUN_INSET_MODIFY: {
195 Buffer const & buffer = *cmd.view()->buffer();
196 InsetGraphicsParams p;
197 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
198 if (!p.filename.empty()) {
200 cmd.view()->updateInset(this);
205 case LFUN_INSET_DIALOG_UPDATE:
206 InsetGraphicsMailer(*this).updateDialog(cmd.view());
209 case LFUN_INSET_EDIT:
210 case LFUN_MOUSE_RELEASE:
211 InsetGraphicsMailer(*this).showDialog(cmd.view());
215 return InsetOld::localDispatch(cmd);
220 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
222 graphic_->metrics(mi, dim);
227 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
229 graphic_->draw(pi, x, y);
233 InsetOld::EDITABLE InsetGraphics::editable() const
239 void InsetGraphics::write(Buffer const & buf, ostream & os) const
242 params().Write(os, buf.filePath());
246 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
248 string const token = lex.getString();
250 if (token == "Graphics")
251 readInsetGraphics(lex, buf.filePath());
253 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
255 graphic_->update(params().as_grfxParams());
259 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
261 bool finished = false;
263 while (lex.isOK() && !finished) {
266 string const token = lex.getString();
267 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
272 } else if (token == "\\end_inset") {
274 } else if (token == "FormatVersion") {
276 int version = lex.getInteger();
277 if (version > VersionNumber)
279 << "This document was created with a newer Graphics widget"
280 ", You should use a newer version of LyX to read this"
283 // TODO: Possibly open up a dialog?
286 if (!params_.Read(lex, token, bufpath))
287 lyxerr << "Unknown token, " << token << ", skipping."
294 string const InsetGraphics::createLatexOptions() const
296 // Calculate the options part of the command, we must do it to a string
297 // stream since we might have a trailing comma that we would like to remove
298 // before writing it to the output stream.
299 ostringstream options;
300 if (!params().bb.empty())
301 options << " bb=" << rtrim(params().bb) << ",\n";
303 options << " draft,\n";
305 options << " clip,\n";
306 if (!float_equal(params().scale, 0.0, 0.05)) {
307 if (!float_equal(params().scale, 100.0, 0.05))
308 options << " scale=" << params().scale / 100.0
311 if (!params().width.zero())
312 options << " width=" << params().width.asLatexString() << ",\n";
313 if (!params().height.zero())
314 options << " height=" << params().height.asLatexString() << ",\n";
315 if (params().keepAspectRatio)
316 options << " keepaspectratio,\n";
319 // Make sure rotation angle is not very close to zero;
320 // a float can be effectively zero but not exactly zero.
321 if (!float_equal(params().rotateAngle, 0, 0.001)) {
322 options << " angle=" << params().rotateAngle << ",\n";
323 if (!params().rotateOrigin.empty()) {
324 options << " origin=" << params().rotateOrigin[0];
325 if (contains(params().rotateOrigin,"Top"))
327 else if (contains(params().rotateOrigin,"Bottom"))
329 else if (contains(params().rotateOrigin,"Baseline"))
335 if (!params().special.empty())
336 options << params().special << ",\n";
338 string opts = options.str();
340 return opts.substr(0, opts.size() - 2);
354 std::pair<CopyStatus, string> const
355 copyToDirIfNeeded(string const & file_in, string const & dir)
357 using support::rtrim;
359 BOOST_ASSERT(AbsolutePath(file_in));
361 string const only_path = support::OnlyPath(file_in);
362 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
363 return std::make_pair(IDENTICAL_PATHS, file_in);
366 if (support::zippedFile(file_in)) {
367 string const ext = GetExtension(file_in);
368 string const unzipped = support::unzippedFileName(file_in);
369 mangled = FileName(unzipped).mangledFilename();
370 mangled += "." + ext;
372 mangled = FileName(file_in).mangledFilename();
374 string const file_out = support::MakeAbsPath(mangled, dir);
376 unsigned long const checksum_in = support::sum(file_in);
377 unsigned long const checksum_out = support::sum(file_out);
379 if (checksum_in == checksum_out)
381 return std::make_pair(IDENTICAL_CONTENTS, file_out);
383 bool const success = support::copy(file_in, file_out);
385 lyxerr[Debug::GRAPHICS]
386 << support::bformat(_("Could not copy the file\n%1$s\n"
387 "into the temporary directory."),
392 CopyStatus status = success ? SUCCESS : FAILURE;
393 return std::make_pair(status, file_out);
397 string const stripExtensionIfPossible(string const & file, string const & to)
399 // No conversion is needed. LaTeX can handle the graphic file as is.
400 // This is true even if the orig_file is compressed.
401 if (formats.getFormat(to)->extension() == GetExtension(file))
402 return RemoveExtension(file);
409 string const InsetGraphics::prepareFile(Buffer const & buf,
410 LatexRunParams const & runparams) const
412 string orig_file = params().filename.absFilename();
413 string const rel_file = params().filename.relFilename(buf.filePath());
415 // LaTeX can cope if the graphics file doesn't exist, so just return the
417 if (!IsFileReadable(orig_file)) {
418 lyxerr[Debug::GRAPHICS]
419 << "InsetGraphics::prepareFile\n"
420 << "No file '" << orig_file << "' can be found!" << endl;
424 // If the file is compressed and we have specified that it
425 // should not be uncompressed, then just return its name and
426 // let LaTeX do the rest!
427 bool const zipped = params().filename.isZipped();
429 if (zipped && params().noUnzip) {
430 lyxerr[Debug::GRAPHICS]
431 << "\tpass zipped file to LaTeX but with full path.\n";
432 // LaTeX needs an absolute path, otherwise the
433 // coresponding *.eps.bb file isn't found
437 // temp_file will contain the file for LaTeX to act on if, for example,
438 // we move it to a temp dir or uncompress it.
439 string temp_file = orig_file;
443 boost::tie(status, temp_file) =
444 copyToDirIfNeeded(orig_file, buf.temppath());
446 if (status == FAILURE)
449 orig_file = unzippedFileName(temp_file);
450 if (!IsFileReadable(orig_file)) {
451 unzipFile(temp_file);
452 lyxerr[Debug::GRAPHICS]
453 << "\tunzipped to " << orig_file << endl;
457 string const from = getExtFromContents(orig_file);
458 string const to = findTargetFormat(from, runparams);
459 lyxerr[Debug::GRAPHICS]
460 << "\t we have: from " << from << " to " << to << '\n';
462 if (from == to && !lyxrc.use_tempdir)
463 return stripExtensionIfPossible(orig_file, to);
465 // We're going to be running the exported buffer through the LaTeX
466 // compiler, so must ensure that LaTeX can cope with the graphics
469 lyxerr[Debug::GRAPHICS]
470 << "\tthe orig file is: " << orig_file << endl;
472 bool conversion_needed = true;
473 if (lyxrc.use_tempdir) {
475 boost::tie(status, temp_file) =
476 copyToDirIfNeeded(orig_file, buf.temppath());
478 if (status == FAILURE)
480 else if (status == IDENTICAL_CONTENTS)
481 conversion_needed = false;
485 return stripExtensionIfPossible(temp_file, to);
487 string const to_file_base = RemoveExtension(temp_file);
488 string const to_file = ChangeExtension(to_file_base, to);
490 // Do we need to perform the conversion?
491 // Yes if to_file does not exist or if temp_file is newer than to_file
492 if (!conversion_needed ||
493 support::compare_timestamps(temp_file, to_file) < 0) {
494 lyxerr[Debug::GRAPHICS]
495 << bformat(_("No conversion of %1$s is needed after all"),
501 lyxerr[Debug::GRAPHICS]
502 << "\tThe original file is " << orig_file << "\n"
503 << "\tA copy has been made and convert is to be called with:\n"
504 << "\tfile to convert = " << temp_file << '\n'
505 << "\tto_file_base = " << to_file_base << '\n'
506 << "\t from " << from << " to " << to << '\n';
508 // if no special converter defined, than we take the default one
509 // from ImageMagic: convert from:inname.from to:outname.to
510 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
511 string const command =
512 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
513 ' ' + from + ':' + temp_file + ' ' +
514 to + ':' + to_file_base + '.' + to;
515 lyxerr[Debug::GRAPHICS]
516 << "No converter defined! I use convertDefault.sh:\n\t"
519 one.startscript(Systemcall::Wait, command);
520 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
521 string str = bformat(_("No information for converting %1$s "
522 "format files to %2$s.\n"
523 "Try defining a convertor in the preferences."), from, to);
524 Alert::error(_("Could not convert image"), str);
532 int InsetGraphics::latex(Buffer const & buf, ostream & os,
533 LatexRunParams const & runparams) const
535 // If there is no file specified or not existing,
536 // just output a message about it in the latex output.
537 lyxerr[Debug::GRAPHICS]
538 << "insetgraphics::latex: Filename = "
539 << params().filename.absFilename() << endl;
541 string const relative_file =
542 params().filename.relFilename(buf.filePath());
544 // A missing (e)ps-extension is no problem for LaTeX, so
545 // we have to test three different cases
546 #warning uh, but can our cache handle it ? no.
547 string const file_ = params().filename.absFilename();
548 bool const file_exists =
550 (IsFileReadable(file_) || // original
551 IsFileReadable(file_ + ".eps") || // original.eps
552 IsFileReadable(file_ + ".ps")); // original.ps
553 string const message = file_exists ?
554 string() : string("bb = 0 0 200 100, draft, type=eps");
555 // if !message.empty() than there was no existing file
556 // "filename(.(e)ps)" found. In this case LaTeX
557 // draws only a rectangle with the above bb and the
558 // not found filename in it.
559 lyxerr[Debug::GRAPHICS]
560 << "\tMessage = \"" << message << '\"' << endl;
562 // These variables collect all the latex code that should be before and
563 // after the actual includegraphics command.
566 // Do we want subcaptions?
567 if (params().subcaption) {
568 before += "\\subfigure[" + params().subcaptionText + "]{";
571 // We never use the starred form, we use the "clip" option instead.
572 before += "\\includegraphics";
574 // Write the options if there are any.
575 string const opts = createLatexOptions();
576 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
578 if (!opts.empty() && !message.empty())
579 before += ("[%\n" + opts + ',' + message + ']');
580 else if (!opts.empty() || !message.empty())
581 before += ("[%\n" + opts + message + ']');
583 lyxerr[Debug::GRAPHICS]
584 << "\tBefore = " << before
585 << "\n\tafter = " << after << endl;
588 // "nice" means that the buffer is exported to LaTeX format but not
589 // run through the LaTeX compiler.
590 if (runparams.nice) {
591 os << before <<'{' << relative_file << '}' << after;
595 // Make the filename relative to the lyx file
596 // and remove the extension so the LaTeX will use whatever is
597 // appropriate (when there are several versions in different formats)
598 string const latex_str = message.empty() ?
599 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
600 (before + '{' + relative_file + " not found!}" + after);
603 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
604 << latex_str << endl;
605 // Return how many newlines we issued.
606 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
610 int InsetGraphics::ascii(Buffer const &, ostream & os, int) const
612 // No graphics in ascii output. Possible to use gifscii to convert
613 // images to ascii approximation.
614 // 1. Convert file to ascii using gifscii
615 // 2. Read ascii output file and add it to the output stream.
616 // at least we send the filename
617 os << '<' << bformat(_("Graphics file: %1$s"),
618 params().filename.absFilename()) << ">\n";
623 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os) const
625 string const file_name = buf.niceFile() ?
626 params().filename.relFilename(buf.filePath()):
627 params().filename.absFilename();
629 os << "<eps file=\"" << file_name << "\">\n";
630 os << "<img src=\"" << file_name << "\">";
635 // For explanation on inserting graphics into DocBook checkout:
636 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
637 // See also the docbook guide at http://www.docbook.org/
638 int InsetGraphics::docbook(Buffer const &, ostream & os,
639 bool /*mixcont*/) const
641 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
642 // need to switch to MediaObject. However, for now this is sufficient and
644 os << "<graphic fileref=\"&" << graphic_label << ";\">";
649 void InsetGraphics::validate(LaTeXFeatures & features) const
651 // If we have no image, we should not require anything.
652 if (params().filename.empty())
655 features.includeFile(graphic_label,
656 RemoveExtension(params().filename.absFilename()));
658 features.require("graphicx");
660 if (params().subcaption)
661 features.require("subfigure");
665 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
667 // If nothing is changed, just return and say so.
668 if (params() == p && !p.filename.empty())
671 // Copy the new parameters.
674 // Update the display using the new parameters.
675 graphic_->update(params().as_grfxParams());
677 // We have changed data, report it.
682 InsetGraphicsParams const & InsetGraphics::params() const
688 string const InsetGraphicsMailer::name_("graphics");
690 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
695 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
697 return params2string(inset_.params(), buffer);
701 void InsetGraphicsMailer::string2params(string const & in,
702 Buffer const & buffer,
703 InsetGraphicsParams & params)
705 params = InsetGraphicsParams();
710 istringstream data(in);
716 string const token = lex.getString();
723 inset.readInsetGraphics(lex, buffer.filePath());
724 params = inset.params();
730 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
731 Buffer const & buffer)
734 data << name_ << ' ';
735 params.Write(data, buffer.filePath());
736 data << "\\end_inset\n";