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 "TocBackend.h"
73 #include "frontends/alert.h"
74 #include "frontends/Application.h"
76 #include "support/convert.h"
77 #include "support/debug.h"
78 #include "support/docstream.h"
79 #include "support/ExceptionMessage.h"
80 #include "support/filetools.h"
81 #include "support/gettext.h"
82 #include "support/lyxlib.h"
83 #include "support/lstrings.h"
84 #include "support/os.h"
85 #include "support/Systemcall.h"
87 #include <boost/tuple/tuple.hpp>
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/pdflatex?
106 if (runparams.flavor == OutputParams::PDFLATEX
107 || runparams.flavor == OutputParams::XETEX) {
108 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
109 Format const * const f = formats.getFormat(format);
110 // Convert vector graphics to pdf
111 if (f && f->vectorFormat())
113 // pdflatex can use jpeg, png and pdf directly
116 // Convert everything else to png
119 // for HTML, we leave the known formats and otherwise convert to png
120 if (runparams.flavor == OutputParams::HTML) {
121 if (format == "jpg" || format == "png" || format == "gif")
125 // If it's postscript, we always do eps.
126 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
128 // any other than ps is changed to eps
135 void readInsetGraphics(Lexer & lex, string const & bufpath,
136 InsetGraphicsParams & params)
138 bool finished = false;
140 while (lex.isOK() && !finished) {
143 string const token = lex.getString();
144 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
149 if (token == "\\end_inset") {
152 if (!params.Read(lex, token, bufpath))
153 lyxerr << "Unknown token, "
164 InsetGraphics::InsetGraphics(Buffer * buf)
165 : Inset(buf), graphic_label(sgml::uniqueID(from_ascii("graph"))),
166 graphic_(new RenderGraphic(this))
171 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
173 graphic_label(sgml::uniqueID(from_ascii("graph"))),
174 graphic_(new RenderGraphic(*ig.graphic_, this))
176 setParams(ig.params());
180 Inset * InsetGraphics::clone() const
182 return new InsetGraphics(*this);
186 InsetGraphics::~InsetGraphics()
188 hideDialogs("graphics", this);
193 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
195 switch (cmd.action()) {
196 case LFUN_INSET_EDIT: {
197 InsetGraphicsParams p = params();
198 if (!cmd.argument().empty())
199 string2params(to_utf8(cmd.argument()), buffer(), p);
204 case LFUN_INSET_MODIFY: {
205 InsetGraphicsParams p;
206 string2params(to_utf8(cmd.argument()), buffer(), p);
207 if (p.filename.empty()) {
213 // if the inset is part of a graphics group, all the
214 // other members should be updated too.
215 if (!params_.groupId.empty())
216 graphics::unifyGraphicsGroups(buffer(),
217 to_utf8(cmd.argument()));
221 case LFUN_INSET_DIALOG_UPDATE:
222 cur.bv().updateDialog("graphics", params2string(params(), buffer()));
225 case LFUN_GRAPHICS_RELOAD:
226 params_.filename.refresh();
231 Inset::doDispatch(cur, cmd);
237 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
238 FuncStatus & flag) const
240 switch (cmd.action()) {
241 case LFUN_INSET_EDIT:
242 case LFUN_INSET_MODIFY:
243 case LFUN_INSET_DIALOG_UPDATE:
244 case LFUN_GRAPHICS_RELOAD:
245 flag.setEnabled(true);
249 return Inset::getStatus(cur, cmd, flag);
254 bool InsetGraphics::showInsetDialog(BufferView * bv) const
256 bv->showDialog("graphics", params2string(params(), bv->buffer()),
257 const_cast<InsetGraphics *>(this));
263 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
265 graphic_->metrics(mi, dim);
269 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
271 graphic_->draw(pi, x, y);
275 void InsetGraphics::write(ostream & os) const
278 params().Write(os, buffer());
282 void InsetGraphics::read(Lexer & lex)
284 lex.setContext("InsetGraphics::read");
286 readInsetGraphics(lex, buffer().filePath(), params_);
287 graphic_->update(params().as_grfxParams());
291 string InsetGraphics::createLatexOptions() const
293 // Calculate the options part of the command, we must do it to a string
294 // stream since we might have a trailing comma that we would like to remove
295 // before writing it to the output stream.
296 ostringstream options;
297 if (!params().bb.empty())
298 options << "bb=" << rtrim(params().bb) << ',';
304 double const scl = convert<double>(params().scale);
305 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
306 if (!float_equal(scl, 100.0, 0.05))
307 size << "scale=" << scl / 100.0 << ',';
309 if (!params().width.zero())
310 size << "width=" << params().width.asLatexString() << ',';
311 if (!params().height.zero())
312 size << "height=" << params().height.asLatexString() << ',';
313 if (params().keepAspectRatio)
314 size << "keepaspectratio,";
316 if (params().scaleBeforeRotation && !size.str().empty())
317 options << size.str();
319 // Make sure rotation angle is not very close to zero;
320 // a float can be effectively zero but not exactly zero.
321 if (!params().rotateAngle.empty()
322 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
323 options << "angle=" << params().rotateAngle << ',';
324 if (!params().rotateOrigin.empty()) {
325 options << "origin=" << params().rotateOrigin[0];
326 if (contains(params().rotateOrigin,"Top"))
328 else if (contains(params().rotateOrigin,"Bottom"))
330 else if (contains(params().rotateOrigin,"Baseline"))
335 if (!params().scaleBeforeRotation && !size.str().empty())
336 options << size.str();
338 if (!params().special.empty())
339 options << params().special << ',';
341 string opts = options.str();
343 if (suffixIs(opts, ','))
344 opts = opts.substr(0, opts.size() - 1);
350 docstring InsetGraphics::toDocbookLength(Length const & len) const
352 odocstringstream result;
353 switch (len.unit()) {
354 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
355 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
357 case Length::PT: // Point = 1/72.27in = 0.351mm
358 result << len.value() * 72 / 72.27 << "pt";
360 case Length::BP: // Big point (72bp = 1in), also PostScript point
361 result << len.value() << "pt";
363 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
364 result << len.value() * 0.376 << "mm";
366 case Length::MM: // Millimeter = 2.845pt
367 result << len.value() << "mm";
369 case Length::PC: // Pica = 12pt = 4.218mm
370 result << len.value() << "pc";
372 case Length::CC: // Cicero = 12dd = 4.531mm
373 result << len.value() * 4.531 << "mm";
375 case Length::CM: // Centimeter = 10mm = 2.371pc
376 result << len.value() << "cm";
378 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
379 result << len.value() << "in";
381 case Length::EX: // Height of a small "x" for the current font.
382 // Obviously we have to compromise here. Any better ratio than 1.5 ?
383 result << len.value() / 1.5 << "em";
385 case Length::EM: // Width of capital "M" in current font.
386 result << len.value() << "em";
388 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
389 result << len.value() * 18 << "em";
391 case Length::PTW: // Percent of TextWidth
392 case Length::PCW: // Percent of ColumnWidth
393 case Length::PPW: // Percent of PageWidth
394 case Length::PLW: // Percent of LineWidth
395 case Length::PTH: // Percent of TextHeight
396 case Length::PPH: // Percent of Paper
397 // Sigh, this will go wrong.
398 result << len.value() << "%";
401 result << len.asDocstring();
408 docstring InsetGraphics::createDocBookAttributes() const
410 // Calculate the options part of the command, we must do it to a string
411 // stream since we copied the code from createLatexParams() ;-)
413 // FIXME: av: need to translate spec -> Docbook XSL spec
414 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
415 // Right now it only works with my version of db2latex :-)
417 odocstringstream options;
418 double const scl = convert<double>(params().scale);
419 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
420 if (!float_equal(scl, 100.0, 0.05))
421 options << " scale=\""
422 << static_cast<int>( (scl) + 0.5 )
425 if (!params().width.zero()) {
426 options << " width=\"" << toDocbookLength(params().width) << "\" ";
428 if (!params().height.zero()) {
429 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
431 if (params().keepAspectRatio) {
432 // This will be irrelevant unless both width and height are set
433 options << "scalefit=\"1\" ";
438 if (!params().special.empty())
439 options << from_ascii(params().special) << " ";
441 // trailing blanks are ok ...
442 return options.str();
448 enum GraphicsCopyStatus {
456 pair<GraphicsCopyStatus, FileName> const
457 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
459 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
460 unsigned long const checksum_in = file_in.checksum();
461 unsigned long const checksum_out = file_out.checksum();
463 if (checksum_in == checksum_out)
465 return make_pair(IDENTICAL_CONTENTS, file_out);
467 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
468 bool const success = mover.copy(file_in, file_out);
471 LYXERR(Debug::GRAPHICS,
472 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
473 "into the temporary directory."),
474 from_utf8(file_in.absFileName()))));
477 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
478 return make_pair(status, file_out);
482 pair<GraphicsCopyStatus, FileName> const
483 copyToDirIfNeeded(DocFileName const & file, string const & dir)
485 string const file_in = file.absFileName();
486 string const only_path = onlyPath(file_in);
487 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
488 return make_pair(IDENTICAL_PATHS, file_in);
490 string mangled = file.mangledFileName();
491 if (file.isZipped()) {
492 // We need to change _eps.gz to .eps.gz. The mangled name is
493 // still unique because of the counter in mangledFileName().
494 // We can't just call mangledFileName() with the zip
495 // extension removed, because base.eps and base.eps.gz may
496 // have different content but would get the same mangled
497 // name in this case.
498 string const base = removeExtension(file.unzippedFileName());
499 string::size_type const ext_len = file_in.length() - base.length();
500 mangled[mangled.length() - ext_len] = '.';
502 FileName const file_out(makeAbsPath(mangled, dir));
504 return copyFileIfNeeded(file, file_out);
508 string const stripExtensionIfPossible(string const & file, bool nice)
510 // Remove the extension so the LaTeX compiler will use whatever
511 // is appropriate (when there are several versions in different
513 // Do this only if we are not exporting for internal usage, because
514 // pdflatex prefers png over pdf and it would pick up the png images
515 // that we generate for preview.
516 // This works only if the filename contains no dots besides
517 // the just removed one. We can fool here by replacing all
518 // dots with a macro whose definition is just a dot ;-)
519 // The automatic format selection does not work if the file
521 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
522 if (!nice || contains(latex_name, '"'))
524 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
528 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
530 // No conversion is needed. LaTeX can handle the graphic file as is.
531 // This is true even if the orig_file is compressed.
532 string const to_format = formats.getFormat(to)->extension();
533 string const file_format = getExtension(file);
534 // for latex .ps == .eps
535 if (to_format == file_format ||
536 (to_format == "eps" && file_format == "ps") ||
537 (to_format == "ps" && file_format == "eps"))
538 return stripExtensionIfPossible(file, nice);
539 return latex_path(file, EXCLUDE_EXTENSION);
545 string InsetGraphics::prepareFile(OutputParams const & runparams) const
547 // The following code depends on non-empty filenames
548 if (params().filename.empty())
551 string const orig_file = params().filename.absFileName();
552 // this is for dryrun and display purposes, do not use latexFilename
553 string const rel_file = params().filename.relFileName(buffer().filePath());
555 // previewing source code, no file copying or file format conversion
556 if (runparams.dryrun)
557 return stripExtensionIfPossible(rel_file, runparams.nice);
559 // The master buffer. This is useful when there are multiple levels
561 Buffer const * masterBuffer = buffer().masterBuffer();
563 // Return the output name if we are inside a comment or the file does
565 // We are not going to change the extension or using the name of the
566 // temporary file, the code is already complicated enough.
567 if (runparams.inComment || !params().filename.isReadableFile())
568 return params().filename.outputFileName(masterBuffer->filePath());
570 // We place all temporary files in the master buffer's temp dir.
571 // This is possible because we use mangled file names.
572 // This is necessary for DVI export.
573 string const temp_path = masterBuffer->temppath();
575 // temp_file will contain the file for LaTeX to act on if, for example,
576 // we move it to a temp dir or uncompress it.
578 GraphicsCopyStatus status;
579 boost::tie(status, temp_file) =
580 copyToDirIfNeeded(params().filename, temp_path);
582 if (status == FAILURE)
585 // a relative filename should be relative to the master buffer.
586 // "nice" means that the buffer is exported to LaTeX format but not
587 // run through the LaTeX compiler.
588 string output_file = runparams.nice ?
589 params().filename.outputFileName(masterBuffer->filePath()) :
590 onlyFileName(temp_file.absFileName());
592 if (runparams.nice && !isValidLaTeXFileName(output_file)) {
593 frontend::Alert::warning(_("Invalid filename"),
594 _("The following filename is likely to cause trouble "
595 "when running the exported file through LaTeX: ") +
596 from_utf8(output_file));
599 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
600 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
601 "latex" : "pdflatex";
603 // If the file is compressed and we have specified that it
604 // should not be uncompressed, then just return its name and
605 // let LaTeX do the rest!
606 if (params().filename.isZipped()) {
607 if (params().noUnzip) {
608 // We don't know whether latex can actually handle
609 // this file, but we can't check, because that would
610 // mean to unzip the file and thereby making the
611 // noUnzip parameter meaningless.
612 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
614 FileName const bb_orig_file =
615 FileName(changeExtension(orig_file, "bb"));
616 if (runparams.nice) {
617 runparams.exportdata->addExternalFile(tex_format,
619 changeExtension(output_file, "bb"));
621 // LaTeX needs the bounding box file in the
624 FileName(changeExtension(temp_file.absFileName(), "bb"));
625 boost::tie(status, bb_file) =
626 copyFileIfNeeded(bb_orig_file, bb_file);
627 if (status == FAILURE)
629 runparams.exportdata->addExternalFile(tex_format,
632 runparams.exportdata->addExternalFile(tex_format,
633 source_file, output_file);
634 runparams.exportdata->addExternalFile("dvi",
635 source_file, output_file);
636 // We can't strip the extension, because we don't know
637 // the unzipped file format
638 return latex_path(output_file, EXCLUDE_EXTENSION);
641 FileName const unzipped_temp_file =
642 FileName(unzippedFileName(temp_file.absFileName()));
643 output_file = unzippedFileName(output_file);
644 source_file = FileName(unzippedFileName(source_file.absFileName()));
645 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
646 // temp_file has been unzipped already and
647 // orig_file has not changed in the meantime.
648 temp_file = unzipped_temp_file;
649 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
651 // unzipped_temp_file does not exist or is too old
652 temp_file = unzipFile(temp_file);
653 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
657 string const from = formats.getFormatFromFile(temp_file);
659 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
661 string const to = findTargetFormat(from, runparams);
662 string const ext = formats.extension(to);
663 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
665 // We're going to be running the exported buffer through the LaTeX
666 // compiler, so must ensure that LaTeX can cope with the graphics
669 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
672 // source and destination formats are the same
673 if (!runparams.nice && !FileName(temp_file).hasExtension(ext)) {
674 // The LaTeX compiler will not be able to determine
675 // the file format from the extension, so we must
677 FileName const new_file =
678 FileName(changeExtension(temp_file.absFileName(), ext));
679 if (temp_file.moveTo(new_file)) {
680 temp_file = new_file;
681 output_file = changeExtension(output_file, ext);
683 FileName(changeExtension(source_file.absFileName(), ext));
685 LYXERR(Debug::GRAPHICS, "Could not rename file `"
686 << temp_file << "' to `" << new_file << "'.");
689 // The extension of temp_file might be != ext!
690 runparams.exportdata->addExternalFile(tex_format, source_file,
692 runparams.exportdata->addExternalFile("dvi", source_file,
694 return stripExtensionIfPossible(output_file, to, runparams.nice);
697 // so the source and destination formats are different
698 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
699 string const output_to_file = changeExtension(output_file, ext);
701 // Do we need to perform the conversion?
702 // Yes if to_file does not exist or if temp_file is newer than to_file
703 if (compare_timestamps(temp_file, to_file) < 0) {
705 LYXERR(Debug::GRAPHICS,
706 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
707 from_utf8(rel_file))));
708 runparams.exportdata->addExternalFile(tex_format, to_file,
710 runparams.exportdata->addExternalFile("dvi", to_file,
712 return stripExtensionIfPossible(output_to_file, runparams.nice);
715 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
716 << "\tA copy has been made and convert is to be called with:\n"
717 << "\tfile to convert = " << temp_file << '\n'
718 << "\t from " << from << " to " << to);
720 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
722 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
724 Converters::try_default | Converters::try_cache)) {
725 runparams.exportdata->addExternalFile(tex_format,
726 to_file, output_to_file);
727 runparams.exportdata->addExternalFile("dvi",
728 to_file, output_to_file);
731 return stripExtensionIfPossible(output_to_file, runparams.nice);
735 int InsetGraphics::latex(odocstream & os,
736 OutputParams const & runparams) const
738 // If there is no file specified or not existing,
739 // just output a message about it in the latex output.
740 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
741 << params().filename.absFileName());
743 bool const file_exists = !params().filename.empty()
744 && params().filename.isReadableFile();
745 string const message = file_exists ?
746 string() : string("bb = 0 0 200 100, draft, type=eps");
747 // if !message.empty() then there was no existing file
748 // "filename" found. In this case LaTeX
749 // draws only a rectangle with the above bb and the
750 // not found filename in it.
751 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
753 // These variables collect all the latex code that should be before and
754 // after the actual includegraphics command.
758 if (runparams.moving_arg)
759 before += "\\protect";
761 // We never use the starred form, we use the "clip" option instead.
762 before += "\\includegraphics";
764 // Write the options if there are any.
765 string const opts = createLatexOptions();
766 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
768 if (!opts.empty() && !message.empty())
769 before += ('[' + opts + ',' + message + ']');
770 else if (!opts.empty() || !message.empty())
771 before += ('[' + opts + message + ']');
773 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
775 string latex_str = before + '{';
776 // Convert the file if necessary.
777 // Remove the extension so LaTeX will use whatever is appropriate
778 // (when there are several versions in different formats)
779 latex_str += prepareFile(runparams);
780 latex_str += '}' + after;
782 os << from_utf8(latex_str);
784 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
785 // Return how many newlines we issued.
786 return int(count(latex_str.begin(), latex_str.end(),'\n'));
790 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
792 // No graphics in ascii output. Possible to use gifscii to convert
793 // images to ascii approximation.
794 // 1. Convert file to ascii using gifscii
795 // 2. Read ascii output file and add it to the output stream.
796 // at least we send the filename
798 // FIXME: We have no idea what the encoding of the filename is
800 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
801 from_utf8(params().filename.absFileName()));
802 os << '<' << str << '>';
804 return 2 + str.size();
808 static int writeImageObject(char const * format, odocstream & os,
809 OutputParams const & runparams, docstring const & graphic_label,
810 docstring const & attributes)
812 if (runparams.flavor != OutputParams::XML)
813 os << "<![ %output.print." << format
816 os <<"<imageobject><imagedata fileref=\"&"
823 if (runparams.flavor == OutputParams::XML)
824 os << " role=\"" << format << "\"/>" ;
826 os << " format=\"" << format << "\">" ;
828 os << "</imageobject>";
830 if (runparams.flavor != OutputParams::XML)
831 os << endl << "]]>" ;
833 return runparams.flavor == OutputParams::XML ? 0 : 2;
837 // For explanation on inserting graphics into DocBook checkout:
838 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
839 // See also the docbook guide at http://www.docbook.org/
840 int InsetGraphics::docbook(odocstream & os,
841 OutputParams const & runparams) const
843 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
844 // need to switch to MediaObject. However, for now this is sufficient and
846 if (runparams.flavor == OutputParams::XML)
847 runparams.exportdata->addExternalFile("docbook-xml",
850 runparams.exportdata->addExternalFile("docbook",
853 os << "<inlinemediaobject>";
856 docstring attributes = createDocBookAttributes();
857 r += writeImageObject("png", os, runparams, graphic_label, attributes);
858 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
859 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
860 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
862 os << "</inlinemediaobject>";
867 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
869 // The following code depends on non-empty filenames
870 if (params().filename.empty())
873 string const orig_file = params().filename.absFileName();
875 // The master buffer. This is useful when there are multiple levels
877 Buffer const * masterBuffer = buffer().masterBuffer();
879 if (!params().filename.isReadableFile())
882 // We place all temporary files in the master buffer's temp dir.
883 // This is possible because we use mangled file names.
884 // FIXME We may want to put these files in some special temporary
886 string const temp_path = masterBuffer->temppath();
888 // Copy to temporary directory.
890 GraphicsCopyStatus status;
891 boost::tie(status, temp_file) =
892 copyToDirIfNeeded(params().filename, temp_path);
894 if (status == FAILURE)
897 string output_file = onlyFileName(temp_file.absFileName());
899 string const from = formats.getFormatFromFile(temp_file);
901 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
903 string const to = findTargetFormat(from, runparams);
904 string const ext = formats.extension(to);
905 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
906 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
909 // source and destination formats are the same
910 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
914 // so the source and destination formats are different
915 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
916 string const output_to_file = changeExtension(output_file, ext);
918 // Do we need to perform the conversion?
919 // Yes if to_file does not exist or if temp_file is newer than to_file
920 if (compare_timestamps(temp_file, to_file) < 0) {
922 LYXERR(Debug::GRAPHICS,
923 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
924 from_utf8(orig_file))));
925 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
926 return output_to_file;
929 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
930 << "\tA copy has been made and convert is to be called with:\n"
931 << "\tfile to convert = " << temp_file << '\n'
932 << "\t from " << from << " to " << to);
934 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
937 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
938 from, to, el, Converters::try_default | Converters::try_cache);
941 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
942 return output_to_file;
946 docstring InsetGraphics::xhtml(XHTMLStream & xs, OutputParams const & op) const
948 string const output_file = prepareHTMLFile(op);
949 if (output_file.empty()) {
950 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
951 << params().filename << "' for output. File missing?");
952 string const attr = "src='" + params().filename.absFileName()
953 + "' alt='image: " + output_file + "'";
954 xs << html::CompTag("img", attr);
959 // Do we want to do something with the parameters, other than use them to
960 // crop, etc, the image?
961 // Speaking of which: Do the cropping, rotating, etc.
962 string const attr = "src='" + output_file + "' alt='image: "
964 xs << html::CompTag("img", attr);
969 void InsetGraphics::validate(LaTeXFeatures & features) const
971 // If we have no image, we should not require anything.
972 if (params().filename.empty())
975 features.includeFile(graphic_label,
976 removeExtension(params().filename.absFileName()));
978 features.require("graphicx");
980 if (features.runparams().nice) {
981 Buffer const * masterBuffer = features.buffer().masterBuffer();
982 string const rel_file = removeExtension(
983 params().filename.relFileName(masterBuffer->filePath()));
984 if (contains(rel_file, "."))
985 features.require("lyxdot");
990 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
992 // If nothing is changed, just return and say so.
993 if (params() == p && !p.filename.empty())
996 // Copy the new parameters.
999 // Update the display using the new parameters.
1000 graphic_->update(params().as_grfxParams());
1002 // We have changed data, report it.
1007 InsetGraphicsParams const & InsetGraphics::params() const
1013 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1015 formats.edit(buffer(), p.filename,
1016 formats.getFormatFromFile(p.filename));
1020 void InsetGraphics::addToToc(DocIterator const & cpit)
1022 TocBackend & backend = buffer().tocBackend();
1025 docstring const str = from_utf8(params_.filename.onlyFileName());
1026 backend.toc("graphics").push_back(TocItem(cpit, 0, str));
1030 docstring InsetGraphics::contextMenu(BufferView const &, int, int) const
1032 return from_ascii("context-graphics");
1036 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1037 InsetGraphicsParams & params)
1042 istringstream data(in);
1044 lex.setStream(data);
1045 lex.setContext("InsetGraphics::string2params");
1047 params = InsetGraphicsParams();
1048 readInsetGraphics(lex, buffer.filePath(), params);
1052 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1053 Buffer const & buffer)
1056 data << "graphics" << ' ';
1057 params.Write(data, buffer);
1058 data << "\\end_inset\n";
1062 namespace graphics {
1064 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1066 Inset & inset = b.inset();
1067 InsetIterator it = inset_iterator_begin(inset);
1068 InsetIterator const end = inset_iterator_end(inset);
1069 for (; it != end; ++it)
1070 if (it->lyxCode() == GRAPHICS_CODE) {
1071 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1072 InsetGraphicsParams inspar = ins.getParams();
1073 if (!inspar.groupId.empty())
1074 ids.insert(inspar.groupId);
1079 int countGroupMembers(Buffer const & b, string const & groupId)
1082 if (groupId.empty())
1084 Inset & inset = b.inset();
1085 InsetIterator it = inset_iterator_begin(inset);
1086 InsetIterator const end = inset_iterator_end(inset);
1087 for (; it != end; ++it)
1088 if (it->lyxCode() == GRAPHICS_CODE) {
1089 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1090 if (ins.getParams().groupId == groupId)
1097 string getGroupParams(Buffer const & b, string const & groupId)
1099 if (groupId.empty())
1101 Inset & inset = b.inset();
1102 InsetIterator it = inset_iterator_begin(inset);
1103 InsetIterator const end = inset_iterator_end(inset);
1104 for (; it != end; ++it)
1105 if (it->lyxCode() == GRAPHICS_CODE) {
1106 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1107 InsetGraphicsParams inspar = ins.getParams();
1108 if (inspar.groupId == groupId) {
1109 InsetGraphicsParams tmp = inspar;
1110 tmp.filename.erase();
1111 return InsetGraphics::params2string(tmp, b);
1118 void unifyGraphicsGroups(Buffer & b, string const & argument)
1120 InsetGraphicsParams params;
1121 InsetGraphics::string2params(argument, b, params);
1123 b.undo().beginUndoGroup();
1124 Inset & inset = b.inset();
1125 InsetIterator it = inset_iterator_begin(inset);
1126 InsetIterator const end = inset_iterator_end(inset);
1127 for (; it != end; ++it) {
1128 if (it->lyxCode() == GRAPHICS_CODE) {
1129 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1130 InsetGraphicsParams inspar = ins.getParams();
1131 if (params.groupId == inspar.groupId) {
1132 b.undo().recordUndo(it);
1133 params.filename = inspar.filename;
1134 ins.setParams(params);
1138 b.undo().endUndoGroup();
1142 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1144 Inset * instmp = &cur.inset();
1145 if (instmp->lyxCode() != GRAPHICS_CODE)
1146 instmp = cur.nextInset();
1147 if (!instmp || instmp->lyxCode() != GRAPHICS_CODE)
1150 return static_cast<InsetGraphics *>(instmp);
1153 } // namespace graphics