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::setBuffer(Buffer & buffer)
161 // a file may not be copied successfully when, e.g. buffer_
162 // has already been closed.
163 params_.filename = params_.filename.copyTo(&buffer);
164 } catch (ExceptionMessage const & message) {
165 Alert::error(message.title_, message.details_);
167 params_.filename.setEmbed(false);
170 Inset::setBuffer(buffer);
174 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
176 switch (cmd.action) {
177 case LFUN_GRAPHICS_EDIT: {
178 // use buffer() from cursor because this inset may not
179 // have an initialized buffer_.
180 Buffer const & buf = cur.bv().buffer();
181 InsetGraphicsParams p;
182 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buf, p);
183 editGraphics(p, buf);
187 case LFUN_INSET_MODIFY: {
188 InsetGraphicsParams p;
189 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
190 if (!p.filename.empty())
197 case LFUN_INSET_DIALOG_UPDATE:
198 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
201 case LFUN_MOUSE_RELEASE:
202 if (!cur.selection())
203 InsetGraphicsMailer(*this).showDialog(&cur.bv());
207 Inset::doDispatch(cur, cmd);
213 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
214 FuncStatus & flag) const
216 switch (cmd.action) {
217 case LFUN_GRAPHICS_EDIT:
218 case LFUN_INSET_MODIFY:
219 case LFUN_INSET_DIALOG_UPDATE:
224 return Inset::getStatus(cur, cmd, flag);
229 void InsetGraphics::registerEmbeddedFiles(EmbeddedFileList & files) const
231 files.registerFile(params().filename, this, buffer());
235 void InsetGraphics::updateEmbeddedFile(EmbeddedFile const & file)
237 // only properties of an embedded file can be changed here.
238 params_.filename = file;
242 void InsetGraphics::edit(Cursor & cur, bool, EntryDirection)
244 InsetGraphicsMailer(*this).showDialog(&cur.bv());
248 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
250 graphic_->metrics(mi, dim);
254 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
256 graphic_->draw(pi, x, y);
260 Inset::EDITABLE InsetGraphics::editable() const
266 void InsetGraphics::write(ostream & os) const
269 params().Write(os, buffer());
273 void InsetGraphics::read(Lexer & lex)
275 string const token = lex.getString();
277 if (token == "Graphics")
278 readInsetGraphics(lex, buffer().filePath());
280 LYXERR(Debug::GRAPHICS, "Not a Graphics inset!");
282 params_.filename.enable(buffer().embedded(), &buffer(), false);
283 graphic_->update(params().as_grfxParams());
287 void InsetGraphics::readInsetGraphics(Lexer & lex, string const & bufpath)
289 bool finished = false;
291 while (lex.isOK() && !finished) {
294 string const token = lex.getString();
295 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
300 if (token == "\\end_inset") {
303 if (!params_.Read(lex, token, bufpath))
304 lyxerr << "Unknown token, " << token << ", skipping."
311 string const InsetGraphics::createLatexOptions() const
313 // Calculate the options part of the command, we must do it to a string
314 // stream since we might have a trailing comma that we would like to remove
315 // before writing it to the output stream.
316 ostringstream options;
317 if (!params().bb.empty())
318 options << "bb=" << rtrim(params().bb) << ',';
324 double const scl = convert<double>(params().scale);
325 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
326 if (!float_equal(scl, 100.0, 0.05))
327 size << "scale=" << scl / 100.0 << ',';
329 if (!params().width.zero())
330 size << "width=" << params().width.asLatexString() << ',';
331 if (!params().height.zero())
332 size << "height=" << params().height.asLatexString() << ',';
333 if (params().keepAspectRatio)
334 size << "keepaspectratio,";
336 if (params().scaleBeforeRotation && !size.str().empty())
337 options << size.str();
339 // Make sure rotation angle is not very close to zero;
340 // a float can be effectively zero but not exactly zero.
341 if (!params().rotateAngle.empty()
342 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
343 options << "angle=" << params().rotateAngle << ',';
344 if (!params().rotateOrigin.empty()) {
345 options << "origin=" << params().rotateOrigin[0];
346 if (contains(params().rotateOrigin,"Top"))
348 else if (contains(params().rotateOrigin,"Bottom"))
350 else if (contains(params().rotateOrigin,"Baseline"))
355 if (!params().scaleBeforeRotation && !size.str().empty())
356 options << size.str();
358 if (!params().special.empty())
359 options << params().special << ',';
361 string opts = options.str();
363 if (suffixIs(opts, ','))
364 opts = opts.substr(0, opts.size() - 1);
370 docstring const InsetGraphics::toDocbookLength(Length const & len) const
372 odocstringstream result;
373 switch (len.unit()) {
374 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
375 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
377 case Length::PT: // Point = 1/72.27in = 0.351mm
378 result << len.value() * 72 / 72.27 << "pt";
380 case Length::BP: // Big point (72bp = 1in), also PostScript point
381 result << len.value() << "pt";
383 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
384 result << len.value() * 0.376 << "mm";
386 case Length::MM: // Millimeter = 2.845pt
387 result << len.value() << "mm";
389 case Length::PC: // Pica = 12pt = 4.218mm
390 result << len.value() << "pc";
392 case Length::CC: // Cicero = 12dd = 4.531mm
393 result << len.value() * 4.531 << "mm";
395 case Length::CM: // Centimeter = 10mm = 2.371pc
396 result << len.value() << "cm";
398 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
399 result << len.value() << "in";
401 case Length::EX: // Height of a small "x" for the current font.
402 // Obviously we have to compromise here. Any better ratio than 1.5 ?
403 result << len.value() / 1.5 << "em";
405 case Length::EM: // Width of capital "M" in current font.
406 result << len.value() << "em";
408 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
409 result << len.value() * 18 << "em";
411 case Length::PTW: // Percent of TextWidth
412 case Length::PCW: // Percent of ColumnWidth
413 case Length::PPW: // Percent of PageWidth
414 case Length::PLW: // Percent of LineWidth
415 case Length::PTH: // Percent of TextHeight
416 case Length::PPH: // Percent of Paper
417 // Sigh, this will go wrong.
418 result << len.value() << "%";
421 result << len.asDocstring();
427 docstring const InsetGraphics::createDocBookAttributes() const
429 // Calculate the options part of the command, we must do it to a string
430 // stream since we copied the code from createLatexParams() ;-)
432 // FIXME: av: need to translate spec -> Docbook XSL spec
433 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
434 // Right now it only works with my version of db2latex :-)
436 odocstringstream options;
437 double const scl = convert<double>(params().scale);
438 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
439 if (!float_equal(scl, 100.0, 0.05))
440 options << " scale=\""
441 << static_cast<int>( (scl) + 0.5 )
444 if (!params().width.zero()) {
445 options << " width=\"" << toDocbookLength(params().width) << "\" ";
447 if (!params().height.zero()) {
448 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
450 if (params().keepAspectRatio) {
451 // This will be irrelevant unless both width and height are set
452 options << "scalefit=\"1\" ";
457 if (!params().special.empty())
458 options << from_ascii(params().special) << " ";
460 // trailing blanks are ok ...
461 return options.str();
467 enum GraphicsCopyStatus {
475 pair<GraphicsCopyStatus, FileName> const
476 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
478 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
479 unsigned long const checksum_in = file_in.checksum();
480 unsigned long const checksum_out = file_out.checksum();
482 if (checksum_in == checksum_out)
484 return make_pair(IDENTICAL_CONTENTS, file_out);
486 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
487 bool const success = mover.copy(file_in, file_out);
490 LYXERR(Debug::GRAPHICS,
491 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
492 "into the temporary directory."),
493 from_utf8(file_in.absFilename()))));
496 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
497 return make_pair(status, file_out);
501 pair<GraphicsCopyStatus, FileName> const
502 copyToDirIfNeeded(DocFileName const & file, string const & dir)
504 string const file_in = file.absFilename();
505 string const only_path = onlyPath(file_in);
506 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
507 return make_pair(IDENTICAL_PATHS, file_in);
509 string mangled = file.mangledFilename();
510 if (file.isZipped()) {
511 // We need to change _eps.gz to .eps.gz. The mangled name is
512 // still unique because of the counter in mangledFilename().
513 // We can't just call mangledFilename() with the zip
514 // extension removed, because base.eps and base.eps.gz may
515 // have different content but would get the same mangled
516 // name in this case.
517 string const base = removeExtension(file.unzippedFilename());
518 string::size_type const ext_len = file_in.length() - base.length();
519 mangled[mangled.length() - ext_len] = '.';
521 FileName const file_out(makeAbsPath(mangled, dir));
523 return copyFileIfNeeded(file, file_out);
527 string const stripExtensionIfPossible(string const & file, bool nice)
529 // Remove the extension so the LaTeX compiler will use whatever
530 // is appropriate (when there are several versions in different
532 // Do this only if we are not exporting for internal usage, because
533 // pdflatex prefers png over pdf and it would pick up the png images
534 // that we generate for preview.
535 // This works only if the filename contains no dots besides
536 // the just removed one. We can fool here by replacing all
537 // dots with a macro whose definition is just a dot ;-)
538 // The automatic format selection does not work if the file
540 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
541 if (!nice || contains(latex_name, '"'))
543 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
547 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
549 // No conversion is needed. LaTeX can handle the graphic file as is.
550 // This is true even if the orig_file is compressed.
551 string const to_format = formats.getFormat(to)->extension();
552 string const file_format = getExtension(file);
553 // for latex .ps == .eps
554 if (to_format == file_format ||
555 (to_format == "eps" && file_format == "ps") ||
556 (to_format == "ps" && file_format == "eps"))
557 return stripExtensionIfPossible(file, nice);
558 return latex_path(file, EXCLUDE_EXTENSION);
564 string InsetGraphics::prepareFile(OutputParams const & runparams) const
566 // The following code depends on non-empty filenames
567 if (params().filename.empty())
570 string const orig_file = params().filename.availableFile().absFilename();
571 // this is for dryrun and display purposes, do not use latexFilename
572 string const rel_file = params().filename.relFilename(buffer().filePath());
574 // previewing source code, no file copying or file format conversion
575 if (runparams.dryrun)
576 return stripExtensionIfPossible(rel_file, runparams.nice);
578 // temp_file will contain the file for LaTeX to act on if, for example,
579 // we move it to a temp dir or uncompress it.
580 FileName temp_file = params().filename.availableFile();
582 // The master buffer. This is useful when there are multiple levels
584 Buffer const * masterBuffer = buffer().masterBuffer();
586 // Return the output name if we are inside a comment or the file does
588 // We are not going to change the extension or using the name of the
589 // temporary file, the code is already complicated enough.
590 if (runparams.inComment || !params().filename.isReadableFile())
591 return params().filename.outputFilename(masterBuffer->filePath());
593 // We place all temporary files in the master buffer's temp dir.
594 // This is possible because we use mangled file names.
595 // This is necessary for DVI export.
596 string const temp_path = masterBuffer->temppath();
598 GraphicsCopyStatus status;
599 boost::tie(status, temp_file) =
600 copyToDirIfNeeded(params().filename.availableFile(), temp_path);
602 if (status == FAILURE)
605 // a relative filename should be relative to the master buffer.
606 // "nice" means that the buffer is exported to LaTeX format but not
607 // run through the LaTeX compiler.
608 string output_file = runparams.nice ?
609 params().filename.outputFilename(masterBuffer->filePath()) :
610 onlyFilename(temp_file.absFilename());
612 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
613 frontend::Alert::warning(_("Invalid filename"),
614 _("The following filename is likely to cause trouble "
615 "when running the exported file through LaTeX: ") +
616 from_utf8(output_file));
619 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
620 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
621 "latex" : "pdflatex";
623 // If the file is compressed and we have specified that it
624 // should not be uncompressed, then just return its name and
625 // let LaTeX do the rest!
626 if (params().filename.isZipped()) {
627 if (params().noUnzip) {
628 // We don't know whether latex can actually handle
629 // this file, but we can't check, because that would
630 // mean to unzip the file and thereby making the
631 // noUnzip parameter meaningless.
632 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
634 FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
635 if (runparams.nice) {
636 runparams.exportdata->addExternalFile(tex_format,
638 changeExtension(output_file, "bb"));
640 // LaTeX needs the bounding box file in the
642 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
643 boost::tie(status, bb_file) =
644 copyFileIfNeeded(bb_orig_file, bb_file);
645 if (status == FAILURE)
647 runparams.exportdata->addExternalFile(tex_format,
650 runparams.exportdata->addExternalFile(tex_format,
651 source_file, output_file);
652 runparams.exportdata->addExternalFile("dvi",
653 source_file, output_file);
654 // We can't strip the extension, because we don't know
655 // the unzipped file format
656 return latex_path(output_file, EXCLUDE_EXTENSION);
659 FileName const unzipped_temp_file =
660 FileName(unzippedFileName(temp_file.absFilename()));
661 output_file = unzippedFileName(output_file);
662 source_file = FileName(unzippedFileName(source_file.absFilename()));
663 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
664 // temp_file has been unzipped already and
665 // orig_file has not changed in the meantime.
666 temp_file = unzipped_temp_file;
667 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
669 // unzipped_temp_file does not exist or is too old
670 temp_file = unzipFile(temp_file);
671 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
675 string const from = formats.getFormatFromFile(temp_file);
677 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
679 string const to = findTargetFormat(from, runparams);
680 string const ext = formats.extension(to);
681 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
683 // We're going to be running the exported buffer through the LaTeX
684 // compiler, so must ensure that LaTeX can cope with the graphics
687 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
690 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
691 // The LaTeX compiler will not be able to determine
692 // the file format from the extension, so we must
694 FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
695 if (temp_file.moveTo(new_file)) {
696 temp_file = new_file;
697 output_file = changeExtension(output_file, ext);
698 source_file = FileName(changeExtension(source_file.absFilename(), ext));
700 LYXERR(Debug::GRAPHICS, "Could not rename file `"
701 << temp_file << "' to `" << new_file << "'.");
704 // The extension of temp_file might be != ext!
705 runparams.exportdata->addExternalFile(tex_format, source_file,
707 runparams.exportdata->addExternalFile("dvi", source_file,
709 return stripExtensionIfPossible(output_file, to, runparams.nice);
712 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
713 string const output_to_file = changeExtension(output_file, ext);
715 // Do we need to perform the conversion?
716 // Yes if to_file does not exist or if temp_file is newer than to_file
717 if (compare_timestamps(temp_file, to_file) < 0) {
719 LYXERR(Debug::GRAPHICS,
720 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
721 from_utf8(rel_file))));
722 runparams.exportdata->addExternalFile(tex_format, to_file,
724 runparams.exportdata->addExternalFile("dvi", to_file,
726 return stripExtensionIfPossible(output_to_file, runparams.nice);
729 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
730 << "\tA copy has been made and convert is to be called with:\n"
731 << "\tfile to convert = " << temp_file << '\n'
732 << "\t from " << from << " to " << to);
734 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
736 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
738 Converters::try_default | Converters::try_cache)) {
739 runparams.exportdata->addExternalFile(tex_format,
740 to_file, output_to_file);
741 runparams.exportdata->addExternalFile("dvi",
742 to_file, output_to_file);
745 return stripExtensionIfPossible(output_to_file, runparams.nice);
749 int InsetGraphics::latex(odocstream & os,
750 OutputParams const & runparams) const
752 // If there is no file specified or not existing,
753 // just output a message about it in the latex output.
754 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
755 << params().filename.absFilename());
757 bool const file_exists = !params().filename.empty()
758 && params().filename.isReadableFile();
759 string const message = file_exists ?
760 string() : string("bb = 0 0 200 100, draft, type=eps");
761 // if !message.empty() then there was no existing file
762 // "filename" found. In this case LaTeX
763 // draws only a rectangle with the above bb and the
764 // not found filename in it.
765 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
767 // These variables collect all the latex code that should be before and
768 // after the actual includegraphics command.
772 if (runparams.moving_arg)
773 before += "\\protect";
775 // We never use the starred form, we use the "clip" option instead.
776 before += "\\includegraphics";
778 // Write the options if there are any.
779 string const opts = createLatexOptions();
780 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
782 if (!opts.empty() && !message.empty())
783 before += ('[' + opts + ',' + message + ']');
784 else if (!opts.empty() || !message.empty())
785 before += ('[' + opts + message + ']');
787 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
789 string latex_str = before + '{';
790 // Convert the file if necessary.
791 // Remove the extension so LaTeX will use whatever is appropriate
792 // (when there are several versions in different formats)
793 latex_str += prepareFile(runparams);
794 latex_str += '}' + after;
796 os << from_utf8(latex_str);
798 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
799 // Return how many newlines we issued.
800 return int(count(latex_str.begin(), latex_str.end(),'\n'));
804 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
806 // No graphics in ascii output. Possible to use gifscii to convert
807 // images to ascii approximation.
808 // 1. Convert file to ascii using gifscii
809 // 2. Read ascii output file and add it to the output stream.
810 // at least we send the filename
812 // FIXME: We have no idea what the encoding of the filename is
814 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
815 from_utf8(params().filename.absFilename()));
816 os << '<' << str << '>';
818 return 2 + str.size();
822 static int writeImageObject(char const * format, odocstream & os,
823 OutputParams const & runparams, docstring const & graphic_label,
824 docstring const & attributes)
826 if (runparams.flavor != OutputParams::XML)
827 os << "<![ %output.print." << format
830 os <<"<imageobject><imagedata fileref=\"&"
837 if (runparams.flavor == OutputParams::XML)
838 os << " role=\"" << format << "\"/>" ;
840 os << " format=\"" << format << "\">" ;
842 os << "</imageobject>";
844 if (runparams.flavor != OutputParams::XML)
845 os << endl << "]]>" ;
847 return runparams.flavor == OutputParams::XML ? 0 : 2;
851 // For explanation on inserting graphics into DocBook checkout:
852 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
853 // See also the docbook guide at http://www.docbook.org/
854 int InsetGraphics::docbook(odocstream & os,
855 OutputParams const & runparams) const
857 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
858 // need to switch to MediaObject. However, for now this is sufficient and
860 if (runparams.flavor == OutputParams::XML)
861 runparams.exportdata->addExternalFile("docbook-xml",
864 runparams.exportdata->addExternalFile("docbook",
867 os << "<inlinemediaobject>";
870 docstring attributes = createDocBookAttributes();
871 r += writeImageObject("png", os, runparams, graphic_label, attributes);
872 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
873 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
874 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
876 os << "</inlinemediaobject>";
881 void InsetGraphics::validate(LaTeXFeatures & features) const
883 // If we have no image, we should not require anything.
884 if (params().filename.empty())
887 features.includeFile(graphic_label,
888 removeExtension(params().filename.absFilename()));
890 features.require("graphicx");
892 if (features.runparams().nice) {
893 Buffer const * masterBuffer = features.buffer().masterBuffer();
894 string const rel_file = removeExtension(params().filename.relFilename(masterBuffer->filePath()));
895 if (contains(rel_file, "."))
896 features.require("lyxdot");
901 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
903 // If nothing is changed, just return and say so.
904 if (params() == p && !p.filename.empty())
907 // Copy the new parameters.
910 // Update the display using the new parameters.
911 graphic_->update(params().as_grfxParams());
913 // We have changed data, report it.
918 InsetGraphicsParams const & InsetGraphics::params() const
924 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
925 Buffer const & buffer) const
927 formats.edit(buffer, p.filename,
928 formats.getFormatFromFile(p.filename));
932 void InsetGraphics::addToToc(ParConstIterator const & cpit) const
934 TocBackend & backend = buffer().tocBackend();
936 docstring str = params_.filename.displayName();
937 if (params_.filename.embedded()) {
938 backend.toc("embedded").push_back(TocItem(cpit, 0, str));
939 str += _(" (embedded)");
941 backend.toc("graphics").push_back(TocItem(cpit, 0, str));
945 string const InsetGraphicsMailer::name_("graphics");
947 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
952 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
954 return params2string(inset_.params(), buffer);
958 void InsetGraphicsMailer::string2params(string const & in,
959 Buffer const & buffer,
960 InsetGraphicsParams & params)
962 params = InsetGraphicsParams();
966 istringstream data(in);
972 if (!lex || name != name_)
973 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
976 inset.readInsetGraphics(lex, buffer.filePath());
977 params = inset.params();
982 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
983 Buffer const & buffer)
986 data << name_ << ' ';
987 params.Write(data, buffer);
988 data << "\\end_inset\n";