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 "latexrunparams.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 #include "support/std_sstream.h"
85 namespace support = lyx::support;
86 using namespace lyx::support;
90 using std::istringstream;
92 using std::ostringstream;
97 ///////////////////////////////////////////////////////////////////////////
98 int const VersionNumber = 1;
99 ///////////////////////////////////////////////////////////////////////////
101 // This function is a utility function
102 // ... that should be with ChangeExtension ...
104 string const RemoveExtension(string const & filename)
106 return ChangeExtension(filename, string());
110 string const uniqueID()
112 static unsigned int seed = 1000;
113 return "graph" + tostr(++seed);
117 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
119 // Are we using latex or pdflatex).
120 if (runparams.flavor == LatexRunParams::PDFLATEX) {
121 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
122 if (contains(suffix, "ps") || suffix == "pdf")
124 if (suffix == "jpg") // pdflatex can use jpeg
126 return "png"; // and also png
128 // If it's postscript, we always do eps.
129 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
130 if (suffix != "ps") // any other than ps
131 return "eps"; // is changed to eps
132 return suffix; // let ps untouched
138 InsetGraphics::InsetGraphics()
139 : graphic_label(uniqueID()),
140 graphic_(new GraphicRenderer)
142 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
146 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
148 boost::signals::trackable(),
149 graphic_label(uniqueID()),
150 graphic_(new GraphicRenderer(*ig.graphic_))
152 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
153 setParams(ig.params());
157 auto_ptr<InsetBase> InsetGraphics::clone() const
159 return auto_ptr<InsetBase>(new InsetGraphics(*this));
163 InsetGraphics::~InsetGraphics()
165 InsetGraphicsMailer(*this).hideDialog();
169 void InsetGraphics::statusChanged()
171 BufferView * bv = graphic_->view();
173 bv->updateInset(this);
177 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
179 switch (cmd.action) {
180 case LFUN_INSET_MODIFY: {
181 Buffer const & buffer = *cmd.view()->buffer();
182 InsetGraphicsParams p;
183 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
184 if (!p.filename.empty()) {
186 cmd.view()->updateInset(this);
191 case LFUN_INSET_DIALOG_UPDATE:
192 InsetGraphicsMailer(*this).updateDialog(cmd.view());
195 case LFUN_INSET_EDIT:
196 case LFUN_MOUSE_RELEASE:
197 InsetGraphicsMailer(*this).showDialog(cmd.view());
201 return InsetOld::localDispatch(cmd);
206 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
208 graphic_->metrics(mi, dim);
213 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
215 graphic_->draw(pi, x, y);
219 InsetOld::EDITABLE InsetGraphics::editable() const
225 void InsetGraphics::write(Buffer const & buf, ostream & os) const
228 params().Write(os, buf.filePath());
232 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
234 string const token = lex.getString();
236 if (token == "Graphics")
237 readInsetGraphics(lex, buf.filePath());
239 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
241 graphic_->update(params().as_grfxParams());
245 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
247 bool finished = false;
249 while (lex.isOK() && !finished) {
252 string const token = lex.getString();
253 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
258 } else if (token == "\\end_inset") {
260 } else if (token == "FormatVersion") {
262 int version = lex.getInteger();
263 if (version > VersionNumber)
265 << "This document was created with a newer Graphics widget"
266 ", You should use a newer version of LyX to read this"
269 // TODO: Possibly open up a dialog?
272 if (!params_.Read(lex, token, bufpath))
273 lyxerr << "Unknown token, " << token << ", skipping."
280 string const InsetGraphics::createLatexOptions() const
282 // Calculate the options part of the command, we must do it to a string
283 // stream since we might have a trailing comma that we would like to remove
284 // before writing it to the output stream.
285 ostringstream options;
286 if (!params().bb.empty())
287 options << " bb=" << rtrim(params().bb) << ",\n";
289 options << " draft,\n";
291 options << " clip,\n";
292 if (!float_equal(params().scale, 0.0, 0.05)) {
293 if (!float_equal(params().scale, 100.0, 0.05))
294 options << " scale=" << params().scale / 100.0
297 if (!params().width.zero())
298 options << " width=" << params().width.asLatexString() << ",\n";
299 if (!params().height.zero())
300 options << " height=" << params().height.asLatexString() << ",\n";
301 if (params().keepAspectRatio)
302 options << " keepaspectratio,\n";
305 // Make sure rotation angle is not very close to zero;
306 // a float can be effectively zero but not exactly zero.
307 if (!float_equal(params().rotateAngle, 0, 0.001)) {
308 options << " angle=" << params().rotateAngle << ",\n";
309 if (!params().rotateOrigin.empty()) {
310 options << " origin=" << params().rotateOrigin[0];
311 if (contains(params().rotateOrigin,"Top"))
313 else if (contains(params().rotateOrigin,"Bottom"))
315 else if (contains(params().rotateOrigin,"Baseline"))
321 if (!params().special.empty())
322 options << params().special << ",\n";
324 string opts = STRCONV(options.str());
326 return opts.substr(0, opts.size() - 2);
340 std::pair<CopyStatus, string> const
341 copyToDirIfNeeded(string const & file_in, string const & dir)
343 using support::rtrim;
345 support::Assert(AbsolutePath(file_in));
347 string const only_path = support::OnlyPath(file_in);
348 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
349 return std::make_pair(IDENTICAL_PATHS, file_in);
352 if (support::zippedFile(file_in)) {
353 string const ext = GetExtension(file_in);
354 string const unzipped = support::unzippedFileName(file_in);
355 mangled = FileName(unzipped).mangledFilename();
356 mangled += "." + ext;
358 mangled = FileName(file_in).mangledFilename();
360 string const file_out = support::MakeAbsPath(mangled, dir);
362 unsigned long const checksum_in = support::sum(file_in);
363 unsigned long const checksum_out = support::sum(file_out);
365 if (checksum_in == checksum_out)
367 return std::make_pair(IDENTICAL_CONTENTS, file_out);
369 bool const success = support::copy(file_in, file_out);
371 lyxerr[Debug::GRAPHICS]
372 << support::bformat(_("Could not copy the file\n%1$s\n"
373 "into the temporary directory."),
378 CopyStatus status = success ? SUCCESS : FAILURE;
379 return std::make_pair(status, file_out);
383 string const stripExtensionIfPossible(string const & file, string const & to)
385 // No conversion is needed. LaTeX can handle the graphic file as is.
386 // This is true even if the orig_file is compressed.
387 if (formats.getFormat(to)->extension() == GetExtension(file))
388 return RemoveExtension(file);
395 string const InsetGraphics::prepareFile(Buffer const & buf,
396 LatexRunParams const & runparams) const
398 string orig_file = params().filename.absFilename();
399 string const rel_file = params().filename.relFilename(buf.filePath());
401 // LaTeX can cope if the graphics file doesn't exist, so just return the
403 if (!IsFileReadable(orig_file)) {
404 lyxerr[Debug::GRAPHICS]
405 << "InsetGraphics::prepareFile\n"
406 << "No file '" << orig_file << "' can be found!" << endl;
410 // If the file is compressed and we have specified that it
411 // should not be uncompressed, then just return its name and
412 // let LaTeX do the rest!
413 bool const zipped = params().filename.isZipped();
415 if (zipped && params().noUnzip) {
416 lyxerr[Debug::GRAPHICS]
417 << "\tpass zipped file to LaTeX but with full path.\n";
418 // LaTeX needs an absolute path, otherwise the
419 // coresponding *.eps.bb file isn't found
423 // temp_file will contain the file for LaTeX to act on if, for example,
424 // we move it to a temp dir or uncompress it.
425 string temp_file = orig_file;
429 boost::tie(status, temp_file) =
430 copyToDirIfNeeded(orig_file, buf.temppath());
432 if (status == FAILURE)
435 orig_file = unzippedFileName(temp_file);
436 if (!IsFileReadable(orig_file)) {
437 unzipFile(temp_file);
438 lyxerr[Debug::GRAPHICS]
439 << "\tunzipped to " << orig_file << endl;
443 string const from = getExtFromContents(orig_file);
444 string const to = findTargetFormat(from, runparams);
445 lyxerr[Debug::GRAPHICS]
446 << "\t we have: from " << from << " to " << to << '\n';
448 if (from == to && !lyxrc.use_tempdir)
449 return stripExtensionIfPossible(orig_file, to);
451 // We're going to be running the exported buffer through the LaTeX
452 // compiler, so must ensure that LaTeX can cope with the graphics
455 lyxerr[Debug::GRAPHICS]
456 << "\tthe orig file is: " << orig_file << endl;
458 bool conversion_needed = true;
459 if (lyxrc.use_tempdir) {
461 boost::tie(status, temp_file) =
462 copyToDirIfNeeded(orig_file, buf.temppath());
464 if (status == FAILURE)
466 else if (status == IDENTICAL_CONTENTS)
467 conversion_needed = false;
471 return stripExtensionIfPossible(temp_file, to);
473 string const to_file_base = RemoveExtension(temp_file);
474 string const to_file = ChangeExtension(to_file_base, to);
476 // Do we need to perform the conversion?
477 // Yes if to_file does not exist or if temp_file is newer than to_file
478 if (!conversion_needed ||
479 support::compare_timestamps(temp_file, to_file) < 0) {
480 lyxerr[Debug::GRAPHICS]
481 << bformat(_("No conversion of %1$s is needed after all"),
487 lyxerr[Debug::GRAPHICS]
488 << "\tThe original file is " << orig_file << "\n"
489 << "\tA copy has been made and convert is to be called with:\n"
490 << "\tfile to convert = " << temp_file << '\n'
491 << "\tto_file_base = " << to_file_base << '\n'
492 << "\t from " << from << " to " << to << '\n';
494 // if no special converter defined, than we take the default one
495 // from ImageMagic: convert from:inname.from to:outname.to
496 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
497 string const command =
498 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
499 ' ' + from + ':' + temp_file + ' ' +
500 to + ':' + to_file_base + '.' + to;
501 lyxerr[Debug::GRAPHICS]
502 << "No converter defined! I use convertDefault.sh:\n\t"
505 one.startscript(Systemcall::Wait, command);
506 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
507 string str = bformat(_("No information for converting %1$s "
508 "format files to %2$s.\n"
509 "Try defining a convertor in the preferences."), from, to);
510 Alert::error(_("Could not convert image"), str);
518 int InsetGraphics::latex(Buffer const & buf, ostream & os,
519 LatexRunParams const & runparams) const
521 // If there is no file specified or not existing,
522 // just output a message about it in the latex output.
523 lyxerr[Debug::GRAPHICS]
524 << "insetgraphics::latex: Filename = "
525 << params().filename.absFilename() << endl;
527 string const relative_file =
528 params().filename.relFilename(buf.filePath());
530 // A missing (e)ps-extension is no problem for LaTeX, so
531 // we have to test three different cases
532 #warning uh, but can our cache handle it ? no.
533 string const file_ = params().filename.absFilename();
534 bool const file_exists =
536 (IsFileReadable(file_) || // original
537 IsFileReadable(file_ + ".eps") || // original.eps
538 IsFileReadable(file_ + ".ps")); // original.ps
539 string const message = file_exists ?
540 string() : string("bb = 0 0 200 100, draft, type=eps");
541 // if !message.empty() than there was no existing file
542 // "filename(.(e)ps)" found. In this case LaTeX
543 // draws only a rectangle with the above bb and the
544 // not found filename in it.
545 lyxerr[Debug::GRAPHICS]
546 << "\tMessage = \"" << message << '\"' << endl;
548 // These variables collect all the latex code that should be before and
549 // after the actual includegraphics command.
552 // Do we want subcaptions?
553 if (params().subcaption) {
554 before += "\\subfigure[" + params().subcaptionText + "]{";
557 // We never use the starred form, we use the "clip" option instead.
558 before += "\\includegraphics";
560 // Write the options if there are any.
561 string const opts = createLatexOptions();
562 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
564 if (!opts.empty() && !message.empty())
565 before += ("[%\n" + opts + ',' + message + ']');
566 else if (!opts.empty() || !message.empty())
567 before += ("[%\n" + opts + message + ']');
569 lyxerr[Debug::GRAPHICS]
570 << "\tBefore = " << before
571 << "\n\tafter = " << after << endl;
574 // "nice" means that the buffer is exported to LaTeX format but not
575 // run through the LaTeX compiler.
576 if (runparams.nice) {
577 os << before <<'{' << relative_file << '}' << after;
581 // Make the filename relative to the lyx file
582 // and remove the extension so the LaTeX will use whatever is
583 // appropriate (when there are several versions in different formats)
584 string const latex_str = message.empty() ?
585 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
586 (before + '{' + relative_file + " not found!}" + after);
589 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
590 << latex_str << endl;
591 // Return how many newlines we issued.
592 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
596 int InsetGraphics::ascii(Buffer const &, ostream & os, int) const
598 // No graphics in ascii output. Possible to use gifscii to convert
599 // images to ascii approximation.
600 // 1. Convert file to ascii using gifscii
601 // 2. Read ascii output file and add it to the output stream.
602 // at least we send the filename
603 os << '<' << bformat(_("Graphics file: %1$s"),
604 params().filename.absFilename()) << ">\n";
609 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os) const
611 string const file_name = buf.niceFile() ?
612 params().filename.relFilename(buf.filePath()):
613 params().filename.absFilename();
615 os << "<eps file=\"" << file_name << "\">\n";
616 os << "<img src=\"" << file_name << "\">";
621 // For explanation on inserting graphics into DocBook checkout:
622 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
623 // See also the docbook guide at http://www.docbook.org/
624 int InsetGraphics::docbook(Buffer const &, ostream & os,
625 bool /*mixcont*/) const
627 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
628 // need to switch to MediaObject. However, for now this is sufficient and
630 os << "<graphic fileref=\"&" << graphic_label << ";\">";
635 void InsetGraphics::validate(LaTeXFeatures & features) const
637 // If we have no image, we should not require anything.
638 if (params().filename.empty())
641 features.includeFile(graphic_label,
642 RemoveExtension(params().filename.absFilename()));
644 features.require("graphicx");
646 if (params().subcaption)
647 features.require("subfigure");
651 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
653 // If nothing is changed, just return and say so.
654 if (params() == p && !p.filename.empty())
657 // Copy the new parameters.
660 // Update the display using the new parameters.
661 graphic_->update(params().as_grfxParams());
663 // We have changed data, report it.
668 InsetGraphicsParams const & InsetGraphics::params() const
674 string const InsetGraphicsMailer::name_("graphics");
676 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
681 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
683 return params2string(inset_.params(), buffer);
687 void InsetGraphicsMailer::string2params(string const & in,
688 Buffer const & buffer,
689 InsetGraphicsParams & params)
691 params = InsetGraphicsParams();
696 istringstream data(STRCONV(in));
702 string const token = lex.getString();
709 inset.readInsetGraphics(lex, buffer.filePath());
710 params = inset.params();
716 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
717 Buffer const & buffer)
720 data << name_ << ' ';
721 params.Write(data, buffer.filePath());
722 data << "\\end_inset\n";
723 return STRCONV(data.str());