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/LAssert.h"
78 #include "support/filetools.h"
79 #include "support/lyxalgo.h" // lyx::count
80 #include "support/lyxlib.h" // float_equal
81 #include "support/os.h"
82 #include "support/systemcall.h"
83 #include "support/tostr.h"
85 #include <boost/bind.hpp>
86 #include <boost/tuple/tuple.hpp>
88 #include <algorithm> // For the std::max
92 namespace support = lyx::support;
93 using namespace lyx::support;
102 ///////////////////////////////////////////////////////////////////////////
103 int const VersionNumber = 1;
104 ///////////////////////////////////////////////////////////////////////////
106 // This function is a utility function
107 // ... that should be with ChangeExtension ...
109 string const RemoveExtension(string const & filename)
111 return ChangeExtension(filename, string());
115 string const uniqueID()
117 static unsigned int seed = 1000;
118 return "graph" + tostr(++seed);
122 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
124 // Are we using latex or pdflatex).
125 if (runparams.flavor == LatexRunParams::PDFLATEX) {
126 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
127 if (contains(suffix, "ps") || suffix == "pdf")
129 if (suffix == "jpg") // pdflatex can use jpeg
131 return "png"; // and also png
133 // If it's postscript, we always do eps.
134 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
135 if (suffix != "ps") // any other than ps
136 return "eps"; // is changed to eps
137 return suffix; // let ps untouched
143 InsetGraphics::InsetGraphics()
144 : graphic_label(uniqueID()),
145 graphic_(new GraphicRenderer)
147 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
151 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
153 boost::signals::trackable(),
154 graphic_label(uniqueID()),
155 graphic_(new GraphicRenderer(*ig.graphic_))
157 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
158 setParams(ig.params());
162 auto_ptr<InsetBase> InsetGraphics::clone() const
164 return auto_ptr<InsetBase>(new InsetGraphics(*this));
168 InsetGraphics::~InsetGraphics()
170 InsetGraphicsMailer(*this).hideDialog();
174 void InsetGraphics::statusChanged()
176 BufferView * bv = graphic_->view();
178 bv->updateInset(this);
182 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
184 switch (cmd.action) {
185 case LFUN_INSET_MODIFY: {
186 Buffer const & buffer = *cmd.view()->buffer();
187 InsetGraphicsParams p;
188 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
189 if (!p.filename.empty()) {
191 cmd.view()->updateInset(this);
196 case LFUN_INSET_DIALOG_UPDATE:
197 InsetGraphicsMailer(*this).updateDialog(cmd.view());
200 case LFUN_INSET_EDIT:
201 case LFUN_MOUSE_RELEASE:
202 InsetGraphicsMailer(*this).showDialog(cmd.view());
206 return InsetOld::localDispatch(cmd);
211 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
213 graphic_->metrics(mi, dim);
218 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
220 graphic_->draw(pi, x, y);
224 InsetOld::EDITABLE InsetGraphics::editable() const
230 void InsetGraphics::write(Buffer const & buf, ostream & os) const
233 params().Write(os, buf.filePath());
237 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
239 string const token = lex.getString();
241 if (token == "Graphics")
242 readInsetGraphics(lex, buf.filePath());
244 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
246 graphic_->update(params().as_grfxParams());
250 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
252 bool finished = false;
254 while (lex.isOK() && !finished) {
257 string const token = lex.getString();
258 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
263 } else if (token == "\\end_inset") {
265 } else if (token == "FormatVersion") {
267 int version = lex.getInteger();
268 if (version > VersionNumber)
270 << "This document was created with a newer Graphics widget"
271 ", You should use a newer version of LyX to read this"
274 // TODO: Possibly open up a dialog?
277 if (!params_.Read(lex, token, bufpath))
278 lyxerr << "Unknown token, " << token << ", skipping."
285 string const InsetGraphics::createLatexOptions() const
287 // Calculate the options part of the command, we must do it to a string
288 // stream since we might have a trailing comma that we would like to remove
289 // before writing it to the output stream.
290 ostringstream options;
291 if (!params().bb.empty())
292 options << " bb=" << rtrim(params().bb) << ",\n";
294 options << " draft,\n";
296 options << " clip,\n";
297 if (!float_equal(params().scale, 0.0, 0.05)) {
298 if (!float_equal(params().scale, 100.0, 0.05))
299 options << " scale=" << params().scale / 100.0
302 if (!params().width.zero())
303 options << " width=" << params().width.asLatexString() << ",\n";
304 if (!params().height.zero())
305 options << " height=" << params().height.asLatexString() << ",\n";
306 if (params().keepAspectRatio)
307 options << " keepaspectratio,\n";
310 // Make sure rotation angle is not very close to zero;
311 // a float can be effectively zero but not exactly zero.
312 if (!float_equal(params().rotateAngle, 0, 0.001)) {
313 options << " angle=" << params().rotateAngle << ",\n";
314 if (!params().rotateOrigin.empty()) {
315 options << " origin=" << params().rotateOrigin[0];
316 if (contains(params().rotateOrigin,"Top"))
318 else if (contains(params().rotateOrigin,"Bottom"))
320 else if (contains(params().rotateOrigin,"Baseline"))
326 if (!params().special.empty())
327 options << params().special << ",\n";
329 string opts = STRCONV(options.str());
331 return opts.substr(0, opts.size() - 2);
345 std::pair<CopyStatus, string> const
346 copyToDirIfNeeded(string const & file_in, string const & dir)
348 using support::rtrim;
350 support::Assert(AbsolutePath(file_in));
352 string const only_path = support::OnlyPath(file_in);
353 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
354 return std::make_pair(IDENTICAL_PATHS, file_in);
357 if (support::zippedFile(file_in)) {
358 string const ext = GetExtension(file_in);
359 string const unzipped = support::unzippedFileName(file_in);
360 mangled = FileName(unzipped).mangledFilename();
361 mangled += "." + ext;
363 mangled = FileName(file_in).mangledFilename();
365 string const file_out = support::MakeAbsPath(mangled, dir);
367 unsigned long const checksum_in = support::sum(file_in);
368 unsigned long const checksum_out = support::sum(file_out);
370 if (checksum_in == checksum_out)
372 return std::make_pair(IDENTICAL_CONTENTS, file_out);
374 bool const success = support::copy(file_in, file_out);
376 lyxerr[Debug::GRAPHICS]
377 << support::bformat(_("Could not copy the file\n%1$s\n"
378 "into the temporary directory."),
383 CopyStatus status = success ? SUCCESS : FAILURE;
384 return std::make_pair(status, file_out);
388 string const stripExtensionIfPossible(string const & file, string const & to)
390 // No conversion is needed. LaTeX can handle the graphic file as is.
391 // This is true even if the orig_file is compressed.
392 if (formats.getFormat(to)->extension() == GetExtension(file))
393 return RemoveExtension(file);
400 string const InsetGraphics::prepareFile(Buffer const & buf,
401 LatexRunParams const & runparams) const
403 string orig_file = params().filename.absFilename();
404 string const rel_file = params().filename.relFilename(buf.filePath());
406 // LaTeX can cope if the graphics file doesn't exist, so just return the
408 if (!IsFileReadable(orig_file)) {
409 lyxerr[Debug::GRAPHICS]
410 << "InsetGraphics::prepareFile\n"
411 << "No file '" << orig_file << "' can be found!" << endl;
415 // If the file is compressed and we have specified that it
416 // should not be uncompressed, then just return its name and
417 // let LaTeX do the rest!
418 bool const zipped = params().filename.isZipped();
420 if (zipped && params().noUnzip) {
421 lyxerr[Debug::GRAPHICS]
422 << "\tpass zipped file to LaTeX but with full path.\n";
423 // LaTeX needs an absolute path, otherwise the
424 // coresponding *.eps.bb file isn't found
428 // temp_file will contain the file for LaTeX to act on if, for example,
429 // we move it to a temp dir or uncompress it.
430 string temp_file = orig_file;
434 boost::tie(status, temp_file) =
435 copyToDirIfNeeded(orig_file, buf.tmppath);
437 if (status == FAILURE)
440 orig_file = unzippedFileName(temp_file);
441 if (!IsFileReadable(orig_file)) {
442 unzipFile(temp_file);
443 lyxerr[Debug::GRAPHICS]
444 << "\tunzipped to " << orig_file << endl;
448 string const from = getExtFromContents(orig_file);
449 string const to = findTargetFormat(from, runparams);
450 lyxerr[Debug::GRAPHICS]
451 << "\t we have: from " << from << " to " << to << '\n';
453 if (from == to && !lyxrc.use_tempdir)
454 return stripExtensionIfPossible(orig_file, to);
456 // We're going to be running the exported buffer through the LaTeX
457 // compiler, so must ensure that LaTeX can cope with the graphics
460 lyxerr[Debug::GRAPHICS]
461 << "\tthe orig file is: " << orig_file << endl;
463 bool conversion_needed = true;
464 if (lyxrc.use_tempdir) {
466 boost::tie(status, temp_file) =
467 copyToDirIfNeeded(orig_file, buf.tmppath);
469 if (status == FAILURE)
471 else if (status == IDENTICAL_CONTENTS)
472 conversion_needed = false;
476 return stripExtensionIfPossible(temp_file, to);
478 string const to_file_base = RemoveExtension(temp_file);
479 string const to_file = ChangeExtension(to_file_base, to);
481 // Do we need to perform the conversion?
482 // Yes if to_file does not exist or if temp_file is newer than to_file
483 if (!conversion_needed ||
484 support::compare_timestamps(temp_file, to_file) < 0) {
485 lyxerr[Debug::GRAPHICS]
486 << bformat(_("No conversion of %1$s is needed after all"),
492 lyxerr[Debug::GRAPHICS]
493 << "\tThe original file is " << orig_file << "\n"
494 << "\tA copy has been made and convert is to be called with:\n"
495 << "\tfile to convert = " << temp_file << '\n'
496 << "\tto_file_base = " << to_file_base << '\n'
497 << "\t from " << from << " to " << to << '\n';
499 // if no special converter defined, than we take the default one
500 // from ImageMagic: convert from:inname.from to:outname.to
501 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
502 string const command =
503 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
504 ' ' + from + ':' + temp_file + ' ' +
505 to + ':' + to_file_base + '.' + to;
506 lyxerr[Debug::GRAPHICS]
507 << "No converter defined! I use convertDefault.sh:\n\t"
510 one.startscript(Systemcall::Wait, command);
511 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
512 string str = bformat(_("No information for converting %1$s "
513 "format files to %2$s.\n"
514 "Try defining a convertor in the preferences."), from, to);
515 Alert::error(_("Could not convert image"), str);
523 int InsetGraphics::latex(Buffer const & buf, ostream & os,
524 LatexRunParams const & runparams) const
526 // If there is no file specified or not existing,
527 // just output a message about it in the latex output.
528 lyxerr[Debug::GRAPHICS]
529 << "insetgraphics::latex: Filename = "
530 << params().filename.absFilename() << endl;
532 string const relative_file =
533 params().filename.relFilename(buf.filePath());
535 // A missing (e)ps-extension is no problem for LaTeX, so
536 // we have to test three different cases
537 #warning uh, but can our cache handle it ? no.
538 string const file_ = params().filename.absFilename();
539 bool const file_exists =
541 (IsFileReadable(file_) || // original
542 IsFileReadable(file_ + ".eps") || // original.eps
543 IsFileReadable(file_ + ".ps")); // original.ps
544 string const message = file_exists ?
545 string() : string("bb = 0 0 200 100, draft, type=eps");
546 // if !message.empty() than there was no existing file
547 // "filename(.(e)ps)" found. In this case LaTeX
548 // draws only a rectangle with the above bb and the
549 // not found filename in it.
550 lyxerr[Debug::GRAPHICS]
551 << "\tMessage = \"" << message << '\"' << endl;
553 // These variables collect all the latex code that should be before and
554 // after the actual includegraphics command.
557 // Do we want subcaptions?
558 if (params().subcaption) {
559 before += "\\subfigure[" + params().subcaptionText + "]{";
562 // We never use the starred form, we use the "clip" option instead.
563 before += "\\includegraphics";
565 // Write the options if there are any.
566 string const opts = createLatexOptions();
567 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
569 if (!opts.empty() && !message.empty())
570 before += ("[%\n" + opts + ',' + message + ']');
571 else if (!opts.empty() || !message.empty())
572 before += ("[%\n" + opts + message + ']');
574 lyxerr[Debug::GRAPHICS]
575 << "\tBefore = " << before
576 << "\n\tafter = " << after << endl;
579 // "nice" means that the buffer is exported to LaTeX format but not
580 // run through the LaTeX compiler.
581 if (runparams.nice) {
582 os << before <<'{' << relative_file << '}' << after;
586 // Make the filename relative to the lyx file
587 // and remove the extension so the LaTeX will use whatever is
588 // appropriate (when there are several versions in different formats)
589 string const latex_str = message.empty() ?
590 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
591 (before + '{' + relative_file + " not found!}" + after);
594 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
595 << latex_str << endl;
596 // Return how many newlines we issued.
597 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
601 int InsetGraphics::ascii(Buffer const &, ostream & os, int) const
603 // No graphics in ascii output. Possible to use gifscii to convert
604 // images to ascii approximation.
605 // 1. Convert file to ascii using gifscii
606 // 2. Read ascii output file and add it to the output stream.
607 // at least we send the filename
608 os << '<' << bformat(_("Graphics file: %1$s"),
609 params().filename.absFilename()) << ">\n";
614 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os) const
616 string const file_name = buf.niceFile ?
617 params().filename.relFilename(buf.filePath()):
618 params().filename.absFilename();
620 os << "<eps file=\"" << file_name << "\">\n";
621 os << "<img src=\"" << file_name << "\">";
626 // For explanation on inserting graphics into DocBook checkout:
627 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
628 // See also the docbook guide at http://www.docbook.org/
629 int InsetGraphics::docbook(Buffer const &, ostream & os,
630 bool /*mixcont*/) const
632 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
633 // need to switch to MediaObject. However, for now this is sufficient and
635 os << "<graphic fileref=\"&" << graphic_label << ";\">";
640 void InsetGraphics::validate(LaTeXFeatures & features) const
642 // If we have no image, we should not require anything.
643 if (params().filename.empty())
646 features.includeFile(graphic_label,
647 RemoveExtension(params().filename.absFilename()));
649 features.require("graphicx");
651 if (params().subcaption)
652 features.require("subfigure");
656 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
658 // If nothing is changed, just return and say so.
659 if (params() == p && !p.filename.empty())
662 // Copy the new parameters.
665 // Update the display using the new parameters.
666 graphic_->update(params().as_grfxParams());
668 // We have changed data, report it.
673 InsetGraphicsParams const & InsetGraphics::params() const
679 string const InsetGraphicsMailer::name_("graphics");
681 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
686 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
688 return params2string(inset_.params(), buffer);
692 void InsetGraphicsMailer::string2params(string const & in,
693 Buffer const & buffer,
694 InsetGraphicsParams & params)
696 params = InsetGraphicsParams();
701 istringstream data(STRCONV(in));
707 string const token = lex.getString();
714 inset.readInsetGraphics(lex, buffer.filePath());
715 params = inset.params();
721 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
722 Buffer const & buffer)
725 data << name_ << ' ';
726 params.Write(data, buffer.filePath());
727 data << "\\end_inset\n";
728 return STRCONV(data.str());