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 "EmbeddedFiles.h"
58 #include "ErrorList.h"
61 #include "FuncRequest.h"
62 #include "FuncStatus.h"
63 #include "LaTeXFeatures.h"
66 #include "MetricsInfo.h"
68 #include "OutputParams.h"
70 #include "TocBackend.h"
72 #include "frontends/alert.h"
74 #include "support/convert.h"
75 #include "support/debug.h"
76 #include "support/docstream.h"
77 #include "support/ExceptionMessage.h"
78 #include "support/filetools.h"
79 #include "support/gettext.h"
80 #include "support/lyxlib.h"
81 #include "support/lstrings.h"
82 #include "support/os.h"
83 #include "support/Systemcall.h"
85 #include <boost/bind.hpp>
86 #include <boost/tuple/tuple.hpp>
92 using namespace lyx::support;
96 namespace Alert = frontend::Alert;
100 /// Find the most suitable image format for images in \p format
101 /// Note that \p format may be unknown (i. e. an empty string)
102 string findTargetFormat(string const & format, OutputParams const & runparams)
104 // Are we using latex or pdflatex?
105 if (runparams.flavor == OutputParams::PDFLATEX) {
106 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
107 Format const * const f = formats.getFormat(format);
108 // Convert vector graphics to pdf
109 if (f && f->vectorFormat())
111 // pdflatex can use jpeg, png and pdf directly
114 // Convert everything else to png
117 // If it's postscript, we always do eps.
118 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
120 // any other than ps is changed to eps
129 InsetGraphics::InsetGraphics()
130 : graphic_label(sgml::uniqueID(from_ascii("graph"))),
131 graphic_(new RenderGraphic(this))
135 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
137 boost::signals::trackable(),
138 graphic_label(sgml::uniqueID(from_ascii("graph"))),
139 graphic_(new RenderGraphic(*ig.graphic_, this))
141 setParams(ig.params());
145 Inset * InsetGraphics::clone() const
147 return new InsetGraphics(*this);
151 InsetGraphics::~InsetGraphics()
153 InsetGraphicsMailer(*this).hideDialog();
157 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
159 switch (cmd.action) {
160 case LFUN_GRAPHICS_EDIT: {
161 InsetGraphicsParams p;
162 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
163 editGraphics(p, buffer());
167 case LFUN_INSET_MODIFY: {
168 InsetGraphicsParams p;
169 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
170 if (!p.filename.empty())
177 case LFUN_INSET_DIALOG_UPDATE:
178 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
181 case LFUN_MOUSE_RELEASE:
182 if (!cur.selection())
183 InsetGraphicsMailer(*this).showDialog(&cur.bv());
187 Inset::doDispatch(cur, cmd);
193 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
194 FuncStatus & flag) const
196 switch (cmd.action) {
197 case LFUN_GRAPHICS_EDIT:
198 case LFUN_INSET_MODIFY:
199 case LFUN_INSET_DIALOG_UPDATE:
204 return Inset::getStatus(cur, cmd, flag);
209 void InsetGraphics::registerEmbeddedFiles(EmbeddedFileList & files) const
211 files.registerFile(params().filename, this, buffer());
215 void InsetGraphics::updateEmbeddedFile(EmbeddedFile const & file)
217 // only properties of an embedded file can be changed here.
218 params_.filename = file;
222 void InsetGraphics::edit(Cursor & cur, bool, EntryDirection)
224 InsetGraphicsMailer(*this).showDialog(&cur.bv());
228 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
230 graphic_->metrics(mi, dim);
234 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
236 graphic_->draw(pi, x, y);
240 Inset::EDITABLE InsetGraphics::editable() const
246 void InsetGraphics::write(ostream & os) const
249 params().Write(os, buffer());
253 void InsetGraphics::read(Lexer & lex)
255 string const token = lex.getString();
257 if (token == "Graphics")
258 readInsetGraphics(lex, buffer().filePath());
260 LYXERR(Debug::GRAPHICS, "Not a Graphics inset!");
262 params_.filename.enable(buffer().embedded(), &buffer(), false);
263 graphic_->update(params().as_grfxParams());
267 void InsetGraphics::readInsetGraphics(Lexer & lex, string const & bufpath)
269 bool finished = false;
271 while (lex.isOK() && !finished) {
274 string const token = lex.getString();
275 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
280 if (token == "\\end_inset") {
283 if (!params_.Read(lex, token, bufpath))
284 lyxerr << "Unknown token, " << token << ", skipping."
291 string const InsetGraphics::createLatexOptions() const
293 // Calculate the options part of the command, we must do it to a string
294 // stream since we might have a trailing comma that we would like to remove
295 // before writing it to the output stream.
296 ostringstream options;
297 if (!params().bb.empty())
298 options << "bb=" << rtrim(params().bb) << ',';
304 double const scl = convert<double>(params().scale);
305 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
306 if (!float_equal(scl, 100.0, 0.05))
307 size << "scale=" << scl / 100.0 << ',';
309 if (!params().width.zero())
310 size << "width=" << params().width.asLatexString() << ',';
311 if (!params().height.zero())
312 size << "height=" << params().height.asLatexString() << ',';
313 if (params().keepAspectRatio)
314 size << "keepaspectratio,";
316 if (params().scaleBeforeRotation && !size.str().empty())
317 options << size.str();
319 // Make sure rotation angle is not very close to zero;
320 // a float can be effectively zero but not exactly zero.
321 if (!params().rotateAngle.empty()
322 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
323 options << "angle=" << params().rotateAngle << ',';
324 if (!params().rotateOrigin.empty()) {
325 options << "origin=" << params().rotateOrigin[0];
326 if (contains(params().rotateOrigin,"Top"))
328 else if (contains(params().rotateOrigin,"Bottom"))
330 else if (contains(params().rotateOrigin,"Baseline"))
335 if (!params().scaleBeforeRotation && !size.str().empty())
336 options << size.str();
338 if (!params().special.empty())
339 options << params().special << ',';
341 string opts = options.str();
343 if (suffixIs(opts, ','))
344 opts = opts.substr(0, opts.size() - 1);
350 docstring const InsetGraphics::toDocbookLength(Length const & len) const
352 odocstringstream result;
353 switch (len.unit()) {
354 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
355 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
357 case Length::PT: // Point = 1/72.27in = 0.351mm
358 result << len.value() * 72 / 72.27 << "pt";
360 case Length::BP: // Big point (72bp = 1in), also PostScript point
361 result << len.value() << "pt";
363 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
364 result << len.value() * 0.376 << "mm";
366 case Length::MM: // Millimeter = 2.845pt
367 result << len.value() << "mm";
369 case Length::PC: // Pica = 12pt = 4.218mm
370 result << len.value() << "pc";
372 case Length::CC: // Cicero = 12dd = 4.531mm
373 result << len.value() * 4.531 << "mm";
375 case Length::CM: // Centimeter = 10mm = 2.371pc
376 result << len.value() << "cm";
378 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
379 result << len.value() << "in";
381 case Length::EX: // Height of a small "x" for the current font.
382 // Obviously we have to compromise here. Any better ratio than 1.5 ?
383 result << len.value() / 1.5 << "em";
385 case Length::EM: // Width of capital "M" in current font.
386 result << len.value() << "em";
388 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
389 result << len.value() * 18 << "em";
391 case Length::PTW: // Percent of TextWidth
392 case Length::PCW: // Percent of ColumnWidth
393 case Length::PPW: // Percent of PageWidth
394 case Length::PLW: // Percent of LineWidth
395 case Length::PTH: // Percent of TextHeight
396 case Length::PPH: // Percent of Paper
397 // Sigh, this will go wrong.
398 result << len.value() << "%";
401 result << len.asDocstring();
407 docstring const InsetGraphics::createDocBookAttributes() const
409 // Calculate the options part of the command, we must do it to a string
410 // stream since we copied the code from createLatexParams() ;-)
412 // FIXME: av: need to translate spec -> Docbook XSL spec
413 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
414 // Right now it only works with my version of db2latex :-)
416 odocstringstream options;
417 double const scl = convert<double>(params().scale);
418 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
419 if (!float_equal(scl, 100.0, 0.05))
420 options << " scale=\""
421 << static_cast<int>( (scl) + 0.5 )
424 if (!params().width.zero()) {
425 options << " width=\"" << toDocbookLength(params().width) << "\" ";
427 if (!params().height.zero()) {
428 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
430 if (params().keepAspectRatio) {
431 // This will be irrelevant unless both width and height are set
432 options << "scalefit=\"1\" ";
437 if (!params().special.empty())
438 options << from_ascii(params().special) << " ";
440 // trailing blanks are ok ...
441 return options.str();
447 enum GraphicsCopyStatus {
455 pair<GraphicsCopyStatus, FileName> const
456 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
458 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
459 unsigned long const checksum_in = file_in.checksum();
460 unsigned long const checksum_out = file_out.checksum();
462 if (checksum_in == checksum_out)
464 return make_pair(IDENTICAL_CONTENTS, file_out);
466 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
467 bool const success = mover.copy(file_in, file_out);
470 LYXERR(Debug::GRAPHICS,
471 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
472 "into the temporary directory."),
473 from_utf8(file_in.absFilename()))));
476 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
477 return make_pair(status, file_out);
481 pair<GraphicsCopyStatus, FileName> const
482 copyToDirIfNeeded(DocFileName const & file, string const & dir)
484 string const file_in = file.absFilename();
485 string const only_path = onlyPath(file_in);
486 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
487 return make_pair(IDENTICAL_PATHS, file_in);
489 string mangled = file.mangledFilename();
490 if (file.isZipped()) {
491 // We need to change _eps.gz to .eps.gz. The mangled name is
492 // still unique because of the counter in mangledFilename().
493 // We can't just call mangledFilename() with the zip
494 // extension removed, because base.eps and base.eps.gz may
495 // have different content but would get the same mangled
496 // name in this case.
497 string const base = removeExtension(file.unzippedFilename());
498 string::size_type const ext_len = file_in.length() - base.length();
499 mangled[mangled.length() - ext_len] = '.';
501 FileName const file_out(makeAbsPath(mangled, dir));
503 return copyFileIfNeeded(file, file_out);
507 string const stripExtensionIfPossible(string const & file, bool nice)
509 // Remove the extension so the LaTeX compiler will use whatever
510 // is appropriate (when there are several versions in different
512 // Do this only if we are not exporting for internal usage, because
513 // pdflatex prefers png over pdf and it would pick up the png images
514 // that we generate for preview.
515 // This works only if the filename contains no dots besides
516 // the just removed one. We can fool here by replacing all
517 // dots with a macro whose definition is just a dot ;-)
518 // The automatic format selection does not work if the file
520 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
521 if (!nice || contains(latex_name, '"'))
523 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
527 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
529 // No conversion is needed. LaTeX can handle the graphic file as is.
530 // This is true even if the orig_file is compressed.
531 string const to_format = formats.getFormat(to)->extension();
532 string const file_format = getExtension(file);
533 // for latex .ps == .eps
534 if (to_format == file_format ||
535 (to_format == "eps" && file_format == "ps") ||
536 (to_format == "ps" && file_format == "eps"))
537 return stripExtensionIfPossible(file, nice);
538 return latex_path(file, EXCLUDE_EXTENSION);
544 string InsetGraphics::prepareFile(OutputParams const & runparams) const
546 // The following code depends on non-empty filenames
547 if (params().filename.empty())
550 string const orig_file = params().filename.availableFile().absFilename();
551 // this is for dryrun and display purposes, do not use latexFilename
552 string const rel_file = params().filename.relFilename(buffer().filePath());
554 // previewing source code, no file copying or file format conversion
555 if (runparams.dryrun)
556 return stripExtensionIfPossible(rel_file, runparams.nice);
558 // temp_file will contain the file for LaTeX to act on if, for example,
559 // we move it to a temp dir or uncompress it.
560 FileName temp_file = params().filename.availableFile();
562 // The master buffer. This is useful when there are multiple levels
564 Buffer const * masterBuffer = buffer().masterBuffer();
566 // Return the output name if we are inside a comment or the file does
568 // We are not going to change the extension or using the name of the
569 // temporary file, the code is already complicated enough.
570 if (runparams.inComment || !params().filename.isReadableFile())
571 return params().filename.outputFilename(masterBuffer->filePath());
573 // We place all temporary files in the master buffer's temp dir.
574 // This is possible because we use mangled file names.
575 // This is necessary for DVI export.
576 string const temp_path = masterBuffer->temppath();
578 GraphicsCopyStatus status;
579 boost::tie(status, temp_file) =
580 copyToDirIfNeeded(params().filename.availableFile(), temp_path);
582 if (status == FAILURE)
585 // a relative filename should be relative to the master buffer.
586 // "nice" means that the buffer is exported to LaTeX format but not
587 // run through the LaTeX compiler.
588 string output_file = runparams.nice ?
589 params().filename.outputFilename(masterBuffer->filePath()) :
590 onlyFilename(temp_file.absFilename());
592 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
593 frontend::Alert::warning(_("Invalid filename"),
594 _("The following filename is likely to cause trouble "
595 "when running the exported file through LaTeX: ") +
596 from_utf8(output_file));
599 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
600 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
601 "latex" : "pdflatex";
603 // If the file is compressed and we have specified that it
604 // should not be uncompressed, then just return its name and
605 // let LaTeX do the rest!
606 if (params().filename.isZipped()) {
607 if (params().noUnzip) {
608 // We don't know whether latex can actually handle
609 // this file, but we can't check, because that would
610 // mean to unzip the file and thereby making the
611 // noUnzip parameter meaningless.
612 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
614 FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
615 if (runparams.nice) {
616 runparams.exportdata->addExternalFile(tex_format,
618 changeExtension(output_file, "bb"));
620 // LaTeX needs the bounding box file in the
622 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
623 boost::tie(status, bb_file) =
624 copyFileIfNeeded(bb_orig_file, bb_file);
625 if (status == FAILURE)
627 runparams.exportdata->addExternalFile(tex_format,
630 runparams.exportdata->addExternalFile(tex_format,
631 source_file, output_file);
632 runparams.exportdata->addExternalFile("dvi",
633 source_file, output_file);
634 // We can't strip the extension, because we don't know
635 // the unzipped file format
636 return latex_path(output_file, EXCLUDE_EXTENSION);
639 FileName const unzipped_temp_file =
640 FileName(unzippedFileName(temp_file.absFilename()));
641 output_file = unzippedFileName(output_file);
642 source_file = FileName(unzippedFileName(source_file.absFilename()));
643 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
644 // temp_file has been unzipped already and
645 // orig_file has not changed in the meantime.
646 temp_file = unzipped_temp_file;
647 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
649 // unzipped_temp_file does not exist or is too old
650 temp_file = unzipFile(temp_file);
651 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
655 string const from = formats.getFormatFromFile(temp_file);
657 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
659 string const to = findTargetFormat(from, runparams);
660 string const ext = formats.extension(to);
661 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
663 // We're going to be running the exported buffer through the LaTeX
664 // compiler, so must ensure that LaTeX can cope with the graphics
667 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
670 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
671 // The LaTeX compiler will not be able to determine
672 // the file format from the extension, so we must
674 FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
675 if (temp_file.moveTo(new_file)) {
676 temp_file = new_file;
677 output_file = changeExtension(output_file, ext);
678 source_file = FileName(changeExtension(source_file.absFilename(), ext));
680 LYXERR(Debug::GRAPHICS, "Could not rename file `"
681 << temp_file << "' to `" << new_file << "'.");
684 // The extension of temp_file might be != ext!
685 runparams.exportdata->addExternalFile(tex_format, source_file,
687 runparams.exportdata->addExternalFile("dvi", source_file,
689 return stripExtensionIfPossible(output_file, to, runparams.nice);
692 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
693 string const output_to_file = changeExtension(output_file, ext);
695 // Do we need to perform the conversion?
696 // Yes if to_file does not exist or if temp_file is newer than to_file
697 if (compare_timestamps(temp_file, to_file) < 0) {
699 LYXERR(Debug::GRAPHICS,
700 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
701 from_utf8(rel_file))));
702 runparams.exportdata->addExternalFile(tex_format, to_file,
704 runparams.exportdata->addExternalFile("dvi", to_file,
706 return stripExtensionIfPossible(output_to_file, runparams.nice);
709 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
710 << "\tA copy has been made and convert is to be called with:\n"
711 << "\tfile to convert = " << temp_file << '\n'
712 << "\t from " << from << " to " << to);
714 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
716 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
718 Converters::try_default | Converters::try_cache)) {
719 runparams.exportdata->addExternalFile(tex_format,
720 to_file, output_to_file);
721 runparams.exportdata->addExternalFile("dvi",
722 to_file, output_to_file);
725 return stripExtensionIfPossible(output_to_file, runparams.nice);
729 int InsetGraphics::latex(odocstream & os,
730 OutputParams const & runparams) const
732 // If there is no file specified or not existing,
733 // just output a message about it in the latex output.
734 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
735 << params().filename.absFilename());
737 bool const file_exists = !params().filename.empty()
738 && params().filename.isReadableFile();
739 string const message = file_exists ?
740 string() : string("bb = 0 0 200 100, draft, type=eps");
741 // if !message.empty() then there was no existing file
742 // "filename" found. In this case LaTeX
743 // draws only a rectangle with the above bb and the
744 // not found filename in it.
745 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
747 // These variables collect all the latex code that should be before and
748 // after the actual includegraphics command.
752 if (runparams.moving_arg)
753 before += "\\protect";
755 // We never use the starred form, we use the "clip" option instead.
756 before += "\\includegraphics";
758 // Write the options if there are any.
759 string const opts = createLatexOptions();
760 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
762 if (!opts.empty() && !message.empty())
763 before += ('[' + opts + ',' + message + ']');
764 else if (!opts.empty() || !message.empty())
765 before += ('[' + opts + message + ']');
767 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
769 string latex_str = before + '{';
770 // Convert the file if necessary.
771 // Remove the extension so LaTeX will use whatever is appropriate
772 // (when there are several versions in different formats)
773 latex_str += prepareFile(runparams);
774 latex_str += '}' + after;
776 os << from_utf8(latex_str);
778 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
779 // Return how many newlines we issued.
780 return int(count(latex_str.begin(), latex_str.end(),'\n'));
784 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
786 // No graphics in ascii output. Possible to use gifscii to convert
787 // images to ascii approximation.
788 // 1. Convert file to ascii using gifscii
789 // 2. Read ascii output file and add it to the output stream.
790 // at least we send the filename
792 // FIXME: We have no idea what the encoding of the filename is
794 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
795 from_utf8(params().filename.absFilename()));
796 os << '<' << str << '>';
798 return 2 + str.size();
802 static int writeImageObject(char const * format, odocstream & os,
803 OutputParams const & runparams, docstring const & graphic_label,
804 docstring const & attributes)
806 if (runparams.flavor != OutputParams::XML)
807 os << "<![ %output.print." << format
810 os <<"<imageobject><imagedata fileref=\"&"
817 if (runparams.flavor == OutputParams::XML)
818 os << " role=\"" << format << "\"/>" ;
820 os << " format=\"" << format << "\">" ;
822 os << "</imageobject>";
824 if (runparams.flavor != OutputParams::XML)
825 os << endl << "]]>" ;
827 return runparams.flavor == OutputParams::XML ? 0 : 2;
831 // For explanation on inserting graphics into DocBook checkout:
832 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
833 // See also the docbook guide at http://www.docbook.org/
834 int InsetGraphics::docbook(odocstream & os,
835 OutputParams const & runparams) const
837 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
838 // need to switch to MediaObject. However, for now this is sufficient and
840 if (runparams.flavor == OutputParams::XML)
841 runparams.exportdata->addExternalFile("docbook-xml",
844 runparams.exportdata->addExternalFile("docbook",
847 os << "<inlinemediaobject>";
850 docstring attributes = createDocBookAttributes();
851 r += writeImageObject("png", os, runparams, graphic_label, attributes);
852 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
853 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
854 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
856 os << "</inlinemediaobject>";
861 void InsetGraphics::validate(LaTeXFeatures & features) const
863 // If we have no image, we should not require anything.
864 if (params().filename.empty())
867 features.includeFile(graphic_label,
868 removeExtension(params().filename.absFilename()));
870 features.require("graphicx");
872 if (features.runparams().nice) {
873 Buffer const * masterBuffer = features.buffer().masterBuffer();
874 string const rel_file = removeExtension(params().filename.relFilename(masterBuffer->filePath()));
875 if (contains(rel_file, "."))
876 features.require("lyxdot");
881 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
883 // If nothing is changed, just return and say so.
884 if (params() == p && !p.filename.empty())
887 // Copy the new parameters.
890 // Update the display using the new parameters.
891 graphic_->update(params().as_grfxParams());
893 // We have changed data, report it.
898 InsetGraphicsParams const & InsetGraphics::params() const
904 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
905 Buffer const & buffer) const
907 formats.edit(buffer, p.filename,
908 formats.getFormatFromFile(p.filename));
912 void InsetGraphics::addToToc(ParConstIterator const & cpit) const
914 TocBackend & backend = buffer().tocBackend();
916 docstring str = params_.filename.displayName();
917 if (params_.filename.embedded()) {
918 backend.toc("embedded").push_back(TocItem(cpit, 0, str));
919 str += _(" (embedded)");
921 backend.toc("graphics").push_back(TocItem(cpit, 0, str));
925 string const InsetGraphicsMailer::name_("graphics");
927 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
932 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
934 return params2string(inset_.params(), buffer);
938 void InsetGraphicsMailer::string2params(string const & in,
939 Buffer const & buffer,
940 InsetGraphicsParams & params)
942 params = InsetGraphicsParams();
946 istringstream data(in);
952 if (!lex || name != name_)
953 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
956 inset.readInsetGraphics(lex, buffer.filePath());
957 params = inset.params();
962 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
963 Buffer const & buffer)
966 data << name_ << ' ';
967 params.Write(data, buffer);
968 data << "\\end_inset\n";