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/graphicinset.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 GraphicInset)
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 GraphicInset(*ig.graphic_))
149 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
150 setParams(ig.params());
154 Inset * 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(rel_file))
336 bool const zipped = zippedFile(orig_file);
338 // If the file is compressed and we have specified that it
339 // should not be uncompressed, then just return its name and
340 // let LaTeX do the rest!
341 if (zipped && params().noUnzip) {
342 lyxerr[Debug::GRAPHICS]
343 << "\tpass zipped file to LaTeX but with full path.\n";
344 // LaTeX needs an absolute path, otherwise the
345 // coresponding *.eps.bb file isn't found
349 // temp_file will contain the file for LaTeX to act on if, for example,
350 // we move it to a temp dir or uncompress it.
351 string temp_file = orig_file;
354 // Uncompress the file if necessary.
355 // If it has been uncompressed in a previous call to
356 // prepareFile, do nothing.
357 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
358 lyxerr[Debug::GRAPHICS]
359 << "\ttemp_file: " << temp_file << endl;
360 if (graphic_->hasFileChanged() || !IsFileReadable(temp_file)) {
361 bool const success = lyx::copy(orig_file, temp_file);
362 lyxerr[Debug::GRAPHICS]
363 << "\tCopying zipped file from "
364 << orig_file << " to " << temp_file
365 << (success ? " succeeded\n" : " failed\n");
367 lyxerr[Debug::GRAPHICS]
368 << "\tzipped file " << temp_file
369 << " exists! Maybe no tempdir ...\n";
370 orig_file = unzipFile(temp_file);
371 lyxerr[Debug::GRAPHICS]
372 << "\tunzipped to " << orig_file << endl;
375 string const from = getExtFromContents(orig_file);
376 string const to = findTargetFormat(from, runparams);
377 lyxerr[Debug::GRAPHICS]
378 << "\t we have: from " << from << " to " << to << '\n';
380 if (from == to && !lyxrc.use_tempdir) {
381 // No conversion is needed. LaTeX can handle the
382 // graphic file as is.
383 // This is true even if the orig_file is compressed.
384 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
385 return RemoveExtension(orig_file);
389 // We're going to be running the exported buffer through the LaTeX
390 // compiler, so must ensure that LaTeX can cope with the graphics
393 // Perform all these manipulations on a temporary file if possible.
394 // If we are not using a temp dir, then temp_file contains the
396 // to allow files with the same name in different dirs
397 // we manipulate the original file "any.dir/file.ext"
398 // to "any_dir_file.ext"! changing the dots in the
399 // dirname is important for the use of ChangeExtension
400 lyxerr[Debug::GRAPHICS]
401 << "\tthe orig file is: " << orig_file << endl;
403 if (lyxrc.use_tempdir) {
404 temp_file = copyFileToDir(buf->tmppath, orig_file);
405 if (temp_file.empty()) {
406 string str = bformat(_("Could not copy the file\n%1$s\n"
407 "into the temporary directory."),
409 Alert::error(_("Graphics display failed"), str);
414 // No conversion is needed. LaTeX can handle the
415 // graphic file as is.
416 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
417 return RemoveExtension(temp_file);
422 string const outfile_base = RemoveExtension(temp_file);
423 lyxerr[Debug::GRAPHICS]
424 << "\tThe original file is " << orig_file << "\n"
425 << "\tA copy has been made and convert is to be called with:\n"
426 << "\tfile to convert = " << temp_file << '\n'
427 << "\toutfile_base = " << outfile_base << '\n'
428 << "\t from " << from << " to " << to << '\n';
430 // if no special converter defined, than we take the default one
431 // from ImageMagic: convert from:inname.from to:outname.to
432 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
433 string const command =
434 LibFileSearch("scripts", "convertDefault.sh") +
435 ' ' + from + ':' + temp_file + ' ' +
436 to + ':' + outfile_base + '.' + to;
437 lyxerr[Debug::GRAPHICS]
438 << "No converter defined! I use convertDefault.sh:\n\t"
441 one.startscript(Systemcall::Wait, command);
442 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
443 string str = bformat(_("No information for converting %1$s "
444 "format files to %2$s.\n"
445 "Try defining a convertor in the preferences."), from, to);
446 Alert::error(_("Could not convert image"), str);
450 return RemoveExtension(temp_file);
454 int InsetGraphics::latex(Buffer const * buf, ostream & os,
455 LatexRunParams const & runparams) const
457 // If there is no file specified or not existing,
458 // just output a message about it in the latex output.
459 lyxerr[Debug::GRAPHICS]
460 << "insetgraphics::latex: Filename = "
461 << params().filename << endl;
463 string const relative_file = MakeRelPath(params().filename, buf->filePath());
465 // A missing (e)ps-extension is no problem for LaTeX, so
466 // we have to test three different cases
467 #warning uh, but can our cache handle it ? no.
468 string const file_ = params().filename;
469 bool const file_exists =
471 (IsFileReadable(file_) || // original
472 IsFileReadable(file_ + ".eps") || // original.eps
473 IsFileReadable(file_ + ".ps")); // original.ps
474 string const message = file_exists ?
475 string() : string("bb = 0 0 200 100, draft, type=eps");
476 // if !message.empty() than there was no existing file
477 // "filename(.(e)ps)" found. In this case LaTeX
478 // draws only a rectangle with the above bb and the
479 // not found filename in it.
480 lyxerr[Debug::GRAPHICS]
481 << "\tMessage = \"" << message << '\"' << endl;
483 // These variables collect all the latex code that should be before and
484 // after the actual includegraphics command.
487 // Do we want subcaptions?
488 if (params().subcaption) {
489 before += "\\subfigure[" + params().subcaptionText + "]{";
492 // We never use the starred form, we use the "clip" option instead.
493 before += "\\includegraphics";
495 // Write the options if there are any.
496 string const opts = createLatexOptions();
497 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
499 if (!opts.empty() && !message.empty())
500 before += ("[%\n" + opts + ',' + message + ']');
501 else if (!opts.empty() || !message.empty())
502 before += ("[%\n" + opts + message + ']');
504 lyxerr[Debug::GRAPHICS]
505 << "\tBefore = " << before
506 << "\n\tafter = " << after << endl;
509 // "nice" means that the buffer is exported to LaTeX format but not
510 // run through the LaTeX compiler.
511 if (runparams.nice) {
512 os << before <<'{' << relative_file << '}' << after;
516 // Make the filename relative to the lyx file
517 // and remove the extension so the LaTeX will use whatever is
518 // appropriate (when there are several versions in different formats)
519 string const latex_str = message.empty() ?
520 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
521 (before + '{' + relative_file + " not found!}" + after);
524 // Return how many newlines we issued.
525 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
529 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
531 // No graphics in ascii output. Possible to use gifscii to convert
532 // images to ascii approximation.
533 // 1. Convert file to ascii using gifscii
534 // 2. Read ascii output file and add it to the output stream.
535 // at least we send the filename
536 os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
541 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
543 // No graphics in LinuxDoc output. Should check how/what to add.
548 // For explanation on inserting graphics into DocBook checkout:
549 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
550 // See also the docbook guide at http://www.docbook.org/
551 int InsetGraphics::docbook(Buffer const *, ostream & os,
552 bool /*mixcont*/) const
554 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
555 // need to switch to MediaObject. However, for now this is sufficient and
557 os << "<graphic fileref=\"&" << graphic_label << ";\">";
562 void InsetGraphics::validate(LaTeXFeatures & features) const
564 // If we have no image, we should not require anything.
565 if (params().filename.empty())
568 features.includeFile(graphic_label, RemoveExtension(params().filename));
570 features.require("graphicx");
572 if (params().subcaption)
573 features.require("subfigure");
577 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
579 // If nothing is changed, just return and say so.
580 if (params() == p && !p.filename.empty())
583 // Copy the new parameters.
586 // Update the display using the new parameters.
587 graphic_->update(params().as_grfxParams());
589 // We have changed data, report it.
594 InsetGraphicsParams const & InsetGraphics::params() const
600 string const InsetGraphicsMailer::name_("graphics");
602 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
607 string const InsetGraphicsMailer::inset2string() const
609 return params2string(inset_.params());
613 void InsetGraphicsMailer::string2params(string const & in,
614 InsetGraphicsParams & params)
616 params = InsetGraphicsParams();
621 istringstream data(STRCONV(in));
627 string const token = lex.getString();
634 #warning FIXME not setting bufpath is dubious
635 inset.readInsetGraphics(lex, string());
636 params = inset.params();
642 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
645 data << name_ << ' ';
646 #warning FIXME not setting bufpath is dubious
647 params.Write(data, string());
648 data << "\\end_inset\n";
649 return STRCONV(data.str());