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"
70 #include "metricsinfo.h"
72 #include "frontends/Alert.h"
73 #include "frontends/LyXView.h"
75 #include "support/filetools.h"
76 #include "support/lyxalgo.h" // lyx::count
77 #include "support/lyxlib.h" // float_equal
78 #include "support/os.h"
79 #include "support/systemcall.h"
80 #include "support/tostr.h"
82 #include <boost/bind.hpp>
83 #include <boost/tuple/tuple.hpp>
85 #include "support/std_sstream.h"
87 namespace support = lyx::support;
88 using lyx::support::AbsolutePath;
89 using lyx::support::bformat;
90 using lyx::support::ChangeExtension;
91 using lyx::support::contains;
92 using lyx::support::FileName;
93 using lyx::support::float_equal;
94 using lyx::support::GetExtension;
95 using lyx::support::getExtFromContents;
96 using lyx::support::IsFileReadable;
97 using lyx::support::LibFileSearch;
98 using lyx::support::rtrim;
99 using lyx::support::Systemcall;
100 using lyx::support::unzipFile;
101 using lyx::support::unzippedFileName;
103 namespace os = lyx::support::os;
108 using std::istringstream;
110 using std::ostringstream;
115 ///////////////////////////////////////////////////////////////////////////
116 int const VersionNumber = 1;
117 ///////////////////////////////////////////////////////////////////////////
119 // This function is a utility function
120 // ... that should be with ChangeExtension ...
122 string const RemoveExtension(string const & filename)
124 return ChangeExtension(filename, string());
128 string const uniqueID()
130 static unsigned int seed = 1000;
131 return "graph" + tostr(++seed);
135 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
137 // Are we using latex or pdflatex).
138 if (runparams.flavor == LatexRunParams::PDFLATEX) {
139 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
140 if (contains(suffix, "ps") || suffix == "pdf")
142 if (suffix == "jpg") // pdflatex can use jpeg
144 return "png"; // and also png
146 // If it's postscript, we always do eps.
147 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
148 if (suffix != "ps") // any other than ps
149 return "eps"; // is changed to eps
150 return suffix; // let ps untouched
156 InsetGraphics::InsetGraphics()
157 : graphic_label(uniqueID()),
158 graphic_(new RenderGraphic)
160 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
164 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
166 boost::signals::trackable(),
167 graphic_label(uniqueID()),
168 graphic_(new RenderGraphic(*ig.graphic_))
170 graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
171 setParams(ig.params());
175 auto_ptr<InsetBase> InsetGraphics::clone() const
177 return auto_ptr<InsetBase>(new InsetGraphics(*this));
181 InsetGraphics::~InsetGraphics()
183 InsetGraphicsMailer(*this).hideDialog();
187 void InsetGraphics::statusChanged() const
189 LyX::cref().updateInset(this);
193 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
195 switch (cmd.action) {
196 case LFUN_INSET_MODIFY: {
197 Buffer const & buffer = *cmd.view()->buffer();
198 InsetGraphicsParams p;
199 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
200 if (!p.filename.empty()) {
202 cmd.view()->updateInset(this);
207 case LFUN_INSET_DIALOG_UPDATE:
208 InsetGraphicsMailer(*this).updateDialog(cmd.view());
211 case LFUN_INSET_EDIT:
212 case LFUN_MOUSE_RELEASE:
213 InsetGraphicsMailer(*this).showDialog(cmd.view());
222 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
224 graphic_->metrics(mi, dim);
229 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
231 graphic_->draw(pi, x, y);
235 InsetOld::EDITABLE InsetGraphics::editable() const
241 void InsetGraphics::write(Buffer const & buf, ostream & os) const
244 params().Write(os, buf.filePath());
248 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
250 string const token = lex.getString();
252 if (token == "Graphics")
253 readInsetGraphics(lex, buf.filePath());
255 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
257 graphic_->update(params().as_grfxParams());
261 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
263 bool finished = false;
265 while (lex.isOK() && !finished) {
268 string const token = lex.getString();
269 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
274 } else if (token == "\\end_inset") {
276 } else if (token == "FormatVersion") {
278 int version = lex.getInteger();
279 if (version > VersionNumber)
281 << "This document was created with a newer Graphics widget"
282 ", You should use a newer version of LyX to read this"
285 // TODO: Possibly open up a dialog?
288 if (!params_.Read(lex, token, bufpath))
289 lyxerr << "Unknown token, " << token << ", skipping."
296 string const InsetGraphics::createLatexOptions() const
298 // Calculate the options part of the command, we must do it to a string
299 // stream since we might have a trailing comma that we would like to remove
300 // before writing it to the output stream.
301 ostringstream options;
302 if (!params().bb.empty())
303 options << " bb=" << rtrim(params().bb) << ",\n";
305 options << " draft,\n";
307 options << " clip,\n";
308 if (!float_equal(params().scale, 0.0, 0.05)) {
309 if (!float_equal(params().scale, 100.0, 0.05))
310 options << " scale=" << params().scale / 100.0
313 if (!params().width.zero())
314 options << " width=" << params().width.asLatexString() << ",\n";
315 if (!params().height.zero())
316 options << " height=" << params().height.asLatexString() << ",\n";
317 if (params().keepAspectRatio)
318 options << " keepaspectratio,\n";
321 // Make sure rotation angle is not very close to zero;
322 // a float can be effectively zero but not exactly zero.
323 if (!float_equal(params().rotateAngle, 0, 0.001)) {
324 options << " angle=" << params().rotateAngle << ",\n";
325 if (!params().rotateOrigin.empty()) {
326 options << " origin=" << params().rotateOrigin[0];
327 if (contains(params().rotateOrigin,"Top"))
329 else if (contains(params().rotateOrigin,"Bottom"))
331 else if (contains(params().rotateOrigin,"Baseline"))
337 if (!params().special.empty())
338 options << params().special << ",\n";
340 string opts = options.str();
342 return opts.substr(0, opts.size() - 2);
356 std::pair<CopyStatus, string> const
357 copyToDirIfNeeded(string const & file_in, string const & dir)
359 using support::rtrim;
361 BOOST_ASSERT(AbsolutePath(file_in));
363 string const only_path = support::OnlyPath(file_in);
364 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
365 return std::make_pair(IDENTICAL_PATHS, file_in);
368 if (support::zippedFile(file_in)) {
369 string const ext = GetExtension(file_in);
370 string const unzipped = support::unzippedFileName(file_in);
371 mangled = FileName(unzipped).mangledFilename();
372 mangled += "." + ext;
374 mangled = FileName(file_in).mangledFilename();
376 string const file_out = support::MakeAbsPath(mangled, dir);
378 unsigned long const checksum_in = support::sum(file_in);
379 unsigned long const checksum_out = support::sum(file_out);
381 if (checksum_in == checksum_out)
383 return std::make_pair(IDENTICAL_CONTENTS, file_out);
385 bool const success = support::copy(file_in, file_out);
387 lyxerr[Debug::GRAPHICS]
388 << support::bformat(_("Could not copy the file\n%1$s\n"
389 "into the temporary directory."),
394 CopyStatus status = success ? SUCCESS : FAILURE;
395 return std::make_pair(status, file_out);
399 string const stripExtensionIfPossible(string const & file, string const & to)
401 // No conversion is needed. LaTeX can handle the graphic file as is.
402 // This is true even if the orig_file is compressed.
403 if (formats.getFormat(to)->extension() == GetExtension(file))
404 return RemoveExtension(file);
411 string const InsetGraphics::prepareFile(Buffer const & buf,
412 LatexRunParams const & runparams) const
414 string orig_file = params().filename.absFilename();
415 string const rel_file = params().filename.relFilename(buf.filePath());
417 // LaTeX can cope if the graphics file doesn't exist, so just return the
419 if (!IsFileReadable(orig_file)) {
420 lyxerr[Debug::GRAPHICS]
421 << "InsetGraphics::prepareFile\n"
422 << "No file '" << orig_file << "' can be found!" << endl;
426 // If the file is compressed and we have specified that it
427 // should not be uncompressed, then just return its name and
428 // let LaTeX do the rest!
429 bool const zipped = params().filename.isZipped();
431 if (zipped && params().noUnzip) {
432 lyxerr[Debug::GRAPHICS]
433 << "\tpass zipped file to LaTeX but with full path.\n";
434 // LaTeX needs an absolute path, otherwise the
435 // coresponding *.eps.bb file isn't found
439 // temp_file will contain the file for LaTeX to act on if, for example,
440 // we move it to a temp dir or uncompress it.
441 string temp_file = orig_file;
445 boost::tie(status, temp_file) =
446 copyToDirIfNeeded(orig_file, buf.temppath());
448 if (status == FAILURE)
451 orig_file = unzippedFileName(temp_file);
452 if (!IsFileReadable(orig_file)) {
453 unzipFile(temp_file);
454 lyxerr[Debug::GRAPHICS]
455 << "\tunzipped to " << orig_file << endl;
459 string const from = getExtFromContents(orig_file);
460 string const to = findTargetFormat(from, runparams);
461 lyxerr[Debug::GRAPHICS]
462 << "\t we have: from " << from << " to " << to << '\n';
464 if (from == to && !lyxrc.use_tempdir)
465 return stripExtensionIfPossible(orig_file, to);
467 // We're going to be running the exported buffer through the LaTeX
468 // compiler, so must ensure that LaTeX can cope with the graphics
471 lyxerr[Debug::GRAPHICS]
472 << "\tthe orig file is: " << orig_file << endl;
474 bool conversion_needed = true;
475 if (lyxrc.use_tempdir) {
477 boost::tie(status, temp_file) =
478 copyToDirIfNeeded(orig_file, buf.temppath());
480 if (status == FAILURE)
482 else if (status == IDENTICAL_CONTENTS)
483 conversion_needed = false;
487 return stripExtensionIfPossible(temp_file, to);
489 string const to_file_base = RemoveExtension(temp_file);
490 string const to_file = ChangeExtension(to_file_base, to);
492 // Do we need to perform the conversion?
493 // Yes if to_file does not exist or if temp_file is newer than to_file
494 if (!conversion_needed ||
495 support::compare_timestamps(temp_file, to_file) < 0) {
496 lyxerr[Debug::GRAPHICS]
497 << bformat(_("No conversion of %1$s is needed after all"),
503 lyxerr[Debug::GRAPHICS]
504 << "\tThe original file is " << orig_file << "\n"
505 << "\tA copy has been made and convert is to be called with:\n"
506 << "\tfile to convert = " << temp_file << '\n'
507 << "\tto_file_base = " << to_file_base << '\n'
508 << "\t from " << from << " to " << to << '\n';
510 // if no special converter defined, than we take the default one
511 // from ImageMagic: convert from:inname.from to:outname.to
512 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
513 string const command =
514 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
515 ' ' + from + ':' + temp_file + ' ' +
516 to + ':' + to_file_base + '.' + to;
517 lyxerr[Debug::GRAPHICS]
518 << "No converter defined! I use convertDefault.sh:\n\t"
521 one.startscript(Systemcall::Wait, command);
522 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
523 string str = bformat(_("No information for converting %1$s "
524 "format files to %2$s.\n"
525 "Try defining a convertor in the preferences."), from, to);
526 Alert::error(_("Could not convert image"), str);
534 int InsetGraphics::latex(Buffer const & buf, ostream & os,
535 LatexRunParams const & runparams) const
537 // If there is no file specified or not existing,
538 // just output a message about it in the latex output.
539 lyxerr[Debug::GRAPHICS]
540 << "insetgraphics::latex: Filename = "
541 << params().filename.absFilename() << endl;
543 string const relative_file =
544 params().filename.relFilename(buf.filePath());
546 // A missing (e)ps-extension is no problem for LaTeX, so
547 // we have to test three different cases
548 #warning uh, but can our cache handle it ? no.
549 string const file_ = params().filename.absFilename();
550 bool const file_exists =
552 (IsFileReadable(file_) || // original
553 IsFileReadable(file_ + ".eps") || // original.eps
554 IsFileReadable(file_ + ".ps")); // original.ps
555 string const message = file_exists ?
556 string() : string("bb = 0 0 200 100, draft, type=eps");
557 // if !message.empty() than there was no existing file
558 // "filename(.(e)ps)" found. In this case LaTeX
559 // draws only a rectangle with the above bb and the
560 // not found filename in it.
561 lyxerr[Debug::GRAPHICS]
562 << "\tMessage = \"" << message << '\"' << endl;
564 // These variables collect all the latex code that should be before and
565 // after the actual includegraphics command.
568 // Do we want subcaptions?
569 if (params().subcaption) {
570 before += "\\subfigure[" + params().subcaptionText + "]{";
573 // We never use the starred form, we use the "clip" option instead.
574 before += "\\includegraphics";
576 // Write the options if there are any.
577 string const opts = createLatexOptions();
578 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
580 if (!opts.empty() && !message.empty())
581 before += ("[%\n" + opts + ',' + message + ']');
582 else if (!opts.empty() || !message.empty())
583 before += ("[%\n" + opts + message + ']');
585 lyxerr[Debug::GRAPHICS]
586 << "\tBefore = " << before
587 << "\n\tafter = " << after << endl;
590 // "nice" means that the buffer is exported to LaTeX format but not
591 // run through the LaTeX compiler.
592 if (runparams.nice) {
593 os << before <<'{' << relative_file << '}' << after;
597 // Make the filename relative to the lyx file
598 // and remove the extension so the LaTeX will use whatever is
599 // appropriate (when there are several versions in different formats)
600 string const latex_str = message.empty() ?
601 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
602 (before + '{' + relative_file + " not found!}" + after);
605 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
606 << latex_str << endl;
607 // Return how many newlines we issued.
608 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
612 int InsetGraphics::ascii(Buffer const &, ostream & os, int) const
614 // No graphics in ascii output. Possible to use gifscii to convert
615 // images to ascii approximation.
616 // 1. Convert file to ascii using gifscii
617 // 2. Read ascii output file and add it to the output stream.
618 // at least we send the filename
619 os << '<' << bformat(_("Graphics file: %1$s"),
620 params().filename.absFilename()) << ">\n";
625 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os) const
627 string const file_name = buf.niceFile() ?
628 params().filename.relFilename(buf.filePath()):
629 params().filename.absFilename();
631 os << "<eps file=\"" << file_name << "\">\n";
632 os << "<img src=\"" << file_name << "\">";
637 // For explanation on inserting graphics into DocBook checkout:
638 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
639 // See also the docbook guide at http://www.docbook.org/
640 int InsetGraphics::docbook(Buffer const &, ostream & os,
641 bool /*mixcont*/) const
643 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
644 // need to switch to MediaObject. However, for now this is sufficient and
646 os << "<graphic fileref=\"&" << graphic_label << ";\">";
651 void InsetGraphics::validate(LaTeXFeatures & features) const
653 // If we have no image, we should not require anything.
654 if (params().filename.empty())
657 features.includeFile(graphic_label,
658 RemoveExtension(params().filename.absFilename()));
660 features.require("graphicx");
662 if (params().subcaption)
663 features.require("subfigure");
667 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
669 // If nothing is changed, just return and say so.
670 if (params() == p && !p.filename.empty())
673 // Copy the new parameters.
676 // Update the display using the new parameters.
677 graphic_->update(params().as_grfxParams());
679 // We have changed data, report it.
684 InsetGraphicsParams const & InsetGraphics::params() const
690 string const InsetGraphicsMailer::name_("graphics");
692 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
697 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
699 return params2string(inset_.params(), buffer);
703 void InsetGraphicsMailer::string2params(string const & in,
704 Buffer const & buffer,
705 InsetGraphicsParams & params)
707 params = InsetGraphicsParams();
712 istringstream data(in);
718 string const token = lex.getString();
725 inset.readInsetGraphics(lex, buffer.filePath());
726 params = inset.params();
732 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
733 Buffer const & buffer)
736 data << name_ << ' ';
737 params.Write(data, buffer.filePath());
738 data << "\\end_inset\n";