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>
93 using namespace lyx::support;
99 /// Find the most suitable image format for images in \p format
100 /// Note that \p format may be unknown (i. e. an empty string)
101 string findTargetFormat(string const & format, OutputParams const & runparams)
103 // Are we using latex or pdflatex?
104 if (runparams.flavor == OutputParams::PDFLATEX) {
105 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
106 Format const * const f = formats.getFormat(format);
107 // Convert vector graphics to pdf
108 if (f && f->vectorFormat())
110 // pdflatex can use jpeg, png and pdf directly
113 // Convert everything else to png
116 // If it's postscript, we always do eps.
117 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
119 // any other than ps is changed to eps
128 InsetGraphics::InsetGraphics()
129 : graphic_label(sgml::uniqueID(from_ascii("graph"))),
130 graphic_(new RenderGraphic(this))
134 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
136 boost::signals::trackable(),
137 graphic_label(sgml::uniqueID(from_ascii("graph"))),
138 graphic_(new RenderGraphic(*ig.graphic_, this))
140 setParams(ig.params());
144 Inset * InsetGraphics::clone() const
146 return new InsetGraphics(*this);
150 InsetGraphics::~InsetGraphics()
152 InsetGraphicsMailer(*this).hideDialog();
156 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
158 switch (cmd.action) {
159 case LFUN_GRAPHICS_EDIT: {
160 Buffer const & buffer = cur.bv().buffer();
161 InsetGraphicsParams p;
162 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer, p);
163 editGraphics(p, buffer);
167 case LFUN_INSET_MODIFY: {
168 Buffer const & buffer = cur.buffer();
169 InsetGraphicsParams p;
170 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer, p);
171 if (!p.filename.empty())
178 case LFUN_INSET_DIALOG_UPDATE:
179 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
182 case LFUN_MOUSE_RELEASE:
183 if (!cur.selection())
184 InsetGraphicsMailer(*this).showDialog(&cur.bv());
188 Inset::doDispatch(cur, cmd);
194 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
195 FuncStatus & flag) const
197 switch (cmd.action) {
198 case LFUN_GRAPHICS_EDIT:
199 case LFUN_INSET_MODIFY:
200 case LFUN_INSET_DIALOG_UPDATE:
205 return Inset::getStatus(cur, cmd, flag);
210 void InsetGraphics::registerEmbeddedFiles(Buffer const &,
211 EmbeddedFiles & files) const
213 files.registerFile(params().filename.absFilename(),
218 void InsetGraphics::updateEmbeddedFile(Buffer const & buf,
219 EmbeddedFile const & file)
221 BOOST_ASSERT(buf.embeddedFiles().enabled());
222 params_.filename = file;
223 LYXERR(Debug::FILES, "Update InsetGraphic with File "
224 << params_.filename.toFilesystemEncoding()
225 << ", embedding status: " << params_.filename.embedded());
229 void InsetGraphics::edit(Cursor & cur, bool)
231 InsetGraphicsMailer(*this).showDialog(&cur.bv());
235 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
237 graphic_->metrics(mi, dim);
241 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
243 graphic_->draw(pi, x, y);
247 Inset::EDITABLE InsetGraphics::editable() const
253 void InsetGraphics::write(Buffer const & buf, ostream & os) const
256 params().Write(os, buf);
260 void InsetGraphics::read(Buffer const & buf, Lexer & lex)
262 string const token = lex.getString();
264 if (token == "Graphics")
265 readInsetGraphics(lex, buf.filePath());
267 LYXERR(Debug::GRAPHICS, "Not a Graphics inset!");
269 // InsetGraphics is read, with filename in params_. We do not know if this file actually
270 // exists or is embedded so we need to get the 'availableFile' from buf.embeddedFiles()
271 if (buf.embeddedFiles().enabled()) {
272 EmbeddedFiles::EmbeddedFileList::const_iterator it =
273 buf.embeddedFiles().find(params_.filename.toFilesystemEncoding());
274 if (it != buf.embeddedFiles().end())
275 // using available file, embedded or external, depending on file availability and
277 params_.filename = *it;
279 graphic_->update(params().as_grfxParams());
283 void InsetGraphics::readInsetGraphics(Lexer & lex, string const & bufpath)
285 bool finished = false;
287 while (lex.isOK() && !finished) {
290 string const token = lex.getString();
291 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
296 if (token == "\\end_inset") {
299 if (!params_.Read(lex, token, bufpath))
300 lyxerr << "Unknown token, " << token << ", skipping."
307 string const InsetGraphics::createLatexOptions() const
309 // Calculate the options part of the command, we must do it to a string
310 // stream since we might have a trailing comma that we would like to remove
311 // before writing it to the output stream.
312 ostringstream options;
313 if (!params().bb.empty())
314 options << "bb=" << rtrim(params().bb) << ',';
320 double const scl = convert<double>(params().scale);
321 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
322 if (!float_equal(scl, 100.0, 0.05))
323 size << "scale=" << scl / 100.0 << ',';
325 if (!params().width.zero())
326 size << "width=" << params().width.asLatexString() << ',';
327 if (!params().height.zero())
328 size << "height=" << params().height.asLatexString() << ',';
329 if (params().keepAspectRatio)
330 size << "keepaspectratio,";
332 if (params().scaleBeforeRotation && !size.str().empty())
333 options << size.str();
335 // Make sure rotation angle is not very close to zero;
336 // a float can be effectively zero but not exactly zero.
337 if (!params().rotateAngle.empty()
338 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
339 options << "angle=" << params().rotateAngle << ',';
340 if (!params().rotateOrigin.empty()) {
341 options << "origin=" << params().rotateOrigin[0];
342 if (contains(params().rotateOrigin,"Top"))
344 else if (contains(params().rotateOrigin,"Bottom"))
346 else if (contains(params().rotateOrigin,"Baseline"))
351 if (!params().scaleBeforeRotation && !size.str().empty())
352 options << size.str();
354 if (!params().special.empty())
355 options << params().special << ',';
357 string opts = options.str();
359 if (suffixIs(opts, ','))
360 opts = opts.substr(0, opts.size() - 1);
366 docstring const InsetGraphics::toDocbookLength(Length const & len) const
368 odocstringstream result;
369 switch (len.unit()) {
370 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
371 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
373 case Length::PT: // Point = 1/72.27in = 0.351mm
374 result << len.value() * 72 / 72.27 << "pt";
376 case Length::BP: // Big point (72bp = 1in), also PostScript point
377 result << len.value() << "pt";
379 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
380 result << len.value() * 0.376 << "mm";
382 case Length::MM: // Millimeter = 2.845pt
383 result << len.value() << "mm";
385 case Length::PC: // Pica = 12pt = 4.218mm
386 result << len.value() << "pc";
388 case Length::CC: // Cicero = 12dd = 4.531mm
389 result << len.value() * 4.531 << "mm";
391 case Length::CM: // Centimeter = 10mm = 2.371pc
392 result << len.value() << "cm";
394 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
395 result << len.value() << "in";
397 case Length::EX: // Height of a small "x" for the current font.
398 // Obviously we have to compromise here. Any better ratio than 1.5 ?
399 result << len.value() / 1.5 << "em";
401 case Length::EM: // Width of capital "M" in current font.
402 result << len.value() << "em";
404 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
405 result << len.value() * 18 << "em";
407 case Length::PTW: // Percent of TextWidth
408 case Length::PCW: // Percent of ColumnWidth
409 case Length::PPW: // Percent of PageWidth
410 case Length::PLW: // Percent of LineWidth
411 case Length::PTH: // Percent of TextHeight
412 case Length::PPH: // Percent of Paper
413 // Sigh, this will go wrong.
414 result << len.value() << "%";
417 result << len.asDocstring();
423 docstring const InsetGraphics::createDocBookAttributes() const
425 // Calculate the options part of the command, we must do it to a string
426 // stream since we copied the code from createLatexParams() ;-)
428 // FIXME: av: need to translate spec -> Docbook XSL spec
429 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
430 // Right now it only works with my version of db2latex :-)
432 odocstringstream options;
433 double const scl = convert<double>(params().scale);
434 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
435 if (!float_equal(scl, 100.0, 0.05))
436 options << " scale=\""
437 << static_cast<int>( (scl) + 0.5 )
440 if (!params().width.zero()) {
441 options << " width=\"" << toDocbookLength(params().width) << "\" ";
443 if (!params().height.zero()) {
444 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
446 if (params().keepAspectRatio) {
447 // This will be irrelevant unless both width and height are set
448 options << "scalefit=\"1\" ";
453 if (!params().special.empty())
454 options << from_ascii(params().special) << " ";
456 // trailing blanks are ok ...
457 return options.str();
463 enum GraphicsCopyStatus {
471 std::pair<GraphicsCopyStatus, FileName> const
472 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
474 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
475 unsigned long const checksum_in = file_in.checksum();
476 unsigned long const checksum_out = file_out.checksum();
478 if (checksum_in == checksum_out)
480 return std::make_pair(IDENTICAL_CONTENTS, file_out);
482 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
483 bool const success = mover.copy(file_in, file_out);
486 LYXERR(Debug::GRAPHICS,
487 to_utf8(support::bformat(_("Could not copy the file\n%1$s\n"
488 "into the temporary directory."),
489 from_utf8(file_in.absFilename()))));
492 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
493 return std::make_pair(status, file_out);
497 std::pair<GraphicsCopyStatus, FileName> const
498 copyToDirIfNeeded(DocFileName const & file, string const & dir)
500 using support::rtrim;
502 string const file_in = file.absFilename();
503 string const only_path = support::onlyPath(file_in);
504 if (rtrim(support::onlyPath(file_in) , "/") == rtrim(dir, "/"))
505 return std::make_pair(IDENTICAL_PATHS, file_in);
507 string mangled = file.mangledFilename();
508 if (file.isZipped()) {
509 // We need to change _eps.gz to .eps.gz. The mangled name is
510 // still unique because of the counter in mangledFilename().
511 // We can't just call mangledFilename() with the zip
512 // extension removed, because base.eps and base.eps.gz may
513 // have different content but would get the same mangled
514 // name in this case.
515 string const base = removeExtension(file.unzippedFilename());
516 string::size_type const ext_len = file_in.length() - base.length();
517 mangled[mangled.length() - ext_len] = '.';
519 FileName const file_out(support::makeAbsPath(mangled, dir));
521 return copyFileIfNeeded(file, file_out);
525 string const stripExtensionIfPossible(string const & file, bool nice)
527 // Remove the extension so the LaTeX compiler will use whatever
528 // is appropriate (when there are several versions in different
530 // Do this only if we are not exporting for internal usage, because
531 // pdflatex prefers png over pdf and it would pick up the png images
532 // that we generate for preview.
533 // This works only if the filename contains no dots besides
534 // the just removed one. We can fool here by replacing all
535 // dots with a macro whose definition is just a dot ;-)
536 // The automatic format selection does not work if the file
538 string const latex_name = latex_path(file,
539 support::EXCLUDE_EXTENSION);
540 if (!nice || contains(latex_name, '"'))
542 return latex_path(removeExtension(file),
543 support::PROTECT_EXTENSION,
544 support::ESCAPE_DOTS);
548 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
550 // No conversion is needed. LaTeX can handle the graphic file as is.
551 // This is true even if the orig_file is compressed.
552 string const to_format = formats.getFormat(to)->extension();
553 string const file_format = getExtension(file);
554 // for latex .ps == .eps
555 if (to_format == file_format ||
556 (to_format == "eps" && file_format == "ps") ||
557 (to_format == "ps" && file_format == "eps"))
558 return stripExtensionIfPossible(file, nice);
559 return latex_path(file, support::EXCLUDE_EXTENSION);
565 string const InsetGraphics::prepareFile(Buffer const & buf,
566 OutputParams const & runparams) const
568 // The following code depends on non-empty filenames
569 if (params().filename.empty())
572 string const orig_file = params().filename.absFilename();
573 string const rel_file = params().filename.relFilename(buf.filePath());
575 // previewing source code, no file copying or file format conversion
576 if (runparams.dryrun)
577 return stripExtensionIfPossible(rel_file, runparams.nice);
579 // temp_file will contain the file for LaTeX to act on if, for example,
580 // we move it to a temp dir or uncompress it.
581 FileName temp_file = params().filename;
583 // The master buffer. This is useful when there are multiple levels
585 Buffer const * masterBuffer = buf.masterBuffer();
587 // Return the output name if we are inside a comment or the file does
589 // We are not going to change the extension or using the name of the
590 // temporary file, the code is already complicated enough.
591 if (runparams.inComment || !params().filename.isReadableFile())
592 return params().filename.outputFilename(masterBuffer->filePath());
594 // We place all temporary files in the master buffer's temp dir.
595 // This is possible because we use mangled file names.
596 // This is necessary for DVI export.
597 string const temp_path = masterBuffer->temppath();
599 GraphicsCopyStatus status;
600 boost::tie(status, temp_file) =
601 copyToDirIfNeeded(params().filename, temp_path);
603 if (status == FAILURE)
606 // a relative filename should be relative to the master buffer.
607 // "nice" means that the buffer is exported to LaTeX format but not
608 // run through the LaTeX compiler.
609 string output_file = runparams.nice ?
610 params().filename.outputFilename(masterBuffer->filePath()) :
611 onlyFilename(temp_file.absFilename());
613 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
614 frontend::Alert::warning(_("Invalid filename"),
615 _("The following filename is likely to cause trouble "
616 "when running the exported file through LaTeX: ") +
617 from_utf8(output_file));
620 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
621 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
622 "latex" : "pdflatex";
624 // If the file is compressed and we have specified that it
625 // should not be uncompressed, then just return its name and
626 // let LaTeX do the rest!
627 if (params().filename.isZipped()) {
628 if (params().noUnzip) {
629 // We don't know whether latex can actually handle
630 // this file, but we can't check, because that would
631 // mean to unzip the file and thereby making the
632 // noUnzip parameter meaningless.
633 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
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, "\twas already unzipped to " << temp_file);
671 // unzipped_temp_file does not exist or is too old
672 temp_file = unzipFile(temp_file);
673 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
677 string const from = formats.getFormatFromFile(temp_file);
679 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
681 string const to = findTargetFormat(from, runparams);
682 string const ext = formats.extension(to);
683 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
685 // We're going to be running the exported buffer through the LaTeX
686 // compiler, so must ensure that LaTeX can cope with the graphics
689 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
692 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
693 // The LaTeX compiler will not be able to determine
694 // the file format from the extension, so we must
696 FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
697 if (support::rename(temp_file, new_file)) {
698 temp_file = new_file;
699 output_file = changeExtension(output_file, ext);
700 source_file = FileName(changeExtension(source_file.absFilename(), ext));
702 LYXERR(Debug::GRAPHICS, "Could not rename file `"
703 << temp_file << "' to `" << new_file << "'.");
706 // The extension of temp_file might be != ext!
707 runparams.exportdata->addExternalFile(tex_format, source_file,
709 runparams.exportdata->addExternalFile("dvi", source_file,
711 return stripExtensionIfPossible(output_file, to, runparams.nice);
714 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
715 string const output_to_file = changeExtension(output_file, ext);
717 // Do we need to perform the conversion?
718 // Yes if to_file does not exist or if temp_file is newer than to_file
719 if (compare_timestamps(temp_file, to_file) < 0) {
721 LYXERR(Debug::GRAPHICS,
722 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
723 from_utf8(rel_file))));
724 runparams.exportdata->addExternalFile(tex_format, to_file,
726 runparams.exportdata->addExternalFile("dvi", to_file,
728 return stripExtensionIfPossible(output_to_file, runparams.nice);
731 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
732 << "\tA copy has been made and convert is to be called with:\n"
733 << "\tfile to convert = " << temp_file << '\n'
734 << "\t from " << from << " to " << to);
736 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
738 if (theConverters().convert(&buf, temp_file, to_file, params().filename,
740 Converters::try_default | Converters::try_cache)) {
741 runparams.exportdata->addExternalFile(tex_format,
742 to_file, output_to_file);
743 runparams.exportdata->addExternalFile("dvi",
744 to_file, output_to_file);
747 return stripExtensionIfPossible(output_to_file, runparams.nice);
751 int InsetGraphics::latex(Buffer const & buf, odocstream & os,
752 OutputParams const & runparams) const
754 // If there is no file specified or not existing,
755 // just output a message about it in the latex output.
756 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
757 << params().filename.absFilename());
759 string const relative_file =
760 params().filename.relFilename(buf.filePath());
762 bool const file_exists = !params().filename.empty()
763 && params().filename.isReadableFile();
764 string const message = file_exists ?
765 string() : string("bb = 0 0 200 100, draft, type=eps");
766 // if !message.empty() then there was no existing file
767 // "filename" found. In this case LaTeX
768 // draws only a rectangle with the above bb and the
769 // not found filename in it.
770 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
772 // These variables collect all the latex code that should be before and
773 // after the actual includegraphics command.
776 // Do we want subcaptions?
777 if (params().subcaption) {
778 if (runparams.moving_arg)
779 before += "\\protect";
780 before += "\\subfigure[" + params().subcaptionText + "]{";
784 if (runparams.moving_arg)
785 before += "\\protect";
787 // We never use the starred form, we use the "clip" option instead.
788 before += "\\includegraphics";
790 // Write the options if there are any.
791 string const opts = createLatexOptions();
792 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
794 if (!opts.empty() && !message.empty())
795 before += ('[' + opts + ',' + message + ']');
796 else if (!opts.empty() || !message.empty())
797 before += ('[' + opts + message + ']');
799 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
801 string latex_str = before + '{';
802 // Convert the file if necessary.
803 // Remove the extension so LaTeX will use whatever is appropriate
804 // (when there are several versions in different formats)
805 latex_str += prepareFile(buf, runparams);
806 latex_str += '}' + after;
808 os << from_utf8(latex_str);
810 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
811 // Return how many newlines we issued.
812 return int(std::count(latex_str.begin(), latex_str.end(),'\n'));
816 int InsetGraphics::plaintext(Buffer const & buf, odocstream & os,
817 OutputParams const &) const
819 // No graphics in ascii output. Possible to use gifscii to convert
820 // images to ascii approximation.
821 // 1. Convert file to ascii using gifscii
822 // 2. Read ascii output file and add it to the output stream.
823 // at least we send the filename
825 // FIXME: We have no idea what the encoding of the filename is
827 docstring const str = bformat(buf.B_("Graphics file: %1$s"),
828 from_utf8(params().filename.absFilename()));
829 os << '<' << str << '>';
831 return 2 + str.size();
835 static int writeImageObject(char const * format, odocstream & os,
836 OutputParams const & runparams, docstring const & graphic_label,
837 docstring const & attributes)
839 if (runparams.flavor != OutputParams::XML)
840 os << "<![ %output.print." << format
841 << "; [" << std::endl;
843 os <<"<imageobject><imagedata fileref=\"&"
850 if (runparams.flavor == OutputParams::XML)
851 os << " role=\"" << format << "\"/>" ;
853 os << " format=\"" << format << "\">" ;
855 os << "</imageobject>";
857 if (runparams.flavor != OutputParams::XML)
858 os << std::endl << "]]>" ;
860 return runparams.flavor == OutputParams::XML ? 0 : 2;
864 // For explanation on inserting graphics into DocBook checkout:
865 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
866 // See also the docbook guide at http://www.docbook.org/
867 int InsetGraphics::docbook(Buffer const &, odocstream & os,
868 OutputParams const & runparams) const
870 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
871 // need to switch to MediaObject. However, for now this is sufficient and
873 if (runparams.flavor == OutputParams::XML)
874 runparams.exportdata->addExternalFile("docbook-xml",
877 runparams.exportdata->addExternalFile("docbook",
880 os << "<inlinemediaobject>";
883 docstring attributes = createDocBookAttributes();
884 r += writeImageObject("png", os, runparams, graphic_label, attributes);
885 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
886 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
887 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
889 os << "</inlinemediaobject>";
894 void InsetGraphics::validate(LaTeXFeatures & features) const
896 // If we have no image, we should not require anything.
897 if (params().filename.empty())
900 features.includeFile(graphic_label,
901 removeExtension(params().filename.absFilename()));
903 features.require("graphicx");
905 if (features.runparams().nice) {
906 Buffer const * masterBuffer = features.buffer().masterBuffer();
907 string const rel_file = removeExtension(params().filename.relFilename(masterBuffer->filePath()));
908 if (contains(rel_file, "."))
909 features.require("lyxdot");
912 if (params().subcaption)
913 features.require("subfigure");
917 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
919 // If nothing is changed, just return and say so.
920 if (params() == p && !p.filename.empty())
923 // Copy the new parameters.
926 // Update the display using the new parameters.
927 graphic_->update(params().as_grfxParams());
929 // We have changed data, report it.
934 InsetGraphicsParams const & InsetGraphics::params() const
940 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
941 Buffer const & buffer) const
943 formats.edit(buffer, p.filename,
944 formats.getFormatFromFile(p.filename));
948 string const InsetGraphicsMailer::name_("graphics");
950 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
955 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
957 return params2string(inset_.params(), buffer);
961 void InsetGraphicsMailer::string2params(string const & in,
962 Buffer const & buffer,
963 InsetGraphicsParams & params)
965 params = InsetGraphicsParams();
969 istringstream data(in);
975 if (!lex || name != name_)
976 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
979 inset.readInsetGraphics(lex, buffer.filePath());
980 params = inset.params();
985 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
986 Buffer const & buffer)
989 data << name_ << ' ';
990 params.Write(data, buffer);
991 data << "\\end_inset\n";