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 InsetGraphicsParams p;
179 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
180 editGraphics(p, buffer());
184 case LFUN_INSET_MODIFY: {
185 InsetGraphicsParams p;
186 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
187 if (!p.filename.empty())
194 case LFUN_INSET_DIALOG_UPDATE:
195 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
198 case LFUN_MOUSE_RELEASE:
199 if (!cur.selection())
200 InsetGraphicsMailer(*this).showDialog(&cur.bv());
204 Inset::doDispatch(cur, cmd);
210 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
211 FuncStatus & flag) const
213 switch (cmd.action) {
214 case LFUN_GRAPHICS_EDIT:
215 case LFUN_INSET_MODIFY:
216 case LFUN_INSET_DIALOG_UPDATE:
221 return Inset::getStatus(cur, cmd, flag);
226 void InsetGraphics::registerEmbeddedFiles(EmbeddedFileList & files) const
228 files.registerFile(params().filename, this, buffer());
232 void InsetGraphics::updateEmbeddedFile(EmbeddedFile const & file)
234 // only properties of an embedded file can be changed here.
235 params_.filename = file;
239 void InsetGraphics::edit(Cursor & cur, bool, EntryDirection)
241 InsetGraphicsMailer(*this).showDialog(&cur.bv());
245 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
247 graphic_->metrics(mi, dim);
251 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
253 graphic_->draw(pi, x, y);
257 Inset::EDITABLE InsetGraphics::editable() const
263 void InsetGraphics::write(ostream & os) const
266 params().Write(os, buffer());
270 void InsetGraphics::read(Lexer & lex)
272 string const token = lex.getString();
274 if (token == "Graphics")
275 readInsetGraphics(lex, buffer().filePath());
277 LYXERR(Debug::GRAPHICS, "Not a Graphics inset!");
279 params_.filename.enable(buffer().embedded(), &buffer(), false);
280 graphic_->update(params().as_grfxParams());
284 void InsetGraphics::readInsetGraphics(Lexer & lex, string const & bufpath)
286 bool finished = false;
288 while (lex.isOK() && !finished) {
291 string const token = lex.getString();
292 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
297 if (token == "\\end_inset") {
300 if (!params_.Read(lex, token, bufpath))
301 lyxerr << "Unknown token, " << token << ", skipping."
308 string const InsetGraphics::createLatexOptions() const
310 // Calculate the options part of the command, we must do it to a string
311 // stream since we might have a trailing comma that we would like to remove
312 // before writing it to the output stream.
313 ostringstream options;
314 if (!params().bb.empty())
315 options << "bb=" << rtrim(params().bb) << ',';
321 double const scl = convert<double>(params().scale);
322 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
323 if (!float_equal(scl, 100.0, 0.05))
324 size << "scale=" << scl / 100.0 << ',';
326 if (!params().width.zero())
327 size << "width=" << params().width.asLatexString() << ',';
328 if (!params().height.zero())
329 size << "height=" << params().height.asLatexString() << ',';
330 if (params().keepAspectRatio)
331 size << "keepaspectratio,";
333 if (params().scaleBeforeRotation && !size.str().empty())
334 options << size.str();
336 // Make sure rotation angle is not very close to zero;
337 // a float can be effectively zero but not exactly zero.
338 if (!params().rotateAngle.empty()
339 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
340 options << "angle=" << params().rotateAngle << ',';
341 if (!params().rotateOrigin.empty()) {
342 options << "origin=" << params().rotateOrigin[0];
343 if (contains(params().rotateOrigin,"Top"))
345 else if (contains(params().rotateOrigin,"Bottom"))
347 else if (contains(params().rotateOrigin,"Baseline"))
352 if (!params().scaleBeforeRotation && !size.str().empty())
353 options << size.str();
355 if (!params().special.empty())
356 options << params().special << ',';
358 string opts = options.str();
360 if (suffixIs(opts, ','))
361 opts = opts.substr(0, opts.size() - 1);
367 docstring const InsetGraphics::toDocbookLength(Length const & len) const
369 odocstringstream result;
370 switch (len.unit()) {
371 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
372 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
374 case Length::PT: // Point = 1/72.27in = 0.351mm
375 result << len.value() * 72 / 72.27 << "pt";
377 case Length::BP: // Big point (72bp = 1in), also PostScript point
378 result << len.value() << "pt";
380 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
381 result << len.value() * 0.376 << "mm";
383 case Length::MM: // Millimeter = 2.845pt
384 result << len.value() << "mm";
386 case Length::PC: // Pica = 12pt = 4.218mm
387 result << len.value() << "pc";
389 case Length::CC: // Cicero = 12dd = 4.531mm
390 result << len.value() * 4.531 << "mm";
392 case Length::CM: // Centimeter = 10mm = 2.371pc
393 result << len.value() << "cm";
395 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
396 result << len.value() << "in";
398 case Length::EX: // Height of a small "x" for the current font.
399 // Obviously we have to compromise here. Any better ratio than 1.5 ?
400 result << len.value() / 1.5 << "em";
402 case Length::EM: // Width of capital "M" in current font.
403 result << len.value() << "em";
405 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
406 result << len.value() * 18 << "em";
408 case Length::PTW: // Percent of TextWidth
409 case Length::PCW: // Percent of ColumnWidth
410 case Length::PPW: // Percent of PageWidth
411 case Length::PLW: // Percent of LineWidth
412 case Length::PTH: // Percent of TextHeight
413 case Length::PPH: // Percent of Paper
414 // Sigh, this will go wrong.
415 result << len.value() << "%";
418 result << len.asDocstring();
424 docstring const InsetGraphics::createDocBookAttributes() const
426 // Calculate the options part of the command, we must do it to a string
427 // stream since we copied the code from createLatexParams() ;-)
429 // FIXME: av: need to translate spec -> Docbook XSL spec
430 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
431 // Right now it only works with my version of db2latex :-)
433 odocstringstream options;
434 double const scl = convert<double>(params().scale);
435 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
436 if (!float_equal(scl, 100.0, 0.05))
437 options << " scale=\""
438 << static_cast<int>( (scl) + 0.5 )
441 if (!params().width.zero()) {
442 options << " width=\"" << toDocbookLength(params().width) << "\" ";
444 if (!params().height.zero()) {
445 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
447 if (params().keepAspectRatio) {
448 // This will be irrelevant unless both width and height are set
449 options << "scalefit=\"1\" ";
454 if (!params().special.empty())
455 options << from_ascii(params().special) << " ";
457 // trailing blanks are ok ...
458 return options.str();
464 enum GraphicsCopyStatus {
472 pair<GraphicsCopyStatus, FileName> const
473 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
475 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
476 unsigned long const checksum_in = file_in.checksum();
477 unsigned long const checksum_out = file_out.checksum();
479 if (checksum_in == checksum_out)
481 return make_pair(IDENTICAL_CONTENTS, file_out);
483 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
484 bool const success = mover.copy(file_in, file_out);
487 LYXERR(Debug::GRAPHICS,
488 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
489 "into the temporary directory."),
490 from_utf8(file_in.absFilename()))));
493 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
494 return make_pair(status, file_out);
498 pair<GraphicsCopyStatus, FileName> const
499 copyToDirIfNeeded(DocFileName const & file, string const & dir)
501 string const file_in = file.absFilename();
502 string const only_path = onlyPath(file_in);
503 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
504 return make_pair(IDENTICAL_PATHS, file_in);
506 string mangled = file.mangledFilename();
507 if (file.isZipped()) {
508 // We need to change _eps.gz to .eps.gz. The mangled name is
509 // still unique because of the counter in mangledFilename().
510 // We can't just call mangledFilename() with the zip
511 // extension removed, because base.eps and base.eps.gz may
512 // have different content but would get the same mangled
513 // name in this case.
514 string const base = removeExtension(file.unzippedFilename());
515 string::size_type const ext_len = file_in.length() - base.length();
516 mangled[mangled.length() - ext_len] = '.';
518 FileName const file_out(makeAbsPath(mangled, dir));
520 return copyFileIfNeeded(file, file_out);
524 string const stripExtensionIfPossible(string const & file, bool nice)
526 // Remove the extension so the LaTeX compiler will use whatever
527 // is appropriate (when there are several versions in different
529 // Do this only if we are not exporting for internal usage, because
530 // pdflatex prefers png over pdf and it would pick up the png images
531 // that we generate for preview.
532 // This works only if the filename contains no dots besides
533 // the just removed one. We can fool here by replacing all
534 // dots with a macro whose definition is just a dot ;-)
535 // The automatic format selection does not work if the file
537 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
538 if (!nice || contains(latex_name, '"'))
540 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
544 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
546 // No conversion is needed. LaTeX can handle the graphic file as is.
547 // This is true even if the orig_file is compressed.
548 string const to_format = formats.getFormat(to)->extension();
549 string const file_format = getExtension(file);
550 // for latex .ps == .eps
551 if (to_format == file_format ||
552 (to_format == "eps" && file_format == "ps") ||
553 (to_format == "ps" && file_format == "eps"))
554 return stripExtensionIfPossible(file, nice);
555 return latex_path(file, EXCLUDE_EXTENSION);
561 string InsetGraphics::prepareFile(OutputParams const & runparams) const
563 // The following code depends on non-empty filenames
564 if (params().filename.empty())
567 string const orig_file = params().filename.availableFile().absFilename();
568 // this is for dryrun and display purposes, do not use latexFilename
569 string const rel_file = params().filename.relFilename(buffer().filePath());
571 // previewing source code, no file copying or file format conversion
572 if (runparams.dryrun)
573 return stripExtensionIfPossible(rel_file, runparams.nice);
575 // temp_file will contain the file for LaTeX to act on if, for example,
576 // we move it to a temp dir or uncompress it.
577 FileName temp_file = params().filename.availableFile();
579 // The master buffer. This is useful when there are multiple levels
581 Buffer const * masterBuffer = buffer().masterBuffer();
583 // Return the output name if we are inside a comment or the file does
585 // We are not going to change the extension or using the name of the
586 // temporary file, the code is already complicated enough.
587 if (runparams.inComment || !params().filename.isReadableFile())
588 return params().filename.outputFilename(masterBuffer->filePath());
590 // We place all temporary files in the master buffer's temp dir.
591 // This is possible because we use mangled file names.
592 // This is necessary for DVI export.
593 string const temp_path = masterBuffer->temppath();
595 GraphicsCopyStatus status;
596 boost::tie(status, temp_file) =
597 copyToDirIfNeeded(params().filename.availableFile(), temp_path);
599 if (status == FAILURE)
602 // a relative filename should be relative to the master buffer.
603 // "nice" means that the buffer is exported to LaTeX format but not
604 // run through the LaTeX compiler.
605 string output_file = runparams.nice ?
606 params().filename.outputFilename(masterBuffer->filePath()) :
607 onlyFilename(temp_file.absFilename());
609 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
610 frontend::Alert::warning(_("Invalid filename"),
611 _("The following filename is likely to cause trouble "
612 "when running the exported file through LaTeX: ") +
613 from_utf8(output_file));
616 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
617 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
618 "latex" : "pdflatex";
620 // If the file is compressed and we have specified that it
621 // should not be uncompressed, then just return its name and
622 // let LaTeX do the rest!
623 if (params().filename.isZipped()) {
624 if (params().noUnzip) {
625 // We don't know whether latex can actually handle
626 // this file, but we can't check, because that would
627 // mean to unzip the file and thereby making the
628 // noUnzip parameter meaningless.
629 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
631 FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
632 if (runparams.nice) {
633 runparams.exportdata->addExternalFile(tex_format,
635 changeExtension(output_file, "bb"));
637 // LaTeX needs the bounding box file in the
639 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
640 boost::tie(status, bb_file) =
641 copyFileIfNeeded(bb_orig_file, bb_file);
642 if (status == FAILURE)
644 runparams.exportdata->addExternalFile(tex_format,
647 runparams.exportdata->addExternalFile(tex_format,
648 source_file, output_file);
649 runparams.exportdata->addExternalFile("dvi",
650 source_file, output_file);
651 // We can't strip the extension, because we don't know
652 // the unzipped file format
653 return latex_path(output_file, EXCLUDE_EXTENSION);
656 FileName const unzipped_temp_file =
657 FileName(unzippedFileName(temp_file.absFilename()));
658 output_file = unzippedFileName(output_file);
659 source_file = FileName(unzippedFileName(source_file.absFilename()));
660 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
661 // temp_file has been unzipped already and
662 // orig_file has not changed in the meantime.
663 temp_file = unzipped_temp_file;
664 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
666 // unzipped_temp_file does not exist or is too old
667 temp_file = unzipFile(temp_file);
668 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
672 string const from = formats.getFormatFromFile(temp_file);
674 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
676 string const to = findTargetFormat(from, runparams);
677 string const ext = formats.extension(to);
678 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
680 // We're going to be running the exported buffer through the LaTeX
681 // compiler, so must ensure that LaTeX can cope with the graphics
684 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
687 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
688 // The LaTeX compiler will not be able to determine
689 // the file format from the extension, so we must
691 FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
692 if (temp_file.moveTo(new_file)) {
693 temp_file = new_file;
694 output_file = changeExtension(output_file, ext);
695 source_file = FileName(changeExtension(source_file.absFilename(), ext));
697 LYXERR(Debug::GRAPHICS, "Could not rename file `"
698 << temp_file << "' to `" << new_file << "'.");
701 // The extension of temp_file might be != ext!
702 runparams.exportdata->addExternalFile(tex_format, source_file,
704 runparams.exportdata->addExternalFile("dvi", source_file,
706 return stripExtensionIfPossible(output_file, to, runparams.nice);
709 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
710 string const output_to_file = changeExtension(output_file, ext);
712 // Do we need to perform the conversion?
713 // Yes if to_file does not exist or if temp_file is newer than to_file
714 if (compare_timestamps(temp_file, to_file) < 0) {
716 LYXERR(Debug::GRAPHICS,
717 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
718 from_utf8(rel_file))));
719 runparams.exportdata->addExternalFile(tex_format, to_file,
721 runparams.exportdata->addExternalFile("dvi", to_file,
723 return stripExtensionIfPossible(output_to_file, runparams.nice);
726 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
727 << "\tA copy has been made and convert is to be called with:\n"
728 << "\tfile to convert = " << temp_file << '\n'
729 << "\t from " << from << " to " << to);
731 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
733 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
735 Converters::try_default | Converters::try_cache)) {
736 runparams.exportdata->addExternalFile(tex_format,
737 to_file, output_to_file);
738 runparams.exportdata->addExternalFile("dvi",
739 to_file, output_to_file);
742 return stripExtensionIfPossible(output_to_file, runparams.nice);
746 int InsetGraphics::latex(odocstream & os,
747 OutputParams const & runparams) const
749 // If there is no file specified or not existing,
750 // just output a message about it in the latex output.
751 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
752 << params().filename.absFilename());
754 bool const file_exists = !params().filename.empty()
755 && params().filename.isReadableFile();
756 string const message = file_exists ?
757 string() : string("bb = 0 0 200 100, draft, type=eps");
758 // if !message.empty() then there was no existing file
759 // "filename" found. In this case LaTeX
760 // draws only a rectangle with the above bb and the
761 // not found filename in it.
762 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
764 // These variables collect all the latex code that should be before and
765 // after the actual includegraphics command.
769 if (runparams.moving_arg)
770 before += "\\protect";
772 // We never use the starred form, we use the "clip" option instead.
773 before += "\\includegraphics";
775 // Write the options if there are any.
776 string const opts = createLatexOptions();
777 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
779 if (!opts.empty() && !message.empty())
780 before += ('[' + opts + ',' + message + ']');
781 else if (!opts.empty() || !message.empty())
782 before += ('[' + opts + message + ']');
784 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
786 string latex_str = before + '{';
787 // Convert the file if necessary.
788 // Remove the extension so LaTeX will use whatever is appropriate
789 // (when there are several versions in different formats)
790 latex_str += prepareFile(runparams);
791 latex_str += '}' + after;
793 os << from_utf8(latex_str);
795 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
796 // Return how many newlines we issued.
797 return int(count(latex_str.begin(), latex_str.end(),'\n'));
801 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
803 // No graphics in ascii output. Possible to use gifscii to convert
804 // images to ascii approximation.
805 // 1. Convert file to ascii using gifscii
806 // 2. Read ascii output file and add it to the output stream.
807 // at least we send the filename
809 // FIXME: We have no idea what the encoding of the filename is
811 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
812 from_utf8(params().filename.absFilename()));
813 os << '<' << str << '>';
815 return 2 + str.size();
819 static int writeImageObject(char const * format, odocstream & os,
820 OutputParams const & runparams, docstring const & graphic_label,
821 docstring const & attributes)
823 if (runparams.flavor != OutputParams::XML)
824 os << "<![ %output.print." << format
827 os <<"<imageobject><imagedata fileref=\"&"
834 if (runparams.flavor == OutputParams::XML)
835 os << " role=\"" << format << "\"/>" ;
837 os << " format=\"" << format << "\">" ;
839 os << "</imageobject>";
841 if (runparams.flavor != OutputParams::XML)
842 os << endl << "]]>" ;
844 return runparams.flavor == OutputParams::XML ? 0 : 2;
848 // For explanation on inserting graphics into DocBook checkout:
849 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
850 // See also the docbook guide at http://www.docbook.org/
851 int InsetGraphics::docbook(odocstream & os,
852 OutputParams const & runparams) const
854 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
855 // need to switch to MediaObject. However, for now this is sufficient and
857 if (runparams.flavor == OutputParams::XML)
858 runparams.exportdata->addExternalFile("docbook-xml",
861 runparams.exportdata->addExternalFile("docbook",
864 os << "<inlinemediaobject>";
867 docstring attributes = createDocBookAttributes();
868 r += writeImageObject("png", os, runparams, graphic_label, attributes);
869 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
870 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
871 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
873 os << "</inlinemediaobject>";
878 void InsetGraphics::validate(LaTeXFeatures & features) const
880 // If we have no image, we should not require anything.
881 if (params().filename.empty())
884 features.includeFile(graphic_label,
885 removeExtension(params().filename.absFilename()));
887 features.require("graphicx");
889 if (features.runparams().nice) {
890 Buffer const * masterBuffer = features.buffer().masterBuffer();
891 string const rel_file = removeExtension(params().filename.relFilename(masterBuffer->filePath()));
892 if (contains(rel_file, "."))
893 features.require("lyxdot");
898 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
900 // If nothing is changed, just return and say so.
901 if (params() == p && !p.filename.empty())
904 // Copy the new parameters.
907 // Update the display using the new parameters.
908 graphic_->update(params().as_grfxParams());
910 // We have changed data, report it.
915 InsetGraphicsParams const & InsetGraphics::params() const
921 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
922 Buffer const & buffer) const
924 formats.edit(buffer, p.filename,
925 formats.getFormatFromFile(p.filename));
929 void InsetGraphics::addToToc(ParConstIterator const & cpit) const
931 TocBackend & backend = buffer().tocBackend();
933 docstring str = params_.filename.displayName();
934 if (params_.filename.embedded()) {
935 backend.toc("embedded").push_back(TocItem(cpit, 0, str));
936 str += _(" (embedded)");
938 backend.toc("graphics").push_back(TocItem(cpit, 0, str));
942 string const InsetGraphicsMailer::name_("graphics");
944 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
949 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
951 return params2string(inset_.params(), buffer);
955 void InsetGraphicsMailer::string2params(string const & in,
956 Buffer const & buffer,
957 InsetGraphicsParams & params)
959 params = InsetGraphicsParams();
963 istringstream data(in);
969 if (!lex || name != name_)
970 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
973 inset.readInsetGraphics(lex, buffer.filePath());
974 params = inset.params();
979 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
980 Buffer const & buffer)
983 data << name_ << ' ';
984 params.Write(data, buffer);
985 data << "\\end_inset\n";