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"
69 #include "output_xhtml.h"
71 #include "texstream.h"
72 #include "TocBackend.h"
74 #include "frontends/alert.h"
75 #include "frontends/Application.h"
77 #include "support/convert.h"
78 #include "support/debug.h"
79 #include "support/docstream.h"
80 #include "support/ExceptionMessage.h"
81 #include "support/filetools.h"
82 #include "support/gettext.h"
83 #include "support/lyxlib.h"
84 #include "support/lstrings.h"
85 #include "support/os.h"
86 #include "support/Systemcall.h"
93 using namespace lyx::support;
97 namespace Alert = frontend::Alert;
101 /// Find the most suitable image format for images in \p format
102 /// Note that \p format may be unknown (i. e. an empty string)
103 string findTargetFormat(string const & format, OutputParams const & runparams)
105 // Are we using latex or XeTeX/LuaTeX/pdflatex?
106 if (runparams.flavor == OutputParams::PDFLATEX
107 || runparams.flavor == OutputParams::XETEX
108 || runparams.flavor == OutputParams::LUATEX) {
109 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
110 Format const * const f = formats.getFormat(format);
111 // Convert vector graphics to pdf
112 if (f && f->vectorFormat())
114 // pdflatex can use jpeg, png and pdf directly
117 // Convert everything else to png
120 // for HTML, we leave the known formats and otherwise convert to png
121 if (runparams.flavor == OutputParams::HTML) {
122 Format const * const f = formats.getFormat(format);
123 // Convert vector graphics to svg
124 if (f && f->vectorFormat() && theConverters().isReachable(format, "svg"))
126 // Leave the known formats alone
127 if (format == "jpg" || format == "png" || format == "gif")
129 // Convert everything else to png
132 // If it's postscript, we always do eps.
133 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
135 // any other than ps is changed to eps
142 void readInsetGraphics(Lexer & lex, Buffer const & buf, bool allowOrigin,
143 InsetGraphicsParams & params)
145 bool finished = false;
147 while (lex.isOK() && !finished) {
150 string const token = lex.getString();
151 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
156 if (token == "\\end_inset") {
159 if (!params.Read(lex, token, buf, allowOrigin))
160 lyxerr << "Unknown token, "
171 InsetGraphics::InsetGraphics(Buffer * buf)
172 : Inset(buf), graphic_label(sgml::uniqueID(from_ascii("graph"))),
173 graphic_(new RenderGraphic(this))
178 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
180 graphic_label(sgml::uniqueID(from_ascii("graph"))),
181 graphic_(new RenderGraphic(*ig.graphic_, this))
183 setParams(ig.params());
187 Inset * InsetGraphics::clone() const
189 return new InsetGraphics(*this);
193 InsetGraphics::~InsetGraphics()
195 hideDialogs("graphics", this);
200 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
202 switch (cmd.action()) {
203 case LFUN_INSET_EDIT: {
204 InsetGraphicsParams p = params();
205 if (!cmd.argument().empty())
206 string2params(to_utf8(cmd.argument()), buffer(), p);
211 case LFUN_INSET_MODIFY: {
212 if (cmd.getArg(0) != "graphics") {
213 Inset::doDispatch(cur, cmd);
217 InsetGraphicsParams p;
218 string2params(to_utf8(cmd.argument()), buffer(), p);
219 if (p.filename.empty()) {
220 cur.noScreenUpdate();
226 // if the inset is part of a graphics group, all the
227 // other members should be updated too.
228 if (!params_.groupId.empty())
229 graphics::unifyGraphicsGroups(buffer(),
230 to_utf8(cmd.argument()));
234 case LFUN_INSET_DIALOG_UPDATE:
235 cur.bv().updateDialog("graphics", params2string(params(), buffer()));
238 case LFUN_GRAPHICS_RELOAD:
239 params_.filename.refresh();
244 Inset::doDispatch(cur, cmd);
250 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
251 FuncStatus & flag) const
253 switch (cmd.action()) {
254 case LFUN_INSET_MODIFY:
255 if (cmd.getArg(0) != "graphics")
256 return Inset::getStatus(cur, cmd, flag);
258 case LFUN_INSET_EDIT:
259 case LFUN_INSET_DIALOG_UPDATE:
260 case LFUN_GRAPHICS_RELOAD:
261 flag.setEnabled(true);
265 return Inset::getStatus(cur, cmd, flag);
270 bool InsetGraphics::showInsetDialog(BufferView * bv) const
272 bv->showDialog("graphics", params2string(params(), bv->buffer()),
273 const_cast<InsetGraphics *>(this));
279 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
281 graphic_->metrics(mi, dim);
285 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
287 graphic_->draw(pi, x, y);
291 void InsetGraphics::write(ostream & os) const
294 params().Write(os, buffer());
298 void InsetGraphics::read(Lexer & lex)
300 lex.setContext("InsetGraphics::read");
302 readInsetGraphics(lex, buffer(), true, params_);
303 graphic_->update(params().as_grfxParams());
307 string InsetGraphics::createLatexOptions() const
309 // Calculate the options part of the command, we must do it to a string
310 // stream since we might have a trailing comma that we would like to remove
311 // before writing it to the output stream.
312 ostringstream options;
313 if (!params().bbox.empty())
314 options << "bb=" << params().bbox.xl.asLatexString() << ' '
315 << params().bbox.yb.asLatexString() << ' '
316 << params().bbox.xr.asLatexString() << ' '
317 << params().bbox.yt.asLatexString() << ',';
323 double const scl = convert<double>(params().scale);
324 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
325 if (!float_equal(scl, 100.0, 0.05))
326 size << "scale=" << scl / 100.0 << ',';
328 if (!params().width.zero())
329 size << "width=" << params().width.asLatexString() << ',';
330 if (!params().height.zero())
331 size << "height=" << params().height.asLatexString() << ',';
332 if (params().keepAspectRatio)
333 size << "keepaspectratio,";
335 if (params().scaleBeforeRotation && !size.str().empty())
336 options << size.str();
338 // Make sure rotation angle is not very close to zero;
339 // a float can be effectively zero but not exactly zero.
340 if (!params().rotateAngle.empty()
341 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
342 options << "angle=" << params().rotateAngle << ',';
343 if (!params().rotateOrigin.empty()) {
344 options << "origin=" << params().rotateOrigin[0];
345 if (contains(params().rotateOrigin,"Top"))
347 else if (contains(params().rotateOrigin,"Bottom"))
349 else if (contains(params().rotateOrigin,"Baseline"))
354 if (!params().scaleBeforeRotation && !size.str().empty())
355 options << size.str();
357 if (!params().special.empty())
358 options << params().special << ',';
360 string opts = options.str();
362 if (suffixIs(opts, ','))
363 opts = opts.substr(0, opts.size() - 1);
369 docstring InsetGraphics::toDocbookLength(Length const & len) const
371 odocstringstream result;
372 switch (len.unit()) {
373 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
374 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
376 case Length::PT: // Point = 1/72.27in = 0.351mm
377 result << len.value() * 72 / 72.27 << "pt";
379 case Length::BP: // Big point (72bp = 1in), also PostScript point
380 result << len.value() << "pt";
382 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
383 result << len.value() * 0.376 << "mm";
385 case Length::MM: // Millimeter = 2.845pt
386 result << len.value() << "mm";
388 case Length::PC: // Pica = 12pt = 4.218mm
389 result << len.value() << "pc";
391 case Length::CC: // Cicero = 12dd = 4.531mm
392 result << len.value() * 4.531 << "mm";
394 case Length::CM: // Centimeter = 10mm = 2.371pc
395 result << len.value() << "cm";
397 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
398 result << len.value() << "in";
400 case Length::EX: // Height of a small "x" for the current font.
401 // Obviously we have to compromise here. Any better ratio than 1.5 ?
402 result << len.value() / 1.5 << "em";
404 case Length::EM: // Width of capital "M" in current font.
405 result << len.value() << "em";
407 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
408 result << len.value() * 18 << "em";
410 case Length::PTW: // Percent of TextWidth
411 case Length::PCW: // Percent of ColumnWidth
412 case Length::PPW: // Percent of PageWidth
413 case Length::PLW: // Percent of LineWidth
414 case Length::PTH: // Percent of TextHeight
415 case Length::PPH: // Percent of PaperHeight
416 // Sigh, this will go wrong.
417 result << len.value() << "%";
420 result << len.asDocstring();
427 docstring InsetGraphics::createDocBookAttributes() const
429 // Calculate the options part of the command, we must do it to a string
430 // stream since we copied the code from createLatexParams() ;-)
432 // FIXME: av: need to translate spec -> Docbook XSL spec
433 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
434 // Right now it only works with my version of db2latex :-)
436 odocstringstream options;
437 double const scl = convert<double>(params().scale);
438 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
439 if (!float_equal(scl, 100.0, 0.05))
440 options << " scale=\""
441 << support::iround(scl)
444 if (!params().width.zero()) {
445 options << " width=\"" << toDocbookLength(params().width) << "\" ";
447 if (!params().height.zero()) {
448 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
450 if (params().keepAspectRatio) {
451 // This will be irrelevant unless both width and height are set
452 options << "scalefit=\"1\" ";
457 if (!params().special.empty())
458 options << from_ascii(params().special) << " ";
460 // trailing blanks are ok ...
461 return options.str();
467 enum GraphicsCopyStatus {
475 pair<GraphicsCopyStatus, FileName> const
476 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
478 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
479 unsigned long const checksum_in = file_in.checksum();
480 unsigned long const checksum_out = file_out.checksum();
482 if (checksum_in == checksum_out)
484 return make_pair(IDENTICAL_CONTENTS, file_out);
486 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
487 bool const success = mover.copy(file_in, file_out);
490 LYXERR(Debug::GRAPHICS,
491 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
492 "into the temporary directory."),
493 from_utf8(file_in.absFileName()))));
496 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
497 return make_pair(status, file_out);
501 pair<GraphicsCopyStatus, FileName> const
502 copyToDirIfNeeded(DocFileName const & file, string const & dir)
504 string const file_in = file.absFileName();
505 string const only_path = onlyPath(file_in);
506 if (rtrim(only_path, "/") == rtrim(dir, "/"))
507 return make_pair(IDENTICAL_PATHS, FileName(file_in));
509 string mangled = file.mangledFileName();
510 if (formats.isZippedFile(file)) {
511 // We need to change _eps.gz to .eps.gz. The mangled name is
512 // still unique because of the counter in mangledFileName().
513 // We can't just call mangledFileName() with the zip
514 // extension removed, because base.eps and base.eps.gz may
515 // have different content but would get the same mangled
516 // name in this case.
517 string const base = removeExtension(file.unzippedFileName());
518 string::size_type const ext_len = file_in.length() - base.length();
519 mangled[mangled.length() - ext_len] = '.';
521 FileName const file_out(makeAbsPath(mangled, dir));
523 return copyFileIfNeeded(file, file_out);
527 string const stripExtensionIfPossible(string const & file, bool nice)
529 // Remove the extension so the LaTeX compiler will use whatever
530 // is appropriate (when there are several versions in different
532 // Do this only if we are not exporting for internal usage, because
533 // pdflatex prefers png over pdf and it would pick up the png images
534 // that we generate for preview.
535 // This works only if the filename contains no dots besides
536 // the just removed one. We can fool here by replacing all
537 // dots with a macro whose definition is just a dot ;-)
538 // The automatic format selection does not work if the file
540 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
541 if (!nice || contains(latex_name, '"'))
543 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
547 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
549 // No conversion is needed. LaTeX can handle the graphic file as is.
550 // This is true even if the orig_file is compressed.
551 string const to_format = formats.getFormat(to)->extension();
552 string const file_format = getExtension(file);
553 // for latex .ps == .eps
554 if (to_format == file_format ||
555 (to_format == "eps" && file_format == "ps") ||
556 (to_format == "ps" && file_format == "eps"))
557 return stripExtensionIfPossible(file, nice);
558 return latex_path(file, EXCLUDE_EXTENSION);
564 string InsetGraphics::prepareFile(OutputParams const & runparams) const
566 // The following code depends on non-empty filenames
567 if (params().filename.empty())
570 string const orig_file = params().filename.absFileName();
571 // this is for dryrun and display purposes, do not use latexFilename
572 string const rel_file = params().filename.relFileName(buffer().filePath());
574 // previewing source code, no file copying or file format conversion
575 if (runparams.dryrun)
576 return stripExtensionIfPossible(rel_file, runparams.nice);
578 // The master buffer. This is useful when there are multiple levels
580 Buffer const * masterBuffer = buffer().masterBuffer();
582 // Return the output name if we are inside a comment or the file does
584 // We are not going to change the extension or using the name of the
585 // temporary file, the code is already complicated enough.
586 if (runparams.inComment || !params().filename.isReadableFile())
587 return params().filename.outputFileName(masterBuffer->filePath());
589 // We place all temporary files in the master buffer's temp dir.
590 // This is possible because we use mangled file names.
591 // This is necessary for DVI export.
592 string const temp_path = masterBuffer->temppath();
594 // temp_file will contain the file for LaTeX to act on if, for example,
595 // we move it to a temp dir or uncompress it.
597 GraphicsCopyStatus status;
598 tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
600 if (status == FAILURE)
603 // a relative filename should be relative to the master buffer.
604 // "nice" means that the buffer is exported to LaTeX format but not
605 // run through the LaTeX compiler.
606 string output_file = runparams.nice ?
607 params().filename.outputFileName(masterBuffer->filePath()) :
608 onlyFileName(temp_file.absFileName());
610 if (runparams.nice) {
611 if (!isValidLaTeXFileName(output_file)) {
612 frontend::Alert::warning(_("Invalid filename"),
613 _("The following filename will cause troubles "
614 "when running the exported file through LaTeX: ") +
615 from_utf8(output_file));
617 // only show DVI-specific warning when export format is plain latex
618 if (!isValidDVIFileName(output_file)
619 && runparams.flavor == OutputParams::LATEX) {
620 frontend::Alert::warning(_("Problematic filename for DVI"),
621 _("The following filename can cause troubles "
622 "when running the exported file through LaTeX "
623 "and opening the resulting DVI: ") +
624 from_utf8(output_file), true);
628 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
629 // determine the export format
630 string const tex_format = flavor2format(runparams.flavor);
632 if (formats.isZippedFile(params().filename)) {
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 // source and destination formats are the same
665 if (!runparams.nice && !FileName(temp_file).hasExtension(ext)) {
666 // The LaTeX compiler will not be able to determine
667 // the file format from the extension, so we must
669 FileName const new_file =
670 FileName(changeExtension(temp_file.absFileName(), ext));
671 if (temp_file.moveTo(new_file)) {
672 temp_file = new_file;
673 output_file = changeExtension(output_file, ext);
675 FileName(changeExtension(source_file.absFileName(), ext));
677 LYXERR(Debug::GRAPHICS, "Could not rename file `"
678 << temp_file << "' to `" << new_file << "'.");
681 // The extension of temp_file might be != ext!
682 runparams.exportdata->addExternalFile(tex_format, source_file,
684 runparams.exportdata->addExternalFile("dvi", source_file,
686 return stripExtensionIfPossible(output_file, to, runparams.nice);
689 // so the source and destination formats are different
690 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
691 string const output_to_file = changeExtension(output_file, ext);
693 // Do we need to perform the conversion?
694 // Yes if to_file does not exist or if temp_file is newer than to_file
695 if (compare_timestamps(temp_file, to_file) < 0) {
697 LYXERR(Debug::GRAPHICS,
698 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
699 from_utf8(rel_file))));
700 runparams.exportdata->addExternalFile(tex_format, to_file,
702 runparams.exportdata->addExternalFile("dvi", to_file,
704 return stripExtensionIfPossible(output_to_file, runparams.nice);
707 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
708 << "\tA copy has been made and convert is to be called with:\n"
709 << "\tfile to convert = " << temp_file << '\n'
710 << "\t from " << from << " to " << to);
712 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
714 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
716 Converters::try_default | Converters::try_cache)) {
717 runparams.exportdata->addExternalFile(tex_format,
718 to_file, output_to_file);
719 runparams.exportdata->addExternalFile("dvi",
720 to_file, output_to_file);
723 return stripExtensionIfPossible(output_to_file, runparams.nice);
727 void InsetGraphics::latex(otexstream & os,
728 OutputParams const & runparams) const
730 // If there is no file specified or not existing,
731 // just output a message about it in the latex output.
732 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
733 << params().filename.absFileName());
735 bool const file_exists = !params().filename.empty()
736 && params().filename.isReadableFile();
739 if (params().bbox.empty())
740 message = "bb = 0 0 200 100";
741 if (!params().draft) {
742 if (!message.empty())
746 if (!message.empty())
748 message += "type=eps";
750 // If no existing file "filename" was found LaTeX
751 // draws only a rectangle with the above bb and the
752 // not found filename in it.
753 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
755 // These variables collect all the latex code that should be before and
756 // after the actual includegraphics command.
760 if (runparams.moving_arg)
761 before += "\\protect";
763 // We never use the starred form, we use the "clip" option instead.
764 before += "\\includegraphics";
766 // Write the options if there are any.
767 string const opts = createLatexOptions();
768 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
770 if (!opts.empty() && !message.empty())
771 before += ('[' + opts + ',' + message + ']');
772 else if (!opts.empty() || !message.empty())
773 before += ('[' + opts + message + ']');
775 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
777 string latex_str = before + '{';
778 // Convert the file if necessary.
779 // Remove the extension so LaTeX will use whatever is appropriate
780 // (when there are several versions in different formats)
781 string file_path = prepareFile(runparams);
782 latex_str += file_path;
783 latex_str += '}' + after;
785 os << from_utf8(latex_str);
787 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
791 int InsetGraphics::plaintext(odocstringstream & os,
792 OutputParams const &, size_t) const
794 // No graphics in ascii output. Possible to use gifscii to convert
795 // images to ascii approximation.
796 // 1. Convert file to ascii using gifscii
797 // 2. Read ascii output file and add it to the output stream.
798 // at least we send the filename
800 // FIXME: We have no idea what the encoding of the filename is
802 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
803 from_utf8(params().filename.absFileName()));
804 os << '<' << str << '>';
806 return 2 + str.size();
810 static int writeImageObject(char const * format, odocstream & os,
811 OutputParams const & runparams, docstring const & graphic_label,
812 docstring const & attributes)
814 if (runparams.flavor != OutputParams::XML)
815 os << "<![ %output.print." << format
818 os <<"<imageobject><imagedata fileref=\"&"
825 if (runparams.flavor == OutputParams::XML)
826 os << " role=\"" << format << "\"/>" ;
828 os << " format=\"" << format << "\">" ;
830 os << "</imageobject>";
832 if (runparams.flavor != OutputParams::XML)
833 os << endl << "]]>" ;
835 return runparams.flavor == OutputParams::XML ? 0 : 2;
839 // For explanation on inserting graphics into DocBook checkout:
840 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
841 // See also the docbook guide at http://www.docbook.org/
842 int InsetGraphics::docbook(odocstream & os,
843 OutputParams const & runparams) const
845 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
846 // need to switch to MediaObject. However, for now this is sufficient and
848 if (runparams.flavor == OutputParams::XML)
849 runparams.exportdata->addExternalFile("docbook-xml",
852 runparams.exportdata->addExternalFile("docbook",
855 os << "<inlinemediaobject>";
858 docstring attributes = createDocBookAttributes();
859 r += writeImageObject("png", os, runparams, graphic_label, attributes);
860 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
861 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
862 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
864 os << "</inlinemediaobject>";
869 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
871 // The following code depends on non-empty filenames
872 if (params().filename.empty())
875 string const orig_file = params().filename.absFileName();
877 // The master buffer. This is useful when there are multiple levels
879 Buffer const * masterBuffer = buffer().masterBuffer();
881 if (!params().filename.isReadableFile())
884 // We place all temporary files in the master buffer's temp dir.
885 // This is possible because we use mangled file names.
886 // FIXME We may want to put these files in some special temporary
888 string const temp_path = masterBuffer->temppath();
890 // Copy to temporary directory.
892 GraphicsCopyStatus status;
893 tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
895 if (status == FAILURE)
898 string output_file = onlyFileName(temp_file.absFileName());
900 string const from = formats.getFormatFromFile(temp_file);
902 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
904 string const to = findTargetFormat(from, runparams);
905 string const ext = formats.extension(to);
906 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
907 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
910 // source and destination formats are the same
911 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
915 // so the source and destination formats are different
916 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
917 string const output_to_file = changeExtension(output_file, ext);
919 // Do we need to perform the conversion?
920 // Yes if to_file does not exist or if temp_file is newer than to_file
921 if (compare_timestamps(temp_file, to_file) < 0) {
923 LYXERR(Debug::GRAPHICS,
924 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
925 from_utf8(orig_file))));
926 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
927 return output_to_file;
930 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
931 << "\tA copy has been made and convert is to be called with:\n"
932 << "\tfile to convert = " << temp_file << '\n'
933 << "\t from " << from << " to " << to);
935 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
938 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
939 from, to, el, Converters::try_default | Converters::try_cache);
942 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
943 return output_to_file;
947 docstring InsetGraphics::xhtml(XHTMLStream & xs, OutputParams const & op) const
949 string const output_file = prepareHTMLFile(op);
951 if (output_file.empty()) {
952 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
953 << params().filename << "' for output. File missing?");
954 string const attr = "src='" + params().filename.absFileName()
955 + "' alt='image: " + output_file + "'";
956 xs << html::CompTag("img", attr);
961 // We aren't doing anything with the crop and rotate parameters, and it would
962 // really be better to do width and height conversion, rather than to output
963 // these parameters here.
965 if (!params().width.zero())
966 imgstyle += "width:" + params().width.asHTMLString() + ";";
967 if (!params().height.zero())
968 imgstyle += " height:" + params().height.asHTMLString() + ";";
969 if (!imgstyle.empty())
970 imgstyle = "style='" + imgstyle + "' ";
972 string const attr = imgstyle + "src='" + output_file + "' alt='image: "
974 xs << html::CompTag("img", attr);
979 void InsetGraphics::validate(LaTeXFeatures & features) const
981 // If we have no image, we should not require anything.
982 if (params().filename.empty())
985 features.includeFile(graphic_label,
986 removeExtension(params().filename.absFileName()));
988 features.require("graphicx");
990 if (features.runparams().nice) {
991 string const rel_file = params().filename.onlyFileNameWithoutExt();
992 if (contains(rel_file, "."))
993 features.require("lyxdot");
998 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1000 // If nothing is changed, just return and say so.
1001 if (params() == p && !p.filename.empty())
1004 // Copy the new parameters.
1007 // Update the display using the new parameters.
1008 graphic_->update(params().as_grfxParams());
1010 // We have changed data, report it.
1015 InsetGraphicsParams const & InsetGraphics::params() const
1021 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1023 formats.edit(buffer(), p.filename,
1024 formats.getFormatFromFile(p.filename));
1028 void InsetGraphics::addToToc(DocIterator const & cpit, bool output_active,
1032 docstring const str = from_utf8(params_.filename.onlyFileName());
1033 buffer().tocBackend().toc("graphics")->push_back(TocItem(cpit, 0, str, output_active));
1037 string InsetGraphics::contextMenuName() const
1039 return "context-graphics";
1043 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1044 InsetGraphicsParams & params)
1049 istringstream data(in);
1051 lex.setStream(data);
1052 lex.setContext("InsetGraphics::string2params");
1054 params = InsetGraphicsParams();
1055 readInsetGraphics(lex, buffer, false, params);
1059 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1060 Buffer const & buffer)
1063 data << "graphics" << ' ';
1064 params.Write(data, buffer);
1065 data << "\\end_inset\n";
1070 docstring InsetGraphics::toolTip(BufferView const &, int, int) const
1072 return from_utf8(params().filename.onlyFileName());
1075 namespace graphics {
1077 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1079 Inset & inset = b.inset();
1080 InsetIterator it = inset_iterator_begin(inset);
1081 InsetIterator const end = inset_iterator_end(inset);
1082 for (; it != end; ++it)
1083 if (it->lyxCode() == GRAPHICS_CODE) {
1084 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1085 InsetGraphicsParams inspar = ins.getParams();
1086 if (!inspar.groupId.empty())
1087 ids.insert(inspar.groupId);
1092 int countGroupMembers(Buffer const & b, string const & groupId)
1095 if (groupId.empty())
1097 Inset & inset = b.inset();
1098 InsetIterator it = inset_iterator_begin(inset);
1099 InsetIterator const end = inset_iterator_end(inset);
1100 for (; it != end; ++it)
1101 if (it->lyxCode() == GRAPHICS_CODE) {
1102 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1103 if (ins.getParams().groupId == groupId)
1110 string getGroupParams(Buffer const & b, string const & groupId)
1112 if (groupId.empty())
1114 Inset & inset = b.inset();
1115 InsetIterator it = inset_iterator_begin(inset);
1116 InsetIterator const end = inset_iterator_end(inset);
1117 for (; it != end; ++it)
1118 if (it->lyxCode() == GRAPHICS_CODE) {
1119 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1120 InsetGraphicsParams inspar = ins.getParams();
1121 if (inspar.groupId == groupId) {
1122 InsetGraphicsParams tmp = inspar;
1123 tmp.filename.erase();
1124 return InsetGraphics::params2string(tmp, b);
1131 void unifyGraphicsGroups(Buffer & b, string const & argument)
1133 InsetGraphicsParams params;
1134 InsetGraphics::string2params(argument, b, params);
1136 b.undo().beginUndoGroup();
1137 Inset & inset = b.inset();
1138 InsetIterator it = inset_iterator_begin(inset);
1139 InsetIterator const end = inset_iterator_end(inset);
1140 for (; it != end; ++it) {
1141 if (it->lyxCode() == GRAPHICS_CODE) {
1142 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1143 InsetGraphicsParams inspar = ins.getParams();
1144 if (params.groupId == inspar.groupId) {
1145 b.undo().recordUndo(CursorData(it));
1146 params.filename = inspar.filename;
1147 ins.setParams(params);
1151 b.undo().endUndoGroup();
1155 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1157 Inset * instmp = &cur.inset();
1158 if (instmp->lyxCode() != GRAPHICS_CODE)
1159 instmp = cur.nextInset();
1160 if (!instmp || instmp->lyxCode() != GRAPHICS_CODE)
1163 return static_cast<InsetGraphics *>(instmp);
1166 } // namespace graphics