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 * Add a way to roll the image file into the file format.
19 * When loading, if the image is not found in the expected place, try
20 to find it in the clipart, or in the same directory with the image.
21 * The image choosing dialog could show thumbnails of the image formats
22 it knows of, thus selection based on the image instead of based on
24 * Add support for the 'picins' package.
25 * Add support for the 'picinpar' package.
26 * Improve support for 'subfigure' - Allow to set the various options
32 * The filename is kept in the lyx file in a relative way, so as to allow
33 * moving the document file and its images with no problem.
37 * Postscript output means EPS figures.
39 * PDF output is best done with PDF figures if it's a direct conversion
40 * or PNG figures otherwise.
52 #include "insets/InsetGraphics.h"
53 #include "insets/RenderGraphic.h"
56 #include "BufferView.h"
57 #include "Converter.h"
60 #include "DispatchResult.h"
61 #include "ErrorList.h"
64 #include "FuncRequest.h"
65 #include "FuncStatus.h"
67 #include "LaTeXFeatures.h"
70 #include "MetricsInfo.h"
72 #include "OutputParams.h"
75 #include "frontends/alert.h"
77 #include "support/convert.h"
78 #include "support/filetools.h"
79 #include "support/lyxalgo.h" // count
80 #include "support/lyxlib.h" // sum
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>
93 using support::bformat;
94 using support::changeExtension;
95 using support::compare_timestamps;
96 using support::contains;
97 using support::DocFileName;
98 using support::FileName;
99 using support::float_equal;
100 using support::getExtension;
101 using support::isFileReadable;
102 using support::isValidLaTeXFilename;
103 using support::latex_path;
104 using support::onlyFilename;
105 using support::removeExtension;
106 using support::rtrim;
107 using support::subst;
108 using support::suffixIs;
109 using support::Systemcall;
110 using support::unzipFile;
111 using support::unzippedFileName;
116 using std::istringstream;
118 using std::ostringstream;
123 /// Find the most suitable image format for images in \p format
124 /// Note that \p format may be unknown (i. e. an empty string)
125 string findTargetFormat(string const & format, OutputParams const & runparams)
127 // Are we using latex or pdflatex?
128 if (runparams.flavor == OutputParams::PDFLATEX) {
129 LYXERR(Debug::GRAPHICS) << "findTargetFormat: PDF mode" << endl;
130 Format const * const f = formats.getFormat(format);
131 // Convert vector graphics to pdf
132 if (f && f->vectorFormat())
134 // pdflatex can use jpeg, png and pdf directly
137 // Convert everything else to png
140 // If it's postscript, we always do eps.
141 LYXERR(Debug::GRAPHICS) << "findTargetFormat: PostScript mode" << endl;
143 // any other than ps is changed to eps
152 InsetGraphics::InsetGraphics()
153 : graphic_label(sgml::uniqueID(from_ascii("graph"))),
154 graphic_(new RenderGraphic(this))
158 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
160 boost::signals::trackable(),
161 graphic_label(sgml::uniqueID(from_ascii("graph"))),
162 graphic_(new RenderGraphic(*ig.graphic_, this))
164 setParams(ig.params());
168 auto_ptr<Inset> InsetGraphics::doClone() const
170 return auto_ptr<Inset>(new InsetGraphics(*this));
174 InsetGraphics::~InsetGraphics()
176 InsetGraphicsMailer(*this).hideDialog();
180 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
182 switch (cmd.action) {
183 case LFUN_GRAPHICS_EDIT: {
184 Buffer const & buffer = *cur.bv().buffer();
185 InsetGraphicsParams p;
186 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer, p);
187 editGraphics(p, buffer);
191 case LFUN_INSET_MODIFY: {
192 Buffer const & buffer = cur.buffer();
193 InsetGraphicsParams p;
194 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer, p);
195 if (!p.filename.empty())
202 case LFUN_INSET_DIALOG_UPDATE:
203 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
206 case LFUN_MOUSE_RELEASE:
207 if (!cur.selection())
208 InsetGraphicsMailer(*this).showDialog(&cur.bv());
212 Inset::doDispatch(cur, cmd);
218 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
219 FuncStatus & flag) const
221 switch (cmd.action) {
222 case LFUN_GRAPHICS_EDIT:
223 case LFUN_INSET_MODIFY:
224 case LFUN_INSET_DIALOG_UPDATE:
229 return Inset::getStatus(cur, cmd, flag);
234 void InsetGraphics::edit(Cursor & cur, bool)
236 InsetGraphicsMailer(*this).showDialog(&cur.bv());
240 bool InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
242 graphic_->metrics(mi, dim);
243 bool const changed = dim_ != dim;
249 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
251 setPosCache(pi, x, y);
252 graphic_->draw(pi, x, y);
256 Inset::EDITABLE InsetGraphics::editable() const
262 void InsetGraphics::write(Buffer const & buf, ostream & os) const
265 params().Write(os, buf.filePath());
269 void InsetGraphics::read(Buffer const & buf, Lexer & lex)
271 string const token = lex.getString();
273 if (token == "Graphics")
274 readInsetGraphics(lex, buf.filePath());
276 LYXERR(Debug::GRAPHICS) << "Not a Graphics inset!" << endl;
278 graphic_->update(params().as_grfxParams());
282 void InsetGraphics::readInsetGraphics(Lexer & lex, string const & bufpath)
284 bool finished = false;
286 while (lex.isOK() && !finished) {
289 string const token = lex.getString();
290 LYXERR(Debug::GRAPHICS) << "Token: '" << token << '\''
295 } else if (token == "\\end_inset") {
298 if (!params_.Read(lex, token, bufpath))
299 lyxerr << "Unknown token, " << token << ", skipping."
306 string const InsetGraphics::createLatexOptions() const
308 // Calculate the options part of the command, we must do it to a string
309 // stream since we might have a trailing comma that we would like to remove
310 // before writing it to the output stream.
311 ostringstream options;
312 if (!params().bb.empty())
313 options << "bb=" << rtrim(params().bb) << ',';
319 double const scl = convert<double>(params().scale);
320 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
321 if (!float_equal(scl, 100.0, 0.05))
322 size << "scale=" << scl / 100.0 << ',';
324 if (!params().width.zero())
325 size << "width=" << params().width.asLatexString() << ',';
326 if (!params().height.zero())
327 size << "height=" << params().height.asLatexString() << ',';
328 if (params().keepAspectRatio)
329 size << "keepaspectratio,";
331 if (params().scaleBeforeRotation && !size.str().empty())
332 options << size.str();
334 // Make sure rotation angle is not very close to zero;
335 // a float can be effectively zero but not exactly zero.
336 if (!params().rotateAngle.empty()
337 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
338 options << "angle=" << params().rotateAngle << ',';
339 if (!params().rotateOrigin.empty()) {
340 options << "origin=" << params().rotateOrigin[0];
341 if (contains(params().rotateOrigin,"Top"))
343 else if (contains(params().rotateOrigin,"Bottom"))
345 else if (contains(params().rotateOrigin,"Baseline"))
350 if (!params().scaleBeforeRotation && !size.str().empty())
351 options << size.str();
353 if (!params().special.empty())
354 options << params().special << ',';
356 string opts = options.str();
358 if (suffixIs(opts, ','))
359 opts = opts.substr(0, opts.size() - 1);
365 docstring const InsetGraphics::toDocbookLength(Length const & len) const
367 odocstringstream result;
368 switch (len.unit()) {
369 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
370 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
372 case Length::PT: // Point = 1/72.27in = 0.351mm
373 result << len.value() * 72 / 72.27 << "pt";
375 case Length::BP: // Big point (72bp = 1in), also PostScript point
376 result << len.value() << "pt";
378 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
379 result << len.value() * 0.376 << "mm";
381 case Length::MM: // Millimeter = 2.845pt
382 result << len.value() << "mm";
384 case Length::PC: // Pica = 12pt = 4.218mm
385 result << len.value() << "pc";
387 case Length::CC: // Cicero = 12dd = 4.531mm
388 result << len.value() * 4.531 << "mm";
390 case Length::CM: // Centimeter = 10mm = 2.371pc
391 result << len.value() << "cm";
393 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
394 result << len.value() << "in";
396 case Length::EX: // Height of a small "x" for the current font.
397 // Obviously we have to compromise here. Any better ratio than 1.5 ?
398 result << len.value() / 1.5 << "em";
400 case Length::EM: // Width of capital "M" in current font.
401 result << len.value() << "em";
403 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
404 result << len.value() * 18 << "em";
406 case Length::PTW: // Percent of TextWidth
407 case Length::PCW: // Percent of ColumnWidth
408 case Length::PPW: // Percent of PageWidth
409 case Length::PLW: // Percent of LineWidth
410 case Length::PTH: // Percent of TextHeight
411 case Length::PPH: // Percent of Paper
412 // Sigh, this will go wrong.
413 result << len.value() << "%";
416 result << len.asDocstring();
422 docstring const InsetGraphics::createDocBookAttributes() const
424 // Calculate the options part of the command, we must do it to a string
425 // stream since we copied the code from createLatexParams() ;-)
427 // FIXME: av: need to translate spec -> Docbook XSL spec (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();
469 std::pair<CopyStatus, FileName> const
470 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
472 unsigned long const checksum_in = support::sum(file_in);
473 unsigned long const checksum_out = support::sum(file_out);
475 if (checksum_in == checksum_out)
477 return std::make_pair(IDENTICAL_CONTENTS, file_out);
479 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
480 bool const success = mover.copy(file_in, file_out);
483 LYXERR(Debug::GRAPHICS)
484 << to_utf8(support::bformat(_("Could not copy the file\n%1$s\n"
485 "into the temporary directory."),
486 from_utf8(file_in.absFilename())))
490 CopyStatus status = success ? SUCCESS : FAILURE;
491 return std::make_pair(status, file_out);
495 std::pair<CopyStatus, FileName> const
496 copyToDirIfNeeded(DocFileName const & file, string const & dir)
498 using support::rtrim;
500 string const file_in = file.absFilename();
501 string const only_path = support::onlyPath(file_in);
502 if (rtrim(support::onlyPath(file_in) , "/") == rtrim(dir, "/"))
503 return std::make_pair(IDENTICAL_PATHS, file_in);
505 string mangled = file.mangledFilename();
506 if (file.isZipped()) {
507 // We need to change _eps.gz to .eps.gz. The mangled name is
508 // still unique because of the counter in mangledFilename().
509 // We can't just call mangledFilename() with the zip
510 // extension removed, because base.eps and base.eps.gz may
511 // have different content but would get the same mangled
512 // name in this case.
513 string const base = removeExtension(file.unzippedFilename());
514 string::size_type const ext_len = file_in.length() - base.length();
515 mangled[mangled.length() - ext_len] = '.';
517 FileName const file_out(support::makeAbsPath(mangled, dir));
519 return copyFileIfNeeded(file, file_out);
523 string const stripExtensionIfPossible(string const & file, bool nice)
525 // Remove the extension so the LaTeX compiler will use whatever
526 // is appropriate (when there are several versions in different
528 // Do this only if we are not exporting for internal usage, because
529 // pdflatex prefers png over pdf and it would pick up the png images
530 // that we generate for preview.
531 // This works only if the filename contains no dots besides
532 // the just removed one. We can fool here by replacing all
533 // dots with a macro whose definition is just a dot ;-)
534 // The automatic format selection does not work if the file
536 string const latex_name = latex_path(file,
537 support::EXCLUDE_EXTENSION);
538 if (!nice || contains(latex_name, '"'))
540 return latex_path(removeExtension(file),
541 support::PROTECT_EXTENSION,
542 support::ESCAPE_DOTS);
546 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
548 // No conversion is needed. LaTeX can handle the graphic file as is.
549 // This is true even if the orig_file is compressed.
550 string const to_format = formats.getFormat(to)->extension();
551 string const file_format = getExtension(file);
552 // for latex .ps == .eps
553 if (to_format == file_format ||
554 (to_format == "eps" && file_format == "ps") ||
555 (to_format == "ps" && file_format == "eps"))
556 return stripExtensionIfPossible(file, nice);
557 return latex_path(file, support::EXCLUDE_EXTENSION);
563 string const InsetGraphics::prepareFile(Buffer const & buf,
564 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.absFilename();
571 string const rel_file = params().filename.relFilename(buf.filePath());
573 // previewing source code, no file copying or file format conversion
574 if (runparams.dryrun)
575 return stripExtensionIfPossible(rel_file, runparams.nice);
577 // temp_file will contain the file for LaTeX to act on if, for example,
578 // we move it to a temp dir or uncompress it.
579 FileName temp_file = params().filename;
581 // The master buffer. This is useful when there are multiple levels
583 Buffer const * m_buffer = buf.getMasterBuffer();
585 // Return the output name if we are inside a comment or the file does
587 // We are not going to change the extension or using the name of the
588 // temporary file, the code is already complicated enough.
589 if (runparams.inComment || !isFileReadable(params().filename))
590 return params().filename.outputFilename(m_buffer->filePath());
592 // We place all temporary files in the master buffer's temp dir.
593 // This is possible because we use mangled file names.
594 // This is necessary for DVI export.
595 string const temp_path = m_buffer->temppath();
598 boost::tie(status, temp_file) =
599 copyToDirIfNeeded(params().filename, temp_path);
601 if (status == FAILURE)
604 // a relative filename should be relative to the master
606 // "nice" means that the buffer is exported to LaTeX format but not
607 // run through the LaTeX compiler.
608 string output_file = support::os::external_path(runparams.nice ?
609 params().filename.outputFilename(m_buffer->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)
633 << "\tpass zipped file to LaTeX.\n";
635 FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
636 if (runparams.nice) {
637 runparams.exportdata->addExternalFile(tex_format,
639 changeExtension(output_file, "bb"));
641 // LaTeX needs the bounding box file in the
643 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
644 boost::tie(status, bb_file) =
645 copyFileIfNeeded(bb_orig_file, bb_file);
646 if (status == FAILURE)
648 runparams.exportdata->addExternalFile(tex_format,
651 runparams.exportdata->addExternalFile(tex_format,
652 source_file, output_file);
653 runparams.exportdata->addExternalFile("dvi",
654 source_file, output_file);
655 // We can't strip the extension, because we don't know
656 // the unzipped file format
657 return latex_path(output_file,
658 support::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)
670 << "\twas already unzipped to " << temp_file
673 // unzipped_temp_file does not exist or is too old
674 temp_file = unzipFile(temp_file);
675 LYXERR(Debug::GRAPHICS)
676 << "\tunzipped to " << temp_file << endl;
680 string const from = formats.getFormatFromFile(temp_file);
682 LYXERR(Debug::GRAPHICS)
683 << "\tCould not get file format." << endl;
685 string const to = findTargetFormat(from, runparams);
686 string const ext = formats.extension(to);
687 LYXERR(Debug::GRAPHICS)
688 << "\t we have: from " << from << " to " << to << '\n';
690 // We're going to be running the exported buffer through the LaTeX
691 // compiler, so must ensure that LaTeX can cope with the graphics
694 LYXERR(Debug::GRAPHICS)
695 << "\tthe orig file is: " << orig_file << endl;
698 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
699 // The LaTeX compiler will not be able to determine
700 // the file format from the extension, so we must
702 FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
703 if (support::rename(temp_file, new_file)) {
704 temp_file = new_file;
705 output_file = changeExtension(output_file, ext);
706 source_file = FileName(changeExtension(source_file.absFilename(), ext));
708 LYXERR(Debug::GRAPHICS)
709 << "Could not rename file `"
710 << temp_file << "' to `" << new_file
713 // The extension of temp_file might be != ext!
714 runparams.exportdata->addExternalFile(tex_format, source_file,
716 runparams.exportdata->addExternalFile("dvi", source_file,
718 return stripExtensionIfPossible(output_file, to, runparams.nice);
721 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
722 string const output_to_file = changeExtension(output_file, ext);
724 // Do we need to perform the conversion?
725 // Yes if to_file does not exist or if temp_file is newer than to_file
726 if (compare_timestamps(temp_file, to_file) < 0) {
728 LYXERR(Debug::GRAPHICS)
729 << to_utf8(bformat(_("No conversion of %1$s is needed after all"),
730 from_utf8(rel_file)))
732 runparams.exportdata->addExternalFile(tex_format, to_file,
734 runparams.exportdata->addExternalFile("dvi", to_file,
736 return stripExtensionIfPossible(output_to_file, runparams.nice);
739 LYXERR(Debug::GRAPHICS)
740 << "\tThe original file is " << orig_file << "\n"
741 << "\tA copy has been made and convert is to be called with:\n"
742 << "\tfile to convert = " << temp_file << '\n'
743 << "\t from " << from << " to " << to << '\n';
745 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
747 if (theConverters().convert(&buf, temp_file, to_file, params().filename,
749 Converters::try_default | Converters::try_cache)) {
750 runparams.exportdata->addExternalFile(tex_format,
751 to_file, output_to_file);
752 runparams.exportdata->addExternalFile("dvi",
753 to_file, output_to_file);
756 return stripExtensionIfPossible(output_to_file, runparams.nice);
760 int InsetGraphics::latex(Buffer const & buf, odocstream & os,
761 OutputParams const & runparams) const
763 // If there is no file specified or not existing,
764 // just output a message about it in the latex output.
765 LYXERR(Debug::GRAPHICS)
766 << "insetgraphics::latex: Filename = "
767 << params().filename.absFilename() << endl;
769 string const relative_file =
770 params().filename.relFilename(buf.filePath());
772 bool const file_exists = !params().filename.empty() &&
773 isFileReadable(params().filename);
774 string const message = file_exists ?
775 string() : string("bb = 0 0 200 100, draft, type=eps");
776 // if !message.empty() then there was no existing file
777 // "filename" found. In this case LaTeX
778 // draws only a rectangle with the above bb and the
779 // not found filename in it.
780 LYXERR(Debug::GRAPHICS)
781 << "\tMessage = \"" << message << '\"' << endl;
783 // These variables collect all the latex code that should be before and
784 // after the actual includegraphics command.
787 // Do we want subcaptions?
788 if (params().subcaption) {
789 if (runparams.moving_arg)
790 before += "\\protect";
791 before += "\\subfigure[" + params().subcaptionText + "]{";
795 if (runparams.moving_arg)
796 before += "\\protect";
798 // We never use the starred form, we use the "clip" option instead.
799 before += "\\includegraphics";
801 // Write the options if there are any.
802 string const opts = createLatexOptions();
803 LYXERR(Debug::GRAPHICS) << "\tOpts = " << opts << endl;
805 if (!opts.empty() && !message.empty())
806 before += ('[' + opts + ',' + message + ']');
807 else if (!opts.empty() || !message.empty())
808 before += ('[' + opts + message + ']');
810 LYXERR(Debug::GRAPHICS)
811 << "\tBefore = " << before
812 << "\n\tafter = " << after << endl;
814 string latex_str = before + '{';
815 // Convert the file if necessary.
816 // Remove the extension so LaTeX will use whatever is appropriate
817 // (when there are several versions in different formats)
818 latex_str += prepareFile(buf, runparams);
819 latex_str += '}' + after;
821 os << from_utf8(latex_str);
823 LYXERR(Debug::GRAPHICS) << "InsetGraphics::latex outputting:\n"
824 << latex_str << endl;
825 // Return how many newlines we issued.
826 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n'));
830 int InsetGraphics::plaintext(Buffer const & buf, odocstream & os,
831 OutputParams const &) const
833 // No graphics in ascii output. Possible to use gifscii to convert
834 // images to ascii approximation.
835 // 1. Convert file to ascii using gifscii
836 // 2. Read ascii output file and add it to the output stream.
837 // at least we send the filename
839 // FIXME: We have no idea what the encoding of the filename is
841 docstring const str = bformat(buf.B_("Graphics file: %1$s"),
842 from_utf8(params().filename.absFilename()));
843 os << '<' << str << '>';
845 return 2 + str.size();
851 int writeImageObject(char * format, odocstream & os, OutputParams const & runparams,
852 docstring const graphic_label, docstring const attributes)
854 if (runparams.flavor != OutputParams::XML) {
855 os << "<![ %output.print."
860 os <<"<imageobject><imagedata fileref=\"&"
866 if (runparams.flavor == OutputParams::XML) {
867 os << " role=\"" << format << "\"/>" ;
870 os << " format=\"" << format << "\">" ;
872 os << "</imageobject>";
873 if (runparams.flavor != OutputParams::XML) {
874 os << std::endl << "]]>" ;
876 return runparams.flavor == OutputParams::XML ? 0 : 2;
878 // end anonymous namespace
882 // For explanation on inserting graphics into DocBook checkout:
883 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
884 // See also the docbook guide at http://www.docbook.org/
885 int InsetGraphics::docbook(Buffer const &, odocstream & os,
886 OutputParams const & runparams) const
888 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
889 // need to switch to MediaObject. However, for now this is sufficient and
891 if (runparams.flavor == OutputParams::XML) {
892 runparams.exportdata->addExternalFile("docbook-xml",
895 runparams.exportdata->addExternalFile("docbook",
898 os << "<inlinemediaobject>";
901 docstring attributes = createDocBookAttributes();
902 r += writeImageObject("png", os, runparams, graphic_label, attributes);
903 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
904 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
905 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
907 os << "</inlinemediaobject>";
912 void InsetGraphics::validate(LaTeXFeatures & features) const
914 // If we have no image, we should not require anything.
915 if (params().filename.empty())
918 features.includeFile(graphic_label,
919 removeExtension(params().filename.absFilename()));
921 features.require("graphicx");
923 if (features.runparams().nice) {
924 Buffer const * m_buffer = features.buffer().getMasterBuffer();
925 string const rel_file = removeExtension(params().filename.relFilename(m_buffer->filePath()));
926 if (contains(rel_file, "."))
927 features.require("lyxdot");
930 if (params().subcaption)
931 features.require("subfigure");
935 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
937 // If nothing is changed, just return and say so.
938 if (params() == p && !p.filename.empty())
941 // Copy the new parameters.
944 // Update the display using the new parameters.
945 graphic_->update(params().as_grfxParams());
947 // We have changed data, report it.
952 InsetGraphicsParams const & InsetGraphics::params() const
958 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
959 Buffer const & buffer) const
961 formats.edit(buffer, p.filename,
962 formats.getFormatFromFile(p.filename));
966 string const InsetGraphicsMailer::name_("graphics");
968 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
973 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
975 return params2string(inset_.params(), buffer);
979 void InsetGraphicsMailer::string2params(string const & in,
980 Buffer const & buffer,
981 InsetGraphicsParams & params)
983 params = InsetGraphicsParams();
987 istringstream data(in);
993 if (!lex || name != name_)
994 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
997 inset.readInsetGraphics(lex, buffer.filePath());
998 params = inset.params();
1003 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
1004 Buffer const & buffer)
1007 data << name_ << ' ';
1008 params.Write(data, buffer.filePath());
1009 data << "\\end_inset\n";