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(buffer(),
210 to_utf8(cmd.argument()));
214 case LFUN_INSET_DIALOG_UPDATE:
215 cur.bv().updateDialog("graphics", params2string(params(), buffer()));
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 case LFUN_INSET_SETTINGS:
233 flag.setEnabled(true);
237 return Inset::getStatus(cur, cmd, flag);
242 bool InsetGraphics::showInsetDialog(BufferView * bv) const
244 bv->showDialog("graphics", params2string(params(), bv->buffer()),
245 const_cast<InsetGraphics *>(this));
251 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
253 graphic_->metrics(mi, dim);
257 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
259 graphic_->draw(pi, x, y);
263 Inset::EDITABLE InsetGraphics::editable() const
269 void InsetGraphics::write(ostream & os) const
272 params().Write(os, buffer());
276 void InsetGraphics::read(Lexer & lex)
278 lex.setContext("InsetGraphics::read");
280 readInsetGraphics(lex, buffer().filePath(), params_);
281 graphic_->update(params().as_grfxParams());
285 string InsetGraphics::createLatexOptions() const
287 // Calculate the options part of the command, we must do it to a string
288 // stream since we might have a trailing comma that we would like to remove
289 // before writing it to the output stream.
290 ostringstream options;
291 if (!params().bb.empty())
292 options << "bb=" << rtrim(params().bb) << ',';
298 double const scl = convert<double>(params().scale);
299 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
300 if (!float_equal(scl, 100.0, 0.05))
301 size << "scale=" << scl / 100.0 << ',';
303 if (!params().width.zero())
304 size << "width=" << params().width.asLatexString() << ',';
305 if (!params().height.zero())
306 size << "height=" << params().height.asLatexString() << ',';
307 if (params().keepAspectRatio)
308 size << "keepaspectratio,";
310 if (params().scaleBeforeRotation && !size.str().empty())
311 options << size.str();
313 // Make sure rotation angle is not very close to zero;
314 // a float can be effectively zero but not exactly zero.
315 if (!params().rotateAngle.empty()
316 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
317 options << "angle=" << params().rotateAngle << ',';
318 if (!params().rotateOrigin.empty()) {
319 options << "origin=" << params().rotateOrigin[0];
320 if (contains(params().rotateOrigin,"Top"))
322 else if (contains(params().rotateOrigin,"Bottom"))
324 else if (contains(params().rotateOrigin,"Baseline"))
329 if (!params().scaleBeforeRotation && !size.str().empty())
330 options << size.str();
332 if (!params().special.empty())
333 options << params().special << ',';
335 string opts = options.str();
337 if (suffixIs(opts, ','))
338 opts = opts.substr(0, opts.size() - 1);
344 docstring InsetGraphics::toDocbookLength(Length const & len) const
346 odocstringstream result;
347 switch (len.unit()) {
348 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
349 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
351 case Length::PT: // Point = 1/72.27in = 0.351mm
352 result << len.value() * 72 / 72.27 << "pt";
354 case Length::BP: // Big point (72bp = 1in), also PostScript point
355 result << len.value() << "pt";
357 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
358 result << len.value() * 0.376 << "mm";
360 case Length::MM: // Millimeter = 2.845pt
361 result << len.value() << "mm";
363 case Length::PC: // Pica = 12pt = 4.218mm
364 result << len.value() << "pc";
366 case Length::CC: // Cicero = 12dd = 4.531mm
367 result << len.value() * 4.531 << "mm";
369 case Length::CM: // Centimeter = 10mm = 2.371pc
370 result << len.value() << "cm";
372 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
373 result << len.value() << "in";
375 case Length::EX: // Height of a small "x" for the current font.
376 // Obviously we have to compromise here. Any better ratio than 1.5 ?
377 result << len.value() / 1.5 << "em";
379 case Length::EM: // Width of capital "M" in current font.
380 result << len.value() << "em";
382 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
383 result << len.value() * 18 << "em";
385 case Length::PTW: // Percent of TextWidth
386 case Length::PCW: // Percent of ColumnWidth
387 case Length::PPW: // Percent of PageWidth
388 case Length::PLW: // Percent of LineWidth
389 case Length::PTH: // Percent of TextHeight
390 case Length::PPH: // Percent of Paper
391 // Sigh, this will go wrong.
392 result << len.value() << "%";
395 result << len.asDocstring();
402 docstring InsetGraphics::createDocBookAttributes() const
404 // Calculate the options part of the command, we must do it to a string
405 // stream since we copied the code from createLatexParams() ;-)
407 // FIXME: av: need to translate spec -> Docbook XSL spec
408 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
409 // Right now it only works with my version of db2latex :-)
411 odocstringstream options;
412 double const scl = convert<double>(params().scale);
413 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
414 if (!float_equal(scl, 100.0, 0.05))
415 options << " scale=\""
416 << static_cast<int>( (scl) + 0.5 )
419 if (!params().width.zero()) {
420 options << " width=\"" << toDocbookLength(params().width) << "\" ";
422 if (!params().height.zero()) {
423 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
425 if (params().keepAspectRatio) {
426 // This will be irrelevant unless both width and height are set
427 options << "scalefit=\"1\" ";
432 if (!params().special.empty())
433 options << from_ascii(params().special) << " ";
435 // trailing blanks are ok ...
436 return options.str();
442 enum GraphicsCopyStatus {
450 pair<GraphicsCopyStatus, FileName> const
451 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
453 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
454 unsigned long const checksum_in = file_in.checksum();
455 unsigned long const checksum_out = file_out.checksum();
457 if (checksum_in == checksum_out)
459 return make_pair(IDENTICAL_CONTENTS, file_out);
461 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
462 bool const success = mover.copy(file_in, file_out);
465 LYXERR(Debug::GRAPHICS,
466 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
467 "into the temporary directory."),
468 from_utf8(file_in.absFilename()))));
471 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
472 return make_pair(status, file_out);
476 pair<GraphicsCopyStatus, FileName> const
477 copyToDirIfNeeded(DocFileName const & file, string const & dir)
479 string const file_in = file.absFilename();
480 string const only_path = onlyPath(file_in);
481 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
482 return make_pair(IDENTICAL_PATHS, file_in);
484 string mangled = file.mangledFilename();
485 if (file.isZipped()) {
486 // We need to change _eps.gz to .eps.gz. The mangled name is
487 // still unique because of the counter in mangledFilename().
488 // We can't just call mangledFilename() with the zip
489 // extension removed, because base.eps and base.eps.gz may
490 // have different content but would get the same mangled
491 // name in this case.
492 string const base = removeExtension(file.unzippedFilename());
493 string::size_type const ext_len = file_in.length() - base.length();
494 mangled[mangled.length() - ext_len] = '.';
496 FileName const file_out(makeAbsPath(mangled, dir));
498 return copyFileIfNeeded(file, file_out);
502 string const stripExtensionIfPossible(string const & file, bool nice)
504 // Remove the extension so the LaTeX compiler will use whatever
505 // is appropriate (when there are several versions in different
507 // Do this only if we are not exporting for internal usage, because
508 // pdflatex prefers png over pdf and it would pick up the png images
509 // that we generate for preview.
510 // This works only if the filename contains no dots besides
511 // the just removed one. We can fool here by replacing all
512 // dots with a macro whose definition is just a dot ;-)
513 // The automatic format selection does not work if the file
515 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
516 if (!nice || contains(latex_name, '"'))
518 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
522 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
524 // No conversion is needed. LaTeX can handle the graphic file as is.
525 // This is true even if the orig_file is compressed.
526 string const to_format = formats.getFormat(to)->extension();
527 string const file_format = getExtension(file);
528 // for latex .ps == .eps
529 if (to_format == file_format ||
530 (to_format == "eps" && file_format == "ps") ||
531 (to_format == "ps" && file_format == "eps"))
532 return stripExtensionIfPossible(file, nice);
533 return latex_path(file, EXCLUDE_EXTENSION);
539 string InsetGraphics::prepareFile(OutputParams const & runparams) const
541 // The following code depends on non-empty filenames
542 if (params().filename.empty())
545 string const orig_file = params().filename.absFilename();
546 // this is for dryrun and display purposes, do not use latexFilename
547 string const rel_file = params().filename.relFilename(buffer().filePath());
549 // previewing source code, no file copying or file format conversion
550 if (runparams.dryrun)
551 return stripExtensionIfPossible(rel_file, runparams.nice);
553 // temp_file will contain the file for LaTeX to act on if, for example,
554 // we move it to a temp dir or uncompress it.
555 FileName temp_file = params().filename;
557 // The master buffer. This is useful when there are multiple levels
559 Buffer const * masterBuffer = buffer().masterBuffer();
561 // Return the output name if we are inside a comment or the file does
563 // We are not going to change the extension or using the name of the
564 // temporary file, the code is already complicated enough.
565 if (runparams.inComment || !params().filename.isReadableFile())
566 return params().filename.outputFilename(masterBuffer->filePath());
568 // We place all temporary files in the master buffer's temp dir.
569 // This is possible because we use mangled file names.
570 // This is necessary for DVI export.
571 string const temp_path = masterBuffer->temppath();
573 GraphicsCopyStatus status;
574 boost::tie(status, temp_file) =
575 copyToDirIfNeeded(params().filename, temp_path);
577 if (status == FAILURE)
580 // a relative filename should be relative to the master buffer.
581 // "nice" means that the buffer is exported to LaTeX format but not
582 // run through the LaTeX compiler.
583 string output_file = runparams.nice ?
584 params().filename.outputFilename(masterBuffer->filePath()) :
585 onlyFilename(temp_file.absFilename());
587 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
588 frontend::Alert::warning(_("Invalid filename"),
589 _("The following filename is likely to cause trouble "
590 "when running the exported file through LaTeX: ") +
591 from_utf8(output_file));
594 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
595 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
596 "latex" : "pdflatex";
598 // If the file is compressed and we have specified that it
599 // should not be uncompressed, then just return its name and
600 // let LaTeX do the rest!
601 if (params().filename.isZipped()) {
602 if (params().noUnzip) {
603 // We don't know whether latex can actually handle
604 // this file, but we can't check, because that would
605 // mean to unzip the file and thereby making the
606 // noUnzip parameter meaningless.
607 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
609 FileName const bb_orig_file =
610 FileName(changeExtension(orig_file, "bb"));
611 if (runparams.nice) {
612 runparams.exportdata->addExternalFile(tex_format,
614 changeExtension(output_file, "bb"));
616 // LaTeX needs the bounding box file in the
619 FileName(changeExtension(temp_file.absFilename(), "bb"));
620 boost::tie(status, bb_file) =
621 copyFileIfNeeded(bb_orig_file, bb_file);
622 if (status == FAILURE)
624 runparams.exportdata->addExternalFile(tex_format,
627 runparams.exportdata->addExternalFile(tex_format,
628 source_file, output_file);
629 runparams.exportdata->addExternalFile("dvi",
630 source_file, output_file);
631 // We can't strip the extension, because we don't know
632 // the unzipped file format
633 return latex_path(output_file, EXCLUDE_EXTENSION);
636 FileName const unzipped_temp_file =
637 FileName(unzippedFileName(temp_file.absFilename()));
638 output_file = unzippedFileName(output_file);
639 source_file = FileName(unzippedFileName(source_file.absFilename()));
640 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
641 // temp_file has been unzipped already and
642 // orig_file has not changed in the meantime.
643 temp_file = unzipped_temp_file;
644 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
646 // unzipped_temp_file does not exist or is too old
647 temp_file = unzipFile(temp_file);
648 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
652 string const from = formats.getFormatFromFile(temp_file);
654 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
656 string const to = findTargetFormat(from, runparams);
657 string const ext = formats.extension(to);
658 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
660 // We're going to be running the exported buffer through the LaTeX
661 // compiler, so must ensure that LaTeX can cope with the graphics
664 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
667 if (!runparams.nice && !FileName(temp_file).hasExtension(ext)) {
668 // The LaTeX compiler will not be able to determine
669 // the file format from the extension, so we must
671 FileName const new_file =
672 FileName(changeExtension(temp_file.absFilename(), ext));
673 if (temp_file.moveTo(new_file)) {
674 temp_file = new_file;
675 output_file = changeExtension(output_file, ext);
677 FileName(changeExtension(source_file.absFilename(), ext));
679 LYXERR(Debug::GRAPHICS, "Could not rename file `"
680 << temp_file << "' to `" << new_file << "'.");
683 // The extension of temp_file might be != ext!
684 runparams.exportdata->addExternalFile(tex_format, source_file,
686 runparams.exportdata->addExternalFile("dvi", source_file,
688 return stripExtensionIfPossible(output_file, to, runparams.nice);
691 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
692 string const output_to_file = changeExtension(output_file, ext);
694 // Do we need to perform the conversion?
695 // Yes if to_file does not exist or if temp_file is newer than to_file
696 if (compare_timestamps(temp_file, to_file) < 0) {
698 LYXERR(Debug::GRAPHICS,
699 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
700 from_utf8(rel_file))));
701 runparams.exportdata->addExternalFile(tex_format, to_file,
703 runparams.exportdata->addExternalFile("dvi", to_file,
705 return stripExtensionIfPossible(output_to_file, runparams.nice);
708 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
709 << "\tA copy has been made and convert is to be called with:\n"
710 << "\tfile to convert = " << temp_file << '\n'
711 << "\t from " << from << " to " << to);
713 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
715 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
717 Converters::try_default | Converters::try_cache)) {
718 runparams.exportdata->addExternalFile(tex_format,
719 to_file, output_to_file);
720 runparams.exportdata->addExternalFile("dvi",
721 to_file, output_to_file);
724 return stripExtensionIfPossible(output_to_file, runparams.nice);
728 int InsetGraphics::latex(odocstream & os,
729 OutputParams const & runparams) const
731 // If there is no file specified or not existing,
732 // just output a message about it in the latex output.
733 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
734 << params().filename.absFilename());
736 bool const file_exists = !params().filename.empty()
737 && params().filename.isReadableFile();
738 string const message = file_exists ?
739 string() : string("bb = 0 0 200 100, draft, type=eps");
740 // if !message.empty() then there was no existing file
741 // "filename" found. In this case LaTeX
742 // draws only a rectangle with the above bb and the
743 // not found filename in it.
744 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
746 // These variables collect all the latex code that should be before and
747 // after the actual includegraphics command.
751 if (runparams.moving_arg)
752 before += "\\protect";
754 // We never use the starred form, we use the "clip" option instead.
755 before += "\\includegraphics";
757 // Write the options if there are any.
758 string const opts = createLatexOptions();
759 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
761 if (!opts.empty() && !message.empty())
762 before += ('[' + opts + ',' + message + ']');
763 else if (!opts.empty() || !message.empty())
764 before += ('[' + opts + message + ']');
766 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
768 string latex_str = before + '{';
769 // Convert the file if necessary.
770 // Remove the extension so LaTeX will use whatever is appropriate
771 // (when there are several versions in different formats)
772 latex_str += prepareFile(runparams);
773 latex_str += '}' + after;
775 os << from_utf8(latex_str);
777 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
778 // Return how many newlines we issued.
779 return int(count(latex_str.begin(), latex_str.end(),'\n'));
783 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
785 // No graphics in ascii output. Possible to use gifscii to convert
786 // images to ascii approximation.
787 // 1. Convert file to ascii using gifscii
788 // 2. Read ascii output file and add it to the output stream.
789 // at least we send the filename
791 // FIXME: We have no idea what the encoding of the filename is
793 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
794 from_utf8(params().filename.absFilename()));
795 os << '<' << str << '>';
797 return 2 + str.size();
801 static int writeImageObject(char const * format, odocstream & os,
802 OutputParams const & runparams, docstring const & graphic_label,
803 docstring const & attributes)
805 if (runparams.flavor != OutputParams::XML)
806 os << "<![ %output.print." << format
809 os <<"<imageobject><imagedata fileref=\"&"
816 if (runparams.flavor == OutputParams::XML)
817 os << " role=\"" << format << "\"/>" ;
819 os << " format=\"" << format << "\">" ;
821 os << "</imageobject>";
823 if (runparams.flavor != OutputParams::XML)
824 os << endl << "]]>" ;
826 return runparams.flavor == OutputParams::XML ? 0 : 2;
830 // For explanation on inserting graphics into DocBook checkout:
831 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
832 // See also the docbook guide at http://www.docbook.org/
833 int InsetGraphics::docbook(odocstream & os,
834 OutputParams const & runparams) const
836 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
837 // need to switch to MediaObject. However, for now this is sufficient and
839 if (runparams.flavor == OutputParams::XML)
840 runparams.exportdata->addExternalFile("docbook-xml",
843 runparams.exportdata->addExternalFile("docbook",
846 os << "<inlinemediaobject>";
849 docstring attributes = createDocBookAttributes();
850 r += writeImageObject("png", os, runparams, graphic_label, attributes);
851 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
852 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
853 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
855 os << "</inlinemediaobject>";
860 void InsetGraphics::validate(LaTeXFeatures & features) const
862 // If we have no image, we should not require anything.
863 if (params().filename.empty())
866 features.includeFile(graphic_label,
867 removeExtension(params().filename.absFilename()));
869 features.require("graphicx");
871 if (features.runparams().nice) {
872 Buffer const * masterBuffer = features.buffer().masterBuffer();
873 string const rel_file = removeExtension(
874 params().filename.relFilename(masterBuffer->filePath()));
875 if (contains(rel_file, "."))
876 features.require("lyxdot");
881 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
883 // If nothing is changed, just return and say so.
884 if (params() == p && !p.filename.empty())
887 // Copy the new parameters.
890 // Update the display using the new parameters.
891 graphic_->update(params().as_grfxParams());
893 // We have changed data, report it.
898 InsetGraphicsParams const & InsetGraphics::params() const
904 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
905 Buffer const & buffer) const
907 formats.edit(buffer, p.filename,
908 formats.getFormatFromFile(p.filename));
912 void InsetGraphics::addToToc(DocIterator const & cpit)
914 TocBackend & backend = buffer().tocBackend();
917 docstring const str = from_utf8(params_.filename.onlyFileName());
918 backend.toc("graphics").push_back(TocItem(cpit, 0, str));
922 docstring InsetGraphics::contextMenu(BufferView const &, int, int) const
924 return from_ascii("context-graphics");
928 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
929 InsetGraphicsParams & params)
934 istringstream data(in);
937 lex.setContext("InsetGraphics::string2params");
939 params = InsetGraphicsParams();
940 readInsetGraphics(lex, buffer.filePath(), params);
944 string InsetGraphics::params2string(InsetGraphicsParams const & params,
945 Buffer const & buffer)
948 data << "graphics" << ' ';
949 params.Write(data, buffer);
950 data << "\\end_inset\n";
956 void getGraphicsGroups(Buffer const & b, set<string> & ids)
958 Inset & inset = b.inset();
959 InsetIterator it = inset_iterator_begin(inset);
960 InsetIterator const end = inset_iterator_end(inset);
961 for (; it != end; ++it)
962 if (it->lyxCode() == GRAPHICS_CODE) {
963 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
964 InsetGraphicsParams inspar = ins.getParams();
965 if (!inspar.groupId.empty())
966 ids.insert(inspar.groupId);
971 int countGroupMembers(Buffer const & b, string const & groupId)
976 Inset & inset = b.inset();
977 InsetIterator it = inset_iterator_begin(inset);
978 InsetIterator const end = inset_iterator_end(inset);
979 for (; it != end; ++it)
980 if (it->lyxCode() == GRAPHICS_CODE) {
981 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
982 if (ins.getParams().groupId == groupId)
989 string getGroupParams(Buffer const & b, string const & groupId)
993 Inset & inset = b.inset();
994 InsetIterator it = inset_iterator_begin(inset);
995 InsetIterator const end = inset_iterator_end(inset);
996 for (; it != end; ++it)
997 if (it->lyxCode() == GRAPHICS_CODE) {
998 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
999 InsetGraphicsParams inspar = ins.getParams();
1000 if (inspar.groupId == groupId) {
1001 InsetGraphicsParams tmp = inspar;
1002 tmp.filename.erase();
1003 return InsetGraphics::params2string(tmp, b);
1010 void unifyGraphicsGroups(Buffer & b, string const & argument)
1012 InsetGraphicsParams params;
1013 InsetGraphics::string2params(argument, b, params);
1015 b.undo().beginUndoGroup();
1016 Inset & inset = b.inset();
1017 InsetIterator it = inset_iterator_begin(inset);
1018 InsetIterator const end = inset_iterator_end(inset);
1019 for (; it != end; ++it) {
1020 if (it->lyxCode() == GRAPHICS_CODE) {
1021 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1022 InsetGraphicsParams inspar = ins.getParams();
1023 if (params.groupId == inspar.groupId) {
1024 b.undo().recordUndo(it);
1025 params.filename = inspar.filename;
1026 ins.setParams(params);
1030 b.undo().endUndoGroup();
1034 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1036 Inset * instmp = &cur.inset();
1037 if (instmp->lyxCode() != GRAPHICS_CODE)
1038 instmp = cur.nextInset();
1039 if (!instmp || instmp->lyxCode() != GRAPHICS_CODE)
1042 return static_cast<InsetGraphics *>(instmp);
1045 } // namespace graphics