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"
65 #include "LaTeXFeatures.h"
68 #include "MetricsInfo.h"
70 #include "OutputParams.h"
71 #include "output_xhtml.h"
73 #include "texstream.h"
74 #include "TocBackend.h"
76 #include "frontends/alert.h"
77 #include "frontends/Application.h"
79 #include "graphics/GraphicsCache.h"
80 #include "graphics/GraphicsCacheItem.h"
81 #include "graphics/GraphicsImage.h"
83 #include "support/convert.h"
84 #include "support/debug.h"
85 #include "support/docstream.h"
86 #include "support/ExceptionMessage.h"
87 #include "support/filetools.h"
88 #include "support/gettext.h"
89 #include "support/lyxlib.h"
90 #include "support/lstrings.h"
91 #include "support/os.h"
92 #include "support/qstring_helpers.h"
93 #include "support/Systemcall.h"
102 using namespace lyx::support;
106 namespace Alert = frontend::Alert;
110 /// Find the most suitable image format for images in \p format
111 /// Note that \p format may be unknown (i. e. an empty string)
112 string findTargetFormat(string const & format, OutputParams const & runparams)
114 // Are we using latex or XeTeX/LuaTeX/pdflatex?
115 if (runparams.flavor == OutputParams::PDFLATEX
116 || runparams.flavor == OutputParams::XETEX
117 || runparams.flavor == OutputParams::LUATEX) {
118 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
119 Format const * const f = theFormats().getFormat(format);
120 // Convert vector graphics to pdf
121 if (f && f->vectorFormat())
123 // pdflatex can use jpeg, png and pdf directly
126 // Convert everything else to png
129 // for HTML, we leave the known formats and otherwise convert to png
130 if (runparams.flavor == OutputParams::HTML) {
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(sgml::uniqueID(from_ascii("graph"))),
182 graphic_(new RenderGraphic(this))
187 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
189 graphic_label(sgml::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);
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 postscript 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 (Formats::isPostScriptFileFormat(format))
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 if (width == 0 || height == 0)
346 // Use extractbb to find the dimensions in the typeset output
348 extractbb.start("extractbb", QStringList() << "-O" << toqstr(file.absFileName()));
349 if (!extractbb.waitForStarted() || !extractbb.waitForFinished()) {
350 LYXERR0("Cannot read output bounding box of " << file);
354 string const result = extractbb.readAll().constData();
355 size_t i = result.find("%%BoundingBox:");
356 if (i == string::npos) {
357 LYXERR0("Cannot find output bounding box of " << file);
361 string const bb = result.substr(i);
362 int out_width = convert<int>(token(bb, ' ', 3));
363 int out_height = convert<int>(token(bb, ' ', 4));
365 // Compute the scaling ratio and correct the bounding box
366 double scalex = out_width / double(width);
367 double scaley = out_height / double(height);
369 bbox.xl.value(scalex * bbox.xl.value());
370 bbox.xr.value(scalex * bbox.xr.value());
371 bbox.yb.value(scaley * bbox.yb.value());
372 bbox.yt.value(scaley * bbox.yt.value());
376 string InsetGraphics::createLatexOptions(bool const ps) const
378 // Calculate the options part of the command, we must do it to a string
379 // stream since we might have a trailing comma that we would like to remove
380 // before writing it to the output stream.
381 ostringstream options;
382 if (!params().bbox.empty()) {
383 graphics::BoundingBox out_bbox = params().bbox;
384 outBoundingBox(out_bbox);
385 string const key = ps ? "bb=" : "viewport=";
386 options << key << out_bbox.xl.asLatexString() << ' '
387 << out_bbox.yb.asLatexString() << ' '
388 << out_bbox.xr.asLatexString() << ' '
389 << out_bbox.yt.asLatexString() << ',';
396 double const scl = convert<double>(params().scale);
397 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
398 if (!float_equal(scl, 100.0, 0.05))
399 size << "scale=" << scl / 100.0 << ',';
401 if (!params().width.zero())
402 size << "width=" << params().width.asLatexString() << ',';
403 if (!params().height.zero())
404 size << "height=" << params().height.asLatexString() << ',';
405 if (params().keepAspectRatio)
406 size << "keepaspectratio,";
408 if (params().scaleBeforeRotation && !size.str().empty())
409 options << size.str();
411 // Make sure rotation angle is not very close to zero;
412 // a float can be effectively zero but not exactly zero.
413 if (!params().rotateAngle.empty()
414 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
415 options << "angle=" << params().rotateAngle << ',';
416 if (!params().rotateOrigin.empty()) {
417 options << "origin=" << params().rotateOrigin[0];
418 if (contains(params().rotateOrigin,"Top"))
420 else if (contains(params().rotateOrigin,"Bottom"))
422 else if (contains(params().rotateOrigin,"Baseline"))
427 if (!params().scaleBeforeRotation && !size.str().empty())
428 options << size.str();
430 if (!params().special.empty())
431 options << params().special << ',';
433 string opts = options.str();
435 if (suffixIs(opts, ','))
436 opts = opts.substr(0, opts.size() - 1);
442 docstring InsetGraphics::toDocbookLength(Length const & len) const
444 odocstringstream result;
445 switch (len.unit()) {
446 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
447 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
449 case Length::PT: // Point = 1/72.27in = 0.351mm
450 result << len.value() * 72 / 72.27 << "pt";
452 case Length::BP: // Big point (72bp = 1in), also PostScript point
453 result << len.value() << "pt";
455 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
456 result << len.value() * 0.376 << "mm";
458 case Length::MM: // Millimeter = 2.845pt
459 result << len.value() << "mm";
461 case Length::PC: // Pica = 12pt = 4.218mm
462 result << len.value() << "pc";
464 case Length::CC: // Cicero = 12dd = 4.531mm
465 result << len.value() * 4.531 << "mm";
467 case Length::CM: // Centimeter = 10mm = 2.371pc
468 result << len.value() << "cm";
470 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
471 result << len.value() << "in";
473 case Length::EX: // Height of a small "x" for the current font.
474 // Obviously we have to compromise here. Any better ratio than 1.5 ?
475 result << len.value() / 1.5 << "em";
477 case Length::EM: // Width of capital "M" in current font.
478 result << len.value() << "em";
480 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
481 result << len.value() * 18 << "em";
483 case Length::PTW: // Percent of TextWidth
484 case Length::PCW: // Percent of ColumnWidth
485 case Length::PPW: // Percent of PageWidth
486 case Length::PLW: // Percent of LineWidth
487 case Length::PTH: // Percent of TextHeight
488 case Length::PPH: // Percent of PaperHeight
489 case Length::BLS: // Percent of BaselineSkip
490 // Sigh, this will go wrong.
491 result << len.value() << "%";
494 result << len.asDocstring();
501 docstring InsetGraphics::createDocBookAttributes() const
503 // Calculate the options part of the command, we must do it to a string
504 // stream since we copied the code from createLatexParams() ;-)
506 // FIXME: av: need to translate spec -> Docbook XSL spec
507 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
508 // Right now it only works with my version of db2latex :-)
510 odocstringstream options;
511 double const scl = convert<double>(params().scale);
512 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
513 if (!float_equal(scl, 100.0, 0.05))
514 options << " scale=\""
515 << support::iround(scl)
518 if (!params().width.zero()) {
519 options << " width=\"" << toDocbookLength(params().width) << "\" ";
521 if (!params().height.zero()) {
522 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\" ";
531 if (!params().special.empty())
532 options << from_ascii(params().special) << " ";
534 // trailing blanks are ok ...
535 return options.str();
541 enum GraphicsCopyStatus {
549 pair<GraphicsCopyStatus, FileName> const
550 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
552 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
553 unsigned long const checksum_in = file_in.checksum();
554 unsigned long const checksum_out = file_out.checksum();
556 if (checksum_in == checksum_out)
558 return make_pair(IDENTICAL_CONTENTS, file_out);
560 Mover const & mover = getMover(theFormats().getFormatFromFile(file_in));
561 bool const success = mover.copy(file_in, file_out);
564 LYXERR(Debug::GRAPHICS,
565 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
566 "into the temporary directory."),
567 from_utf8(file_in.absFileName()))));
570 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
571 return make_pair(status, file_out);
575 pair<GraphicsCopyStatus, FileName> const
576 copyToDirIfNeeded(DocFileName const & file, string const & dir)
578 string const file_in = file.absFileName();
579 string const only_path = onlyPath(file_in);
580 if (rtrim(only_path, "/") == rtrim(dir, "/"))
581 return make_pair(IDENTICAL_PATHS, FileName(file_in));
583 string mangled = file.mangledFileName();
584 if (theFormats().isZippedFile(file)) {
585 // We need to change _eps.gz to .eps.gz. The mangled name is
586 // still unique because of the counter in mangledFileName().
587 // We can't just call mangledFileName() with the zip
588 // extension removed, because base.eps and base.eps.gz may
589 // have different content but would get the same mangled
590 // name in this case.
591 // Also take into account that if the name of the zipped file
592 // has no zip extension then the name of the unzipped one is
593 // prefixed by "unzipped_".
594 string const base = removeExtension(file.unzippedFileName());
595 string::size_type const prefix_len =
596 prefixIs(onlyFileName(base), "unzipped_") ? 9 : 0;
597 string::size_type const ext_len =
598 file_in.length() + prefix_len - base.length();
599 mangled[mangled.length() - ext_len] = '.';
601 FileName const file_out(makeAbsPath(mangled, dir));
603 return copyFileIfNeeded(file, file_out);
607 string const stripExtensionIfPossible(string const & file, bool nice)
609 // Remove the extension so the LaTeX compiler will use whatever
610 // is appropriate (when there are several versions in different
612 // Do this only if we are not exporting for internal usage, because
613 // pdflatex prefers png over pdf and it would pick up the png images
614 // that we generate for preview.
615 // This works only if the filename contains no dots besides
616 // the just removed one. We can fool here by replacing all
617 // dots with a macro whose definition is just a dot ;-)
618 // The automatic format selection does not work if the file
620 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
621 if (!nice || contains(latex_name, '"'))
623 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
627 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
629 // No conversion is needed. LaTeX can handle the graphic file as is.
630 // This is true even if the orig_file is compressed.
631 string const to_format = theFormats().getFormat(to)->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 == OutputParams::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 && !FileName(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 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
796 Converters::try_default | Converters::try_cache)) {
797 runparams.exportdata->addExternalFile(tex_format,
798 to_file, output_to_file);
799 runparams.exportdata->addExternalFile("dvi",
800 to_file, output_to_file);
803 return stripExtensionIfPossible(output_to_file, runparams.nice);
807 void InsetGraphics::latex(otexstream & os,
808 OutputParams const & runparams) const
810 // If there is no file specified or not existing,
811 // just output a message about it in the latex output.
812 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
813 << params().filename.absFileName());
815 bool const file_exists = !params().filename.empty()
816 && params().filename.isReadableFile();
819 if (params().bbox.empty())
820 message = "bb = 0 0 200 100";
821 if (!params().draft) {
822 if (!message.empty())
826 if (!message.empty())
828 message += "type=eps";
830 // If no existing file "filename" was found LaTeX
831 // draws only a rectangle with the above bb and the
832 // not found filename in it.
833 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
835 // These variables collect all the latex code that should be before and
836 // after the actual includegraphics command.
840 // Write the options if there are any.
841 bool const ps = runparams.flavor == OutputParams::LATEX
842 || runparams.flavor == OutputParams::DVILUATEX;
843 string const opts = createLatexOptions(ps);
844 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
846 if (contains(opts, '=')) {
847 std::set<Language const *> langs = buffer().masterBuffer()->getLanguages();
848 for (auto const lang : langs) {
849 if (lang->lang() == "turkish" || lang->lang() == "latin") {
850 // Turkish and Latin activate = (#2005).
851 // Deactivate locally for keyval option parsing
852 before = "\\begingroup\\catcode`\\=12";
853 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 (size_type i = 0 ; i < file_path.size() ; ++i) {
882 char_type c = file_path[i];
884 if (runparams.encoding->encodable(c))
885 encodable_file_path += c;
886 else if (runparams.dryrun) {
887 encodable_file_path += "<" + _("LyX Warning: ")
888 + _("uncodable character") + " '";
889 encodable_file_path += docstring(1, c);
890 encodable_file_path += "'>";
893 } catch (EncodingException & /* e */) {
894 if (runparams.dryrun) {
895 encodable_file_path += "<" + _("LyX Warning: ")
896 + _("uncodable character") + " '";
897 encodable_file_path += docstring(1, c);
898 encodable_file_path += "'>";
903 if (!uncodable.empty() && !runparams.silent) {
904 // issue a warning about omitted characters
905 // FIXME: should be passed to the error dialog
906 frontend::Alert::warning(_("Uncodable characters in path"),
907 bformat(_("The following characters in one of the graphic paths are\n"
908 "not representable in the current encoding and have been omitted: %1$s.\n"
909 "You need to adapt either the encoding or the path."),
912 latex_str += to_utf8(encodable_file_path);
913 latex_str += '}' + after;
915 os << from_utf8(latex_str);
917 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
921 int InsetGraphics::plaintext(odocstringstream & os,
922 OutputParams const &, size_t) const
924 // No graphics in ascii output. Possible to use gifscii to convert
925 // images to ascii approximation.
926 // 1. Convert file to ascii using gifscii
927 // 2. Read ascii output file and add it to the output stream.
928 // at least we send the filename
930 // FIXME: We have no idea what the encoding of the filename is
932 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
933 from_utf8(params().filename.absFileName()));
934 os << '<' << str << '>';
936 return 2 + str.size();
940 static int writeImageObject(char const * format, odocstream & os,
941 OutputParams const & runparams, docstring const & graphic_label,
942 docstring const & attributes)
944 if (runparams.flavor != OutputParams::XML)
945 os << "<![ %output.print." << format
948 os <<"<imageobject><imagedata fileref=\"&"
955 if (runparams.flavor == OutputParams::XML)
956 os << " role=\"" << format << "\"/>" ;
958 os << " format=\"" << format << "\">" ;
960 os << "</imageobject>";
962 if (runparams.flavor != OutputParams::XML)
963 os << endl << "]]>" ;
965 return runparams.flavor == OutputParams::XML ? 0 : 2;
969 // For explanation on inserting graphics into DocBook checkout:
970 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
971 // See also the docbook guide at http://www.docbook.org/
972 int InsetGraphics::docbook(odocstream & os,
973 OutputParams const & runparams) const
975 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
976 // need to switch to MediaObject. However, for now this is sufficient and
978 if (runparams.flavor == OutputParams::XML)
979 runparams.exportdata->addExternalFile("docbook-xml",
982 runparams.exportdata->addExternalFile("docbook",
985 os << "<inlinemediaobject>";
988 docstring attributes = createDocBookAttributes();
989 r += writeImageObject("png", os, runparams, graphic_label, attributes);
990 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
991 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
992 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
994 os << "</inlinemediaobject>";
999 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
1001 // The following code depends on non-empty filenames
1002 if (params().filename.empty())
1005 if (!params().filename.isReadableFile())
1008 // The master buffer. This is useful when there are multiple levels
1010 Buffer const * masterBuffer = buffer().masterBuffer();
1012 // We place all temporary files in the master buffer's temp dir.
1013 // This is possible because we use mangled file names.
1014 // FIXME We may want to put these files in some special temporary
1016 string const temp_path = masterBuffer->temppath();
1018 // Copy to temporary directory.
1020 GraphicsCopyStatus status;
1021 tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
1023 if (status == FAILURE)
1026 string const from = theFormats().getFormatFromFile(temp_file);
1028 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
1032 string const to = findTargetFormat(from, runparams);
1033 string const ext = theFormats().extension(to);
1034 string const orig_file = params().filename.absFileName();
1035 string output_file = onlyFileName(temp_file.absFileName());
1036 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
1037 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
1040 // source and destination formats are the same
1041 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
1045 // so the source and destination formats are different
1046 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
1047 string const output_to_file = changeExtension(output_file, ext);
1049 // Do we need to perform the conversion?
1050 // Yes if to_file does not exist or if temp_file is newer than to_file
1051 if (compare_timestamps(temp_file, to_file) < 0) {
1053 LYXERR(Debug::GRAPHICS,
1054 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
1055 from_utf8(orig_file))));
1056 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
1057 return output_to_file;
1060 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
1061 << "\tA copy has been made and convert is to be called with:\n"
1062 << "\tfile to convert = " << temp_file << '\n'
1063 << "\t from " << from << " to " << to);
1065 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
1067 bool const success =
1068 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
1069 from, to, el, Converters::try_default | Converters::try_cache);
1072 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
1073 return output_to_file;
1077 docstring InsetGraphics::xhtml(XHTMLStream & xs, OutputParams const & op) const
1079 string const output_file = op.dryrun ? string() : prepareHTMLFile(op);
1081 if (output_file.empty() && !op.dryrun) {
1082 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
1083 << params().filename << "' for output. File missing?");
1084 string const attr = "src='" + params().filename.absFileName()
1085 + "' alt='image: " + output_file + "'";
1086 xs << html::CompTag("img", attr);
1091 // We aren't doing anything with the crop and rotate parameters, and it would
1092 // really be better to do width and height conversion, rather than to output
1093 // these parameters here.
1095 bool const havewidth = !params().width.zero();
1096 bool const haveheight = !params().height.zero();
1097 if (havewidth || haveheight) {
1099 imgstyle += "width:" + params().width.asHTMLString() + ";";
1101 imgstyle += " height:" + params().height.asHTMLString() + ";";
1102 } else if (params().scale != "100") {
1103 // Note that this will not have the same effect as in LaTeX export:
1104 // There, the image will be scaled from its original size. Here, the
1105 // percentage will be interpreted by the browser, and the image will
1106 // be scaled to a percentage of the window size.
1107 imgstyle = "width:" + params().scale + "%;";
1109 if (!imgstyle.empty())
1110 imgstyle = "style='" + imgstyle + "' ";
1112 string const attr = imgstyle + "src='" + output_file + "' alt='image: "
1113 + output_file + "'";
1114 xs << html::CompTag("img", attr);
1119 void InsetGraphics::validate(LaTeXFeatures & features) const
1121 // If we have no image, we should not require anything.
1122 if (params().filename.empty())
1125 features.includeFile(graphic_label,
1126 removeExtension(params().filename.absFileName()));
1128 features.require("graphicx");
1130 if (features.runparams().nice) {
1131 string const rel_file = params().filename.onlyFileNameWithoutExt();
1132 if (contains(rel_file, "."))
1133 features.require("lyxdot");
1138 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1140 // If nothing is changed, just return and say so.
1141 if (params() == p && !p.filename.empty())
1144 // Copy the new parameters.
1147 // Update the display using the new parameters.
1148 graphic_->update(params().as_grfxParams());
1150 // We have changed data, report it.
1155 InsetGraphicsParams const & InsetGraphics::params() const
1161 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1163 theFormats().edit(buffer(), p.filename,
1164 theFormats().getFormatFromFile(p.filename));
1168 void InsetGraphics::addToToc(DocIterator const & cpit, bool output_active,
1169 UpdateType, TocBackend & backend) const
1172 docstring const str = from_utf8(params_.filename.onlyFileName());
1173 TocBuilder & b = backend.builder("graphics");
1174 b.pushItem(cpit, str, output_active);
1179 string InsetGraphics::contextMenuName() const
1181 return "context-graphics";
1185 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1186 InsetGraphicsParams & params)
1191 istringstream data(in);
1193 lex.setStream(data);
1194 lex.setContext("InsetGraphics::string2params");
1196 params = InsetGraphicsParams();
1197 readInsetGraphics(lex, buffer, false, params);
1201 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1202 Buffer const & buffer)
1205 data << "graphics" << ' ';
1206 params.Write(data, buffer);
1207 data << "\\end_inset\n";
1212 docstring InsetGraphics::toolTip(BufferView const &, int, int) const
1214 return from_utf8(params().filename.onlyFileName());
1217 namespace graphics {
1219 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1221 Inset & inset = b.inset();
1222 InsetIterator it = inset_iterator_begin(inset);
1223 InsetIterator const end = inset_iterator_end(inset);
1224 for (; it != end; ++it)
1225 if (it->lyxCode() == GRAPHICS_CODE) {
1226 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1227 InsetGraphicsParams inspar = ins.getParams();
1228 if (!inspar.groupId.empty())
1229 ids.insert(inspar.groupId);
1234 int countGroupMembers(Buffer const & b, string const & groupId)
1237 if (groupId.empty())
1239 Inset & inset = b.inset();
1240 InsetIterator it = inset_iterator_begin(inset);
1241 InsetIterator const end = inset_iterator_end(inset);
1242 for (; it != end; ++it)
1243 if (it->lyxCode() == GRAPHICS_CODE) {
1244 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1245 if (ins.getParams().groupId == groupId)
1252 string getGroupParams(Buffer const & b, string const & groupId)
1254 if (groupId.empty())
1256 Inset & inset = b.inset();
1257 InsetIterator it = inset_iterator_begin(inset);
1258 InsetIterator const end = inset_iterator_end(inset);
1259 for (; it != end; ++it)
1260 if (it->lyxCode() == GRAPHICS_CODE) {
1261 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1262 InsetGraphicsParams inspar = ins.getParams();
1263 if (inspar.groupId == groupId) {
1264 InsetGraphicsParams tmp = inspar;
1265 tmp.filename.erase();
1266 return InsetGraphics::params2string(tmp, b);
1273 void unifyGraphicsGroups(Buffer & b, string const & argument)
1275 InsetGraphicsParams params;
1276 InsetGraphics::string2params(argument, b, params);
1278 // This handles undo groups automagically
1279 UndoGroupHelper ugh(&b);
1280 Inset & inset = b.inset();
1281 InsetIterator it = inset_iterator_begin(inset);
1282 InsetIterator const end = inset_iterator_end(inset);
1283 for (; it != end; ++it) {
1284 if (it->lyxCode() == GRAPHICS_CODE) {
1285 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1286 InsetGraphicsParams inspar = ins.getParams();
1287 if (params.groupId == inspar.groupId) {
1288 b.undo().recordUndo(CursorData(it));
1289 params.filename = inspar.filename;
1290 ins.setParams(params);
1297 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1299 Inset * instmp = &cur.inset();
1300 if (instmp->lyxCode() != GRAPHICS_CODE)
1301 instmp = cur.nextInset();
1302 if (!instmp || instmp->lyxCode() != GRAPHICS_CODE)
1305 return static_cast<InsetGraphics *>(instmp);
1308 } // namespace graphics