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())
207 case LFUN_INSET_DIALOG_UPDATE:
208 cur.bv().updateDialog("graphics", params2string(params(),
212 case LFUN_MOUSE_RELEASE:
213 if (!cur.selection() && cmd.button() == mouse_button::button1)
214 cur.bv().showDialog("graphics", params2string(params(),
215 cur.bv().buffer()), this);
219 Inset::doDispatch(cur, cmd);
225 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
226 FuncStatus & flag) const
228 switch (cmd.action) {
229 case LFUN_INSET_EDIT:
230 case LFUN_INSET_MODIFY:
231 case LFUN_INSET_DIALOG_UPDATE:
232 flag.setEnabled(true);
236 return Inset::getStatus(cur, cmd, flag);
241 void InsetGraphics::edit(Cursor & cur, bool, EntryDirection)
243 cur.bv().showDialog("graphics", params2string(params(),
244 cur.bv().buffer()), this);
248 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
250 graphic_->metrics(mi, dim);
254 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
256 graphic_->draw(pi, x, y);
260 Inset::EDITABLE InsetGraphics::editable() const
266 void InsetGraphics::write(ostream & os) const
269 params().Write(os, buffer());
273 void InsetGraphics::read(Lexer & lex)
275 lex.setContext("InsetGraphics::read");
277 readInsetGraphics(lex, buffer().filePath(), params_);
278 graphic_->update(params().as_grfxParams());
282 string InsetGraphics::createLatexOptions() const
284 // Calculate the options part of the command, we must do it to a string
285 // stream since we might have a trailing comma that we would like to remove
286 // before writing it to the output stream.
287 ostringstream options;
288 if (!params().bb.empty())
289 options << "bb=" << rtrim(params().bb) << ',';
295 double const scl = convert<double>(params().scale);
296 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
297 if (!float_equal(scl, 100.0, 0.05))
298 size << "scale=" << scl / 100.0 << ',';
300 if (!params().width.zero())
301 size << "width=" << params().width.asLatexString() << ',';
302 if (!params().height.zero())
303 size << "height=" << params().height.asLatexString() << ',';
304 if (params().keepAspectRatio)
305 size << "keepaspectratio,";
307 if (params().scaleBeforeRotation && !size.str().empty())
308 options << size.str();
310 // Make sure rotation angle is not very close to zero;
311 // a float can be effectively zero but not exactly zero.
312 if (!params().rotateAngle.empty()
313 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
314 options << "angle=" << params().rotateAngle << ',';
315 if (!params().rotateOrigin.empty()) {
316 options << "origin=" << params().rotateOrigin[0];
317 if (contains(params().rotateOrigin,"Top"))
319 else if (contains(params().rotateOrigin,"Bottom"))
321 else if (contains(params().rotateOrigin,"Baseline"))
326 if (!params().scaleBeforeRotation && !size.str().empty())
327 options << size.str();
329 if (!params().special.empty())
330 options << params().special << ',';
332 string opts = options.str();
334 if (suffixIs(opts, ','))
335 opts = opts.substr(0, opts.size() - 1);
341 docstring InsetGraphics::toDocbookLength(Length const & len) const
343 odocstringstream result;
344 switch (len.unit()) {
345 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
346 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
348 case Length::PT: // Point = 1/72.27in = 0.351mm
349 result << len.value() * 72 / 72.27 << "pt";
351 case Length::BP: // Big point (72bp = 1in), also PostScript point
352 result << len.value() << "pt";
354 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
355 result << len.value() * 0.376 << "mm";
357 case Length::MM: // Millimeter = 2.845pt
358 result << len.value() << "mm";
360 case Length::PC: // Pica = 12pt = 4.218mm
361 result << len.value() << "pc";
363 case Length::CC: // Cicero = 12dd = 4.531mm
364 result << len.value() * 4.531 << "mm";
366 case Length::CM: // Centimeter = 10mm = 2.371pc
367 result << len.value() << "cm";
369 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
370 result << len.value() << "in";
372 case Length::EX: // Height of a small "x" for the current font.
373 // Obviously we have to compromise here. Any better ratio than 1.5 ?
374 result << len.value() / 1.5 << "em";
376 case Length::EM: // Width of capital "M" in current font.
377 result << len.value() << "em";
379 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
380 result << len.value() * 18 << "em";
382 case Length::PTW: // Percent of TextWidth
383 case Length::PCW: // Percent of ColumnWidth
384 case Length::PPW: // Percent of PageWidth
385 case Length::PLW: // Percent of LineWidth
386 case Length::PTH: // Percent of TextHeight
387 case Length::PPH: // Percent of Paper
388 // Sigh, this will go wrong.
389 result << len.value() << "%";
392 result << len.asDocstring();
399 docstring InsetGraphics::createDocBookAttributes() const
401 // Calculate the options part of the command, we must do it to a string
402 // stream since we copied the code from createLatexParams() ;-)
404 // FIXME: av: need to translate spec -> Docbook XSL spec
405 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
406 // Right now it only works with my version of db2latex :-)
408 odocstringstream options;
409 double const scl = convert<double>(params().scale);
410 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
411 if (!float_equal(scl, 100.0, 0.05))
412 options << " scale=\""
413 << static_cast<int>( (scl) + 0.5 )
416 if (!params().width.zero()) {
417 options << " width=\"" << toDocbookLength(params().width) << "\" ";
419 if (!params().height.zero()) {
420 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
422 if (params().keepAspectRatio) {
423 // This will be irrelevant unless both width and height are set
424 options << "scalefit=\"1\" ";
429 if (!params().special.empty())
430 options << from_ascii(params().special) << " ";
432 // trailing blanks are ok ...
433 return options.str();
439 enum GraphicsCopyStatus {
447 pair<GraphicsCopyStatus, FileName> const
448 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
450 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
451 unsigned long const checksum_in = file_in.checksum();
452 unsigned long const checksum_out = file_out.checksum();
454 if (checksum_in == checksum_out)
456 return make_pair(IDENTICAL_CONTENTS, file_out);
458 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
459 bool const success = mover.copy(file_in, file_out);
462 LYXERR(Debug::GRAPHICS,
463 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
464 "into the temporary directory."),
465 from_utf8(file_in.absFilename()))));
468 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
469 return make_pair(status, file_out);
473 pair<GraphicsCopyStatus, FileName> const
474 copyToDirIfNeeded(DocFileName const & file, string const & dir)
476 string const file_in = file.absFilename();
477 string const only_path = onlyPath(file_in);
478 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
479 return make_pair(IDENTICAL_PATHS, file_in);
481 string mangled = file.mangledFilename();
482 if (file.isZipped()) {
483 // We need to change _eps.gz to .eps.gz. The mangled name is
484 // still unique because of the counter in mangledFilename().
485 // We can't just call mangledFilename() with the zip
486 // extension removed, because base.eps and base.eps.gz may
487 // have different content but would get the same mangled
488 // name in this case.
489 string const base = removeExtension(file.unzippedFilename());
490 string::size_type const ext_len = file_in.length() - base.length();
491 mangled[mangled.length() - ext_len] = '.';
493 FileName const file_out(makeAbsPath(mangled, dir));
495 return copyFileIfNeeded(file, file_out);
499 string const stripExtensionIfPossible(string const & file, bool nice)
501 // Remove the extension so the LaTeX compiler will use whatever
502 // is appropriate (when there are several versions in different
504 // Do this only if we are not exporting for internal usage, because
505 // pdflatex prefers png over pdf and it would pick up the png images
506 // that we generate for preview.
507 // This works only if the filename contains no dots besides
508 // the just removed one. We can fool here by replacing all
509 // dots with a macro whose definition is just a dot ;-)
510 // The automatic format selection does not work if the file
512 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
513 if (!nice || contains(latex_name, '"'))
515 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
519 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
521 // No conversion is needed. LaTeX can handle the graphic file as is.
522 // This is true even if the orig_file is compressed.
523 string const to_format = formats.getFormat(to)->extension();
524 string const file_format = getExtension(file);
525 // for latex .ps == .eps
526 if (to_format == file_format ||
527 (to_format == "eps" && file_format == "ps") ||
528 (to_format == "ps" && file_format == "eps"))
529 return stripExtensionIfPossible(file, nice);
530 return latex_path(file, EXCLUDE_EXTENSION);
536 string InsetGraphics::prepareFile(OutputParams const & runparams) const
538 // The following code depends on non-empty filenames
539 if (params().filename.empty())
542 string const orig_file = params().filename.absFilename();
543 // this is for dryrun and display purposes, do not use latexFilename
544 string const rel_file = params().filename.relFilename(buffer().filePath());
546 // previewing source code, no file copying or file format conversion
547 if (runparams.dryrun)
548 return stripExtensionIfPossible(rel_file, runparams.nice);
550 // temp_file will contain the file for LaTeX to act on if, for example,
551 // we move it to a temp dir or uncompress it.
552 FileName temp_file = params().filename;
554 // The master buffer. This is useful when there are multiple levels
556 Buffer const * masterBuffer = buffer().masterBuffer();
558 // Return the output name if we are inside a comment or the file does
560 // We are not going to change the extension or using the name of the
561 // temporary file, the code is already complicated enough.
562 if (runparams.inComment || !params().filename.isReadableFile())
563 return params().filename.outputFilename(masterBuffer->filePath());
565 // We place all temporary files in the master buffer's temp dir.
566 // This is possible because we use mangled file names.
567 // This is necessary for DVI export.
568 string const temp_path = masterBuffer->temppath();
570 GraphicsCopyStatus status;
571 boost::tie(status, temp_file) =
572 copyToDirIfNeeded(params().filename, temp_path);
574 if (status == FAILURE)
577 // a relative filename should be relative to the master buffer.
578 // "nice" means that the buffer is exported to LaTeX format but not
579 // run through the LaTeX compiler.
580 string output_file = runparams.nice ?
581 params().filename.outputFilename(masterBuffer->filePath()) :
582 onlyFilename(temp_file.absFilename());
584 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
585 frontend::Alert::warning(_("Invalid filename"),
586 _("The following filename is likely to cause trouble "
587 "when running the exported file through LaTeX: ") +
588 from_utf8(output_file));
591 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
592 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
593 "latex" : "pdflatex";
595 // If the file is compressed and we have specified that it
596 // should not be uncompressed, then just return its name and
597 // let LaTeX do the rest!
598 if (params().filename.isZipped()) {
599 if (params().noUnzip) {
600 // We don't know whether latex can actually handle
601 // this file, but we can't check, because that would
602 // mean to unzip the file and thereby making the
603 // noUnzip parameter meaningless.
604 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
606 FileName const bb_orig_file =
607 FileName(changeExtension(orig_file, "bb"));
608 if (runparams.nice) {
609 runparams.exportdata->addExternalFile(tex_format,
611 changeExtension(output_file, "bb"));
613 // LaTeX needs the bounding box file in the
616 FileName(changeExtension(temp_file.absFilename(), "bb"));
617 boost::tie(status, bb_file) =
618 copyFileIfNeeded(bb_orig_file, bb_file);
619 if (status == FAILURE)
621 runparams.exportdata->addExternalFile(tex_format,
624 runparams.exportdata->addExternalFile(tex_format,
625 source_file, output_file);
626 runparams.exportdata->addExternalFile("dvi",
627 source_file, output_file);
628 // We can't strip the extension, because we don't know
629 // the unzipped file format
630 return latex_path(output_file, EXCLUDE_EXTENSION);
633 FileName const unzipped_temp_file =
634 FileName(unzippedFileName(temp_file.absFilename()));
635 output_file = unzippedFileName(output_file);
636 source_file = FileName(unzippedFileName(source_file.absFilename()));
637 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
638 // temp_file has been unzipped already and
639 // orig_file has not changed in the meantime.
640 temp_file = unzipped_temp_file;
641 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
643 // unzipped_temp_file does not exist or is too old
644 temp_file = unzipFile(temp_file);
645 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
649 string const from = formats.getFormatFromFile(temp_file);
651 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
653 string const to = findTargetFormat(from, runparams);
654 string const ext = formats.extension(to);
655 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
657 // We're going to be running the exported buffer through the LaTeX
658 // compiler, so must ensure that LaTeX can cope with the graphics
661 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
664 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
665 // The LaTeX compiler will not be able to determine
666 // the file format from the extension, so we must
668 FileName const new_file =
669 FileName(changeExtension(temp_file.absFilename(), ext));
670 if (temp_file.moveTo(new_file)) {
671 temp_file = new_file;
672 output_file = changeExtension(output_file, ext);
674 FileName(changeExtension(source_file.absFilename(), ext));
676 LYXERR(Debug::GRAPHICS, "Could not rename file `"
677 << temp_file << "' to `" << new_file << "'.");
680 // The extension of temp_file might be != ext!
681 runparams.exportdata->addExternalFile(tex_format, source_file,
683 runparams.exportdata->addExternalFile("dvi", source_file,
685 return stripExtensionIfPossible(output_file, to, runparams.nice);
688 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
689 string const output_to_file = changeExtension(output_file, ext);
691 // Do we need to perform the conversion?
692 // Yes if to_file does not exist or if temp_file is newer than to_file
693 if (compare_timestamps(temp_file, to_file) < 0) {
695 LYXERR(Debug::GRAPHICS,
696 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
697 from_utf8(rel_file))));
698 runparams.exportdata->addExternalFile(tex_format, to_file,
700 runparams.exportdata->addExternalFile("dvi", to_file,
702 return stripExtensionIfPossible(output_to_file, runparams.nice);
705 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
706 << "\tA copy has been made and convert is to be called with:\n"
707 << "\tfile to convert = " << temp_file << '\n'
708 << "\t from " << from << " to " << to);
710 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
712 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
714 Converters::try_default | Converters::try_cache)) {
715 runparams.exportdata->addExternalFile(tex_format,
716 to_file, output_to_file);
717 runparams.exportdata->addExternalFile("dvi",
718 to_file, output_to_file);
721 return stripExtensionIfPossible(output_to_file, runparams.nice);
725 int InsetGraphics::latex(odocstream & os,
726 OutputParams const & runparams) const
728 // If there is no file specified or not existing,
729 // just output a message about it in the latex output.
730 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
731 << params().filename.absFilename());
733 bool const file_exists = !params().filename.empty()
734 && params().filename.isReadableFile();
735 string const message = file_exists ?
736 string() : string("bb = 0 0 200 100, draft, type=eps");
737 // if !message.empty() then there was no existing file
738 // "filename" found. In this case LaTeX
739 // draws only a rectangle with the above bb and the
740 // not found filename in it.
741 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
743 // These variables collect all the latex code that should be before and
744 // after the actual includegraphics command.
748 if (runparams.moving_arg)
749 before += "\\protect";
751 // We never use the starred form, we use the "clip" option instead.
752 before += "\\includegraphics";
754 // Write the options if there are any.
755 string const opts = createLatexOptions();
756 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
758 if (!opts.empty() && !message.empty())
759 before += ('[' + opts + ',' + message + ']');
760 else if (!opts.empty() || !message.empty())
761 before += ('[' + opts + message + ']');
763 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
765 string latex_str = before + '{';
766 // Convert the file if necessary.
767 // Remove the extension so LaTeX will use whatever is appropriate
768 // (when there are several versions in different formats)
769 latex_str += prepareFile(runparams);
770 latex_str += '}' + after;
772 os << from_utf8(latex_str);
774 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
775 // Return how many newlines we issued.
776 return int(count(latex_str.begin(), latex_str.end(),'\n'));
780 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
782 // No graphics in ascii output. Possible to use gifscii to convert
783 // images to ascii approximation.
784 // 1. Convert file to ascii using gifscii
785 // 2. Read ascii output file and add it to the output stream.
786 // at least we send the filename
788 // FIXME: We have no idea what the encoding of the filename is
790 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
791 from_utf8(params().filename.absFilename()));
792 os << '<' << str << '>';
794 return 2 + str.size();
798 static int writeImageObject(char const * format, odocstream & os,
799 OutputParams const & runparams, docstring const & graphic_label,
800 docstring const & attributes)
802 if (runparams.flavor != OutputParams::XML)
803 os << "<![ %output.print." << format
806 os <<"<imageobject><imagedata fileref=\"&"
813 if (runparams.flavor == OutputParams::XML)
814 os << " role=\"" << format << "\"/>" ;
816 os << " format=\"" << format << "\">" ;
818 os << "</imageobject>";
820 if (runparams.flavor != OutputParams::XML)
821 os << endl << "]]>" ;
823 return runparams.flavor == OutputParams::XML ? 0 : 2;
827 // For explanation on inserting graphics into DocBook checkout:
828 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
829 // See also the docbook guide at http://www.docbook.org/
830 int InsetGraphics::docbook(odocstream & os,
831 OutputParams const & runparams) const
833 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
834 // need to switch to MediaObject. However, for now this is sufficient and
836 if (runparams.flavor == OutputParams::XML)
837 runparams.exportdata->addExternalFile("docbook-xml",
840 runparams.exportdata->addExternalFile("docbook",
843 os << "<inlinemediaobject>";
846 docstring attributes = createDocBookAttributes();
847 r += writeImageObject("png", os, runparams, graphic_label, attributes);
848 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
849 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
850 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
852 os << "</inlinemediaobject>";
857 void InsetGraphics::validate(LaTeXFeatures & features) const
859 // If we have no image, we should not require anything.
860 if (params().filename.empty())
863 features.includeFile(graphic_label,
864 removeExtension(params().filename.absFilename()));
866 features.require("graphicx");
868 if (features.runparams().nice) {
869 Buffer const * masterBuffer = features.buffer().masterBuffer();
870 string const rel_file = removeExtension(
871 params().filename.relFilename(masterBuffer->filePath()));
872 if (contains(rel_file, "."))
873 features.require("lyxdot");
878 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
880 // If nothing is changed, just return and say so.
881 if (params() == p && !p.filename.empty())
884 // Copy the new parameters.
887 // Update the display using the new parameters.
888 graphic_->update(params().as_grfxParams());
890 // We have changed data, report it.
895 InsetGraphicsParams const & InsetGraphics::params() const
901 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
902 Buffer const & buffer) const
904 formats.edit(buffer, p.filename,
905 formats.getFormatFromFile(p.filename));
909 void InsetGraphics::addToToc(DocIterator const & cpit)
911 TocBackend & backend = buffer().tocBackend();
914 docstring const str = from_utf8(params_.filename.onlyFileName());
915 backend.toc("graphics").push_back(TocItem(cpit, 0, str));
919 docstring InsetGraphics::contextMenu(BufferView const &, int, int) const
921 return from_ascii("context-graphics");
925 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
926 InsetGraphicsParams & params)
931 istringstream data(in);
934 lex.setContext("InsetGraphics::string2params");
936 params = InsetGraphicsParams();
937 readInsetGraphics(lex, buffer.filePath(), params);
941 string InsetGraphics::params2string(InsetGraphicsParams const & params,
942 Buffer const & buffer)
945 data << "graphics" << ' ';
946 params.Write(data, buffer);
947 data << "\\end_inset\n";
953 void getGraphicsGroups(Buffer const & b, set<string> & ids)
955 Inset & inset = b.inset();
956 InsetIterator it = inset_iterator_begin(inset);
957 InsetIterator const end = inset_iterator_end(inset);
958 for (; it != end; ++it)
959 if (it->lyxCode() == GRAPHICS_CODE) {
960 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
961 InsetGraphicsParams inspar = ins.getParams();
962 if (!inspar.groupId.empty())
963 ids.insert(inspar.groupId);
968 string getGroupParams(Buffer const & b, string const & groupId)
972 Inset & inset = b.inset();
973 InsetIterator it = inset_iterator_begin(inset);
974 InsetIterator const end = inset_iterator_end(inset);
975 for (; it != end; ++it)
976 if (it->lyxCode() == GRAPHICS_CODE) {
977 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
978 InsetGraphicsParams inspar = ins.getParams();
979 if (inspar.groupId == groupId) {
980 InsetGraphicsParams tmp = inspar;
981 tmp.filename.erase();
982 return InsetGraphics::params2string(tmp, b);
989 void unifyGraphicsGroups(Buffer & b, string const & argument)
991 InsetGraphicsParams params;
992 InsetGraphics::string2params(argument, b, params);
994 b.undo().beginUndoGroup();
995 Inset & inset = b.inset();
996 InsetIterator it = inset_iterator_begin(inset);
997 InsetIterator const end = inset_iterator_end(inset);
998 for (; it != end; ++it) {
999 if (it->lyxCode() == GRAPHICS_CODE) {
1000 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1001 InsetGraphicsParams inspar = ins.getParams();
1002 if (params.groupId == inspar.groupId) {
1003 b.undo().recordUndo(it);
1004 params.filename = inspar.filename;
1005 ins.setParams(params);
1009 b.undo().endUndoGroup();
1013 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1015 Inset * instmp = &cur.inset();
1016 if (instmp->lyxCode() != GRAPHICS_CODE)
1017 instmp = cur.nextInset();
1018 if (!instmp || instmp->lyxCode() != GRAPHICS_CODE)
1021 return static_cast<InsetGraphics *>(instmp);
1024 } // namespace graphics