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"
62 #include "funcrequest.h"
64 #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"
80 #include "support/std_sstream.h"
82 #include <boost/bind.hpp>
83 #include <boost/tuple/tuple.hpp>
85 namespace support = lyx::support;
86 using lyx::support::AbsolutePath;
87 using lyx::support::bformat;
88 using lyx::support::ChangeExtension;
89 using lyx::support::contains;
90 using lyx::support::FileName;
91 using lyx::support::float_equal;
92 using lyx::support::GetExtension;
93 using lyx::support::getExtFromContents;
94 using lyx::support::IsFileReadable;
95 using lyx::support::LibFileSearch;
96 using lyx::support::rtrim;
97 using lyx::support::Systemcall;
98 using lyx::support::unzipFile;
99 using lyx::support::unzippedFileName;
101 namespace os = lyx::support::os;
106 using std::istringstream;
108 using std::ostringstream;
113 ///////////////////////////////////////////////////////////////////////////
114 int const VersionNumber = 1;
115 ///////////////////////////////////////////////////////////////////////////
117 // This function is a utility function
118 // ... that should be with ChangeExtension ...
120 string const RemoveExtension(string const & filename)
122 return ChangeExtension(filename, string());
126 string const uniqueID()
128 static unsigned int seed = 1000;
129 return "graph" + tostr(++seed);
133 string findTargetFormat(string const & suffix, OutputParams const & runparams)
135 // Are we using latex or pdflatex).
136 if (runparams.flavor == OutputParams::PDFLATEX) {
137 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
138 if (contains(suffix, "ps") || suffix == "pdf")
140 if (suffix == "jpg") // pdflatex can use jpeg
142 return "png"; // and also png
144 // If it's postscript, we always do eps.
145 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
146 if (suffix != "ps") // any other than ps
147 return "eps"; // is changed to eps
148 return suffix; // let ps untouched
154 InsetGraphics::InsetGraphics()
155 : graphic_label(uniqueID()),
156 graphic_(new RenderGraphic)
158 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
162 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
164 boost::signals::trackable(),
165 graphic_label(uniqueID()),
166 graphic_(new RenderGraphic(*ig.graphic_))
168 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
169 setParams(ig.params());
173 auto_ptr<InsetBase> InsetGraphics::clone() const
175 return auto_ptr<InsetBase>(new InsetGraphics(*this));
179 InsetGraphics::~InsetGraphics()
181 InsetGraphicsMailer(*this).hideDialog();
185 void InsetGraphics::statusChanged() const
187 LyX::cref().updateInset(this);
191 void InsetGraphics::priv_dispatch(LCursor & cur, FuncRequest & cmd)
193 switch (cmd.action) {
194 case LFUN_INSET_MODIFY: {
195 Buffer const & buffer = *cur.bv().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 copyToDirIfNeeded(string const & file_in, string const & dir)
353 using support::rtrim;
355 BOOST_ASSERT(AbsolutePath(file_in));
357 string const only_path = support::OnlyPath(file_in);
358 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
359 return std::make_pair(IDENTICAL_PATHS, file_in);
362 if (support::zippedFile(file_in)) {
363 string const ext = GetExtension(file_in);
364 string const unzipped = support::unzippedFileName(file_in);
365 mangled = FileName(unzipped).mangledFilename();
366 mangled += "." + ext;
368 mangled = FileName(file_in).mangledFilename();
370 string const file_out = support::MakeAbsPath(mangled, dir);
372 unsigned long const checksum_in = support::sum(file_in);
373 unsigned long const checksum_out = support::sum(file_out);
375 if (checksum_in == checksum_out)
377 return std::make_pair(IDENTICAL_CONTENTS, file_out);
379 bool const success = support::copy(file_in, file_out);
381 lyxerr[Debug::GRAPHICS]
382 << support::bformat(_("Could not copy the file\n%1$s\n"
383 "into the temporary directory."),
388 CopyStatus status = success ? SUCCESS : FAILURE;
389 return std::make_pair(status, file_out);
393 string const stripExtensionIfPossible(string const & file, string const & to)
395 // No conversion is needed. LaTeX can handle the graphic file as is.
396 // This is true even if the orig_file is compressed.
397 if (formats.getFormat(to)->extension() == GetExtension(file))
398 return RemoveExtension(file);
405 string const InsetGraphics::prepareFile(Buffer const & buf,
406 OutputParams const & runparams) const
408 string orig_file = params().filename.absFilename();
409 string const rel_file = params().filename.relFilename(buf.filePath());
411 // LaTeX can cope if the graphics file doesn't exist, so just return the
413 if (!IsFileReadable(orig_file)) {
414 lyxerr[Debug::GRAPHICS]
415 << "InsetGraphics::prepareFile\n"
416 << "No file '" << orig_file << "' can be found!" << endl;
420 // If the file is compressed and we have specified that it
421 // should not be uncompressed, then just return its name and
422 // let LaTeX do the rest!
423 bool const zipped = params().filename.isZipped();
425 if (zipped && params().noUnzip) {
426 lyxerr[Debug::GRAPHICS]
427 << "\tpass zipped file to LaTeX but with full path.\n";
428 // LaTeX needs an absolute path, otherwise the
429 // coresponding *.eps.bb file isn't found
433 // temp_file will contain the file for LaTeX to act on if, for example,
434 // we move it to a temp dir or uncompress it.
435 string temp_file = orig_file;
439 boost::tie(status, temp_file) =
440 copyToDirIfNeeded(orig_file, buf.temppath());
442 if (status == FAILURE)
445 orig_file = unzippedFileName(temp_file);
446 if (!IsFileReadable(orig_file)) {
447 unzipFile(temp_file);
448 lyxerr[Debug::GRAPHICS]
449 << "\tunzipped to " << orig_file << endl;
453 string const from = getExtFromContents(orig_file);
454 string const to = findTargetFormat(from, runparams);
455 lyxerr[Debug::GRAPHICS]
456 << "\t we have: from " << from << " to " << to << '\n';
458 // We're going to be running the exported buffer through the LaTeX
459 // compiler, so must ensure that LaTeX can cope with the graphics
462 lyxerr[Debug::GRAPHICS]
463 << "\tthe orig file is: " << orig_file << endl;
465 bool conversion_needed = true;
467 boost::tie(status, temp_file) =
468 copyToDirIfNeeded(orig_file, buf.temppath());
470 if (status == FAILURE)
472 else if (status == IDENTICAL_CONTENTS)
473 conversion_needed = false;
476 return stripExtensionIfPossible(temp_file, to);
478 string const to_file_base = RemoveExtension(temp_file);
479 string const to_file = ChangeExtension(to_file_base, to);
481 // Do we need to perform the conversion?
482 // Yes if to_file does not exist or if temp_file is newer than to_file
483 if (!conversion_needed ||
484 support::compare_timestamps(temp_file, to_file) < 0) {
485 lyxerr[Debug::GRAPHICS]
486 << bformat(_("No conversion of %1$s is needed after all"),
492 lyxerr[Debug::GRAPHICS]
493 << "\tThe original file is " << orig_file << "\n"
494 << "\tA copy has been made and convert is to be called with:\n"
495 << "\tfile to convert = " << temp_file << '\n'
496 << "\tto_file_base = " << to_file_base << '\n'
497 << "\t from " << from << " to " << to << '\n';
499 // if no special converter defined, then we take the default one
500 // from ImageMagic: convert from:inname.from to:outname.to
501 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
502 string const command =
503 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
504 ' ' + from + ':' + temp_file + ' ' +
505 to + ':' + to_file_base + '.' + to;
506 lyxerr[Debug::GRAPHICS]
507 << "No converter defined! I use convertDefault.sh:\n\t"
510 one.startscript(Systemcall::Wait, command);
511 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
512 string str = bformat(_("No information for converting %1$s "
513 "format files to %2$s.\n"
514 "Try defining a convertor in the preferences."), from, to);
515 Alert::error(_("Could not convert image"), str);
523 int InsetGraphics::latex(Buffer const & buf, ostream & os,
524 OutputParams const & runparams) const
526 // If there is no file specified or not existing,
527 // just output a message about it in the latex output.
528 lyxerr[Debug::GRAPHICS]
529 << "insetgraphics::latex: Filename = "
530 << params().filename.absFilename() << endl;
532 string const relative_file =
533 params().filename.relFilename(buf.filePath());
535 // A missing (e)ps-extension is no problem for LaTeX, so
536 // we have to test three different cases
537 #warning uh, but can our cache handle it ? no.
538 string const file_ = params().filename.absFilename();
539 bool const file_exists =
541 (IsFileReadable(file_) || // original
542 IsFileReadable(file_ + ".eps") || // original.eps
543 IsFileReadable(file_ + ".ps")); // original.ps
544 string const message = file_exists ?
545 string() : string("bb = 0 0 200 100, draft, type=eps");
546 // if !message.empty() than there was no existing file
547 // "filename(.(e)ps)" found. In this case LaTeX
548 // draws only a rectangle with the above bb and the
549 // not found filename in it.
550 lyxerr[Debug::GRAPHICS]
551 << "\tMessage = \"" << message << '\"' << endl;
553 // These variables collect all the latex code that should be before and
554 // after the actual includegraphics command.
557 // Do we want subcaptions?
558 if (params().subcaption) {
559 before += "\\subfigure[" + params().subcaptionText + "]{";
562 // We never use the starred form, we use the "clip" option instead.
563 before += "\\includegraphics";
565 // Write the options if there are any.
566 string const opts = createLatexOptions();
567 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
569 if (!opts.empty() && !message.empty())
570 before += ("[%\n" + opts + ',' + message + ']');
571 else if (!opts.empty() || !message.empty())
572 before += ("[%\n" + opts + message + ']');
574 lyxerr[Debug::GRAPHICS]
575 << "\tBefore = " << before
576 << "\n\tafter = " << after << endl;
579 // "nice" means that the buffer is exported to LaTeX format but not
580 // run through the LaTeX compiler.
581 if (runparams.nice) {
582 os << before <<'{' << relative_file << '}' << after;
586 // Make the filename relative to the lyx file
587 // and remove the extension so the LaTeX will use whatever is
588 // appropriate (when there are several versions in different formats)
589 string const latex_str = message.empty() ?
590 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
591 (before + '{' + relative_file + " not found!}" + after);
594 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
595 << latex_str << endl;
596 // Return how many newlines we issued.
597 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
601 int InsetGraphics::plaintext(Buffer const &, ostream & os,
602 OutputParams const &) const
604 // No graphics in ascii output. Possible to use gifscii to convert
605 // images to ascii approximation.
606 // 1. Convert file to ascii using gifscii
607 // 2. Read ascii output file and add it to the output stream.
608 // at least we send the filename
609 os << '<' << bformat(_("Graphics file: %1$s"),
610 params().filename.absFilename()) << ">\n";
615 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os,
616 OutputParams const & runparams) const
618 string const file_name = runparams.nice ?
619 params().filename.relFilename(buf.filePath()):
620 params().filename.absFilename();
622 os << "<eps file=\"" << file_name << "\">\n";
623 os << "<img src=\"" << file_name << "\">";
628 // For explanation on inserting graphics into DocBook checkout:
629 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
630 // See also the docbook guide at http://www.docbook.org/
631 int InsetGraphics::docbook(Buffer const &, ostream & os,
632 OutputParams const &) const
634 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
635 // need to switch to MediaObject. However, for now this is sufficient and
637 os << "<graphic fileref=\"&" << graphic_label << ";\">";
642 void InsetGraphics::validate(LaTeXFeatures & features) const
644 // If we have no image, we should not require anything.
645 if (params().filename.empty())
648 features.includeFile(graphic_label,
649 RemoveExtension(params().filename.absFilename()));
651 features.require("graphicx");
653 if (params().subcaption)
654 features.require("subfigure");
658 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
660 // If nothing is changed, just return and say so.
661 if (params() == p && !p.filename.empty())
664 // Copy the new parameters.
667 // Update the display using the new parameters.
668 graphic_->update(params().as_grfxParams());
670 // We have changed data, report it.
675 InsetGraphicsParams const & InsetGraphics::params() const
681 string const InsetGraphicsMailer::name_("graphics");
683 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
688 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
690 return params2string(inset_.params(), buffer);
694 void InsetGraphicsMailer::string2params(string const & in,
695 Buffer const & buffer,
696 InsetGraphicsParams & params)
698 params = InsetGraphicsParams();
702 istringstream data(in);
708 if (!lex || name != name_)
709 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
712 inset.readInsetGraphics(lex, buffer.filePath());
713 params = inset.params();
718 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
719 Buffer const & buffer)
722 data << name_ << ' ';
723 params.Write(data, buffer.filePath());
724 data << "\\end_inset\n";