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 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 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(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 make_pair(status, file_out);
497 pair<GraphicsCopyStatus, FileName> const
498 copyToDirIfNeeded(DocFileName const & file, string const & dir)
500 string const file_in = file.absFilename();
501 string const only_path = onlyPath(file_in);
502 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
503 return make_pair(IDENTICAL_PATHS, file_in);
505 string mangled = file.mangledFilename();
506 if (file.isZipped()) {
507 // We need to change _eps.gz to .eps.gz. The mangled name is
508 // still unique because of the counter in mangledFilename().
509 // We can't just call mangledFilename() with the zip
510 // extension removed, because base.eps and base.eps.gz may
511 // have different content but would get the same mangled
512 // name in this case.
513 string const base = removeExtension(file.unzippedFilename());
514 string::size_type const ext_len = file_in.length() - base.length();
515 mangled[mangled.length() - ext_len] = '.';
517 FileName const file_out(makeAbsPath(mangled, dir));
519 return copyFileIfNeeded(file, file_out);
523 string const stripExtensionIfPossible(string const & file, bool nice)
525 // Remove the extension so the LaTeX compiler will use whatever
526 // is appropriate (when there are several versions in different
528 // Do this only if we are not exporting for internal usage, because
529 // pdflatex prefers png over pdf and it would pick up the png images
530 // that we generate for preview.
531 // This works only if the filename contains no dots besides
532 // the just removed one. We can fool here by replacing all
533 // dots with a macro whose definition is just a dot ;-)
534 // The automatic format selection does not work if the file
536 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
537 if (!nice || contains(latex_name, '"'))
539 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
543 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
545 // No conversion is needed. LaTeX can handle the graphic file as is.
546 // This is true even if the orig_file is compressed.
547 string const to_format = formats.getFormat(to)->extension();
548 string const file_format = getExtension(file);
549 // for latex .ps == .eps
550 if (to_format == file_format ||
551 (to_format == "eps" && file_format == "ps") ||
552 (to_format == "ps" && file_format == "eps"))
553 return stripExtensionIfPossible(file, nice);
554 return latex_path(file, EXCLUDE_EXTENSION);
560 string const InsetGraphics::prepareFile(Buffer const & buf,
561 OutputParams const & runparams) const
563 // The following code depends on non-empty filenames
564 if (params().filename.empty())
567 string const orig_file = params().filename.absFilename();
568 string const rel_file = params().filename.relFilename(buf.filePath());
570 // previewing source code, no file copying or file format conversion
571 if (runparams.dryrun)
572 return stripExtensionIfPossible(rel_file, runparams.nice);
574 // temp_file will contain the file for LaTeX to act on if, for example,
575 // we move it to a temp dir or uncompress it.
576 FileName temp_file = params().filename;
578 // The master buffer. This is useful when there are multiple levels
580 Buffer const * masterBuffer = buf.masterBuffer();
582 // Return the output name if we are inside a comment or the file does
584 // We are not going to change the extension or using the name of the
585 // temporary file, the code is already complicated enough.
586 if (runparams.inComment || !params().filename.isReadableFile())
587 return params().filename.outputFilename(masterBuffer->filePath());
589 // We place all temporary files in the master buffer's temp dir.
590 // This is possible because we use mangled file names.
591 // This is necessary for DVI export.
592 string const temp_path = masterBuffer->temppath();
594 GraphicsCopyStatus status;
595 boost::tie(status, temp_file) =
596 copyToDirIfNeeded(params().filename, temp_path);
598 if (status == FAILURE)
601 // a relative filename should be relative to the master buffer.
602 // "nice" means that the buffer is exported to LaTeX format but not
603 // run through the LaTeX compiler.
604 string output_file = runparams.nice ?
605 params().filename.outputFilename(masterBuffer->filePath()) :
606 onlyFilename(temp_file.absFilename());
608 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
609 frontend::Alert::warning(_("Invalid filename"),
610 _("The following filename is likely to cause trouble "
611 "when running the exported file through LaTeX: ") +
612 from_utf8(output_file));
615 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
616 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
617 "latex" : "pdflatex";
619 // If the file is compressed and we have specified that it
620 // should not be uncompressed, then just return its name and
621 // let LaTeX do the rest!
622 if (params().filename.isZipped()) {
623 if (params().noUnzip) {
624 // We don't know whether latex can actually handle
625 // this file, but we can't check, because that would
626 // mean to unzip the file and thereby making the
627 // noUnzip parameter meaningless.
628 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
630 FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
631 if (runparams.nice) {
632 runparams.exportdata->addExternalFile(tex_format,
634 changeExtension(output_file, "bb"));
636 // LaTeX needs the bounding box file in the
638 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
639 boost::tie(status, bb_file) =
640 copyFileIfNeeded(bb_orig_file, bb_file);
641 if (status == FAILURE)
643 runparams.exportdata->addExternalFile(tex_format,
646 runparams.exportdata->addExternalFile(tex_format,
647 source_file, output_file);
648 runparams.exportdata->addExternalFile("dvi",
649 source_file, output_file);
650 // We can't strip the extension, because we don't know
651 // the unzipped file format
652 return latex_path(output_file, EXCLUDE_EXTENSION);
655 FileName const unzipped_temp_file =
656 FileName(unzippedFileName(temp_file.absFilename()));
657 output_file = unzippedFileName(output_file);
658 source_file = FileName(unzippedFileName(source_file.absFilename()));
659 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
660 // temp_file has been unzipped already and
661 // orig_file has not changed in the meantime.
662 temp_file = unzipped_temp_file;
663 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
665 // unzipped_temp_file does not exist or is too old
666 temp_file = unzipFile(temp_file);
667 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
671 string const from = formats.getFormatFromFile(temp_file);
673 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
675 string const to = findTargetFormat(from, runparams);
676 string const ext = formats.extension(to);
677 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
679 // We're going to be running the exported buffer through the LaTeX
680 // compiler, so must ensure that LaTeX can cope with the graphics
683 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
686 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
687 // The LaTeX compiler will not be able to determine
688 // the file format from the extension, so we must
690 FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
691 if (rename(temp_file, new_file)) {
692 temp_file = new_file;
693 output_file = changeExtension(output_file, ext);
694 source_file = FileName(changeExtension(source_file.absFilename(), ext));
696 LYXERR(Debug::GRAPHICS, "Could not rename file `"
697 << temp_file << "' to `" << new_file << "'.");
700 // The extension of temp_file might be != ext!
701 runparams.exportdata->addExternalFile(tex_format, source_file,
703 runparams.exportdata->addExternalFile("dvi", source_file,
705 return stripExtensionIfPossible(output_file, to, runparams.nice);
708 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
709 string const output_to_file = changeExtension(output_file, ext);
711 // Do we need to perform the conversion?
712 // Yes if to_file does not exist or if temp_file is newer than to_file
713 if (compare_timestamps(temp_file, to_file) < 0) {
715 LYXERR(Debug::GRAPHICS,
716 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
717 from_utf8(rel_file))));
718 runparams.exportdata->addExternalFile(tex_format, to_file,
720 runparams.exportdata->addExternalFile("dvi", to_file,
722 return stripExtensionIfPossible(output_to_file, runparams.nice);
725 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
726 << "\tA copy has been made and convert is to be called with:\n"
727 << "\tfile to convert = " << temp_file << '\n'
728 << "\t from " << from << " to " << to);
730 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
732 if (theConverters().convert(&buf, temp_file, to_file, params().filename,
734 Converters::try_default | Converters::try_cache)) {
735 runparams.exportdata->addExternalFile(tex_format,
736 to_file, output_to_file);
737 runparams.exportdata->addExternalFile("dvi",
738 to_file, output_to_file);
741 return stripExtensionIfPossible(output_to_file, runparams.nice);
745 int InsetGraphics::latex(Buffer const & buf, odocstream & os,
746 OutputParams const & runparams) const
748 // If there is no file specified or not existing,
749 // just output a message about it in the latex output.
750 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
751 << params().filename.absFilename());
753 string const relative_file =
754 params().filename.relFilename(buf.filePath());
756 bool const file_exists = !params().filename.empty()
757 && params().filename.isReadableFile();
758 string const message = file_exists ?
759 string() : string("bb = 0 0 200 100, draft, type=eps");
760 // if !message.empty() then there was no existing file
761 // "filename" found. In this case LaTeX
762 // draws only a rectangle with the above bb and the
763 // not found filename in it.
764 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
766 // These variables collect all the latex code that should be before and
767 // after the actual includegraphics command.
770 // Do we want subcaptions?
771 if (params().subcaption) {
772 if (runparams.moving_arg)
773 before += "\\protect";
774 before += "\\subfigure[" + params().subcaptionText + "]{";
778 if (runparams.moving_arg)
779 before += "\\protect";
781 // We never use the starred form, we use the "clip" option instead.
782 before += "\\includegraphics";
784 // Write the options if there are any.
785 string const opts = createLatexOptions();
786 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
788 if (!opts.empty() && !message.empty())
789 before += ('[' + opts + ',' + message + ']');
790 else if (!opts.empty() || !message.empty())
791 before += ('[' + opts + message + ']');
793 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
795 string latex_str = before + '{';
796 // Convert the file if necessary.
797 // Remove the extension so LaTeX will use whatever is appropriate
798 // (when there are several versions in different formats)
799 latex_str += prepareFile(buf, runparams);
800 latex_str += '}' + after;
802 os << from_utf8(latex_str);
804 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
805 // Return how many newlines we issued.
806 return int(count(latex_str.begin(), latex_str.end(),'\n'));
810 int InsetGraphics::plaintext(Buffer const & buf, odocstream & os,
811 OutputParams const &) const
813 // No graphics in ascii output. Possible to use gifscii to convert
814 // images to ascii approximation.
815 // 1. Convert file to ascii using gifscii
816 // 2. Read ascii output file and add it to the output stream.
817 // at least we send the filename
819 // FIXME: We have no idea what the encoding of the filename is
821 docstring const str = bformat(buf.B_("Graphics file: %1$s"),
822 from_utf8(params().filename.absFilename()));
823 os << '<' << str << '>';
825 return 2 + str.size();
829 static int writeImageObject(char const * format, odocstream & os,
830 OutputParams const & runparams, docstring const & graphic_label,
831 docstring const & attributes)
833 if (runparams.flavor != OutputParams::XML)
834 os << "<![ %output.print." << format
837 os <<"<imageobject><imagedata fileref=\"&"
844 if (runparams.flavor == OutputParams::XML)
845 os << " role=\"" << format << "\"/>" ;
847 os << " format=\"" << format << "\">" ;
849 os << "</imageobject>";
851 if (runparams.flavor != OutputParams::XML)
852 os << endl << "]]>" ;
854 return runparams.flavor == OutputParams::XML ? 0 : 2;
858 // For explanation on inserting graphics into DocBook checkout:
859 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
860 // See also the docbook guide at http://www.docbook.org/
861 int InsetGraphics::docbook(Buffer const &, odocstream & os,
862 OutputParams const & runparams) const
864 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
865 // need to switch to MediaObject. However, for now this is sufficient and
867 if (runparams.flavor == OutputParams::XML)
868 runparams.exportdata->addExternalFile("docbook-xml",
871 runparams.exportdata->addExternalFile("docbook",
874 os << "<inlinemediaobject>";
877 docstring attributes = createDocBookAttributes();
878 r += writeImageObject("png", os, runparams, graphic_label, attributes);
879 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
880 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
881 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
883 os << "</inlinemediaobject>";
888 void InsetGraphics::validate(LaTeXFeatures & features) const
890 // If we have no image, we should not require anything.
891 if (params().filename.empty())
894 features.includeFile(graphic_label,
895 removeExtension(params().filename.absFilename()));
897 features.require("graphicx");
899 if (features.runparams().nice) {
900 Buffer const * masterBuffer = features.buffer().masterBuffer();
901 string const rel_file = removeExtension(params().filename.relFilename(masterBuffer->filePath()));
902 if (contains(rel_file, "."))
903 features.require("lyxdot");
906 if (params().subcaption)
907 features.require("subfigure");
911 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
913 // If nothing is changed, just return and say so.
914 if (params() == p && !p.filename.empty())
917 // Copy the new parameters.
920 // Update the display using the new parameters.
921 graphic_->update(params().as_grfxParams());
923 // We have changed data, report it.
928 InsetGraphicsParams const & InsetGraphics::params() const
934 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
935 Buffer const & buffer) const
937 formats.edit(buffer, p.filename,
938 formats.getFormatFromFile(p.filename));
942 string const InsetGraphicsMailer::name_("graphics");
944 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
949 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
951 return params2string(inset_.params(), buffer);
955 void InsetGraphicsMailer::string2params(string const & in,
956 Buffer const & buffer,
957 InsetGraphicsParams & params)
959 params = InsetGraphicsParams();
963 istringstream data(in);
969 if (!lex || name != name_)
970 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
973 inset.readInsetGraphics(lex, buffer.filePath());
974 params = inset.params();
979 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
980 Buffer const & buffer)
983 data << name_ << ' ';
984 params.Write(data, buffer);
985 data << "\\end_inset\n";