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"
57 #include "ErrorList.h"
60 #include "FuncRequest.h"
61 #include "FuncStatus.h"
62 #include "InsetIterator.h"
63 #include "LaTeXFeatures.h"
66 #include "MetricsInfo.h"
68 #include "OutputParams.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/lyxlib.h"
88 #include "support/lstrings.h"
89 #include "support/os.h"
90 #include "support/qstring_helpers.h"
91 #include "support/Systemcall.h"
100 using namespace lyx::support;
104 namespace Alert = frontend::Alert;
108 /// Find the most suitable image format for images in \p format
109 /// Note that \p format may be unknown (i. e. an empty string)
110 string findTargetFormat(string const & format, OutputParams const & runparams)
112 // Are we using latex or XeTeX/LuaTeX/pdflatex?
113 if (runparams.flavor == OutputParams::PDFLATEX
114 || runparams.flavor == OutputParams::XETEX
115 || runparams.flavor == OutputParams::LUATEX) {
116 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
117 Format const * const f = theFormats().getFormat(format);
118 // Convert vector graphics to pdf
119 if (f && f->vectorFormat())
121 // pdflatex can use jpeg, png and pdf directly
124 // Convert everything else to png
127 // for HTML, we leave the known formats and otherwise convert to png
128 if (runparams.flavor == OutputParams::HTML) {
129 Format const * const f = theFormats().getFormat(format);
130 // Convert vector graphics to svg
131 if (f && f->vectorFormat() && theConverters().isReachable(format, "svg"))
133 // Leave the known formats alone
134 if (format == "jpg" || format == "png" || format == "gif")
136 // Convert everything else to png
139 // If it's postscript, we always do eps.
140 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
142 // any other than ps is changed to eps
149 void readInsetGraphics(Lexer & lex, Buffer const & buf, bool allowOrigin,
150 InsetGraphicsParams & params)
152 bool finished = false;
154 while (lex.isOK() && !finished) {
157 string const token = lex.getString();
158 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
163 if (token == "\\end_inset") {
166 if (!params.Read(lex, token, buf, allowOrigin))
167 lyxerr << "Unknown token, "
178 InsetGraphics::InsetGraphics(Buffer * buf)
179 : Inset(buf), graphic_label(sgml::uniqueID(from_ascii("graph"))),
180 graphic_(new RenderGraphic(this))
185 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
187 graphic_label(sgml::uniqueID(from_ascii("graph"))),
188 graphic_(new RenderGraphic(*ig.graphic_, this))
190 setParams(ig.params());
194 Inset * InsetGraphics::clone() const
196 return new InsetGraphics(*this);
200 InsetGraphics::~InsetGraphics()
202 hideDialogs("graphics", this);
207 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
209 switch (cmd.action()) {
210 case LFUN_INSET_EDIT: {
211 InsetGraphicsParams p = params();
212 if (!cmd.argument().empty())
213 string2params(to_utf8(cmd.argument()), buffer(), p);
218 case LFUN_INSET_MODIFY: {
219 if (cmd.getArg(0) != "graphics") {
220 Inset::doDispatch(cur, cmd);
224 InsetGraphicsParams p;
225 string2params(to_utf8(cmd.argument()), buffer(), p);
226 if (p.filename.empty()) {
227 cur.noScreenUpdate();
233 // if the inset is part of a graphics group, all the
234 // other members should be updated too.
235 if (!params_.groupId.empty())
236 graphics::unifyGraphicsGroups(buffer(),
237 to_utf8(cmd.argument()));
241 case LFUN_INSET_DIALOG_UPDATE:
242 cur.bv().updateDialog("graphics", params2string(params(), buffer()));
245 case LFUN_GRAPHICS_RELOAD:
246 params_.filename.refresh();
251 Inset::doDispatch(cur, cmd);
257 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
258 FuncStatus & flag) const
260 switch (cmd.action()) {
261 case LFUN_INSET_MODIFY:
262 if (cmd.getArg(0) != "graphics")
263 return Inset::getStatus(cur, cmd, flag);
265 case LFUN_INSET_EDIT:
266 case LFUN_INSET_DIALOG_UPDATE:
267 case LFUN_GRAPHICS_RELOAD:
268 flag.setEnabled(true);
272 return Inset::getStatus(cur, cmd, flag);
277 bool InsetGraphics::showInsetDialog(BufferView * bv) const
279 bv->showDialog("graphics", params2string(params(), bv->buffer()),
280 const_cast<InsetGraphics *>(this));
286 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
288 graphic_->metrics(mi, dim);
292 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
294 graphic_->draw(pi, x, y);
298 void InsetGraphics::write(ostream & os) const
301 params().Write(os, buffer());
305 void InsetGraphics::read(Lexer & lex)
307 lex.setContext("InsetGraphics::read");
309 readInsetGraphics(lex, buffer(), true, params_);
310 graphic_->update(params().as_grfxParams());
314 void InsetGraphics::outBoundingBox(graphics::BoundingBox & bbox) const
319 FileName const file(params().filename.absFileName());
321 // No correction is necessary for a postscript image
322 bool const zipped = theFormats().isZippedFile(file);
323 FileName const unzipped_file = zipped ? unzipFile(file) : file;
324 string const format = theFormats().getFormatFromFile(unzipped_file);
326 unzipped_file.removeFile();
327 if (Formats::isPostScriptFileFormat(format))
330 // Get the actual image dimensions in pixels
333 graphics::Cache & gc = graphics::Cache::get();
334 if (gc.inCache(file)) {
335 graphics::Image const * image = gc.item(file)->image();
337 width = image->width();
338 height = image->height();
341 if (width == 0 || height == 0)
344 // Use extractbb to find the dimensions in the typeset output
346 extractbb.start("extractbb", QStringList() << "-O" << toqstr(file.absFileName()));
347 if (!extractbb.waitForStarted() || !extractbb.waitForFinished()) {
348 LYXERR0("Cannot read output bounding box of " << file);
352 string const result = extractbb.readAll().constData();
353 size_t i = result.find("%%BoundingBox:");
354 if (i == string::npos) {
355 LYXERR0("Cannot find output bounding box of " << file);
359 string const bb = result.substr(i);
360 int out_width = convert<int>(token(bb, ' ', 3));
361 int out_height = convert<int>(token(bb, ' ', 4));
363 // Compute the scaling ratio and correct the bounding box
364 double scalex = out_width / double(width);
365 double scaley = out_height / double(height);
367 bbox.xl.value(scalex * bbox.xl.value());
368 bbox.xr.value(scalex * bbox.xr.value());
369 bbox.yb.value(scaley * bbox.yb.value());
370 bbox.yt.value(scaley * bbox.yt.value());
374 string InsetGraphics::createLatexOptions(bool const ps) const
376 // Calculate the options part of the command, we must do it to a string
377 // stream since we might have a trailing comma that we would like to remove
378 // before writing it to the output stream.
379 ostringstream options;
380 if (!params().bbox.empty()) {
381 graphics::BoundingBox out_bbox = params().bbox;
382 outBoundingBox(out_bbox);
383 string const key = ps ? "bb=" : "viewport=";
384 options << key << out_bbox.xl.asLatexString() << ' '
385 << out_bbox.yb.asLatexString() << ' '
386 << out_bbox.xr.asLatexString() << ' '
387 << out_bbox.yt.asLatexString() << ',';
394 double const scl = convert<double>(params().scale);
395 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
396 if (!float_equal(scl, 100.0, 0.05))
397 size << "scale=" << scl / 100.0 << ',';
399 if (!params().width.zero())
400 size << "width=" << params().width.asLatexString() << ',';
401 if (!params().height.zero())
402 size << "height=" << params().height.asLatexString() << ',';
403 if (params().keepAspectRatio)
404 size << "keepaspectratio,";
406 if (params().scaleBeforeRotation && !size.str().empty())
407 options << size.str();
409 // Make sure rotation angle is not very close to zero;
410 // a float can be effectively zero but not exactly zero.
411 if (!params().rotateAngle.empty()
412 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
413 options << "angle=" << params().rotateAngle << ',';
414 if (!params().rotateOrigin.empty()) {
415 options << "origin=" << params().rotateOrigin[0];
416 if (contains(params().rotateOrigin,"Top"))
418 else if (contains(params().rotateOrigin,"Bottom"))
420 else if (contains(params().rotateOrigin,"Baseline"))
425 if (!params().scaleBeforeRotation && !size.str().empty())
426 options << size.str();
428 if (!params().special.empty())
429 options << params().special << ',';
431 string opts = options.str();
433 if (suffixIs(opts, ','))
434 opts = opts.substr(0, opts.size() - 1);
440 docstring InsetGraphics::toDocbookLength(Length const & len) const
442 odocstringstream result;
443 switch (len.unit()) {
444 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
445 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
447 case Length::PT: // Point = 1/72.27in = 0.351mm
448 result << len.value() * 72 / 72.27 << "pt";
450 case Length::BP: // Big point (72bp = 1in), also PostScript point
451 result << len.value() << "pt";
453 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
454 result << len.value() * 0.376 << "mm";
456 case Length::MM: // Millimeter = 2.845pt
457 result << len.value() << "mm";
459 case Length::PC: // Pica = 12pt = 4.218mm
460 result << len.value() << "pc";
462 case Length::CC: // Cicero = 12dd = 4.531mm
463 result << len.value() * 4.531 << "mm";
465 case Length::CM: // Centimeter = 10mm = 2.371pc
466 result << len.value() << "cm";
468 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
469 result << len.value() << "in";
471 case Length::EX: // Height of a small "x" for the current font.
472 // Obviously we have to compromise here. Any better ratio than 1.5 ?
473 result << len.value() / 1.5 << "em";
475 case Length::EM: // Width of capital "M" in current font.
476 result << len.value() << "em";
478 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
479 result << len.value() * 18 << "em";
481 case Length::PTW: // Percent of TextWidth
482 case Length::PCW: // Percent of ColumnWidth
483 case Length::PPW: // Percent of PageWidth
484 case Length::PLW: // Percent of LineWidth
485 case Length::PTH: // Percent of TextHeight
486 case Length::PPH: // Percent of PaperHeight
487 case Length::BLS: // Percent of BaselineSkip
488 // Sigh, this will go wrong.
489 result << len.value() << "%";
492 result << len.asDocstring();
499 docstring InsetGraphics::createDocBookAttributes() const
501 // Calculate the options part of the command, we must do it to a string
502 // stream since we copied the code from createLatexParams() ;-)
504 // FIXME: av: need to translate spec -> Docbook XSL spec
505 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
506 // Right now it only works with my version of db2latex :-)
508 odocstringstream options;
509 double const scl = convert<double>(params().scale);
510 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
511 if (!float_equal(scl, 100.0, 0.05))
512 options << " scale=\""
513 << support::iround(scl)
516 if (!params().width.zero()) {
517 options << " width=\"" << toDocbookLength(params().width) << "\" ";
519 if (!params().height.zero()) {
520 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
522 if (params().keepAspectRatio) {
523 // This will be irrelevant unless both width and height are set
524 options << "scalefit=\"1\" ";
529 if (!params().special.empty())
530 options << from_ascii(params().special) << " ";
532 // trailing blanks are ok ...
533 return options.str();
539 enum GraphicsCopyStatus {
547 pair<GraphicsCopyStatus, FileName> const
548 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
550 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
551 unsigned long const checksum_in = file_in.checksum();
552 unsigned long const checksum_out = file_out.checksum();
554 if (checksum_in == checksum_out)
556 return make_pair(IDENTICAL_CONTENTS, file_out);
558 Mover const & mover = getMover(theFormats().getFormatFromFile(file_in));
559 bool const success = mover.copy(file_in, file_out);
562 LYXERR(Debug::GRAPHICS,
563 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
564 "into the temporary directory."),
565 from_utf8(file_in.absFileName()))));
568 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
569 return make_pair(status, file_out);
573 pair<GraphicsCopyStatus, FileName> const
574 copyToDirIfNeeded(DocFileName const & file, string const & dir)
576 string const file_in = file.absFileName();
577 string const only_path = onlyPath(file_in);
578 if (rtrim(only_path, "/") == rtrim(dir, "/"))
579 return make_pair(IDENTICAL_PATHS, FileName(file_in));
581 string mangled = file.mangledFileName();
582 if (theFormats().isZippedFile(file)) {
583 // We need to change _eps.gz to .eps.gz. The mangled name is
584 // still unique because of the counter in mangledFileName().
585 // We can't just call mangledFileName() with the zip
586 // extension removed, because base.eps and base.eps.gz may
587 // have different content but would get the same mangled
588 // name in this case.
589 string const base = removeExtension(file.unzippedFileName());
590 string::size_type const ext_len = file_in.length() - base.length();
591 mangled[mangled.length() - ext_len] = '.';
593 FileName const file_out(makeAbsPath(mangled, dir));
595 return copyFileIfNeeded(file, file_out);
599 string const stripExtensionIfPossible(string const & file, bool nice)
601 // Remove the extension so the LaTeX compiler will use whatever
602 // is appropriate (when there are several versions in different
604 // Do this only if we are not exporting for internal usage, because
605 // pdflatex prefers png over pdf and it would pick up the png images
606 // that we generate for preview.
607 // This works only if the filename contains no dots besides
608 // the just removed one. We can fool here by replacing all
609 // dots with a macro whose definition is just a dot ;-)
610 // The automatic format selection does not work if the file
612 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
613 if (!nice || contains(latex_name, '"'))
615 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
619 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
621 // No conversion is needed. LaTeX can handle the graphic file as is.
622 // This is true even if the orig_file is compressed.
623 string const to_format = theFormats().getFormat(to)->extension();
624 string const file_format = getExtension(file);
625 // for latex .ps == .eps
626 if (to_format == file_format ||
627 (to_format == "eps" && file_format == "ps") ||
628 (to_format == "ps" && file_format == "eps"))
629 return stripExtensionIfPossible(file, nice);
630 return latex_path(file, EXCLUDE_EXTENSION);
636 string InsetGraphics::prepareFile(OutputParams const & runparams) const
638 // The following code depends on non-empty filenames
639 if (params().filename.empty())
642 string const orig_file = params().filename.absFileName();
643 // this is for dryrun and display purposes, do not use latexFilename
644 string const rel_file = params().filename.relFileName(buffer().filePath());
646 // previewing source code, no file copying or file format conversion
647 if (runparams.dryrun)
648 return stripExtensionIfPossible(rel_file, runparams.nice);
650 // The master buffer. This is useful when there are multiple levels
652 Buffer const * masterBuffer = buffer().masterBuffer();
654 // Return the output name if we are inside a comment or the file does
656 // We are not going to change the extension or using the name of the
657 // temporary file, the code is already complicated enough.
658 if (runparams.inComment || !params().filename.isReadableFile())
659 return params().filename.outputFileName(masterBuffer->filePath());
661 // We place all temporary files in the master buffer's temp dir.
662 // This is possible because we use mangled file names.
663 // This is necessary for DVI export.
664 string const temp_path = masterBuffer->temppath();
666 // temp_file will contain the file for LaTeX to act on if, for example,
667 // we move it to a temp dir or uncompress it.
669 GraphicsCopyStatus status;
670 tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
672 if (status == FAILURE)
675 // a relative filename should be relative to the master buffer.
676 // "nice" means that the buffer is exported to LaTeX format but not
677 // run through the LaTeX compiler.
678 string output_file = runparams.nice ?
679 params().filename.outputFileName(masterBuffer->filePath()) :
680 onlyFileName(temp_file.absFileName());
682 if (runparams.nice) {
683 if (!isValidLaTeXFileName(output_file)) {
684 frontend::Alert::warning(_("Invalid filename"),
685 _("The following filename will cause troubles "
686 "when running the exported file through LaTeX: ") +
687 from_utf8(output_file));
689 // only show DVI-specific warning when export format is plain latex
690 if (!isValidDVIFileName(output_file)
691 && runparams.flavor == OutputParams::LATEX) {
692 frontend::Alert::warning(_("Problematic filename for DVI"),
693 _("The following filename can cause troubles "
694 "when running the exported file through LaTeX "
695 "and opening the resulting DVI: ") +
696 from_utf8(output_file), true);
700 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
701 // determine the export format
702 string const tex_format = flavor2format(runparams.flavor);
704 if (theFormats().isZippedFile(params().filename)) {
705 FileName const unzipped_temp_file =
706 FileName(unzippedFileName(temp_file.absFileName()));
707 output_file = unzippedFileName(output_file);
708 source_file = FileName(unzippedFileName(source_file.absFileName()));
709 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
710 // temp_file has been unzipped already and
711 // orig_file has not changed in the meantime.
712 temp_file = unzipped_temp_file;
713 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
715 // unzipped_temp_file does not exist or is too old
716 temp_file = unzipFile(temp_file);
717 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
721 string const from = theFormats().getFormatFromFile(temp_file);
723 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
725 string const to = findTargetFormat(from, runparams);
726 string const ext = theFormats().extension(to);
727 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
729 // We're going to be running the exported buffer through the LaTeX
730 // compiler, so must ensure that LaTeX can cope with the graphics
733 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
736 // source and destination formats are the same
737 if (!runparams.nice && !FileName(temp_file).hasExtension(ext)) {
738 // The LaTeX compiler will not be able to determine
739 // the file format from the extension, so we must
741 FileName const new_file =
742 FileName(changeExtension(temp_file.absFileName(), ext));
743 if (temp_file.moveTo(new_file)) {
744 temp_file = new_file;
745 output_file = changeExtension(output_file, ext);
747 FileName(changeExtension(source_file.absFileName(), ext));
749 LYXERR(Debug::GRAPHICS, "Could not rename file `"
750 << temp_file << "' to `" << new_file << "'.");
753 // The extension of temp_file might be != ext!
754 runparams.exportdata->addExternalFile(tex_format, source_file,
756 runparams.exportdata->addExternalFile("dvi", source_file,
758 return stripExtensionIfPossible(output_file, to, runparams.nice);
761 // so the source and destination formats are different
762 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
763 string const output_to_file = changeExtension(output_file, ext);
765 // Do we need to perform the conversion?
766 // Yes if to_file does not exist or if temp_file is newer than to_file
767 if (compare_timestamps(temp_file, to_file) < 0) {
769 LYXERR(Debug::GRAPHICS,
770 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
771 from_utf8(rel_file))));
772 runparams.exportdata->addExternalFile(tex_format, to_file,
774 runparams.exportdata->addExternalFile("dvi", to_file,
776 return stripExtensionIfPossible(output_to_file, runparams.nice);
779 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
780 << "\tA copy has been made and convert is to be called with:\n"
781 << "\tfile to convert = " << temp_file << '\n'
782 << "\t from " << from << " to " << to);
784 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
786 Converters::RetVal const rv =
787 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
789 Converters::try_default | Converters::try_cache);
790 if (rv == Converters::KILLED) {
791 LYXERR0("Graphics preparation killed.");
792 if (buffer().isClone() && buffer().isExporting())
793 throw ConversionException();
794 } else if (rv == Converters::SUCCESS) {
795 runparams.exportdata->addExternalFile(tex_format,
796 to_file, output_to_file);
797 runparams.exportdata->addExternalFile("dvi",
798 to_file, output_to_file);
801 return stripExtensionIfPossible(output_to_file, runparams.nice);
805 void InsetGraphics::latex(otexstream & os,
806 OutputParams const & runparams) const
808 // If there is no file specified or not existing,
809 // just output a message about it in the latex output.
810 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
811 << params().filename.absFileName());
813 bool const file_exists = !params().filename.empty()
814 && params().filename.isReadableFile();
817 if (params().bbox.empty())
818 message = "bb = 0 0 200 100";
819 if (!params().draft) {
820 if (!message.empty())
824 if (!message.empty())
826 message += "type=eps";
828 // If no existing file "filename" was found LaTeX
829 // draws only a rectangle with the above bb and the
830 // not found filename in it.
831 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
833 // These variables collect all the latex code that should be before and
834 // after the actual includegraphics command.
838 if (runparams.moving_arg)
839 before += "\\protect";
841 // We never use the starred form, we use the "clip" option instead.
842 before += "\\includegraphics";
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 (!opts.empty() && !message.empty())
851 before += ('[' + opts + ',' + message + ']');
852 else if (!opts.empty() || !message.empty())
853 before += ('[' + opts + message + ']');
855 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
857 string latex_str = before + '{';
858 // Convert the file if necessary.
859 // Remove the extension so LaTeX will use whatever is appropriate
860 // (when there are several versions in different formats)
861 string file_path = prepareFile(runparams);
862 latex_str += file_path;
863 latex_str += '}' + after;
865 os << from_utf8(latex_str);
867 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
871 int InsetGraphics::plaintext(odocstringstream & os,
872 OutputParams const &, size_t) const
874 // No graphics in ascii output. Possible to use gifscii to convert
875 // images to ascii approximation.
876 // 1. Convert file to ascii using gifscii
877 // 2. Read ascii output file and add it to the output stream.
878 // at least we send the filename
880 // FIXME: We have no idea what the encoding of the filename is
882 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
883 from_utf8(params().filename.absFileName()));
884 os << '<' << str << '>';
886 return 2 + str.size();
890 static int writeImageObject(char const * format, odocstream & os,
891 OutputParams const & runparams, docstring const & graphic_label,
892 docstring const & attributes)
894 if (runparams.flavor != OutputParams::XML)
895 os << "<![ %output.print." << format
898 os <<"<imageobject><imagedata fileref=\"&"
905 if (runparams.flavor == OutputParams::XML)
906 os << " role=\"" << format << "\"/>" ;
908 os << " format=\"" << format << "\">" ;
910 os << "</imageobject>";
912 if (runparams.flavor != OutputParams::XML)
913 os << endl << "]]>" ;
915 return runparams.flavor == OutputParams::XML ? 0 : 2;
919 // For explanation on inserting graphics into DocBook checkout:
920 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
921 // See also the docbook guide at http://www.docbook.org/
922 int InsetGraphics::docbook(odocstream & os,
923 OutputParams const & runparams) const
925 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
926 // need to switch to MediaObject. However, for now this is sufficient and
928 if (runparams.flavor == OutputParams::XML)
929 runparams.exportdata->addExternalFile("docbook-xml",
932 runparams.exportdata->addExternalFile("docbook",
935 os << "<inlinemediaobject>";
938 docstring attributes = createDocBookAttributes();
939 r += writeImageObject("png", os, runparams, graphic_label, attributes);
940 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
941 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
942 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
944 os << "</inlinemediaobject>";
949 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
951 // The following code depends on non-empty filenames
952 if (params().filename.empty())
955 if (!params().filename.isReadableFile())
958 // The master buffer. This is useful when there are multiple levels
960 Buffer const * masterBuffer = buffer().masterBuffer();
962 // We place all temporary files in the master buffer's temp dir.
963 // This is possible because we use mangled file names.
964 // FIXME We may want to put these files in some special temporary
966 string const temp_path = masterBuffer->temppath();
968 // Copy to temporary directory.
970 GraphicsCopyStatus status;
971 tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
973 if (status == FAILURE)
976 string const from = theFormats().getFormatFromFile(temp_file);
978 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
982 string const to = findTargetFormat(from, runparams);
983 string const ext = theFormats().extension(to);
984 string const orig_file = params().filename.absFileName();
985 string output_file = onlyFileName(temp_file.absFileName());
986 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
987 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
990 // source and destination formats are the same
991 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
995 // so the source and destination formats are different
996 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
997 string const output_to_file = changeExtension(output_file, ext);
999 // Do we need to perform the conversion?
1000 // Yes if to_file does not exist or if temp_file is newer than to_file
1001 if (compare_timestamps(temp_file, to_file) < 0) {
1003 LYXERR(Debug::GRAPHICS,
1004 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
1005 from_utf8(orig_file))));
1006 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
1007 return output_to_file;
1010 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
1011 << "\tA copy has been made and convert is to be called with:\n"
1012 << "\tfile to convert = " << temp_file << '\n'
1013 << "\t from " << from << " to " << to);
1015 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
1017 Converters::RetVal const rv =
1018 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
1019 from, to, el, Converters::try_default | Converters::try_cache);
1020 if (rv == Converters::KILLED) {
1021 if (buffer().isClone() && buffer().isExporting())
1022 throw ConversionException();
1025 if (rv != Converters::SUCCESS)
1027 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
1028 return output_to_file;
1032 docstring InsetGraphics::xhtml(XHTMLStream & xs, OutputParams const & op) const
1034 string const output_file = op.dryrun ? string() : prepareHTMLFile(op);
1036 if (output_file.empty() && !op.dryrun) {
1037 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
1038 << params().filename << "' for output. File missing?");
1039 string const attr = "src='" + params().filename.absFileName()
1040 + "' alt='image: " + output_file + "'";
1041 xs << html::CompTag("img", attr);
1046 // We aren't doing anything with the crop and rotate parameters, and it would
1047 // really be better to do width and height conversion, rather than to output
1048 // these parameters here.
1050 bool const havewidth = !params().width.zero();
1051 bool const haveheight = !params().height.zero();
1052 if (havewidth || haveheight) {
1054 imgstyle += "width:" + params().width.asHTMLString() + ";";
1056 imgstyle += " height:" + params().height.asHTMLString() + ";";
1057 } else if (params().scale != "100") {
1058 // Note that this will not have the same effect as in LaTeX export:
1059 // There, the image will be scaled from its original size. Here, the
1060 // percentage will be interpreted by the browser, and the image will
1061 // be scaled to a percentage of the window size.
1062 imgstyle = "width:" + params().scale + "%;";
1064 if (!imgstyle.empty())
1065 imgstyle = "style='" + imgstyle + "' ";
1067 string const attr = imgstyle + "src='" + output_file + "' alt='image: "
1068 + output_file + "'";
1069 xs << html::CompTag("img", attr);
1074 void InsetGraphics::validate(LaTeXFeatures & features) const
1076 // If we have no image, we should not require anything.
1077 if (params().filename.empty())
1080 features.includeFile(graphic_label,
1081 removeExtension(params().filename.absFileName()));
1083 features.require("graphicx");
1085 if (features.runparams().nice) {
1086 string const rel_file = params().filename.onlyFileNameWithoutExt();
1087 if (contains(rel_file, "."))
1088 features.require("lyxdot");
1093 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1095 // If nothing is changed, just return and say so.
1096 if (params() == p && !p.filename.empty())
1099 // Copy the new parameters.
1102 // Update the display using the new parameters.
1103 graphic_->update(params().as_grfxParams());
1105 // We have changed data, report it.
1110 InsetGraphicsParams const & InsetGraphics::params() const
1116 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1118 theFormats().edit(buffer(), p.filename,
1119 theFormats().getFormatFromFile(p.filename));
1123 void InsetGraphics::addToToc(DocIterator const & cpit, bool output_active,
1124 UpdateType, TocBackend & backend) const
1127 docstring const str = from_utf8(params_.filename.onlyFileName());
1128 TocBuilder & b = backend.builder("graphics");
1129 b.pushItem(cpit, str, output_active);
1134 string InsetGraphics::contextMenuName() const
1136 return "context-graphics";
1140 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1141 InsetGraphicsParams & params)
1146 istringstream data(in);
1148 lex.setStream(data);
1149 lex.setContext("InsetGraphics::string2params");
1151 params = InsetGraphicsParams();
1152 readInsetGraphics(lex, buffer, false, params);
1156 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1157 Buffer const & buffer)
1160 data << "graphics" << ' ';
1161 params.Write(data, buffer);
1162 data << "\\end_inset\n";
1167 docstring InsetGraphics::toolTip(BufferView const &, int, int) const
1169 return from_utf8(params().filename.onlyFileName());
1172 namespace graphics {
1174 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1176 Inset & inset = b.inset();
1177 InsetIterator it = inset_iterator_begin(inset);
1178 InsetIterator const end = inset_iterator_end(inset);
1179 for (; it != end; ++it) {
1180 InsetGraphics const * ins = it->asInsetGraphics();
1183 InsetGraphicsParams const & inspar = ins->getParams();
1184 if (!inspar.groupId.empty())
1185 ids.insert(inspar.groupId);
1190 int countGroupMembers(Buffer const & b, string const & groupId)
1193 if (groupId.empty())
1195 Inset & inset = b.inset();
1196 InsetIterator it = inset_iterator_begin(inset);
1197 InsetIterator const end = inset_iterator_end(inset);
1198 for (; it != end; ++it) {
1199 InsetGraphics const * ins = it->asInsetGraphics();
1202 if (ins->getParams().groupId == groupId)
1209 string getGroupParams(Buffer const & b, string const & groupId)
1211 if (groupId.empty())
1213 Inset & inset = b.inset();
1214 InsetIterator it = inset_iterator_begin(inset);
1215 InsetIterator const end = inset_iterator_end(inset);
1216 for (; it != end; ++it) {
1217 InsetGraphics const * ins = it->asInsetGraphics();
1220 InsetGraphicsParams const & inspar = ins->getParams();
1221 if (inspar.groupId == groupId) {
1222 InsetGraphicsParams tmp = inspar;
1223 tmp.filename.erase();
1224 return InsetGraphics::params2string(tmp, b);
1231 void unifyGraphicsGroups(Buffer & b, string const & argument)
1233 InsetGraphicsParams params;
1234 InsetGraphics::string2params(argument, b, params);
1236 // This handles undo groups automagically
1237 UndoGroupHelper ugh(&b);
1238 Inset & inset = b.inset();
1239 InsetIterator it = inset_iterator_begin(inset);
1240 InsetIterator const end = inset_iterator_end(inset);
1241 for (; it != end; ++it) {
1242 InsetGraphics * ins = it->asInsetGraphics();
1245 InsetGraphicsParams const & inspar = ins->getParams();
1246 if (params.groupId == inspar.groupId) {
1247 CursorData(it).recordUndo();
1248 params.filename = inspar.filename;
1249 ins->setParams(params);
1255 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1257 Inset * instmp = &cur.inset();
1258 if (!instmp->asInsetGraphics())
1259 instmp = cur.nextInset();
1260 if (!instmp || !instmp->asInsetGraphics())
1263 return instmp->asInsetGraphics();
1266 } // namespace graphics