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>
96 using support::bformat;
97 using support::changeExtension;
98 using support::compare_timestamps;
99 using support::contains;
100 using support::DocFileName;
101 using support::FileName;
102 using support::float_equal;
103 using support::getExtension;
104 using support::isValidLaTeXFilename;
105 using support::latex_path;
106 using support::onlyFilename;
107 using support::removeExtension;
108 using support::rtrim;
109 using support::subst;
110 using support::suffixIs;
111 using support::Systemcall;
112 using support::unzipFile;
113 using support::unzippedFileName;
118 /// Find the most suitable image format for images in \p format
119 /// Note that \p format may be unknown (i. e. an empty string)
120 string findTargetFormat(string const & format, OutputParams const & runparams)
122 // Are we using latex or pdflatex?
123 if (runparams.flavor == OutputParams::PDFLATEX) {
124 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
125 Format const * const f = formats.getFormat(format);
126 // Convert vector graphics to pdf
127 if (f && f->vectorFormat())
129 // pdflatex can use jpeg, png and pdf directly
132 // Convert everything else to png
135 // If it's postscript, we always do eps.
136 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
138 // any other than ps is changed to eps
147 InsetGraphics::InsetGraphics()
148 : graphic_label(sgml::uniqueID(from_ascii("graph"))),
149 graphic_(new RenderGraphic(this))
153 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
155 boost::signals::trackable(),
156 graphic_label(sgml::uniqueID(from_ascii("graph"))),
157 graphic_(new RenderGraphic(*ig.graphic_, this))
159 setParams(ig.params());
163 Inset * InsetGraphics::clone() const
165 return new InsetGraphics(*this);
169 InsetGraphics::~InsetGraphics()
171 InsetGraphicsMailer(*this).hideDialog();
175 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
177 switch (cmd.action) {
178 case LFUN_GRAPHICS_EDIT: {
179 Buffer const & buffer = cur.bv().buffer();
180 InsetGraphicsParams p;
181 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer, p);
182 editGraphics(p, buffer);
186 case LFUN_INSET_MODIFY: {
187 Buffer const & buffer = cur.buffer();
188 InsetGraphicsParams p;
189 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer, p);
190 if (!p.filename.empty())
197 case LFUN_INSET_DIALOG_UPDATE:
198 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
201 case LFUN_MOUSE_RELEASE:
202 if (!cur.selection())
203 InsetGraphicsMailer(*this).showDialog(&cur.bv());
207 Inset::doDispatch(cur, cmd);
213 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
214 FuncStatus & flag) const
216 switch (cmd.action) {
217 case LFUN_GRAPHICS_EDIT:
218 case LFUN_INSET_MODIFY:
219 case LFUN_INSET_DIALOG_UPDATE:
224 return Inset::getStatus(cur, cmd, flag);
229 void InsetGraphics::registerEmbeddedFiles(Buffer const &,
230 EmbeddedFiles & files) const
232 files.registerFile(params().filename.absFilename(),
237 void InsetGraphics::updateEmbeddedFile(Buffer const & buf,
238 EmbeddedFile const & file)
240 BOOST_ASSERT(buf.embeddedFiles().enabled());
241 params_.filename = file;
242 LYXERR(Debug::FILES, "Update InsetGraphic with File "
243 << params_.filename.toFilesystemEncoding()
244 << ", embedding status: " << params_.filename.embedded());
248 void InsetGraphics::edit(Cursor & cur, bool)
250 InsetGraphicsMailer(*this).showDialog(&cur.bv());
254 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
256 graphic_->metrics(mi, dim);
260 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
262 graphic_->draw(pi, x, y);
266 Inset::EDITABLE InsetGraphics::editable() const
272 void InsetGraphics::write(Buffer const & buf, ostream & os) const
275 params().Write(os, buf);
279 void InsetGraphics::read(Buffer const & buf, Lexer & lex)
281 string const token = lex.getString();
283 if (token == "Graphics")
284 readInsetGraphics(lex, buf.filePath());
286 LYXERR(Debug::GRAPHICS, "Not a Graphics inset!");
288 // InsetGraphics is read, with filename in params_. We do not know if this file actually
289 // exists or is embedded so we need to get the 'availableFile' from buf.embeddedFiles()
290 if (buf.embeddedFiles().enabled()) {
291 EmbeddedFiles::EmbeddedFileList::const_iterator it =
292 buf.embeddedFiles().find(params_.filename.toFilesystemEncoding());
293 if (it != buf.embeddedFiles().end())
294 // using available file, embedded or external, depending on file availability and
296 params_.filename = *it;
298 graphic_->update(params().as_grfxParams());
302 void InsetGraphics::readInsetGraphics(Lexer & lex, string const & bufpath)
304 bool finished = false;
306 while (lex.isOK() && !finished) {
309 string const token = lex.getString();
310 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
315 if (token == "\\end_inset") {
318 if (!params_.Read(lex, token, bufpath))
319 lyxerr << "Unknown token, " << token << ", skipping."
326 string const InsetGraphics::createLatexOptions() const
328 // Calculate the options part of the command, we must do it to a string
329 // stream since we might have a trailing comma that we would like to remove
330 // before writing it to the output stream.
331 ostringstream options;
332 if (!params().bb.empty())
333 options << "bb=" << rtrim(params().bb) << ',';
339 double const scl = convert<double>(params().scale);
340 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
341 if (!float_equal(scl, 100.0, 0.05))
342 size << "scale=" << scl / 100.0 << ',';
344 if (!params().width.zero())
345 size << "width=" << params().width.asLatexString() << ',';
346 if (!params().height.zero())
347 size << "height=" << params().height.asLatexString() << ',';
348 if (params().keepAspectRatio)
349 size << "keepaspectratio,";
351 if (params().scaleBeforeRotation && !size.str().empty())
352 options << size.str();
354 // Make sure rotation angle is not very close to zero;
355 // a float can be effectively zero but not exactly zero.
356 if (!params().rotateAngle.empty()
357 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
358 options << "angle=" << params().rotateAngle << ',';
359 if (!params().rotateOrigin.empty()) {
360 options << "origin=" << params().rotateOrigin[0];
361 if (contains(params().rotateOrigin,"Top"))
363 else if (contains(params().rotateOrigin,"Bottom"))
365 else if (contains(params().rotateOrigin,"Baseline"))
370 if (!params().scaleBeforeRotation && !size.str().empty())
371 options << size.str();
373 if (!params().special.empty())
374 options << params().special << ',';
376 string opts = options.str();
378 if (suffixIs(opts, ','))
379 opts = opts.substr(0, opts.size() - 1);
385 docstring const InsetGraphics::toDocbookLength(Length const & len) const
387 odocstringstream result;
388 switch (len.unit()) {
389 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
390 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
392 case Length::PT: // Point = 1/72.27in = 0.351mm
393 result << len.value() * 72 / 72.27 << "pt";
395 case Length::BP: // Big point (72bp = 1in), also PostScript point
396 result << len.value() << "pt";
398 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
399 result << len.value() * 0.376 << "mm";
401 case Length::MM: // Millimeter = 2.845pt
402 result << len.value() << "mm";
404 case Length::PC: // Pica = 12pt = 4.218mm
405 result << len.value() << "pc";
407 case Length::CC: // Cicero = 12dd = 4.531mm
408 result << len.value() * 4.531 << "mm";
410 case Length::CM: // Centimeter = 10mm = 2.371pc
411 result << len.value() << "cm";
413 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
414 result << len.value() << "in";
416 case Length::EX: // Height of a small "x" for the current font.
417 // Obviously we have to compromise here. Any better ratio than 1.5 ?
418 result << len.value() / 1.5 << "em";
420 case Length::EM: // Width of capital "M" in current font.
421 result << len.value() << "em";
423 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
424 result << len.value() * 18 << "em";
426 case Length::PTW: // Percent of TextWidth
427 case Length::PCW: // Percent of ColumnWidth
428 case Length::PPW: // Percent of PageWidth
429 case Length::PLW: // Percent of LineWidth
430 case Length::PTH: // Percent of TextHeight
431 case Length::PPH: // Percent of Paper
432 // Sigh, this will go wrong.
433 result << len.value() << "%";
436 result << len.asDocstring();
442 docstring const InsetGraphics::createDocBookAttributes() const
444 // Calculate the options part of the command, we must do it to a string
445 // stream since we copied the code from createLatexParams() ;-)
447 // FIXME: av: need to translate spec -> Docbook XSL spec
448 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
449 // Right now it only works with my version of db2latex :-)
451 odocstringstream options;
452 double const scl = convert<double>(params().scale);
453 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
454 if (!float_equal(scl, 100.0, 0.05))
455 options << " scale=\""
456 << static_cast<int>( (scl) + 0.5 )
459 if (!params().width.zero()) {
460 options << " width=\"" << toDocbookLength(params().width) << "\" ";
462 if (!params().height.zero()) {
463 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
465 if (params().keepAspectRatio) {
466 // This will be irrelevant unless both width and height are set
467 options << "scalefit=\"1\" ";
472 if (!params().special.empty())
473 options << from_ascii(params().special) << " ";
475 // trailing blanks are ok ...
476 return options.str();
482 enum GraphicsCopyStatus {
490 std::pair<GraphicsCopyStatus, FileName> const
491 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
493 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
494 unsigned long const checksum_in = file_in.checksum();
495 unsigned long const checksum_out = file_out.checksum();
497 if (checksum_in == checksum_out)
499 return std::make_pair(IDENTICAL_CONTENTS, file_out);
501 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
502 bool const success = mover.copy(file_in, file_out);
505 LYXERR(Debug::GRAPHICS,
506 to_utf8(support::bformat(_("Could not copy the file\n%1$s\n"
507 "into the temporary directory."),
508 from_utf8(file_in.absFilename()))));
511 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
512 return std::make_pair(status, file_out);
516 std::pair<GraphicsCopyStatus, FileName> const
517 copyToDirIfNeeded(DocFileName const & file, string const & dir)
519 using support::rtrim;
521 string const file_in = file.absFilename();
522 string const only_path = support::onlyPath(file_in);
523 if (rtrim(support::onlyPath(file_in) , "/") == rtrim(dir, "/"))
524 return std::make_pair(IDENTICAL_PATHS, file_in);
526 string mangled = file.mangledFilename();
527 if (file.isZipped()) {
528 // We need to change _eps.gz to .eps.gz. The mangled name is
529 // still unique because of the counter in mangledFilename().
530 // We can't just call mangledFilename() with the zip
531 // extension removed, because base.eps and base.eps.gz may
532 // have different content but would get the same mangled
533 // name in this case.
534 string const base = removeExtension(file.unzippedFilename());
535 string::size_type const ext_len = file_in.length() - base.length();
536 mangled[mangled.length() - ext_len] = '.';
538 FileName const file_out(support::makeAbsPath(mangled, dir));
540 return copyFileIfNeeded(file, file_out);
544 string const stripExtensionIfPossible(string const & file, bool nice)
546 // Remove the extension so the LaTeX compiler will use whatever
547 // is appropriate (when there are several versions in different
549 // Do this only if we are not exporting for internal usage, because
550 // pdflatex prefers png over pdf and it would pick up the png images
551 // that we generate for preview.
552 // This works only if the filename contains no dots besides
553 // the just removed one. We can fool here by replacing all
554 // dots with a macro whose definition is just a dot ;-)
555 // The automatic format selection does not work if the file
557 string const latex_name = latex_path(file,
558 support::EXCLUDE_EXTENSION);
559 if (!nice || contains(latex_name, '"'))
561 return latex_path(removeExtension(file),
562 support::PROTECT_EXTENSION,
563 support::ESCAPE_DOTS);
567 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
569 // No conversion is needed. LaTeX can handle the graphic file as is.
570 // This is true even if the orig_file is compressed.
571 string const to_format = formats.getFormat(to)->extension();
572 string const file_format = getExtension(file);
573 // for latex .ps == .eps
574 if (to_format == file_format ||
575 (to_format == "eps" && file_format == "ps") ||
576 (to_format == "ps" && file_format == "eps"))
577 return stripExtensionIfPossible(file, nice);
578 return latex_path(file, support::EXCLUDE_EXTENSION);
584 string const InsetGraphics::prepareFile(Buffer const & buf,
585 OutputParams const & runparams) const
587 // The following code depends on non-empty filenames
588 if (params().filename.empty())
591 string const orig_file = params().filename.absFilename();
592 string const rel_file = params().filename.relFilename(buf.filePath());
594 // previewing source code, no file copying or file format conversion
595 if (runparams.dryrun)
596 return stripExtensionIfPossible(rel_file, runparams.nice);
598 // temp_file will contain the file for LaTeX to act on if, for example,
599 // we move it to a temp dir or uncompress it.
600 FileName temp_file = params().filename;
602 // The master buffer. This is useful when there are multiple levels
604 Buffer const * masterBuffer = buf.masterBuffer();
606 // Return the output name if we are inside a comment or the file does
608 // We are not going to change the extension or using the name of the
609 // temporary file, the code is already complicated enough.
610 if (runparams.inComment || !params().filename.isReadableFile())
611 return params().filename.outputFilename(masterBuffer->filePath());
613 // We place all temporary files in the master buffer's temp dir.
614 // This is possible because we use mangled file names.
615 // This is necessary for DVI export.
616 string const temp_path = masterBuffer->temppath();
618 GraphicsCopyStatus status;
619 boost::tie(status, temp_file) =
620 copyToDirIfNeeded(params().filename, temp_path);
622 if (status == FAILURE)
625 // a relative filename should be relative to the master buffer.
626 // "nice" means that the buffer is exported to LaTeX format but not
627 // run through the LaTeX compiler.
628 string output_file = runparams.nice ?
629 params().filename.outputFilename(masterBuffer->filePath()) :
630 onlyFilename(temp_file.absFilename());
632 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
633 frontend::Alert::warning(_("Invalid filename"),
634 _("The following filename is likely to cause trouble "
635 "when running the exported file through LaTeX: ") +
636 from_utf8(output_file));
639 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
640 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
641 "latex" : "pdflatex";
643 // If the file is compressed and we have specified that it
644 // should not be uncompressed, then just return its name and
645 // let LaTeX do the rest!
646 if (params().filename.isZipped()) {
647 if (params().noUnzip) {
648 // We don't know whether latex can actually handle
649 // this file, but we can't check, because that would
650 // mean to unzip the file and thereby making the
651 // noUnzip parameter meaningless.
652 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
654 FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
655 if (runparams.nice) {
656 runparams.exportdata->addExternalFile(tex_format,
658 changeExtension(output_file, "bb"));
660 // LaTeX needs the bounding box file in the
662 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
663 boost::tie(status, bb_file) =
664 copyFileIfNeeded(bb_orig_file, bb_file);
665 if (status == FAILURE)
667 runparams.exportdata->addExternalFile(tex_format,
670 runparams.exportdata->addExternalFile(tex_format,
671 source_file, output_file);
672 runparams.exportdata->addExternalFile("dvi",
673 source_file, output_file);
674 // We can't strip the extension, because we don't know
675 // the unzipped file format
676 return latex_path(output_file,
677 support::EXCLUDE_EXTENSION);
680 FileName const unzipped_temp_file =
681 FileName(unzippedFileName(temp_file.absFilename()));
682 output_file = unzippedFileName(output_file);
683 source_file = FileName(unzippedFileName(source_file.absFilename()));
684 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
685 // temp_file has been unzipped already and
686 // orig_file has not changed in the meantime.
687 temp_file = unzipped_temp_file;
688 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
690 // unzipped_temp_file does not exist or is too old
691 temp_file = unzipFile(temp_file);
692 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
696 string const from = formats.getFormatFromFile(temp_file);
698 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
700 string const to = findTargetFormat(from, runparams);
701 string const ext = formats.extension(to);
702 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
704 // We're going to be running the exported buffer through the LaTeX
705 // compiler, so must ensure that LaTeX can cope with the graphics
708 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
711 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
712 // The LaTeX compiler will not be able to determine
713 // the file format from the extension, so we must
715 FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
716 if (support::rename(temp_file, new_file)) {
717 temp_file = new_file;
718 output_file = changeExtension(output_file, ext);
719 source_file = FileName(changeExtension(source_file.absFilename(), ext));
721 LYXERR(Debug::GRAPHICS, "Could not rename file `"
722 << temp_file << "' to `" << new_file << "'.");
725 // The extension of temp_file might be != ext!
726 runparams.exportdata->addExternalFile(tex_format, source_file,
728 runparams.exportdata->addExternalFile("dvi", source_file,
730 return stripExtensionIfPossible(output_file, to, runparams.nice);
733 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
734 string const output_to_file = changeExtension(output_file, ext);
736 // Do we need to perform the conversion?
737 // Yes if to_file does not exist or if temp_file is newer than to_file
738 if (compare_timestamps(temp_file, to_file) < 0) {
740 LYXERR(Debug::GRAPHICS,
741 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
742 from_utf8(rel_file))));
743 runparams.exportdata->addExternalFile(tex_format, to_file,
745 runparams.exportdata->addExternalFile("dvi", to_file,
747 return stripExtensionIfPossible(output_to_file, runparams.nice);
750 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
751 << "\tA copy has been made and convert is to be called with:\n"
752 << "\tfile to convert = " << temp_file << '\n'
753 << "\t from " << from << " to " << to);
755 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
757 if (theConverters().convert(&buf, temp_file, to_file, params().filename,
759 Converters::try_default | Converters::try_cache)) {
760 runparams.exportdata->addExternalFile(tex_format,
761 to_file, output_to_file);
762 runparams.exportdata->addExternalFile("dvi",
763 to_file, output_to_file);
766 return stripExtensionIfPossible(output_to_file, runparams.nice);
770 int InsetGraphics::latex(Buffer const & buf, odocstream & os,
771 OutputParams const & runparams) const
773 // If there is no file specified or not existing,
774 // just output a message about it in the latex output.
775 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
776 << params().filename.absFilename());
778 string const relative_file =
779 params().filename.relFilename(buf.filePath());
781 bool const file_exists = !params().filename.empty()
782 && params().filename.isReadableFile();
783 string const message = file_exists ?
784 string() : string("bb = 0 0 200 100, draft, type=eps");
785 // if !message.empty() then there was no existing file
786 // "filename" found. In this case LaTeX
787 // draws only a rectangle with the above bb and the
788 // not found filename in it.
789 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
791 // These variables collect all the latex code that should be before and
792 // after the actual includegraphics command.
795 // Do we want subcaptions?
796 if (params().subcaption) {
797 if (runparams.moving_arg)
798 before += "\\protect";
799 before += "\\subfigure[" + params().subcaptionText + "]{";
803 if (runparams.moving_arg)
804 before += "\\protect";
806 // We never use the starred form, we use the "clip" option instead.
807 before += "\\includegraphics";
809 // Write the options if there are any.
810 string const opts = createLatexOptions();
811 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
813 if (!opts.empty() && !message.empty())
814 before += ('[' + opts + ',' + message + ']');
815 else if (!opts.empty() || !message.empty())
816 before += ('[' + opts + message + ']');
818 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
820 string latex_str = before + '{';
821 // Convert the file if necessary.
822 // Remove the extension so LaTeX will use whatever is appropriate
823 // (when there are several versions in different formats)
824 latex_str += prepareFile(buf, runparams);
825 latex_str += '}' + after;
827 os << from_utf8(latex_str);
829 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
830 // Return how many newlines we issued.
831 return int(std::count(latex_str.begin(), latex_str.end(),'\n'));
835 int InsetGraphics::plaintext(Buffer const & buf, odocstream & os,
836 OutputParams const &) const
838 // No graphics in ascii output. Possible to use gifscii to convert
839 // images to ascii approximation.
840 // 1. Convert file to ascii using gifscii
841 // 2. Read ascii output file and add it to the output stream.
842 // at least we send the filename
844 // FIXME: We have no idea what the encoding of the filename is
846 docstring const str = bformat(buf.B_("Graphics file: %1$s"),
847 from_utf8(params().filename.absFilename()));
848 os << '<' << str << '>';
850 return 2 + str.size();
854 static int writeImageObject(char const * format, odocstream & os,
855 OutputParams const & runparams, docstring const & graphic_label,
856 docstring const & attributes)
858 if (runparams.flavor != OutputParams::XML)
859 os << "<![ %output.print." << format
860 << "; [" << std::endl;
862 os <<"<imageobject><imagedata fileref=\"&"
869 if (runparams.flavor == OutputParams::XML)
870 os << " role=\"" << format << "\"/>" ;
872 os << " format=\"" << format << "\">" ;
874 os << "</imageobject>";
876 if (runparams.flavor != OutputParams::XML)
877 os << std::endl << "]]>" ;
879 return runparams.flavor == OutputParams::XML ? 0 : 2;
883 // For explanation on inserting graphics into DocBook checkout:
884 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
885 // See also the docbook guide at http://www.docbook.org/
886 int InsetGraphics::docbook(Buffer const &, odocstream & os,
887 OutputParams const & runparams) const
889 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
890 // need to switch to MediaObject. However, for now this is sufficient and
892 if (runparams.flavor == OutputParams::XML)
893 runparams.exportdata->addExternalFile("docbook-xml",
896 runparams.exportdata->addExternalFile("docbook",
899 os << "<inlinemediaobject>";
902 docstring attributes = createDocBookAttributes();
903 r += writeImageObject("png", os, runparams, graphic_label, attributes);
904 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
905 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
906 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
908 os << "</inlinemediaobject>";
913 void InsetGraphics::validate(LaTeXFeatures & features) const
915 // If we have no image, we should not require anything.
916 if (params().filename.empty())
919 features.includeFile(graphic_label,
920 removeExtension(params().filename.absFilename()));
922 features.require("graphicx");
924 if (features.runparams().nice) {
925 Buffer const * masterBuffer = features.buffer().masterBuffer();
926 string const rel_file = removeExtension(params().filename.relFilename(masterBuffer->filePath()));
927 if (contains(rel_file, "."))
928 features.require("lyxdot");
931 if (params().subcaption)
932 features.require("subfigure");
936 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
938 // If nothing is changed, just return and say so.
939 if (params() == p && !p.filename.empty())
942 // Copy the new parameters.
945 // Update the display using the new parameters.
946 graphic_->update(params().as_grfxParams());
948 // We have changed data, report it.
953 InsetGraphicsParams const & InsetGraphics::params() const
959 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
960 Buffer const & buffer) const
962 formats.edit(buffer, p.filename,
963 formats.getFormatFromFile(p.filename));
967 string const InsetGraphicsMailer::name_("graphics");
969 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
974 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
976 return params2string(inset_.params(), buffer);
980 void InsetGraphicsMailer::string2params(string const & in,
981 Buffer const & buffer,
982 InsetGraphicsParams & params)
984 params = InsetGraphicsParams();
988 istringstream data(in);
994 if (!lex || name != name_)
995 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
998 inset.readInsetGraphics(lex, buffer.filePath());
999 params = inset.params();
1004 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
1005 Buffer const & buffer)
1008 data << name_ << ' ';
1009 params.Write(data, buffer);
1010 data << "\\end_inset\n";