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;
437 // We place all temporary files in the master buffer's temp dir.
438 // This is possible because we use mangled file names.
439 // This is necessary for DVI export.
440 string const temp_path = buf.getMasterBuffer()->temppath();
444 boost::tie(status, temp_file) =
445 copyToDirIfNeeded(orig_file, temp_path);
447 if (status == FAILURE)
450 orig_file = unzippedFileName(temp_file);
451 if (!IsFileReadable(orig_file)) {
452 unzipFile(temp_file);
453 lyxerr[Debug::GRAPHICS]
454 << "\tunzipped to " << orig_file << endl;
458 string const from = getExtFromContents(orig_file);
459 string const to = findTargetFormat(from, runparams);
460 lyxerr[Debug::GRAPHICS]
461 << "\t we have: from " << from << " to " << to << '\n';
463 // We're going to be running the exported buffer through the LaTeX
464 // compiler, so must ensure that LaTeX can cope with the graphics
467 lyxerr[Debug::GRAPHICS]
468 << "\tthe orig file is: " << orig_file << endl;
470 bool conversion_needed = true;
472 boost::tie(status, temp_file) =
473 copyToDirIfNeeded(orig_file, temp_path);
475 if (status == FAILURE)
477 else if (status == IDENTICAL_CONTENTS)
478 conversion_needed = false;
481 return stripExtensionIfPossible(temp_file, to);
483 string const to_file_base = RemoveExtension(temp_file);
484 string const to_file = ChangeExtension(to_file_base, to);
486 // Do we need to perform the conversion?
487 // Yes if to_file does not exist or if temp_file is newer than to_file
488 if (!conversion_needed ||
489 support::compare_timestamps(temp_file, to_file) < 0) {
490 lyxerr[Debug::GRAPHICS]
491 << bformat(_("No conversion of %1$s is needed after all"),
497 lyxerr[Debug::GRAPHICS]
498 << "\tThe original file is " << orig_file << "\n"
499 << "\tA copy has been made and convert is to be called with:\n"
500 << "\tfile to convert = " << temp_file << '\n'
501 << "\tto_file_base = " << to_file_base << '\n'
502 << "\t from " << from << " to " << to << '\n';
504 // if no special converter defined, then we take the default one
505 // from ImageMagic: convert from:inname.from to:outname.to
506 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
507 string const command =
508 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
509 ' ' + from + ':' + temp_file + ' ' +
510 to + ':' + to_file_base + '.' + to;
511 lyxerr[Debug::GRAPHICS]
512 << "No converter defined! I use convertDefault.sh:\n\t"
515 one.startscript(Systemcall::Wait, command);
516 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
517 string str = bformat(_("No information for converting %1$s "
518 "format files to %2$s.\n"
519 "Try defining a convertor in the preferences."), from, to);
520 Alert::error(_("Could not convert image"), str);
528 int InsetGraphics::latex(Buffer const & buf, ostream & os,
529 OutputParams const & runparams) const
531 // The master buffer. This is useful when there are multiple levels
533 Buffer const * m_buffer = buf.getMasterBuffer();
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 string latex_str = before + '{';
589 // "nice" means that the buffer is exported to LaTeX format but not
590 // run through the LaTeX compiler.
591 if (runparams.nice) {
592 // a relative filename should be relative to the master
594 latex_str += params().filename.outputFilename(m_buffer->filePath());
595 } else if (file_exists) {
596 // Make the filename relative to the lyx file
597 // and remove the extension so the LaTeX will use whatever
598 // is appropriate (when there are several versions in
599 // different formats)
600 latex_str += os::external_path(prepareFile(buf, runparams));
602 latex_str += relative_file + " not found!";
604 latex_str += '}' + after;
607 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
608 << latex_str << endl;
609 // Return how many newlines we issued.
610 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
614 int InsetGraphics::plaintext(Buffer const &, ostream & os,
615 OutputParams const &) const
617 // No graphics in ascii output. Possible to use gifscii to convert
618 // images to ascii approximation.
619 // 1. Convert file to ascii using gifscii
620 // 2. Read ascii output file and add it to the output stream.
621 // at least we send the filename
622 os << '<' << bformat(_("Graphics file: %1$s"),
623 params().filename.absFilename()) << ">\n";
628 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os,
629 OutputParams const & runparams) const
631 string const file_name = runparams.nice ?
632 params().filename.relFilename(buf.filePath()):
633 params().filename.absFilename();
635 os << "<eps file=\"" << file_name << "\">\n";
636 os << "<img src=\"" << file_name << "\">";
641 // For explanation on inserting graphics into DocBook checkout:
642 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
643 // See also the docbook guide at http://www.docbook.org/
644 int InsetGraphics::docbook(Buffer const &, ostream & os,
645 OutputParams const &) const
647 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
648 // need to switch to MediaObject. However, for now this is sufficient and
650 os << "<graphic fileref=\"&" << graphic_label << ";\">";
655 void InsetGraphics::validate(LaTeXFeatures & features) const
657 // If we have no image, we should not require anything.
658 if (params().filename.empty())
661 features.includeFile(graphic_label,
662 RemoveExtension(params().filename.absFilename()));
664 features.require("graphicx");
666 if (params().subcaption)
667 features.require("subfigure");
671 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
673 // If nothing is changed, just return and say so.
674 if (params() == p && !p.filename.empty())
677 // Copy the new parameters.
680 // Update the display using the new parameters.
681 graphic_->update(params().as_grfxParams());
683 // We have changed data, report it.
688 InsetGraphicsParams const & InsetGraphics::params() const
694 string const InsetGraphicsMailer::name_("graphics");
696 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
701 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
703 return params2string(inset_.params(), buffer);
707 void InsetGraphicsMailer::string2params(string const & in,
708 Buffer const & buffer,
709 InsetGraphicsParams & params)
711 params = InsetGraphicsParams();
715 istringstream data(in);
721 if (!lex || name != name_)
722 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
725 inset.readInsetGraphics(lex, buffer.filePath());
726 params = inset.params();
731 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
732 Buffer const & buffer)
735 data << name_ << ' ';
736 params.Write(data, buffer.filePath());
737 data << "\\end_inset\n";