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
87 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" << endl;
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" << endl;
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 auto_ptr<InsetBase> InsetGraphics::clone() const
158 return auto_ptr<InsetBase>(new InsetGraphics(*this));
162 InsetGraphics::~InsetGraphics()
164 InsetGraphicsMailer(*this).hideDialog();
168 void InsetGraphics::statusChanged()
170 BufferView * bv = graphic_->view();
176 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
178 switch (cmd.action) {
179 case LFUN_INSET_MODIFY: {
180 Buffer const & buffer = *cmd.view()->buffer();
181 InsetGraphicsParams p;
182 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
183 if (!p.filename.empty()) {
185 cmd.view()->updateInset();
190 case LFUN_INSET_DIALOG_UPDATE:
191 InsetGraphicsMailer(*this).updateDialog(cmd.view());
194 case LFUN_INSET_EDIT:
195 case LFUN_MOUSE_RELEASE:
196 InsetGraphicsMailer(*this).showDialog(cmd.view());
200 return InsetOld::localDispatch(cmd);
205 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
207 graphic_->metrics(mi, dim);
212 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
214 graphic_->draw(pi, x, y);
218 InsetOld::EDITABLE InsetGraphics::editable() const
224 void InsetGraphics::write(Buffer const * buf, ostream & os) const
227 params().Write(os, buf->filePath());
231 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
233 string const token = lex.getString();
235 if (token == "Graphics")
236 readInsetGraphics(lex, buf->filePath());
238 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
240 graphic_->update(params().as_grfxParams());
244 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
246 bool finished = false;
248 while (lex.isOK() && !finished) {
251 string const token = lex.getString();
252 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
257 } else if (token == "\\end_inset") {
259 } else if (token == "FormatVersion") {
261 int version = lex.getInteger();
262 if (version > VersionNumber)
264 << "This document was created with a newer Graphics widget"
265 ", You should use a newer version of LyX to read this"
268 // TODO: Possibly open up a dialog?
271 if (!params_.Read(lex, token, bufpath))
272 lyxerr << "Unknown token, " << token << ", skipping."
279 string const InsetGraphics::createLatexOptions() const
281 // Calculate the options part of the command, we must do it to a string
282 // stream since we might have a trailing comma that we would like to remove
283 // before writing it to the output stream.
284 ostringstream options;
285 if (!params().bb.empty())
286 options << " bb=" << rtrim(params().bb) << ",\n";
288 options << " draft,\n";
290 options << " clip,\n";
291 if (!float_equal(params().scale, 0.0, 0.05)) {
292 if (!float_equal(params().scale, 100.0, 0.05))
293 options << " scale=" << params().scale / 100.0
296 if (!params().width.zero())
297 options << " width=" << params().width.asLatexString() << ",\n";
298 if (!params().height.zero())
299 options << " height=" << params().height.asLatexString() << ",\n";
300 if (params().keepAspectRatio)
301 options << " keepaspectratio,\n";
304 // Make sure rotation angle is not very close to zero;
305 // a float can be effectively zero but not exactly zero.
306 if (!float_equal(params().rotateAngle, 0, 0.001)) {
307 options << " angle=" << params().rotateAngle << ",\n";
308 if (!params().rotateOrigin.empty()) {
309 options << " origin=" << params().rotateOrigin[0];
310 if (contains(params().rotateOrigin,"Top"))
312 else if (contains(params().rotateOrigin,"Bottom"))
314 else if (contains(params().rotateOrigin,"Baseline"))
320 if (!params().special.empty())
321 options << params().special << ",\n";
323 string opts = STRCONV(options.str());
325 return opts.substr(0, opts.size() - 2);
329 string const InsetGraphics::prepareFile(Buffer const * buf,
330 LatexRunParams const & runparams) const
332 // LaTeX can cope if the graphics file doesn't exist, so just return the
334 string orig_file = params().filename.absFilename();
335 string const rel_file = params().filename.relFilename(buf->filePath());
337 if (!IsFileReadable(orig_file)) {
338 lyxerr[Debug::GRAPHICS]
339 << "InsetGraphics::prepareFile\n"
340 << "No file '" << orig_file << "' can be found!" << endl;
344 bool const zipped = zippedFile(orig_file);
346 // If the file is compressed and we have specified that it
347 // should not be uncompressed, then just return its name and
348 // let LaTeX do the rest!
349 if (zipped && params().noUnzip) {
350 lyxerr[Debug::GRAPHICS]
351 << "\tpass zipped file to LaTeX but with full path.\n";
352 // LaTeX needs an absolute path, otherwise the
353 // coresponding *.eps.bb file isn't found
357 // temp_file will contain the file for LaTeX to act on if, for example,
358 // we move it to a temp dir or uncompress it.
359 string temp_file = orig_file;
362 // Uncompress the file if necessary.
363 // If it has been uncompressed in a previous call to
364 // prepareFile, do nothing.
365 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
366 lyxerr[Debug::GRAPHICS]
367 << "\ttemp_file: " << temp_file << endl;
368 if (graphic_->hasFileChanged() || !IsFileReadable(temp_file)) {
369 bool const success = copy(orig_file, temp_file);
370 lyxerr[Debug::GRAPHICS]
371 << "\tCopying zipped file from "
372 << orig_file << " to " << temp_file
373 << (success ? " succeeded\n" : " failed\n");
375 lyxerr[Debug::GRAPHICS]
376 << "\tzipped file " << temp_file
377 << " exists! Maybe no tempdir ...\n";
378 orig_file = unzipFile(temp_file);
379 lyxerr[Debug::GRAPHICS]
380 << "\tunzipped to " << orig_file << endl;
383 string const from = getExtFromContents(orig_file);
384 string const to = findTargetFormat(from, runparams);
385 lyxerr[Debug::GRAPHICS]
386 << "\t we have: from " << from << " to " << to << '\n';
388 if (from == to && !lyxrc.use_tempdir) {
389 // No conversion is needed. LaTeX can handle the
390 // graphic file as is.
391 // This is true even if the orig_file is compressed.
392 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
393 return RemoveExtension(orig_file);
397 // We're going to be running the exported buffer through the LaTeX
398 // compiler, so must ensure that LaTeX can cope with the graphics
401 // Perform all these manipulations on a temporary file if possible.
402 // If we are not using a temp dir, then temp_file contains the
404 // to allow files with the same name in different dirs
405 // we manipulate the original file "any.dir/file.ext"
406 // to "any_dir_file.ext"! changing the dots in the
407 // dirname is important for the use of ChangeExtension
408 lyxerr[Debug::GRAPHICS]
409 << "\tthe orig file is: " << orig_file << endl;
411 if (lyxrc.use_tempdir) {
412 temp_file = copyFileToDir(buf->tmppath, orig_file);
413 if (temp_file.empty()) {
414 string str = bformat(_("Could not copy the file\n%1$s\n"
415 "into the temporary directory."),
417 Alert::error(_("Graphics display failed"), str);
422 // No conversion is needed. LaTeX can handle the
423 // graphic file as is.
424 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
425 return RemoveExtension(temp_file);
430 string const outfile_base = RemoveExtension(temp_file);
431 lyxerr[Debug::GRAPHICS]
432 << "\tThe original file is " << orig_file << "\n"
433 << "\tA copy has been made and convert is to be called with:\n"
434 << "\tfile to convert = " << temp_file << '\n'
435 << "\toutfile_base = " << outfile_base << '\n'
436 << "\t from " << from << " to " << to << '\n';
438 // if no special converter defined, than we take the default one
439 // from ImageMagic: convert from:inname.from to:outname.to
440 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
441 string const command =
442 LibFileSearch("scripts", "convertDefault.sh") +
443 ' ' + from + ':' + temp_file + ' ' +
444 to + ':' + outfile_base + '.' + to;
445 lyxerr[Debug::GRAPHICS]
446 << "No converter defined! I use convertDefault.sh:\n\t"
449 one.startscript(Systemcall::Wait, command);
450 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
451 string str = bformat(_("No information for converting %1$s "
452 "format files to %2$s.\n"
453 "Try defining a convertor in the preferences."), from, to);
454 Alert::error(_("Could not convert image"), str);
458 return RemoveExtension(temp_file);
462 int InsetGraphics::latex(Buffer const * buf, ostream & os,
463 LatexRunParams const & runparams) const
465 // If there is no file specified or not existing,
466 // just output a message about it in the latex output.
467 lyxerr[Debug::GRAPHICS]
468 << "insetgraphics::latex: Filename = "
469 << params().filename.absFilename() << endl;
471 string const relative_file =
472 params().filename.relFilename(buf->filePath());
474 // A missing (e)ps-extension is no problem for LaTeX, so
475 // we have to test three different cases
476 #warning uh, but can our cache handle it ? no.
477 string const file_ = params().filename.absFilename();
478 bool const file_exists =
480 (IsFileReadable(file_) || // original
481 IsFileReadable(file_ + ".eps") || // original.eps
482 IsFileReadable(file_ + ".ps")); // original.ps
483 string const message = file_exists ?
484 string() : string("bb = 0 0 200 100, draft, type=eps");
485 // if !message.empty() than there was no existing file
486 // "filename(.(e)ps)" found. In this case LaTeX
487 // draws only a rectangle with the above bb and the
488 // not found filename in it.
489 lyxerr[Debug::GRAPHICS]
490 << "\tMessage = \"" << message << '\"' << endl;
492 // These variables collect all the latex code that should be before and
493 // after the actual includegraphics command.
496 // Do we want subcaptions?
497 if (params().subcaption) {
498 before += "\\subfigure[" + params().subcaptionText + "]{";
501 // We never use the starred form, we use the "clip" option instead.
502 before += "\\includegraphics";
504 // Write the options if there are any.
505 string const opts = createLatexOptions();
506 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
508 if (!opts.empty() && !message.empty())
509 before += ("[%\n" + opts + ',' + message + ']');
510 else if (!opts.empty() || !message.empty())
511 before += ("[%\n" + opts + message + ']');
513 lyxerr[Debug::GRAPHICS]
514 << "\tBefore = " << before
515 << "\n\tafter = " << after << endl;
518 // "nice" means that the buffer is exported to LaTeX format but not
519 // run through the LaTeX compiler.
520 if (runparams.nice) {
521 os << before <<'{' << relative_file << '}' << after;
525 // Make the filename relative to the lyx file
526 // and remove the extension so the LaTeX will use whatever is
527 // appropriate (when there are several versions in different formats)
528 string const latex_str = message.empty() ?
529 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
530 (before + '{' + relative_file + " not found!}" + after);
533 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
534 << latex_str << endl;
535 // Return how many newlines we issued.
536 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
540 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
542 // No graphics in ascii output. Possible to use gifscii to convert
543 // images to ascii approximation.
544 // 1. Convert file to ascii using gifscii
545 // 2. Read ascii output file and add it to the output stream.
546 // at least we send the filename
547 os << '<' << bformat(_("Graphics file: %1$s"),
548 params().filename.absFilename()) << ">\n";
553 int InsetGraphics::linuxdoc(Buffer const * buf, ostream & os) const
555 string const file_name = buf->niceFile ?
556 params().filename.relFilename(buf->filePath()):
557 params().filename.absFilename();
559 os << "<eps file=\"" << file_name << "\">\n";
560 os << "<img src=\"" << file_name << "\">";
565 // For explanation on inserting graphics into DocBook checkout:
566 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
567 // See also the docbook guide at http://www.docbook.org/
568 int InsetGraphics::docbook(Buffer const *, ostream & os,
569 bool /*mixcont*/) const
571 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
572 // need to switch to MediaObject. However, for now this is sufficient and
574 os << "<graphic fileref=\"&" << graphic_label << ";\">";
579 void InsetGraphics::validate(LaTeXFeatures & features) const
581 // If we have no image, we should not require anything.
582 if (params().filename.empty())
585 features.includeFile(graphic_label,
586 RemoveExtension(params().filename.absFilename()));
588 features.require("graphicx");
590 if (params().subcaption)
591 features.require("subfigure");
595 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
597 // If nothing is changed, just return and say so.
598 if (params() == p && !p.filename.empty())
601 // Copy the new parameters.
604 // Update the display using the new parameters.
605 graphic_->update(params().as_grfxParams());
607 // We have changed data, report it.
612 InsetGraphicsParams const & InsetGraphics::params() const
618 string const InsetGraphicsMailer::name_("graphics");
620 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
625 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
627 return params2string(inset_.params(), buffer);
631 void InsetGraphicsMailer::string2params(string const & in,
632 Buffer const & buffer,
633 InsetGraphicsParams & params)
635 params = InsetGraphicsParams();
640 istringstream data(STRCONV(in));
646 string const token = lex.getString();
653 inset.readInsetGraphics(lex, buffer.filePath());
654 params = inset.params();
660 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
661 Buffer const & buffer)
664 data << name_ << ' ';
665 params.Write(data, buffer.filePath());
666 data << "\\end_inset\n";
667 return STRCONV(data.str());