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"
71 #include "paragraph_funcs.h"
74 #include "frontends/Alert.h"
75 #include "frontends/Dialogs.h"
77 #include "support/filetools.h"
78 #include "support/lyxalgo.h" // lyx::count
79 #include "support/lyxlib.h" // float_equal
80 #include "support/tostr.h"
81 #include "support/systemcall.h"
83 #include <boost/bind.hpp>
85 #include <algorithm> // For the std::max
89 using namespace lyx::support;
98 ///////////////////////////////////////////////////////////////////////////
99 int const VersionNumber = 1;
100 ///////////////////////////////////////////////////////////////////////////
102 // This function is a utility function
103 // ... that should be with ChangeExtension ...
105 string const RemoveExtension(string const & filename)
107 return ChangeExtension(filename, string());
111 string const uniqueID()
113 static unsigned int seed = 1000;
114 return "graph" + tostr(++seed);
118 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
120 // Are we using latex or pdflatex).
121 if (runparams.flavor == LatexRunParams::PDFLATEX) {
122 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
123 if (contains(suffix, "ps") || suffix == "pdf")
125 if (suffix == "jpg") // pdflatex can use jpeg
127 return "png"; // and also png
129 // If it's postscript, we always do eps.
130 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
131 if (suffix != "ps") // any other than ps
132 return "eps"; // is changed to eps
133 return suffix; // let ps untouched
139 InsetGraphics::InsetGraphics()
140 : graphic_label(uniqueID()),
141 graphic_(new GraphicRenderer)
143 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
147 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
149 boost::signals::trackable(),
150 graphic_label(uniqueID()),
151 graphic_(new GraphicRenderer(*ig.graphic_))
153 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
154 setParams(ig.params());
158 auto_ptr<InsetBase> InsetGraphics::clone() const
160 return auto_ptr<InsetBase>(new InsetGraphics(*this));
164 InsetGraphics::~InsetGraphics()
166 InsetGraphicsMailer(*this).hideDialog();
170 void InsetGraphics::statusChanged()
172 BufferView * bv = graphic_->view();
174 bv->updateInset(this);
178 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
180 switch (cmd.action) {
181 case LFUN_INSET_MODIFY: {
182 Buffer const & buffer = *cmd.view()->buffer();
183 InsetGraphicsParams p;
184 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
185 if (!p.filename.empty()) {
187 cmd.view()->updateInset(this);
192 case LFUN_INSET_DIALOG_UPDATE:
193 InsetGraphicsMailer(*this).updateDialog(cmd.view());
196 case LFUN_INSET_EDIT:
197 case LFUN_MOUSE_RELEASE:
198 InsetGraphicsMailer(*this).showDialog(cmd.view());
202 return InsetOld::localDispatch(cmd);
207 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
209 graphic_->metrics(mi, dim);
214 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
216 graphic_->draw(pi, x, y);
220 InsetOld::EDITABLE InsetGraphics::editable() const
226 void InsetGraphics::write(Buffer const & buf, ostream & os) const
229 params().Write(os, buf.filePath());
233 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
235 string const token = lex.getString();
237 if (token == "Graphics")
238 readInsetGraphics(lex, buf.filePath());
240 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
242 graphic_->update(params().as_grfxParams());
246 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
248 bool finished = false;
250 while (lex.isOK() && !finished) {
253 string const token = lex.getString();
254 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
259 } else if (token == "\\end_inset") {
261 } else if (token == "FormatVersion") {
263 int version = lex.getInteger();
264 if (version > VersionNumber)
266 << "This document was created with a newer Graphics widget"
267 ", You should use a newer version of LyX to read this"
270 // TODO: Possibly open up a dialog?
273 if (!params_.Read(lex, token, bufpath))
274 lyxerr << "Unknown token, " << token << ", skipping."
281 string const InsetGraphics::createLatexOptions() const
283 // Calculate the options part of the command, we must do it to a string
284 // stream since we might have a trailing comma that we would like to remove
285 // before writing it to the output stream.
286 ostringstream options;
287 if (!params().bb.empty())
288 options << " bb=" << rtrim(params().bb) << ",\n";
290 options << " draft,\n";
292 options << " clip,\n";
293 if (!float_equal(params().scale, 0.0, 0.05)) {
294 if (!float_equal(params().scale, 100.0, 0.05))
295 options << " scale=" << params().scale / 100.0
298 if (!params().width.zero())
299 options << " width=" << params().width.asLatexString() << ",\n";
300 if (!params().height.zero())
301 options << " height=" << params().height.asLatexString() << ",\n";
302 if (params().keepAspectRatio)
303 options << " keepaspectratio,\n";
306 // Make sure rotation angle is not very close to zero;
307 // a float can be effectively zero but not exactly zero.
308 if (!float_equal(params().rotateAngle, 0, 0.001)) {
309 options << " angle=" << params().rotateAngle << ",\n";
310 if (!params().rotateOrigin.empty()) {
311 options << " origin=" << params().rotateOrigin[0];
312 if (contains(params().rotateOrigin,"Top"))
314 else if (contains(params().rotateOrigin,"Bottom"))
316 else if (contains(params().rotateOrigin,"Baseline"))
322 if (!params().special.empty())
323 options << params().special << ",\n";
325 string opts = STRCONV(options.str());
327 return opts.substr(0, opts.size() - 2);
331 string const InsetGraphics::prepareFile(Buffer const & buf,
332 LatexRunParams const & runparams) const
334 // LaTeX can cope if the graphics file doesn't exist, so just return the
336 string orig_file = params().filename.absFilename();
337 string const rel_file = params().filename.relFilename(buf.filePath());
339 if (!IsFileReadable(orig_file)) {
340 lyxerr[Debug::GRAPHICS]
341 << "InsetGraphics::prepareFile\n"
342 << "No file '" << orig_file << "' can be found!" << endl;
346 bool const zipped = zippedFile(orig_file);
348 // If the file is compressed and we have specified that it
349 // should not be uncompressed, then just return its name and
350 // let LaTeX do the rest!
351 if (zipped && params().noUnzip) {
352 lyxerr[Debug::GRAPHICS]
353 << "\tpass zipped file to LaTeX but with full path.\n";
354 // LaTeX needs an absolute path, otherwise the
355 // coresponding *.eps.bb file isn't found
359 // temp_file will contain the file for LaTeX to act on if, for example,
360 // we move it to a temp dir or uncompress it.
361 string temp_file = orig_file;
364 // Uncompress the file if necessary.
365 // If it has been uncompressed in a previous call to
366 // prepareFile, do nothing.
367 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf.tmppath);
368 lyxerr[Debug::GRAPHICS]
369 << "\ttemp_file: " << temp_file << endl;
370 if (graphic_->hasFileChanged() || !IsFileReadable(temp_file)) {
371 bool const success = copy(orig_file, temp_file);
372 lyxerr[Debug::GRAPHICS]
373 << "\tCopying zipped file from "
374 << orig_file << " to " << temp_file
375 << (success ? " succeeded\n" : " failed\n");
377 lyxerr[Debug::GRAPHICS]
378 << "\tzipped file " << temp_file
379 << " exists! Maybe no tempdir ...\n";
380 orig_file = unzipFile(temp_file);
381 lyxerr[Debug::GRAPHICS]
382 << "\tunzipped to " << orig_file << endl;
385 string const from = getExtFromContents(orig_file);
386 string const to = findTargetFormat(from, runparams);
387 lyxerr[Debug::GRAPHICS]
388 << "\t we have: from " << from << " to " << to << '\n';
390 if (from == to && !lyxrc.use_tempdir) {
391 // No conversion is needed. LaTeX can handle the
392 // graphic file as is.
393 // This is true even if the orig_file is compressed.
394 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
395 return RemoveExtension(orig_file);
399 // We're going to be running the exported buffer through the LaTeX
400 // compiler, so must ensure that LaTeX can cope with the graphics
403 // Perform all these manipulations on a temporary file if possible.
404 // If we are not using a temp dir, then temp_file contains the
406 // to allow files with the same name in different dirs
407 // we manipulate the original file "any.dir/file.ext"
408 // to "any_dir_file.ext"! changing the dots in the
409 // dirname is important for the use of ChangeExtension
410 lyxerr[Debug::GRAPHICS]
411 << "\tthe orig file is: " << orig_file << endl;
413 if (lyxrc.use_tempdir) {
414 temp_file = copyFileToDir(buf.tmppath, orig_file);
415 if (temp_file.empty()) {
416 string str = bformat(_("Could not copy the file\n%1$s\n"
417 "into the temporary directory."),
419 Alert::error(_("Graphics display failed"), str);
424 // No conversion is needed. LaTeX can handle the
425 // graphic file as is.
426 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
427 return RemoveExtension(temp_file);
432 string const outfile_base = RemoveExtension(temp_file);
433 lyxerr[Debug::GRAPHICS]
434 << "\tThe original file is " << orig_file << "\n"
435 << "\tA copy has been made and convert is to be called with:\n"
436 << "\tfile to convert = " << temp_file << '\n'
437 << "\toutfile_base = " << outfile_base << '\n'
438 << "\t from " << from << " to " << to << '\n';
440 // if no special converter defined, than we take the default one
441 // from ImageMagic: convert from:inname.from to:outname.to
442 if (!converters.convert(&buf, temp_file, outfile_base, from, to)) {
443 string const command =
444 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
445 ' ' + from + ':' + temp_file + ' ' +
446 to + ':' + outfile_base + '.' + to;
447 lyxerr[Debug::GRAPHICS]
448 << "No converter defined! I use convertDefault.sh:\n\t"
451 one.startscript(Systemcall::Wait, command);
452 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
453 string str = bformat(_("No information for converting %1$s "
454 "format files to %2$s.\n"
455 "Try defining a convertor in the preferences."), from, to);
456 Alert::error(_("Could not convert image"), str);
460 return RemoveExtension(temp_file);
464 int InsetGraphics::latex(Buffer const & buf, ostream & os,
465 LatexRunParams const & runparams) const
467 // If there is no file specified or not existing,
468 // just output a message about it in the latex output.
469 lyxerr[Debug::GRAPHICS]
470 << "insetgraphics::latex: Filename = "
471 << params().filename.absFilename() << endl;
473 string const relative_file =
474 params().filename.relFilename(buf.filePath());
476 // A missing (e)ps-extension is no problem for LaTeX, so
477 // we have to test three different cases
478 #warning uh, but can our cache handle it ? no.
479 string const file_ = params().filename.absFilename();
480 bool const file_exists =
482 (IsFileReadable(file_) || // original
483 IsFileReadable(file_ + ".eps") || // original.eps
484 IsFileReadable(file_ + ".ps")); // original.ps
485 string const message = file_exists ?
486 string() : string("bb = 0 0 200 100, draft, type=eps");
487 // if !message.empty() than there was no existing file
488 // "filename(.(e)ps)" found. In this case LaTeX
489 // draws only a rectangle with the above bb and the
490 // not found filename in it.
491 lyxerr[Debug::GRAPHICS]
492 << "\tMessage = \"" << message << '\"' << endl;
494 // These variables collect all the latex code that should be before and
495 // after the actual includegraphics command.
498 // Do we want subcaptions?
499 if (params().subcaption) {
500 before += "\\subfigure[" + params().subcaptionText + "]{";
503 // We never use the starred form, we use the "clip" option instead.
504 before += "\\includegraphics";
506 // Write the options if there are any.
507 string const opts = createLatexOptions();
508 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
510 if (!opts.empty() && !message.empty())
511 before += ("[%\n" + opts + ',' + message + ']');
512 else if (!opts.empty() || !message.empty())
513 before += ("[%\n" + opts + message + ']');
515 lyxerr[Debug::GRAPHICS]
516 << "\tBefore = " << before
517 << "\n\tafter = " << after << endl;
520 // "nice" means that the buffer is exported to LaTeX format but not
521 // run through the LaTeX compiler.
522 if (runparams.nice) {
523 os << before <<'{' << relative_file << '}' << after;
527 // Make the filename relative to the lyx file
528 // and remove the extension so the LaTeX will use whatever is
529 // appropriate (when there are several versions in different formats)
530 string const latex_str = message.empty() ?
531 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
532 (before + '{' + relative_file + " not found!}" + after);
535 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
536 << latex_str << endl;
537 // Return how many newlines we issued.
538 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
542 int InsetGraphics::ascii(Buffer const &, ostream & os, int) const
544 // No graphics in ascii output. Possible to use gifscii to convert
545 // images to ascii approximation.
546 // 1. Convert file to ascii using gifscii
547 // 2. Read ascii output file and add it to the output stream.
548 // at least we send the filename
549 os << '<' << bformat(_("Graphics file: %1$s"),
550 params().filename.absFilename()) << ">\n";
555 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os) const
557 string const file_name = buf.niceFile ?
558 params().filename.relFilename(buf.filePath()):
559 params().filename.absFilename();
561 os << "<eps file=\"" << file_name << "\">\n";
562 os << "<img src=\"" << file_name << "\">";
567 // For explanation on inserting graphics into DocBook checkout:
568 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
569 // See also the docbook guide at http://www.docbook.org/
570 int InsetGraphics::docbook(Buffer const &, ostream & os,
571 bool /*mixcont*/) const
573 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
574 // need to switch to MediaObject. However, for now this is sufficient and
576 os << "<graphic fileref=\"&" << graphic_label << ";\">";
581 void InsetGraphics::validate(LaTeXFeatures & features) const
583 // If we have no image, we should not require anything.
584 if (params().filename.empty())
587 features.includeFile(graphic_label,
588 RemoveExtension(params().filename.absFilename()));
590 features.require("graphicx");
592 if (params().subcaption)
593 features.require("subfigure");
597 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
599 // If nothing is changed, just return and say so.
600 if (params() == p && !p.filename.empty())
603 // Copy the new parameters.
606 // Update the display using the new parameters.
607 graphic_->update(params().as_grfxParams());
609 // We have changed data, report it.
614 InsetGraphicsParams const & InsetGraphics::params() const
620 string const InsetGraphicsMailer::name_("graphics");
622 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
627 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
629 return params2string(inset_.params(), buffer);
633 void InsetGraphicsMailer::string2params(string const & in,
634 Buffer const & buffer,
635 InsetGraphicsParams & params)
637 params = InsetGraphicsParams();
642 istringstream data(STRCONV(in));
648 string const token = lex.getString();
655 inset.readInsetGraphics(lex, buffer.filePath());
656 params = inset.params();
662 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
663 Buffer const & buffer)
666 data << name_ << ' ';
667 params.Write(data, buffer.filePath());
668 data << "\\end_inset\n";
669 return STRCONV(data.str());