2 * \file InsetGraphics.cpp
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 * When loading, if the image is not found in the expected place, try
19 to find it in the clipart, or in the same directory with the image.
20 * The image choosing dialog could show thumbnails of the image formats
21 it knows of, thus selection based on the image instead of based on
23 * Add support for the 'picins' package.
24 * Add support for the 'picinpar' package.
29 * The filename is kept in the lyx file in a relative way, so as to allow
30 * moving the document file and its images with no problem.
34 * Postscript output means EPS figures.
36 * PDF output is best done with PDF figures if it's a direct conversion
37 * or PNG figures otherwise.
49 #include "insets/InsetGraphics.h"
50 #include "insets/RenderGraphic.h"
53 #include "BufferView.h"
54 #include "Converter.h"
56 #include "DispatchResult.h"
58 #include "ErrorList.h"
61 #include "FuncRequest.h"
62 #include "FuncStatus.h"
63 #include "InsetIterator.h"
64 #include "LaTeXFeatures.h"
66 #include "MetricsInfo.h"
68 #include "output_docbook.h"
69 #include "output_xhtml.h"
71 #include "texstream.h"
72 #include "TocBackend.h"
74 #include "frontends/alert.h"
75 #include "frontends/Application.h"
77 #include "graphics/GraphicsCache.h"
78 #include "graphics/GraphicsCacheItem.h"
79 #include "graphics/GraphicsImage.h"
81 #include "support/convert.h"
82 #include "support/debug.h"
83 #include "support/docstream.h"
84 #include "support/ExceptionMessage.h"
85 #include "support/filetools.h"
86 #include "support/gettext.h"
87 #include "support/Length.h"
88 #include "support/lyxlib.h"
89 #include "support/lstrings.h"
90 #include "support/os.h"
91 #include "support/qstring_helpers.h"
92 #include "support/Systemcall.h"
95 #include <QtGui/QImage>
101 using namespace lyx::support;
105 namespace Alert = frontend::Alert;
109 /// Find the most suitable image format for images in \p format
110 /// Note that \p format may be unknown (i.e. an empty string)
111 string findTargetFormat(string const & format, OutputParams const & runparams)
113 // Are we latexing to DVI or PDF?
114 if (runparams.flavor == Flavor::PdfLaTeX
115 || runparams.flavor == Flavor::XeTeX
116 || runparams.flavor == Flavor::LuaTeX) {
117 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
118 Format const * const f = theFormats().getFormat(format);
119 // Convert vector graphics to pdf
120 if (f && f->vectorFormat())
122 // pdflatex can use jpeg, png and pdf directly
125 // Convert everything else to png
129 // for HTML and DocBook, we leave the known formats and otherwise convert to png
130 if (runparams.flavor == Flavor::Html || runparams.flavor == Flavor::DocBook5) {
131 Format const * const f = theFormats().getFormat(format);
132 // Convert vector graphics to svg
133 if (f && f->vectorFormat() && theConverters().isReachable(format, "svg"))
135 // Leave the known formats alone
136 if (format == "jpg" || format == "png" || format == "gif")
138 // Convert everything else to png
141 // If it's postscript, we always do eps.
142 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
144 // any other than ps is changed to eps
151 void readInsetGraphics(Lexer & lex, Buffer const & buf, bool allowOrigin,
152 InsetGraphicsParams & params)
154 bool finished = false;
156 while (lex.isOK() && !finished) {
159 string const token = lex.getString();
160 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
165 if (token == "\\end_inset") {
168 if (!params.Read(lex, token, buf, allowOrigin))
169 lyxerr << "Unknown token, "
180 InsetGraphics::InsetGraphics(Buffer * buf)
181 : Inset(buf), graphic_label(xml::uniqueID(from_ascii("graph"))),
182 graphic_(new RenderGraphic(this))
187 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
189 graphic_label(xml::uniqueID(from_ascii("graph"))),
190 graphic_(new RenderGraphic(*ig.graphic_, this))
192 setParams(ig.params());
196 Inset * InsetGraphics::clone() const
198 return new InsetGraphics(*this);
202 InsetGraphics::~InsetGraphics()
204 hideDialogs("graphics", this);
209 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
211 switch (cmd.action()) {
212 case LFUN_INSET_EDIT: {
213 InsetGraphicsParams p = params();
214 if (!cmd.argument().empty())
215 string2params(to_utf8(cmd.argument()), buffer(), p);
220 case LFUN_INSET_MODIFY: {
221 if (cmd.getArg(0) != "graphics") {
222 Inset::doDispatch(cur, cmd);
226 InsetGraphicsParams p;
227 string2params(to_utf8(cmd.argument()), buffer(), p);
228 if (p.filename.empty()) {
229 cur.noScreenUpdate();
235 // if the inset is part of a graphics group, all the
236 // other members should be updated too.
237 if (!params_.groupId.empty())
238 graphics::unifyGraphicsGroups(buffer(),
239 to_utf8(cmd.argument()));
243 case LFUN_INSET_DIALOG_UPDATE:
244 cur.bv().updateDialog("graphics", params2string(params(), buffer()));
247 case LFUN_GRAPHICS_RELOAD:
248 params_.filename.refresh();
253 Inset::doDispatch(cur, cmd);
259 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
260 FuncStatus & flag) const
262 switch (cmd.action()) {
263 case LFUN_INSET_MODIFY:
264 if (cmd.getArg(0) != "graphics")
265 return Inset::getStatus(cur, cmd, flag);
267 case LFUN_INSET_EDIT:
268 case LFUN_INSET_DIALOG_UPDATE:
269 case LFUN_GRAPHICS_RELOAD:
270 flag.setEnabled(true);
274 return Inset::getStatus(cur, cmd, flag);
279 bool InsetGraphics::showInsetDialog(BufferView * bv) const
281 bv->showDialog("graphics", params2string(params(), bv->buffer()),
282 const_cast<InsetGraphics *>(this));
288 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
290 graphic_->metrics(mi, dim);
294 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
296 graphic_->draw(pi, x, y, params_.darkModeSensitive);
300 void InsetGraphics::write(ostream & os) const
303 params().Write(os, buffer());
307 void InsetGraphics::read(Lexer & lex)
309 lex.setContext("InsetGraphics::read");
311 readInsetGraphics(lex, buffer(), true, params_);
312 graphic_->update(params().as_grfxParams());
316 void InsetGraphics::outBoundingBox(graphics::BoundingBox & bbox) const
321 FileName const file(params().filename.absFileName());
323 // No correction is necessary for a vector image
324 bool const zipped = theFormats().isZippedFile(file);
325 FileName const unzipped_file = zipped ? unzipFile(file) : file;
326 string const format = theFormats().getFormatFromFile(unzipped_file);
328 unzipped_file.removeFile();
329 if (theFormats().getFormat(format)->vectorFormat())
332 // Get the actual image dimensions in pixels
335 graphics::Cache & gc = graphics::Cache::get();
336 if (gc.inCache(file)) {
337 graphics::Image const * image = gc.item(file)->image();
339 width = image->width();
340 height = image->height();
343 // Even if cached, the image is not loaded without GUI
344 if (width == 0 && height == 0) {
345 QImage image(toqstr(file.absFileName()));
346 width = image.width();
347 height = image.height();
349 if (width == 0 || height == 0)
352 // Use extractbb to find the dimensions in the typeset output
354 extractbb.start("extractbb", QStringList() << "-O" << toqstr(file.absFileName()));
355 if (!extractbb.waitForStarted() || !extractbb.waitForFinished()) {
356 LYXERR0("Cannot read output bounding box of " << file);
360 string const result = extractbb.readAll().constData();
361 size_t i = result.find("%%BoundingBox:");
362 if (i == string::npos) {
363 LYXERR0("Cannot find output bounding box of " << file);
367 string const bb = result.substr(i);
368 int out_width = convert<int>(token(bb, ' ', 3));
369 int out_height = convert<int>(token(bb, ' ', 4));
371 // Compute the scaling ratio and correct the bounding box
372 double scalex = out_width / double(width);
373 double scaley = out_height / double(height);
375 bbox.xl.value(scalex * bbox.xl.value());
376 bbox.xr.value(scalex * bbox.xr.value());
377 bbox.yb.value(scaley * bbox.yb.value());
378 bbox.yt.value(scaley * bbox.yt.value());
382 string InsetGraphics::createLatexOptions(bool const ps) const
384 // Calculate the options part of the command, we must do it to a string
385 // stream since we might have a trailing comma that we would like to remove
386 // before writing it to the output stream.
387 ostringstream options;
388 if (!params().bbox.empty()) {
389 graphics::BoundingBox out_bbox = params().bbox;
390 outBoundingBox(out_bbox);
391 string const key = ps ? "bb=" : "viewport=";
392 options << key << out_bbox.xl.asLatexString() << ' '
393 << out_bbox.yb.asLatexString() << ' '
394 << out_bbox.xr.asLatexString() << ' '
395 << out_bbox.yt.asLatexString() << ',';
402 double const scl = convert<double>(params().scale);
403 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
404 if (!float_equal(scl, 100.0, 0.05))
405 size << "scale=" << scl / 100.0 << ',';
407 if (!params().width.zero())
408 size << "width=" << params().width.asLatexString() << ',';
409 if (!params().height.zero())
410 size << "totalheight=" << params().height.asLatexString() << ',';
411 if (params().keepAspectRatio)
412 size << "keepaspectratio,";
414 if (params().scaleBeforeRotation && !size.str().empty())
415 options << size.str();
417 // Make sure rotation angle is not very close to zero;
418 // a float can be effectively zero but not exactly zero.
419 if (!params().rotateAngle.empty()
420 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
421 options << "angle=" << params().rotateAngle << ',';
422 if (!params().rotateOrigin.empty()) {
423 options << "origin=" << params().rotateOrigin[0];
424 if (contains(params().rotateOrigin,"Top"))
426 else if (contains(params().rotateOrigin,"Bottom"))
428 else if (contains(params().rotateOrigin,"Baseline"))
433 if (!params().scaleBeforeRotation && !size.str().empty())
434 options << size.str();
436 if (!params().special.empty())
437 options << params().special << ',';
439 string opts = options.str();
441 if (suffixIs(opts, ','))
442 opts = opts.substr(0, opts.size() - 1);
448 docstring InsetGraphics::toDocbookLength(Length const & len) const
450 odocstringstream result;
451 switch (len.unit()) {
452 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
453 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
455 case Length::PT: // Point = 1/72.27in = 0.351mm
456 result << len.value() * 72 / 72.27 << "pt";
458 case Length::BP: // Big point (72bp = 1in), also PostScript point
459 result << len.value() << "pt";
461 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
462 result << len.value() * 0.376 << "mm";
464 case Length::MM: // Millimeter = 2.845pt
465 result << len.value() << "mm";
467 case Length::PC: // Pica = 12pt = 4.218mm
468 result << len.value() << "pc";
470 case Length::CC: // Cicero = 12dd = 4.531mm
471 result << len.value() * 4.531 << "mm";
473 case Length::CM: // Centimeter = 10mm = 2.371pc
474 result << len.value() << "cm";
476 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
477 result << len.value() << "in";
479 case Length::EX: // Height of a small "x" for the current font.
480 // Obviously we have to compromise here. Any better ratio than 1.5 ?
481 result << len.value() / 1.5 << "em";
483 case Length::EM: // Width of capital "M" in current font.
484 result << len.value() << "em";
486 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
487 result << len.value() * 18 << "em";
489 case Length::PTW: // Percent of TextWidth
490 case Length::PCW: // Percent of ColumnWidth
491 case Length::PPW: // Percent of PageWidth
492 case Length::PLW: // Percent of LineWidth
493 case Length::PTH: // Percent of TextHeight
494 case Length::PPH: // Percent of PaperHeight
495 case Length::BLS: // Percent of BaselineSkip
496 // Sigh, this will go wrong.
497 result << len.value() << "%";
500 result << len.asDocstring();
507 docstring InsetGraphics::createDocBookAttributes() const
509 // Calculate the options part of the command, we must do it to a string
510 // stream since we copied the code from createLatexParams() ;-)
512 odocstringstream options;
513 auto const scl = convert<double>(params().scale);
514 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
515 if (!float_equal(scl, 100.0, 0.05))
516 options << " scale=\""
517 << support::iround(scl)
520 if (!params().width.zero())
521 options << " width=\"" << toDocbookLength(params().width) << "\" ";
522 if (!params().height.zero())
523 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
524 if (params().keepAspectRatio)
525 // This will be irrelevant unless both width and height are set
526 options << "scalefit=\"1\" ";
529 // TODO: parse params().special?
531 // trailing blanks are ok ...
532 return options.str();
538 enum GraphicsCopyStatus {
546 pair<GraphicsCopyStatus, FileName> const
547 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
549 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
550 unsigned long const checksum_in = file_in.checksum();
551 unsigned long const checksum_out = file_out.checksum();
553 if (checksum_in == checksum_out)
555 return make_pair(IDENTICAL_CONTENTS, file_out);
557 Mover const & mover = getMover(theFormats().getFormatFromFile(file_in));
558 bool const success = mover.copy(file_in, file_out);
561 LYXERR(Debug::GRAPHICS,
562 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
563 "into the temporary directory."),
564 from_utf8(file_in.absFileName()))));
567 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
568 return make_pair(status, file_out);
572 pair<GraphicsCopyStatus, FileName> const
573 copyToDirIfNeeded(DocFileName const & file, string const & dir)
575 string const file_in = file.absFileName();
576 string const only_path = onlyPath(file_in);
577 if (rtrim(only_path, "/") == rtrim(dir, "/"))
578 return make_pair(IDENTICAL_PATHS, FileName(file_in));
580 string mangled = file.mangledFileName(empty_string(), false, true);
581 if (theFormats().isZippedFile(file)) {
582 // We need to change _eps.gz to .eps.gz. The mangled name is
583 // still unique because of the counter in mangledFileName().
584 // We can't just call mangledFileName() with the zip
585 // extension removed, because base.eps and base.eps.gz may
586 // have different content but would get the same mangled
587 // name in this case.
588 // Also take into account that if the name of the zipped file
589 // has no zip extension then the name of the unzipped one is
590 // prefixed by "unzipped_".
591 string const base = removeExtension(file.unzippedFileName());
592 string::size_type const prefix_len =
593 prefixIs(onlyFileName(base), "unzipped_") ? 9 : 0;
594 string::size_type const ext_len =
595 file_in.length() + prefix_len - base.length();
596 mangled[mangled.length() - ext_len] = '.';
598 FileName const file_out(makeAbsPath(mangled, dir));
600 return copyFileIfNeeded(file, file_out);
604 string const stripExtensionIfPossible(string const & file, bool nice)
606 // Remove the extension so the LaTeX compiler will use whatever
607 // is appropriate (when there are several versions in different
609 // Do this only if we are not exporting for internal usage, because
610 // pdflatex prefers png over pdf and it would pick up the png images
611 // that we generate for preview.
612 // This works only if the filename contains no dots besides
613 // the just removed one. We can fool here by replacing all
614 // dots with a macro whose definition is just a dot ;-)
615 // The automatic format selection does not work if the file
617 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
618 if (!nice || contains(latex_name, '"'))
620 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
624 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
626 // No conversion is needed. LaTeX can handle the graphic file as is.
627 // This is true even if the orig_file is compressed.
628 Format const * f = theFormats().getFormat(to);
630 return latex_path(file, EXCLUDE_EXTENSION);
631 string const to_format = f->extension();
632 string const file_format = getExtension(file);
633 // for latex .ps == .eps
634 if (to_format == file_format ||
635 (to_format == "eps" && file_format == "ps") ||
636 (to_format == "ps" && file_format == "eps"))
637 return stripExtensionIfPossible(file, nice);
638 return latex_path(file, EXCLUDE_EXTENSION);
644 string InsetGraphics::prepareFile(OutputParams const & runparams) const
646 // The following code depends on non-empty filenames
647 if (params().filename.empty())
650 string const orig_file = params().filename.absFileName();
651 // this is for dryrun and display purposes, do not use latexFilename
652 string const rel_file = params().filename.relFileName(buffer().filePath());
654 // previewing source code, no file copying or file format conversion
655 if (runparams.dryrun)
656 return stripExtensionIfPossible(rel_file, runparams.nice);
658 // The master buffer. This is useful when there are multiple levels
660 Buffer const * masterBuffer = buffer().masterBuffer();
662 // Return the output name if we are inside a comment or the file does
664 // We are not going to change the extension or using the name of the
665 // temporary file, the code is already complicated enough.
666 if (runparams.inComment || !params().filename.isReadableFile())
667 return params().filename.outputFileName(masterBuffer->filePath());
669 // We place all temporary files in the master buffer's temp dir.
670 // This is possible because we use mangled file names.
671 // This is necessary for DVI export.
672 string const temp_path = masterBuffer->temppath();
674 // temp_file will contain the file for LaTeX to act on if, for example,
675 // we move it to a temp dir or uncompress it.
677 GraphicsCopyStatus status;
678 tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
680 if (status == FAILURE)
683 // a relative filename should be relative to the master buffer.
684 // "nice" means that the buffer is exported to LaTeX format but not
685 // run through the LaTeX compiler.
686 string output_file = runparams.nice ?
687 params().filename.outputFileName(masterBuffer->filePath()) :
688 onlyFileName(temp_file.absFileName());
690 if (runparams.nice) {
691 if (!isValidLaTeXFileName(output_file)) {
692 frontend::Alert::warning(_("Invalid filename"),
693 _("The following filename will cause troubles "
694 "when running the exported file through LaTeX: ") +
695 from_utf8(output_file));
697 // only show DVI-specific warning when export format is plain latex
698 if (!isValidDVIFileName(output_file)
699 && runparams.flavor == Flavor::LaTeX) {
700 frontend::Alert::warning(_("Problematic filename for DVI"),
701 _("The following filename can cause troubles "
702 "when running the exported file through LaTeX "
703 "and opening the resulting DVI: ") +
704 from_utf8(output_file), true);
708 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
709 // determine the export format
710 string const tex_format = flavor2format(runparams.flavor);
712 if (theFormats().isZippedFile(params().filename)) {
713 FileName const unzipped_temp_file =
714 FileName(unzippedFileName(temp_file.absFileName()));
715 output_file = unzippedFileName(output_file);
716 source_file = FileName(unzippedFileName(source_file.absFileName()));
717 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
718 // temp_file has been unzipped already and
719 // orig_file has not changed in the meantime.
720 temp_file = unzipped_temp_file;
721 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
723 // unzipped_temp_file does not exist or is too old
724 temp_file = unzipFile(temp_file);
725 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
729 string const from = theFormats().getFormatFromFile(temp_file);
731 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
733 string const to = findTargetFormat(from, runparams);
734 string const ext = theFormats().extension(to);
735 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
737 // We're going to be running the exported buffer through the LaTeX
738 // compiler, so must ensure that LaTeX can cope with the graphics
741 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
744 // source and destination formats are the same
745 if (!runparams.nice && !temp_file.hasExtension(ext)) {
746 // The LaTeX compiler will not be able to determine
747 // the file format from the extension, so we must
749 FileName const new_file =
750 FileName(changeExtension(temp_file.absFileName(), ext));
751 if (temp_file.moveTo(new_file)) {
752 temp_file = new_file;
753 output_file = changeExtension(output_file, ext);
755 FileName(changeExtension(source_file.absFileName(), ext));
757 LYXERR(Debug::GRAPHICS, "Could not rename file `"
758 << temp_file << "' to `" << new_file << "'.");
761 // The extension of temp_file might be != ext!
762 runparams.exportdata->addExternalFile(tex_format, source_file,
764 runparams.exportdata->addExternalFile("dvi", source_file,
766 return stripExtensionIfPossible(output_file, to, runparams.nice);
769 // so the source and destination formats are different
770 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
771 string const output_to_file = changeExtension(output_file, ext);
773 // Do we need to perform the conversion?
774 // Yes if to_file does not exist or if temp_file is newer than to_file
775 if (compare_timestamps(temp_file, to_file) < 0) {
777 LYXERR(Debug::GRAPHICS,
778 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
779 from_utf8(rel_file))));
780 runparams.exportdata->addExternalFile(tex_format, to_file,
782 runparams.exportdata->addExternalFile("dvi", to_file,
784 return stripExtensionIfPossible(output_to_file, runparams.nice);
787 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
788 << "\tA copy has been made and convert is to be called with:\n"
789 << "\tfile to convert = " << temp_file << '\n'
790 << "\t from " << from << " to " << to);
792 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
794 Converters::RetVal const rv =
795 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
797 Converters::try_default | Converters::try_cache);
798 if (rv == Converters::KILLED) {
799 LYXERR0("Graphics preparation killed.");
800 if (buffer().isClone() && buffer().isExporting())
801 throw ConversionException();
802 } else if (rv == Converters::SUCCESS) {
803 runparams.exportdata->addExternalFile(tex_format,
804 to_file, output_to_file);
805 runparams.exportdata->addExternalFile("dvi",
806 to_file, output_to_file);
809 return stripExtensionIfPossible(output_to_file, runparams.nice);
813 void InsetGraphics::latex(otexstream & os,
814 OutputParams const & runparams) const
816 // If there is no file specified or not existing,
817 // just output a message about it in the latex output.
818 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
819 << params().filename.absFileName());
821 bool const file_exists = !params().filename.empty()
822 && params().filename.isReadableFile();
825 if (params().bbox.empty())
826 message = "bb = 0 0 200 100";
827 if (!params().draft) {
828 if (!message.empty())
832 if (!message.empty())
834 message += "type=eps";
836 // If no existing file "filename" was found LaTeX
837 // draws only a rectangle with the above bb and the
838 // not found filename in it.
839 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
841 // These variables collect all the latex code that should be before and
842 // after the actual includegraphics command.
846 // Write the options if there are any.
847 bool const ps = runparams.flavor == Flavor::LaTeX
848 || runparams.flavor == Flavor::DviLuaTeX;
849 string const opts = createLatexOptions(ps);
850 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
852 if (contains(opts, '=') && contains(runparams.active_chars, '=')) {
853 // We have a language that makes = active. Deactivate locally
854 // for keyval option parsing (#2005).
855 before = "\\begingroup\\catcode`\\=12";
856 after = "\\endgroup ";
859 if (runparams.moving_arg)
860 before += "\\protect";
862 // We never use the starred form, we use the "clip" option instead.
863 before += "\\includegraphics";
865 if (!opts.empty() && !message.empty())
866 before += ('[' + opts + ',' + message + ']');
867 else if (!opts.empty() || !message.empty())
868 before += ('[' + opts + message + ']');
870 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
872 string latex_str = before + '{';
873 // Convert the file if necessary.
874 // Remove the extension so LaTeX will use whatever is appropriate
875 // (when there are several versions in different formats)
876 docstring file_path = from_utf8(prepareFile(runparams));
877 // we can only output characters covered by the current
880 docstring encodable_file_path;
881 for (char_type c : file_path) {
883 if (runparams.encoding->encodable(c))
884 encodable_file_path += c;
885 else if (runparams.dryrun) {
886 encodable_file_path += "<" + _("LyX Warning: ")
887 + _("uncodable character") + " '";
888 encodable_file_path += docstring(1, c);
889 encodable_file_path += "'>";
892 } catch (EncodingException & /* e */) {
893 if (runparams.dryrun) {
894 encodable_file_path += "<" + _("LyX Warning: ")
895 + _("uncodable character") + " '";
896 encodable_file_path += docstring(1, c);
897 encodable_file_path += "'>";
902 if (!uncodable.empty() && !runparams.silent) {
903 // issue a warning about omitted characters
904 // FIXME: should be passed to the error dialog
905 frontend::Alert::warning(_("Uncodable character in file path"),
906 bformat(_("The following characters in one of the graphic paths are\n"
907 "not representable in the current encoding and have been omitted: %1$s.\n"
908 "You need to adapt either the encoding or the path."),
911 latex_str += to_utf8(encodable_file_path);
912 latex_str += '}' + after;
914 os << from_utf8(latex_str);
916 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
920 int InsetGraphics::plaintext(odocstringstream & os,
921 OutputParams const &, size_t) const
923 // No graphics in ascii output. Possible to use gifscii to convert
924 // images to ascii approximation.
925 // 1. Convert file to ascii using gifscii
926 // 2. Read ascii output file and add it to the output stream.
927 // at least we send the filename
929 // FIXME: We have no idea what the encoding of the filename is
931 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
932 from_utf8(params().filename.absFileName()));
933 os << '<' << str << '>';
935 return 2 + str.size();
939 // For explanation on inserting graphics into DocBook checkout:
940 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
941 // See also the docbook guide at http://www.docbook.org/
942 void InsetGraphics::docbook(XMLStream & xs, OutputParams const & runparams) const
944 string fn = params().filename.relFileName(runparams.export_folder);
945 string tag = runparams.docbook_in_float ? "mediaobject" : "inlinemediaobject";
947 xs << xml::StartTag(tag);
949 xs << xml::StartTag("imageobject");
951 xs << xml::CompTag("imagedata", "fileref=\"" + fn + "\" " + to_utf8(createDocBookAttributes()));
953 xs << xml::EndTag("imageobject");
955 xs << xml::EndTag(tag);
960 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
962 // The following code depends on non-empty filenames
963 if (params().filename.empty())
966 if (!params().filename.isReadableFile())
969 // The master buffer. This is useful when there are multiple levels
971 Buffer const * masterBuffer = buffer().masterBuffer();
973 // We place all temporary files in the master buffer's temp dir.
974 // This is possible because we use mangled file names.
975 // FIXME We may want to put these files in some special temporary
977 string const temp_path = masterBuffer->temppath();
979 // Copy to temporary directory.
981 GraphicsCopyStatus status;
982 tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
984 if (status == FAILURE)
987 string const from = theFormats().getFormatFromFile(temp_file);
989 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
993 string const to = findTargetFormat(from, runparams);
994 string const ext = theFormats().extension(to);
995 string const orig_file = params().filename.absFileName();
996 string output_file = onlyFileName(temp_file.absFileName());
997 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
998 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
1001 // source and destination formats are the same
1002 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
1006 // so the source and destination formats are different
1007 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
1008 string const output_to_file = changeExtension(output_file, ext);
1010 // Do we need to perform the conversion?
1011 // Yes if to_file does not exist or if temp_file is newer than to_file
1012 if (compare_timestamps(temp_file, to_file) < 0) {
1014 LYXERR(Debug::GRAPHICS,
1015 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
1016 from_utf8(orig_file))));
1017 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
1018 return output_to_file;
1021 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
1022 << "\tA copy has been made and convert is to be called with:\n"
1023 << "\tfile to convert = " << temp_file << '\n'
1024 << "\t from " << from << " to " << to);
1026 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
1028 Converters::RetVal const rv =
1029 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
1030 from, to, el, Converters::try_default | Converters::try_cache);
1031 if (rv == Converters::KILLED) {
1032 if (buffer().isClone() && buffer().isExporting())
1033 throw ConversionException();
1036 if (rv != Converters::SUCCESS)
1038 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
1039 return output_to_file;
1043 CtObject InsetGraphics::getCtObject(OutputParams const &) const
1045 return CtObject::Object;
1049 docstring InsetGraphics::xhtml(XMLStream & xs, OutputParams const & op) const
1051 string const output_file = op.dryrun ? string() : prepareHTMLFile(op);
1053 if (output_file.empty() && !op.dryrun) {
1054 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
1055 << params().filename << "' for output. File missing?");
1056 string const attr = "src='" + params().filename.absFileName()
1057 + "' alt='image: " + output_file + "'";
1058 xs << xml::CompTag("img", attr);
1063 // We aren't doing anything with the crop and rotate parameters, and it would
1064 // really be better to do width and height conversion, rather than to output
1065 // these parameters here.
1067 bool const havewidth = !params().width.zero();
1068 bool const haveheight = !params().height.zero();
1069 if (havewidth || haveheight) {
1071 imgstyle += "width:" + params().width.asHTMLString() + ";";
1073 imgstyle += " height:" + params().height.asHTMLString() + ";";
1074 } else if (params().scale != "100") {
1075 // Note that this will not have the same effect as in LaTeX export:
1076 // There, the image will be scaled from its original size. Here, the
1077 // percentage will be interpreted by the browser, and the image will
1078 // be scaled to a percentage of the window size.
1079 imgstyle = "width:" + params().scale + "%;";
1081 if (!imgstyle.empty())
1082 imgstyle = "style='" + imgstyle + "' ";
1084 string const attr = imgstyle + "src='" + output_file + "' alt='image: "
1085 + output_file + "'";
1086 xs << xml::CompTag("img", attr);
1091 void InsetGraphics::validate(LaTeXFeatures & features) const
1093 // If we have no image, we should not require anything.
1094 if (params().filename.empty())
1097 features.includeFile(graphic_label,
1098 removeExtension(params().filename.absFileName()));
1100 features.require("graphicx");
1102 if (features.runparams().nice) {
1103 string const rel_file = params().filename.onlyFileNameWithoutExt();
1104 if (contains(rel_file, "."))
1105 features.require("lyxdot");
1107 if (features.inDeletedInset()) {
1108 features.require("tikz");
1109 features.require("ct-tikz-object-sout");
1114 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1116 // If nothing is changed, just return and say so.
1117 if (params() == p && !p.filename.empty())
1120 // Copy the new parameters.
1123 // Update the display using the new parameters.
1124 graphic_->update(params().as_grfxParams());
1126 // We have changed data, report it.
1131 InsetGraphicsParams const & InsetGraphics::params() const
1137 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1139 theFormats().edit(buffer(), p.filename,
1140 theFormats().getFormatFromFile(p.filename));
1144 void InsetGraphics::addToToc(DocIterator const & cpit, bool output_active,
1145 UpdateType, TocBackend & backend) const
1148 docstring const str = from_utf8(params_.filename.onlyFileName());
1149 TocBuilder & b = backend.builder("graphics");
1150 b.pushItem(cpit, str, output_active);
1155 string InsetGraphics::contextMenuName() const
1157 return "context-graphics";
1161 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1162 InsetGraphicsParams & params)
1167 istringstream data(in);
1169 lex.setStream(data);
1170 lex.setContext("InsetGraphics::string2params");
1172 params = InsetGraphicsParams();
1173 readInsetGraphics(lex, buffer, false, params);
1177 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1178 Buffer const & buffer)
1181 data << "graphics" << ' ';
1182 params.Write(data, buffer);
1183 data << "\\end_inset\n";
1188 docstring InsetGraphics::toolTip(BufferView const &, int, int) const
1190 return from_utf8(params().filename.onlyFileName());
1193 namespace graphics {
1195 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1197 for (Inset const & it : b.inset()) {
1198 InsetGraphics const * ins = it.asInsetGraphics();
1201 InsetGraphicsParams const & inspar = ins->getParams();
1202 if (!inspar.groupId.empty())
1203 ids.insert(inspar.groupId);
1208 int countGroupMembers(Buffer const & b, string const & groupId)
1211 if (groupId.empty())
1213 for (Inset const & it : b.inset()) {
1214 InsetGraphics const * ins = it.asInsetGraphics();
1217 if (ins->getParams().groupId == groupId)
1224 string getGroupParams(Buffer const & b, string const & groupId)
1226 if (groupId.empty())
1228 for (Inset const & it : b.inset()) {
1229 InsetGraphics const * ins = it.asInsetGraphics();
1232 InsetGraphicsParams const & inspar = ins->getParams();
1233 if (inspar.groupId == groupId) {
1234 InsetGraphicsParams tmp = inspar;
1235 tmp.filename.erase();
1236 return InsetGraphics::params2string(tmp, b);
1243 void unifyGraphicsGroups(Buffer & b, string const & argument)
1245 InsetGraphicsParams params;
1246 InsetGraphics::string2params(argument, b, params);
1248 // This handles undo groups automagically
1249 UndoGroupHelper ugh(&b);
1250 Inset & inset = b.inset();
1251 InsetIterator it = begin(inset);
1252 InsetIterator const itend = end(inset);
1253 for (; it != itend; ++it) {
1254 InsetGraphics * ins = it->asInsetGraphics();
1257 InsetGraphicsParams const & inspar = ins->getParams();
1258 if (params.groupId == inspar.groupId) {
1259 CursorData(it).recordUndo();
1260 params.filename = inspar.filename;
1261 ins->setParams(params);
1267 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1269 Inset * instmp = &cur.inset();
1270 if (!instmp->asInsetGraphics())
1271 instmp = cur.nextInset();
1272 if (!instmp || !instmp->asInsetGraphics())
1275 return instmp->asInsetGraphics();
1278 } // namespace graphics