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/render_graphic.h"
59 #include "BufferView.h"
60 #include "converter.h"
62 #include "dispatchresult.h"
64 #include "funcrequest.h"
66 #include "LaTeXFeatures.h"
70 #include "metricsinfo.h"
71 #include "outputparams.h"
73 #include "frontends/Alert.h"
74 #include "frontends/LyXView.h"
76 #include "support/filetools.h"
77 #include "support/lyxalgo.h" // lyx::count
78 #include "support/lyxlib.h" // float_equal
79 #include "support/os.h"
80 #include "support/systemcall.h"
81 #include "support/tostr.h"
83 #include <boost/bind.hpp>
84 #include <boost/tuple/tuple.hpp>
86 #include "support/std_sstream.h"
88 namespace support = lyx::support;
89 using lyx::support::AbsolutePath;
90 using lyx::support::bformat;
91 using lyx::support::ChangeExtension;
92 using lyx::support::contains;
93 using lyx::support::FileName;
94 using lyx::support::float_equal;
95 using lyx::support::GetExtension;
96 using lyx::support::getExtFromContents;
97 using lyx::support::IsFileReadable;
98 using lyx::support::LibFileSearch;
99 using lyx::support::rtrim;
100 using lyx::support::Systemcall;
101 using lyx::support::unzipFile;
102 using lyx::support::unzippedFileName;
104 namespace os = lyx::support::os;
109 using std::istringstream;
111 using std::ostringstream;
116 ///////////////////////////////////////////////////////////////////////////
117 int const VersionNumber = 1;
118 ///////////////////////////////////////////////////////////////////////////
120 // This function is a utility function
121 // ... that should be with ChangeExtension ...
123 string const RemoveExtension(string const & filename)
125 return ChangeExtension(filename, string());
129 string const uniqueID()
131 static unsigned int seed = 1000;
132 return "graph" + tostr(++seed);
136 string findTargetFormat(string const & suffix, OutputParams const & runparams)
138 // Are we using latex or pdflatex).
139 if (runparams.flavor == OutputParams::PDFLATEX) {
140 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
141 if (contains(suffix, "ps") || suffix == "pdf")
143 if (suffix == "jpg") // pdflatex can use jpeg
145 return "png"; // and also png
147 // If it's postscript, we always do eps.
148 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
149 if (suffix != "ps") // any other than ps
150 return "eps"; // is changed to eps
151 return suffix; // let ps untouched
157 InsetGraphics::InsetGraphics()
158 : graphic_label(uniqueID()),
159 graphic_(new RenderGraphic)
161 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
165 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
167 boost::signals::trackable(),
168 graphic_label(uniqueID()),
169 graphic_(new RenderGraphic(*ig.graphic_))
171 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
172 setParams(ig.params());
176 auto_ptr<InsetBase> InsetGraphics::clone() const
178 return auto_ptr<InsetBase>(new InsetGraphics(*this));
182 InsetGraphics::~InsetGraphics()
184 InsetGraphicsMailer(*this).hideDialog();
188 void InsetGraphics::statusChanged() const
190 LyX::cref().updateInset(this);
195 InsetGraphics::priv_dispatch(FuncRequest const & cmd, idx_type &, pos_type &)
197 switch (cmd.action) {
198 case LFUN_INSET_MODIFY: {
199 Buffer const & buffer = *cmd.view()->buffer();
200 InsetGraphicsParams p;
201 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
202 if (!p.filename.empty()) {
204 cmd.view()->update();
206 return DispatchResult(true, true);
209 case LFUN_INSET_DIALOG_UPDATE:
210 InsetGraphicsMailer(*this).updateDialog(cmd.view());
211 return DispatchResult(true, true);
213 case LFUN_MOUSE_RELEASE:
214 InsetGraphicsMailer(*this).showDialog(cmd.view());
215 return DispatchResult(true, true);
218 return DispatchResult(false);
223 void InsetGraphics::edit(BufferView * bv, bool)
225 InsetGraphicsMailer(*this).showDialog(bv);
229 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
231 graphic_->metrics(mi, dim);
236 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
238 graphic_->draw(pi, x, y);
242 InsetOld::EDITABLE InsetGraphics::editable() const
248 void InsetGraphics::write(Buffer const & buf, ostream & os) const
251 params().Write(os, buf.filePath());
255 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
257 string const token = lex.getString();
259 if (token == "Graphics")
260 readInsetGraphics(lex, buf.filePath());
262 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
264 graphic_->update(params().as_grfxParams());
268 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
270 bool finished = false;
272 while (lex.isOK() && !finished) {
275 string const token = lex.getString();
276 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
281 } else if (token == "\\end_inset") {
283 } else if (token == "FormatVersion") {
285 int version = lex.getInteger();
286 if (version > VersionNumber)
288 << "This document was created with a newer Graphics widget"
289 ", You should use a newer version of LyX to read this"
292 // TODO: Possibly open up a dialog?
295 if (!params_.Read(lex, token, bufpath))
296 lyxerr << "Unknown token, " << token << ", skipping."
303 string const InsetGraphics::createLatexOptions() const
305 // Calculate the options part of the command, we must do it to a string
306 // stream since we might have a trailing comma that we would like to remove
307 // before writing it to the output stream.
308 ostringstream options;
309 if (!params().bb.empty())
310 options << " bb=" << rtrim(params().bb) << ",\n";
312 options << " draft,\n";
314 options << " clip,\n";
315 if (!float_equal(params().scale, 0.0, 0.05)) {
316 if (!float_equal(params().scale, 100.0, 0.05))
317 options << " scale=" << params().scale / 100.0
320 if (!params().width.zero())
321 options << " width=" << params().width.asLatexString() << ",\n";
322 if (!params().height.zero())
323 options << " height=" << params().height.asLatexString() << ",\n";
324 if (params().keepAspectRatio)
325 options << " keepaspectratio,\n";
328 // Make sure rotation angle is not very close to zero;
329 // a float can be effectively zero but not exactly zero.
330 if (!float_equal(params().rotateAngle, 0, 0.001)) {
331 options << " angle=" << params().rotateAngle << ",\n";
332 if (!params().rotateOrigin.empty()) {
333 options << " origin=" << params().rotateOrigin[0];
334 if (contains(params().rotateOrigin,"Top"))
336 else if (contains(params().rotateOrigin,"Bottom"))
338 else if (contains(params().rotateOrigin,"Baseline"))
344 if (!params().special.empty())
345 options << params().special << ",\n";
347 string opts = options.str();
349 return opts.substr(0, opts.size() - 2);
363 std::pair<CopyStatus, string> const
364 copyToDirIfNeeded(string const & file_in, string const & dir)
366 using support::rtrim;
368 BOOST_ASSERT(AbsolutePath(file_in));
370 string const only_path = support::OnlyPath(file_in);
371 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
372 return std::make_pair(IDENTICAL_PATHS, file_in);
375 if (support::zippedFile(file_in)) {
376 string const ext = GetExtension(file_in);
377 string const unzipped = support::unzippedFileName(file_in);
378 mangled = FileName(unzipped).mangledFilename();
379 mangled += "." + ext;
381 mangled = FileName(file_in).mangledFilename();
383 string const file_out = support::MakeAbsPath(mangled, dir);
385 unsigned long const checksum_in = support::sum(file_in);
386 unsigned long const checksum_out = support::sum(file_out);
388 if (checksum_in == checksum_out)
390 return std::make_pair(IDENTICAL_CONTENTS, file_out);
392 bool const success = support::copy(file_in, file_out);
394 lyxerr[Debug::GRAPHICS]
395 << support::bformat(_("Could not copy the file\n%1$s\n"
396 "into the temporary directory."),
401 CopyStatus status = success ? SUCCESS : FAILURE;
402 return std::make_pair(status, file_out);
406 string const stripExtensionIfPossible(string const & file, string const & to)
408 // No conversion is needed. LaTeX can handle the graphic file as is.
409 // This is true even if the orig_file is compressed.
410 if (formats.getFormat(to)->extension() == GetExtension(file))
411 return RemoveExtension(file);
418 string const InsetGraphics::prepareFile(Buffer const & buf,
419 OutputParams const & runparams) const
421 string orig_file = params().filename.absFilename();
422 string const rel_file = params().filename.relFilename(buf.filePath());
424 // LaTeX can cope if the graphics file doesn't exist, so just return the
426 if (!IsFileReadable(orig_file)) {
427 lyxerr[Debug::GRAPHICS]
428 << "InsetGraphics::prepareFile\n"
429 << "No file '" << orig_file << "' can be found!" << endl;
433 // If the file is compressed and we have specified that it
434 // should not be uncompressed, then just return its name and
435 // let LaTeX do the rest!
436 bool const zipped = params().filename.isZipped();
438 if (zipped && params().noUnzip) {
439 lyxerr[Debug::GRAPHICS]
440 << "\tpass zipped file to LaTeX but with full path.\n";
441 // LaTeX needs an absolute path, otherwise the
442 // coresponding *.eps.bb file isn't found
446 // temp_file will contain the file for LaTeX to act on if, for example,
447 // we move it to a temp dir or uncompress it.
448 string temp_file = orig_file;
452 boost::tie(status, temp_file) =
453 copyToDirIfNeeded(orig_file, buf.temppath());
455 if (status == FAILURE)
458 orig_file = unzippedFileName(temp_file);
459 if (!IsFileReadable(orig_file)) {
460 unzipFile(temp_file);
461 lyxerr[Debug::GRAPHICS]
462 << "\tunzipped to " << orig_file << endl;
466 string const from = getExtFromContents(orig_file);
467 string const to = findTargetFormat(from, runparams);
468 lyxerr[Debug::GRAPHICS]
469 << "\t we have: from " << from << " to " << to << '\n';
471 if (from == to && !lyxrc.use_tempdir)
472 return stripExtensionIfPossible(orig_file, to);
474 // We're going to be running the exported buffer through the LaTeX
475 // compiler, so must ensure that LaTeX can cope with the graphics
478 lyxerr[Debug::GRAPHICS]
479 << "\tthe orig file is: " << orig_file << endl;
481 bool conversion_needed = true;
482 if (lyxrc.use_tempdir) {
484 boost::tie(status, temp_file) =
485 copyToDirIfNeeded(orig_file, buf.temppath());
487 if (status == FAILURE)
489 else if (status == IDENTICAL_CONTENTS)
490 conversion_needed = false;
494 return stripExtensionIfPossible(temp_file, to);
496 string const to_file_base = RemoveExtension(temp_file);
497 string const to_file = ChangeExtension(to_file_base, to);
499 // Do we need to perform the conversion?
500 // Yes if to_file does not exist or if temp_file is newer than to_file
501 if (!conversion_needed ||
502 support::compare_timestamps(temp_file, to_file) < 0) {
503 lyxerr[Debug::GRAPHICS]
504 << bformat(_("No conversion of %1$s is needed after all"),
510 lyxerr[Debug::GRAPHICS]
511 << "\tThe original file is " << orig_file << "\n"
512 << "\tA copy has been made and convert is to be called with:\n"
513 << "\tfile to convert = " << temp_file << '\n'
514 << "\tto_file_base = " << to_file_base << '\n'
515 << "\t from " << from << " to " << to << '\n';
517 // if no special converter defined, than we take the default one
518 // from ImageMagic: convert from:inname.from to:outname.to
519 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
520 string const command =
521 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
522 ' ' + from + ':' + temp_file + ' ' +
523 to + ':' + to_file_base + '.' + to;
524 lyxerr[Debug::GRAPHICS]
525 << "No converter defined! I use convertDefault.sh:\n\t"
528 one.startscript(Systemcall::Wait, command);
529 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
530 string str = bformat(_("No information for converting %1$s "
531 "format files to %2$s.\n"
532 "Try defining a convertor in the preferences."), from, to);
533 Alert::error(_("Could not convert image"), str);
541 int InsetGraphics::latex(Buffer const & buf, ostream & os,
542 OutputParams const & runparams) const
544 // If there is no file specified or not existing,
545 // just output a message about it in the latex output.
546 lyxerr[Debug::GRAPHICS]
547 << "insetgraphics::latex: Filename = "
548 << params().filename.absFilename() << endl;
550 string const relative_file =
551 params().filename.relFilename(buf.filePath());
553 // A missing (e)ps-extension is no problem for LaTeX, so
554 // we have to test three different cases
555 #warning uh, but can our cache handle it ? no.
556 string const file_ = params().filename.absFilename();
557 bool const file_exists =
559 (IsFileReadable(file_) || // original
560 IsFileReadable(file_ + ".eps") || // original.eps
561 IsFileReadable(file_ + ".ps")); // original.ps
562 string const message = file_exists ?
563 string() : string("bb = 0 0 200 100, draft, type=eps");
564 // if !message.empty() than there was no existing file
565 // "filename(.(e)ps)" found. In this case LaTeX
566 // draws only a rectangle with the above bb and the
567 // not found filename in it.
568 lyxerr[Debug::GRAPHICS]
569 << "\tMessage = \"" << message << '\"' << endl;
571 // These variables collect all the latex code that should be before and
572 // after the actual includegraphics command.
575 // Do we want subcaptions?
576 if (params().subcaption) {
577 before += "\\subfigure[" + params().subcaptionText + "]{";
580 // We never use the starred form, we use the "clip" option instead.
581 before += "\\includegraphics";
583 // Write the options if there are any.
584 string const opts = createLatexOptions();
585 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
587 if (!opts.empty() && !message.empty())
588 before += ("[%\n" + opts + ',' + message + ']');
589 else if (!opts.empty() || !message.empty())
590 before += ("[%\n" + opts + message + ']');
592 lyxerr[Debug::GRAPHICS]
593 << "\tBefore = " << before
594 << "\n\tafter = " << after << endl;
597 // "nice" means that the buffer is exported to LaTeX format but not
598 // run through the LaTeX compiler.
599 if (runparams.nice) {
600 os << before <<'{' << relative_file << '}' << after;
604 // Make the filename relative to the lyx file
605 // and remove the extension so the LaTeX will use whatever is
606 // appropriate (when there are several versions in different formats)
607 string const latex_str = message.empty() ?
608 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
609 (before + '{' + relative_file + " not found!}" + after);
612 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
613 << latex_str << endl;
614 // Return how many newlines we issued.
615 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
619 int InsetGraphics::plaintext(Buffer const &, ostream & os,
620 OutputParams const &) const
622 // No graphics in ascii output. Possible to use gifscii to convert
623 // images to ascii approximation.
624 // 1. Convert file to ascii using gifscii
625 // 2. Read ascii output file and add it to the output stream.
626 // at least we send the filename
627 os << '<' << bformat(_("Graphics file: %1$s"),
628 params().filename.absFilename()) << ">\n";
633 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os,
634 OutputParams const &) const
636 string const file_name = buf.niceFile() ?
637 params().filename.relFilename(buf.filePath()):
638 params().filename.absFilename();
640 os << "<eps file=\"" << file_name << "\">\n";
641 os << "<img src=\"" << file_name << "\">";
646 // For explanation on inserting graphics into DocBook checkout:
647 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
648 // See also the docbook guide at http://www.docbook.org/
649 int InsetGraphics::docbook(Buffer const &, ostream & os,
650 OutputParams const &) const
652 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
653 // need to switch to MediaObject. However, for now this is sufficient and
655 os << "<graphic fileref=\"&" << graphic_label << ";\">";
660 void InsetGraphics::validate(LaTeXFeatures & features) const
662 // If we have no image, we should not require anything.
663 if (params().filename.empty())
666 features.includeFile(graphic_label,
667 RemoveExtension(params().filename.absFilename()));
669 features.require("graphicx");
671 if (params().subcaption)
672 features.require("subfigure");
676 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
678 // If nothing is changed, just return and say so.
679 if (params() == p && !p.filename.empty())
682 // Copy the new parameters.
685 // Update the display using the new parameters.
686 graphic_->update(params().as_grfxParams());
688 // We have changed data, report it.
693 InsetGraphicsParams const & InsetGraphics::params() const
699 string const InsetGraphicsMailer::name_("graphics");
701 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
706 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
708 return params2string(inset_.params(), buffer);
712 void InsetGraphicsMailer::string2params(string const & in,
713 Buffer const & buffer,
714 InsetGraphicsParams & params)
716 params = InsetGraphicsParams();
721 istringstream data(in);
727 string const token = lex.getString();
734 inset.readInsetGraphics(lex, buffer.filePath());
735 params = inset.params();
741 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
742 Buffer const & buffer)
745 data << name_ << ' ';
746 params.Write(data, buffer.filePath());
747 data << "\\end_inset\n";