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/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 if (format == "jpg" || format == "png" || format == "gif")
126 // If it's postscript, we always do eps.
127 LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
129 // any other than ps is changed to eps
136 void readInsetGraphics(Lexer & lex, string const & bufpath,
137 InsetGraphicsParams & params)
139 bool finished = false;
141 while (lex.isOK() && !finished) {
144 string const token = lex.getString();
145 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
150 if (token == "\\end_inset") {
153 if (!params.Read(lex, token, bufpath))
154 lyxerr << "Unknown token, "
165 InsetGraphics::InsetGraphics(Buffer * buf)
166 : Inset(buf), graphic_label(sgml::uniqueID(from_ascii("graph"))),
167 graphic_(new RenderGraphic(this))
172 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
174 graphic_label(sgml::uniqueID(from_ascii("graph"))),
175 graphic_(new RenderGraphic(*ig.graphic_, this))
177 setParams(ig.params());
181 Inset * InsetGraphics::clone() const
183 return new InsetGraphics(*this);
187 InsetGraphics::~InsetGraphics()
189 hideDialogs("graphics", this);
194 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
196 switch (cmd.action()) {
197 case LFUN_INSET_EDIT: {
198 InsetGraphicsParams p = params();
199 if (!cmd.argument().empty())
200 string2params(to_utf8(cmd.argument()), buffer(), p);
205 case LFUN_INSET_MODIFY: {
206 if (cmd.getArg(0) != "graphics") {
207 Inset::doDispatch(cur, cmd);
211 InsetGraphicsParams p;
212 string2params(to_utf8(cmd.argument()), buffer(), p);
213 if (p.filename.empty()) {
214 cur.noScreenUpdate();
220 // if the inset is part of a graphics group, all the
221 // other members should be updated too.
222 if (!params_.groupId.empty())
223 graphics::unifyGraphicsGroups(buffer(),
224 to_utf8(cmd.argument()));
228 case LFUN_INSET_DIALOG_UPDATE:
229 cur.bv().updateDialog("graphics", params2string(params(), buffer()));
232 case LFUN_GRAPHICS_RELOAD:
233 params_.filename.refresh();
238 Inset::doDispatch(cur, cmd);
244 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
245 FuncStatus & flag) const
247 switch (cmd.action()) {
248 case LFUN_INSET_MODIFY:
249 if (cmd.getArg(0) != "graphics")
250 return Inset::getStatus(cur, cmd, flag);
252 case LFUN_INSET_EDIT:
253 case LFUN_INSET_DIALOG_UPDATE:
254 case LFUN_GRAPHICS_RELOAD:
255 flag.setEnabled(true);
259 return Inset::getStatus(cur, cmd, flag);
264 bool InsetGraphics::showInsetDialog(BufferView * bv) const
266 bv->showDialog("graphics", params2string(params(), bv->buffer()),
267 const_cast<InsetGraphics *>(this));
273 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
275 graphic_->metrics(mi, dim);
279 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
281 graphic_->draw(pi, x, y);
285 void InsetGraphics::write(ostream & os) const
288 params().Write(os, buffer());
292 void InsetGraphics::read(Lexer & lex)
294 lex.setContext("InsetGraphics::read");
296 readInsetGraphics(lex, buffer().filePath(), params_);
297 graphic_->update(params().as_grfxParams());
301 string InsetGraphics::createLatexOptions() const
303 // Calculate the options part of the command, we must do it to a string
304 // stream since we might have a trailing comma that we would like to remove
305 // before writing it to the output stream.
306 ostringstream options;
307 if (!params().bb.empty())
308 options << "bb=" << rtrim(params().bb) << ',';
314 double const scl = convert<double>(params().scale);
315 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
316 if (!float_equal(scl, 100.0, 0.05))
317 size << "scale=" << scl / 100.0 << ',';
319 if (!params().width.zero())
320 size << "width=" << params().width.asLatexString() << ',';
321 if (!params().height.zero())
322 size << "height=" << params().height.asLatexString() << ',';
323 if (params().keepAspectRatio)
324 size << "keepaspectratio,";
326 if (params().scaleBeforeRotation && !size.str().empty())
327 options << size.str();
329 // Make sure rotation angle is not very close to zero;
330 // a float can be effectively zero but not exactly zero.
331 if (!params().rotateAngle.empty()
332 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
333 options << "angle=" << params().rotateAngle << ',';
334 if (!params().rotateOrigin.empty()) {
335 options << "origin=" << params().rotateOrigin[0];
336 if (contains(params().rotateOrigin,"Top"))
338 else if (contains(params().rotateOrigin,"Bottom"))
340 else if (contains(params().rotateOrigin,"Baseline"))
345 if (!params().scaleBeforeRotation && !size.str().empty())
346 options << size.str();
348 if (!params().special.empty())
349 options << params().special << ',';
351 string opts = options.str();
353 if (suffixIs(opts, ','))
354 opts = opts.substr(0, opts.size() - 1);
360 docstring InsetGraphics::toDocbookLength(Length const & len) const
362 odocstringstream result;
363 switch (len.unit()) {
364 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
365 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
367 case Length::PT: // Point = 1/72.27in = 0.351mm
368 result << len.value() * 72 / 72.27 << "pt";
370 case Length::BP: // Big point (72bp = 1in), also PostScript point
371 result << len.value() << "pt";
373 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
374 result << len.value() * 0.376 << "mm";
376 case Length::MM: // Millimeter = 2.845pt
377 result << len.value() << "mm";
379 case Length::PC: // Pica = 12pt = 4.218mm
380 result << len.value() << "pc";
382 case Length::CC: // Cicero = 12dd = 4.531mm
383 result << len.value() * 4.531 << "mm";
385 case Length::CM: // Centimeter = 10mm = 2.371pc
386 result << len.value() << "cm";
388 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
389 result << len.value() << "in";
391 case Length::EX: // Height of a small "x" for the current font.
392 // Obviously we have to compromise here. Any better ratio than 1.5 ?
393 result << len.value() / 1.5 << "em";
395 case Length::EM: // Width of capital "M" in current font.
396 result << len.value() << "em";
398 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
399 result << len.value() * 18 << "em";
401 case Length::PTW: // Percent of TextWidth
402 case Length::PCW: // Percent of ColumnWidth
403 case Length::PPW: // Percent of PageWidth
404 case Length::PLW: // Percent of LineWidth
405 case Length::PTH: // Percent of TextHeight
406 case Length::PPH: // Percent of PaperHeight
407 // Sigh, this will go wrong.
408 result << len.value() << "%";
411 result << len.asDocstring();
418 docstring InsetGraphics::createDocBookAttributes() const
420 // Calculate the options part of the command, we must do it to a string
421 // stream since we copied the code from createLatexParams() ;-)
423 // FIXME: av: need to translate spec -> Docbook XSL spec
424 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
425 // Right now it only works with my version of db2latex :-)
427 odocstringstream options;
428 double const scl = convert<double>(params().scale);
429 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
430 if (!float_equal(scl, 100.0, 0.05))
431 options << " scale=\""
432 << static_cast<int>( (scl) + 0.5 )
435 if (!params().width.zero()) {
436 options << " width=\"" << toDocbookLength(params().width) << "\" ";
438 if (!params().height.zero()) {
439 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
441 if (params().keepAspectRatio) {
442 // This will be irrelevant unless both width and height are set
443 options << "scalefit=\"1\" ";
448 if (!params().special.empty())
449 options << from_ascii(params().special) << " ";
451 // trailing blanks are ok ...
452 return options.str();
458 enum GraphicsCopyStatus {
466 pair<GraphicsCopyStatus, FileName> const
467 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
469 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
470 unsigned long const checksum_in = file_in.checksum();
471 unsigned long const checksum_out = file_out.checksum();
473 if (checksum_in == checksum_out)
475 return make_pair(IDENTICAL_CONTENTS, file_out);
477 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
478 bool const success = mover.copy(file_in, file_out);
481 LYXERR(Debug::GRAPHICS,
482 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
483 "into the temporary directory."),
484 from_utf8(file_in.absFileName()))));
487 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
488 return make_pair(status, file_out);
492 pair<GraphicsCopyStatus, FileName> const
493 copyToDirIfNeeded(DocFileName const & file, string const & dir)
495 string const file_in = file.absFileName();
496 string const only_path = onlyPath(file_in);
497 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
498 return make_pair(IDENTICAL_PATHS, FileName(file_in));
500 string mangled = file.mangledFileName();
501 if (formats.isZippedFile(file)) {
502 // We need to change _eps.gz to .eps.gz. The mangled name is
503 // still unique because of the counter in mangledFileName().
504 // We can't just call mangledFileName() with the zip
505 // extension removed, because base.eps and base.eps.gz may
506 // have different content but would get the same mangled
507 // name in this case.
508 string const base = removeExtension(file.unzippedFileName());
509 string::size_type const ext_len = file_in.length() - base.length();
510 mangled[mangled.length() - ext_len] = '.';
512 FileName const file_out(makeAbsPath(mangled, dir));
514 return copyFileIfNeeded(file, file_out);
518 string const stripExtensionIfPossible(string const & file, bool nice)
520 // Remove the extension so the LaTeX compiler will use whatever
521 // is appropriate (when there are several versions in different
523 // Do this only if we are not exporting for internal usage, because
524 // pdflatex prefers png over pdf and it would pick up the png images
525 // that we generate for preview.
526 // This works only if the filename contains no dots besides
527 // the just removed one. We can fool here by replacing all
528 // dots with a macro whose definition is just a dot ;-)
529 // The automatic format selection does not work if the file
531 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
532 if (!nice || contains(latex_name, '"'))
534 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
538 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
540 // No conversion is needed. LaTeX can handle the graphic file as is.
541 // This is true even if the orig_file is compressed.
542 string const to_format = formats.getFormat(to)->extension();
543 string const file_format = getExtension(file);
544 // for latex .ps == .eps
545 if (to_format == file_format ||
546 (to_format == "eps" && file_format == "ps") ||
547 (to_format == "ps" && file_format == "eps"))
548 return stripExtensionIfPossible(file, nice);
549 return latex_path(file, EXCLUDE_EXTENSION);
555 string InsetGraphics::prepareFile(OutputParams const & runparams) const
557 // The following code depends on non-empty filenames
558 if (params().filename.empty())
561 string const orig_file = params().filename.absFileName();
562 // this is for dryrun and display purposes, do not use latexFilename
563 string const rel_file = params().filename.relFileName(buffer().filePath());
565 // previewing source code, no file copying or file format conversion
566 if (runparams.dryrun)
567 return stripExtensionIfPossible(rel_file, runparams.nice);
569 // The master buffer. This is useful when there are multiple levels
571 Buffer const * masterBuffer = buffer().masterBuffer();
573 // Return the output name if we are inside a comment or the file does
575 // We are not going to change the extension or using the name of the
576 // temporary file, the code is already complicated enough.
577 if (runparams.inComment || !params().filename.isReadableFile())
578 return params().filename.outputFileName(masterBuffer->filePath());
580 // We place all temporary files in the master buffer's temp dir.
581 // This is possible because we use mangled file names.
582 // This is necessary for DVI export.
583 string const temp_path = masterBuffer->temppath();
585 // temp_file will contain the file for LaTeX to act on if, for example,
586 // we move it to a temp dir or uncompress it.
588 GraphicsCopyStatus status;
589 boost::tie(status, temp_file) =
590 copyToDirIfNeeded(params().filename, temp_path);
592 if (status == FAILURE)
595 // a relative filename should be relative to the master buffer.
596 // "nice" means that the buffer is exported to LaTeX format but not
597 // run through the LaTeX compiler.
598 string output_file = runparams.nice ?
599 params().filename.outputFileName(masterBuffer->filePath()) :
600 onlyFileName(temp_file.absFileName());
602 if (runparams.nice) {
603 if (!isValidLaTeXFileName(output_file)) {
604 frontend::Alert::warning(_("Invalid filename"),
605 _("The following filename will cause troubles "
606 "when running the exported file through LaTeX: ") +
607 from_utf8(output_file));
609 // only show DVI-specific warning when export format is plain latex
610 if (!isValidDVIFileName(output_file)
611 && runparams.flavor == OutputParams::LATEX) {
612 frontend::Alert::warning(_("Problematic filename for DVI"),
613 _("The following filename can cause troubles "
614 "when running the exported file through LaTeX "
615 "and opening the resulting DVI: ") +
616 from_utf8(output_file), true);
620 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
621 // determine the export format
622 string const tex_format = flavor2format(runparams.flavor);
624 // If the file is compressed and we have specified that it
625 // should not be uncompressed, then just return its name and
626 // let LaTeX do the rest!
627 if (formats.isZippedFile(params().filename)) {
628 if (params().noUnzip) {
629 // We don't know whether latex can actually handle
630 // this file, but we can't check, because that would
631 // mean to unzip the file and thereby making the
632 // noUnzip parameter meaningless.
633 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
635 FileName const bb_orig_file =
636 FileName(changeExtension(orig_file, "bb"));
637 if (runparams.nice) {
638 runparams.exportdata->addExternalFile(tex_format,
640 changeExtension(output_file, "bb"));
642 // LaTeX needs the bounding box file in the
645 FileName(changeExtension(temp_file.absFileName(), "bb"));
646 boost::tie(status, bb_file) =
647 copyFileIfNeeded(bb_orig_file, bb_file);
648 if (status == FAILURE)
650 runparams.exportdata->addExternalFile(tex_format,
653 runparams.exportdata->addExternalFile(tex_format,
654 source_file, output_file);
655 runparams.exportdata->addExternalFile("dvi",
656 source_file, output_file);
657 // We can't strip the extension, because we don't know
658 // the unzipped file format
659 return latex_path(output_file, EXCLUDE_EXTENSION);
662 FileName const unzipped_temp_file =
663 FileName(unzippedFileName(temp_file.absFileName()));
664 output_file = unzippedFileName(output_file);
665 source_file = FileName(unzippedFileName(source_file.absFileName()));
666 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
667 // temp_file has been unzipped already and
668 // orig_file has not changed in the meantime.
669 temp_file = unzipped_temp_file;
670 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
672 // unzipped_temp_file does not exist or is too old
673 temp_file = unzipFile(temp_file);
674 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
678 string const from = formats.getFormatFromFile(temp_file);
680 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
682 string const to = findTargetFormat(from, runparams);
683 string const ext = formats.extension(to);
684 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
686 // We're going to be running the exported buffer through the LaTeX
687 // compiler, so must ensure that LaTeX can cope with the graphics
690 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
693 // source and destination formats are the same
694 if (!runparams.nice && !FileName(temp_file).hasExtension(ext)) {
695 // The LaTeX compiler will not be able to determine
696 // the file format from the extension, so we must
698 FileName const new_file =
699 FileName(changeExtension(temp_file.absFileName(), ext));
700 if (temp_file.moveTo(new_file)) {
701 temp_file = new_file;
702 output_file = changeExtension(output_file, ext);
704 FileName(changeExtension(source_file.absFileName(), ext));
706 LYXERR(Debug::GRAPHICS, "Could not rename file `"
707 << temp_file << "' to `" << new_file << "'.");
710 // The extension of temp_file might be != ext!
711 runparams.exportdata->addExternalFile(tex_format, source_file,
713 runparams.exportdata->addExternalFile("dvi", source_file,
715 return stripExtensionIfPossible(output_file, to, runparams.nice);
718 // so the source and destination formats are different
719 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
720 string const output_to_file = changeExtension(output_file, ext);
722 // Do we need to perform the conversion?
723 // Yes if to_file does not exist or if temp_file is newer than to_file
724 if (compare_timestamps(temp_file, to_file) < 0) {
726 LYXERR(Debug::GRAPHICS,
727 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
728 from_utf8(rel_file))));
729 runparams.exportdata->addExternalFile(tex_format, to_file,
731 runparams.exportdata->addExternalFile("dvi", to_file,
733 return stripExtensionIfPossible(output_to_file, runparams.nice);
736 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
737 << "\tA copy has been made and convert is to be called with:\n"
738 << "\tfile to convert = " << temp_file << '\n'
739 << "\t from " << from << " to " << to);
741 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
743 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
745 Converters::try_default | Converters::try_cache)) {
746 runparams.exportdata->addExternalFile(tex_format,
747 to_file, output_to_file);
748 runparams.exportdata->addExternalFile("dvi",
749 to_file, output_to_file);
752 return stripExtensionIfPossible(output_to_file, runparams.nice);
756 void InsetGraphics::latex(otexstream & os,
757 OutputParams const & runparams) const
759 // If there is no file specified or not existing,
760 // just output a message about it in the latex output.
761 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
762 << params().filename.absFileName());
764 bool const file_exists = !params().filename.empty()
765 && params().filename.isReadableFile();
768 if (params().bb.empty())
769 message = "bb = 0 0 200 100";
770 if (!params().draft) {
771 if (!message.empty())
775 if (!message.empty())
777 message += "type=eps";
779 // If no existing file "filename" was found LaTeX
780 // draws only a rectangle with the above bb and the
781 // not found filename in it.
782 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
784 // These variables collect all the latex code that should be before and
785 // after the actual includegraphics command.
789 if (runparams.moving_arg)
790 before += "\\protect";
792 // We never use the starred form, we use the "clip" option instead.
793 before += "\\includegraphics";
795 // Write the options if there are any.
796 string const opts = createLatexOptions();
797 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
799 if (!opts.empty() && !message.empty())
800 before += ('[' + opts + ',' + message + ']');
801 else if (!opts.empty() || !message.empty())
802 before += ('[' + opts + message + ']');
804 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
806 string latex_str = before + '{';
807 // Convert the file if necessary.
808 // Remove the extension so LaTeX will use whatever is appropriate
809 // (when there are several versions in different formats)
810 string file_path = prepareFile(runparams);
811 latex_str += file_path;
812 latex_str += '}' + after;
814 os << from_utf8(latex_str);
816 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
820 int InsetGraphics::plaintext(odocstringstream & os,
821 OutputParams const &, size_t) const
823 // No graphics in ascii output. Possible to use gifscii to convert
824 // images to ascii approximation.
825 // 1. Convert file to ascii using gifscii
826 // 2. Read ascii output file and add it to the output stream.
827 // at least we send the filename
829 // FIXME: We have no idea what the encoding of the filename is
831 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
832 from_utf8(params().filename.absFileName()));
833 os << '<' << str << '>';
835 return 2 + str.size();
839 static int writeImageObject(char const * format, odocstream & os,
840 OutputParams const & runparams, docstring const & graphic_label,
841 docstring const & attributes)
843 if (runparams.flavor != OutputParams::XML)
844 os << "<![ %output.print." << format
847 os <<"<imageobject><imagedata fileref=\"&"
854 if (runparams.flavor == OutputParams::XML)
855 os << " role=\"" << format << "\"/>" ;
857 os << " format=\"" << format << "\">" ;
859 os << "</imageobject>";
861 if (runparams.flavor != OutputParams::XML)
862 os << endl << "]]>" ;
864 return runparams.flavor == OutputParams::XML ? 0 : 2;
868 // For explanation on inserting graphics into DocBook checkout:
869 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
870 // See also the docbook guide at http://www.docbook.org/
871 int InsetGraphics::docbook(odocstream & os,
872 OutputParams const & runparams) const
874 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
875 // need to switch to MediaObject. However, for now this is sufficient and
877 if (runparams.flavor == OutputParams::XML)
878 runparams.exportdata->addExternalFile("docbook-xml",
881 runparams.exportdata->addExternalFile("docbook",
884 os << "<inlinemediaobject>";
887 docstring attributes = createDocBookAttributes();
888 r += writeImageObject("png", os, runparams, graphic_label, attributes);
889 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
890 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
891 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
893 os << "</inlinemediaobject>";
898 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
900 // The following code depends on non-empty filenames
901 if (params().filename.empty())
904 string const orig_file = params().filename.absFileName();
906 // The master buffer. This is useful when there are multiple levels
908 Buffer const * masterBuffer = buffer().masterBuffer();
910 if (!params().filename.isReadableFile())
913 // We place all temporary files in the master buffer's temp dir.
914 // This is possible because we use mangled file names.
915 // FIXME We may want to put these files in some special temporary
917 string const temp_path = masterBuffer->temppath();
919 // Copy to temporary directory.
921 GraphicsCopyStatus status;
922 boost::tie(status, temp_file) =
923 copyToDirIfNeeded(params().filename, temp_path);
925 if (status == FAILURE)
928 string output_file = onlyFileName(temp_file.absFileName());
930 string const from = formats.getFormatFromFile(temp_file);
932 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
934 string const to = findTargetFormat(from, runparams);
935 string const ext = formats.extension(to);
936 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
937 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
940 // source and destination formats are the same
941 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
945 // so the source and destination formats are different
946 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
947 string const output_to_file = changeExtension(output_file, ext);
949 // Do we need to perform the conversion?
950 // Yes if to_file does not exist or if temp_file is newer than to_file
951 if (compare_timestamps(temp_file, to_file) < 0) {
953 LYXERR(Debug::GRAPHICS,
954 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
955 from_utf8(orig_file))));
956 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
957 return output_to_file;
960 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
961 << "\tA copy has been made and convert is to be called with:\n"
962 << "\tfile to convert = " << temp_file << '\n'
963 << "\t from " << from << " to " << to);
965 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
968 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
969 from, to, el, Converters::try_default | Converters::try_cache);
972 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
973 return output_to_file;
977 docstring InsetGraphics::xhtml(XHTMLStream & xs, OutputParams const & op) const
979 string const output_file = prepareHTMLFile(op);
981 if (output_file.empty()) {
982 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
983 << params().filename << "' for output. File missing?");
984 string const attr = "src='" + params().filename.absFileName()
985 + "' alt='image: " + output_file + "'";
986 xs << html::CompTag("img", attr);
991 // We aren't doing anything with the crop and rotate parameters, and it would
992 // really be better to do width and height conversion, rather than to output
993 // these parameters here.
995 if (!params().width.zero())
996 imgstyle += "width:" + params().width.asHTMLString() + ";";
997 if (!params().height.zero())
998 imgstyle += " height:" + params().height.asHTMLString() + ";";
999 if (!imgstyle.empty())
1000 imgstyle = "style='" + imgstyle + "' ";
1002 string const attr = imgstyle + "src='" + output_file + "' alt='image: "
1003 + output_file + "'";
1004 xs << html::CompTag("img", attr);
1009 void InsetGraphics::validate(LaTeXFeatures & features) const
1011 // If we have no image, we should not require anything.
1012 if (params().filename.empty())
1015 features.includeFile(graphic_label,
1016 removeExtension(params().filename.absFileName()));
1018 features.require("graphicx");
1020 if (features.runparams().nice) {
1021 string const rel_file = params().filename.onlyFileNameWithoutExt();
1022 if (contains(rel_file, "."))
1023 features.require("lyxdot");
1028 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1030 // If nothing is changed, just return and say so.
1031 if (params() == p && !p.filename.empty())
1034 // Copy the new parameters.
1037 // Update the display using the new parameters.
1038 graphic_->update(params().as_grfxParams());
1040 // We have changed data, report it.
1045 InsetGraphicsParams const & InsetGraphics::params() const
1051 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1053 formats.edit(buffer(), p.filename,
1054 formats.getFormatFromFile(p.filename));
1058 void InsetGraphics::addToToc(DocIterator const & cpit, bool output_active) const
1061 docstring const str = from_utf8(params_.filename.onlyFileName());
1062 buffer().tocBackend().toc("graphics").push_back(TocItem(cpit, 0, str, output_active));
1066 string InsetGraphics::contextMenuName() const
1068 return "context-graphics";
1072 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1073 InsetGraphicsParams & params)
1078 istringstream data(in);
1080 lex.setStream(data);
1081 lex.setContext("InsetGraphics::string2params");
1083 params = InsetGraphicsParams();
1084 readInsetGraphics(lex, buffer.filePath(), params);
1088 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1089 Buffer const & buffer)
1092 data << "graphics" << ' ';
1093 params.Write(data, buffer);
1094 data << "\\end_inset\n";
1099 docstring InsetGraphics::toolTip(BufferView const &, int, int) const
1101 return from_utf8(params().filename.onlyFileName());
1104 namespace graphics {
1106 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1108 Inset & inset = b.inset();
1109 InsetIterator it = inset_iterator_begin(inset);
1110 InsetIterator const end = inset_iterator_end(inset);
1111 for (; it != end; ++it)
1112 if (it->lyxCode() == GRAPHICS_CODE) {
1113 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1114 InsetGraphicsParams inspar = ins.getParams();
1115 if (!inspar.groupId.empty())
1116 ids.insert(inspar.groupId);
1121 int countGroupMembers(Buffer const & b, string const & groupId)
1124 if (groupId.empty())
1126 Inset & inset = b.inset();
1127 InsetIterator it = inset_iterator_begin(inset);
1128 InsetIterator const end = inset_iterator_end(inset);
1129 for (; it != end; ++it)
1130 if (it->lyxCode() == GRAPHICS_CODE) {
1131 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1132 if (ins.getParams().groupId == groupId)
1139 string getGroupParams(Buffer const & b, string const & groupId)
1141 if (groupId.empty())
1143 Inset & inset = b.inset();
1144 InsetIterator it = inset_iterator_begin(inset);
1145 InsetIterator const end = inset_iterator_end(inset);
1146 for (; it != end; ++it)
1147 if (it->lyxCode() == GRAPHICS_CODE) {
1148 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1149 InsetGraphicsParams inspar = ins.getParams();
1150 if (inspar.groupId == groupId) {
1151 InsetGraphicsParams tmp = inspar;
1152 tmp.filename.erase();
1153 return InsetGraphics::params2string(tmp, b);
1160 void unifyGraphicsGroups(Buffer & b, string const & argument)
1162 InsetGraphicsParams params;
1163 InsetGraphics::string2params(argument, b, params);
1165 b.undo().beginUndoGroup();
1166 Inset & inset = b.inset();
1167 InsetIterator it = inset_iterator_begin(inset);
1168 InsetIterator const end = inset_iterator_end(inset);
1169 for (; it != end; ++it) {
1170 if (it->lyxCode() == GRAPHICS_CODE) {
1171 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1172 InsetGraphicsParams inspar = ins.getParams();
1173 if (params.groupId == inspar.groupId) {
1174 b.undo().recordUndo(CursorData(it));
1175 params.filename = inspar.filename;
1176 ins.setParams(params);
1180 b.undo().endUndoGroup();
1184 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1186 Inset * instmp = &cur.inset();
1187 if (instmp->lyxCode() != GRAPHICS_CODE)
1188 instmp = cur.nextInset();
1189 if (!instmp || instmp->lyxCode() != GRAPHICS_CODE)
1192 return static_cast<InsetGraphics *>(instmp);
1195 } // namespace graphics