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 "LaTeXFeatures.h"
65 #include "MetricsInfo.h"
67 #include "OutputParams.h"
69 #include "EmbeddedFiles.h"
71 #include "frontends/alert.h"
73 #include "support/convert.h"
74 #include "support/debug.h"
75 #include "support/docstream.h"
76 #include "support/ExceptionMessage.h"
77 #include "support/filetools.h"
78 #include "support/gettext.h"
79 #include "support/lyxlib.h"
80 #include "support/lstrings.h"
81 #include "support/os.h"
82 #include "support/Systemcall.h"
84 #include <boost/bind.hpp>
85 #include <boost/tuple/tuple.hpp>
91 using namespace lyx::support;
95 namespace Alert = frontend::Alert;
99 /// Find the most suitable image format for images in \p format
100 /// Note that \p format may be unknown (i. e. an empty string)
101 string findTargetFormat(string const & format, OutputParams const & runparams)
103 // Are we using latex or pdflatex?
104 if (runparams.flavor == OutputParams::PDFLATEX) {
105 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
106 Format const * const f = formats.getFormat(format);
107 // Convert vector graphics to pdf
108 if (f && f->vectorFormat())
110 // pdflatex can use jpeg, png and pdf directly
113 // Convert everything else to png
116 // If it's postscript, we always do eps.
117 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
119 // any other than ps is changed to eps
128 InsetGraphics::InsetGraphics()
129 : graphic_label(sgml::uniqueID(from_ascii("graph"))),
130 graphic_(new RenderGraphic(this))
134 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
136 boost::signals::trackable(),
137 graphic_label(sgml::uniqueID(from_ascii("graph"))),
138 graphic_(new RenderGraphic(*ig.graphic_, this))
140 setParams(ig.params());
144 Inset * InsetGraphics::clone() const
146 return new InsetGraphics(*this);
150 InsetGraphics::~InsetGraphics()
152 InsetGraphicsMailer(*this).hideDialog();
156 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
158 switch (cmd.action) {
159 case LFUN_GRAPHICS_EDIT: {
160 InsetGraphicsParams p;
161 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
162 editGraphics(p, buffer());
166 case LFUN_INSET_MODIFY: {
167 InsetGraphicsParams p;
168 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
169 if (!p.filename.empty()) {
171 p.filename.enable(buffer().embedded(), &buffer());
172 } catch (ExceptionMessage const & message) {
173 Alert::error(message.title_, message.details_);
174 // do not set parameter if an error happens
183 case LFUN_INSET_DIALOG_UPDATE:
184 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
187 case LFUN_MOUSE_RELEASE:
188 if (!cur.selection())
189 InsetGraphicsMailer(*this).showDialog(&cur.bv());
193 Inset::doDispatch(cur, cmd);
199 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
200 FuncStatus & flag) const
202 switch (cmd.action) {
203 case LFUN_GRAPHICS_EDIT:
204 case LFUN_INSET_MODIFY:
205 case LFUN_INSET_DIALOG_UPDATE:
210 return Inset::getStatus(cur, cmd, flag);
215 void InsetGraphics::registerEmbeddedFiles(EmbeddedFileList & files) const
217 files.registerFile(params().filename, this, buffer());
221 void InsetGraphics::updateEmbeddedFile(EmbeddedFile const & file)
223 // when embedding is enabled, change of embedding status leads to actions
224 EmbeddedFile temp = file;
225 temp.enable(buffer().embedded(), &buffer());
226 // this will not be set if an exception is thorwn in enable()
227 params_.filename = temp;
229 LYXERR(Debug::FILES, "Update InsetGraphic with File "
230 << params_.filename.toFilesystemEncoding()
231 << ", embedding status: " << params_.filename.embedded()
232 << ", enabled: " << params_.filename.enabled());
236 void InsetGraphics::edit(Cursor & cur, bool, EntryDirection)
238 InsetGraphicsMailer(*this).showDialog(&cur.bv());
242 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
244 graphic_->metrics(mi, dim);
248 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
250 graphic_->draw(pi, x, y);
254 Inset::EDITABLE InsetGraphics::editable() const
260 void InsetGraphics::write(ostream & os) const
263 params().Write(os, buffer());
267 void InsetGraphics::read(Lexer & lex)
269 string const token = lex.getString();
271 if (token == "Graphics")
272 readInsetGraphics(lex, buffer().filePath());
274 LYXERR(Debug::GRAPHICS, "Not a Graphics inset!");
276 params_.filename.enable(buffer().embedded(), &buffer());
277 graphic_->update(params().as_grfxParams());
281 void InsetGraphics::readInsetGraphics(Lexer & lex, string const & bufpath)
283 bool finished = false;
285 while (lex.isOK() && !finished) {
288 string const token = lex.getString();
289 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
294 if (token == "\\end_inset") {
297 if (!params_.Read(lex, token, bufpath))
298 lyxerr << "Unknown token, " << token << ", skipping."
305 string const InsetGraphics::createLatexOptions() const
307 // Calculate the options part of the command, we must do it to a string
308 // stream since we might have a trailing comma that we would like to remove
309 // before writing it to the output stream.
310 ostringstream options;
311 if (!params().bb.empty())
312 options << "bb=" << rtrim(params().bb) << ',';
318 double const scl = convert<double>(params().scale);
319 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
320 if (!float_equal(scl, 100.0, 0.05))
321 size << "scale=" << scl / 100.0 << ',';
323 if (!params().width.zero())
324 size << "width=" << params().width.asLatexString() << ',';
325 if (!params().height.zero())
326 size << "height=" << params().height.asLatexString() << ',';
327 if (params().keepAspectRatio)
328 size << "keepaspectratio,";
330 if (params().scaleBeforeRotation && !size.str().empty())
331 options << size.str();
333 // Make sure rotation angle is not very close to zero;
334 // a float can be effectively zero but not exactly zero.
335 if (!params().rotateAngle.empty()
336 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
337 options << "angle=" << params().rotateAngle << ',';
338 if (!params().rotateOrigin.empty()) {
339 options << "origin=" << params().rotateOrigin[0];
340 if (contains(params().rotateOrigin,"Top"))
342 else if (contains(params().rotateOrigin,"Bottom"))
344 else if (contains(params().rotateOrigin,"Baseline"))
349 if (!params().scaleBeforeRotation && !size.str().empty())
350 options << size.str();
352 if (!params().special.empty())
353 options << params().special << ',';
355 string opts = options.str();
357 if (suffixIs(opts, ','))
358 opts = opts.substr(0, opts.size() - 1);
364 docstring const InsetGraphics::toDocbookLength(Length const & len) const
366 odocstringstream result;
367 switch (len.unit()) {
368 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
369 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
371 case Length::PT: // Point = 1/72.27in = 0.351mm
372 result << len.value() * 72 / 72.27 << "pt";
374 case Length::BP: // Big point (72bp = 1in), also PostScript point
375 result << len.value() << "pt";
377 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
378 result << len.value() * 0.376 << "mm";
380 case Length::MM: // Millimeter = 2.845pt
381 result << len.value() << "mm";
383 case Length::PC: // Pica = 12pt = 4.218mm
384 result << len.value() << "pc";
386 case Length::CC: // Cicero = 12dd = 4.531mm
387 result << len.value() * 4.531 << "mm";
389 case Length::CM: // Centimeter = 10mm = 2.371pc
390 result << len.value() << "cm";
392 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
393 result << len.value() << "in";
395 case Length::EX: // Height of a small "x" for the current font.
396 // Obviously we have to compromise here. Any better ratio than 1.5 ?
397 result << len.value() / 1.5 << "em";
399 case Length::EM: // Width of capital "M" in current font.
400 result << len.value() << "em";
402 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
403 result << len.value() * 18 << "em";
405 case Length::PTW: // Percent of TextWidth
406 case Length::PCW: // Percent of ColumnWidth
407 case Length::PPW: // Percent of PageWidth
408 case Length::PLW: // Percent of LineWidth
409 case Length::PTH: // Percent of TextHeight
410 case Length::PPH: // Percent of Paper
411 // Sigh, this will go wrong.
412 result << len.value() << "%";
415 result << len.asDocstring();
421 docstring const InsetGraphics::createDocBookAttributes() const
423 // Calculate the options part of the command, we must do it to a string
424 // stream since we copied the code from createLatexParams() ;-)
426 // FIXME: av: need to translate spec -> Docbook XSL spec
427 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
428 // Right now it only works with my version of db2latex :-)
430 odocstringstream options;
431 double const scl = convert<double>(params().scale);
432 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
433 if (!float_equal(scl, 100.0, 0.05))
434 options << " scale=\""
435 << static_cast<int>( (scl) + 0.5 )
438 if (!params().width.zero()) {
439 options << " width=\"" << toDocbookLength(params().width) << "\" ";
441 if (!params().height.zero()) {
442 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
444 if (params().keepAspectRatio) {
445 // This will be irrelevant unless both width and height are set
446 options << "scalefit=\"1\" ";
451 if (!params().special.empty())
452 options << from_ascii(params().special) << " ";
454 // trailing blanks are ok ...
455 return options.str();
461 enum GraphicsCopyStatus {
469 pair<GraphicsCopyStatus, FileName> const
470 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
472 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
473 unsigned long const checksum_in = file_in.checksum();
474 unsigned long const checksum_out = file_out.checksum();
476 if (checksum_in == checksum_out)
478 return make_pair(IDENTICAL_CONTENTS, file_out);
480 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
481 bool const success = mover.copy(file_in, file_out);
484 LYXERR(Debug::GRAPHICS,
485 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
486 "into the temporary directory."),
487 from_utf8(file_in.absFilename()))));
490 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
491 return make_pair(status, file_out);
495 pair<GraphicsCopyStatus, FileName> const
496 copyToDirIfNeeded(DocFileName const & file, string const & dir)
498 string const file_in = file.absFilename();
499 string const only_path = onlyPath(file_in);
500 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
501 return make_pair(IDENTICAL_PATHS, file_in);
503 string mangled = file.mangledFilename();
504 if (file.isZipped()) {
505 // We need to change _eps.gz to .eps.gz. The mangled name is
506 // still unique because of the counter in mangledFilename().
507 // We can't just call mangledFilename() with the zip
508 // extension removed, because base.eps and base.eps.gz may
509 // have different content but would get the same mangled
510 // name in this case.
511 string const base = removeExtension(file.unzippedFilename());
512 string::size_type const ext_len = file_in.length() - base.length();
513 mangled[mangled.length() - ext_len] = '.';
515 FileName const file_out(makeAbsPath(mangled, dir));
517 return copyFileIfNeeded(file, file_out);
521 string const stripExtensionIfPossible(string const & file, bool nice)
523 // Remove the extension so the LaTeX compiler will use whatever
524 // is appropriate (when there are several versions in different
526 // Do this only if we are not exporting for internal usage, because
527 // pdflatex prefers png over pdf and it would pick up the png images
528 // that we generate for preview.
529 // This works only if the filename contains no dots besides
530 // the just removed one. We can fool here by replacing all
531 // dots with a macro whose definition is just a dot ;-)
532 // The automatic format selection does not work if the file
534 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
535 if (!nice || contains(latex_name, '"'))
537 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
541 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
543 // No conversion is needed. LaTeX can handle the graphic file as is.
544 // This is true even if the orig_file is compressed.
545 string const to_format = formats.getFormat(to)->extension();
546 string const file_format = getExtension(file);
547 // for latex .ps == .eps
548 if (to_format == file_format ||
549 (to_format == "eps" && file_format == "ps") ||
550 (to_format == "ps" && file_format == "eps"))
551 return stripExtensionIfPossible(file, nice);
552 return latex_path(file, EXCLUDE_EXTENSION);
558 string InsetGraphics::prepareFile(OutputParams const & runparams) const
560 // The following code depends on non-empty filenames
561 if (params().filename.empty())
564 string const orig_file = params().filename.availableFile().absFilename();
565 // this is for dryrun and display purposes, do not use latexFilename
566 string const rel_file = params().filename.relFilename(buffer().filePath());
568 // previewing source code, no file copying or file format conversion
569 if (runparams.dryrun)
570 return stripExtensionIfPossible(rel_file, runparams.nice);
572 // temp_file will contain the file for LaTeX to act on if, for example,
573 // we move it to a temp dir or uncompress it.
574 FileName temp_file = params().filename.availableFile();
576 // The master buffer. This is useful when there are multiple levels
578 Buffer const * masterBuffer = buffer().masterBuffer();
580 // Return the output name if we are inside a comment or the file does
582 // We are not going to change the extension or using the name of the
583 // temporary file, the code is already complicated enough.
584 if (runparams.inComment || !params().filename.isReadableFile())
585 return params().filename.outputFilename(masterBuffer->filePath());
587 // We place all temporary files in the master buffer's temp dir.
588 // This is possible because we use mangled file names.
589 // This is necessary for DVI export.
590 string const temp_path = masterBuffer->temppath();
592 GraphicsCopyStatus status;
593 boost::tie(status, temp_file) =
594 copyToDirIfNeeded(params().filename.availableFile(), temp_path);
596 if (status == FAILURE)
599 // a relative filename should be relative to the master buffer.
600 // "nice" means that the buffer is exported to LaTeX format but not
601 // run through the LaTeX compiler.
602 string output_file = runparams.nice ?
603 params().filename.outputFilename(masterBuffer->filePath()) :
604 onlyFilename(temp_file.absFilename());
606 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
607 frontend::Alert::warning(_("Invalid filename"),
608 _("The following filename is likely to cause trouble "
609 "when running the exported file through LaTeX: ") +
610 from_utf8(output_file));
613 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
614 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
615 "latex" : "pdflatex";
617 // If the file is compressed and we have specified that it
618 // should not be uncompressed, then just return its name and
619 // let LaTeX do the rest!
620 if (params().filename.isZipped()) {
621 if (params().noUnzip) {
622 // We don't know whether latex can actually handle
623 // this file, but we can't check, because that would
624 // mean to unzip the file and thereby making the
625 // noUnzip parameter meaningless.
626 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
628 FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
629 if (runparams.nice) {
630 runparams.exportdata->addExternalFile(tex_format,
632 changeExtension(output_file, "bb"));
634 // LaTeX needs the bounding box file in the
636 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
637 boost::tie(status, bb_file) =
638 copyFileIfNeeded(bb_orig_file, bb_file);
639 if (status == FAILURE)
641 runparams.exportdata->addExternalFile(tex_format,
644 runparams.exportdata->addExternalFile(tex_format,
645 source_file, output_file);
646 runparams.exportdata->addExternalFile("dvi",
647 source_file, output_file);
648 // We can't strip the extension, because we don't know
649 // the unzipped file format
650 return latex_path(output_file, EXCLUDE_EXTENSION);
653 FileName const unzipped_temp_file =
654 FileName(unzippedFileName(temp_file.absFilename()));
655 output_file = unzippedFileName(output_file);
656 source_file = FileName(unzippedFileName(source_file.absFilename()));
657 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
658 // temp_file has been unzipped already and
659 // orig_file has not changed in the meantime.
660 temp_file = unzipped_temp_file;
661 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
663 // unzipped_temp_file does not exist or is too old
664 temp_file = unzipFile(temp_file);
665 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
669 string const from = formats.getFormatFromFile(temp_file);
671 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
673 string const to = findTargetFormat(from, runparams);
674 string const ext = formats.extension(to);
675 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
677 // We're going to be running the exported buffer through the LaTeX
678 // compiler, so must ensure that LaTeX can cope with the graphics
681 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
684 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
685 // The LaTeX compiler will not be able to determine
686 // the file format from the extension, so we must
688 FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
689 if (temp_file.moveTo(new_file)) {
690 temp_file = new_file;
691 output_file = changeExtension(output_file, ext);
692 source_file = FileName(changeExtension(source_file.absFilename(), ext));
694 LYXERR(Debug::GRAPHICS, "Could not rename file `"
695 << temp_file << "' to `" << new_file << "'.");
698 // The extension of temp_file might be != ext!
699 runparams.exportdata->addExternalFile(tex_format, source_file,
701 runparams.exportdata->addExternalFile("dvi", source_file,
703 return stripExtensionIfPossible(output_file, to, runparams.nice);
706 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
707 string const output_to_file = changeExtension(output_file, ext);
709 // Do we need to perform the conversion?
710 // Yes if to_file does not exist or if temp_file is newer than to_file
711 if (compare_timestamps(temp_file, to_file) < 0) {
713 LYXERR(Debug::GRAPHICS,
714 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
715 from_utf8(rel_file))));
716 runparams.exportdata->addExternalFile(tex_format, to_file,
718 runparams.exportdata->addExternalFile("dvi", to_file,
720 return stripExtensionIfPossible(output_to_file, runparams.nice);
723 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
724 << "\tA copy has been made and convert is to be called with:\n"
725 << "\tfile to convert = " << temp_file << '\n'
726 << "\t from " << from << " to " << to);
728 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
730 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
732 Converters::try_default | Converters::try_cache)) {
733 runparams.exportdata->addExternalFile(tex_format,
734 to_file, output_to_file);
735 runparams.exportdata->addExternalFile("dvi",
736 to_file, output_to_file);
739 return stripExtensionIfPossible(output_to_file, runparams.nice);
743 int InsetGraphics::latex(odocstream & os,
744 OutputParams const & runparams) const
746 // If there is no file specified or not existing,
747 // just output a message about it in the latex output.
748 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
749 << params().filename.absFilename());
751 bool const file_exists = !params().filename.empty()
752 && params().filename.isReadableFile();
753 string const message = file_exists ?
754 string() : string("bb = 0 0 200 100, draft, type=eps");
755 // if !message.empty() then there was no existing file
756 // "filename" found. In this case LaTeX
757 // draws only a rectangle with the above bb and the
758 // not found filename in it.
759 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
761 // These variables collect all the latex code that should be before and
762 // after the actual includegraphics command.
766 if (runparams.moving_arg)
767 before += "\\protect";
769 // We never use the starred form, we use the "clip" option instead.
770 before += "\\includegraphics";
772 // Write the options if there are any.
773 string const opts = createLatexOptions();
774 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
776 if (!opts.empty() && !message.empty())
777 before += ('[' + opts + ',' + message + ']');
778 else if (!opts.empty() || !message.empty())
779 before += ('[' + opts + message + ']');
781 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
783 string latex_str = before + '{';
784 // Convert the file if necessary.
785 // Remove the extension so LaTeX will use whatever is appropriate
786 // (when there are several versions in different formats)
787 latex_str += prepareFile(runparams);
788 latex_str += '}' + after;
790 os << from_utf8(latex_str);
792 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
793 // Return how many newlines we issued.
794 return int(count(latex_str.begin(), latex_str.end(),'\n'));
798 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
800 // No graphics in ascii output. Possible to use gifscii to convert
801 // images to ascii approximation.
802 // 1. Convert file to ascii using gifscii
803 // 2. Read ascii output file and add it to the output stream.
804 // at least we send the filename
806 // FIXME: We have no idea what the encoding of the filename is
808 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
809 from_utf8(params().filename.absFilename()));
810 os << '<' << str << '>';
812 return 2 + str.size();
816 static int writeImageObject(char const * format, odocstream & os,
817 OutputParams const & runparams, docstring const & graphic_label,
818 docstring const & attributes)
820 if (runparams.flavor != OutputParams::XML)
821 os << "<![ %output.print." << format
824 os <<"<imageobject><imagedata fileref=\"&"
831 if (runparams.flavor == OutputParams::XML)
832 os << " role=\"" << format << "\"/>" ;
834 os << " format=\"" << format << "\">" ;
836 os << "</imageobject>";
838 if (runparams.flavor != OutputParams::XML)
839 os << endl << "]]>" ;
841 return runparams.flavor == OutputParams::XML ? 0 : 2;
845 // For explanation on inserting graphics into DocBook checkout:
846 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
847 // See also the docbook guide at http://www.docbook.org/
848 int InsetGraphics::docbook(odocstream & os,
849 OutputParams const & runparams) const
851 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
852 // need to switch to MediaObject. However, for now this is sufficient and
854 if (runparams.flavor == OutputParams::XML)
855 runparams.exportdata->addExternalFile("docbook-xml",
858 runparams.exportdata->addExternalFile("docbook",
861 os << "<inlinemediaobject>";
864 docstring attributes = createDocBookAttributes();
865 r += writeImageObject("png", os, runparams, graphic_label, attributes);
866 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
867 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
868 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
870 os << "</inlinemediaobject>";
875 void InsetGraphics::validate(LaTeXFeatures & features) const
877 // If we have no image, we should not require anything.
878 if (params().filename.empty())
881 features.includeFile(graphic_label,
882 removeExtension(params().filename.absFilename()));
884 features.require("graphicx");
886 if (features.runparams().nice) {
887 Buffer const * masterBuffer = features.buffer().masterBuffer();
888 string const rel_file = removeExtension(params().filename.relFilename(masterBuffer->filePath()));
889 if (contains(rel_file, "."))
890 features.require("lyxdot");
895 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
897 // If nothing is changed, just return and say so.
898 if (params() == p && !p.filename.empty())
901 // Copy the new parameters.
904 // Update the display using the new parameters.
905 graphic_->update(params().as_grfxParams());
907 // We have changed data, report it.
912 InsetGraphicsParams const & InsetGraphics::params() const
918 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
919 Buffer const & buffer) const
921 formats.edit(buffer, p.filename,
922 formats.getFormatFromFile(p.filename));
926 string const InsetGraphicsMailer::name_("graphics");
928 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
933 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
935 return params2string(inset_.params(), buffer);
939 void InsetGraphicsMailer::string2params(string const & in,
940 Buffer const & buffer,
941 InsetGraphicsParams & params)
943 params = InsetGraphicsParams();
947 istringstream data(in);
953 if (!lex || name != name_)
954 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
957 inset.readInsetGraphics(lex, buffer.filePath());
958 params = inset.params();
963 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
964 Buffer const & buffer)
967 data << name_ << ' ';
968 params.Write(data, buffer);
969 data << "\\end_inset\n";