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"
73 #include "frontends/Application.h"
75 #include "support/convert.h"
76 #include "support/debug.h"
77 #include "support/docstream.h"
78 #include "support/ExceptionMessage.h"
79 #include "support/filetools.h"
80 #include "support/gettext.h"
81 #include "support/lyxlib.h"
82 #include "support/lstrings.h"
83 #include "support/os.h"
84 #include "support/Systemcall.h"
86 #include <boost/bind.hpp>
87 #include <boost/tuple/tuple.hpp>
93 using namespace lyx::support;
97 namespace Alert = frontend::Alert;
101 /// Find the most suitable image format for images in \p format
102 /// Note that \p format may be unknown (i. e. an empty string)
103 string findTargetFormat(string const & format, OutputParams const & runparams)
105 // Are we using latex or pdflatex?
106 if (runparams.flavor == OutputParams::PDFLATEX) {
107 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
108 Format const * const f = formats.getFormat(format);
109 // Convert vector graphics to pdf
110 if (f && f->vectorFormat())
112 // pdflatex can use jpeg, png and pdf directly
115 // Convert everything else to png
118 // If it's postscript, we always do eps.
119 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
121 // any other than ps is changed to eps
128 void readInsetGraphics(Lexer & lex, string const & bufpath,
129 InsetGraphicsParams & params)
131 bool finished = false;
133 while (lex.isOK() && !finished) {
136 string const token = lex.getString();
137 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
142 if (token == "\\end_inset") {
145 if (!params.Read(lex, token, bufpath))
146 lyxerr << "Unknown token, " << token << ", skipping."
155 InsetGraphics::InsetGraphics(Buffer & buf)
156 : graphic_label(sgml::uniqueID(from_ascii("graph"))),
157 graphic_(new RenderGraphic(this))
159 Inset::setBuffer(buf);
163 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
165 boost::signals::trackable(),
166 graphic_label(sgml::uniqueID(from_ascii("graph"))),
167 graphic_(new RenderGraphic(*ig.graphic_, this))
169 setParams(ig.params());
173 Inset * InsetGraphics::clone() const
175 return new InsetGraphics(*this);
179 InsetGraphics::~InsetGraphics()
181 hideDialogs("graphics", this);
185 void InsetGraphics::setBuffer(Buffer & buffer)
189 // a file may not be copied successfully when, e.g. buffer_
190 // has already been closed.
191 params_.filename = params_.filename.copyTo(buffer);
192 } catch (ExceptionMessage const & message) {
193 Alert::error(message.title_, message.details_);
195 params_.filename.setEmbed(false);
198 Inset::setBuffer(buffer);
202 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
204 switch (cmd.action) {
205 case LFUN_GRAPHICS_EDIT: {
206 InsetGraphicsParams p = params();
207 if (!cmd.argument().empty())
208 string2params(to_utf8(cmd.argument()), buffer(), p);
209 editGraphics(p, buffer());
213 case LFUN_INSET_MODIFY: {
214 InsetGraphicsParams p;
215 string2params(to_utf8(cmd.argument()), buffer(), p);
216 if (!p.filename.empty())
223 case LFUN_INSET_DIALOG_UPDATE:
224 cur.bv().updateDialog("graphics", params2string(params(),
228 case LFUN_MOUSE_RELEASE:
229 if (!cur.selection() && cmd.button() == mouse_button::button1)
230 cur.bv().showDialog("graphics", params2string(params(),
231 cur.bv().buffer()), this);
235 Inset::doDispatch(cur, cmd);
241 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
242 FuncStatus & flag) const
244 switch (cmd.action) {
245 case LFUN_GRAPHICS_EDIT:
246 case LFUN_INSET_MODIFY:
247 case LFUN_INSET_DIALOG_UPDATE:
252 return Inset::getStatus(cur, cmd, flag);
257 void InsetGraphics::registerEmbeddedFiles(EmbeddedFileList & files) const
259 files.registerFile(params().filename, this, buffer());
263 void InsetGraphics::updateEmbeddedFile(EmbeddedFile const & file)
265 // only properties of an embedded file can be changed here.
266 params_.filename = file;
270 void InsetGraphics::edit(Cursor & cur, bool, EntryDirection)
272 cur.bv().showDialog("graphics", params2string(params(),
273 cur.bv().buffer()), this);
277 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
279 graphic_->metrics(mi, dim);
283 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
285 graphic_->draw(pi, x, y);
289 Inset::EDITABLE InsetGraphics::editable() const
295 void InsetGraphics::write(ostream & os) const
298 params().Write(os, buffer());
302 void InsetGraphics::read(Lexer & lex)
304 lex.setContext("InsetGraphics::read");
306 readInsetGraphics(lex, buffer().filePath(), params_);
307 params_.filename.enable(buffer().embedded(), buffer(), false);
308 graphic_->update(params().as_grfxParams());
312 string InsetGraphics::createLatexOptions() const
314 // Calculate the options part of the command, we must do it to a string
315 // stream since we might have a trailing comma that we would like to remove
316 // before writing it to the output stream.
317 ostringstream options;
318 if (!params().bb.empty())
319 options << "bb=" << rtrim(params().bb) << ',';
325 double const scl = convert<double>(params().scale);
326 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
327 if (!float_equal(scl, 100.0, 0.05))
328 size << "scale=" << scl / 100.0 << ',';
330 if (!params().width.zero())
331 size << "width=" << params().width.asLatexString() << ',';
332 if (!params().height.zero())
333 size << "height=" << params().height.asLatexString() << ',';
334 if (params().keepAspectRatio)
335 size << "keepaspectratio,";
337 if (params().scaleBeforeRotation && !size.str().empty())
338 options << size.str();
340 // Make sure rotation angle is not very close to zero;
341 // a float can be effectively zero but not exactly zero.
342 if (!params().rotateAngle.empty()
343 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
344 options << "angle=" << params().rotateAngle << ',';
345 if (!params().rotateOrigin.empty()) {
346 options << "origin=" << params().rotateOrigin[0];
347 if (contains(params().rotateOrigin,"Top"))
349 else if (contains(params().rotateOrigin,"Bottom"))
351 else if (contains(params().rotateOrigin,"Baseline"))
356 if (!params().scaleBeforeRotation && !size.str().empty())
357 options << size.str();
359 if (!params().special.empty())
360 options << params().special << ',';
362 string opts = options.str();
364 if (suffixIs(opts, ','))
365 opts = opts.substr(0, opts.size() - 1);
371 docstring InsetGraphics::toDocbookLength(Length const & len) const
373 odocstringstream result;
374 switch (len.unit()) {
375 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
376 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
378 case Length::PT: // Point = 1/72.27in = 0.351mm
379 result << len.value() * 72 / 72.27 << "pt";
381 case Length::BP: // Big point (72bp = 1in), also PostScript point
382 result << len.value() << "pt";
384 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
385 result << len.value() * 0.376 << "mm";
387 case Length::MM: // Millimeter = 2.845pt
388 result << len.value() << "mm";
390 case Length::PC: // Pica = 12pt = 4.218mm
391 result << len.value() << "pc";
393 case Length::CC: // Cicero = 12dd = 4.531mm
394 result << len.value() * 4.531 << "mm";
396 case Length::CM: // Centimeter = 10mm = 2.371pc
397 result << len.value() << "cm";
399 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
400 result << len.value() << "in";
402 case Length::EX: // Height of a small "x" for the current font.
403 // Obviously we have to compromise here. Any better ratio than 1.5 ?
404 result << len.value() / 1.5 << "em";
406 case Length::EM: // Width of capital "M" in current font.
407 result << len.value() << "em";
409 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
410 result << len.value() * 18 << "em";
412 case Length::PTW: // Percent of TextWidth
413 case Length::PCW: // Percent of ColumnWidth
414 case Length::PPW: // Percent of PageWidth
415 case Length::PLW: // Percent of LineWidth
416 case Length::PTH: // Percent of TextHeight
417 case Length::PPH: // Percent of Paper
418 // Sigh, this will go wrong.
419 result << len.value() << "%";
422 result << len.asDocstring();
429 docstring InsetGraphics::createDocBookAttributes() const
431 // Calculate the options part of the command, we must do it to a string
432 // stream since we copied the code from createLatexParams() ;-)
434 // FIXME: av: need to translate spec -> Docbook XSL spec
435 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
436 // Right now it only works with my version of db2latex :-)
438 odocstringstream options;
439 double const scl = convert<double>(params().scale);
440 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
441 if (!float_equal(scl, 100.0, 0.05))
442 options << " scale=\""
443 << static_cast<int>( (scl) + 0.5 )
446 if (!params().width.zero()) {
447 options << " width=\"" << toDocbookLength(params().width) << "\" ";
449 if (!params().height.zero()) {
450 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
452 if (params().keepAspectRatio) {
453 // This will be irrelevant unless both width and height are set
454 options << "scalefit=\"1\" ";
459 if (!params().special.empty())
460 options << from_ascii(params().special) << " ";
462 // trailing blanks are ok ...
463 return options.str();
469 enum GraphicsCopyStatus {
477 pair<GraphicsCopyStatus, FileName> const
478 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
480 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
481 unsigned long const checksum_in = file_in.checksum();
482 unsigned long const checksum_out = file_out.checksum();
484 if (checksum_in == checksum_out)
486 return make_pair(IDENTICAL_CONTENTS, file_out);
488 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
489 bool const success = mover.copy(file_in, file_out);
492 LYXERR(Debug::GRAPHICS,
493 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
494 "into the temporary directory."),
495 from_utf8(file_in.absFilename()))));
498 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
499 return make_pair(status, file_out);
503 pair<GraphicsCopyStatus, FileName> const
504 copyToDirIfNeeded(DocFileName const & file, string const & dir)
506 string const file_in = file.absFilename();
507 string const only_path = onlyPath(file_in);
508 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
509 return make_pair(IDENTICAL_PATHS, file_in);
511 string mangled = file.mangledFilename();
512 if (file.isZipped()) {
513 // We need to change _eps.gz to .eps.gz. The mangled name is
514 // still unique because of the counter in mangledFilename().
515 // We can't just call mangledFilename() with the zip
516 // extension removed, because base.eps and base.eps.gz may
517 // have different content but would get the same mangled
518 // name in this case.
519 string const base = removeExtension(file.unzippedFilename());
520 string::size_type const ext_len = file_in.length() - base.length();
521 mangled[mangled.length() - ext_len] = '.';
523 FileName const file_out(makeAbsPath(mangled, dir));
525 return copyFileIfNeeded(file, file_out);
529 string const stripExtensionIfPossible(string const & file, bool nice)
531 // Remove the extension so the LaTeX compiler will use whatever
532 // is appropriate (when there are several versions in different
534 // Do this only if we are not exporting for internal usage, because
535 // pdflatex prefers png over pdf and it would pick up the png images
536 // that we generate for preview.
537 // This works only if the filename contains no dots besides
538 // the just removed one. We can fool here by replacing all
539 // dots with a macro whose definition is just a dot ;-)
540 // The automatic format selection does not work if the file
542 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
543 if (!nice || contains(latex_name, '"'))
545 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
549 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
551 // No conversion is needed. LaTeX can handle the graphic file as is.
552 // This is true even if the orig_file is compressed.
553 string const to_format = formats.getFormat(to)->extension();
554 string const file_format = getExtension(file);
555 // for latex .ps == .eps
556 if (to_format == file_format ||
557 (to_format == "eps" && file_format == "ps") ||
558 (to_format == "ps" && file_format == "eps"))
559 return stripExtensionIfPossible(file, nice);
560 return latex_path(file, EXCLUDE_EXTENSION);
566 string InsetGraphics::prepareFile(OutputParams const & runparams) const
568 // The following code depends on non-empty filenames
569 if (params().filename.empty())
572 string const orig_file = params().filename.availableFile().absFilename();
573 // this is for dryrun and display purposes, do not use latexFilename
574 string const rel_file = params().filename.relFilename(buffer().filePath());
576 // previewing source code, no file copying or file format conversion
577 if (runparams.dryrun)
578 return stripExtensionIfPossible(rel_file, runparams.nice);
580 // temp_file will contain the file for LaTeX to act on if, for example,
581 // we move it to a temp dir or uncompress it.
582 FileName temp_file = params().filename.availableFile();
584 // The master buffer. This is useful when there are multiple levels
586 Buffer const * masterBuffer = buffer().masterBuffer();
588 // Return the output name if we are inside a comment or the file does
590 // We are not going to change the extension or using the name of the
591 // temporary file, the code is already complicated enough.
592 if (runparams.inComment || !params().filename.isReadableFile())
593 return params().filename.outputFilename(masterBuffer->filePath());
595 // We place all temporary files in the master buffer's temp dir.
596 // This is possible because we use mangled file names.
597 // This is necessary for DVI export.
598 string const temp_path = masterBuffer->temppath();
600 GraphicsCopyStatus status;
601 boost::tie(status, temp_file) =
602 copyToDirIfNeeded(params().filename.availableFile(), temp_path);
604 if (status == FAILURE)
607 // a relative filename should be relative to the master buffer.
608 // "nice" means that the buffer is exported to LaTeX format but not
609 // run through the LaTeX compiler.
610 string output_file = runparams.nice ?
611 params().filename.outputFilename(masterBuffer->filePath()) :
612 onlyFilename(temp_file.absFilename());
614 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
615 frontend::Alert::warning(_("Invalid filename"),
616 _("The following filename is likely to cause trouble "
617 "when running the exported file through LaTeX: ") +
618 from_utf8(output_file));
621 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
622 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
623 "latex" : "pdflatex";
625 // If the file is compressed and we have specified that it
626 // should not be uncompressed, then just return its name and
627 // let LaTeX do the rest!
628 if (params().filename.isZipped()) {
629 if (params().noUnzip) {
630 // We don't know whether latex can actually handle
631 // this file, but we can't check, because that would
632 // mean to unzip the file and thereby making the
633 // noUnzip parameter meaningless.
634 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
636 FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
637 if (runparams.nice) {
638 runparams.exportdata->addExternalFile(tex_format,
640 changeExtension(output_file, "bb"));
642 // LaTeX needs the bounding box file in the
644 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
645 boost::tie(status, bb_file) =
646 copyFileIfNeeded(bb_orig_file, bb_file);
647 if (status == FAILURE)
649 runparams.exportdata->addExternalFile(tex_format,
652 runparams.exportdata->addExternalFile(tex_format,
653 source_file, output_file);
654 runparams.exportdata->addExternalFile("dvi",
655 source_file, output_file);
656 // We can't strip the extension, because we don't know
657 // the unzipped file format
658 return latex_path(output_file, EXCLUDE_EXTENSION);
661 FileName const unzipped_temp_file =
662 FileName(unzippedFileName(temp_file.absFilename()));
663 output_file = unzippedFileName(output_file);
664 source_file = FileName(unzippedFileName(source_file.absFilename()));
665 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
666 // temp_file has been unzipped already and
667 // orig_file has not changed in the meantime.
668 temp_file = unzipped_temp_file;
669 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
671 // unzipped_temp_file does not exist or is too old
672 temp_file = unzipFile(temp_file);
673 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
677 string const from = formats.getFormatFromFile(temp_file);
679 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
681 string const to = findTargetFormat(from, runparams);
682 string const ext = formats.extension(to);
683 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
685 // We're going to be running the exported buffer through the LaTeX
686 // compiler, so must ensure that LaTeX can cope with the graphics
689 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
692 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
693 // The LaTeX compiler will not be able to determine
694 // the file format from the extension, so we must
696 FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
697 if (temp_file.moveTo(new_file)) {
698 temp_file = new_file;
699 output_file = changeExtension(output_file, ext);
700 source_file = FileName(changeExtension(source_file.absFilename(), ext));
702 LYXERR(Debug::GRAPHICS, "Could not rename file `"
703 << temp_file << "' to `" << new_file << "'.");
706 // The extension of temp_file might be != ext!
707 runparams.exportdata->addExternalFile(tex_format, source_file,
709 runparams.exportdata->addExternalFile("dvi", source_file,
711 return stripExtensionIfPossible(output_file, to, runparams.nice);
714 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
715 string const output_to_file = changeExtension(output_file, ext);
717 // Do we need to perform the conversion?
718 // Yes if to_file does not exist or if temp_file is newer than to_file
719 if (compare_timestamps(temp_file, to_file) < 0) {
721 LYXERR(Debug::GRAPHICS,
722 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
723 from_utf8(rel_file))));
724 runparams.exportdata->addExternalFile(tex_format, to_file,
726 runparams.exportdata->addExternalFile("dvi", to_file,
728 return stripExtensionIfPossible(output_to_file, runparams.nice);
731 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
732 << "\tA copy has been made and convert is to be called with:\n"
733 << "\tfile to convert = " << temp_file << '\n'
734 << "\t from " << from << " to " << to);
736 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
738 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
740 Converters::try_default | Converters::try_cache)) {
741 runparams.exportdata->addExternalFile(tex_format,
742 to_file, output_to_file);
743 runparams.exportdata->addExternalFile("dvi",
744 to_file, output_to_file);
747 return stripExtensionIfPossible(output_to_file, runparams.nice);
751 int InsetGraphics::latex(odocstream & os,
752 OutputParams const & runparams) const
754 // If there is no file specified or not existing,
755 // just output a message about it in the latex output.
756 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
757 << params().filename.absFilename());
759 bool const file_exists = !params().filename.empty()
760 && params().filename.isReadableFile();
761 string const message = file_exists ?
762 string() : string("bb = 0 0 200 100, draft, type=eps");
763 // if !message.empty() then there was no existing file
764 // "filename" found. In this case LaTeX
765 // draws only a rectangle with the above bb and the
766 // not found filename in it.
767 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
769 // These variables collect all the latex code that should be before and
770 // after the actual includegraphics command.
774 if (runparams.moving_arg)
775 before += "\\protect";
777 // We never use the starred form, we use the "clip" option instead.
778 before += "\\includegraphics";
780 // Write the options if there are any.
781 string const opts = createLatexOptions();
782 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
784 if (!opts.empty() && !message.empty())
785 before += ('[' + opts + ',' + message + ']');
786 else if (!opts.empty() || !message.empty())
787 before += ('[' + opts + message + ']');
789 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
791 string latex_str = before + '{';
792 // Convert the file if necessary.
793 // Remove the extension so LaTeX will use whatever is appropriate
794 // (when there are several versions in different formats)
795 latex_str += prepareFile(runparams);
796 latex_str += '}' + after;
798 os << from_utf8(latex_str);
800 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
801 // Return how many newlines we issued.
802 return int(count(latex_str.begin(), latex_str.end(),'\n'));
806 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
808 // No graphics in ascii output. Possible to use gifscii to convert
809 // images to ascii approximation.
810 // 1. Convert file to ascii using gifscii
811 // 2. Read ascii output file and add it to the output stream.
812 // at least we send the filename
814 // FIXME: We have no idea what the encoding of the filename is
816 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
817 from_utf8(params().filename.absFilename()));
818 os << '<' << str << '>';
820 return 2 + str.size();
824 static int writeImageObject(char const * format, odocstream & os,
825 OutputParams const & runparams, docstring const & graphic_label,
826 docstring const & attributes)
828 if (runparams.flavor != OutputParams::XML)
829 os << "<![ %output.print." << format
832 os <<"<imageobject><imagedata fileref=\"&"
839 if (runparams.flavor == OutputParams::XML)
840 os << " role=\"" << format << "\"/>" ;
842 os << " format=\"" << format << "\">" ;
844 os << "</imageobject>";
846 if (runparams.flavor != OutputParams::XML)
847 os << endl << "]]>" ;
849 return runparams.flavor == OutputParams::XML ? 0 : 2;
853 // For explanation on inserting graphics into DocBook checkout:
854 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
855 // See also the docbook guide at http://www.docbook.org/
856 int InsetGraphics::docbook(odocstream & os,
857 OutputParams const & runparams) const
859 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
860 // need to switch to MediaObject. However, for now this is sufficient and
862 if (runparams.flavor == OutputParams::XML)
863 runparams.exportdata->addExternalFile("docbook-xml",
866 runparams.exportdata->addExternalFile("docbook",
869 os << "<inlinemediaobject>";
872 docstring attributes = createDocBookAttributes();
873 r += writeImageObject("png", os, runparams, graphic_label, attributes);
874 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
875 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
876 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
878 os << "</inlinemediaobject>";
883 void InsetGraphics::validate(LaTeXFeatures & features) const
885 // If we have no image, we should not require anything.
886 if (params().filename.empty())
889 features.includeFile(graphic_label,
890 removeExtension(params().filename.absFilename()));
892 features.require("graphicx");
894 if (features.runparams().nice) {
895 Buffer const * masterBuffer = features.buffer().masterBuffer();
896 string const rel_file = removeExtension(params().filename.relFilename(masterBuffer->filePath()));
897 if (contains(rel_file, "."))
898 features.require("lyxdot");
903 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
905 // If nothing is changed, just return and say so.
906 if (params() == p && !p.filename.empty())
909 // Copy the new parameters.
912 // Update the display using the new parameters.
913 graphic_->update(params().as_grfxParams());
915 // We have changed data, report it.
920 InsetGraphicsParams const & InsetGraphics::params() const
926 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
927 Buffer const & buffer) const
929 formats.edit(buffer, p.filename,
930 formats.getFormatFromFile(p.filename));
934 void InsetGraphics::addToToc(ParConstIterator const & cpit) const
936 TocBackend & backend = buffer().tocBackend();
938 docstring str = params_.filename.displayName();
939 if (params_.filename.embedded()) {
940 backend.toc("embedded").push_back(TocItem(cpit, 0, str));
941 str += _(" (embedded)");
943 backend.toc("graphics").push_back(TocItem(cpit, 0, str));
947 docstring InsetGraphics::contextMenu(BufferView const &, int, int) const
949 return from_ascii("context-graphics");
953 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
954 InsetGraphicsParams & params)
959 istringstream data(in);
962 lex.setContext("InsetGraphics::string2params");
964 params = InsetGraphicsParams();
965 readInsetGraphics(lex, buffer.filePath(), params);
969 string InsetGraphics::params2string(InsetGraphicsParams const & params,
970 Buffer const & buffer)
973 data << "graphics" << ' ';
974 params.Write(data, buffer);
975 data << "\\end_inset\n";