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/renderers.h"
59 #include "BufferView.h"
60 #include "converter.h"
63 #include "funcrequest.h"
65 #include "LaTeXFeatures.h"
66 #include "support/std_sstream.h"
70 #include "frontends/Alert.h"
72 #include "support/filetools.h"
73 #include "support/LAssert.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"
80 #include <boost/bind.hpp>
81 #include <boost/tuple/tuple.hpp>
83 namespace support = lyx::support;
84 using namespace lyx::support;
93 ///////////////////////////////////////////////////////////////////////////
94 int const VersionNumber = 1;
95 ///////////////////////////////////////////////////////////////////////////
97 // This function is a utility function
98 // ... that should be with ChangeExtension ...
100 string const RemoveExtension(string const & filename)
102 return ChangeExtension(filename, string());
106 string const uniqueID()
108 static unsigned int seed = 1000;
109 return "graph" + tostr(++seed);
113 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
115 // Are we using latex or pdflatex).
116 if (runparams.flavor == LatexRunParams::PDFLATEX) {
117 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
118 if (contains(suffix, "ps") || suffix == "pdf")
120 if (suffix == "jpg") // pdflatex can use jpeg
122 return "png"; // and also png
124 // If it's postscript, we always do eps.
125 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
126 if (suffix != "ps") // any other than ps
127 return "eps"; // is changed to eps
128 return suffix; // let ps untouched
134 InsetGraphics::InsetGraphics()
135 : graphic_label(uniqueID()),
136 graphic_(new GraphicRenderer)
138 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
142 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
144 boost::signals::trackable(),
145 graphic_label(uniqueID()),
146 graphic_(new GraphicRenderer(*ig.graphic_))
148 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
149 setParams(ig.params());
153 auto_ptr<InsetBase> InsetGraphics::clone() const
155 return auto_ptr<InsetBase>(new InsetGraphics(*this));
159 InsetGraphics::~InsetGraphics()
161 InsetGraphicsMailer(*this).hideDialog();
165 void InsetGraphics::statusChanged()
167 BufferView * bv = graphic_->view();
169 bv->updateInset(this);
173 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
175 switch (cmd.action) {
176 case LFUN_INSET_MODIFY: {
177 Buffer const & buffer = *cmd.view()->buffer();
178 InsetGraphicsParams p;
179 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
180 if (!p.filename.empty()) {
182 cmd.view()->updateInset(this);
187 case LFUN_INSET_DIALOG_UPDATE:
188 InsetGraphicsMailer(*this).updateDialog(cmd.view());
191 case LFUN_INSET_EDIT:
192 case LFUN_MOUSE_RELEASE:
193 InsetGraphicsMailer(*this).showDialog(cmd.view());
197 return InsetOld::localDispatch(cmd);
202 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
204 graphic_->metrics(mi, dim);
209 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
211 graphic_->draw(pi, x, y);
215 InsetOld::EDITABLE InsetGraphics::editable() const
221 void InsetGraphics::write(Buffer const & buf, ostream & os) const
224 params().Write(os, buf.filePath());
228 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
230 string const token = lex.getString();
232 if (token == "Graphics")
233 readInsetGraphics(lex, buf.filePath());
235 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
237 graphic_->update(params().as_grfxParams());
241 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
243 bool finished = false;
245 while (lex.isOK() && !finished) {
248 string const token = lex.getString();
249 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
254 } else if (token == "\\end_inset") {
256 } else if (token == "FormatVersion") {
258 int version = lex.getInteger();
259 if (version > VersionNumber)
261 << "This document was created with a newer Graphics widget"
262 ", You should use a newer version of LyX to read this"
265 // TODO: Possibly open up a dialog?
268 if (!params_.Read(lex, token, bufpath))
269 lyxerr << "Unknown token, " << token << ", skipping."
276 string const InsetGraphics::createLatexOptions() const
278 // Calculate the options part of the command, we must do it to a string
279 // stream since we might have a trailing comma that we would like to remove
280 // before writing it to the output stream.
281 ostringstream options;
282 if (!params().bb.empty())
283 options << " bb=" << rtrim(params().bb) << ",\n";
285 options << " draft,\n";
287 options << " clip,\n";
288 if (!float_equal(params().scale, 0.0, 0.05)) {
289 if (!float_equal(params().scale, 100.0, 0.05))
290 options << " scale=" << params().scale / 100.0
293 if (!params().width.zero())
294 options << " width=" << params().width.asLatexString() << ",\n";
295 if (!params().height.zero())
296 options << " height=" << params().height.asLatexString() << ",\n";
297 if (params().keepAspectRatio)
298 options << " keepaspectratio,\n";
301 // Make sure rotation angle is not very close to zero;
302 // a float can be effectively zero but not exactly zero.
303 if (!float_equal(params().rotateAngle, 0, 0.001)) {
304 options << " angle=" << params().rotateAngle << ",\n";
305 if (!params().rotateOrigin.empty()) {
306 options << " origin=" << params().rotateOrigin[0];
307 if (contains(params().rotateOrigin,"Top"))
309 else if (contains(params().rotateOrigin,"Bottom"))
311 else if (contains(params().rotateOrigin,"Baseline"))
317 if (!params().special.empty())
318 options << params().special << ",\n";
320 string opts = STRCONV(options.str());
322 return opts.substr(0, opts.size() - 2);
336 std::pair<CopyStatus, string> const
337 copyToDirIfNeeded(string const & file_in, string const & dir)
339 using support::rtrim;
341 support::Assert(AbsolutePath(file_in));
343 string const only_path = support::OnlyPath(file_in);
344 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
345 return std::make_pair(IDENTICAL_PATHS, file_in);
348 if (support::zippedFile(file_in)) {
349 string const ext = GetExtension(file_in);
350 string const unzipped = support::unzippedFileName(file_in);
351 mangled = FileName(unzipped).mangledFilename();
352 mangled += "." + ext;
354 mangled = FileName(file_in).mangledFilename();
356 string const file_out = support::MakeAbsPath(mangled, dir);
358 unsigned long const checksum_in = support::sum(file_in);
359 unsigned long const checksum_out = support::sum(file_out);
361 if (checksum_in == checksum_out)
363 return std::make_pair(IDENTICAL_CONTENTS, file_out);
365 bool const success = support::copy(file_in, file_out);
367 lyxerr[Debug::GRAPHICS]
368 << support::bformat(_("Could not copy the file\n%1$s\n"
369 "into the temporary directory."),
374 CopyStatus status = success ? SUCCESS : FAILURE;
375 return std::make_pair(status, file_out);
379 string const stripExtensionIfPossible(string const & file, string const & to)
381 // No conversion is needed. LaTeX can handle the graphic file as is.
382 // This is true even if the orig_file is compressed.
383 if (formats.getFormat(to)->extension() == GetExtension(file))
384 return RemoveExtension(file);
391 string const InsetGraphics::prepareFile(Buffer const & buf,
392 LatexRunParams const & runparams) const
394 string orig_file = params().filename.absFilename();
395 string const rel_file = params().filename.relFilename(buf.filePath());
397 // LaTeX can cope if the graphics file doesn't exist, so just return the
399 if (!IsFileReadable(orig_file)) {
400 lyxerr[Debug::GRAPHICS]
401 << "InsetGraphics::prepareFile\n"
402 << "No file '" << orig_file << "' can be found!" << endl;
406 // If the file is compressed and we have specified that it
407 // should not be uncompressed, then just return its name and
408 // let LaTeX do the rest!
409 bool const zipped = params().filename.isZipped();
411 if (zipped && params().noUnzip) {
412 lyxerr[Debug::GRAPHICS]
413 << "\tpass zipped file to LaTeX but with full path.\n";
414 // LaTeX needs an absolute path, otherwise the
415 // coresponding *.eps.bb file isn't found
419 // temp_file will contain the file for LaTeX to act on if, for example,
420 // we move it to a temp dir or uncompress it.
421 string temp_file = orig_file;
425 boost::tie(status, temp_file) =
426 copyToDirIfNeeded(orig_file, buf.tmppath);
428 if (status == FAILURE)
431 orig_file = unzippedFileName(temp_file);
432 if (!IsFileReadable(orig_file)) {
433 unzipFile(temp_file);
434 lyxerr[Debug::GRAPHICS]
435 << "\tunzipped to " << orig_file << endl;
439 string const from = getExtFromContents(orig_file);
440 string const to = findTargetFormat(from, runparams);
441 lyxerr[Debug::GRAPHICS]
442 << "\t we have: from " << from << " to " << to << '\n';
444 if (from == to && !lyxrc.use_tempdir)
445 return stripExtensionIfPossible(orig_file, to);
447 // We're going to be running the exported buffer through the LaTeX
448 // compiler, so must ensure that LaTeX can cope with the graphics
451 lyxerr[Debug::GRAPHICS]
452 << "\tthe orig file is: " << orig_file << endl;
454 bool conversion_needed = true;
455 if (lyxrc.use_tempdir) {
457 boost::tie(status, temp_file) =
458 copyToDirIfNeeded(orig_file, buf.tmppath);
460 if (status == FAILURE)
462 else if (status == IDENTICAL_CONTENTS)
463 conversion_needed = false;
467 return stripExtensionIfPossible(temp_file, to);
469 string const to_file_base = RemoveExtension(temp_file);
470 string const to_file = ChangeExtension(to_file_base, to);
472 // Do we need to perform the conversion?
473 // Yes if to_file does not exist or if temp_file is newer than to_file
474 if (!conversion_needed ||
475 support::compare_timestamps(temp_file, to_file) < 0) {
476 lyxerr[Debug::GRAPHICS]
477 << bformat(_("No conversion of %1$s is needed after all"),
483 lyxerr[Debug::GRAPHICS]
484 << "\tThe original file is " << orig_file << "\n"
485 << "\tA copy has been made and convert is to be called with:\n"
486 << "\tfile to convert = " << temp_file << '\n'
487 << "\tto_file_base = " << to_file_base << '\n'
488 << "\t from " << from << " to " << to << '\n';
490 // if no special converter defined, than we take the default one
491 // from ImageMagic: convert from:inname.from to:outname.to
492 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
493 string const command =
494 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
495 ' ' + from + ':' + temp_file + ' ' +
496 to + ':' + to_file_base + '.' + to;
497 lyxerr[Debug::GRAPHICS]
498 << "No converter defined! I use convertDefault.sh:\n\t"
501 one.startscript(Systemcall::Wait, command);
502 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
503 string str = bformat(_("No information for converting %1$s "
504 "format files to %2$s.\n"
505 "Try defining a convertor in the preferences."), from, to);
506 Alert::error(_("Could not convert image"), str);
514 int InsetGraphics::latex(Buffer const & buf, ostream & os,
515 LatexRunParams const & runparams) const
517 // If there is no file specified or not existing,
518 // just output a message about it in the latex output.
519 lyxerr[Debug::GRAPHICS]
520 << "insetgraphics::latex: Filename = "
521 << params().filename.absFilename() << endl;
523 string const relative_file =
524 params().filename.relFilename(buf.filePath());
526 // A missing (e)ps-extension is no problem for LaTeX, so
527 // we have to test three different cases
528 #warning uh, but can our cache handle it ? no.
529 string const file_ = params().filename.absFilename();
530 bool const file_exists =
532 (IsFileReadable(file_) || // original
533 IsFileReadable(file_ + ".eps") || // original.eps
534 IsFileReadable(file_ + ".ps")); // original.ps
535 string const message = file_exists ?
536 string() : string("bb = 0 0 200 100, draft, type=eps");
537 // if !message.empty() than there was no existing file
538 // "filename(.(e)ps)" found. In this case LaTeX
539 // draws only a rectangle with the above bb and the
540 // not found filename in it.
541 lyxerr[Debug::GRAPHICS]
542 << "\tMessage = \"" << message << '\"' << endl;
544 // These variables collect all the latex code that should be before and
545 // after the actual includegraphics command.
548 // Do we want subcaptions?
549 if (params().subcaption) {
550 before += "\\subfigure[" + params().subcaptionText + "]{";
553 // We never use the starred form, we use the "clip" option instead.
554 before += "\\includegraphics";
556 // Write the options if there are any.
557 string const opts = createLatexOptions();
558 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
560 if (!opts.empty() && !message.empty())
561 before += ("[%\n" + opts + ',' + message + ']');
562 else if (!opts.empty() || !message.empty())
563 before += ("[%\n" + opts + message + ']');
565 lyxerr[Debug::GRAPHICS]
566 << "\tBefore = " << before
567 << "\n\tafter = " << after << endl;
570 // "nice" means that the buffer is exported to LaTeX format but not
571 // run through the LaTeX compiler.
572 if (runparams.nice) {
573 os << before <<'{' << relative_file << '}' << after;
577 // Make the filename relative to the lyx file
578 // and remove the extension so the LaTeX will use whatever is
579 // appropriate (when there are several versions in different formats)
580 string const latex_str = message.empty() ?
581 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
582 (before + '{' + relative_file + " not found!}" + after);
585 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
586 << latex_str << endl;
587 // Return how many newlines we issued.
588 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
592 int InsetGraphics::ascii(Buffer const &, ostream & os, int) const
594 // No graphics in ascii output. Possible to use gifscii to convert
595 // images to ascii approximation.
596 // 1. Convert file to ascii using gifscii
597 // 2. Read ascii output file and add it to the output stream.
598 // at least we send the filename
599 os << '<' << bformat(_("Graphics file: %1$s"),
600 params().filename.absFilename()) << ">\n";
605 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os) const
607 string const file_name = buf.niceFile ?
608 params().filename.relFilename(buf.filePath()):
609 params().filename.absFilename();
611 os << "<eps file=\"" << file_name << "\">\n";
612 os << "<img src=\"" << file_name << "\">";
617 // For explanation on inserting graphics into DocBook checkout:
618 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
619 // See also the docbook guide at http://www.docbook.org/
620 int InsetGraphics::docbook(Buffer const &, ostream & os,
621 bool /*mixcont*/) const
623 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
624 // need to switch to MediaObject. However, for now this is sufficient and
626 os << "<graphic fileref=\"&" << graphic_label << ";\">";
631 void InsetGraphics::validate(LaTeXFeatures & features) const
633 // If we have no image, we should not require anything.
634 if (params().filename.empty())
637 features.includeFile(graphic_label,
638 RemoveExtension(params().filename.absFilename()));
640 features.require("graphicx");
642 if (params().subcaption)
643 features.require("subfigure");
647 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
649 // If nothing is changed, just return and say so.
650 if (params() == p && !p.filename.empty())
653 // Copy the new parameters.
656 // Update the display using the new parameters.
657 graphic_->update(params().as_grfxParams());
659 // We have changed data, report it.
664 InsetGraphicsParams const & InsetGraphics::params() const
670 string const InsetGraphicsMailer::name_("graphics");
672 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
677 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
679 return params2string(inset_.params(), buffer);
683 void InsetGraphicsMailer::string2params(string const & in,
684 Buffer const & buffer,
685 InsetGraphicsParams & params)
687 params = InsetGraphicsParams();
692 istringstream data(STRCONV(in));
698 string const token = lex.getString();
705 inset.readInsetGraphics(lex, buffer.filePath());
706 params = inset.params();
712 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
713 Buffer const & buffer)
716 data << name_ << ' ';
717 params.Write(data, buffer.filePath());
718 data << "\\end_inset\n";
719 return STRCONV(data.str());