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"
67 #include "MetricsInfo.h"
69 #include "OutputParams.h"
70 #include "output_xhtml.h"
72 #include "texstream.h"
73 #include "TocBackend.h"
75 #include "frontends/alert.h"
76 #include "frontends/Application.h"
78 #include "graphics/GraphicsCache.h"
79 #include "graphics/GraphicsCacheItem.h"
80 #include "graphics/GraphicsImage.h"
82 #include "support/convert.h"
83 #include "support/debug.h"
84 #include "support/docstream.h"
85 #include "support/ExceptionMessage.h"
86 #include "support/filetools.h"
87 #include "support/gettext.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"
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 == OutputParams::PDFLATEX
115 || runparams.flavor == OutputParams::XETEX
116 || runparams.flavor == OutputParams::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
128 // for HTML, we leave the known formats and otherwise convert to png
129 if (runparams.flavor == OutputParams::HTML) {
130 Format const * const f = theFormats().getFormat(format);
131 // Convert vector graphics to svg
132 if (f && f->vectorFormat() && theConverters().isReachable(format, "svg"))
134 // Leave the known formats alone
135 if (format == "jpg" || format == "png" || format == "gif")
137 // Convert everything else to png
140 // If it's postscript, we always do eps.
141 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
143 // any other than ps is changed to eps
150 void readInsetGraphics(Lexer & lex, Buffer const & buf, bool allowOrigin,
151 InsetGraphicsParams & params)
153 bool finished = false;
155 while (lex.isOK() && !finished) {
158 string const token = lex.getString();
159 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
164 if (token == "\\end_inset") {
167 if (!params.Read(lex, token, buf, allowOrigin))
168 lyxerr << "Unknown token, "
179 InsetGraphics::InsetGraphics(Buffer * buf)
180 : Inset(buf), graphic_label(xml::uniqueID(from_ascii("graph"))),
181 graphic_(new RenderGraphic(this))
186 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
188 graphic_label(xml::uniqueID(from_ascii("graph"))),
189 graphic_(new RenderGraphic(*ig.graphic_, this))
191 setParams(ig.params());
195 Inset * InsetGraphics::clone() const
197 return new InsetGraphics(*this);
201 InsetGraphics::~InsetGraphics()
203 hideDialogs("graphics", this);
208 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
210 switch (cmd.action()) {
211 case LFUN_INSET_EDIT: {
212 InsetGraphicsParams p = params();
213 if (!cmd.argument().empty())
214 string2params(to_utf8(cmd.argument()), buffer(), p);
219 case LFUN_INSET_MODIFY: {
220 if (cmd.getArg(0) != "graphics") {
221 Inset::doDispatch(cur, cmd);
225 InsetGraphicsParams p;
226 string2params(to_utf8(cmd.argument()), buffer(), p);
227 if (p.filename.empty()) {
228 cur.noScreenUpdate();
234 // if the inset is part of a graphics group, all the
235 // other members should be updated too.
236 if (!params_.groupId.empty())
237 graphics::unifyGraphicsGroups(buffer(),
238 to_utf8(cmd.argument()));
242 case LFUN_INSET_DIALOG_UPDATE:
243 cur.bv().updateDialog("graphics", params2string(params(), buffer()));
246 case LFUN_GRAPHICS_RELOAD:
247 params_.filename.refresh();
252 Inset::doDispatch(cur, cmd);
258 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
259 FuncStatus & flag) const
261 switch (cmd.action()) {
262 case LFUN_INSET_MODIFY:
263 if (cmd.getArg(0) != "graphics")
264 return Inset::getStatus(cur, cmd, flag);
266 case LFUN_INSET_EDIT:
267 case LFUN_INSET_DIALOG_UPDATE:
268 case LFUN_GRAPHICS_RELOAD:
269 flag.setEnabled(true);
273 return Inset::getStatus(cur, cmd, flag);
278 bool InsetGraphics::showInsetDialog(BufferView * bv) const
280 bv->showDialog("graphics", params2string(params(), bv->buffer()),
281 const_cast<InsetGraphics *>(this));
287 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
289 graphic_->metrics(mi, dim);
293 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
295 graphic_->draw(pi, x, y);
299 void InsetGraphics::write(ostream & os) const
302 params().Write(os, buffer());
306 void InsetGraphics::read(Lexer & lex)
308 lex.setContext("InsetGraphics::read");
310 readInsetGraphics(lex, buffer(), true, params_);
311 graphic_->update(params().as_grfxParams());
315 void InsetGraphics::outBoundingBox(graphics::BoundingBox & bbox) const
320 FileName const file(params().filename.absFileName());
322 // No correction is necessary for a postscript image
323 bool const zipped = theFormats().isZippedFile(file);
324 FileName const unzipped_file = zipped ? unzipFile(file) : file;
325 string const format = theFormats().getFormatFromFile(unzipped_file);
327 unzipped_file.removeFile();
328 if (Formats::isPostScriptFileFormat(format))
331 // Get the actual image dimensions in pixels
334 graphics::Cache & gc = graphics::Cache::get();
335 if (gc.inCache(file)) {
336 graphics::Image const * image = gc.item(file)->image();
338 width = image->width();
339 height = image->height();
342 if (width == 0 || height == 0)
345 // Use extractbb to find the dimensions in the typeset output
347 extractbb.start("extractbb", QStringList() << "-O" << toqstr(file.absFileName()));
348 if (!extractbb.waitForStarted() || !extractbb.waitForFinished()) {
349 LYXERR0("Cannot read output bounding box of " << file);
353 string const result = extractbb.readAll().constData();
354 size_t i = result.find("%%BoundingBox:");
355 if (i == string::npos) {
356 LYXERR0("Cannot find output bounding box of " << file);
360 string const bb = result.substr(i);
361 int out_width = convert<int>(token(bb, ' ', 3));
362 int out_height = convert<int>(token(bb, ' ', 4));
364 // Compute the scaling ratio and correct the bounding box
365 double scalex = out_width / double(width);
366 double scaley = out_height / double(height);
368 bbox.xl.value(scalex * bbox.xl.value());
369 bbox.xr.value(scalex * bbox.xr.value());
370 bbox.yb.value(scaley * bbox.yb.value());
371 bbox.yt.value(scaley * bbox.yt.value());
375 string InsetGraphics::createLatexOptions(bool const ps) const
377 // Calculate the options part of the command, we must do it to a string
378 // stream since we might have a trailing comma that we would like to remove
379 // before writing it to the output stream.
380 ostringstream options;
381 if (!params().bbox.empty()) {
382 graphics::BoundingBox out_bbox = params().bbox;
383 outBoundingBox(out_bbox);
384 string const key = ps ? "bb=" : "viewport=";
385 options << key << out_bbox.xl.asLatexString() << ' '
386 << out_bbox.yb.asLatexString() << ' '
387 << out_bbox.xr.asLatexString() << ' '
388 << out_bbox.yt.asLatexString() << ',';
395 double const scl = convert<double>(params().scale);
396 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
397 if (!float_equal(scl, 100.0, 0.05))
398 size << "scale=" << scl / 100.0 << ',';
400 if (!params().width.zero())
401 size << "width=" << params().width.asLatexString() << ',';
402 if (!params().height.zero())
403 size << "totalheight=" << params().height.asLatexString() << ',';
404 if (params().keepAspectRatio)
405 size << "keepaspectratio,";
407 if (params().scaleBeforeRotation && !size.str().empty())
408 options << size.str();
410 // Make sure rotation angle is not very close to zero;
411 // a float can be effectively zero but not exactly zero.
412 if (!params().rotateAngle.empty()
413 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
414 options << "angle=" << params().rotateAngle << ',';
415 if (!params().rotateOrigin.empty()) {
416 options << "origin=" << params().rotateOrigin[0];
417 if (contains(params().rotateOrigin,"Top"))
419 else if (contains(params().rotateOrigin,"Bottom"))
421 else if (contains(params().rotateOrigin,"Baseline"))
426 if (!params().scaleBeforeRotation && !size.str().empty())
427 options << size.str();
429 if (!params().special.empty())
430 options << params().special << ',';
432 string opts = options.str();
434 if (suffixIs(opts, ','))
435 opts = opts.substr(0, opts.size() - 1);
441 docstring InsetGraphics::toDocbookLength(Length const & len) const
443 odocstringstream result;
444 switch (len.unit()) {
445 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
446 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
448 case Length::PT: // Point = 1/72.27in = 0.351mm
449 result << len.value() * 72 / 72.27 << "pt";
451 case Length::BP: // Big point (72bp = 1in), also PostScript point
452 result << len.value() << "pt";
454 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
455 result << len.value() * 0.376 << "mm";
457 case Length::MM: // Millimeter = 2.845pt
458 result << len.value() << "mm";
460 case Length::PC: // Pica = 12pt = 4.218mm
461 result << len.value() << "pc";
463 case Length::CC: // Cicero = 12dd = 4.531mm
464 result << len.value() * 4.531 << "mm";
466 case Length::CM: // Centimeter = 10mm = 2.371pc
467 result << len.value() << "cm";
469 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
470 result << len.value() << "in";
472 case Length::EX: // Height of a small "x" for the current font.
473 // Obviously we have to compromise here. Any better ratio than 1.5 ?
474 result << len.value() / 1.5 << "em";
476 case Length::EM: // Width of capital "M" in current font.
477 result << len.value() << "em";
479 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
480 result << len.value() * 18 << "em";
482 case Length::PTW: // Percent of TextWidth
483 case Length::PCW: // Percent of ColumnWidth
484 case Length::PPW: // Percent of PageWidth
485 case Length::PLW: // Percent of LineWidth
486 case Length::PTH: // Percent of TextHeight
487 case Length::PPH: // Percent of PaperHeight
488 case Length::BLS: // Percent of BaselineSkip
489 // Sigh, this will go wrong.
490 result << len.value() << "%";
493 result << len.asDocstring();
500 docstring InsetGraphics::createDocBookAttributes() const
502 // Calculate the options part of the command, we must do it to a string
503 // stream since we copied the code from createLatexParams() ;-)
505 odocstringstream options;
506 double const scl = convert<double>(params().scale);
507 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
508 if (!float_equal(scl, 100.0, 0.05))
509 options << " scale=\""
510 << support::iround(scl)
513 if (!params().width.zero()) {
514 options << " width=\"" << toDocbookLength(params().width) << "\" ";
516 if (!params().height.zero()) {
517 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
519 if (params().keepAspectRatio) {
520 // This will be irrelevant unless both width and height are set
521 options << "scalefit=\"1\" ";
526 if (!params().special.empty())
527 options << from_ascii(params().special) << " ";
529 // trailing blanks are ok ...
530 return options.str();
536 enum GraphicsCopyStatus {
544 pair<GraphicsCopyStatus, FileName> const
545 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
547 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
548 unsigned long const checksum_in = file_in.checksum();
549 unsigned long const checksum_out = file_out.checksum();
551 if (checksum_in == checksum_out)
553 return make_pair(IDENTICAL_CONTENTS, file_out);
555 Mover const & mover = getMover(theFormats().getFormatFromFile(file_in));
556 bool const success = mover.copy(file_in, file_out);
559 LYXERR(Debug::GRAPHICS,
560 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
561 "into the temporary directory."),
562 from_utf8(file_in.absFileName()))));
565 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
566 return make_pair(status, file_out);
570 pair<GraphicsCopyStatus, FileName> const
571 copyToDirIfNeeded(DocFileName const & file, string const & dir)
573 string const file_in = file.absFileName();
574 string const only_path = onlyPath(file_in);
575 if (rtrim(only_path, "/") == rtrim(dir, "/"))
576 return make_pair(IDENTICAL_PATHS, FileName(file_in));
578 string mangled = file.mangledFileName();
579 if (theFormats().isZippedFile(file)) {
580 // We need to change _eps.gz to .eps.gz. The mangled name is
581 // still unique because of the counter in mangledFileName().
582 // We can't just call mangledFileName() with the zip
583 // extension removed, because base.eps and base.eps.gz may
584 // have different content but would get the same mangled
585 // name in this case.
586 // Also take into account that if the name of the zipped file
587 // has no zip extension then the name of the unzipped one is
588 // prefixed by "unzipped_".
589 string const base = removeExtension(file.unzippedFileName());
590 string::size_type const prefix_len =
591 prefixIs(onlyFileName(base), "unzipped_") ? 9 : 0;
592 string::size_type const ext_len =
593 file_in.length() + prefix_len - base.length();
594 mangled[mangled.length() - ext_len] = '.';
596 FileName const file_out(makeAbsPath(mangled, dir));
598 return copyFileIfNeeded(file, file_out);
602 string const stripExtensionIfPossible(string const & file, bool nice)
604 // Remove the extension so the LaTeX compiler will use whatever
605 // is appropriate (when there are several versions in different
607 // Do this only if we are not exporting for internal usage, because
608 // pdflatex prefers png over pdf and it would pick up the png images
609 // that we generate for preview.
610 // This works only if the filename contains no dots besides
611 // the just removed one. We can fool here by replacing all
612 // dots with a macro whose definition is just a dot ;-)
613 // The automatic format selection does not work if the file
615 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
616 if (!nice || contains(latex_name, '"'))
618 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
622 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
624 // No conversion is needed. LaTeX can handle the graphic file as is.
625 // This is true even if the orig_file is compressed.
626 Format const * f = theFormats().getFormat(to);
628 return latex_path(file, EXCLUDE_EXTENSION);
629 string const to_format = f->extension();
630 string const file_format = getExtension(file);
631 // for latex .ps == .eps
632 if (to_format == file_format ||
633 (to_format == "eps" && file_format == "ps") ||
634 (to_format == "ps" && file_format == "eps"))
635 return stripExtensionIfPossible(file, nice);
636 return latex_path(file, EXCLUDE_EXTENSION);
642 string InsetGraphics::prepareFile(OutputParams const & runparams) const
644 // The following code depends on non-empty filenames
645 if (params().filename.empty())
648 string const orig_file = params().filename.absFileName();
649 // this is for dryrun and display purposes, do not use latexFilename
650 string const rel_file = params().filename.relFileName(buffer().filePath());
652 // previewing source code, no file copying or file format conversion
653 if (runparams.dryrun)
654 return stripExtensionIfPossible(rel_file, runparams.nice);
656 // The master buffer. This is useful when there are multiple levels
658 Buffer const * masterBuffer = buffer().masterBuffer();
660 // Return the output name if we are inside a comment or the file does
662 // We are not going to change the extension or using the name of the
663 // temporary file, the code is already complicated enough.
664 if (runparams.inComment || !params().filename.isReadableFile())
665 return params().filename.outputFileName(masterBuffer->filePath());
667 // We place all temporary files in the master buffer's temp dir.
668 // This is possible because we use mangled file names.
669 // This is necessary for DVI export.
670 string const temp_path = masterBuffer->temppath();
672 // temp_file will contain the file for LaTeX to act on if, for example,
673 // we move it to a temp dir or uncompress it.
675 GraphicsCopyStatus status;
676 tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
678 if (status == FAILURE)
681 // a relative filename should be relative to the master buffer.
682 // "nice" means that the buffer is exported to LaTeX format but not
683 // run through the LaTeX compiler.
684 string output_file = runparams.nice ?
685 params().filename.outputFileName(masterBuffer->filePath()) :
686 onlyFileName(temp_file.absFileName());
688 if (runparams.nice) {
689 if (!isValidLaTeXFileName(output_file)) {
690 frontend::Alert::warning(_("Invalid filename"),
691 _("The following filename will cause troubles "
692 "when running the exported file through LaTeX: ") +
693 from_utf8(output_file));
695 // only show DVI-specific warning when export format is plain latex
696 if (!isValidDVIFileName(output_file)
697 && runparams.flavor == OutputParams::LATEX) {
698 frontend::Alert::warning(_("Problematic filename for DVI"),
699 _("The following filename can cause troubles "
700 "when running the exported file through LaTeX "
701 "and opening the resulting DVI: ") +
702 from_utf8(output_file), true);
706 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
707 // determine the export format
708 string const tex_format = flavor2format(runparams.flavor);
710 if (theFormats().isZippedFile(params().filename)) {
711 FileName const unzipped_temp_file =
712 FileName(unzippedFileName(temp_file.absFileName()));
713 output_file = unzippedFileName(output_file);
714 source_file = FileName(unzippedFileName(source_file.absFileName()));
715 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
716 // temp_file has been unzipped already and
717 // orig_file has not changed in the meantime.
718 temp_file = unzipped_temp_file;
719 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
721 // unzipped_temp_file does not exist or is too old
722 temp_file = unzipFile(temp_file);
723 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
727 string const from = theFormats().getFormatFromFile(temp_file);
729 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
731 string const to = findTargetFormat(from, runparams);
732 string const ext = theFormats().extension(to);
733 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
735 // We're going to be running the exported buffer through the LaTeX
736 // compiler, so must ensure that LaTeX can cope with the graphics
739 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
742 // source and destination formats are the same
743 if (!runparams.nice && !FileName(temp_file).hasExtension(ext)) {
744 // The LaTeX compiler will not be able to determine
745 // the file format from the extension, so we must
747 FileName const new_file =
748 FileName(changeExtension(temp_file.absFileName(), ext));
749 if (temp_file.moveTo(new_file)) {
750 temp_file = new_file;
751 output_file = changeExtension(output_file, ext);
753 FileName(changeExtension(source_file.absFileName(), ext));
755 LYXERR(Debug::GRAPHICS, "Could not rename file `"
756 << temp_file << "' to `" << new_file << "'.");
759 // The extension of temp_file might be != ext!
760 runparams.exportdata->addExternalFile(tex_format, source_file,
762 runparams.exportdata->addExternalFile("dvi", source_file,
764 return stripExtensionIfPossible(output_file, to, runparams.nice);
767 // so the source and destination formats are different
768 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
769 string const output_to_file = changeExtension(output_file, ext);
771 // Do we need to perform the conversion?
772 // Yes if to_file does not exist or if temp_file is newer than to_file
773 if (compare_timestamps(temp_file, to_file) < 0) {
775 LYXERR(Debug::GRAPHICS,
776 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
777 from_utf8(rel_file))));
778 runparams.exportdata->addExternalFile(tex_format, to_file,
780 runparams.exportdata->addExternalFile("dvi", to_file,
782 return stripExtensionIfPossible(output_to_file, runparams.nice);
785 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
786 << "\tA copy has been made and convert is to be called with:\n"
787 << "\tfile to convert = " << temp_file << '\n'
788 << "\t from " << from << " to " << to);
790 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
792 Converters::RetVal const rv =
793 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
795 Converters::try_default | Converters::try_cache);
796 if (rv == Converters::KILLED) {
797 LYXERR0("Graphics preparation killed.");
798 if (buffer().isClone() && buffer().isExporting())
799 throw ConversionException();
800 } else if (rv == Converters::SUCCESS) {
801 runparams.exportdata->addExternalFile(tex_format,
802 to_file, output_to_file);
803 runparams.exportdata->addExternalFile("dvi",
804 to_file, output_to_file);
807 return stripExtensionIfPossible(output_to_file, runparams.nice);
811 void InsetGraphics::latex(otexstream & os,
812 OutputParams const & runparams) const
814 // If there is no file specified or not existing,
815 // just output a message about it in the latex output.
816 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
817 << params().filename.absFileName());
819 bool const file_exists = !params().filename.empty()
820 && params().filename.isReadableFile();
823 if (params().bbox.empty())
824 message = "bb = 0 0 200 100";
825 if (!params().draft) {
826 if (!message.empty())
830 if (!message.empty())
832 message += "type=eps";
834 // If no existing file "filename" was found LaTeX
835 // draws only a rectangle with the above bb and the
836 // not found filename in it.
837 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
839 // These variables collect all the latex code that should be before and
840 // after the actual includegraphics command.
844 // Write the options if there are any.
845 bool const ps = runparams.flavor == OutputParams::LATEX
846 || runparams.flavor == OutputParams::DVILUATEX;
847 string const opts = createLatexOptions(ps);
848 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
850 if (contains(opts, '=') && contains(runparams.active_chars, '=')) {
851 // We have a language that makes = active. Deactivate locally
852 // for keyval option parsing (#2005).
853 before = "\\begingroup\\catcode`\\=12";
854 after = "\\endgroup ";
857 if (runparams.moving_arg)
858 before += "\\protect";
860 // We never use the starred form, we use the "clip" option instead.
861 before += "\\includegraphics";
863 if (!opts.empty() && !message.empty())
864 before += ('[' + opts + ',' + message + ']');
865 else if (!opts.empty() || !message.empty())
866 before += ('[' + opts + message + ']');
868 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
870 string latex_str = before + '{';
871 // Convert the file if necessary.
872 // Remove the extension so LaTeX will use whatever is appropriate
873 // (when there are several versions in different formats)
874 docstring file_path = from_utf8(prepareFile(runparams));
875 // we can only output characters covered by the current
878 docstring encodable_file_path;
879 for (size_type i = 0 ; i < file_path.size() ; ++i) {
880 char_type c = file_path[i];
882 if (runparams.encoding->encodable(c))
883 encodable_file_path += c;
884 else if (runparams.dryrun) {
885 encodable_file_path += "<" + _("LyX Warning: ")
886 + _("uncodable character") + " '";
887 encodable_file_path += docstring(1, c);
888 encodable_file_path += "'>";
891 } catch (EncodingException & /* e */) {
892 if (runparams.dryrun) {
893 encodable_file_path += "<" + _("LyX Warning: ")
894 + _("uncodable character") + " '";
895 encodable_file_path += docstring(1, c);
896 encodable_file_path += "'>";
901 if (!uncodable.empty() && !runparams.silent) {
902 // issue a warning about omitted characters
903 // FIXME: should be passed to the error dialog
904 frontend::Alert::warning(_("Uncodable character in file path"),
905 bformat(_("The following characters in one of the graphic paths are\n"
906 "not representable in the current encoding and have been omitted: %1$s.\n"
907 "You need to adapt either the encoding or the path."),
910 latex_str += to_utf8(encodable_file_path);
911 latex_str += '}' + after;
913 os << from_utf8(latex_str);
915 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
919 int InsetGraphics::plaintext(odocstringstream & os,
920 OutputParams const &, size_t) const
922 // No graphics in ascii output. Possible to use gifscii to convert
923 // images to ascii approximation.
924 // 1. Convert file to ascii using gifscii
925 // 2. Read ascii output file and add it to the output stream.
926 // at least we send the filename
928 // FIXME: We have no idea what the encoding of the filename is
930 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
931 from_utf8(params().filename.absFileName()));
932 os << '<' << str << '>';
934 return 2 + str.size();
938 static int writeImageObject(char const * format, odocstream & os,
939 OutputParams const & runparams, docstring const & graphic_label,
940 docstring const & attributes)
942 if (runparams.flavor != OutputParams::XML)
943 os << "<![ %output.print." << format
946 os <<"<imageobject><imagedata fileref=\"&"
953 if (runparams.flavor == OutputParams::XML)
954 os << " role=\"" << format << "\"/>" ;
956 os << " format=\"" << format << "\">" ;
958 os << "</imageobject>";
960 if (runparams.flavor != OutputParams::XML)
961 os << endl << "]]>" ;
963 return runparams.flavor == OutputParams::XML ? 0 : 2;
967 // For explanation on inserting graphics into DocBook checkout:
968 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
969 // See also the docbook guide at http://www.docbook.org/
970 int InsetGraphics::docbook(odocstream & os,
971 OutputParams const & runparams) const
973 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
974 // need to switch to MediaObject. However, for now this is sufficient and
976 if (runparams.flavor == OutputParams::XML)
977 runparams.exportdata->addExternalFile("docbook-xml",
980 runparams.exportdata->addExternalFile("docbook",
983 os << "<inlinemediaobject>";
986 docstring attributes = createDocBookAttributes();
987 r += writeImageObject("png", os, runparams, graphic_label, attributes);
988 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
989 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
990 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
992 os << "</inlinemediaobject>";
997 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
999 // The following code depends on non-empty filenames
1000 if (params().filename.empty())
1003 if (!params().filename.isReadableFile())
1006 // The master buffer. This is useful when there are multiple levels
1008 Buffer const * masterBuffer = buffer().masterBuffer();
1010 // We place all temporary files in the master buffer's temp dir.
1011 // This is possible because we use mangled file names.
1012 // FIXME We may want to put these files in some special temporary
1014 string const temp_path = masterBuffer->temppath();
1016 // Copy to temporary directory.
1018 GraphicsCopyStatus status;
1019 tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
1021 if (status == FAILURE)
1024 string const from = theFormats().getFormatFromFile(temp_file);
1026 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
1030 string const to = findTargetFormat(from, runparams);
1031 string const ext = theFormats().extension(to);
1032 string const orig_file = params().filename.absFileName();
1033 string output_file = onlyFileName(temp_file.absFileName());
1034 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
1035 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
1038 // source and destination formats are the same
1039 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
1043 // so the source and destination formats are different
1044 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
1045 string const output_to_file = changeExtension(output_file, ext);
1047 // Do we need to perform the conversion?
1048 // Yes if to_file does not exist or if temp_file is newer than to_file
1049 if (compare_timestamps(temp_file, to_file) < 0) {
1051 LYXERR(Debug::GRAPHICS,
1052 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
1053 from_utf8(orig_file))));
1054 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
1055 return output_to_file;
1058 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
1059 << "\tA copy has been made and convert is to be called with:\n"
1060 << "\tfile to convert = " << temp_file << '\n'
1061 << "\t from " << from << " to " << to);
1063 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
1065 Converters::RetVal const rv =
1066 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
1067 from, to, el, Converters::try_default | Converters::try_cache);
1068 if (rv == Converters::KILLED) {
1069 if (buffer().isClone() && buffer().isExporting())
1070 throw ConversionException();
1073 if (rv != Converters::SUCCESS)
1075 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
1076 return output_to_file;
1080 docstring InsetGraphics::xhtml(XMLStream & xs, OutputParams const & op) const
1082 string const output_file = op.dryrun ? string() : prepareHTMLFile(op);
1084 if (output_file.empty() && !op.dryrun) {
1085 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
1086 << params().filename << "' for output. File missing?");
1087 string const attr = "src='" + params().filename.absFileName()
1088 + "' alt='image: " + output_file + "'";
1089 xs << xml::CompTag("img", attr);
1094 // We aren't doing anything with the crop and rotate parameters, and it would
1095 // really be better to do width and height conversion, rather than to output
1096 // these parameters here.
1098 bool const havewidth = !params().width.zero();
1099 bool const haveheight = !params().height.zero();
1100 if (havewidth || haveheight) {
1102 imgstyle += "width:" + params().width.asHTMLString() + ";";
1104 imgstyle += " height:" + params().height.asHTMLString() + ";";
1105 } else if (params().scale != "100") {
1106 // Note that this will not have the same effect as in LaTeX export:
1107 // There, the image will be scaled from its original size. Here, the
1108 // percentage will be interpreted by the browser, and the image will
1109 // be scaled to a percentage of the window size.
1110 imgstyle = "width:" + params().scale + "%;";
1112 if (!imgstyle.empty())
1113 imgstyle = "style='" + imgstyle + "' ";
1115 string const attr = imgstyle + "src='" + output_file + "' alt='image: "
1116 + output_file + "'";
1117 xs << xml::CompTag("img", attr);
1122 void InsetGraphics::validate(LaTeXFeatures & features) const
1124 // If we have no image, we should not require anything.
1125 if (params().filename.empty())
1128 features.includeFile(graphic_label,
1129 removeExtension(params().filename.absFileName()));
1131 features.require("graphicx");
1133 if (features.runparams().nice) {
1134 string const rel_file = params().filename.onlyFileNameWithoutExt();
1135 if (contains(rel_file, "."))
1136 features.require("lyxdot");
1138 if (features.inDeletedInset()) {
1139 features.require("tikz");
1140 features.require("ct-tikz-object-sout");
1145 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1147 // If nothing is changed, just return and say so.
1148 if (params() == p && !p.filename.empty())
1151 // Copy the new parameters.
1154 // Update the display using the new parameters.
1155 graphic_->update(params().as_grfxParams());
1157 // We have changed data, report it.
1162 InsetGraphicsParams const & InsetGraphics::params() const
1168 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1170 theFormats().edit(buffer(), p.filename,
1171 theFormats().getFormatFromFile(p.filename));
1175 void InsetGraphics::addToToc(DocIterator const & cpit, bool output_active,
1176 UpdateType, TocBackend & backend) const
1179 docstring const str = from_utf8(params_.filename.onlyFileName());
1180 TocBuilder & b = backend.builder("graphics");
1181 b.pushItem(cpit, str, output_active);
1186 string InsetGraphics::contextMenuName() const
1188 return "context-graphics";
1192 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1193 InsetGraphicsParams & params)
1198 istringstream data(in);
1200 lex.setStream(data);
1201 lex.setContext("InsetGraphics::string2params");
1203 params = InsetGraphicsParams();
1204 readInsetGraphics(lex, buffer, false, params);
1208 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1209 Buffer const & buffer)
1212 data << "graphics" << ' ';
1213 params.Write(data, buffer);
1214 data << "\\end_inset\n";
1219 docstring InsetGraphics::toolTip(BufferView const &, int, int) const
1221 return from_utf8(params().filename.onlyFileName());
1224 namespace graphics {
1226 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1228 Inset & inset = b.inset();
1229 InsetIterator it = inset_iterator_begin(inset);
1230 InsetIterator const end = inset_iterator_end(inset);
1231 for (; it != end; ++it) {
1232 InsetGraphics const * ins = it->asInsetGraphics();
1235 InsetGraphicsParams const & inspar = ins->getParams();
1236 if (!inspar.groupId.empty())
1237 ids.insert(inspar.groupId);
1242 int countGroupMembers(Buffer const & b, string const & groupId)
1245 if (groupId.empty())
1247 Inset & inset = b.inset();
1248 InsetIterator it = inset_iterator_begin(inset);
1249 InsetIterator const end = inset_iterator_end(inset);
1250 for (; it != end; ++it) {
1251 InsetGraphics const * ins = it->asInsetGraphics();
1254 if (ins->getParams().groupId == groupId)
1261 string getGroupParams(Buffer const & b, string const & groupId)
1263 if (groupId.empty())
1265 Inset & inset = b.inset();
1266 InsetIterator it = inset_iterator_begin(inset);
1267 InsetIterator const end = inset_iterator_end(inset);
1268 for (; it != end; ++it) {
1269 InsetGraphics const * ins = it->asInsetGraphics();
1272 InsetGraphicsParams const & inspar = ins->getParams();
1273 if (inspar.groupId == groupId) {
1274 InsetGraphicsParams tmp = inspar;
1275 tmp.filename.erase();
1276 return InsetGraphics::params2string(tmp, b);
1283 void unifyGraphicsGroups(Buffer & b, string const & argument)
1285 InsetGraphicsParams params;
1286 InsetGraphics::string2params(argument, b, params);
1288 // This handles undo groups automagically
1289 UndoGroupHelper ugh(&b);
1290 Inset & inset = b.inset();
1291 InsetIterator it = inset_iterator_begin(inset);
1292 InsetIterator const end = inset_iterator_end(inset);
1293 for (; it != end; ++it) {
1294 InsetGraphics * ins = it->asInsetGraphics();
1297 InsetGraphicsParams const & inspar = ins->getParams();
1298 if (params.groupId == inspar.groupId) {
1299 CursorData(it).recordUndo();
1300 params.filename = inspar.filename;
1301 ins->setParams(params);
1307 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1309 Inset * instmp = &cur.inset();
1310 if (!instmp->asInsetGraphics())
1311 instmp = cur.nextInset();
1312 if (!instmp || !instmp->asInsetGraphics())
1315 return instmp->asInsetGraphics();
1318 } // namespace graphics