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 * When loading, if the image is not found in the expected place, try
19 to find it in the clipart, or in the same directory with the image.
20 * The image choosing dialog could show thumbnails of the image formats
21 it knows of, thus selection based on the image instead of based on
23 * Add support for the 'picins' package.
24 * Add support for the 'picinpar' package.
29 * The filename is kept in the lyx file in a relative way, so as to allow
30 * moving the document file and its images with no problem.
34 * Postscript output means EPS figures.
36 * PDF output is best done with PDF figures if it's a direct conversion
37 * or PNG figures otherwise.
49 #include "insets/InsetGraphics.h"
50 #include "insets/RenderGraphic.h"
53 #include "BufferView.h"
54 #include "Converter.h"
56 #include "DispatchResult.h"
57 #include "ErrorList.h"
60 #include "FuncRequest.h"
61 #include "FuncStatus.h"
62 #include "InsetIterator.h"
63 #include "LaTeXFeatures.h"
66 #include "MetricsInfo.h"
68 #include "OutputParams.h"
70 #include "TocBackend.h"
72 #include "frontends/alert.h"
73 #include "frontends/Application.h"
75 #include "support/convert.h"
76 #include "support/debug.h"
77 #include "support/docstream.h"
78 #include "support/ExceptionMessage.h"
79 #include "support/filetools.h"
80 #include "support/gettext.h"
81 #include "support/lyxlib.h"
82 #include "support/lstrings.h"
83 #include "support/os.h"
84 #include "support/Systemcall.h"
86 #include <boost/tuple/tuple.hpp>
92 using namespace lyx::support;
96 namespace Alert = frontend::Alert;
100 /// Find the most suitable image format for images in \p format
101 /// Note that \p format may be unknown (i. e. an empty string)
102 string findTargetFormat(string const & format, OutputParams const & runparams)
104 // Are we using latex or pdflatex?
105 if (runparams.flavor == OutputParams::PDFLATEX) {
106 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
107 Format const * const f = formats.getFormat(format);
108 // Convert vector graphics to pdf
109 if (f && f->vectorFormat())
111 // pdflatex can use jpeg, png and pdf directly
114 // Convert everything else to png
117 // If it's postscript, we always do eps.
118 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
120 // any other than ps is changed to eps
127 void readInsetGraphics(Lexer & lex, string const & bufpath,
128 InsetGraphicsParams & params)
130 bool finished = false;
132 while (lex.isOK() && !finished) {
135 string const token = lex.getString();
136 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
141 if (token == "\\end_inset") {
144 if (!params.Read(lex, token, bufpath))
145 lyxerr << "Unknown token, "
156 InsetGraphics::InsetGraphics(Buffer & buf)
157 : graphic_label(sgml::uniqueID(from_ascii("graph"))),
158 graphic_(new RenderGraphic(this))
160 Inset::setBuffer(buf);
164 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
166 graphic_label(sgml::uniqueID(from_ascii("graph"))),
167 graphic_(new RenderGraphic(*ig.graphic_, this))
169 setParams(ig.params());
173 Inset * InsetGraphics::clone() const
175 return new InsetGraphics(*this);
179 InsetGraphics::~InsetGraphics()
181 hideDialogs("graphics", this);
186 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
188 switch (cmd.action) {
189 case LFUN_INSET_EDIT: {
190 InsetGraphicsParams p = params();
191 if (!cmd.argument().empty())
192 string2params(to_utf8(cmd.argument()), buffer(), p);
193 editGraphics(p, buffer());
197 case LFUN_INSET_MODIFY: {
198 InsetGraphicsParams p;
199 string2params(to_utf8(cmd.argument()), buffer(), p);
200 if (p.filename.empty()) {
206 // if the inset is part of a graphics group, all the
207 // other members should be updated too.
208 if (!params_.groupId.empty())
209 graphics::unifyGraphicsGroups(cur.buffer(),
210 to_utf8(cmd.argument()));
214 case LFUN_INSET_DIALOG_UPDATE:
215 cur.bv().updateDialog("graphics", params2string(params(),
219 case LFUN_MOUSE_RELEASE:
220 if (!cur.selection() && cmd.button() == mouse_button::button1)
221 cur.bv().showDialog("graphics", params2string(params(),
222 cur.bv().buffer()), this);
226 Inset::doDispatch(cur, cmd);
232 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
233 FuncStatus & flag) const
235 switch (cmd.action) {
236 case LFUN_INSET_EDIT:
237 case LFUN_INSET_MODIFY:
238 case LFUN_INSET_DIALOG_UPDATE:
239 flag.setEnabled(true);
243 return Inset::getStatus(cur, cmd, flag);
248 void InsetGraphics::edit(Cursor & cur, bool, EntryDirection)
250 cur.bv().showDialog("graphics", params2string(params(),
251 cur.bv().buffer()), this);
255 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
257 graphic_->metrics(mi, dim);
261 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
263 graphic_->draw(pi, x, y);
267 Inset::EDITABLE InsetGraphics::editable() const
273 void InsetGraphics::write(ostream & os) const
276 params().Write(os, buffer());
280 void InsetGraphics::read(Lexer & lex)
282 lex.setContext("InsetGraphics::read");
284 readInsetGraphics(lex, buffer().filePath(), params_);
285 graphic_->update(params().as_grfxParams());
289 string InsetGraphics::createLatexOptions() const
291 // Calculate the options part of the command, we must do it to a string
292 // stream since we might have a trailing comma that we would like to remove
293 // before writing it to the output stream.
294 ostringstream options;
295 if (!params().bb.empty())
296 options << "bb=" << rtrim(params().bb) << ',';
302 double const scl = convert<double>(params().scale);
303 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
304 if (!float_equal(scl, 100.0, 0.05))
305 size << "scale=" << scl / 100.0 << ',';
307 if (!params().width.zero())
308 size << "width=" << params().width.asLatexString() << ',';
309 if (!params().height.zero())
310 size << "height=" << params().height.asLatexString() << ',';
311 if (params().keepAspectRatio)
312 size << "keepaspectratio,";
314 if (params().scaleBeforeRotation && !size.str().empty())
315 options << size.str();
317 // Make sure rotation angle is not very close to zero;
318 // a float can be effectively zero but not exactly zero.
319 if (!params().rotateAngle.empty()
320 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
321 options << "angle=" << params().rotateAngle << ',';
322 if (!params().rotateOrigin.empty()) {
323 options << "origin=" << params().rotateOrigin[0];
324 if (contains(params().rotateOrigin,"Top"))
326 else if (contains(params().rotateOrigin,"Bottom"))
328 else if (contains(params().rotateOrigin,"Baseline"))
333 if (!params().scaleBeforeRotation && !size.str().empty())
334 options << size.str();
336 if (!params().special.empty())
337 options << params().special << ',';
339 string opts = options.str();
341 if (suffixIs(opts, ','))
342 opts = opts.substr(0, opts.size() - 1);
348 docstring InsetGraphics::toDocbookLength(Length const & len) const
350 odocstringstream result;
351 switch (len.unit()) {
352 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
353 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
355 case Length::PT: // Point = 1/72.27in = 0.351mm
356 result << len.value() * 72 / 72.27 << "pt";
358 case Length::BP: // Big point (72bp = 1in), also PostScript point
359 result << len.value() << "pt";
361 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
362 result << len.value() * 0.376 << "mm";
364 case Length::MM: // Millimeter = 2.845pt
365 result << len.value() << "mm";
367 case Length::PC: // Pica = 12pt = 4.218mm
368 result << len.value() << "pc";
370 case Length::CC: // Cicero = 12dd = 4.531mm
371 result << len.value() * 4.531 << "mm";
373 case Length::CM: // Centimeter = 10mm = 2.371pc
374 result << len.value() << "cm";
376 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
377 result << len.value() << "in";
379 case Length::EX: // Height of a small "x" for the current font.
380 // Obviously we have to compromise here. Any better ratio than 1.5 ?
381 result << len.value() / 1.5 << "em";
383 case Length::EM: // Width of capital "M" in current font.
384 result << len.value() << "em";
386 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
387 result << len.value() * 18 << "em";
389 case Length::PTW: // Percent of TextWidth
390 case Length::PCW: // Percent of ColumnWidth
391 case Length::PPW: // Percent of PageWidth
392 case Length::PLW: // Percent of LineWidth
393 case Length::PTH: // Percent of TextHeight
394 case Length::PPH: // Percent of Paper
395 // Sigh, this will go wrong.
396 result << len.value() << "%";
399 result << len.asDocstring();
406 docstring InsetGraphics::createDocBookAttributes() const
408 // Calculate the options part of the command, we must do it to a string
409 // stream since we copied the code from createLatexParams() ;-)
411 // FIXME: av: need to translate spec -> Docbook XSL spec
412 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
413 // Right now it only works with my version of db2latex :-)
415 odocstringstream options;
416 double const scl = convert<double>(params().scale);
417 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
418 if (!float_equal(scl, 100.0, 0.05))
419 options << " scale=\""
420 << static_cast<int>( (scl) + 0.5 )
423 if (!params().width.zero()) {
424 options << " width=\"" << toDocbookLength(params().width) << "\" ";
426 if (!params().height.zero()) {
427 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
429 if (params().keepAspectRatio) {
430 // This will be irrelevant unless both width and height are set
431 options << "scalefit=\"1\" ";
436 if (!params().special.empty())
437 options << from_ascii(params().special) << " ";
439 // trailing blanks are ok ...
440 return options.str();
446 enum GraphicsCopyStatus {
454 pair<GraphicsCopyStatus, FileName> const
455 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
457 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
458 unsigned long const checksum_in = file_in.checksum();
459 unsigned long const checksum_out = file_out.checksum();
461 if (checksum_in == checksum_out)
463 return make_pair(IDENTICAL_CONTENTS, file_out);
465 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
466 bool const success = mover.copy(file_in, file_out);
469 LYXERR(Debug::GRAPHICS,
470 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
471 "into the temporary directory."),
472 from_utf8(file_in.absFilename()))));
475 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
476 return make_pair(status, file_out);
480 pair<GraphicsCopyStatus, FileName> const
481 copyToDirIfNeeded(DocFileName const & file, string const & dir)
483 string const file_in = file.absFilename();
484 string const only_path = onlyPath(file_in);
485 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
486 return make_pair(IDENTICAL_PATHS, file_in);
488 string mangled = file.mangledFilename();
489 if (file.isZipped()) {
490 // We need to change _eps.gz to .eps.gz. The mangled name is
491 // still unique because of the counter in mangledFilename().
492 // We can't just call mangledFilename() with the zip
493 // extension removed, because base.eps and base.eps.gz may
494 // have different content but would get the same mangled
495 // name in this case.
496 string const base = removeExtension(file.unzippedFilename());
497 string::size_type const ext_len = file_in.length() - base.length();
498 mangled[mangled.length() - ext_len] = '.';
500 FileName const file_out(makeAbsPath(mangled, dir));
502 return copyFileIfNeeded(file, file_out);
506 string const stripExtensionIfPossible(string const & file, bool nice)
508 // Remove the extension so the LaTeX compiler will use whatever
509 // is appropriate (when there are several versions in different
511 // Do this only if we are not exporting for internal usage, because
512 // pdflatex prefers png over pdf and it would pick up the png images
513 // that we generate for preview.
514 // This works only if the filename contains no dots besides
515 // the just removed one. We can fool here by replacing all
516 // dots with a macro whose definition is just a dot ;-)
517 // The automatic format selection does not work if the file
519 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
520 if (!nice || contains(latex_name, '"'))
522 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
526 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
528 // No conversion is needed. LaTeX can handle the graphic file as is.
529 // This is true even if the orig_file is compressed.
530 string const to_format = formats.getFormat(to)->extension();
531 string const file_format = getExtension(file);
532 // for latex .ps == .eps
533 if (to_format == file_format ||
534 (to_format == "eps" && file_format == "ps") ||
535 (to_format == "ps" && file_format == "eps"))
536 return stripExtensionIfPossible(file, nice);
537 return latex_path(file, EXCLUDE_EXTENSION);
543 string InsetGraphics::prepareFile(OutputParams const & runparams) const
545 // The following code depends on non-empty filenames
546 if (params().filename.empty())
549 string const orig_file = params().filename.absFilename();
550 // this is for dryrun and display purposes, do not use latexFilename
551 string const rel_file = params().filename.relFilename(buffer().filePath());
553 // previewing source code, no file copying or file format conversion
554 if (runparams.dryrun)
555 return stripExtensionIfPossible(rel_file, runparams.nice);
557 // temp_file will contain the file for LaTeX to act on if, for example,
558 // we move it to a temp dir or uncompress it.
559 FileName temp_file = params().filename;
561 // The master buffer. This is useful when there are multiple levels
563 Buffer const * masterBuffer = buffer().masterBuffer();
565 // Return the output name if we are inside a comment or the file does
567 // We are not going to change the extension or using the name of the
568 // temporary file, the code is already complicated enough.
569 if (runparams.inComment || !params().filename.isReadableFile())
570 return params().filename.outputFilename(masterBuffer->filePath());
572 // We place all temporary files in the master buffer's temp dir.
573 // This is possible because we use mangled file names.
574 // This is necessary for DVI export.
575 string const temp_path = masterBuffer->temppath();
577 GraphicsCopyStatus status;
578 boost::tie(status, temp_file) =
579 copyToDirIfNeeded(params().filename, temp_path);
581 if (status == FAILURE)
584 // a relative filename should be relative to the master buffer.
585 // "nice" means that the buffer is exported to LaTeX format but not
586 // run through the LaTeX compiler.
587 string output_file = runparams.nice ?
588 params().filename.outputFilename(masterBuffer->filePath()) :
589 onlyFilename(temp_file.absFilename());
591 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
592 frontend::Alert::warning(_("Invalid filename"),
593 _("The following filename is likely to cause trouble "
594 "when running the exported file through LaTeX: ") +
595 from_utf8(output_file));
598 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
599 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
600 "latex" : "pdflatex";
602 // If the file is compressed and we have specified that it
603 // should not be uncompressed, then just return its name and
604 // let LaTeX do the rest!
605 if (params().filename.isZipped()) {
606 if (params().noUnzip) {
607 // We don't know whether latex can actually handle
608 // this file, but we can't check, because that would
609 // mean to unzip the file and thereby making the
610 // noUnzip parameter meaningless.
611 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
613 FileName const bb_orig_file =
614 FileName(changeExtension(orig_file, "bb"));
615 if (runparams.nice) {
616 runparams.exportdata->addExternalFile(tex_format,
618 changeExtension(output_file, "bb"));
620 // LaTeX needs the bounding box file in the
623 FileName(changeExtension(temp_file.absFilename(), "bb"));
624 boost::tie(status, bb_file) =
625 copyFileIfNeeded(bb_orig_file, bb_file);
626 if (status == FAILURE)
628 runparams.exportdata->addExternalFile(tex_format,
631 runparams.exportdata->addExternalFile(tex_format,
632 source_file, output_file);
633 runparams.exportdata->addExternalFile("dvi",
634 source_file, output_file);
635 // We can't strip the extension, because we don't know
636 // the unzipped file format
637 return latex_path(output_file, EXCLUDE_EXTENSION);
640 FileName const unzipped_temp_file =
641 FileName(unzippedFileName(temp_file.absFilename()));
642 output_file = unzippedFileName(output_file);
643 source_file = FileName(unzippedFileName(source_file.absFilename()));
644 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
645 // temp_file has been unzipped already and
646 // orig_file has not changed in the meantime.
647 temp_file = unzipped_temp_file;
648 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
650 // unzipped_temp_file does not exist or is too old
651 temp_file = unzipFile(temp_file);
652 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
656 string const from = formats.getFormatFromFile(temp_file);
658 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
660 string const to = findTargetFormat(from, runparams);
661 string const ext = formats.extension(to);
662 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
664 // We're going to be running the exported buffer through the LaTeX
665 // compiler, so must ensure that LaTeX can cope with the graphics
668 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
671 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
672 // The LaTeX compiler will not be able to determine
673 // the file format from the extension, so we must
675 FileName const new_file =
676 FileName(changeExtension(temp_file.absFilename(), ext));
677 if (temp_file.moveTo(new_file)) {
678 temp_file = new_file;
679 output_file = changeExtension(output_file, ext);
681 FileName(changeExtension(source_file.absFilename(), ext));
683 LYXERR(Debug::GRAPHICS, "Could not rename file `"
684 << temp_file << "' to `" << new_file << "'.");
687 // The extension of temp_file might be != ext!
688 runparams.exportdata->addExternalFile(tex_format, source_file,
690 runparams.exportdata->addExternalFile("dvi", source_file,
692 return stripExtensionIfPossible(output_file, to, runparams.nice);
695 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
696 string const output_to_file = changeExtension(output_file, ext);
698 // Do we need to perform the conversion?
699 // Yes if to_file does not exist or if temp_file is newer than to_file
700 if (compare_timestamps(temp_file, to_file) < 0) {
702 LYXERR(Debug::GRAPHICS,
703 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
704 from_utf8(rel_file))));
705 runparams.exportdata->addExternalFile(tex_format, to_file,
707 runparams.exportdata->addExternalFile("dvi", to_file,
709 return stripExtensionIfPossible(output_to_file, runparams.nice);
712 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
713 << "\tA copy has been made and convert is to be called with:\n"
714 << "\tfile to convert = " << temp_file << '\n'
715 << "\t from " << from << " to " << to);
717 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
719 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
721 Converters::try_default | Converters::try_cache)) {
722 runparams.exportdata->addExternalFile(tex_format,
723 to_file, output_to_file);
724 runparams.exportdata->addExternalFile("dvi",
725 to_file, output_to_file);
728 return stripExtensionIfPossible(output_to_file, runparams.nice);
732 int InsetGraphics::latex(odocstream & os,
733 OutputParams const & runparams) const
735 // If there is no file specified or not existing,
736 // just output a message about it in the latex output.
737 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
738 << params().filename.absFilename());
740 bool const file_exists = !params().filename.empty()
741 && params().filename.isReadableFile();
742 string const message = file_exists ?
743 string() : string("bb = 0 0 200 100, draft, type=eps");
744 // if !message.empty() then there was no existing file
745 // "filename" found. In this case LaTeX
746 // draws only a rectangle with the above bb and the
747 // not found filename in it.
748 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
750 // These variables collect all the latex code that should be before and
751 // after the actual includegraphics command.
755 if (runparams.moving_arg)
756 before += "\\protect";
758 // We never use the starred form, we use the "clip" option instead.
759 before += "\\includegraphics";
761 // Write the options if there are any.
762 string const opts = createLatexOptions();
763 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
765 if (!opts.empty() && !message.empty())
766 before += ('[' + opts + ',' + message + ']');
767 else if (!opts.empty() || !message.empty())
768 before += ('[' + opts + message + ']');
770 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
772 string latex_str = before + '{';
773 // Convert the file if necessary.
774 // Remove the extension so LaTeX will use whatever is appropriate
775 // (when there are several versions in different formats)
776 latex_str += prepareFile(runparams);
777 latex_str += '}' + after;
779 os << from_utf8(latex_str);
781 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
782 // Return how many newlines we issued.
783 return int(count(latex_str.begin(), latex_str.end(),'\n'));
787 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
789 // No graphics in ascii output. Possible to use gifscii to convert
790 // images to ascii approximation.
791 // 1. Convert file to ascii using gifscii
792 // 2. Read ascii output file and add it to the output stream.
793 // at least we send the filename
795 // FIXME: We have no idea what the encoding of the filename is
797 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
798 from_utf8(params().filename.absFilename()));
799 os << '<' << str << '>';
801 return 2 + str.size();
805 static int writeImageObject(char const * format, odocstream & os,
806 OutputParams const & runparams, docstring const & graphic_label,
807 docstring const & attributes)
809 if (runparams.flavor != OutputParams::XML)
810 os << "<![ %output.print." << format
813 os <<"<imageobject><imagedata fileref=\"&"
820 if (runparams.flavor == OutputParams::XML)
821 os << " role=\"" << format << "\"/>" ;
823 os << " format=\"" << format << "\">" ;
825 os << "</imageobject>";
827 if (runparams.flavor != OutputParams::XML)
828 os << endl << "]]>" ;
830 return runparams.flavor == OutputParams::XML ? 0 : 2;
834 // For explanation on inserting graphics into DocBook checkout:
835 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
836 // See also the docbook guide at http://www.docbook.org/
837 int InsetGraphics::docbook(odocstream & os,
838 OutputParams const & runparams) const
840 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
841 // need to switch to MediaObject. However, for now this is sufficient and
843 if (runparams.flavor == OutputParams::XML)
844 runparams.exportdata->addExternalFile("docbook-xml",
847 runparams.exportdata->addExternalFile("docbook",
850 os << "<inlinemediaobject>";
853 docstring attributes = createDocBookAttributes();
854 r += writeImageObject("png", os, runparams, graphic_label, attributes);
855 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
856 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
857 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
859 os << "</inlinemediaobject>";
864 void InsetGraphics::validate(LaTeXFeatures & features) const
866 // If we have no image, we should not require anything.
867 if (params().filename.empty())
870 features.includeFile(graphic_label,
871 removeExtension(params().filename.absFilename()));
873 features.require("graphicx");
875 if (features.runparams().nice) {
876 Buffer const * masterBuffer = features.buffer().masterBuffer();
877 string const rel_file = removeExtension(
878 params().filename.relFilename(masterBuffer->filePath()));
879 if (contains(rel_file, "."))
880 features.require("lyxdot");
885 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
887 // If nothing is changed, just return and say so.
888 if (params() == p && !p.filename.empty())
891 // Copy the new parameters.
894 // Update the display using the new parameters.
895 graphic_->update(params().as_grfxParams());
897 // We have changed data, report it.
902 InsetGraphicsParams const & InsetGraphics::params() const
908 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
909 Buffer const & buffer) const
911 formats.edit(buffer, p.filename,
912 formats.getFormatFromFile(p.filename));
916 void InsetGraphics::addToToc(DocIterator const & cpit)
918 TocBackend & backend = buffer().tocBackend();
921 docstring const str = from_utf8(params_.filename.onlyFileName());
922 backend.toc("graphics").push_back(TocItem(cpit, 0, str));
926 docstring InsetGraphics::contextMenu(BufferView const &, int, int) const
928 return from_ascii("context-graphics");
932 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
933 InsetGraphicsParams & params)
938 istringstream data(in);
941 lex.setContext("InsetGraphics::string2params");
943 params = InsetGraphicsParams();
944 readInsetGraphics(lex, buffer.filePath(), params);
948 string InsetGraphics::params2string(InsetGraphicsParams const & params,
949 Buffer const & buffer)
952 data << "graphics" << ' ';
953 params.Write(data, buffer);
954 data << "\\end_inset\n";
960 void getGraphicsGroups(Buffer const & b, set<string> & ids)
962 Inset & inset = b.inset();
963 InsetIterator it = inset_iterator_begin(inset);
964 InsetIterator const end = inset_iterator_end(inset);
965 for (; it != end; ++it)
966 if (it->lyxCode() == GRAPHICS_CODE) {
967 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
968 InsetGraphicsParams inspar = ins.getParams();
969 if (!inspar.groupId.empty())
970 ids.insert(inspar.groupId);
975 string getGroupParams(Buffer const & b, string const & groupId)
979 Inset & inset = b.inset();
980 InsetIterator it = inset_iterator_begin(inset);
981 InsetIterator const end = inset_iterator_end(inset);
982 for (; it != end; ++it)
983 if (it->lyxCode() == GRAPHICS_CODE) {
984 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
985 InsetGraphicsParams inspar = ins.getParams();
986 if (inspar.groupId == groupId) {
987 InsetGraphicsParams tmp = inspar;
988 tmp.filename.erase();
989 return InsetGraphics::params2string(tmp, b);
996 void unifyGraphicsGroups(Buffer & b, string const & argument)
998 InsetGraphicsParams params;
999 InsetGraphics::string2params(argument, b, params);
1001 b.undo().beginUndoGroup();
1002 Inset & inset = b.inset();
1003 InsetIterator it = inset_iterator_begin(inset);
1004 InsetIterator const end = inset_iterator_end(inset);
1005 for (; it != end; ++it) {
1006 if (it->lyxCode() == GRAPHICS_CODE) {
1007 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1008 InsetGraphicsParams inspar = ins.getParams();
1009 if (params.groupId == inspar.groupId) {
1010 b.undo().recordUndo(it);
1011 params.filename = inspar.filename;
1012 ins.setParams(params);
1016 b.undo().endUndoGroup();
1020 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1022 Inset * instmp = &cur.inset();
1023 if (instmp->lyxCode() != GRAPHICS_CODE)
1024 instmp = cur.nextInset();
1025 if (!instmp || instmp->lyxCode() != GRAPHICS_CODE)
1028 return static_cast<InsetGraphics *>(instmp);
1031 } // namespace graphics