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"
59 #include "support/debug.h"
60 #include "DispatchResult.h"
61 #include "ErrorList.h"
64 #include "FuncRequest.h"
65 #include "FuncStatus.h"
66 #include "support/gettext.h"
67 #include "LaTeXFeatures.h"
70 #include "MetricsInfo.h"
72 #include "OutputParams.h"
74 #include "EmbeddedFiles.h"
76 #include "frontends/alert.h"
78 #include "support/convert.h"
79 #include "support/docstream.h"
80 #include "support/filetools.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>
95 using support::bformat;
96 using support::changeExtension;
97 using support::compare_timestamps;
98 using support::contains;
99 using support::DocFileName;
100 using support::FileName;
101 using support::float_equal;
102 using support::getExtension;
103 using support::isValidLaTeXFilename;
104 using support::latex_path;
105 using support::onlyFilename;
106 using support::removeExtension;
107 using support::rtrim;
108 using support::subst;
109 using support::suffixIs;
110 using support::Systemcall;
111 using support::unzipFile;
112 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");
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");
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 Inset * InsetGraphics::clone() const
170 return 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::registerEmbeddedFiles(Buffer const &,
235 EmbeddedFiles & files) const
237 files.registerFile(params().filename.absFilename(),
242 void InsetGraphics::updateEmbeddedFile(Buffer const & buf,
243 EmbeddedFile const & file)
245 BOOST_ASSERT(buf.embeddedFiles().enabled());
246 params_.filename = file;
247 LYXERR(Debug::FILES, "Update InsetGraphic with File "
248 << params_.filename.toFilesystemEncoding()
249 << ", embedding status: " << params_.filename.embedded());
253 void InsetGraphics::edit(Cursor & cur, bool)
255 InsetGraphicsMailer(*this).showDialog(&cur.bv());
259 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
261 graphic_->metrics(mi, dim);
265 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
267 graphic_->draw(pi, x, y);
271 Inset::EDITABLE InsetGraphics::editable() const
277 void InsetGraphics::write(Buffer const & buf, ostream & os) const
280 params().Write(os, buf);
284 void InsetGraphics::read(Buffer const & buf, Lexer & lex)
286 string const token = lex.getString();
288 if (token == "Graphics")
289 readInsetGraphics(lex, buf.filePath());
291 LYXERR(Debug::GRAPHICS, "Not a Graphics inset!");
293 // InsetGraphics is read, with filename in params_. We do not know if this file actually
294 // exists or is embedded so we need to get the 'availableFile' from buf.embeddedFiles()
295 if (buf.embeddedFiles().enabled()) {
296 EmbeddedFiles::EmbeddedFileList::const_iterator it =
297 buf.embeddedFiles().find(params_.filename.toFilesystemEncoding());
298 if (it != buf.embeddedFiles().end())
299 // using available file, embedded or external, depending on file availability and
301 params_.filename = *it;
303 graphic_->update(params().as_grfxParams());
307 void InsetGraphics::readInsetGraphics(Lexer & lex, string const & bufpath)
309 bool finished = false;
311 while (lex.isOK() && !finished) {
314 string const token = lex.getString();
315 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
320 if (token == "\\end_inset") {
323 if (!params_.Read(lex, token, bufpath))
324 lyxerr << "Unknown token, " << token << ", skipping."
331 string const InsetGraphics::createLatexOptions() const
333 // Calculate the options part of the command, we must do it to a string
334 // stream since we might have a trailing comma that we would like to remove
335 // before writing it to the output stream.
336 ostringstream options;
337 if (!params().bb.empty())
338 options << "bb=" << rtrim(params().bb) << ',';
344 double const scl = convert<double>(params().scale);
345 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
346 if (!float_equal(scl, 100.0, 0.05))
347 size << "scale=" << scl / 100.0 << ',';
349 if (!params().width.zero())
350 size << "width=" << params().width.asLatexString() << ',';
351 if (!params().height.zero())
352 size << "height=" << params().height.asLatexString() << ',';
353 if (params().keepAspectRatio)
354 size << "keepaspectratio,";
356 if (params().scaleBeforeRotation && !size.str().empty())
357 options << size.str();
359 // Make sure rotation angle is not very close to zero;
360 // a float can be effectively zero but not exactly zero.
361 if (!params().rotateAngle.empty()
362 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
363 options << "angle=" << params().rotateAngle << ',';
364 if (!params().rotateOrigin.empty()) {
365 options << "origin=" << params().rotateOrigin[0];
366 if (contains(params().rotateOrigin,"Top"))
368 else if (contains(params().rotateOrigin,"Bottom"))
370 else if (contains(params().rotateOrigin,"Baseline"))
375 if (!params().scaleBeforeRotation && !size.str().empty())
376 options << size.str();
378 if (!params().special.empty())
379 options << params().special << ',';
381 string opts = options.str();
383 if (suffixIs(opts, ','))
384 opts = opts.substr(0, opts.size() - 1);
390 docstring const InsetGraphics::toDocbookLength(Length const & len) const
392 odocstringstream result;
393 switch (len.unit()) {
394 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
395 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
397 case Length::PT: // Point = 1/72.27in = 0.351mm
398 result << len.value() * 72 / 72.27 << "pt";
400 case Length::BP: // Big point (72bp = 1in), also PostScript point
401 result << len.value() << "pt";
403 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
404 result << len.value() * 0.376 << "mm";
406 case Length::MM: // Millimeter = 2.845pt
407 result << len.value() << "mm";
409 case Length::PC: // Pica = 12pt = 4.218mm
410 result << len.value() << "pc";
412 case Length::CC: // Cicero = 12dd = 4.531mm
413 result << len.value() * 4.531 << "mm";
415 case Length::CM: // Centimeter = 10mm = 2.371pc
416 result << len.value() << "cm";
418 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
419 result << len.value() << "in";
421 case Length::EX: // Height of a small "x" for the current font.
422 // Obviously we have to compromise here. Any better ratio than 1.5 ?
423 result << len.value() / 1.5 << "em";
425 case Length::EM: // Width of capital "M" in current font.
426 result << len.value() << "em";
428 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
429 result << len.value() * 18 << "em";
431 case Length::PTW: // Percent of TextWidth
432 case Length::PCW: // Percent of ColumnWidth
433 case Length::PPW: // Percent of PageWidth
434 case Length::PLW: // Percent of LineWidth
435 case Length::PTH: // Percent of TextHeight
436 case Length::PPH: // Percent of Paper
437 // Sigh, this will go wrong.
438 result << len.value() << "%";
441 result << len.asDocstring();
447 docstring const InsetGraphics::createDocBookAttributes() const
449 // Calculate the options part of the command, we must do it to a string
450 // stream since we copied the code from createLatexParams() ;-)
452 // FIXME: av: need to translate spec -> Docbook XSL spec
453 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
454 // Right now it only works with my version of db2latex :-)
456 odocstringstream options;
457 double const scl = convert<double>(params().scale);
458 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
459 if (!float_equal(scl, 100.0, 0.05))
460 options << " scale=\""
461 << static_cast<int>( (scl) + 0.5 )
464 if (!params().width.zero()) {
465 options << " width=\"" << toDocbookLength(params().width) << "\" ";
467 if (!params().height.zero()) {
468 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
470 if (params().keepAspectRatio) {
471 // This will be irrelevant unless both width and height are set
472 options << "scalefit=\"1\" ";
477 if (!params().special.empty())
478 options << from_ascii(params().special) << " ";
480 // trailing blanks are ok ...
481 return options.str();
487 enum GraphicsCopyStatus {
495 std::pair<GraphicsCopyStatus, FileName> const
496 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
498 unsigned long const checksum_in = file_in.checksum();
499 unsigned long const checksum_out = file_out.checksum();
501 if (checksum_in == checksum_out)
503 return std::make_pair(IDENTICAL_CONTENTS, file_out);
505 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
506 bool const success = mover.copy(file_in, file_out);
509 LYXERR(Debug::GRAPHICS,
510 to_utf8(support::bformat(_("Could not copy the file\n%1$s\n"
511 "into the temporary directory."),
512 from_utf8(file_in.absFilename()))));
515 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
516 return std::make_pair(status, file_out);
520 std::pair<GraphicsCopyStatus, FileName> const
521 copyToDirIfNeeded(DocFileName const & file, string const & dir)
523 using support::rtrim;
525 string const file_in = file.absFilename();
526 string const only_path = support::onlyPath(file_in);
527 if (rtrim(support::onlyPath(file_in) , "/") == rtrim(dir, "/"))
528 return std::make_pair(IDENTICAL_PATHS, file_in);
530 string mangled = file.mangledFilename();
531 if (file.isZipped()) {
532 // We need to change _eps.gz to .eps.gz. The mangled name is
533 // still unique because of the counter in mangledFilename().
534 // We can't just call mangledFilename() with the zip
535 // extension removed, because base.eps and base.eps.gz may
536 // have different content but would get the same mangled
537 // name in this case.
538 string const base = removeExtension(file.unzippedFilename());
539 string::size_type const ext_len = file_in.length() - base.length();
540 mangled[mangled.length() - ext_len] = '.';
542 FileName const file_out(support::makeAbsPath(mangled, dir));
544 return copyFileIfNeeded(file, file_out);
548 string const stripExtensionIfPossible(string const & file, bool nice)
550 // Remove the extension so the LaTeX compiler will use whatever
551 // is appropriate (when there are several versions in different
553 // Do this only if we are not exporting for internal usage, because
554 // pdflatex prefers png over pdf and it would pick up the png images
555 // that we generate for preview.
556 // This works only if the filename contains no dots besides
557 // the just removed one. We can fool here by replacing all
558 // dots with a macro whose definition is just a dot ;-)
559 // The automatic format selection does not work if the file
561 string const latex_name = latex_path(file,
562 support::EXCLUDE_EXTENSION);
563 if (!nice || contains(latex_name, '"'))
565 return latex_path(removeExtension(file),
566 support::PROTECT_EXTENSION,
567 support::ESCAPE_DOTS);
571 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
573 // No conversion is needed. LaTeX can handle the graphic file as is.
574 // This is true even if the orig_file is compressed.
575 string const to_format = formats.getFormat(to)->extension();
576 string const file_format = getExtension(file);
577 // for latex .ps == .eps
578 if (to_format == file_format ||
579 (to_format == "eps" && file_format == "ps") ||
580 (to_format == "ps" && file_format == "eps"))
581 return stripExtensionIfPossible(file, nice);
582 return latex_path(file, support::EXCLUDE_EXTENSION);
588 string const InsetGraphics::prepareFile(Buffer const & buf,
589 OutputParams const & runparams) const
591 // The following code depends on non-empty filenames
592 if (params().filename.empty())
595 string const orig_file = params().filename.absFilename();
596 string const rel_file = params().filename.relFilename(buf.filePath());
598 // previewing source code, no file copying or file format conversion
599 if (runparams.dryrun)
600 return stripExtensionIfPossible(rel_file, runparams.nice);
602 // temp_file will contain the file for LaTeX to act on if, for example,
603 // we move it to a temp dir or uncompress it.
604 FileName temp_file = params().filename;
606 // The master buffer. This is useful when there are multiple levels
608 Buffer const * masterBuffer = buf.masterBuffer();
610 // Return the output name if we are inside a comment or the file does
612 // We are not going to change the extension or using the name of the
613 // temporary file, the code is already complicated enough.
614 if (runparams.inComment || !params().filename.isReadableFile())
615 return params().filename.outputFilename(masterBuffer->filePath());
617 // We place all temporary files in the master buffer's temp dir.
618 // This is possible because we use mangled file names.
619 // This is necessary for DVI export.
620 string const temp_path = masterBuffer->temppath();
622 GraphicsCopyStatus status;
623 boost::tie(status, temp_file) =
624 copyToDirIfNeeded(params().filename, temp_path);
626 if (status == FAILURE)
629 // a relative filename should be relative to the master buffer.
630 // "nice" means that the buffer is exported to LaTeX format but not
631 // run through the LaTeX compiler.
632 string output_file = runparams.nice ?
633 params().filename.outputFilename(masterBuffer->filePath()) :
634 onlyFilename(temp_file.absFilename());
636 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
637 frontend::Alert::warning(_("Invalid filename"),
638 _("The following filename is likely to cause trouble "
639 "when running the exported file through LaTeX: ") +
640 from_utf8(output_file));
643 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
644 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
645 "latex" : "pdflatex";
647 // If the file is compressed and we have specified that it
648 // should not be uncompressed, then just return its name and
649 // let LaTeX do the rest!
650 if (params().filename.isZipped()) {
651 if (params().noUnzip) {
652 // We don't know whether latex can actually handle
653 // this file, but we can't check, because that would
654 // mean to unzip the file and thereby making the
655 // noUnzip parameter meaningless.
656 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
658 FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
659 if (runparams.nice) {
660 runparams.exportdata->addExternalFile(tex_format,
662 changeExtension(output_file, "bb"));
664 // LaTeX needs the bounding box file in the
666 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
667 boost::tie(status, bb_file) =
668 copyFileIfNeeded(bb_orig_file, bb_file);
669 if (status == FAILURE)
671 runparams.exportdata->addExternalFile(tex_format,
674 runparams.exportdata->addExternalFile(tex_format,
675 source_file, output_file);
676 runparams.exportdata->addExternalFile("dvi",
677 source_file, output_file);
678 // We can't strip the extension, because we don't know
679 // the unzipped file format
680 return latex_path(output_file,
681 support::EXCLUDE_EXTENSION);
684 FileName const unzipped_temp_file =
685 FileName(unzippedFileName(temp_file.absFilename()));
686 output_file = unzippedFileName(output_file);
687 source_file = FileName(unzippedFileName(source_file.absFilename()));
688 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
689 // temp_file has been unzipped already and
690 // orig_file has not changed in the meantime.
691 temp_file = unzipped_temp_file;
692 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
694 // unzipped_temp_file does not exist or is too old
695 temp_file = unzipFile(temp_file);
696 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
700 string const from = formats.getFormatFromFile(temp_file);
702 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
704 string const to = findTargetFormat(from, runparams);
705 string const ext = formats.extension(to);
706 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
708 // We're going to be running the exported buffer through the LaTeX
709 // compiler, so must ensure that LaTeX can cope with the graphics
712 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
715 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
716 // The LaTeX compiler will not be able to determine
717 // the file format from the extension, so we must
719 FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
720 if (support::rename(temp_file, new_file)) {
721 temp_file = new_file;
722 output_file = changeExtension(output_file, ext);
723 source_file = FileName(changeExtension(source_file.absFilename(), ext));
725 LYXERR(Debug::GRAPHICS, "Could not rename file `"
726 << temp_file << "' to `" << new_file << "'.");
729 // The extension of temp_file might be != ext!
730 runparams.exportdata->addExternalFile(tex_format, source_file,
732 runparams.exportdata->addExternalFile("dvi", source_file,
734 return stripExtensionIfPossible(output_file, to, runparams.nice);
737 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
738 string const output_to_file = changeExtension(output_file, ext);
740 // Do we need to perform the conversion?
741 // Yes if to_file does not exist or if temp_file is newer than to_file
742 if (compare_timestamps(temp_file, to_file) < 0) {
744 LYXERR(Debug::GRAPHICS,
745 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
746 from_utf8(rel_file))));
747 runparams.exportdata->addExternalFile(tex_format, to_file,
749 runparams.exportdata->addExternalFile("dvi", to_file,
751 return stripExtensionIfPossible(output_to_file, runparams.nice);
754 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
755 << "\tA copy has been made and convert is to be called with:\n"
756 << "\tfile to convert = " << temp_file << '\n'
757 << "\t from " << from << " to " << to);
759 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
761 if (theConverters().convert(&buf, temp_file, to_file, params().filename,
763 Converters::try_default | Converters::try_cache)) {
764 runparams.exportdata->addExternalFile(tex_format,
765 to_file, output_to_file);
766 runparams.exportdata->addExternalFile("dvi",
767 to_file, output_to_file);
770 return stripExtensionIfPossible(output_to_file, runparams.nice);
774 int InsetGraphics::latex(Buffer const & buf, odocstream & os,
775 OutputParams const & runparams) const
777 // If there is no file specified or not existing,
778 // just output a message about it in the latex output.
779 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
780 << params().filename.absFilename());
782 string const relative_file =
783 params().filename.relFilename(buf.filePath());
785 bool const file_exists = !params().filename.empty()
786 && params().filename.isReadableFile();
787 string const message = file_exists ?
788 string() : string("bb = 0 0 200 100, draft, type=eps");
789 // if !message.empty() then there was no existing file
790 // "filename" found. In this case LaTeX
791 // draws only a rectangle with the above bb and the
792 // not found filename in it.
793 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
795 // These variables collect all the latex code that should be before and
796 // after the actual includegraphics command.
799 // Do we want subcaptions?
800 if (params().subcaption) {
801 if (runparams.moving_arg)
802 before += "\\protect";
803 before += "\\subfigure[" + params().subcaptionText + "]{";
807 if (runparams.moving_arg)
808 before += "\\protect";
810 // We never use the starred form, we use the "clip" option instead.
811 before += "\\includegraphics";
813 // Write the options if there are any.
814 string const opts = createLatexOptions();
815 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
817 if (!opts.empty() && !message.empty())
818 before += ('[' + opts + ',' + message + ']');
819 else if (!opts.empty() || !message.empty())
820 before += ('[' + opts + message + ']');
822 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
824 string latex_str = before + '{';
825 // Convert the file if necessary.
826 // Remove the extension so LaTeX will use whatever is appropriate
827 // (when there are several versions in different formats)
828 latex_str += prepareFile(buf, runparams);
829 latex_str += '}' + after;
831 os << from_utf8(latex_str);
833 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
834 // Return how many newlines we issued.
835 return int(std::count(latex_str.begin(), latex_str.end(),'\n'));
839 int InsetGraphics::plaintext(Buffer const & buf, odocstream & os,
840 OutputParams const &) const
842 // No graphics in ascii output. Possible to use gifscii to convert
843 // images to ascii approximation.
844 // 1. Convert file to ascii using gifscii
845 // 2. Read ascii output file and add it to the output stream.
846 // at least we send the filename
848 // FIXME: We have no idea what the encoding of the filename is
850 docstring const str = bformat(buf.B_("Graphics file: %1$s"),
851 from_utf8(params().filename.absFilename()));
852 os << '<' << str << '>';
854 return 2 + str.size();
858 static int writeImageObject(char const * format, odocstream & os,
859 OutputParams const & runparams, docstring const & graphic_label,
860 docstring const & attributes)
862 if (runparams.flavor != OutputParams::XML)
863 os << "<![ %output.print." << format
864 << "; [" << std::endl;
866 os <<"<imageobject><imagedata fileref=\"&"
873 if (runparams.flavor == OutputParams::XML)
874 os << " role=\"" << format << "\"/>" ;
876 os << " format=\"" << format << "\">" ;
878 os << "</imageobject>";
880 if (runparams.flavor != OutputParams::XML)
881 os << std::endl << "]]>" ;
883 return runparams.flavor == OutputParams::XML ? 0 : 2;
887 // For explanation on inserting graphics into DocBook checkout:
888 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
889 // See also the docbook guide at http://www.docbook.org/
890 int InsetGraphics::docbook(Buffer const &, odocstream & os,
891 OutputParams const & runparams) const
893 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
894 // need to switch to MediaObject. However, for now this is sufficient and
896 if (runparams.flavor == OutputParams::XML)
897 runparams.exportdata->addExternalFile("docbook-xml",
900 runparams.exportdata->addExternalFile("docbook",
903 os << "<inlinemediaobject>";
906 docstring attributes = createDocBookAttributes();
907 r += writeImageObject("png", os, runparams, graphic_label, attributes);
908 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
909 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
910 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
912 os << "</inlinemediaobject>";
917 void InsetGraphics::validate(LaTeXFeatures & features) const
919 // If we have no image, we should not require anything.
920 if (params().filename.empty())
923 features.includeFile(graphic_label,
924 removeExtension(params().filename.absFilename()));
926 features.require("graphicx");
928 if (features.runparams().nice) {
929 Buffer const * masterBuffer = features.buffer().masterBuffer();
930 string const rel_file = removeExtension(params().filename.relFilename(masterBuffer->filePath()));
931 if (contains(rel_file, "."))
932 features.require("lyxdot");
935 if (params().subcaption)
936 features.require("subfigure");
940 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
942 // If nothing is changed, just return and say so.
943 if (params() == p && !p.filename.empty())
946 // Copy the new parameters.
949 // Update the display using the new parameters.
950 graphic_->update(params().as_grfxParams());
952 // We have changed data, report it.
957 InsetGraphicsParams const & InsetGraphics::params() const
963 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
964 Buffer const & buffer) const
966 formats.edit(buffer, p.filename,
967 formats.getFormatFromFile(p.filename));
971 string const InsetGraphicsMailer::name_("graphics");
973 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
978 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
980 return params2string(inset_.params(), buffer);
984 void InsetGraphicsMailer::string2params(string const & in,
985 Buffer const & buffer,
986 InsetGraphicsParams & params)
988 params = InsetGraphicsParams();
992 istringstream data(in);
998 if (!lex || name != name_)
999 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
1001 InsetGraphics inset;
1002 inset.readInsetGraphics(lex, buffer.filePath());
1003 params = inset.params();
1008 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
1009 Buffer const & buffer)
1012 data << name_ << ' ';
1013 params.Write(data, buffer);
1014 data << "\\end_inset\n";