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/insetgraphicsParams.h"
57 #include "insets/renderers.h"
60 #include "BufferView.h"
61 #include "converter.h"
64 #include "funcrequest.h"
66 #include "LaTeXFeatures.h"
67 #include "latexrunparams.h"
71 #include "paragraph_funcs.h"
74 #include "frontends/Alert.h"
75 #include "frontends/Dialogs.h"
77 #include "support/LAssert.h"
78 #include "support/filetools.h"
79 #include "support/lyxalgo.h" // lyx::count
80 #include "support/lyxlib.h" // float_equal
81 #include "support/tostr.h"
82 #include "support/systemcall.h"
84 #include <boost/bind.hpp>
85 #include <boost/tuple/tuple.hpp>
87 #include <algorithm> // For the std::max
91 namespace support = lyx::support;
92 using namespace lyx::support;
101 ///////////////////////////////////////////////////////////////////////////
102 int const VersionNumber = 1;
103 ///////////////////////////////////////////////////////////////////////////
105 // This function is a utility function
106 // ... that should be with ChangeExtension ...
108 string const RemoveExtension(string const & filename)
110 return ChangeExtension(filename, string());
114 string const uniqueID()
116 static unsigned int seed = 1000;
117 return "graph" + tostr(++seed);
121 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
123 // Are we using latex or pdflatex).
124 if (runparams.flavor == LatexRunParams::PDFLATEX) {
125 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
126 if (contains(suffix, "ps") || suffix == "pdf")
128 if (suffix == "jpg") // pdflatex can use jpeg
130 return "png"; // and also png
132 // If it's postscript, we always do eps.
133 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
134 if (suffix != "ps") // any other than ps
135 return "eps"; // is changed to eps
136 return suffix; // let ps untouched
142 InsetGraphics::InsetGraphics()
143 : graphic_label(uniqueID()),
144 graphic_(new GraphicRenderer)
146 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
150 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
152 boost::signals::trackable(),
153 graphic_label(uniqueID()),
154 graphic_(new GraphicRenderer(*ig.graphic_))
156 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
157 setParams(ig.params());
161 auto_ptr<InsetBase> InsetGraphics::clone() const
163 return auto_ptr<InsetBase>(new InsetGraphics(*this));
167 InsetGraphics::~InsetGraphics()
169 InsetGraphicsMailer(*this).hideDialog();
173 void InsetGraphics::statusChanged()
175 BufferView * bv = graphic_->view();
177 bv->updateInset(this);
181 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
183 switch (cmd.action) {
184 case LFUN_INSET_MODIFY: {
185 Buffer const & buffer = *cmd.view()->buffer();
186 InsetGraphicsParams p;
187 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
188 if (!p.filename.empty()) {
190 cmd.view()->updateInset(this);
195 case LFUN_INSET_DIALOG_UPDATE:
196 InsetGraphicsMailer(*this).updateDialog(cmd.view());
199 case LFUN_INSET_EDIT:
200 case LFUN_MOUSE_RELEASE:
201 InsetGraphicsMailer(*this).showDialog(cmd.view());
205 return InsetOld::localDispatch(cmd);
210 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
212 graphic_->metrics(mi, dim);
217 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
219 graphic_->draw(pi, x, y);
223 InsetOld::EDITABLE InsetGraphics::editable() const
229 void InsetGraphics::write(Buffer const & buf, ostream & os) const
232 params().Write(os, buf.filePath());
236 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
238 string const token = lex.getString();
240 if (token == "Graphics")
241 readInsetGraphics(lex, buf.filePath());
243 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
245 graphic_->update(params().as_grfxParams());
249 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
251 bool finished = false;
253 while (lex.isOK() && !finished) {
256 string const token = lex.getString();
257 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
262 } else if (token == "\\end_inset") {
264 } else if (token == "FormatVersion") {
266 int version = lex.getInteger();
267 if (version > VersionNumber)
269 << "This document was created with a newer Graphics widget"
270 ", You should use a newer version of LyX to read this"
273 // TODO: Possibly open up a dialog?
276 if (!params_.Read(lex, token, bufpath))
277 lyxerr << "Unknown token, " << token << ", skipping."
284 string const InsetGraphics::createLatexOptions() const
286 // Calculate the options part of the command, we must do it to a string
287 // stream since we might have a trailing comma that we would like to remove
288 // before writing it to the output stream.
289 ostringstream options;
290 if (!params().bb.empty())
291 options << " bb=" << rtrim(params().bb) << ",\n";
293 options << " draft,\n";
295 options << " clip,\n";
296 if (!float_equal(params().scale, 0.0, 0.05)) {
297 if (!float_equal(params().scale, 100.0, 0.05))
298 options << " scale=" << params().scale / 100.0
301 if (!params().width.zero())
302 options << " width=" << params().width.asLatexString() << ",\n";
303 if (!params().height.zero())
304 options << " height=" << params().height.asLatexString() << ",\n";
305 if (params().keepAspectRatio)
306 options << " keepaspectratio,\n";
309 // Make sure rotation angle is not very close to zero;
310 // a float can be effectively zero but not exactly zero.
311 if (!float_equal(params().rotateAngle, 0, 0.001)) {
312 options << " angle=" << params().rotateAngle << ",\n";
313 if (!params().rotateOrigin.empty()) {
314 options << " origin=" << params().rotateOrigin[0];
315 if (contains(params().rotateOrigin,"Top"))
317 else if (contains(params().rotateOrigin,"Bottom"))
319 else if (contains(params().rotateOrigin,"Baseline"))
325 if (!params().special.empty())
326 options << params().special << ",\n";
328 string opts = STRCONV(options.str());
330 return opts.substr(0, opts.size() - 2);
344 std::pair<CopyStatus, string> const
345 copyToDirIfNeeded(string const & file_in, string const & dir)
347 using support::rtrim;
349 support::Assert(AbsolutePath(file_in));
351 string const only_path = support::OnlyPath(file_in);
352 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
353 return std::make_pair(IDENTICAL_PATHS, file_in);
356 if (support::zippedFile(file_in)) {
357 string const ext = GetExtension(file_in);
358 string const unzipped = support::unzippedFileName(file_in);
359 mangled = FileName(unzipped).mangledFilename();
360 mangled += "." + ext;
362 mangled = FileName(file_in).mangledFilename();
364 string const file_out = support::MakeAbsPath(mangled, dir);
366 unsigned long const checksum_in = support::sum(file_in);
367 unsigned long const checksum_out = support::sum(file_out);
369 if (checksum_in == checksum_out)
371 return std::make_pair(IDENTICAL_CONTENTS, file_out);
373 bool const success = support::copy(file_in, file_out);
375 lyxerr[Debug::GRAPHICS]
376 << support::bformat(_("Could not copy the file\n%1$s\n"
377 "into the temporary directory."),
382 CopyStatus status = success ? SUCCESS : FAILURE;
383 return std::make_pair(status, file_out);
387 string const stripExtensionIfPossible(string const & file, string const & to)
389 // No conversion is needed. LaTeX can handle the graphic file as is.
390 // This is true even if the orig_file is compressed.
391 if (formats.getFormat(to)->extension() == GetExtension(file))
392 return RemoveExtension(file);
399 string const InsetGraphics::prepareFile(Buffer const & buf,
400 LatexRunParams const & runparams) const
402 string orig_file = params().filename.absFilename();
403 string const rel_file = params().filename.relFilename(buf.filePath());
405 // LaTeX can cope if the graphics file doesn't exist, so just return the
407 if (!IsFileReadable(orig_file)) {
408 lyxerr[Debug::GRAPHICS]
409 << "InsetGraphics::prepareFile\n"
410 << "No file '" << orig_file << "' can be found!" << endl;
414 // If the file is compressed and we have specified that it
415 // should not be uncompressed, then just return its name and
416 // let LaTeX do the rest!
417 bool const zipped = params().filename.isZipped();
419 if (zipped && params().noUnzip) {
420 lyxerr[Debug::GRAPHICS]
421 << "\tpass zipped file to LaTeX but with full path.\n";
422 // LaTeX needs an absolute path, otherwise the
423 // coresponding *.eps.bb file isn't found
427 // temp_file will contain the file for LaTeX to act on if, for example,
428 // we move it to a temp dir or uncompress it.
429 string temp_file = orig_file;
433 boost::tie(status, temp_file) =
434 copyToDirIfNeeded(orig_file, buf.tmppath);
436 if (status == FAILURE)
439 orig_file = unzippedFileName(temp_file);
440 if (!IsFileReadable(orig_file)) {
441 unzipFile(temp_file);
442 lyxerr[Debug::GRAPHICS]
443 << "\tunzipped to " << orig_file << endl;
447 string const from = getExtFromContents(orig_file);
448 string const to = findTargetFormat(from, runparams);
449 lyxerr[Debug::GRAPHICS]
450 << "\t we have: from " << from << " to " << to << '\n';
452 if (from == to && !lyxrc.use_tempdir)
453 return stripExtensionIfPossible(orig_file, to);
455 // We're going to be running the exported buffer through the LaTeX
456 // compiler, so must ensure that LaTeX can cope with the graphics
459 lyxerr[Debug::GRAPHICS]
460 << "\tthe orig file is: " << orig_file << endl;
462 bool conversion_needed = true;
463 if (lyxrc.use_tempdir) {
465 boost::tie(status, temp_file) =
466 copyToDirIfNeeded(orig_file, buf.tmppath);
468 if (status == FAILURE)
470 else if (status == IDENTICAL_CONTENTS)
471 conversion_needed = false;
475 return stripExtensionIfPossible(temp_file, to);
477 string const to_file_base = RemoveExtension(temp_file);
478 string const to_file = ChangeExtension(to_file_base, to);
480 // Do we need to perform the conversion?
481 // Yes if to_file does not exist or if temp_file is newer than to_file
482 if (!conversion_needed ||
483 support::compare_timestamps(temp_file, to_file) < 0) {
484 lyxerr[Debug::GRAPHICS]
485 << bformat(_("No conversion of %1$s is needed after all"),
491 lyxerr[Debug::GRAPHICS]
492 << "\tThe original file is " << orig_file << "\n"
493 << "\tA copy has been made and convert is to be called with:\n"
494 << "\tfile to convert = " << temp_file << '\n'
495 << "\tto_file_base = " << to_file_base << '\n'
496 << "\t from " << from << " to " << to << '\n';
498 // if no special converter defined, than we take the default one
499 // from ImageMagic: convert from:inname.from to:outname.to
500 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
501 string const command =
502 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
503 ' ' + from + ':' + temp_file + ' ' +
504 to + ':' + to_file_base + '.' + to;
505 lyxerr[Debug::GRAPHICS]
506 << "No converter defined! I use convertDefault.sh:\n\t"
509 one.startscript(Systemcall::Wait, command);
510 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
511 string str = bformat(_("No information for converting %1$s "
512 "format files to %2$s.\n"
513 "Try defining a convertor in the preferences."), from, to);
514 Alert::error(_("Could not convert image"), str);
522 int InsetGraphics::latex(Buffer const & buf, ostream & os,
523 LatexRunParams const & runparams) const
525 // If there is no file specified or not existing,
526 // just output a message about it in the latex output.
527 lyxerr[Debug::GRAPHICS]
528 << "insetgraphics::latex: Filename = "
529 << params().filename.absFilename() << endl;
531 string const relative_file =
532 params().filename.relFilename(buf.filePath());
534 // A missing (e)ps-extension is no problem for LaTeX, so
535 // we have to test three different cases
536 #warning uh, but can our cache handle it ? no.
537 string const file_ = params().filename.absFilename();
538 bool const file_exists =
540 (IsFileReadable(file_) || // original
541 IsFileReadable(file_ + ".eps") || // original.eps
542 IsFileReadable(file_ + ".ps")); // original.ps
543 string const message = file_exists ?
544 string() : string("bb = 0 0 200 100, draft, type=eps");
545 // if !message.empty() than there was no existing file
546 // "filename(.(e)ps)" found. In this case LaTeX
547 // draws only a rectangle with the above bb and the
548 // not found filename in it.
549 lyxerr[Debug::GRAPHICS]
550 << "\tMessage = \"" << message << '\"' << endl;
552 // These variables collect all the latex code that should be before and
553 // after the actual includegraphics command.
556 // Do we want subcaptions?
557 if (params().subcaption) {
558 before += "\\subfigure[" + params().subcaptionText + "]{";
561 // We never use the starred form, we use the "clip" option instead.
562 before += "\\includegraphics";
564 // Write the options if there are any.
565 string const opts = createLatexOptions();
566 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
568 if (!opts.empty() && !message.empty())
569 before += ("[%\n" + opts + ',' + message + ']');
570 else if (!opts.empty() || !message.empty())
571 before += ("[%\n" + opts + message + ']');
573 lyxerr[Debug::GRAPHICS]
574 << "\tBefore = " << before
575 << "\n\tafter = " << after << endl;
578 // "nice" means that the buffer is exported to LaTeX format but not
579 // run through the LaTeX compiler.
580 if (runparams.nice) {
581 os << before <<'{' << relative_file << '}' << after;
585 // Make the filename relative to the lyx file
586 // and remove the extension so the LaTeX will use whatever is
587 // appropriate (when there are several versions in different formats)
588 string const latex_str = message.empty() ?
589 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
590 (before + '{' + relative_file + " not found!}" + after);
593 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
594 << latex_str << endl;
595 // Return how many newlines we issued.
596 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
600 int InsetGraphics::ascii(Buffer const &, ostream & os, int) const
602 // No graphics in ascii output. Possible to use gifscii to convert
603 // images to ascii approximation.
604 // 1. Convert file to ascii using gifscii
605 // 2. Read ascii output file and add it to the output stream.
606 // at least we send the filename
607 os << '<' << bformat(_("Graphics file: %1$s"),
608 params().filename.absFilename()) << ">\n";
613 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os) const
615 string const file_name = buf.niceFile ?
616 params().filename.relFilename(buf.filePath()):
617 params().filename.absFilename();
619 os << "<eps file=\"" << file_name << "\">\n";
620 os << "<img src=\"" << file_name << "\">";
625 // For explanation on inserting graphics into DocBook checkout:
626 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
627 // See also the docbook guide at http://www.docbook.org/
628 int InsetGraphics::docbook(Buffer const &, ostream & os,
629 bool /*mixcont*/) const
631 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
632 // need to switch to MediaObject. However, for now this is sufficient and
634 os << "<graphic fileref=\"&" << graphic_label << ";\">";
639 void InsetGraphics::validate(LaTeXFeatures & features) const
641 // If we have no image, we should not require anything.
642 if (params().filename.empty())
645 features.includeFile(graphic_label,
646 RemoveExtension(params().filename.absFilename()));
648 features.require("graphicx");
650 if (params().subcaption)
651 features.require("subfigure");
655 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
657 // If nothing is changed, just return and say so.
658 if (params() == p && !p.filename.empty())
661 // Copy the new parameters.
664 // Update the display using the new parameters.
665 graphic_->update(params().as_grfxParams());
667 // We have changed data, report it.
672 InsetGraphicsParams const & InsetGraphics::params() const
678 string const InsetGraphicsMailer::name_("graphics");
680 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
685 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
687 return params2string(inset_.params(), buffer);
691 void InsetGraphicsMailer::string2params(string const & in,
692 Buffer const & buffer,
693 InsetGraphicsParams & params)
695 params = InsetGraphicsParams();
700 istringstream data(STRCONV(in));
706 string const token = lex.getString();
713 inset.readInsetGraphics(lex, buffer.filePath());
714 params = inset.params();
720 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
721 Buffer const & buffer)
724 data << name_ << ' ';
725 params.Write(data, buffer.filePath());
726 data << "\\end_inset\n";
727 return STRCONV(data.str());