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"
63 #include "funcrequest.h"
65 #include "LaTeXFeatures.h"
66 #include "latexrunparams.h"
69 #include "metricsinfo.h"
71 #include "frontends/Alert.h"
72 #include "frontends/LyXView.h"
74 #include "support/filetools.h"
75 #include "support/lyxalgo.h" // lyx::count
76 #include "support/lyxlib.h" // float_equal
77 #include "support/os.h"
78 #include "support/systemcall.h"
79 #include "support/tostr.h"
81 #include <boost/bind.hpp>
82 #include <boost/tuple/tuple.hpp>
84 #include "support/std_sstream.h"
86 namespace support = lyx::support;
87 using lyx::support::AbsolutePath;
88 using lyx::support::bformat;
89 using lyx::support::ChangeExtension;
90 using lyx::support::contains;
91 using lyx::support::FileName;
92 using lyx::support::float_equal;
93 using lyx::support::GetExtension;
94 using lyx::support::getExtFromContents;
95 using lyx::support::IsFileReadable;
96 using lyx::support::LibFileSearch;
97 using lyx::support::rtrim;
98 using lyx::support::Systemcall;
99 using lyx::support::unzipFile;
100 using lyx::support::unzippedFileName;
102 namespace os = lyx::support::os;
107 using std::istringstream;
109 using std::ostringstream;
114 ///////////////////////////////////////////////////////////////////////////
115 int const VersionNumber = 1;
116 ///////////////////////////////////////////////////////////////////////////
118 // This function is a utility function
119 // ... that should be with ChangeExtension ...
121 string const RemoveExtension(string const & filename)
123 return ChangeExtension(filename, string());
127 string const uniqueID()
129 static unsigned int seed = 1000;
130 return "graph" + tostr(++seed);
134 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
136 // Are we using latex or pdflatex).
137 if (runparams.flavor == LatexRunParams::PDFLATEX) {
138 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
139 if (contains(suffix, "ps") || suffix == "pdf")
141 if (suffix == "jpg") // pdflatex can use jpeg
143 return "png"; // and also png
145 // If it's postscript, we always do eps.
146 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
147 if (suffix != "ps") // any other than ps
148 return "eps"; // is changed to eps
149 return suffix; // let ps untouched
155 InsetGraphics::InsetGraphics()
156 : graphic_label(uniqueID()),
157 graphic_(new RenderGraphic)
159 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
163 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
165 boost::signals::trackable(),
166 graphic_label(uniqueID()),
167 graphic_(new RenderGraphic(*ig.graphic_))
169 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
170 setParams(ig.params());
174 auto_ptr<InsetBase> InsetGraphics::clone() const
176 return auto_ptr<InsetBase>(new InsetGraphics(*this));
180 InsetGraphics::~InsetGraphics()
182 InsetGraphicsMailer(*this).hideDialog();
186 void InsetGraphics::cache(BufferView * view) const
189 view_ = view->owner()->view();
192 BufferView * InsetGraphics::view() const
194 return view_.lock().get();
198 void InsetGraphics::statusChanged() const
200 BufferView * bv = view();
202 bv->updateInset(this);
206 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
208 switch (cmd.action) {
209 case LFUN_INSET_MODIFY: {
210 Buffer const & buffer = *cmd.view()->buffer();
211 InsetGraphicsParams p;
212 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
213 if (!p.filename.empty()) {
215 cmd.view()->updateInset(this);
220 case LFUN_INSET_DIALOG_UPDATE:
221 InsetGraphicsMailer(*this).updateDialog(cmd.view());
224 case LFUN_INSET_EDIT:
225 case LFUN_MOUSE_RELEASE:
226 InsetGraphicsMailer(*this).showDialog(cmd.view());
235 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
237 graphic_->metrics(mi, dim);
242 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
245 graphic_->draw(pi, x, y);
249 InsetOld::EDITABLE InsetGraphics::editable() const
255 void InsetGraphics::write(Buffer const & buf, ostream & os) const
258 params().Write(os, buf.filePath());
262 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
264 string const token = lex.getString();
266 if (token == "Graphics")
267 readInsetGraphics(lex, buf.filePath());
269 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
271 graphic_->update(params().as_grfxParams());
275 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
277 bool finished = false;
279 while (lex.isOK() && !finished) {
282 string const token = lex.getString();
283 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
288 } else if (token == "\\end_inset") {
290 } else if (token == "FormatVersion") {
292 int version = lex.getInteger();
293 if (version > VersionNumber)
295 << "This document was created with a newer Graphics widget"
296 ", You should use a newer version of LyX to read this"
299 // TODO: Possibly open up a dialog?
302 if (!params_.Read(lex, token, bufpath))
303 lyxerr << "Unknown token, " << token << ", skipping."
310 string const InsetGraphics::createLatexOptions() const
312 // Calculate the options part of the command, we must do it to a string
313 // stream since we might have a trailing comma that we would like to remove
314 // before writing it to the output stream.
315 ostringstream options;
316 if (!params().bb.empty())
317 options << " bb=" << rtrim(params().bb) << ",\n";
319 options << " draft,\n";
321 options << " clip,\n";
322 if (!float_equal(params().scale, 0.0, 0.05)) {
323 if (!float_equal(params().scale, 100.0, 0.05))
324 options << " scale=" << params().scale / 100.0
327 if (!params().width.zero())
328 options << " width=" << params().width.asLatexString() << ",\n";
329 if (!params().height.zero())
330 options << " height=" << params().height.asLatexString() << ",\n";
331 if (params().keepAspectRatio)
332 options << " keepaspectratio,\n";
335 // Make sure rotation angle is not very close to zero;
336 // a float can be effectively zero but not exactly zero.
337 if (!float_equal(params().rotateAngle, 0, 0.001)) {
338 options << " angle=" << params().rotateAngle << ",\n";
339 if (!params().rotateOrigin.empty()) {
340 options << " origin=" << params().rotateOrigin[0];
341 if (contains(params().rotateOrigin,"Top"))
343 else if (contains(params().rotateOrigin,"Bottom"))
345 else if (contains(params().rotateOrigin,"Baseline"))
351 if (!params().special.empty())
352 options << params().special << ",\n";
354 string opts = options.str();
356 return opts.substr(0, opts.size() - 2);
370 std::pair<CopyStatus, string> const
371 copyToDirIfNeeded(string const & file_in, string const & dir)
373 using support::rtrim;
375 BOOST_ASSERT(AbsolutePath(file_in));
377 string const only_path = support::OnlyPath(file_in);
378 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
379 return std::make_pair(IDENTICAL_PATHS, file_in);
382 if (support::zippedFile(file_in)) {
383 string const ext = GetExtension(file_in);
384 string const unzipped = support::unzippedFileName(file_in);
385 mangled = FileName(unzipped).mangledFilename();
386 mangled += "." + ext;
388 mangled = FileName(file_in).mangledFilename();
390 string const file_out = support::MakeAbsPath(mangled, dir);
392 unsigned long const checksum_in = support::sum(file_in);
393 unsigned long const checksum_out = support::sum(file_out);
395 if (checksum_in == checksum_out)
397 return std::make_pair(IDENTICAL_CONTENTS, file_out);
399 bool const success = support::copy(file_in, file_out);
401 lyxerr[Debug::GRAPHICS]
402 << support::bformat(_("Could not copy the file\n%1$s\n"
403 "into the temporary directory."),
408 CopyStatus status = success ? SUCCESS : FAILURE;
409 return std::make_pair(status, file_out);
413 string const stripExtensionIfPossible(string const & file, string const & to)
415 // No conversion is needed. LaTeX can handle the graphic file as is.
416 // This is true even if the orig_file is compressed.
417 if (formats.getFormat(to)->extension() == GetExtension(file))
418 return RemoveExtension(file);
425 string const InsetGraphics::prepareFile(Buffer const & buf,
426 LatexRunParams const & runparams) const
428 string orig_file = params().filename.absFilename();
429 string const rel_file = params().filename.relFilename(buf.filePath());
431 // LaTeX can cope if the graphics file doesn't exist, so just return the
433 if (!IsFileReadable(orig_file)) {
434 lyxerr[Debug::GRAPHICS]
435 << "InsetGraphics::prepareFile\n"
436 << "No file '" << orig_file << "' can be found!" << endl;
440 // If the file is compressed and we have specified that it
441 // should not be uncompressed, then just return its name and
442 // let LaTeX do the rest!
443 bool const zipped = params().filename.isZipped();
445 if (zipped && params().noUnzip) {
446 lyxerr[Debug::GRAPHICS]
447 << "\tpass zipped file to LaTeX but with full path.\n";
448 // LaTeX needs an absolute path, otherwise the
449 // coresponding *.eps.bb file isn't found
453 // temp_file will contain the file for LaTeX to act on if, for example,
454 // we move it to a temp dir or uncompress it.
455 string temp_file = orig_file;
459 boost::tie(status, temp_file) =
460 copyToDirIfNeeded(orig_file, buf.temppath());
462 if (status == FAILURE)
465 orig_file = unzippedFileName(temp_file);
466 if (!IsFileReadable(orig_file)) {
467 unzipFile(temp_file);
468 lyxerr[Debug::GRAPHICS]
469 << "\tunzipped to " << orig_file << endl;
473 string const from = getExtFromContents(orig_file);
474 string const to = findTargetFormat(from, runparams);
475 lyxerr[Debug::GRAPHICS]
476 << "\t we have: from " << from << " to " << to << '\n';
478 if (from == to && !lyxrc.use_tempdir)
479 return stripExtensionIfPossible(orig_file, to);
481 // We're going to be running the exported buffer through the LaTeX
482 // compiler, so must ensure that LaTeX can cope with the graphics
485 lyxerr[Debug::GRAPHICS]
486 << "\tthe orig file is: " << orig_file << endl;
488 bool conversion_needed = true;
489 if (lyxrc.use_tempdir) {
491 boost::tie(status, temp_file) =
492 copyToDirIfNeeded(orig_file, buf.temppath());
494 if (status == FAILURE)
496 else if (status == IDENTICAL_CONTENTS)
497 conversion_needed = false;
501 return stripExtensionIfPossible(temp_file, to);
503 string const to_file_base = RemoveExtension(temp_file);
504 string const to_file = ChangeExtension(to_file_base, to);
506 // Do we need to perform the conversion?
507 // Yes if to_file does not exist or if temp_file is newer than to_file
508 if (!conversion_needed ||
509 support::compare_timestamps(temp_file, to_file) < 0) {
510 lyxerr[Debug::GRAPHICS]
511 << bformat(_("No conversion of %1$s is needed after all"),
517 lyxerr[Debug::GRAPHICS]
518 << "\tThe original file is " << orig_file << "\n"
519 << "\tA copy has been made and convert is to be called with:\n"
520 << "\tfile to convert = " << temp_file << '\n'
521 << "\tto_file_base = " << to_file_base << '\n'
522 << "\t from " << from << " to " << to << '\n';
524 // if no special converter defined, than we take the default one
525 // from ImageMagic: convert from:inname.from to:outname.to
526 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
527 string const command =
528 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
529 ' ' + from + ':' + temp_file + ' ' +
530 to + ':' + to_file_base + '.' + to;
531 lyxerr[Debug::GRAPHICS]
532 << "No converter defined! I use convertDefault.sh:\n\t"
535 one.startscript(Systemcall::Wait, command);
536 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
537 string str = bformat(_("No information for converting %1$s "
538 "format files to %2$s.\n"
539 "Try defining a convertor in the preferences."), from, to);
540 Alert::error(_("Could not convert image"), str);
548 int InsetGraphics::latex(Buffer const & buf, ostream & os,
549 LatexRunParams const & runparams) const
551 // If there is no file specified or not existing,
552 // just output a message about it in the latex output.
553 lyxerr[Debug::GRAPHICS]
554 << "insetgraphics::latex: Filename = "
555 << params().filename.absFilename() << endl;
557 string const relative_file =
558 params().filename.relFilename(buf.filePath());
560 // A missing (e)ps-extension is no problem for LaTeX, so
561 // we have to test three different cases
562 #warning uh, but can our cache handle it ? no.
563 string const file_ = params().filename.absFilename();
564 bool const file_exists =
566 (IsFileReadable(file_) || // original
567 IsFileReadable(file_ + ".eps") || // original.eps
568 IsFileReadable(file_ + ".ps")); // original.ps
569 string const message = file_exists ?
570 string() : string("bb = 0 0 200 100, draft, type=eps");
571 // if !message.empty() than there was no existing file
572 // "filename(.(e)ps)" found. In this case LaTeX
573 // draws only a rectangle with the above bb and the
574 // not found filename in it.
575 lyxerr[Debug::GRAPHICS]
576 << "\tMessage = \"" << message << '\"' << endl;
578 // These variables collect all the latex code that should be before and
579 // after the actual includegraphics command.
582 // Do we want subcaptions?
583 if (params().subcaption) {
584 before += "\\subfigure[" + params().subcaptionText + "]{";
587 // We never use the starred form, we use the "clip" option instead.
588 before += "\\includegraphics";
590 // Write the options if there are any.
591 string const opts = createLatexOptions();
592 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
594 if (!opts.empty() && !message.empty())
595 before += ("[%\n" + opts + ',' + message + ']');
596 else if (!opts.empty() || !message.empty())
597 before += ("[%\n" + opts + message + ']');
599 lyxerr[Debug::GRAPHICS]
600 << "\tBefore = " << before
601 << "\n\tafter = " << after << endl;
604 // "nice" means that the buffer is exported to LaTeX format but not
605 // run through the LaTeX compiler.
606 if (runparams.nice) {
607 os << before <<'{' << relative_file << '}' << after;
611 // Make the filename relative to the lyx file
612 // and remove the extension so the LaTeX will use whatever is
613 // appropriate (when there are several versions in different formats)
614 string const latex_str = message.empty() ?
615 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
616 (before + '{' + relative_file + " not found!}" + after);
619 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
620 << latex_str << endl;
621 // Return how many newlines we issued.
622 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
626 int InsetGraphics::ascii(Buffer const &, ostream & os, int) const
628 // No graphics in ascii output. Possible to use gifscii to convert
629 // images to ascii approximation.
630 // 1. Convert file to ascii using gifscii
631 // 2. Read ascii output file and add it to the output stream.
632 // at least we send the filename
633 os << '<' << bformat(_("Graphics file: %1$s"),
634 params().filename.absFilename()) << ">\n";
639 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os) const
641 string const file_name = buf.niceFile() ?
642 params().filename.relFilename(buf.filePath()):
643 params().filename.absFilename();
645 os << "<eps file=\"" << file_name << "\">\n";
646 os << "<img src=\"" << file_name << "\">";
651 // For explanation on inserting graphics into DocBook checkout:
652 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
653 // See also the docbook guide at http://www.docbook.org/
654 int InsetGraphics::docbook(Buffer const &, ostream & os,
655 bool /*mixcont*/) const
657 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
658 // need to switch to MediaObject. However, for now this is sufficient and
660 os << "<graphic fileref=\"&" << graphic_label << ";\">";
665 void InsetGraphics::validate(LaTeXFeatures & features) const
667 // If we have no image, we should not require anything.
668 if (params().filename.empty())
671 features.includeFile(graphic_label,
672 RemoveExtension(params().filename.absFilename()));
674 features.require("graphicx");
676 if (params().subcaption)
677 features.require("subfigure");
681 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
683 // If nothing is changed, just return and say so.
684 if (params() == p && !p.filename.empty())
687 // Copy the new parameters.
690 // Update the display using the new parameters.
691 graphic_->update(params().as_grfxParams());
693 // We have changed data, report it.
698 InsetGraphicsParams const & InsetGraphics::params() const
704 string const InsetGraphicsMailer::name_("graphics");
706 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
711 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
713 return params2string(inset_.params(), buffer);
717 void InsetGraphicsMailer::string2params(string const & in,
718 Buffer const & buffer,
719 InsetGraphicsParams & params)
721 params = InsetGraphicsParams();
726 istringstream data(in);
732 string const token = lex.getString();
739 inset.readInsetGraphics(lex, buffer.filePath());
740 params = inset.params();
746 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
747 Buffer const & buffer)
750 data << name_ << ' ';
751 params.Write(data, buffer.filePath());
752 data << "\\end_inset\n";