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/insetgraphicsParams.h"
57 #include "insets/renderers.h"
60 #include "BufferView.h"
61 #include "converter.h"
64 #include "funcrequest.h"
66 #include "LaTeXFeatures.h"
67 #include "latexrunparams.h"
72 #include "frontends/Alert.h"
73 #include "frontends/Dialogs.h"
75 #include "support/filetools.h"
76 #include "support/lyxalgo.h" // lyx::count
77 #include "support/lyxlib.h" // float_equal
78 #include "support/tostr.h"
79 #include "support/systemcall.h"
81 #include <boost/bind.hpp>
83 #include <algorithm> // For the std::max
85 extern string system_tempdir;
88 using namespace lyx::support;
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\n";
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\n";
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 Inset::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 Inset::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!\n";
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);
330 string const InsetGraphics::prepareFile(Buffer const * buf,
331 LatexRunParams const & runparams) const
333 // LaTeX can cope if the graphics file doesn't exist, so just return the
335 string orig_file = params().filename.absFilename();
336 string const rel_file = params().filename.relFilename(buf->filePath());
338 if (!IsFileReadable(orig_file)) {
339 lyxerr[Debug::GRAPHICS]
340 << "InsetGraphics::prepareFile\n"
341 << "No file '" << orig_file << "' can be found!" << endl;
345 bool const zipped = zippedFile(orig_file);
347 // If the file is compressed and we have specified that it
348 // should not be uncompressed, then just return its name and
349 // let LaTeX do the rest!
350 if (zipped && params().noUnzip) {
351 lyxerr[Debug::GRAPHICS]
352 << "\tpass zipped file to LaTeX but with full path.\n";
353 // LaTeX needs an absolute path, otherwise the
354 // coresponding *.eps.bb file isn't found
358 // temp_file will contain the file for LaTeX to act on if, for example,
359 // we move it to a temp dir or uncompress it.
360 string temp_file = orig_file;
363 // Uncompress the file if necessary.
364 // If it has been uncompressed in a previous call to
365 // prepareFile, do nothing.
366 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
367 lyxerr[Debug::GRAPHICS]
368 << "\ttemp_file: " << temp_file << endl;
369 if (graphic_->hasFileChanged() || !IsFileReadable(temp_file)) {
370 bool const success = copy(orig_file, temp_file);
371 lyxerr[Debug::GRAPHICS]
372 << "\tCopying zipped file from "
373 << orig_file << " to " << temp_file
374 << (success ? " succeeded\n" : " failed\n");
376 lyxerr[Debug::GRAPHICS]
377 << "\tzipped file " << temp_file
378 << " exists! Maybe no tempdir ...\n";
379 orig_file = unzipFile(temp_file);
380 lyxerr[Debug::GRAPHICS]
381 << "\tunzipped to " << orig_file << endl;
384 string const from = getExtFromContents(orig_file);
385 string const to = findTargetFormat(from, runparams);
386 lyxerr[Debug::GRAPHICS]
387 << "\t we have: from " << from << " to " << to << '\n';
389 if (from == to && !lyxrc.use_tempdir) {
390 // No conversion is needed. LaTeX can handle the
391 // graphic file as is.
392 // This is true even if the orig_file is compressed.
393 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
394 return RemoveExtension(orig_file);
398 // We're going to be running the exported buffer through the LaTeX
399 // compiler, so must ensure that LaTeX can cope with the graphics
402 // Perform all these manipulations on a temporary file if possible.
403 // If we are not using a temp dir, then temp_file contains the
405 // to allow files with the same name in different dirs
406 // we manipulate the original file "any.dir/file.ext"
407 // to "any_dir_file.ext"! changing the dots in the
408 // dirname is important for the use of ChangeExtension
409 lyxerr[Debug::GRAPHICS]
410 << "\tthe orig file is: " << orig_file << endl;
412 if (lyxrc.use_tempdir) {
413 temp_file = copyFileToDir(buf->tmppath, orig_file);
414 if (temp_file.empty()) {
415 string str = bformat(_("Could not copy the file\n%1$s\n"
416 "into the temporary directory."),
418 Alert::error(_("Graphics display failed"), str);
423 // No conversion is needed. LaTeX can handle the
424 // graphic file as is.
425 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
426 return RemoveExtension(temp_file);
431 string const outfile_base = RemoveExtension(temp_file);
432 lyxerr[Debug::GRAPHICS]
433 << "\tThe original file is " << orig_file << "\n"
434 << "\tA copy has been made and convert is to be called with:\n"
435 << "\tfile to convert = " << temp_file << '\n'
436 << "\toutfile_base = " << outfile_base << '\n'
437 << "\t from " << from << " to " << to << '\n';
439 // if no special converter defined, than we take the default one
440 // from ImageMagic: convert from:inname.from to:outname.to
441 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
442 string const command =
443 LibFileSearch("scripts", "convertDefault.sh") +
444 ' ' + from + ':' + temp_file + ' ' +
445 to + ':' + outfile_base + '.' + to;
446 lyxerr[Debug::GRAPHICS]
447 << "No converter defined! I use convertDefault.sh:\n\t"
450 one.startscript(Systemcall::Wait, command);
451 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
452 string str = bformat(_("No information for converting %1$s "
453 "format files to %2$s.\n"
454 "Try defining a convertor in the preferences."), from, to);
455 Alert::error(_("Could not convert image"), str);
459 return RemoveExtension(temp_file);
463 int InsetGraphics::latex(Buffer const * buf, ostream & os,
464 LatexRunParams const & runparams) const
466 // If there is no file specified or not existing,
467 // just output a message about it in the latex output.
468 lyxerr[Debug::GRAPHICS]
469 << "insetgraphics::latex: Filename = "
470 << params().filename.absFilename() << endl;
472 string const relative_file =
473 params().filename.relFilename(buf->filePath());
475 // A missing (e)ps-extension is no problem for LaTeX, so
476 // we have to test three different cases
477 #warning uh, but can our cache handle it ? no.
478 string const file_ = params().filename.absFilename();
479 bool const file_exists =
481 (IsFileReadable(file_) || // original
482 IsFileReadable(file_ + ".eps") || // original.eps
483 IsFileReadable(file_ + ".ps")); // original.ps
484 string const message = file_exists ?
485 string() : string("bb = 0 0 200 100, draft, type=eps");
486 // if !message.empty() than there was no existing file
487 // "filename(.(e)ps)" found. In this case LaTeX
488 // draws only a rectangle with the above bb and the
489 // not found filename in it.
490 lyxerr[Debug::GRAPHICS]
491 << "\tMessage = \"" << message << '\"' << endl;
493 // These variables collect all the latex code that should be before and
494 // after the actual includegraphics command.
497 // Do we want subcaptions?
498 if (params().subcaption) {
499 before += "\\subfigure[" + params().subcaptionText + "]{";
502 // We never use the starred form, we use the "clip" option instead.
503 before += "\\includegraphics";
505 // Write the options if there are any.
506 string const opts = createLatexOptions();
507 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
509 if (!opts.empty() && !message.empty())
510 before += ("[%\n" + opts + ',' + message + ']');
511 else if (!opts.empty() || !message.empty())
512 before += ("[%\n" + opts + message + ']');
514 lyxerr[Debug::GRAPHICS]
515 << "\tBefore = " << before
516 << "\n\tafter = " << after << endl;
519 // "nice" means that the buffer is exported to LaTeX format but not
520 // run through the LaTeX compiler.
521 if (runparams.nice) {
522 os << before <<'{' << relative_file << '}' << after;
526 // Make the filename relative to the lyx file
527 // and remove the extension so the LaTeX will use whatever is
528 // appropriate (when there are several versions in different formats)
529 string const latex_str = message.empty() ?
530 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
531 (before + '{' + relative_file + " not found!}" + after);
534 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
535 << latex_str << endl;
536 // Return how many newlines we issued.
537 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
541 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
543 // No graphics in ascii output. Possible to use gifscii to convert
544 // images to ascii approximation.
545 // 1. Convert file to ascii using gifscii
546 // 2. Read ascii output file and add it to the output stream.
547 // at least we send the filename
548 os << '<' << bformat(_("Graphics file: %1$s"),
549 params().filename.absFilename()) << ">\n";
554 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
556 // No graphics in LinuxDoc output. Should check how/what to add.
561 // For explanation on inserting graphics into DocBook checkout:
562 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
563 // See also the docbook guide at http://www.docbook.org/
564 int InsetGraphics::docbook(Buffer const *, ostream & os,
565 bool /*mixcont*/) const
567 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
568 // need to switch to MediaObject. However, for now this is sufficient and
570 os << "<graphic fileref=\"&" << graphic_label << ";\">";
575 void InsetGraphics::validate(LaTeXFeatures & features) const
577 // If we have no image, we should not require anything.
578 if (params().filename.empty())
581 features.includeFile(graphic_label,
582 RemoveExtension(params().filename.absFilename()));
584 features.require("graphicx");
586 if (params().subcaption)
587 features.require("subfigure");
591 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
593 // If nothing is changed, just return and say so.
594 if (params() == p && !p.filename.empty())
597 // Copy the new parameters.
600 // Update the display using the new parameters.
601 graphic_->update(params().as_grfxParams());
603 // We have changed data, report it.
608 InsetGraphicsParams const & InsetGraphics::params() const
614 string const InsetGraphicsMailer::name_("graphics");
616 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
621 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
623 return params2string(inset_.params(), buffer);
627 void InsetGraphicsMailer::string2params(string const & in,
628 Buffer const & buffer,
629 InsetGraphicsParams & params)
631 params = InsetGraphicsParams();
636 istringstream data(STRCONV(in));
642 string const token = lex.getString();
649 inset.readInsetGraphics(lex, buffer.filePath());
650 params = inset.params();
656 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
657 Buffer const & buffer)
660 data << name_ << ' ';
661 params.Write(data, buffer.filePath());
662 data << "\\end_inset\n";
663 return STRCONV(data.str());