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;
94 ///////////////////////////////////////////////////////////////////////////
95 int const VersionNumber = 1;
96 ///////////////////////////////////////////////////////////////////////////
98 // This function is a utility function
99 // ... that should be with ChangeExtension ...
101 string const RemoveExtension(string const & filename)
103 return ChangeExtension(filename, string());
107 string const uniqueID()
109 static unsigned int seed = 1000;
110 return "graph" + tostr(++seed);
114 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
116 // Are we using latex or pdflatex).
117 if (runparams.flavor == LatexRunParams::PDFLATEX) {
118 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
119 if (contains(suffix, "ps") || suffix == "pdf")
121 if (suffix == "jpg") // pdflatex can use jpeg
123 return "png"; // and also png
125 // If it's postscript, we always do eps.
126 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
127 if (suffix != "ps") // any other than ps
128 return "eps"; // is changed to eps
129 return suffix; // let ps untouched
135 InsetGraphics::InsetGraphics()
136 : graphic_label(uniqueID()),
137 graphic_(new GraphicRenderer)
139 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
143 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
145 boost::signals::trackable(),
146 graphic_label(uniqueID()),
147 graphic_(new GraphicRenderer(*ig.graphic_))
149 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
150 setParams(ig.params());
154 InsetBase * InsetGraphics::clone() const
156 return new InsetGraphics(*this);
160 InsetGraphics::~InsetGraphics()
162 InsetGraphicsMailer(*this).hideDialog();
166 void InsetGraphics::statusChanged()
168 BufferView * bv = graphic_->view();
170 bv->updateInset(this);
174 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
176 switch (cmd.action) {
177 case LFUN_INSET_MODIFY: {
178 InsetGraphicsParams p;
179 InsetGraphicsMailer::string2params(cmd.argument, 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 Inset::localDispatch(cmd);
202 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
204 graphic_->metrics(mi, dim);
208 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
210 graphic_->draw(pi, x, y);
214 Inset::EDITABLE InsetGraphics::editable() const
220 void InsetGraphics::write(Buffer const * buf, ostream & os) const
223 params().Write(os, buf->filePath());
227 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
229 string const token = lex.getString();
231 if (token == "Graphics")
232 readInsetGraphics(lex, buf->filePath());
234 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
236 graphic_->update(params().as_grfxParams());
240 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
242 bool finished = false;
244 while (lex.isOK() && !finished) {
247 string const token = lex.getString();
248 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
253 } else if (token == "\\end_inset") {
255 } else if (token == "FormatVersion") {
257 int version = lex.getInteger();
258 if (version > VersionNumber)
260 << "This document was created with a newer Graphics widget"
261 ", You should use a newer version of LyX to read this"
264 // TODO: Possibly open up a dialog?
267 if (!params_.Read(lex, token, bufpath))
268 lyxerr << "Unknown token, " << token << ", skipping."
275 string const InsetGraphics::createLatexOptions() const
277 // Calculate the options part of the command, we must do it to a string
278 // stream since we might have a trailing comma that we would like to remove
279 // before writing it to the output stream.
280 ostringstream options;
281 if (!params().bb.empty())
282 options << " bb=" << rtrim(params().bb) << ",\n";
284 options << " draft,\n";
286 options << " clip,\n";
287 if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
288 if (!lyx::float_equal(params().scale, 100.0, 0.05))
289 options << " scale=" << params().scale / 100.0
292 if (!params().width.zero())
293 options << " width=" << params().width.asLatexString() << ",\n";
294 if (!params().height.zero())
295 options << " height=" << params().height.asLatexString() << ",\n";
296 if (params().keepAspectRatio)
297 options << " keepaspectratio,\n";
300 // Make sure rotation angle is not very close to zero;
301 // a float can be effectively zero but not exactly zero.
302 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
303 options << " angle=" << params().rotateAngle << ",\n";
304 if (!params().rotateOrigin.empty()) {
305 options << " origin=" << params().rotateOrigin[0];
306 if (contains(params().rotateOrigin,"Top"))
308 else if (contains(params().rotateOrigin,"Bottom"))
310 else if (contains(params().rotateOrigin,"Baseline"))
316 if (!params().special.empty())
317 options << params().special << ",\n";
319 string opts = STRCONV(options.str());
321 return opts.substr(0, opts.size() - 2);
325 string const InsetGraphics::prepareFile(Buffer const * buf,
326 LatexRunParams const & runparams) const
328 // LaTeX can cope if the graphics file doesn't exist, so just return the
330 string orig_file = params().filename;
331 string const rel_file = MakeRelPath(orig_file, buf->filePath());
333 if (!IsFileReadable(orig_file)) {
334 lyxerr[Debug::GRAPHICS]
335 << "InsetGraphics::prepareFile\n"
336 << "No file '" << orig_file << "' can be found!" << endl;
340 bool const zipped = zippedFile(orig_file);
342 // If the file is compressed and we have specified that it
343 // should not be uncompressed, then just return its name and
344 // let LaTeX do the rest!
345 if (zipped && params().noUnzip) {
346 lyxerr[Debug::GRAPHICS]
347 << "\tpass zipped file to LaTeX but with full path.\n";
348 // LaTeX needs an absolute path, otherwise the
349 // coresponding *.eps.bb file isn't found
353 // temp_file will contain the file for LaTeX to act on if, for example,
354 // we move it to a temp dir or uncompress it.
355 string temp_file = orig_file;
358 // Uncompress the file if necessary.
359 // If it has been uncompressed in a previous call to
360 // prepareFile, do nothing.
361 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
362 lyxerr[Debug::GRAPHICS]
363 << "\ttemp_file: " << temp_file << endl;
364 if (graphic_->hasFileChanged() || !IsFileReadable(temp_file)) {
365 bool const success = lyx::copy(orig_file, temp_file);
366 lyxerr[Debug::GRAPHICS]
367 << "\tCopying zipped file from "
368 << orig_file << " to " << temp_file
369 << (success ? " succeeded\n" : " failed\n");
371 lyxerr[Debug::GRAPHICS]
372 << "\tzipped file " << temp_file
373 << " exists! Maybe no tempdir ...\n";
374 orig_file = unzipFile(temp_file);
375 lyxerr[Debug::GRAPHICS]
376 << "\tunzipped to " << orig_file << endl;
379 string const from = getExtFromContents(orig_file);
380 string const to = findTargetFormat(from, runparams);
381 lyxerr[Debug::GRAPHICS]
382 << "\t we have: from " << from << " to " << to << '\n';
384 if (from == to && !lyxrc.use_tempdir) {
385 // No conversion is needed. LaTeX can handle the
386 // graphic file as is.
387 // This is true even if the orig_file is compressed.
388 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
389 return RemoveExtension(orig_file);
393 // We're going to be running the exported buffer through the LaTeX
394 // compiler, so must ensure that LaTeX can cope with the graphics
397 // Perform all these manipulations on a temporary file if possible.
398 // If we are not using a temp dir, then temp_file contains the
400 // to allow files with the same name in different dirs
401 // we manipulate the original file "any.dir/file.ext"
402 // to "any_dir_file.ext"! changing the dots in the
403 // dirname is important for the use of ChangeExtension
404 lyxerr[Debug::GRAPHICS]
405 << "\tthe orig file is: " << orig_file << endl;
407 if (lyxrc.use_tempdir) {
408 temp_file = copyFileToDir(buf->tmppath, orig_file);
409 if (temp_file.empty()) {
410 string str = bformat(_("Could not copy the file\n%1$s\n"
411 "into the temporary directory."),
413 Alert::error(_("Graphics display failed"), str);
418 // No conversion is needed. LaTeX can handle the
419 // graphic file as is.
420 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
421 return RemoveExtension(temp_file);
426 string const outfile_base = RemoveExtension(temp_file);
427 lyxerr[Debug::GRAPHICS]
428 << "\tThe original file is " << orig_file << "\n"
429 << "\tA copy has been made and convert is to be called with:\n"
430 << "\tfile to convert = " << temp_file << '\n'
431 << "\toutfile_base = " << outfile_base << '\n'
432 << "\t from " << from << " to " << to << '\n';
434 // if no special converter defined, than we take the default one
435 // from ImageMagic: convert from:inname.from to:outname.to
436 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
437 string const command =
438 LibFileSearch("scripts", "convertDefault.sh") +
439 ' ' + from + ':' + temp_file + ' ' +
440 to + ':' + outfile_base + '.' + to;
441 lyxerr[Debug::GRAPHICS]
442 << "No converter defined! I use convertDefault.sh:\n\t"
445 one.startscript(Systemcall::Wait, command);
446 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
447 string str = bformat(_("No information for converting %1$s "
448 "format files to %2$s.\n"
449 "Try defining a convertor in the preferences."), from, to);
450 Alert::error(_("Could not convert image"), str);
454 return RemoveExtension(temp_file);
458 int InsetGraphics::latex(Buffer const * buf, ostream & os,
459 LatexRunParams const & runparams) const
461 // If there is no file specified or not existing,
462 // just output a message about it in the latex output.
463 lyxerr[Debug::GRAPHICS]
464 << "insetgraphics::latex: Filename = "
465 << params().filename << endl;
467 string const relative_file = MakeRelPath(params().filename, buf->filePath());
469 // A missing (e)ps-extension is no problem for LaTeX, so
470 // we have to test three different cases
471 #warning uh, but can our cache handle it ? no.
472 string const file_ = params().filename;
473 bool const file_exists =
475 (IsFileReadable(file_) || // original
476 IsFileReadable(file_ + ".eps") || // original.eps
477 IsFileReadable(file_ + ".ps")); // original.ps
478 string const message = file_exists ?
479 string() : string("bb = 0 0 200 100, draft, type=eps");
480 // if !message.empty() than there was no existing file
481 // "filename(.(e)ps)" found. In this case LaTeX
482 // draws only a rectangle with the above bb and the
483 // not found filename in it.
484 lyxerr[Debug::GRAPHICS]
485 << "\tMessage = \"" << message << '\"' << endl;
487 // These variables collect all the latex code that should be before and
488 // after the actual includegraphics command.
491 // Do we want subcaptions?
492 if (params().subcaption) {
493 before += "\\subfigure[" + params().subcaptionText + "]{";
496 // We never use the starred form, we use the "clip" option instead.
497 before += "\\includegraphics";
499 // Write the options if there are any.
500 string const opts = createLatexOptions();
501 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
503 if (!opts.empty() && !message.empty())
504 before += ("[%\n" + opts + ',' + message + ']');
505 else if (!opts.empty() || !message.empty())
506 before += ("[%\n" + opts + message + ']');
508 lyxerr[Debug::GRAPHICS]
509 << "\tBefore = " << before
510 << "\n\tafter = " << after << endl;
513 // "nice" means that the buffer is exported to LaTeX format but not
514 // run through the LaTeX compiler.
515 if (runparams.nice) {
516 os << before <<'{' << relative_file << '}' << after;
520 // Make the filename relative to the lyx file
521 // and remove the extension so the LaTeX will use whatever is
522 // appropriate (when there are several versions in different formats)
523 string const latex_str = message.empty() ?
524 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
525 (before + '{' + relative_file + " not found!}" + after);
528 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
529 << latex_str << endl;
530 // Return how many newlines we issued.
531 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
535 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
537 // No graphics in ascii output. Possible to use gifscii to convert
538 // images to ascii approximation.
539 // 1. Convert file to ascii using gifscii
540 // 2. Read ascii output file and add it to the output stream.
541 // at least we send the filename
542 os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
547 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
549 // No graphics in LinuxDoc output. Should check how/what to add.
554 // For explanation on inserting graphics into DocBook checkout:
555 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
556 // See also the docbook guide at http://www.docbook.org/
557 int InsetGraphics::docbook(Buffer const *, ostream & os,
558 bool /*mixcont*/) const
560 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
561 // need to switch to MediaObject. However, for now this is sufficient and
563 os << "<graphic fileref=\"&" << graphic_label << ";\">";
568 void InsetGraphics::validate(LaTeXFeatures & features) const
570 // If we have no image, we should not require anything.
571 if (params().filename.empty())
574 features.includeFile(graphic_label, RemoveExtension(params().filename));
576 features.require("graphicx");
578 if (params().subcaption)
579 features.require("subfigure");
583 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
585 // If nothing is changed, just return and say so.
586 if (params() == p && !p.filename.empty())
589 // Copy the new parameters.
592 // Update the display using the new parameters.
593 graphic_->update(params().as_grfxParams());
595 // We have changed data, report it.
600 InsetGraphicsParams const & InsetGraphics::params() const
606 string const InsetGraphicsMailer::name_("graphics");
608 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
613 string const InsetGraphicsMailer::inset2string() const
615 return params2string(inset_.params());
619 void InsetGraphicsMailer::string2params(string const & in,
620 InsetGraphicsParams & params)
622 params = InsetGraphicsParams();
627 istringstream data(STRCONV(in));
633 string const token = lex.getString();
640 #warning FIXME not setting bufpath is dubious
641 inset.readInsetGraphics(lex, string());
642 params = inset.params();
648 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
651 data << name_ << ' ';
652 #warning FIXME not setting bufpath is dubious
653 params.Write(data, string());
654 data << "\\end_inset\n";
655 return STRCONV(data.str());