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;
96 ///////////////////////////////////////////////////////////////////////////
97 int const VersionNumber = 1;
98 ///////////////////////////////////////////////////////////////////////////
100 // This function is a utility function
101 // ... that should be with ChangeExtension ...
103 string const RemoveExtension(string const & filename)
105 return ChangeExtension(filename, string());
109 string const uniqueID()
111 static unsigned int seed = 1000;
112 return "graph" + tostr(++seed);
116 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
118 // Are we using latex or pdflatex).
119 if (runparams.flavor == LatexRunParams::PDFLATEX) {
120 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
121 if (contains(suffix, "ps") || suffix == "pdf")
123 if (suffix == "jpg") // pdflatex can use jpeg
125 return "png"; // and also png
127 // If it's postscript, we always do eps.
128 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
129 if (suffix != "ps") // any other than ps
130 return "eps"; // is changed to eps
131 return suffix; // let ps untouched
137 InsetGraphics::InsetGraphics()
138 : graphic_label(uniqueID()),
139 graphic_(new GraphicRenderer)
141 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
145 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
147 boost::signals::trackable(),
148 graphic_label(uniqueID()),
149 graphic_(new GraphicRenderer(*ig.graphic_))
151 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
152 setParams(ig.params());
156 InsetBase * InsetGraphics::clone() const
158 return new InsetGraphics(*this);
162 InsetGraphics::~InsetGraphics()
164 InsetGraphicsMailer(*this).hideDialog();
168 void InsetGraphics::statusChanged()
170 BufferView * bv = graphic_->view();
172 bv->updateInset(this);
176 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
178 switch (cmd.action) {
179 case LFUN_INSET_MODIFY: {
180 InsetGraphicsParams p;
181 InsetGraphicsMailer::string2params(cmd.argument, p);
182 if (!p.filename.empty()) {
184 cmd.view()->updateInset(this);
189 case LFUN_INSET_DIALOG_UPDATE:
190 InsetGraphicsMailer(*this).updateDialog(cmd.view());
193 case LFUN_INSET_EDIT:
194 case LFUN_MOUSE_RELEASE:
195 InsetGraphicsMailer(*this).showDialog(cmd.view());
199 return Inset::localDispatch(cmd);
204 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
206 graphic_->metrics(mi, dim);
211 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
213 graphic_->draw(pi, x, y);
217 Inset::EDITABLE InsetGraphics::editable() const
223 void InsetGraphics::write(Buffer const * buf, ostream & os) const
226 params().Write(os, buf->filePath());
230 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
232 string const token = lex.getString();
234 if (token == "Graphics")
235 readInsetGraphics(lex, buf->filePath());
237 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
239 graphic_->update(params().as_grfxParams());
243 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
245 bool finished = false;
247 while (lex.isOK() && !finished) {
250 string const token = lex.getString();
251 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
256 } else if (token == "\\end_inset") {
258 } else if (token == "FormatVersion") {
260 int version = lex.getInteger();
261 if (version > VersionNumber)
263 << "This document was created with a newer Graphics widget"
264 ", You should use a newer version of LyX to read this"
267 // TODO: Possibly open up a dialog?
270 if (!params_.Read(lex, token, bufpath))
271 lyxerr << "Unknown token, " << token << ", skipping."
278 string const InsetGraphics::createLatexOptions() const
280 // Calculate the options part of the command, we must do it to a string
281 // stream since we might have a trailing comma that we would like to remove
282 // before writing it to the output stream.
283 ostringstream options;
284 if (!params().bb.empty())
285 options << " bb=" << rtrim(params().bb) << ",\n";
287 options << " draft,\n";
289 options << " clip,\n";
290 if (!float_equal(params().scale, 0.0, 0.05)) {
291 if (!float_equal(params().scale, 100.0, 0.05))
292 options << " scale=" << params().scale / 100.0
295 if (!params().width.zero())
296 options << " width=" << params().width.asLatexString() << ",\n";
297 if (!params().height.zero())
298 options << " height=" << params().height.asLatexString() << ",\n";
299 if (params().keepAspectRatio)
300 options << " keepaspectratio,\n";
303 // Make sure rotation angle is not very close to zero;
304 // a float can be effectively zero but not exactly zero.
305 if (!float_equal(params().rotateAngle, 0, 0.001)) {
306 options << " angle=" << params().rotateAngle << ",\n";
307 if (!params().rotateOrigin.empty()) {
308 options << " origin=" << params().rotateOrigin[0];
309 if (contains(params().rotateOrigin,"Top"))
311 else if (contains(params().rotateOrigin,"Bottom"))
313 else if (contains(params().rotateOrigin,"Baseline"))
319 if (!params().special.empty())
320 options << params().special << ",\n";
322 string opts = STRCONV(options.str());
324 return opts.substr(0, opts.size() - 2);
328 string const InsetGraphics::prepareFile(Buffer const * buf,
329 LatexRunParams const & runparams) const
331 // LaTeX can cope if the graphics file doesn't exist, so just return the
333 string orig_file = params().filename;
334 string const rel_file = MakeRelPath(orig_file, buf->filePath());
336 if (!IsFileReadable(orig_file)) {
337 lyxerr[Debug::GRAPHICS]
338 << "InsetGraphics::prepareFile\n"
339 << "No file '" << orig_file << "' can be found!" << endl;
343 bool const zipped = zippedFile(orig_file);
345 // If the file is compressed and we have specified that it
346 // should not be uncompressed, then just return its name and
347 // let LaTeX do the rest!
348 if (zipped && params().noUnzip) {
349 lyxerr[Debug::GRAPHICS]
350 << "\tpass zipped file to LaTeX but with full path.\n";
351 // LaTeX needs an absolute path, otherwise the
352 // coresponding *.eps.bb file isn't found
356 // temp_file will contain the file for LaTeX to act on if, for example,
357 // we move it to a temp dir or uncompress it.
358 string temp_file = orig_file;
361 // Uncompress the file if necessary.
362 // If it has been uncompressed in a previous call to
363 // prepareFile, do nothing.
364 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
365 lyxerr[Debug::GRAPHICS]
366 << "\ttemp_file: " << temp_file << endl;
367 if (graphic_->hasFileChanged() || !IsFileReadable(temp_file)) {
368 bool const success = copy(orig_file, temp_file);
369 lyxerr[Debug::GRAPHICS]
370 << "\tCopying zipped file from "
371 << orig_file << " to " << temp_file
372 << (success ? " succeeded\n" : " failed\n");
374 lyxerr[Debug::GRAPHICS]
375 << "\tzipped file " << temp_file
376 << " exists! Maybe no tempdir ...\n";
377 orig_file = unzipFile(temp_file);
378 lyxerr[Debug::GRAPHICS]
379 << "\tunzipped to " << orig_file << endl;
382 string const from = getExtFromContents(orig_file);
383 string const to = findTargetFormat(from, runparams);
384 lyxerr[Debug::GRAPHICS]
385 << "\t we have: from " << from << " to " << to << '\n';
387 if (from == to && !lyxrc.use_tempdir) {
388 // No conversion is needed. LaTeX can handle the
389 // graphic file as is.
390 // This is true even if the orig_file is compressed.
391 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
392 return RemoveExtension(orig_file);
396 // We're going to be running the exported buffer through the LaTeX
397 // compiler, so must ensure that LaTeX can cope with the graphics
400 // Perform all these manipulations on a temporary file if possible.
401 // If we are not using a temp dir, then temp_file contains the
403 // to allow files with the same name in different dirs
404 // we manipulate the original file "any.dir/file.ext"
405 // to "any_dir_file.ext"! changing the dots in the
406 // dirname is important for the use of ChangeExtension
407 lyxerr[Debug::GRAPHICS]
408 << "\tthe orig file is: " << orig_file << endl;
410 if (lyxrc.use_tempdir) {
411 temp_file = copyFileToDir(buf->tmppath, orig_file);
412 if (temp_file.empty()) {
413 string str = bformat(_("Could not copy the file\n%1$s\n"
414 "into the temporary directory."),
416 Alert::error(_("Graphics display failed"), str);
421 // No conversion is needed. LaTeX can handle the
422 // graphic file as is.
423 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
424 return RemoveExtension(temp_file);
429 string const outfile_base = RemoveExtension(temp_file);
430 lyxerr[Debug::GRAPHICS]
431 << "\tThe original file is " << orig_file << "\n"
432 << "\tA copy has been made and convert is to be called with:\n"
433 << "\tfile to convert = " << temp_file << '\n'
434 << "\toutfile_base = " << outfile_base << '\n'
435 << "\t from " << from << " to " << to << '\n';
437 // if no special converter defined, than we take the default one
438 // from ImageMagic: convert from:inname.from to:outname.to
439 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
440 string const command =
441 LibFileSearch("scripts", "convertDefault.sh") +
442 ' ' + from + ':' + temp_file + ' ' +
443 to + ':' + outfile_base + '.' + to;
444 lyxerr[Debug::GRAPHICS]
445 << "No converter defined! I use convertDefault.sh:\n\t"
448 one.startscript(Systemcall::Wait, command);
449 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
450 string str = bformat(_("No information for converting %1$s "
451 "format files to %2$s.\n"
452 "Try defining a convertor in the preferences."), from, to);
453 Alert::error(_("Could not convert image"), str);
457 return RemoveExtension(temp_file);
461 int InsetGraphics::latex(Buffer const * buf, ostream & os,
462 LatexRunParams const & runparams) const
464 // If there is no file specified or not existing,
465 // just output a message about it in the latex output.
466 lyxerr[Debug::GRAPHICS]
467 << "insetgraphics::latex: Filename = "
468 << params().filename << endl;
470 string const relative_file = MakeRelPath(params().filename, buf->filePath());
472 // A missing (e)ps-extension is no problem for LaTeX, so
473 // we have to test three different cases
474 #warning uh, but can our cache handle it ? no.
475 string const file_ = params().filename;
476 bool const file_exists =
478 (IsFileReadable(file_) || // original
479 IsFileReadable(file_ + ".eps") || // original.eps
480 IsFileReadable(file_ + ".ps")); // original.ps
481 string const message = file_exists ?
482 string() : string("bb = 0 0 200 100, draft, type=eps");
483 // if !message.empty() than there was no existing file
484 // "filename(.(e)ps)" found. In this case LaTeX
485 // draws only a rectangle with the above bb and the
486 // not found filename in it.
487 lyxerr[Debug::GRAPHICS]
488 << "\tMessage = \"" << message << '\"' << endl;
490 // These variables collect all the latex code that should be before and
491 // after the actual includegraphics command.
494 // Do we want subcaptions?
495 if (params().subcaption) {
496 before += "\\subfigure[" + params().subcaptionText + "]{";
499 // We never use the starred form, we use the "clip" option instead.
500 before += "\\includegraphics";
502 // Write the options if there are any.
503 string const opts = createLatexOptions();
504 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
506 if (!opts.empty() && !message.empty())
507 before += ("[%\n" + opts + ',' + message + ']');
508 else if (!opts.empty() || !message.empty())
509 before += ("[%\n" + opts + message + ']');
511 lyxerr[Debug::GRAPHICS]
512 << "\tBefore = " << before
513 << "\n\tafter = " << after << endl;
516 // "nice" means that the buffer is exported to LaTeX format but not
517 // run through the LaTeX compiler.
518 if (runparams.nice) {
519 os << before <<'{' << relative_file << '}' << after;
523 // Make the filename relative to the lyx file
524 // and remove the extension so the LaTeX will use whatever is
525 // appropriate (when there are several versions in different formats)
526 string const latex_str = message.empty() ?
527 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
528 (before + '{' + relative_file + " not found!}" + after);
531 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
532 << latex_str << endl;
533 // Return how many newlines we issued.
534 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
538 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
540 // No graphics in ascii output. Possible to use gifscii to convert
541 // images to ascii approximation.
542 // 1. Convert file to ascii using gifscii
543 // 2. Read ascii output file and add it to the output stream.
544 // at least we send the filename
545 os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
550 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
552 // No graphics in LinuxDoc output. Should check how/what to add.
557 // For explanation on inserting graphics into DocBook checkout:
558 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
559 // See also the docbook guide at http://www.docbook.org/
560 int InsetGraphics::docbook(Buffer const *, ostream & os,
561 bool /*mixcont*/) const
563 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
564 // need to switch to MediaObject. However, for now this is sufficient and
566 os << "<graphic fileref=\"&" << graphic_label << ";\">";
571 void InsetGraphics::validate(LaTeXFeatures & features) const
573 // If we have no image, we should not require anything.
574 if (params().filename.empty())
577 features.includeFile(graphic_label, RemoveExtension(params().filename));
579 features.require("graphicx");
581 if (params().subcaption)
582 features.require("subfigure");
586 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
588 // If nothing is changed, just return and say so.
589 if (params() == p && !p.filename.empty())
592 // Copy the new parameters.
595 // Update the display using the new parameters.
596 graphic_->update(params().as_grfxParams());
598 // We have changed data, report it.
603 InsetGraphicsParams const & InsetGraphics::params() const
609 string const InsetGraphicsMailer::name_("graphics");
611 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
616 string const InsetGraphicsMailer::inset2string() const
618 return params2string(inset_.params());
622 void InsetGraphicsMailer::string2params(string const & in,
623 InsetGraphicsParams & params)
625 params = InsetGraphicsParams();
630 istringstream data(STRCONV(in));
636 string const token = lex.getString();
643 #warning FIXME not setting bufpath is dubious
644 inset.readInsetGraphics(lex, string());
645 params = inset.params();
651 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
654 data << name_ << ' ';
655 #warning FIXME not setting bufpath is dubious
656 params.Write(data, string());
657 data << "\\end_inset\n";
658 return STRCONV(data.str());