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 XeTeX/pdflatex?
105 if (runparams.flavor == OutputParams::PDFLATEX
106 || runparams.flavor == OutputParams::XETEX) {
107 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
108 Format const * const f = formats.getFormat(format);
109 // Convert vector graphics to pdf
110 if (f && f->vectorFormat())
112 // pdflatex can use jpeg, png and pdf directly
115 // Convert everything else to png
118 // If it's postscript, we always do eps.
119 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
121 // any other than ps is changed to eps
128 void readInsetGraphics(Lexer & lex, string const & bufpath,
129 InsetGraphicsParams & params)
131 bool finished = false;
133 while (lex.isOK() && !finished) {
136 string const token = lex.getString();
137 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
142 if (token == "\\end_inset") {
145 if (!params.Read(lex, token, bufpath))
146 lyxerr << "Unknown token, "
157 InsetGraphics::InsetGraphics(Buffer & buf)
158 : graphic_label(sgml::uniqueID(from_ascii("graph"))),
159 graphic_(new RenderGraphic(this))
161 Inset::setBuffer(buf);
165 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
167 graphic_label(sgml::uniqueID(from_ascii("graph"))),
168 graphic_(new RenderGraphic(*ig.graphic_, this))
170 setParams(ig.params());
174 Inset * InsetGraphics::clone() const
176 return new InsetGraphics(*this);
180 InsetGraphics::~InsetGraphics()
182 hideDialogs("graphics", this);
187 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
189 switch (cmd.action) {
190 case LFUN_INSET_EDIT: {
191 InsetGraphicsParams p = params();
192 if (!cmd.argument().empty())
193 string2params(to_utf8(cmd.argument()), buffer(), p);
194 editGraphics(p, buffer());
198 case LFUN_INSET_MODIFY: {
199 InsetGraphicsParams p;
200 string2params(to_utf8(cmd.argument()), buffer(), p);
201 if (p.filename.empty()) {
207 // if the inset is part of a graphics group, all the
208 // other members should be updated too.
209 if (!params_.groupId.empty())
210 graphics::unifyGraphicsGroups(buffer(),
211 to_utf8(cmd.argument()));
215 case LFUN_INSET_DIALOG_UPDATE:
216 cur.bv().updateDialog("graphics", params2string(params(), buffer()));
220 Inset::doDispatch(cur, cmd);
226 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
227 FuncStatus & flag) const
229 switch (cmd.action) {
230 case LFUN_INSET_EDIT:
231 case LFUN_INSET_MODIFY:
232 case LFUN_INSET_DIALOG_UPDATE:
233 case LFUN_INSET_SETTINGS:
234 flag.setEnabled(true);
238 return Inset::getStatus(cur, cmd, flag);
243 bool InsetGraphics::showInsetDialog(BufferView * bv) const
245 bv->showDialog("graphics", params2string(params(), bv->buffer()),
246 const_cast<InsetGraphics *>(this));
252 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
254 graphic_->metrics(mi, dim);
258 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
260 graphic_->draw(pi, x, y);
264 Inset::EDITABLE InsetGraphics::editable() const
270 void InsetGraphics::write(ostream & os) const
273 params().Write(os, buffer());
277 void InsetGraphics::read(Lexer & lex)
279 lex.setContext("InsetGraphics::read");
281 readInsetGraphics(lex, buffer().filePath(), params_);
282 graphic_->update(params().as_grfxParams());
286 string InsetGraphics::createLatexOptions() const
288 // Calculate the options part of the command, we must do it to a string
289 // stream since we might have a trailing comma that we would like to remove
290 // before writing it to the output stream.
291 ostringstream options;
292 if (!params().bb.empty())
293 options << "bb=" << rtrim(params().bb) << ',';
299 double const scl = convert<double>(params().scale);
300 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
301 if (!float_equal(scl, 100.0, 0.05))
302 size << "scale=" << scl / 100.0 << ',';
304 if (!params().width.zero())
305 size << "width=" << params().width.asLatexString() << ',';
306 if (!params().height.zero())
307 size << "height=" << params().height.asLatexString() << ',';
308 if (params().keepAspectRatio)
309 size << "keepaspectratio,";
311 if (params().scaleBeforeRotation && !size.str().empty())
312 options << size.str();
314 // Make sure rotation angle is not very close to zero;
315 // a float can be effectively zero but not exactly zero.
316 if (!params().rotateAngle.empty()
317 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
318 options << "angle=" << params().rotateAngle << ',';
319 if (!params().rotateOrigin.empty()) {
320 options << "origin=" << params().rotateOrigin[0];
321 if (contains(params().rotateOrigin,"Top"))
323 else if (contains(params().rotateOrigin,"Bottom"))
325 else if (contains(params().rotateOrigin,"Baseline"))
330 if (!params().scaleBeforeRotation && !size.str().empty())
331 options << size.str();
333 if (!params().special.empty())
334 options << params().special << ',';
336 string opts = options.str();
338 if (suffixIs(opts, ','))
339 opts = opts.substr(0, opts.size() - 1);
345 docstring InsetGraphics::toDocbookLength(Length const & len) const
347 odocstringstream result;
348 switch (len.unit()) {
349 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
350 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
352 case Length::PT: // Point = 1/72.27in = 0.351mm
353 result << len.value() * 72 / 72.27 << "pt";
355 case Length::BP: // Big point (72bp = 1in), also PostScript point
356 result << len.value() << "pt";
358 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
359 result << len.value() * 0.376 << "mm";
361 case Length::MM: // Millimeter = 2.845pt
362 result << len.value() << "mm";
364 case Length::PC: // Pica = 12pt = 4.218mm
365 result << len.value() << "pc";
367 case Length::CC: // Cicero = 12dd = 4.531mm
368 result << len.value() * 4.531 << "mm";
370 case Length::CM: // Centimeter = 10mm = 2.371pc
371 result << len.value() << "cm";
373 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
374 result << len.value() << "in";
376 case Length::EX: // Height of a small "x" for the current font.
377 // Obviously we have to compromise here. Any better ratio than 1.5 ?
378 result << len.value() / 1.5 << "em";
380 case Length::EM: // Width of capital "M" in current font.
381 result << len.value() << "em";
383 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
384 result << len.value() * 18 << "em";
386 case Length::PTW: // Percent of TextWidth
387 case Length::PCW: // Percent of ColumnWidth
388 case Length::PPW: // Percent of PageWidth
389 case Length::PLW: // Percent of LineWidth
390 case Length::PTH: // Percent of TextHeight
391 case Length::PPH: // Percent of Paper
392 // Sigh, this will go wrong.
393 result << len.value() << "%";
396 result << len.asDocstring();
403 docstring InsetGraphics::createDocBookAttributes() const
405 // Calculate the options part of the command, we must do it to a string
406 // stream since we copied the code from createLatexParams() ;-)
408 // FIXME: av: need to translate spec -> Docbook XSL spec
409 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
410 // Right now it only works with my version of db2latex :-)
412 odocstringstream options;
413 double const scl = convert<double>(params().scale);
414 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
415 if (!float_equal(scl, 100.0, 0.05))
416 options << " scale=\""
417 << static_cast<int>( (scl) + 0.5 )
420 if (!params().width.zero()) {
421 options << " width=\"" << toDocbookLength(params().width) << "\" ";
423 if (!params().height.zero()) {
424 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
426 if (params().keepAspectRatio) {
427 // This will be irrelevant unless both width and height are set
428 options << "scalefit=\"1\" ";
433 if (!params().special.empty())
434 options << from_ascii(params().special) << " ";
436 // trailing blanks are ok ...
437 return options.str();
443 enum GraphicsCopyStatus {
451 pair<GraphicsCopyStatus, FileName> const
452 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
454 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
455 unsigned long const checksum_in = file_in.checksum();
456 unsigned long const checksum_out = file_out.checksum();
458 if (checksum_in == checksum_out)
460 return make_pair(IDENTICAL_CONTENTS, file_out);
462 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
463 bool const success = mover.copy(file_in, file_out);
466 LYXERR(Debug::GRAPHICS,
467 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
468 "into the temporary directory."),
469 from_utf8(file_in.absFilename()))));
472 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
473 return make_pair(status, file_out);
477 pair<GraphicsCopyStatus, FileName> const
478 copyToDirIfNeeded(DocFileName const & file, string const & dir)
480 string const file_in = file.absFilename();
481 string const only_path = onlyPath(file_in);
482 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
483 return make_pair(IDENTICAL_PATHS, file_in);
485 string mangled = file.mangledFilename();
486 if (file.isZipped()) {
487 // We need to change _eps.gz to .eps.gz. The mangled name is
488 // still unique because of the counter in mangledFilename().
489 // We can't just call mangledFilename() with the zip
490 // extension removed, because base.eps and base.eps.gz may
491 // have different content but would get the same mangled
492 // name in this case.
493 string const base = removeExtension(file.unzippedFilename());
494 string::size_type const ext_len = file_in.length() - base.length();
495 mangled[mangled.length() - ext_len] = '.';
497 FileName const file_out(makeAbsPath(mangled, dir));
499 return copyFileIfNeeded(file, file_out);
503 string const stripExtensionIfPossible(string const & file, bool nice)
505 // Remove the extension so the LaTeX compiler will use whatever
506 // is appropriate (when there are several versions in different
508 // Do this only if we are not exporting for internal usage, because
509 // pdflatex prefers png over pdf and it would pick up the png images
510 // that we generate for preview.
511 // This works only if the filename contains no dots besides
512 // the just removed one. We can fool here by replacing all
513 // dots with a macro whose definition is just a dot ;-)
514 // The automatic format selection does not work if the file
516 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
517 if (!nice || contains(latex_name, '"'))
519 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
523 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
525 // No conversion is needed. LaTeX can handle the graphic file as is.
526 // This is true even if the orig_file is compressed.
527 string const to_format = formats.getFormat(to)->extension();
528 string const file_format = getExtension(file);
529 // for latex .ps == .eps
530 if (to_format == file_format ||
531 (to_format == "eps" && file_format == "ps") ||
532 (to_format == "ps" && file_format == "eps"))
533 return stripExtensionIfPossible(file, nice);
534 return latex_path(file, EXCLUDE_EXTENSION);
540 string InsetGraphics::prepareFile(OutputParams const & runparams) const
542 // The following code depends on non-empty filenames
543 if (params().filename.empty())
546 string const orig_file = params().filename.absFilename();
547 // this is for dryrun and display purposes, do not use latexFilename
548 string const rel_file = params().filename.relFilename(buffer().filePath());
550 // previewing source code, no file copying or file format conversion
551 if (runparams.dryrun)
552 return stripExtensionIfPossible(rel_file, runparams.nice);
554 // temp_file will contain the file for LaTeX to act on if, for example,
555 // we move it to a temp dir or uncompress it.
556 FileName temp_file = params().filename;
558 // The master buffer. This is useful when there are multiple levels
560 Buffer const * masterBuffer = buffer().masterBuffer();
562 // Return the output name if we are inside a comment or the file does
564 // We are not going to change the extension or using the name of the
565 // temporary file, the code is already complicated enough.
566 if (runparams.inComment || !params().filename.isReadableFile())
567 return params().filename.outputFilename(masterBuffer->filePath());
569 // We place all temporary files in the master buffer's temp dir.
570 // This is possible because we use mangled file names.
571 // This is necessary for DVI export.
572 string const temp_path = masterBuffer->temppath();
574 GraphicsCopyStatus status;
575 boost::tie(status, temp_file) =
576 copyToDirIfNeeded(params().filename, temp_path);
578 if (status == FAILURE)
581 // a relative filename should be relative to the master buffer.
582 // "nice" means that the buffer is exported to LaTeX format but not
583 // run through the LaTeX compiler.
584 string output_file = runparams.nice ?
585 params().filename.outputFilename(masterBuffer->filePath()) :
586 onlyFilename(temp_file.absFilename());
588 if (runparams.nice && !isValidLaTeXFilename(output_file)) {
589 frontend::Alert::warning(_("Invalid filename"),
590 _("The following filename is likely to cause trouble "
591 "when running the exported file through LaTeX: ") +
592 from_utf8(output_file));
595 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
596 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
597 "latex" : "pdflatex";
599 // If the file is compressed and we have specified that it
600 // should not be uncompressed, then just return its name and
601 // let LaTeX do the rest!
602 if (params().filename.isZipped()) {
603 if (params().noUnzip) {
604 // We don't know whether latex can actually handle
605 // this file, but we can't check, because that would
606 // mean to unzip the file and thereby making the
607 // noUnzip parameter meaningless.
608 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
610 FileName const bb_orig_file =
611 FileName(changeExtension(orig_file, "bb"));
612 if (runparams.nice) {
613 runparams.exportdata->addExternalFile(tex_format,
615 changeExtension(output_file, "bb"));
617 // LaTeX needs the bounding box file in the
620 FileName(changeExtension(temp_file.absFilename(), "bb"));
621 boost::tie(status, bb_file) =
622 copyFileIfNeeded(bb_orig_file, bb_file);
623 if (status == FAILURE)
625 runparams.exportdata->addExternalFile(tex_format,
628 runparams.exportdata->addExternalFile(tex_format,
629 source_file, output_file);
630 runparams.exportdata->addExternalFile("dvi",
631 source_file, output_file);
632 // We can't strip the extension, because we don't know
633 // the unzipped file format
634 return latex_path(output_file, EXCLUDE_EXTENSION);
637 FileName const unzipped_temp_file =
638 FileName(unzippedFileName(temp_file.absFilename()));
639 output_file = unzippedFileName(output_file);
640 source_file = FileName(unzippedFileName(source_file.absFilename()));
641 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
642 // temp_file has been unzipped already and
643 // orig_file has not changed in the meantime.
644 temp_file = unzipped_temp_file;
645 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
647 // unzipped_temp_file does not exist or is too old
648 temp_file = unzipFile(temp_file);
649 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
653 string const from = formats.getFormatFromFile(temp_file);
655 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
657 string const to = findTargetFormat(from, runparams);
658 string const ext = formats.extension(to);
659 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
661 // We're going to be running the exported buffer through the LaTeX
662 // compiler, so must ensure that LaTeX can cope with the graphics
665 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
668 if (!runparams.nice && !FileName(temp_file).hasExtension(ext)) {
669 // The LaTeX compiler will not be able to determine
670 // the file format from the extension, so we must
672 FileName const new_file =
673 FileName(changeExtension(temp_file.absFilename(), ext));
674 if (temp_file.moveTo(new_file)) {
675 temp_file = new_file;
676 output_file = changeExtension(output_file, ext);
678 FileName(changeExtension(source_file.absFilename(), ext));
680 LYXERR(Debug::GRAPHICS, "Could not rename file `"
681 << temp_file << "' to `" << new_file << "'.");
684 // The extension of temp_file might be != ext!
685 runparams.exportdata->addExternalFile(tex_format, source_file,
687 runparams.exportdata->addExternalFile("dvi", source_file,
689 return stripExtensionIfPossible(output_file, to, runparams.nice);
692 FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
693 string const output_to_file = changeExtension(output_file, ext);
695 // Do we need to perform the conversion?
696 // Yes if to_file does not exist or if temp_file is newer than to_file
697 if (compare_timestamps(temp_file, to_file) < 0) {
699 LYXERR(Debug::GRAPHICS,
700 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
701 from_utf8(rel_file))));
702 runparams.exportdata->addExternalFile(tex_format, to_file,
704 runparams.exportdata->addExternalFile("dvi", to_file,
706 return stripExtensionIfPossible(output_to_file, runparams.nice);
709 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
710 << "\tA copy has been made and convert is to be called with:\n"
711 << "\tfile to convert = " << temp_file << '\n'
712 << "\t from " << from << " to " << to);
714 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
716 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
718 Converters::try_default | Converters::try_cache)) {
719 runparams.exportdata->addExternalFile(tex_format,
720 to_file, output_to_file);
721 runparams.exportdata->addExternalFile("dvi",
722 to_file, output_to_file);
725 return stripExtensionIfPossible(output_to_file, runparams.nice);
729 int InsetGraphics::latex(odocstream & os,
730 OutputParams const & runparams) const
732 // If there is no file specified or not existing,
733 // just output a message about it in the latex output.
734 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
735 << params().filename.absFilename());
737 bool const file_exists = !params().filename.empty()
738 && params().filename.isReadableFile();
739 string const message = file_exists ?
740 string() : string("bb = 0 0 200 100, draft, type=eps");
741 // if !message.empty() then there was no existing file
742 // "filename" found. In this case LaTeX
743 // draws only a rectangle with the above bb and the
744 // not found filename in it.
745 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
747 // These variables collect all the latex code that should be before and
748 // after the actual includegraphics command.
752 if (runparams.moving_arg)
753 before += "\\protect";
755 // We never use the starred form, we use the "clip" option instead.
756 before += "\\includegraphics";
758 // Write the options if there are any.
759 string const opts = createLatexOptions();
760 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
762 if (!opts.empty() && !message.empty())
763 before += ('[' + opts + ',' + message + ']');
764 else if (!opts.empty() || !message.empty())
765 before += ('[' + opts + message + ']');
767 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
769 string latex_str = before + '{';
770 // Convert the file if necessary.
771 // Remove the extension so LaTeX will use whatever is appropriate
772 // (when there are several versions in different formats)
773 latex_str += prepareFile(runparams);
774 latex_str += '}' + after;
776 os << from_utf8(latex_str);
778 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
779 // Return how many newlines we issued.
780 return int(count(latex_str.begin(), latex_str.end(),'\n'));
784 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
786 // No graphics in ascii output. Possible to use gifscii to convert
787 // images to ascii approximation.
788 // 1. Convert file to ascii using gifscii
789 // 2. Read ascii output file and add it to the output stream.
790 // at least we send the filename
792 // FIXME: We have no idea what the encoding of the filename is
794 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
795 from_utf8(params().filename.absFilename()));
796 os << '<' << str << '>';
798 return 2 + str.size();
802 static int writeImageObject(char const * format, odocstream & os,
803 OutputParams const & runparams, docstring const & graphic_label,
804 docstring const & attributes)
806 if (runparams.flavor != OutputParams::XML)
807 os << "<![ %output.print." << format
810 os <<"<imageobject><imagedata fileref=\"&"
817 if (runparams.flavor == OutputParams::XML)
818 os << " role=\"" << format << "\"/>" ;
820 os << " format=\"" << format << "\">" ;
822 os << "</imageobject>";
824 if (runparams.flavor != OutputParams::XML)
825 os << endl << "]]>" ;
827 return runparams.flavor == OutputParams::XML ? 0 : 2;
831 // For explanation on inserting graphics into DocBook checkout:
832 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
833 // See also the docbook guide at http://www.docbook.org/
834 int InsetGraphics::docbook(odocstream & os,
835 OutputParams const & runparams) const
837 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
838 // need to switch to MediaObject. However, for now this is sufficient and
840 if (runparams.flavor == OutputParams::XML)
841 runparams.exportdata->addExternalFile("docbook-xml",
844 runparams.exportdata->addExternalFile("docbook",
847 os << "<inlinemediaobject>";
850 docstring attributes = createDocBookAttributes();
851 r += writeImageObject("png", os, runparams, graphic_label, attributes);
852 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
853 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
854 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
856 os << "</inlinemediaobject>";
861 void InsetGraphics::validate(LaTeXFeatures & features) const
863 // If we have no image, we should not require anything.
864 if (params().filename.empty())
867 features.includeFile(graphic_label,
868 removeExtension(params().filename.absFilename()));
870 features.require("graphicx");
872 if (features.runparams().nice) {
873 Buffer const * masterBuffer = features.buffer().masterBuffer();
874 string const rel_file = removeExtension(
875 params().filename.relFilename(masterBuffer->filePath()));
876 if (contains(rel_file, "."))
877 features.require("lyxdot");
882 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
884 // If nothing is changed, just return and say so.
885 if (params() == p && !p.filename.empty())
888 // Copy the new parameters.
891 // Update the display using the new parameters.
892 graphic_->update(params().as_grfxParams());
894 // We have changed data, report it.
899 InsetGraphicsParams const & InsetGraphics::params() const
905 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
906 Buffer const & buffer) const
908 formats.edit(buffer, p.filename,
909 formats.getFormatFromFile(p.filename));
913 void InsetGraphics::addToToc(DocIterator const & cpit)
915 TocBackend & backend = buffer().tocBackend();
918 docstring const str = from_utf8(params_.filename.onlyFileName());
919 backend.toc("graphics").push_back(TocItem(cpit, 0, str));
923 docstring InsetGraphics::contextMenu(BufferView const &, int, int) const
925 return from_ascii("context-graphics");
929 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
930 InsetGraphicsParams & params)
935 istringstream data(in);
938 lex.setContext("InsetGraphics::string2params");
940 params = InsetGraphicsParams();
941 readInsetGraphics(lex, buffer.filePath(), params);
945 string InsetGraphics::params2string(InsetGraphicsParams const & params,
946 Buffer const & buffer)
949 data << "graphics" << ' ';
950 params.Write(data, buffer);
951 data << "\\end_inset\n";
957 void getGraphicsGroups(Buffer const & b, set<string> & ids)
959 Inset & inset = b.inset();
960 InsetIterator it = inset_iterator_begin(inset);
961 InsetIterator const end = inset_iterator_end(inset);
962 for (; it != end; ++it)
963 if (it->lyxCode() == GRAPHICS_CODE) {
964 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
965 InsetGraphicsParams inspar = ins.getParams();
966 if (!inspar.groupId.empty())
967 ids.insert(inspar.groupId);
972 int countGroupMembers(Buffer const & b, string const & groupId)
977 Inset & inset = b.inset();
978 InsetIterator it = inset_iterator_begin(inset);
979 InsetIterator const end = inset_iterator_end(inset);
980 for (; it != end; ++it)
981 if (it->lyxCode() == GRAPHICS_CODE) {
982 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
983 if (ins.getParams().groupId == groupId)
990 string getGroupParams(Buffer const & b, string const & groupId)
994 Inset & inset = b.inset();
995 InsetIterator it = inset_iterator_begin(inset);
996 InsetIterator const end = inset_iterator_end(inset);
997 for (; it != end; ++it)
998 if (it->lyxCode() == GRAPHICS_CODE) {
999 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1000 InsetGraphicsParams inspar = ins.getParams();
1001 if (inspar.groupId == groupId) {
1002 InsetGraphicsParams tmp = inspar;
1003 tmp.filename.erase();
1004 return InsetGraphics::params2string(tmp, b);
1011 void unifyGraphicsGroups(Buffer & b, string const & argument)
1013 InsetGraphicsParams params;
1014 InsetGraphics::string2params(argument, b, params);
1016 b.undo().beginUndoGroup();
1017 Inset & inset = b.inset();
1018 InsetIterator it = inset_iterator_begin(inset);
1019 InsetIterator const end = inset_iterator_end(inset);
1020 for (; it != end; ++it) {
1021 if (it->lyxCode() == GRAPHICS_CODE) {
1022 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1023 InsetGraphicsParams inspar = ins.getParams();
1024 if (params.groupId == inspar.groupId) {
1025 b.undo().recordUndo(it);
1026 params.filename = inspar.filename;
1027 ins.setParams(params);
1031 b.undo().endUndoGroup();
1035 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1037 Inset * instmp = &cur.inset();
1038 if (instmp->lyxCode() != GRAPHICS_CODE)
1039 instmp = cur.nextInset();
1040 if (!instmp || instmp->lyxCode() != GRAPHICS_CODE)
1043 return static_cast<InsetGraphics *>(instmp);
1046 } // namespace graphics