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/ExceptionMessage.h"
81 #include "support/filetools.h"
82 #include "support/lyxlib.h"
83 #include "support/lstrings.h"
84 #include "support/os.h"
85 #include "support/Systemcall.h"
87 #include <boost/bind.hpp>
88 #include <boost/tuple/tuple.hpp>
94 using namespace lyx::support;
98 namespace Alert = frontend::Alert;
102 /// Find the most suitable image format for images in \p format
103 /// Note that \p format may be unknown (i. e. an empty string)
104 string findTargetFormat(string const & format, OutputParams const & runparams)
106 // Are we using latex or pdflatex?
107 if (runparams.flavor == OutputParams::PDFLATEX) {
108 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
109 Format const * const f = formats.getFormat(format);
110 // Convert vector graphics to pdf
111 if (f && f->vectorFormat())
113 // pdflatex can use jpeg, png and pdf directly
116 // Convert everything else to png
119 // If it's postscript, we always do eps.
120 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
122 // any other than ps is changed to eps
131 InsetGraphics::InsetGraphics()
132 : graphic_label(sgml::uniqueID(from_ascii("graph"))),
133 graphic_(new RenderGraphic(this))
137 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
139 boost::signals::trackable(),
140 graphic_label(sgml::uniqueID(from_ascii("graph"))),
141 graphic_(new RenderGraphic(*ig.graphic_, this))
143 setParams(ig.params());
147 Inset * InsetGraphics::clone() const
149 return new InsetGraphics(*this);
153 InsetGraphics::~InsetGraphics()
155 InsetGraphicsMailer(*this).hideDialog();
159 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
161 switch (cmd.action) {
162 case LFUN_GRAPHICS_EDIT: {
163 Buffer const & buffer = cur.bv().buffer();
164 InsetGraphicsParams p;
165 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer, p);
166 editGraphics(p, buffer);
170 case LFUN_INSET_MODIFY: {
171 Buffer const & buffer = cur.buffer();
172 InsetGraphicsParams p;
173 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer, p);
174 // when embedding is enabled, change of embedding status leads to actions
175 if (!p.filename.empty() && buffer.embeddedFiles().enabled() ) {
177 if (p.filename.embedded())
178 p.filename.updateFromExternalFile(&buffer);
180 p.filename.extract(&buffer);
181 } catch (ExceptionMessage const & message) {
182 Alert::error(message.title_, message.details_);
183 // do not set parameter if an error happens
192 case LFUN_INSET_DIALOG_UPDATE:
193 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
196 case LFUN_MOUSE_RELEASE:
197 if (!cur.selection())
198 InsetGraphicsMailer(*this).showDialog(&cur.bv());
202 Inset::doDispatch(cur, cmd);
208 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
209 FuncStatus & flag) const
211 switch (cmd.action) {
212 case LFUN_GRAPHICS_EDIT:
213 case LFUN_INSET_MODIFY:
214 case LFUN_INSET_DIALOG_UPDATE:
219 return Inset::getStatus(cur, cmd, flag);
224 void InsetGraphics::registerEmbeddedFiles(Buffer const &,
225 EmbeddedFiles & files) const
227 files.registerFile(params().filename, this);
231 void InsetGraphics::updateEmbeddedFile(Buffer const & buf,
232 EmbeddedFile const & file)
234 BOOST_ASSERT(buf.embeddedFiles().enabled());
235 params_.filename = file;
236 LYXERR(Debug::FILES, "Update InsetGraphic with File "
237 << params_.filename.toFilesystemEncoding()
238 << ", embedding status: " << params_.filename.embedded());
242 void InsetGraphics::edit(Cursor & cur, bool)
244 InsetGraphicsMailer(*this).showDialog(&cur.bv());
248 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
250 graphic_->metrics(mi, dim);
254 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
256 graphic_->draw(pi, x, y);
260 Inset::EDITABLE InsetGraphics::editable() const
266 void InsetGraphics::write(Buffer const & buf, ostream & os) const
269 params().Write(os, buf);
273 void InsetGraphics::read(Buffer const & buf, Lexer & lex)
275 string const token = lex.getString();
277 if (token == "Graphics")
278 readInsetGraphics(lex, buf.filePath());
280 LYXERR(Debug::GRAPHICS, "Not a Graphics inset!");
282 // InsetGraphics is read, with filename in params_. We do not know if this file actually
283 // exists or is embedded so we need to get the 'availableFile' from buf.embeddedFiles()
284 if (buf.embeddedFiles().enabled()) {
285 EmbeddedFiles::EmbeddedFileList::const_iterator it =
286 buf.embeddedFiles().find(params_.filename.toFilesystemEncoding());
287 if (it != buf.embeddedFiles().end())
288 // using available file, embedded or external, depending on file availability and
290 params_.filename = *it;
292 graphic_->update(params().as_grfxParams());
296 void InsetGraphics::readInsetGraphics(Lexer & lex, string const & bufpath)
298 bool finished = false;
300 while (lex.isOK() && !finished) {
303 string const token = lex.getString();
304 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
309 if (token == "\\end_inset") {
312 if (!params_.Read(lex, token, bufpath))
313 lyxerr << "Unknown token, " << token << ", skipping."
320 string const InsetGraphics::createLatexOptions() const
322 // Calculate the options part of the command, we must do it to a string
323 // stream since we might have a trailing comma that we would like to remove
324 // before writing it to the output stream.
325 ostringstream options;
326 if (!params().bb.empty())
327 options << "bb=" << rtrim(params().bb) << ',';
333 double const scl = convert<double>(params().scale);
334 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
335 if (!float_equal(scl, 100.0, 0.05))
336 size << "scale=" << scl / 100.0 << ',';
338 if (!params().width.zero())
339 size << "width=" << params().width.asLatexString() << ',';
340 if (!params().height.zero())
341 size << "height=" << params().height.asLatexString() << ',';
342 if (params().keepAspectRatio)
343 size << "keepaspectratio,";
345 if (params().scaleBeforeRotation && !size.str().empty())
346 options << size.str();
348 // Make sure rotation angle is not very close to zero;
349 // a float can be effectively zero but not exactly zero.
350 if (!params().rotateAngle.empty()
351 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
352 options << "angle=" << params().rotateAngle << ',';
353 if (!params().rotateOrigin.empty()) {
354 options << "origin=" << params().rotateOrigin[0];
355 if (contains(params().rotateOrigin,"Top"))
357 else if (contains(params().rotateOrigin,"Bottom"))
359 else if (contains(params().rotateOrigin,"Baseline"))
364 if (!params().scaleBeforeRotation && !size.str().empty())
365 options << size.str();
367 if (!params().special.empty())
368 options << params().special << ',';
370 string opts = options.str();
372 if (suffixIs(opts, ','))
373 opts = opts.substr(0, opts.size() - 1);
379 docstring const InsetGraphics::toDocbookLength(Length const & len) const
381 odocstringstream result;
382 switch (len.unit()) {
383 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
384 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
386 case Length::PT: // Point = 1/72.27in = 0.351mm
387 result << len.value() * 72 / 72.27 << "pt";
389 case Length::BP: // Big point (72bp = 1in), also PostScript point
390 result << len.value() << "pt";
392 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
393 result << len.value() * 0.376 << "mm";
395 case Length::MM: // Millimeter = 2.845pt
396 result << len.value() << "mm";
398 case Length::PC: // Pica = 12pt = 4.218mm
399 result << len.value() << "pc";
401 case Length::CC: // Cicero = 12dd = 4.531mm
402 result << len.value() * 4.531 << "mm";
404 case Length::CM: // Centimeter = 10mm = 2.371pc
405 result << len.value() << "cm";
407 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
408 result << len.value() << "in";
410 case Length::EX: // Height of a small "x" for the current font.
411 // Obviously we have to compromise here. Any better ratio than 1.5 ?
412 result << len.value() / 1.5 << "em";
414 case Length::EM: // Width of capital "M" in current font.
415 result << len.value() << "em";
417 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
418 result << len.value() * 18 << "em";
420 case Length::PTW: // Percent of TextWidth
421 case Length::PCW: // Percent of ColumnWidth
422 case Length::PPW: // Percent of PageWidth
423 case Length::PLW: // Percent of LineWidth
424 case Length::PTH: // Percent of TextHeight
425 case Length::PPH: // Percent of Paper
426 // Sigh, this will go wrong.
427 result << len.value() << "%";
430 result << len.asDocstring();
436 docstring const InsetGraphics::createDocBookAttributes() const
438 // Calculate the options part of the command, we must do it to a string
439 // stream since we copied the code from createLatexParams() ;-)
441 // FIXME: av: need to translate spec -> Docbook XSL spec
442 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
443 // Right now it only works with my version of db2latex :-)
445 odocstringstream options;
446 double const scl = convert<double>(params().scale);
447 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
448 if (!float_equal(scl, 100.0, 0.05))
449 options << " scale=\""
450 << static_cast<int>( (scl) + 0.5 )
453 if (!params().width.zero()) {
454 options << " width=\"" << toDocbookLength(params().width) << "\" ";
456 if (!params().height.zero()) {
457 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
459 if (params().keepAspectRatio) {
460 // This will be irrelevant unless both width and height are set
461 options << "scalefit=\"1\" ";
466 if (!params().special.empty())
467 options << from_ascii(params().special) << " ";
469 // trailing blanks are ok ...
470 return options.str();
476 enum GraphicsCopyStatus {
484 pair<GraphicsCopyStatus, FileName> const
485 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
487 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
488 unsigned long const checksum_in = file_in.checksum();
489 unsigned long const checksum_out = file_out.checksum();
491 if (checksum_in == checksum_out)
493 return make_pair(IDENTICAL_CONTENTS, file_out);
495 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
496 bool const success = mover.copy(file_in, file_out);
499 LYXERR(Debug::GRAPHICS,
500 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
501 "into the temporary directory."),
502 from_utf8(file_in.absFilename()))));
505 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
506 return make_pair(status, file_out);
510 pair<GraphicsCopyStatus, FileName> const
511 copyToDirIfNeeded(DocFileName const & file, string const & dir)
513 string const file_in = file.absFilename();
514 string const only_path = onlyPath(file_in);
515 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
516 return make_pair(IDENTICAL_PATHS, file_in);
518 string mangled = file.mangledFilename();
519 if (file.isZipped()) {
520 // We need to change _eps.gz to .eps.gz. The mangled name is
521 // still unique because of the counter in mangledFilename().
522 // We can't just call mangledFilename() with the zip
523 // extension removed, because base.eps and base.eps.gz may
524 // have different content but would get the same mangled
525 // name in this case.
526 string const base = removeExtension(file.unzippedFilename());
527 string::size_type const ext_len = file_in.length() - base.length();
528 mangled[mangled.length() - ext_len] = '.';
530 FileName const file_out(makeAbsPath(mangled, dir));
532 return copyFileIfNeeded(file, file_out);
536 string const stripExtensionIfPossible(string const & file, bool nice)
538 // Remove the extension so the LaTeX compiler will use whatever
539 // is appropriate (when there are several versions in different
541 // Do this only if we are not exporting for internal usage, because
542 // pdflatex prefers png over pdf and it would pick up the png images
543 // that we generate for preview.
544 // This works only if the filename contains no dots besides
545 // the just removed one. We can fool here by replacing all
546 // dots with a macro whose definition is just a dot ;-)
547 // The automatic format selection does not work if the file
549 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
550 if (!nice || contains(latex_name, '"'))
552 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
556 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
558 // No conversion is needed. LaTeX can handle the graphic file as is.
559 // This is true even if the orig_file is compressed.
560 string const to_format = formats.getFormat(to)->extension();
561 string const file_format = getExtension(file);
562 // for latex .ps == .eps
563 if (to_format == file_format ||
564 (to_format == "eps" && file_format == "ps") ||
565 (to_format == "ps" && file_format == "eps"))
566 return stripExtensionIfPossible(file, nice);
567 return latex_path(file, EXCLUDE_EXTENSION);
573 string const InsetGraphics::prepareFile(Buffer const & buf,
574 OutputParams const & runparams) const
576 // The following code depends on non-empty filenames
577 if (params().filename.empty())
580 string const orig_file = params().filename.absFilename();
581 string const rel_file = params().filename.relFilename(buf.filePath());
583 // previewing source code, no file copying or file format conversion
584 if (runparams.dryrun)
585 return stripExtensionIfPossible(rel_file, runparams.nice);
587 // temp_file will contain the file for LaTeX to act on if, for example,
588 // we move it to a temp dir or uncompress it.
589 FileName temp_file = params().filename;
591 // The master buffer. This is useful when there are multiple levels
593 Buffer const * masterBuffer = buf.masterBuffer();
595 // Return the output name if we are inside a comment or the file does
597 // We are not going to change the extension or using the name of the
598 // temporary file, the code is already complicated enough.
599 if (runparams.inComment || !params().filename.isReadableFile())
600 return params().filename.outputFilename(masterBuffer->filePath());
602 // We place all temporary files in the master buffer's temp dir.
603 // This is possible because we use mangled file names.
604 // This is necessary for DVI export.
605 string const temp_path = masterBuffer->temppath();
607 GraphicsCopyStatus status;
608 boost::tie(status, temp_file) =
609 copyToDirIfNeeded(params().filename, temp_path);
611 if (status == FAILURE)
614 // a relative filename should be relative to the master buffer.
615 // "nice" means that the buffer is exported to LaTeX format but not
616 // run through the LaTeX compiler.
617 string output_file = runparams.nice ?
618 params().filename.outputFilename(masterBuffer->filePath()) :
619 onlyFilename(temp_file.absFilename());
621 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
622 frontend::Alert::warning(_("Invalid filename"),
623 _("The following filename is likely to cause trouble "
624 "when running the exported file through LaTeX: ") +
625 from_utf8(output_file));
628 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
629 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
630 "latex" : "pdflatex";
632 // If the file is compressed and we have specified that it
633 // should not be uncompressed, then just return its name and
634 // let LaTeX do the rest!
635 if (params().filename.isZipped()) {
636 if (params().noUnzip) {
637 // We don't know whether latex can actually handle
638 // this file, but we can't check, because that would
639 // mean to unzip the file and thereby making the
640 // noUnzip parameter meaningless.
641 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
643 FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
644 if (runparams.nice) {
645 runparams.exportdata->addExternalFile(tex_format,
647 changeExtension(output_file, "bb"));
649 // LaTeX needs the bounding box file in the
651 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
652 boost::tie(status, bb_file) =
653 copyFileIfNeeded(bb_orig_file, bb_file);
654 if (status == FAILURE)
656 runparams.exportdata->addExternalFile(tex_format,
659 runparams.exportdata->addExternalFile(tex_format,
660 source_file, output_file);
661 runparams.exportdata->addExternalFile("dvi",
662 source_file, output_file);
663 // We can't strip the extension, because we don't know
664 // the unzipped file format
665 return latex_path(output_file, EXCLUDE_EXTENSION);
668 FileName const unzipped_temp_file =
669 FileName(unzippedFileName(temp_file.absFilename()));
670 output_file = unzippedFileName(output_file);
671 source_file = FileName(unzippedFileName(source_file.absFilename()));
672 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
673 // temp_file has been unzipped already and
674 // orig_file has not changed in the meantime.
675 temp_file = unzipped_temp_file;
676 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
678 // unzipped_temp_file does not exist or is too old
679 temp_file = unzipFile(temp_file);
680 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
684 string const from = formats.getFormatFromFile(temp_file);
686 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
688 string const to = findTargetFormat(from, runparams);
689 string const ext = formats.extension(to);
690 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
692 // We're going to be running the exported buffer through the LaTeX
693 // compiler, so must ensure that LaTeX can cope with the graphics
696 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
699 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
700 // The LaTeX compiler will not be able to determine
701 // the file format from the extension, so we must
703 FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
704 if (temp_file.moveTo(new_file)) {
705 temp_file = new_file;
706 output_file = changeExtension(output_file, ext);
707 source_file = FileName(changeExtension(source_file.absFilename(), ext));
709 LYXERR(Debug::GRAPHICS, "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))));
731 runparams.exportdata->addExternalFile(tex_format, to_file,
733 runparams.exportdata->addExternalFile("dvi", to_file,
735 return stripExtensionIfPossible(output_to_file, runparams.nice);
738 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
739 << "\tA copy has been made and convert is to be called with:\n"
740 << "\tfile to convert = " << temp_file << '\n'
741 << "\t from " << from << " to " << to);
743 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
745 if (theConverters().convert(&buf, temp_file, to_file, params().filename,
747 Converters::try_default | Converters::try_cache)) {
748 runparams.exportdata->addExternalFile(tex_format,
749 to_file, output_to_file);
750 runparams.exportdata->addExternalFile("dvi",
751 to_file, output_to_file);
754 return stripExtensionIfPossible(output_to_file, runparams.nice);
758 int InsetGraphics::latex(Buffer const & buf, odocstream & os,
759 OutputParams const & runparams) const
761 // If there is no file specified or not existing,
762 // just output a message about it in the latex output.
763 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
764 << params().filename.absFilename());
766 string const relative_file =
767 params().filename.relFilename(buf.filePath());
769 bool const file_exists = !params().filename.empty()
770 && params().filename.isReadableFile();
771 string const message = file_exists ?
772 string() : string("bb = 0 0 200 100, draft, type=eps");
773 // if !message.empty() then there was no existing file
774 // "filename" found. In this case LaTeX
775 // draws only a rectangle with the above bb and the
776 // not found filename in it.
777 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
779 // These variables collect all the latex code that should be before and
780 // after the actual includegraphics command.
783 // Do we want subcaptions?
784 if (params().subcaption) {
785 if (runparams.moving_arg)
786 before += "\\protect";
787 before += "\\subfigure[" + params().subcaptionText + "]{";
791 if (runparams.moving_arg)
792 before += "\\protect";
794 // We never use the starred form, we use the "clip" option instead.
795 before += "\\includegraphics";
797 // Write the options if there are any.
798 string const opts = createLatexOptions();
799 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
801 if (!opts.empty() && !message.empty())
802 before += ('[' + opts + ',' + message + ']');
803 else if (!opts.empty() || !message.empty())
804 before += ('[' + opts + message + ']');
806 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
808 string latex_str = before + '{';
809 // Convert the file if necessary.
810 // Remove the extension so LaTeX will use whatever is appropriate
811 // (when there are several versions in different formats)
812 latex_str += prepareFile(buf, runparams);
813 latex_str += '}' + after;
815 os << from_utf8(latex_str);
817 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
818 // Return how many newlines we issued.
819 return int(count(latex_str.begin(), latex_str.end(),'\n'));
823 int InsetGraphics::plaintext(Buffer const & buf, odocstream & os,
824 OutputParams const &) const
826 // No graphics in ascii output. Possible to use gifscii to convert
827 // images to ascii approximation.
828 // 1. Convert file to ascii using gifscii
829 // 2. Read ascii output file and add it to the output stream.
830 // at least we send the filename
832 // FIXME: We have no idea what the encoding of the filename is
834 docstring const str = bformat(buf.B_("Graphics file: %1$s"),
835 from_utf8(params().filename.absFilename()));
836 os << '<' << str << '>';
838 return 2 + str.size();
842 static int writeImageObject(char const * format, odocstream & os,
843 OutputParams const & runparams, docstring const & graphic_label,
844 docstring const & attributes)
846 if (runparams.flavor != OutputParams::XML)
847 os << "<![ %output.print." << format
850 os <<"<imageobject><imagedata fileref=\"&"
857 if (runparams.flavor == OutputParams::XML)
858 os << " role=\"" << format << "\"/>" ;
860 os << " format=\"" << format << "\">" ;
862 os << "</imageobject>";
864 if (runparams.flavor != OutputParams::XML)
865 os << endl << "]]>" ;
867 return runparams.flavor == OutputParams::XML ? 0 : 2;
871 // For explanation on inserting graphics into DocBook checkout:
872 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
873 // See also the docbook guide at http://www.docbook.org/
874 int InsetGraphics::docbook(Buffer const &, odocstream & os,
875 OutputParams const & runparams) const
877 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
878 // need to switch to MediaObject. However, for now this is sufficient and
880 if (runparams.flavor == OutputParams::XML)
881 runparams.exportdata->addExternalFile("docbook-xml",
884 runparams.exportdata->addExternalFile("docbook",
887 os << "<inlinemediaobject>";
890 docstring attributes = createDocBookAttributes();
891 r += writeImageObject("png", os, runparams, graphic_label, attributes);
892 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
893 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
894 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
896 os << "</inlinemediaobject>";
901 void InsetGraphics::validate(LaTeXFeatures & features) const
903 // If we have no image, we should not require anything.
904 if (params().filename.empty())
907 features.includeFile(graphic_label,
908 removeExtension(params().filename.absFilename()));
910 features.require("graphicx");
912 if (features.runparams().nice) {
913 Buffer const * masterBuffer = features.buffer().masterBuffer();
914 string const rel_file = removeExtension(params().filename.relFilename(masterBuffer->filePath()));
915 if (contains(rel_file, "."))
916 features.require("lyxdot");
919 if (params().subcaption)
920 features.require("subfigure");
924 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
926 // If nothing is changed, just return and say so.
927 if (params() == p && !p.filename.empty())
930 // Copy the new parameters.
933 // Update the display using the new parameters.
934 graphic_->update(params().as_grfxParams());
936 // We have changed data, report it.
941 InsetGraphicsParams const & InsetGraphics::params() const
947 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
948 Buffer const & buffer) const
950 formats.edit(buffer, p.filename,
951 formats.getFormatFromFile(p.filename));
955 string const InsetGraphicsMailer::name_("graphics");
957 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
962 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
964 return params2string(inset_.params(), buffer);
968 void InsetGraphicsMailer::string2params(string const & in,
969 Buffer const & buffer,
970 InsetGraphicsParams & params)
972 params = InsetGraphicsParams();
976 istringstream data(in);
982 if (!lex || name != name_)
983 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
986 inset.readInsetGraphics(lex, buffer.filePath());
987 params = inset.params();
992 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
993 Buffer const & buffer)
996 data << name_ << ' ';
997 params.Write(data, buffer);
998 data << "\\end_inset\n";