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_INSET_MODIFY: {
194 Buffer const & buffer = *cur.bv().buffer();
195 InsetGraphicsParams p;
196 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
197 if (!p.filename.empty()) {
204 case LFUN_INSET_DIALOG_UPDATE:
205 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
208 case LFUN_MOUSE_RELEASE:
209 InsetGraphicsMailer(*this).showDialog(&cur.bv());
213 InsetOld::priv_dispatch(cur, cmd);
219 void InsetGraphics::edit(LCursor & cur, bool)
221 InsetGraphicsMailer(*this).showDialog(&cur.bv());
225 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
227 graphic_->metrics(mi, dim);
232 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
234 setPosCache(pi, x, y);
235 graphic_->draw(pi, x, y);
239 InsetOld::EDITABLE InsetGraphics::editable() const
245 void InsetGraphics::write(Buffer const & buf, ostream & os) const
248 params().Write(os, buf.filePath());
252 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
254 string const token = lex.getString();
256 if (token == "Graphics")
257 readInsetGraphics(lex, buf.filePath());
259 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
261 graphic_->update(params().as_grfxParams());
265 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
267 bool finished = false;
269 while (lex.isOK() && !finished) {
272 string const token = lex.getString();
273 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
278 } else if (token == "\\end_inset") {
281 if (!params_.Read(lex, token, bufpath))
282 lyxerr << "Unknown token, " << token << ", skipping."
289 string const InsetGraphics::createLatexOptions() const
291 // Calculate the options part of the command, we must do it to a string
292 // stream since we might have a trailing comma that we would like to remove
293 // before writing it to the output stream.
294 ostringstream options;
295 if (!params().bb.empty())
296 options << " bb=" << rtrim(params().bb) << ",\n";
298 options << " draft,\n";
300 options << " clip,\n";
301 if (!float_equal(params().scale, 0.0, 0.05)) {
302 if (!float_equal(params().scale, 100.0, 0.05))
303 options << " scale=" << params().scale / 100.0
306 if (!params().width.zero())
307 options << " width=" << params().width.asLatexString() << ",\n";
308 if (!params().height.zero())
309 options << " height=" << params().height.asLatexString() << ",\n";
310 if (params().keepAspectRatio)
311 options << " keepaspectratio,\n";
314 // Make sure rotation angle is not very close to zero;
315 // a float can be effectively zero but not exactly zero.
316 if (!float_equal(params().rotateAngle, 0, 0.001)) {
317 options << " angle=" << params().rotateAngle << ",\n";
318 if (!params().rotateOrigin.empty()) {
319 options << " origin=" << params().rotateOrigin[0];
320 if (contains(params().rotateOrigin,"Top"))
322 else if (contains(params().rotateOrigin,"Bottom"))
324 else if (contains(params().rotateOrigin,"Baseline"))
330 if (!params().special.empty())
331 options << params().special << ",\n";
333 string opts = options.str();
335 return opts.substr(0, opts.size() - 2);
349 std::pair<CopyStatus, string> const
350 copyToDirIfNeeded(string const & file_in, string const & dir)
352 using support::rtrim;
354 BOOST_ASSERT(AbsolutePath(file_in));
356 string const only_path = support::OnlyPath(file_in);
357 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
358 return std::make_pair(IDENTICAL_PATHS, file_in);
361 if (support::zippedFile(file_in)) {
362 string const ext = GetExtension(file_in);
363 string const unzipped = support::unzippedFileName(file_in);
364 mangled = FileName(unzipped).mangledFilename();
365 mangled += "." + ext;
367 mangled = FileName(file_in).mangledFilename();
369 string const file_out = support::MakeAbsPath(mangled, dir);
371 unsigned long const checksum_in = support::sum(file_in);
372 unsigned long const checksum_out = support::sum(file_out);
374 if (checksum_in == checksum_out)
376 return std::make_pair(IDENTICAL_CONTENTS, file_out);
378 bool const success = support::copy(file_in, file_out);
380 lyxerr[Debug::GRAPHICS]
381 << support::bformat(_("Could not copy the file\n%1$s\n"
382 "into the temporary directory."),
387 CopyStatus status = success ? SUCCESS : FAILURE;
388 return std::make_pair(status, file_out);
392 string const stripExtensionIfPossible(string const & file, string const & to)
394 // No conversion is needed. LaTeX can handle the graphic file as is.
395 // This is true even if the orig_file is compressed.
396 if (formats.getFormat(to)->extension() == GetExtension(file))
397 return RemoveExtension(file);
404 string const InsetGraphics::prepareFile(Buffer const & buf,
405 OutputParams const & runparams) const
407 string orig_file = params().filename.absFilename();
408 string const rel_file = params().filename.relFilename(buf.filePath());
410 // LaTeX can cope if the graphics file doesn't exist, so just return the
412 if (!IsFileReadable(orig_file)) {
413 lyxerr[Debug::GRAPHICS]
414 << "InsetGraphics::prepareFile\n"
415 << "No file '" << orig_file << "' can be found!" << endl;
419 // If the file is compressed and we have specified that it
420 // should not be uncompressed, then just return its name and
421 // let LaTeX do the rest!
422 bool const zipped = params().filename.isZipped();
424 if (zipped && params().noUnzip) {
425 lyxerr[Debug::GRAPHICS]
426 << "\tpass zipped file to LaTeX but with full path.\n";
427 // LaTeX needs an absolute path, otherwise the
428 // coresponding *.eps.bb file isn't found
432 // temp_file will contain the file for LaTeX to act on if, for example,
433 // we move it to a temp dir or uncompress it.
434 string temp_file = orig_file;
436 // We place all temporary files in the master buffer's temp dir.
437 // This is possible because we use mangled file names.
438 // This is necessary for DVI export.
439 string const temp_path = buf.getMasterBuffer()->temppath();
443 boost::tie(status, temp_file) =
444 copyToDirIfNeeded(orig_file, temp_path);
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 // We're going to be running the exported buffer through the LaTeX
463 // compiler, so must ensure that LaTeX can cope with the graphics
466 lyxerr[Debug::GRAPHICS]
467 << "\tthe orig file is: " << orig_file << endl;
469 bool conversion_needed = true;
471 boost::tie(status, temp_file) =
472 copyToDirIfNeeded(orig_file, temp_path);
474 if (status == FAILURE)
476 else if (status == IDENTICAL_CONTENTS)
477 conversion_needed = false;
480 return stripExtensionIfPossible(temp_file, to);
482 string const to_file_base = RemoveExtension(temp_file);
483 string const to_file = ChangeExtension(to_file_base, to);
485 // Do we need to perform the conversion?
486 // Yes if to_file does not exist or if temp_file is newer than to_file
487 if (!conversion_needed ||
488 support::compare_timestamps(temp_file, to_file) < 0) {
489 lyxerr[Debug::GRAPHICS]
490 << bformat(_("No conversion of %1$s is needed after all"),
496 lyxerr[Debug::GRAPHICS]
497 << "\tThe original file is " << orig_file << "\n"
498 << "\tA copy has been made and convert is to be called with:\n"
499 << "\tfile to convert = " << temp_file << '\n'
500 << "\tto_file_base = " << to_file_base << '\n'
501 << "\t from " << from << " to " << to << '\n';
503 // if no special converter defined, then we take the default one
504 // from ImageMagic: convert from:inname.from to:outname.to
505 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
506 string const command =
507 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
508 ' ' + from + ':' + temp_file + ' ' +
509 to + ':' + to_file_base + '.' + to;
510 lyxerr[Debug::GRAPHICS]
511 << "No converter defined! I use convertDefault.sh:\n\t"
514 one.startscript(Systemcall::Wait, command);
515 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
516 string str = bformat(_("No information for converting %1$s "
517 "format files to %2$s.\n"
518 "Try defining a convertor in the preferences."), from, to);
519 Alert::error(_("Could not convert image"), str);
527 int InsetGraphics::latex(Buffer const & buf, ostream & os,
528 OutputParams const & runparams) const
530 // The master buffer. This is useful when there are multiple levels
532 Buffer const * m_buffer = buf.getMasterBuffer();
534 // If there is no file specified or not existing,
535 // just output a message about it in the latex output.
536 lyxerr[Debug::GRAPHICS]
537 << "insetgraphics::latex: Filename = "
538 << params().filename.absFilename() << endl;
540 string const relative_file =
541 params().filename.relFilename(buf.filePath());
543 // A missing (e)ps-extension is no problem for LaTeX, so
544 // we have to test three different cases
546 #warning uh, but can our cache handle it ? no.
548 string const file_ = params().filename.absFilename();
549 bool const file_exists =
551 (IsFileReadable(file_) || // original
552 IsFileReadable(file_ + ".eps") || // original.eps
553 IsFileReadable(file_ + ".ps")); // original.ps
554 string const message = file_exists ?
555 string() : string("bb = 0 0 200 100, draft, type=eps");
556 // if !message.empty() than there was no existing file
557 // "filename(.(e)ps)" found. In this case LaTeX
558 // draws only a rectangle with the above bb and the
559 // not found filename in it.
560 lyxerr[Debug::GRAPHICS]
561 << "\tMessage = \"" << message << '\"' << endl;
563 // These variables collect all the latex code that should be before and
564 // after the actual includegraphics command.
567 // Do we want subcaptions?
568 if (params().subcaption) {
569 before += "\\subfigure[" + params().subcaptionText + "]{";
572 // We never use the starred form, we use the "clip" option instead.
573 before += "\\includegraphics";
575 // Write the options if there are any.
576 string const opts = createLatexOptions();
577 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
579 if (!opts.empty() && !message.empty())
580 before += ("[%\n" + opts + ',' + message + ']');
581 else if (!opts.empty() || !message.empty())
582 before += ("[%\n" + opts + message + ']');
584 lyxerr[Debug::GRAPHICS]
585 << "\tBefore = " << before
586 << "\n\tafter = " << after << endl;
589 string latex_str = before + '{';
590 // "nice" means that the buffer is exported to LaTeX format but not
591 // run through the LaTeX compiler.
592 if (runparams.nice) {
593 // a relative filename should be relative to the master
595 latex_str += params().filename.outputFilename(m_buffer->filePath());
596 } else if (file_exists) {
597 // Make the filename relative to the lyx file
598 // and remove the extension so the LaTeX will use whatever
599 // is appropriate (when there are several versions in
600 // different formats)
601 latex_str += os::external_path(prepareFile(buf, runparams));
603 latex_str += relative_file + " not found!";
605 latex_str += '}' + after;
608 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
609 << latex_str << endl;
610 // Return how many newlines we issued.
611 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
615 int InsetGraphics::plaintext(Buffer const &, ostream & os,
616 OutputParams const &) const
618 // No graphics in ascii output. Possible to use gifscii to convert
619 // images to ascii approximation.
620 // 1. Convert file to ascii using gifscii
621 // 2. Read ascii output file and add it to the output stream.
622 // at least we send the filename
623 os << '<' << bformat(_("Graphics file: %1$s"),
624 params().filename.absFilename()) << ">\n";
629 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os,
630 OutputParams const & runparams) const
632 string const file_name = runparams.nice ?
633 params().filename.relFilename(buf.filePath()):
634 params().filename.absFilename();
636 os << "<eps file=\"" << file_name << "\">\n";
637 os << "<img src=\"" << file_name << "\">";
642 // For explanation on inserting graphics into DocBook checkout:
643 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
644 // See also the docbook guide at http://www.docbook.org/
645 int InsetGraphics::docbook(Buffer const &, ostream & os,
646 OutputParams const &) const
648 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
649 // need to switch to MediaObject. However, for now this is sufficient and
651 os << "<graphic fileref=\"&" << graphic_label << ";\">";
656 void InsetGraphics::validate(LaTeXFeatures & features) const
658 // If we have no image, we should not require anything.
659 if (params().filename.empty())
662 features.includeFile(graphic_label,
663 RemoveExtension(params().filename.absFilename()));
665 features.require("graphicx");
667 if (params().subcaption)
668 features.require("subfigure");
672 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
674 // If nothing is changed, just return and say so.
675 if (params() == p && !p.filename.empty())
678 // Copy the new parameters.
681 // Update the display using the new parameters.
682 graphic_->update(params().as_grfxParams());
684 // We have changed data, report it.
689 InsetGraphicsParams const & InsetGraphics::params() const
695 string const InsetGraphicsMailer::name_("graphics");
697 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
702 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
704 return params2string(inset_.params(), buffer);
708 void InsetGraphicsMailer::string2params(string const & in,
709 Buffer const & buffer,
710 InsetGraphicsParams & params)
712 params = InsetGraphicsParams();
716 istringstream data(in);
722 if (!lex || name != name_)
723 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
726 inset.readInsetGraphics(lex, buffer.filePath());
727 params = inset.params();
732 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
733 Buffer const & buffer)
736 data << name_ << ' ';
737 params.Write(data, buffer.filePath());
738 data << "\\end_inset\n";