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"
67 #include "metricsinfo.h"
68 #include "outputparams.h"
70 #include "frontends/Alert.h"
71 #include "frontends/LyXView.h"
73 #include "support/filetools.h"
74 #include "support/lyxalgo.h" // lyx::count
75 #include "support/lyxlib.h" // float_equal
76 #include "support/os.h"
77 #include "support/systemcall.h"
78 #include "support/tostr.h"
79 #include "support/std_sstream.h"
81 #include <boost/bind.hpp>
82 #include <boost/tuple/tuple.hpp>
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::rtrim;
96 using lyx::support::Systemcall;
97 using lyx::support::unzipFile;
98 using lyx::support::unzippedFileName;
100 namespace os = lyx::support::os;
105 using std::istringstream;
107 using std::ostringstream;
112 ///////////////////////////////////////////////////////////////////////////
113 int const VersionNumber = 1;
114 ///////////////////////////////////////////////////////////////////////////
116 // This function is a utility function
117 // ... that should be with ChangeExtension ...
119 string const RemoveExtension(string const & filename)
121 return ChangeExtension(filename, string());
125 string const uniqueID()
127 static unsigned int seed = 1000;
128 return "graph" + tostr(++seed);
132 string findTargetFormat(string const & suffix, OutputParams const & runparams)
134 // Are we using latex or pdflatex).
135 if (runparams.flavor == OutputParams::PDFLATEX) {
136 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
137 if (contains(suffix, "ps") || suffix == "pdf")
139 if (suffix == "jpg") // pdflatex can use jpeg
141 return "png"; // and also png
143 // If it's postscript, we always do eps.
144 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
145 if (suffix != "ps") // any other than ps
146 return "eps"; // is changed to eps
147 return suffix; // let ps untouched
153 InsetGraphics::InsetGraphics()
154 : graphic_label(uniqueID()),
155 graphic_(new RenderGraphic)
157 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
161 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
163 boost::signals::trackable(),
164 graphic_label(uniqueID()),
165 graphic_(new RenderGraphic(*ig.graphic_))
167 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
168 setParams(ig.params());
172 auto_ptr<InsetBase> InsetGraphics::clone() const
174 return auto_ptr<InsetBase>(new InsetGraphics(*this));
178 InsetGraphics::~InsetGraphics()
180 InsetGraphicsMailer(*this).hideDialog();
184 void InsetGraphics::statusChanged() const
186 LyX::cref().updateInset(this);
190 void InsetGraphics::priv_dispatch(LCursor & cur, FuncRequest & cmd)
192 switch (cmd.action) {
193 case LFUN_GRAPHICS_EDIT: {
194 Buffer const & buffer = *cur.bv().buffer();
195 InsetGraphicsParams p;
196 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
197 editGraphics(p, buffer);
201 case LFUN_INSET_MODIFY: {
202 Buffer const & buffer = cur.buffer();
203 InsetGraphicsParams p;
204 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
205 if (!p.filename.empty()) {
212 case LFUN_INSET_DIALOG_UPDATE:
213 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
216 case LFUN_MOUSE_RELEASE:
217 InsetGraphicsMailer(*this).showDialog(&cur.bv());
221 InsetOld::priv_dispatch(cur, cmd);
227 void InsetGraphics::edit(LCursor & cur, bool)
229 InsetGraphicsMailer(*this).showDialog(&cur.bv());
233 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
235 graphic_->metrics(mi, dim);
240 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
242 setPosCache(pi, x, y);
243 graphic_->draw(pi, x, y);
247 InsetOld::EDITABLE InsetGraphics::editable() const
253 void InsetGraphics::write(Buffer const & buf, ostream & os) const
256 params().Write(os, buf.filePath());
260 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
262 string const token = lex.getString();
264 if (token == "Graphics")
265 readInsetGraphics(lex, buf.filePath());
267 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
269 graphic_->update(params().as_grfxParams());
273 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
275 bool finished = false;
277 while (lex.isOK() && !finished) {
280 string const token = lex.getString();
281 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
286 } else if (token == "\\end_inset") {
289 if (!params_.Read(lex, token, bufpath))
290 lyxerr << "Unknown token, " << token << ", skipping."
297 string const InsetGraphics::createLatexOptions() const
299 // Calculate the options part of the command, we must do it to a string
300 // stream since we might have a trailing comma that we would like to remove
301 // before writing it to the output stream.
302 ostringstream options;
303 if (!params().bb.empty())
304 options << " bb=" << rtrim(params().bb) << ",\n";
306 options << " draft,\n";
308 options << " clip,\n";
309 if (!float_equal(params().scale, 0.0, 0.05)) {
310 if (!float_equal(params().scale, 100.0, 0.05))
311 options << " scale=" << params().scale / 100.0
314 if (!params().width.zero())
315 options << " width=" << params().width.asLatexString() << ",\n";
316 if (!params().height.zero())
317 options << " height=" << params().height.asLatexString() << ",\n";
318 if (params().keepAspectRatio)
319 options << " keepaspectratio,\n";
322 // Make sure rotation angle is not very close to zero;
323 // a float can be effectively zero but not exactly zero.
324 if (!float_equal(params().rotateAngle, 0, 0.001)) {
325 options << " angle=" << params().rotateAngle << ",\n";
326 if (!params().rotateOrigin.empty()) {
327 options << " origin=" << params().rotateOrigin[0];
328 if (contains(params().rotateOrigin,"Top"))
330 else if (contains(params().rotateOrigin,"Bottom"))
332 else if (contains(params().rotateOrigin,"Baseline"))
338 if (!params().special.empty())
339 options << params().special << ",\n";
341 string opts = options.str();
343 return opts.substr(0, opts.size() - 2);
357 std::pair<CopyStatus, string> const
358 copyToDirIfNeeded(string const & file_in, string const & dir)
360 using support::rtrim;
362 BOOST_ASSERT(AbsolutePath(file_in));
364 string const only_path = support::OnlyPath(file_in);
365 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
366 return std::make_pair(IDENTICAL_PATHS, file_in);
369 if (support::zippedFile(file_in)) {
370 string const ext = GetExtension(file_in);
371 string const unzipped = support::unzippedFileName(file_in);
372 mangled = FileName(unzipped).mangledFilename();
373 mangled += "." + ext;
375 mangled = FileName(file_in).mangledFilename();
377 string const file_out = support::MakeAbsPath(mangled, dir);
379 unsigned long const checksum_in = support::sum(file_in);
380 unsigned long const checksum_out = support::sum(file_out);
382 if (checksum_in == checksum_out)
384 return std::make_pair(IDENTICAL_CONTENTS, file_out);
386 bool const success = support::copy(file_in, file_out);
388 lyxerr[Debug::GRAPHICS]
389 << support::bformat(_("Could not copy the file\n%1$s\n"
390 "into the temporary directory."),
395 CopyStatus status = success ? SUCCESS : FAILURE;
396 return std::make_pair(status, file_out);
400 string const stripExtensionIfPossible(string const & file, string const & to)
402 // No conversion is needed. LaTeX can handle the graphic file as is.
403 // This is true even if the orig_file is compressed.
404 if (formats.getFormat(to)->extension() == GetExtension(file))
405 return RemoveExtension(file);
412 string const InsetGraphics::prepareFile(Buffer const & buf,
413 OutputParams const & runparams) const
415 string orig_file = params().filename.absFilename();
416 string const rel_file = params().filename.relFilename(buf.filePath());
418 // LaTeX can cope if the graphics file doesn't exist, so just return the
420 if (!IsFileReadable(orig_file)) {
421 lyxerr[Debug::GRAPHICS]
422 << "InsetGraphics::prepareFile\n"
423 << "No file '" << orig_file << "' can be found!" << endl;
427 // If the file is compressed and we have specified that it
428 // should not be uncompressed, then just return its name and
429 // let LaTeX do the rest!
430 bool const zipped = params().filename.isZipped();
432 if (zipped && params().noUnzip) {
433 lyxerr[Debug::GRAPHICS]
434 << "\tpass zipped file to LaTeX but with full path.\n";
435 // LaTeX needs an absolute path, otherwise the
436 // coresponding *.eps.bb file isn't found
440 // temp_file will contain the file for LaTeX to act on if, for example,
441 // we move it to a temp dir or uncompress it.
442 string temp_file = orig_file;
444 // We place all temporary files in the master buffer's temp dir.
445 // This is possible because we use mangled file names.
446 // This is necessary for DVI export.
447 string const temp_path = buf.getMasterBuffer()->temppath();
451 boost::tie(status, temp_file) =
452 copyToDirIfNeeded(orig_file, temp_path);
454 if (status == FAILURE)
457 orig_file = unzippedFileName(temp_file);
458 if (!IsFileReadable(orig_file)) {
459 unzipFile(temp_file);
460 lyxerr[Debug::GRAPHICS]
461 << "\tunzipped to " << orig_file << endl;
465 string const from = getExtFromContents(orig_file);
466 string const to = findTargetFormat(from, runparams);
467 lyxerr[Debug::GRAPHICS]
468 << "\t we have: from " << from << " to " << to << '\n';
470 // We're going to be running the exported buffer through the LaTeX
471 // compiler, so must ensure that LaTeX can cope with the graphics
474 lyxerr[Debug::GRAPHICS]
475 << "\tthe orig file is: " << orig_file << endl;
477 bool conversion_needed = true;
479 boost::tie(status, temp_file) =
480 copyToDirIfNeeded(orig_file, temp_path);
482 if (status == FAILURE)
484 else if (status == IDENTICAL_CONTENTS)
485 conversion_needed = false;
488 return stripExtensionIfPossible(temp_file, to);
490 string const to_file_base = RemoveExtension(temp_file);
491 string const to_file = ChangeExtension(to_file_base, to);
493 // Do we need to perform the conversion?
494 // Yes if to_file does not exist or if temp_file is newer than to_file
495 if (!conversion_needed ||
496 support::compare_timestamps(temp_file, to_file) < 0) {
497 lyxerr[Debug::GRAPHICS]
498 << bformat(_("No conversion of %1$s is needed after all"),
504 lyxerr[Debug::GRAPHICS]
505 << "\tThe original file is " << orig_file << "\n"
506 << "\tA copy has been made and convert is to be called with:\n"
507 << "\tfile to convert = " << temp_file << '\n'
508 << "\tto_file_base = " << to_file_base << '\n'
509 << "\t from " << from << " to " << to << '\n';
511 // if no special converter defined, then we take the default one
512 // from ImageMagic: convert from:inname.from to:outname.to
513 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
514 string const command =
515 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
516 ' ' + from + ':' + temp_file + ' ' +
517 to + ':' + to_file_base + '.' + to;
518 lyxerr[Debug::GRAPHICS]
519 << "No converter defined! I use convertDefault.sh:\n\t"
522 one.startscript(Systemcall::Wait, command);
523 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
524 string str = bformat(_("No information for converting %1$s "
525 "format files to %2$s.\n"
526 "Try defining a convertor in the preferences."), from, to);
527 Alert::error(_("Could not convert image"), str);
535 int InsetGraphics::latex(Buffer const & buf, ostream & os,
536 OutputParams const & runparams) const
538 // The master buffer. This is useful when there are multiple levels
540 Buffer const * m_buffer = buf.getMasterBuffer();
542 // If there is no file specified or not existing,
543 // just output a message about it in the latex output.
544 lyxerr[Debug::GRAPHICS]
545 << "insetgraphics::latex: Filename = "
546 << params().filename.absFilename() << endl;
548 string const relative_file =
549 params().filename.relFilename(buf.filePath());
551 // A missing (e)ps-extension is no problem for LaTeX, so
552 // we have to test three different cases
554 #warning uh, but can our cache handle it ? no.
556 string const file_ = params().filename.absFilename();
557 bool const file_exists =
559 (IsFileReadable(file_) || // original
560 IsFileReadable(file_ + ".eps") || // original.eps
561 IsFileReadable(file_ + ".ps")); // original.ps
562 string const message = file_exists ?
563 string() : string("bb = 0 0 200 100, draft, type=eps");
564 // if !message.empty() than there was no existing file
565 // "filename(.(e)ps)" found. In this case LaTeX
566 // draws only a rectangle with the above bb and the
567 // not found filename in it.
568 lyxerr[Debug::GRAPHICS]
569 << "\tMessage = \"" << message << '\"' << endl;
571 // These variables collect all the latex code that should be before and
572 // after the actual includegraphics command.
575 // Do we want subcaptions?
576 if (params().subcaption) {
577 before += "\\subfigure[" + params().subcaptionText + "]{";
580 // We never use the starred form, we use the "clip" option instead.
581 before += "\\includegraphics";
583 // Write the options if there are any.
584 string const opts = createLatexOptions();
585 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
587 if (!opts.empty() && !message.empty())
588 before += ("[%\n" + opts + ',' + message + ']');
589 else if (!opts.empty() || !message.empty())
590 before += ("[%\n" + opts + message + ']');
592 lyxerr[Debug::GRAPHICS]
593 << "\tBefore = " << before
594 << "\n\tafter = " << after << endl;
597 string latex_str = before + '{';
598 // "nice" means that the buffer is exported to LaTeX format but not
599 // run through the LaTeX compiler.
600 if (runparams.nice) {
601 // a relative filename should be relative to the master
603 latex_str += params().filename.outputFilename(m_buffer->filePath());
604 } else if (file_exists) {
605 // Make the filename relative to the lyx file
606 // and remove the extension so the LaTeX will use whatever
607 // is appropriate (when there are several versions in
608 // different formats)
609 latex_str += os::external_path(prepareFile(buf, runparams));
611 latex_str += relative_file + " not found!";
613 latex_str += '}' + after;
616 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
617 << latex_str << endl;
618 // Return how many newlines we issued.
619 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
623 int InsetGraphics::plaintext(Buffer const &, ostream & os,
624 OutputParams const &) const
626 // No graphics in ascii output. Possible to use gifscii to convert
627 // images to ascii approximation.
628 // 1. Convert file to ascii using gifscii
629 // 2. Read ascii output file and add it to the output stream.
630 // at least we send the filename
631 os << '<' << bformat(_("Graphics file: %1$s"),
632 params().filename.absFilename()) << ">\n";
637 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os,
638 OutputParams const & runparams) const
640 string const file_name = runparams.nice ?
641 params().filename.relFilename(buf.filePath()):
642 params().filename.absFilename();
644 os << "<eps file=\"" << file_name << "\">\n";
645 os << "<img src=\"" << file_name << "\">";
650 // For explanation on inserting graphics into DocBook checkout:
651 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
652 // See also the docbook guide at http://www.docbook.org/
653 int InsetGraphics::docbook(Buffer const &, ostream & os,
654 OutputParams const &) const
656 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
657 // need to switch to MediaObject. However, for now this is sufficient and
659 os << "<graphic fileref=\"&" << graphic_label << ";\">";
664 void InsetGraphics::validate(LaTeXFeatures & features) const
666 // If we have no image, we should not require anything.
667 if (params().filename.empty())
670 features.includeFile(graphic_label,
671 RemoveExtension(params().filename.absFilename()));
673 features.require("graphicx");
675 if (params().subcaption)
676 features.require("subfigure");
680 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
682 // If nothing is changed, just return and say so.
683 if (params() == p && !p.filename.empty())
686 // Copy the new parameters.
689 // Update the display using the new parameters.
690 graphic_->update(params().as_grfxParams());
692 // We have changed data, report it.
697 InsetGraphicsParams const & InsetGraphics::params() const
703 void InsetGraphics::editGraphics(InsetGraphicsParams const & p, Buffer const & buffer) const
705 string const file_with_path = p.filename.absFilename();
706 formats.edit(buffer, file_with_path, getExtFromContents(file_with_path));
710 string const InsetGraphicsMailer::name_("graphics");
712 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
717 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
719 return params2string(inset_.params(), buffer);
723 void InsetGraphicsMailer::string2params(string const & in,
724 Buffer const & buffer,
725 InsetGraphicsParams & params)
727 params = InsetGraphicsParams();
731 istringstream data(in);
737 if (!lex || name != name_)
738 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
741 inset.readInsetGraphics(lex, buffer.filePath());
742 params = inset.params();
747 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
748 Buffer const & buffer)
751 data << name_ << ' ';
752 params.Write(data, buffer.filePath());
753 data << "\\end_inset\n";