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"
60 #include "DispatchResult.h"
61 #include "ErrorList.h"
64 #include "FuncRequest.h"
65 #include "FuncStatus.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/filetools.h"
80 #include "support/lyxlib.h" // sum
81 #include "support/lstrings.h"
82 #include "support/os.h"
83 #include "support/Systemcall.h"
85 #include <boost/bind.hpp>
86 #include <boost/tuple/tuple.hpp>
94 using support::bformat;
95 using support::changeExtension;
96 using support::compare_timestamps;
97 using support::contains;
98 using support::DocFileName;
99 using support::FileName;
100 using support::float_equal;
101 using support::getExtension;
102 using support::isFileReadable;
103 using support::isValidLaTeXFilename;
104 using support::latex_path;
105 using support::onlyFilename;
106 using support::removeExtension;
107 using support::rtrim;
108 using support::subst;
109 using support::suffixIs;
110 using support::Systemcall;
111 using support::unzipFile;
112 using support::unzippedFileName;
116 using std::istringstream;
118 using std::ostringstream;
123 /// Find the most suitable image format for images in \p format
124 /// Note that \p format may be unknown (i. e. an empty string)
125 string findTargetFormat(string const & format, OutputParams const & runparams)
127 // Are we using latex or pdflatex?
128 if (runparams.flavor == OutputParams::PDFLATEX) {
129 LYXERR(Debug::GRAPHICS) << "findTargetFormat: PDF mode" << endl;
130 Format const * const f = formats.getFormat(format);
131 // Convert vector graphics to pdf
132 if (f && f->vectorFormat())
134 // pdflatex can use jpeg, png and pdf directly
137 // Convert everything else to png
140 // If it's postscript, we always do eps.
141 LYXERR(Debug::GRAPHICS) << "findTargetFormat: PostScript mode" << endl;
143 // any other than ps is changed to eps
152 InsetGraphics::InsetGraphics()
153 : graphic_label(sgml::uniqueID(from_ascii("graph"))),
154 graphic_(new RenderGraphic(this))
158 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
160 boost::signals::trackable(),
161 graphic_label(sgml::uniqueID(from_ascii("graph"))),
162 graphic_(new RenderGraphic(*ig.graphic_, this))
164 setParams(ig.params());
168 Inset * InsetGraphics::clone() const
170 return new InsetGraphics(*this);
174 InsetGraphics::~InsetGraphics()
176 InsetGraphicsMailer(*this).hideDialog();
180 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
182 switch (cmd.action) {
183 case LFUN_GRAPHICS_EDIT: {
184 Buffer const & buffer = cur.bv().buffer();
185 InsetGraphicsParams p;
186 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer, p);
187 editGraphics(p, buffer);
191 case LFUN_INSET_MODIFY: {
192 Buffer const & buffer = cur.buffer();
193 InsetGraphicsParams p;
194 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer, p);
195 if (!p.filename.empty())
202 case LFUN_INSET_DIALOG_UPDATE:
203 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
206 case LFUN_MOUSE_RELEASE:
207 if (!cur.selection())
208 InsetGraphicsMailer(*this).showDialog(&cur.bv());
212 Inset::doDispatch(cur, cmd);
218 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
219 FuncStatus & flag) const
221 switch (cmd.action) {
222 case LFUN_GRAPHICS_EDIT:
223 case LFUN_INSET_MODIFY:
224 case LFUN_INSET_DIALOG_UPDATE:
229 return Inset::getStatus(cur, cmd, flag);
234 void InsetGraphics::registerEmbeddedFiles(Buffer const &,
235 EmbeddedFiles & files) const
237 files.registerFile(params().filename.absFilename(),
242 void InsetGraphics::updateEmbeddedFile(Buffer const & buf,
243 EmbeddedFile const & file)
245 BOOST_ASSERT(buf.embeddedFiles().enabled());
246 LYXERR(Debug::FILES) << "Update InsetGraphics file from "
247 << params_.filename.toFilesystemEncoding() << std::endl;
248 params_.filename.set(file.availableFile(&buf), buf.filePath());
249 LYXERR(Debug::FILES) << " to "
250 << params_.filename.toFilesystemEncoding() << std::endl;
251 // FIXME: graphics dialog is not updated even if the underlying
252 // filename is updated. What should I do?
256 void InsetGraphics::edit(Cursor & cur, bool)
258 InsetGraphicsMailer(*this).showDialog(&cur.bv());
262 bool InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
264 graphic_->metrics(mi, dim);
265 bool const changed = dim_ != dim;
271 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
273 setPosCache(pi, x, y);
274 graphic_->draw(pi, x, y);
278 Inset::EDITABLE InsetGraphics::editable() const
284 void InsetGraphics::write(Buffer const & buf, ostream & os) const
287 params().Write(os, buf);
291 void InsetGraphics::read(Buffer const & buf, Lexer & lex)
293 string const token = lex.getString();
295 if (token == "Graphics")
296 readInsetGraphics(lex, buf.filePath());
298 LYXERR(Debug::GRAPHICS) << "Not a Graphics inset!" << endl;
300 // InsetGraphics is read, with filename in params_. We do not know if this file actually
301 // exists or is embedded so we need to get the 'availableFile' from buf.embeddedFiles()
302 if (buf.embeddedFiles().enabled()) {
303 EmbeddedFiles::EmbeddedFileList::const_iterator it =
304 buf.embeddedFiles().find(params_.filename.toFilesystemEncoding());
305 if (it != buf.embeddedFiles().end())
306 // using available file, embedded or external, depending on file availability and
308 params_.filename = DocFileName(it->availableFile(&buf));
310 graphic_->update(params().as_grfxParams());
314 void InsetGraphics::readInsetGraphics(Lexer & lex, string const & bufpath)
316 bool finished = false;
318 while (lex.isOK() && !finished) {
321 string const token = lex.getString();
322 LYXERR(Debug::GRAPHICS) << "Token: '" << token << '\''
327 } else if (token == "\\end_inset") {
330 if (!params_.Read(lex, token, bufpath))
331 lyxerr << "Unknown token, " << token << ", skipping."
338 string const InsetGraphics::createLatexOptions() const
340 // Calculate the options part of the command, we must do it to a string
341 // stream since we might have a trailing comma that we would like to remove
342 // before writing it to the output stream.
343 ostringstream options;
344 if (!params().bb.empty())
345 options << "bb=" << rtrim(params().bb) << ',';
351 double const scl = convert<double>(params().scale);
352 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
353 if (!float_equal(scl, 100.0, 0.05))
354 size << "scale=" << scl / 100.0 << ',';
356 if (!params().width.zero())
357 size << "width=" << params().width.asLatexString() << ',';
358 if (!params().height.zero())
359 size << "height=" << params().height.asLatexString() << ',';
360 if (params().keepAspectRatio)
361 size << "keepaspectratio,";
363 if (params().scaleBeforeRotation && !size.str().empty())
364 options << size.str();
366 // Make sure rotation angle is not very close to zero;
367 // a float can be effectively zero but not exactly zero.
368 if (!params().rotateAngle.empty()
369 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
370 options << "angle=" << params().rotateAngle << ',';
371 if (!params().rotateOrigin.empty()) {
372 options << "origin=" << params().rotateOrigin[0];
373 if (contains(params().rotateOrigin,"Top"))
375 else if (contains(params().rotateOrigin,"Bottom"))
377 else if (contains(params().rotateOrigin,"Baseline"))
382 if (!params().scaleBeforeRotation && !size.str().empty())
383 options << size.str();
385 if (!params().special.empty())
386 options << params().special << ',';
388 string opts = options.str();
390 if (suffixIs(opts, ','))
391 opts = opts.substr(0, opts.size() - 1);
397 docstring const InsetGraphics::toDocbookLength(Length const & len) const
399 odocstringstream result;
400 switch (len.unit()) {
401 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
402 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
404 case Length::PT: // Point = 1/72.27in = 0.351mm
405 result << len.value() * 72 / 72.27 << "pt";
407 case Length::BP: // Big point (72bp = 1in), also PostScript point
408 result << len.value() << "pt";
410 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
411 result << len.value() * 0.376 << "mm";
413 case Length::MM: // Millimeter = 2.845pt
414 result << len.value() << "mm";
416 case Length::PC: // Pica = 12pt = 4.218mm
417 result << len.value() << "pc";
419 case Length::CC: // Cicero = 12dd = 4.531mm
420 result << len.value() * 4.531 << "mm";
422 case Length::CM: // Centimeter = 10mm = 2.371pc
423 result << len.value() << "cm";
425 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
426 result << len.value() << "in";
428 case Length::EX: // Height of a small "x" for the current font.
429 // Obviously we have to compromise here. Any better ratio than 1.5 ?
430 result << len.value() / 1.5 << "em";
432 case Length::EM: // Width of capital "M" in current font.
433 result << len.value() << "em";
435 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
436 result << len.value() * 18 << "em";
438 case Length::PTW: // Percent of TextWidth
439 case Length::PCW: // Percent of ColumnWidth
440 case Length::PPW: // Percent of PageWidth
441 case Length::PLW: // Percent of LineWidth
442 case Length::PTH: // Percent of TextHeight
443 case Length::PPH: // Percent of Paper
444 // Sigh, this will go wrong.
445 result << len.value() << "%";
448 result << len.asDocstring();
454 docstring const InsetGraphics::createDocBookAttributes() const
456 // Calculate the options part of the command, we must do it to a string
457 // stream since we copied the code from createLatexParams() ;-)
459 // FIXME: av: need to translate spec -> Docbook XSL spec (http://www.sagehill.net/docbookxsl/ImageSizing.html)
460 // Right now it only works with my version of db2latex :-)
462 odocstringstream options;
463 double const scl = convert<double>(params().scale);
464 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
465 if (!float_equal(scl, 100.0, 0.05))
466 options << " scale=\""
467 << static_cast<int>( (scl) + 0.5 )
470 if (!params().width.zero()) {
471 options << " width=\"" << toDocbookLength(params().width) << "\" ";
473 if (!params().height.zero()) {
474 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
476 if (params().keepAspectRatio) {
477 // This will be irrelevant unless both width and height are set
478 options << "scalefit=\"1\" ";
483 if (!params().special.empty())
484 options << from_ascii(params().special) << " ";
486 // trailing blanks are ok ...
487 return options.str();
501 std::pair<CopyStatus, FileName> const
502 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
504 unsigned long const checksum_in = support::sum(file_in);
505 unsigned long const checksum_out = support::sum(file_out);
507 if (checksum_in == checksum_out)
509 return std::make_pair(IDENTICAL_CONTENTS, file_out);
511 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
512 bool const success = mover.copy(file_in, file_out);
515 LYXERR(Debug::GRAPHICS)
516 << to_utf8(support::bformat(_("Could not copy the file\n%1$s\n"
517 "into the temporary directory."),
518 from_utf8(file_in.absFilename())))
522 CopyStatus status = success ? SUCCESS : FAILURE;
523 return std::make_pair(status, file_out);
527 std::pair<CopyStatus, FileName> const
528 copyToDirIfNeeded(DocFileName const & file, string const & dir)
530 using support::rtrim;
532 string const file_in = file.absFilename();
533 string const only_path = support::onlyPath(file_in);
534 if (rtrim(support::onlyPath(file_in) , "/") == rtrim(dir, "/"))
535 return std::make_pair(IDENTICAL_PATHS, file_in);
537 string mangled = file.mangledFilename();
538 if (file.isZipped()) {
539 // We need to change _eps.gz to .eps.gz. The mangled name is
540 // still unique because of the counter in mangledFilename().
541 // We can't just call mangledFilename() with the zip
542 // extension removed, because base.eps and base.eps.gz may
543 // have different content but would get the same mangled
544 // name in this case.
545 string const base = removeExtension(file.unzippedFilename());
546 string::size_type const ext_len = file_in.length() - base.length();
547 mangled[mangled.length() - ext_len] = '.';
549 FileName const file_out(support::makeAbsPath(mangled, dir));
551 return copyFileIfNeeded(file, file_out);
555 string const stripExtensionIfPossible(string const & file, bool nice)
557 // Remove the extension so the LaTeX compiler will use whatever
558 // is appropriate (when there are several versions in different
560 // Do this only if we are not exporting for internal usage, because
561 // pdflatex prefers png over pdf and it would pick up the png images
562 // that we generate for preview.
563 // This works only if the filename contains no dots besides
564 // the just removed one. We can fool here by replacing all
565 // dots with a macro whose definition is just a dot ;-)
566 // The automatic format selection does not work if the file
568 string const latex_name = latex_path(file,
569 support::EXCLUDE_EXTENSION);
570 if (!nice || contains(latex_name, '"'))
572 return latex_path(removeExtension(file),
573 support::PROTECT_EXTENSION,
574 support::ESCAPE_DOTS);
578 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
580 // No conversion is needed. LaTeX can handle the graphic file as is.
581 // This is true even if the orig_file is compressed.
582 string const to_format = formats.getFormat(to)->extension();
583 string const file_format = getExtension(file);
584 // for latex .ps == .eps
585 if (to_format == file_format ||
586 (to_format == "eps" && file_format == "ps") ||
587 (to_format == "ps" && file_format == "eps"))
588 return stripExtensionIfPossible(file, nice);
589 return latex_path(file, support::EXCLUDE_EXTENSION);
595 string const InsetGraphics::prepareFile(Buffer const & buf,
596 OutputParams const & runparams) const
598 // The following code depends on non-empty filenames
599 if (params().filename.empty())
602 string const orig_file = params().filename.absFilename();
603 string const rel_file = params().filename.relFilename(buf.filePath());
605 // previewing source code, no file copying or file format conversion
606 if (runparams.dryrun)
607 return stripExtensionIfPossible(rel_file, runparams.nice);
609 // temp_file will contain the file for LaTeX to act on if, for example,
610 // we move it to a temp dir or uncompress it.
611 FileName temp_file = params().filename;
613 // The master buffer. This is useful when there are multiple levels
615 Buffer const * m_buffer = buf.getMasterBuffer();
617 // Return the output name if we are inside a comment or the file does
619 // We are not going to change the extension or using the name of the
620 // temporary file, the code is already complicated enough.
621 if (runparams.inComment || !isFileReadable(params().filename))
622 return params().filename.outputFilename(m_buffer->filePath());
624 // We place all temporary files in the master buffer's temp dir.
625 // This is possible because we use mangled file names.
626 // This is necessary for DVI export.
627 string const temp_path = m_buffer->temppath();
630 boost::tie(status, temp_file) =
631 copyToDirIfNeeded(params().filename, temp_path);
633 if (status == FAILURE)
636 // a relative filename should be relative to the master
638 // "nice" means that the buffer is exported to LaTeX format but not
639 // run through the LaTeX compiler.
640 string output_file = support::os::external_path(runparams.nice ?
641 params().filename.outputFilename(m_buffer->filePath()) :
642 onlyFilename(temp_file.absFilename()));
644 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
645 frontend::Alert::warning(_("Invalid filename"),
646 _("The following filename is likely to cause trouble "
647 "when running the exported file through LaTeX: ") +
648 from_utf8(output_file));
651 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
652 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
653 "latex" : "pdflatex";
655 // If the file is compressed and we have specified that it
656 // should not be uncompressed, then just return its name and
657 // let LaTeX do the rest!
658 if (params().filename.isZipped()) {
659 if (params().noUnzip) {
660 // We don't know whether latex can actually handle
661 // this file, but we can't check, because that would
662 // mean to unzip the file and thereby making the
663 // noUnzip parameter meaningless.
664 LYXERR(Debug::GRAPHICS)
665 << "\tpass zipped file to LaTeX.\n";
667 FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
668 if (runparams.nice) {
669 runparams.exportdata->addExternalFile(tex_format,
671 changeExtension(output_file, "bb"));
673 // LaTeX needs the bounding box file in the
675 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
676 boost::tie(status, bb_file) =
677 copyFileIfNeeded(bb_orig_file, bb_file);
678 if (status == FAILURE)
680 runparams.exportdata->addExternalFile(tex_format,
683 runparams.exportdata->addExternalFile(tex_format,
684 source_file, output_file);
685 runparams.exportdata->addExternalFile("dvi",
686 source_file, output_file);
687 // We can't strip the extension, because we don't know
688 // the unzipped file format
689 return latex_path(output_file,
690 support::EXCLUDE_EXTENSION);
693 FileName const unzipped_temp_file =
694 FileName(unzippedFileName(temp_file.absFilename()));
695 output_file = unzippedFileName(output_file);
696 source_file = FileName(unzippedFileName(source_file.absFilename()));
697 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
698 // temp_file has been unzipped already and
699 // orig_file has not changed in the meantime.
700 temp_file = unzipped_temp_file;
701 LYXERR(Debug::GRAPHICS)
702 << "\twas already unzipped to " << temp_file
705 // unzipped_temp_file does not exist or is too old
706 temp_file = unzipFile(temp_file);
707 LYXERR(Debug::GRAPHICS)
708 << "\tunzipped to " << temp_file << endl;
712 string const from = formats.getFormatFromFile(temp_file);
714 LYXERR(Debug::GRAPHICS)
715 << "\tCould not get file format." << endl;
717 string const to = findTargetFormat(from, runparams);
718 string const ext = formats.extension(to);
719 LYXERR(Debug::GRAPHICS)
720 << "\t we have: from " << from << " to " << to << '\n';
722 // We're going to be running the exported buffer through the LaTeX
723 // compiler, so must ensure that LaTeX can cope with the graphics
726 LYXERR(Debug::GRAPHICS)
727 << "\tthe orig file is: " << orig_file << endl;
730 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
731 // The LaTeX compiler will not be able to determine
732 // the file format from the extension, so we must
734 FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
735 if (support::rename(temp_file, new_file)) {
736 temp_file = new_file;
737 output_file = changeExtension(output_file, ext);
738 source_file = FileName(changeExtension(source_file.absFilename(), ext));
740 LYXERR(Debug::GRAPHICS)
741 << "Could not rename file `"
742 << temp_file << "' to `" << new_file
745 // The extension of temp_file might be != ext!
746 runparams.exportdata->addExternalFile(tex_format, source_file,
748 runparams.exportdata->addExternalFile("dvi", source_file,
750 return stripExtensionIfPossible(output_file, to, runparams.nice);
753 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
754 string const output_to_file = changeExtension(output_file, ext);
756 // Do we need to perform the conversion?
757 // Yes if to_file does not exist or if temp_file is newer than to_file
758 if (compare_timestamps(temp_file, to_file) < 0) {
760 LYXERR(Debug::GRAPHICS)
761 << to_utf8(bformat(_("No conversion of %1$s is needed after all"),
762 from_utf8(rel_file)))
764 runparams.exportdata->addExternalFile(tex_format, to_file,
766 runparams.exportdata->addExternalFile("dvi", to_file,
768 return stripExtensionIfPossible(output_to_file, runparams.nice);
771 LYXERR(Debug::GRAPHICS)
772 << "\tThe original file is " << orig_file << "\n"
773 << "\tA copy has been made and convert is to be called with:\n"
774 << "\tfile to convert = " << temp_file << '\n'
775 << "\t from " << from << " to " << to << '\n';
777 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
779 if (theConverters().convert(&buf, temp_file, to_file, params().filename,
781 Converters::try_default | Converters::try_cache)) {
782 runparams.exportdata->addExternalFile(tex_format,
783 to_file, output_to_file);
784 runparams.exportdata->addExternalFile("dvi",
785 to_file, output_to_file);
788 return stripExtensionIfPossible(output_to_file, runparams.nice);
792 int InsetGraphics::latex(Buffer const & buf, odocstream & os,
793 OutputParams const & runparams) const
795 // If there is no file specified or not existing,
796 // just output a message about it in the latex output.
797 LYXERR(Debug::GRAPHICS)
798 << "insetgraphics::latex: Filename = "
799 << params().filename.absFilename() << endl;
801 string const relative_file =
802 params().filename.relFilename(buf.filePath());
804 bool const file_exists = !params().filename.empty() &&
805 isFileReadable(params().filename);
806 string const message = file_exists ?
807 string() : string("bb = 0 0 200 100, draft, type=eps");
808 // if !message.empty() then there was no existing file
809 // "filename" found. In this case LaTeX
810 // draws only a rectangle with the above bb and the
811 // not found filename in it.
812 LYXERR(Debug::GRAPHICS)
813 << "\tMessage = \"" << message << '\"' << endl;
815 // These variables collect all the latex code that should be before and
816 // after the actual includegraphics command.
819 // Do we want subcaptions?
820 if (params().subcaption) {
821 if (runparams.moving_arg)
822 before += "\\protect";
823 before += "\\subfigure[" + params().subcaptionText + "]{";
827 if (runparams.moving_arg)
828 before += "\\protect";
830 // We never use the starred form, we use the "clip" option instead.
831 before += "\\includegraphics";
833 // Write the options if there are any.
834 string const opts = createLatexOptions();
835 LYXERR(Debug::GRAPHICS) << "\tOpts = " << opts << endl;
837 if (!opts.empty() && !message.empty())
838 before += ('[' + opts + ',' + message + ']');
839 else if (!opts.empty() || !message.empty())
840 before += ('[' + opts + message + ']');
842 LYXERR(Debug::GRAPHICS)
843 << "\tBefore = " << before
844 << "\n\tafter = " << after << endl;
846 string latex_str = before + '{';
847 // Convert the file if necessary.
848 // Remove the extension so LaTeX will use whatever is appropriate
849 // (when there are several versions in different formats)
850 latex_str += prepareFile(buf, runparams);
851 latex_str += '}' + after;
853 os << from_utf8(latex_str);
855 LYXERR(Debug::GRAPHICS) << "InsetGraphics::latex outputting:\n"
856 << latex_str << endl;
857 // Return how many newlines we issued.
858 return int(std::count(latex_str.begin(), latex_str.end(),'\n'));
862 int InsetGraphics::plaintext(Buffer const & buf, odocstream & os,
863 OutputParams const &) const
865 // No graphics in ascii output. Possible to use gifscii to convert
866 // images to ascii approximation.
867 // 1. Convert file to ascii using gifscii
868 // 2. Read ascii output file and add it to the output stream.
869 // at least we send the filename
871 // FIXME: We have no idea what the encoding of the filename is
873 docstring const str = bformat(buf.B_("Graphics file: %1$s"),
874 from_utf8(params().filename.absFilename()));
875 os << '<' << str << '>';
877 return 2 + str.size();
883 int writeImageObject(char const * format,
885 OutputParams const & runparams,
886 docstring const & graphic_label,
887 docstring const & attributes)
889 if (runparams.flavor != OutputParams::XML) {
890 os << "<![ %output.print."
895 os <<"<imageobject><imagedata fileref=\"&"
901 if (runparams.flavor == OutputParams::XML) {
902 os << " role=\"" << format << "\"/>" ;
905 os << " format=\"" << format << "\">" ;
907 os << "</imageobject>";
908 if (runparams.flavor != OutputParams::XML) {
909 os << std::endl << "]]>" ;
911 return runparams.flavor == OutputParams::XML ? 0 : 2;
913 // end anonymous namespace
917 // For explanation on inserting graphics into DocBook checkout:
918 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
919 // See also the docbook guide at http://www.docbook.org/
920 int InsetGraphics::docbook(Buffer const &, odocstream & os,
921 OutputParams const & runparams) const
923 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
924 // need to switch to MediaObject. However, for now this is sufficient and
926 if (runparams.flavor == OutputParams::XML) {
927 runparams.exportdata->addExternalFile("docbook-xml",
930 runparams.exportdata->addExternalFile("docbook",
933 os << "<inlinemediaobject>";
936 docstring attributes = createDocBookAttributes();
937 r += writeImageObject("png", os, runparams, graphic_label, attributes);
938 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
939 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
940 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
942 os << "</inlinemediaobject>";
947 void InsetGraphics::validate(LaTeXFeatures & features) const
949 // If we have no image, we should not require anything.
950 if (params().filename.empty())
953 features.includeFile(graphic_label,
954 removeExtension(params().filename.absFilename()));
956 features.require("graphicx");
958 if (features.runparams().nice) {
959 Buffer const * m_buffer = features.buffer().getMasterBuffer();
960 string const rel_file = removeExtension(params().filename.relFilename(m_buffer->filePath()));
961 if (contains(rel_file, "."))
962 features.require("lyxdot");
965 if (params().subcaption)
966 features.require("subfigure");
970 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
972 // If nothing is changed, just return and say so.
973 if (params() == p && !p.filename.empty())
976 // Copy the new parameters.
979 // Update the display using the new parameters.
980 graphic_->update(params().as_grfxParams());
982 // We have changed data, report it.
987 InsetGraphicsParams const & InsetGraphics::params() const
993 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
994 Buffer const & buffer) const
996 formats.edit(buffer, p.filename,
997 formats.getFormatFromFile(p.filename));
1001 string const InsetGraphicsMailer::name_("graphics");
1003 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
1008 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
1010 return params2string(inset_.params(), buffer);
1014 void InsetGraphicsMailer::string2params(string const & in,
1015 Buffer const & buffer,
1016 InsetGraphicsParams & params)
1018 params = InsetGraphicsParams();
1022 istringstream data(in);
1024 lex.setStream(data);
1028 if (!lex || name != name_)
1029 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
1031 InsetGraphics inset;
1032 inset.readInsetGraphics(lex, buffer.filePath());
1033 params = inset.params();
1038 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
1039 Buffer const & buffer)
1042 data << name_ << ' ';
1043 params.Write(data, buffer);
1044 data << "\\end_inset\n";