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);
210 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
212 graphic_->draw(pi, x, y);
216 Inset::EDITABLE InsetGraphics::editable() const
222 void InsetGraphics::write(Buffer const * buf, ostream & os) const
225 params().Write(os, buf->filePath());
229 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
231 string const token = lex.getString();
233 if (token == "Graphics")
234 readInsetGraphics(lex, buf->filePath());
236 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
238 graphic_->update(params().as_grfxParams());
242 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
244 bool finished = false;
246 while (lex.isOK() && !finished) {
249 string const token = lex.getString();
250 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
255 } else if (token == "\\end_inset") {
257 } else if (token == "FormatVersion") {
259 int version = lex.getInteger();
260 if (version > VersionNumber)
262 << "This document was created with a newer Graphics widget"
263 ", You should use a newer version of LyX to read this"
266 // TODO: Possibly open up a dialog?
269 if (!params_.Read(lex, token, bufpath))
270 lyxerr << "Unknown token, " << token << ", skipping."
277 string const InsetGraphics::createLatexOptions() const
279 // Calculate the options part of the command, we must do it to a string
280 // stream since we might have a trailing comma that we would like to remove
281 // before writing it to the output stream.
282 ostringstream options;
283 if (!params().bb.empty())
284 options << " bb=" << rtrim(params().bb) << ",\n";
286 options << " draft,\n";
288 options << " clip,\n";
289 if (!float_equal(params().scale, 0.0, 0.05)) {
290 if (!float_equal(params().scale, 100.0, 0.05))
291 options << " scale=" << params().scale / 100.0
294 if (!params().width.zero())
295 options << " width=" << params().width.asLatexString() << ",\n";
296 if (!params().height.zero())
297 options << " height=" << params().height.asLatexString() << ",\n";
298 if (params().keepAspectRatio)
299 options << " keepaspectratio,\n";
302 // Make sure rotation angle is not very close to zero;
303 // a float can be effectively zero but not exactly zero.
304 if (!float_equal(params().rotateAngle, 0, 0.001)) {
305 options << " angle=" << params().rotateAngle << ",\n";
306 if (!params().rotateOrigin.empty()) {
307 options << " origin=" << params().rotateOrigin[0];
308 if (contains(params().rotateOrigin,"Top"))
310 else if (contains(params().rotateOrigin,"Bottom"))
312 else if (contains(params().rotateOrigin,"Baseline"))
318 if (!params().special.empty())
319 options << params().special << ",\n";
321 string opts = STRCONV(options.str());
323 return opts.substr(0, opts.size() - 2);
327 string const InsetGraphics::prepareFile(Buffer const * buf,
328 LatexRunParams const & runparams) const
330 // LaTeX can cope if the graphics file doesn't exist, so just return the
332 string orig_file = params().filename;
333 string const rel_file = MakeRelPath(orig_file, buf->filePath());
335 if (!IsFileReadable(orig_file)) {
336 lyxerr[Debug::GRAPHICS]
337 << "InsetGraphics::prepareFile\n"
338 << "No file '" << orig_file << "' can be found!" << endl;
342 bool const zipped = zippedFile(orig_file);
344 // If the file is compressed and we have specified that it
345 // should not be uncompressed, then just return its name and
346 // let LaTeX do the rest!
347 if (zipped && params().noUnzip) {
348 lyxerr[Debug::GRAPHICS]
349 << "\tpass zipped file to LaTeX but with full path.\n";
350 // LaTeX needs an absolute path, otherwise the
351 // coresponding *.eps.bb file isn't found
355 // temp_file will contain the file for LaTeX to act on if, for example,
356 // we move it to a temp dir or uncompress it.
357 string temp_file = orig_file;
360 // Uncompress the file if necessary.
361 // If it has been uncompressed in a previous call to
362 // prepareFile, do nothing.
363 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
364 lyxerr[Debug::GRAPHICS]
365 << "\ttemp_file: " << temp_file << endl;
366 if (graphic_->hasFileChanged() || !IsFileReadable(temp_file)) {
367 bool const success = copy(orig_file, temp_file);
368 lyxerr[Debug::GRAPHICS]
369 << "\tCopying zipped file from "
370 << orig_file << " to " << temp_file
371 << (success ? " succeeded\n" : " failed\n");
373 lyxerr[Debug::GRAPHICS]
374 << "\tzipped file " << temp_file
375 << " exists! Maybe no tempdir ...\n";
376 orig_file = unzipFile(temp_file);
377 lyxerr[Debug::GRAPHICS]
378 << "\tunzipped to " << orig_file << endl;
381 string const from = getExtFromContents(orig_file);
382 string const to = findTargetFormat(from, runparams);
383 lyxerr[Debug::GRAPHICS]
384 << "\t we have: from " << from << " to " << to << '\n';
386 if (from == to && !lyxrc.use_tempdir) {
387 // No conversion is needed. LaTeX can handle the
388 // graphic file as is.
389 // This is true even if the orig_file is compressed.
390 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
391 return RemoveExtension(orig_file);
395 // We're going to be running the exported buffer through the LaTeX
396 // compiler, so must ensure that LaTeX can cope with the graphics
399 // Perform all these manipulations on a temporary file if possible.
400 // If we are not using a temp dir, then temp_file contains the
402 // to allow files with the same name in different dirs
403 // we manipulate the original file "any.dir/file.ext"
404 // to "any_dir_file.ext"! changing the dots in the
405 // dirname is important for the use of ChangeExtension
406 lyxerr[Debug::GRAPHICS]
407 << "\tthe orig file is: " << orig_file << endl;
409 if (lyxrc.use_tempdir) {
410 temp_file = copyFileToDir(buf->tmppath, orig_file);
411 if (temp_file.empty()) {
412 string str = bformat(_("Could not copy the file\n%1$s\n"
413 "into the temporary directory."),
415 Alert::error(_("Graphics display failed"), str);
420 // No conversion is needed. LaTeX can handle the
421 // graphic file as is.
422 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
423 return RemoveExtension(temp_file);
428 string const outfile_base = RemoveExtension(temp_file);
429 lyxerr[Debug::GRAPHICS]
430 << "\tThe original file is " << orig_file << "\n"
431 << "\tA copy has been made and convert is to be called with:\n"
432 << "\tfile to convert = " << temp_file << '\n'
433 << "\toutfile_base = " << outfile_base << '\n'
434 << "\t from " << from << " to " << to << '\n';
436 // if no special converter defined, than we take the default one
437 // from ImageMagic: convert from:inname.from to:outname.to
438 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
439 string const command =
440 LibFileSearch("scripts", "convertDefault.sh") +
441 ' ' + from + ':' + temp_file + ' ' +
442 to + ':' + outfile_base + '.' + to;
443 lyxerr[Debug::GRAPHICS]
444 << "No converter defined! I use convertDefault.sh:\n\t"
447 one.startscript(Systemcall::Wait, command);
448 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
449 string str = bformat(_("No information for converting %1$s "
450 "format files to %2$s.\n"
451 "Try defining a convertor in the preferences."), from, to);
452 Alert::error(_("Could not convert image"), str);
456 return RemoveExtension(temp_file);
460 int InsetGraphics::latex(Buffer const * buf, ostream & os,
461 LatexRunParams const & runparams) const
463 // If there is no file specified or not existing,
464 // just output a message about it in the latex output.
465 lyxerr[Debug::GRAPHICS]
466 << "insetgraphics::latex: Filename = "
467 << params().filename << endl;
469 string const relative_file = MakeRelPath(params().filename, buf->filePath());
471 // A missing (e)ps-extension is no problem for LaTeX, so
472 // we have to test three different cases
473 #warning uh, but can our cache handle it ? no.
474 string const file_ = params().filename;
475 bool const file_exists =
477 (IsFileReadable(file_) || // original
478 IsFileReadable(file_ + ".eps") || // original.eps
479 IsFileReadable(file_ + ".ps")); // original.ps
480 string const message = file_exists ?
481 string() : string("bb = 0 0 200 100, draft, type=eps");
482 // if !message.empty() than there was no existing file
483 // "filename(.(e)ps)" found. In this case LaTeX
484 // draws only a rectangle with the above bb and the
485 // not found filename in it.
486 lyxerr[Debug::GRAPHICS]
487 << "\tMessage = \"" << message << '\"' << endl;
489 // These variables collect all the latex code that should be before and
490 // after the actual includegraphics command.
493 // Do we want subcaptions?
494 if (params().subcaption) {
495 before += "\\subfigure[" + params().subcaptionText + "]{";
498 // We never use the starred form, we use the "clip" option instead.
499 before += "\\includegraphics";
501 // Write the options if there are any.
502 string const opts = createLatexOptions();
503 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
505 if (!opts.empty() && !message.empty())
506 before += ("[%\n" + opts + ',' + message + ']');
507 else if (!opts.empty() || !message.empty())
508 before += ("[%\n" + opts + message + ']');
510 lyxerr[Debug::GRAPHICS]
511 << "\tBefore = " << before
512 << "\n\tafter = " << after << endl;
515 // "nice" means that the buffer is exported to LaTeX format but not
516 // run through the LaTeX compiler.
517 if (runparams.nice) {
518 os << before <<'{' << relative_file << '}' << after;
522 // Make the filename relative to the lyx file
523 // and remove the extension so the LaTeX will use whatever is
524 // appropriate (when there are several versions in different formats)
525 string const latex_str = message.empty() ?
526 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
527 (before + '{' + relative_file + " not found!}" + after);
530 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
531 << latex_str << endl;
532 // Return how many newlines we issued.
533 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
537 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
539 // No graphics in ascii output. Possible to use gifscii to convert
540 // images to ascii approximation.
541 // 1. Convert file to ascii using gifscii
542 // 2. Read ascii output file and add it to the output stream.
543 // at least we send the filename
544 os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
549 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
551 // No graphics in LinuxDoc output. Should check how/what to add.
556 // For explanation on inserting graphics into DocBook checkout:
557 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
558 // See also the docbook guide at http://www.docbook.org/
559 int InsetGraphics::docbook(Buffer const *, ostream & os,
560 bool /*mixcont*/) const
562 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
563 // need to switch to MediaObject. However, for now this is sufficient and
565 os << "<graphic fileref=\"&" << graphic_label << ";\">";
570 void InsetGraphics::validate(LaTeXFeatures & features) const
572 // If we have no image, we should not require anything.
573 if (params().filename.empty())
576 features.includeFile(graphic_label, RemoveExtension(params().filename));
578 features.require("graphicx");
580 if (params().subcaption)
581 features.require("subfigure");
585 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
587 // If nothing is changed, just return and say so.
588 if (params() == p && !p.filename.empty())
591 // Copy the new parameters.
594 // Update the display using the new parameters.
595 graphic_->update(params().as_grfxParams());
597 // We have changed data, report it.
602 InsetGraphicsParams const & InsetGraphics::params() const
608 string const InsetGraphicsMailer::name_("graphics");
610 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
615 string const InsetGraphicsMailer::inset2string() const
617 return params2string(inset_.params());
621 void InsetGraphicsMailer::string2params(string const & in,
622 InsetGraphicsParams & params)
624 params = InsetGraphicsParams();
629 istringstream data(STRCONV(in));
635 string const token = lex.getString();
642 #warning FIXME not setting bufpath is dubious
643 inset.readInsetGraphics(lex, string());
644 params = inset.params();
650 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
653 data << name_ << ' ';
654 #warning FIXME not setting bufpath is dubious
655 params.Write(data, string());
656 data << "\\end_inset\n";
657 return STRCONV(data.str());