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);
251 case LFUN_INSET_EDIT:
252 case LFUN_INSET_DIALOG_UPDATE:
253 case LFUN_GRAPHICS_RELOAD:
254 flag.setEnabled(true);
258 return Inset::getStatus(cur, cmd, flag);
263 bool InsetGraphics::showInsetDialog(BufferView * bv) const
265 bv->showDialog("graphics", params2string(params(), bv->buffer()),
266 const_cast<InsetGraphics *>(this));
272 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
274 graphic_->metrics(mi, dim);
278 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
280 graphic_->draw(pi, x, y);
284 void InsetGraphics::write(ostream & os) const
287 params().Write(os, buffer());
291 void InsetGraphics::read(Lexer & lex)
293 lex.setContext("InsetGraphics::read");
295 readInsetGraphics(lex, buffer().filePath(), params_);
296 graphic_->update(params().as_grfxParams());
300 string InsetGraphics::createLatexOptions() const
302 // Calculate the options part of the command, we must do it to a string
303 // stream since we might have a trailing comma that we would like to remove
304 // before writing it to the output stream.
305 ostringstream options;
306 if (!params().bb.empty())
307 options << "bb=" << rtrim(params().bb) << ',';
313 double const scl = convert<double>(params().scale);
314 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
315 if (!float_equal(scl, 100.0, 0.05))
316 size << "scale=" << scl / 100.0 << ',';
318 if (!params().width.zero())
319 size << "width=" << params().width.asLatexString() << ',';
320 if (!params().height.zero())
321 size << "height=" << params().height.asLatexString() << ',';
322 if (params().keepAspectRatio)
323 size << "keepaspectratio,";
325 if (params().scaleBeforeRotation && !size.str().empty())
326 options << size.str();
328 // Make sure rotation angle is not very close to zero;
329 // a float can be effectively zero but not exactly zero.
330 if (!params().rotateAngle.empty()
331 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
332 options << "angle=" << params().rotateAngle << ',';
333 if (!params().rotateOrigin.empty()) {
334 options << "origin=" << params().rotateOrigin[0];
335 if (contains(params().rotateOrigin,"Top"))
337 else if (contains(params().rotateOrigin,"Bottom"))
339 else if (contains(params().rotateOrigin,"Baseline"))
344 if (!params().scaleBeforeRotation && !size.str().empty())
345 options << size.str();
347 if (!params().special.empty())
348 options << params().special << ',';
350 string opts = options.str();
352 if (suffixIs(opts, ','))
353 opts = opts.substr(0, opts.size() - 1);
359 docstring InsetGraphics::toDocbookLength(Length const & len) const
361 odocstringstream result;
362 switch (len.unit()) {
363 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
364 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
366 case Length::PT: // Point = 1/72.27in = 0.351mm
367 result << len.value() * 72 / 72.27 << "pt";
369 case Length::BP: // Big point (72bp = 1in), also PostScript point
370 result << len.value() << "pt";
372 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
373 result << len.value() * 0.376 << "mm";
375 case Length::MM: // Millimeter = 2.845pt
376 result << len.value() << "mm";
378 case Length::PC: // Pica = 12pt = 4.218mm
379 result << len.value() << "pc";
381 case Length::CC: // Cicero = 12dd = 4.531mm
382 result << len.value() * 4.531 << "mm";
384 case Length::CM: // Centimeter = 10mm = 2.371pc
385 result << len.value() << "cm";
387 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
388 result << len.value() << "in";
390 case Length::EX: // Height of a small "x" for the current font.
391 // Obviously we have to compromise here. Any better ratio than 1.5 ?
392 result << len.value() / 1.5 << "em";
394 case Length::EM: // Width of capital "M" in current font.
395 result << len.value() << "em";
397 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
398 result << len.value() * 18 << "em";
400 case Length::PTW: // Percent of TextWidth
401 case Length::PCW: // Percent of ColumnWidth
402 case Length::PPW: // Percent of PageWidth
403 case Length::PLW: // Percent of LineWidth
404 case Length::PTH: // Percent of TextHeight
405 case Length::PPH: // Percent of PaperHeight
406 // Sigh, this will go wrong.
407 result << len.value() << "%";
410 result << len.asDocstring();
417 docstring InsetGraphics::createDocBookAttributes() const
419 // Calculate the options part of the command, we must do it to a string
420 // stream since we copied the code from createLatexParams() ;-)
422 // FIXME: av: need to translate spec -> Docbook XSL spec
423 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
424 // Right now it only works with my version of db2latex :-)
426 odocstringstream options;
427 double const scl = convert<double>(params().scale);
428 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
429 if (!float_equal(scl, 100.0, 0.05))
430 options << " scale=\""
431 << static_cast<int>( (scl) + 0.5 )
434 if (!params().width.zero()) {
435 options << " width=\"" << toDocbookLength(params().width) << "\" ";
437 if (!params().height.zero()) {
438 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
440 if (params().keepAspectRatio) {
441 // This will be irrelevant unless both width and height are set
442 options << "scalefit=\"1\" ";
447 if (!params().special.empty())
448 options << from_ascii(params().special) << " ";
450 // trailing blanks are ok ...
451 return options.str();
457 enum GraphicsCopyStatus {
465 pair<GraphicsCopyStatus, FileName> const
466 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
468 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
469 unsigned long const checksum_in = file_in.checksum();
470 unsigned long const checksum_out = file_out.checksum();
472 if (checksum_in == checksum_out)
474 return make_pair(IDENTICAL_CONTENTS, file_out);
476 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
477 bool const success = mover.copy(file_in, file_out);
480 LYXERR(Debug::GRAPHICS,
481 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
482 "into the temporary directory."),
483 from_utf8(file_in.absFileName()))));
486 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
487 return make_pair(status, file_out);
491 pair<GraphicsCopyStatus, FileName> const
492 copyToDirIfNeeded(DocFileName const & file, string const & dir)
494 string const file_in = file.absFileName();
495 string const only_path = onlyPath(file_in);
496 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
497 return make_pair(IDENTICAL_PATHS, FileName(file_in));
499 string mangled = file.mangledFileName();
500 if (formats.isZippedFile(file)) {
501 // We need to change _eps.gz to .eps.gz. The mangled name is
502 // still unique because of the counter in mangledFileName().
503 // We can't just call mangledFileName() with the zip
504 // extension removed, because base.eps and base.eps.gz may
505 // have different content but would get the same mangled
506 // name in this case.
507 string const base = removeExtension(file.unzippedFileName());
508 string::size_type const ext_len = file_in.length() - base.length();
509 mangled[mangled.length() - ext_len] = '.';
511 FileName const file_out(makeAbsPath(mangled, dir));
513 return copyFileIfNeeded(file, file_out);
517 string const stripExtensionIfPossible(string const & file, bool nice)
519 // Remove the extension so the LaTeX compiler will use whatever
520 // is appropriate (when there are several versions in different
522 // Do this only if we are not exporting for internal usage, because
523 // pdflatex prefers png over pdf and it would pick up the png images
524 // that we generate for preview.
525 // This works only if the filename contains no dots besides
526 // the just removed one. We can fool here by replacing all
527 // dots with a macro whose definition is just a dot ;-)
528 // The automatic format selection does not work if the file
530 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
531 if (!nice || contains(latex_name, '"'))
533 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
537 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
539 // No conversion is needed. LaTeX can handle the graphic file as is.
540 // This is true even if the orig_file is compressed.
541 string const to_format = formats.getFormat(to)->extension();
542 string const file_format = getExtension(file);
543 // for latex .ps == .eps
544 if (to_format == file_format ||
545 (to_format == "eps" && file_format == "ps") ||
546 (to_format == "ps" && file_format == "eps"))
547 return stripExtensionIfPossible(file, nice);
548 return latex_path(file, EXCLUDE_EXTENSION);
554 string InsetGraphics::prepareFile(OutputParams const & runparams) const
556 // The following code depends on non-empty filenames
557 if (params().filename.empty())
560 string const orig_file = params().filename.absFileName();
561 // this is for dryrun and display purposes, do not use latexFilename
562 string const rel_file = params().filename.relFileName(buffer().filePath());
564 // previewing source code, no file copying or file format conversion
565 if (runparams.dryrun)
566 return stripExtensionIfPossible(rel_file, runparams.nice);
568 // The master buffer. This is useful when there are multiple levels
570 Buffer const * masterBuffer = buffer().masterBuffer();
572 // Return the output name if we are inside a comment or the file does
574 // We are not going to change the extension or using the name of the
575 // temporary file, the code is already complicated enough.
576 if (runparams.inComment || !params().filename.isReadableFile())
577 return params().filename.outputFileName(masterBuffer->filePath());
579 // We place all temporary files in the master buffer's temp dir.
580 // This is possible because we use mangled file names.
581 // This is necessary for DVI export.
582 string const temp_path = masterBuffer->temppath();
584 // temp_file will contain the file for LaTeX to act on if, for example,
585 // we move it to a temp dir or uncompress it.
587 GraphicsCopyStatus status;
588 boost::tie(status, temp_file) =
589 copyToDirIfNeeded(params().filename, temp_path);
591 if (status == FAILURE)
594 // a relative filename should be relative to the master buffer.
595 // "nice" means that the buffer is exported to LaTeX format but not
596 // run through the LaTeX compiler.
597 string output_file = runparams.nice ?
598 params().filename.outputFileName(masterBuffer->filePath()) :
599 onlyFileName(temp_file.absFileName());
601 if (runparams.nice) {
602 if (!isValidLaTeXFileName(output_file)) {
603 frontend::Alert::warning(_("Invalid filename"),
604 _("The following filename will cause troubles "
605 "when running the exported file through LaTeX: ") +
606 from_utf8(output_file));
608 // only show DVI-specific warning when export format is plain latex
609 if (!isValidDVIFileName(output_file)
610 && runparams.flavor == OutputParams::LATEX) {
611 frontend::Alert::warning(_("Problematic filename for DVI"),
612 _("The following filename can cause troubles "
613 "when running the exported file through LaTeX "
614 "and opening the resulting DVI: ") +
615 from_utf8(output_file), true);
619 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
620 // determine the export format
621 string const tex_format = flavor2format(runparams.flavor);
623 // If the file is compressed and we have specified that it
624 // should not be uncompressed, then just return its name and
625 // let LaTeX do the rest!
626 if (formats.isZippedFile(params().filename)) {
627 if (params().noUnzip) {
628 // We don't know whether latex can actually handle
629 // this file, but we can't check, because that would
630 // mean to unzip the file and thereby making the
631 // noUnzip parameter meaningless.
632 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
634 FileName const bb_orig_file =
635 FileName(changeExtension(orig_file, "bb"));
636 if (runparams.nice) {
637 runparams.exportdata->addExternalFile(tex_format,
639 changeExtension(output_file, "bb"));
641 // LaTeX needs the bounding box file in the
644 FileName(changeExtension(temp_file.absFileName(), "bb"));
645 boost::tie(status, bb_file) =
646 copyFileIfNeeded(bb_orig_file, bb_file);
647 if (status == FAILURE)
649 runparams.exportdata->addExternalFile(tex_format,
652 runparams.exportdata->addExternalFile(tex_format,
653 source_file, output_file);
654 runparams.exportdata->addExternalFile("dvi",
655 source_file, output_file);
656 // We can't strip the extension, because we don't know
657 // the unzipped file format
658 return latex_path(output_file, EXCLUDE_EXTENSION);
661 FileName const unzipped_temp_file =
662 FileName(unzippedFileName(temp_file.absFileName()));
663 output_file = unzippedFileName(output_file);
664 source_file = FileName(unzippedFileName(source_file.absFileName()));
665 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
666 // temp_file has been unzipped already and
667 // orig_file has not changed in the meantime.
668 temp_file = unzipped_temp_file;
669 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
671 // unzipped_temp_file does not exist or is too old
672 temp_file = unzipFile(temp_file);
673 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
677 string const from = formats.getFormatFromFile(temp_file);
679 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
681 string const to = findTargetFormat(from, runparams);
682 string const ext = formats.extension(to);
683 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
685 // We're going to be running the exported buffer through the LaTeX
686 // compiler, so must ensure that LaTeX can cope with the graphics
689 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
692 // source and destination formats are the same
693 if (!runparams.nice && !FileName(temp_file).hasExtension(ext)) {
694 // The LaTeX compiler will not be able to determine
695 // the file format from the extension, so we must
697 FileName const new_file =
698 FileName(changeExtension(temp_file.absFileName(), ext));
699 if (temp_file.moveTo(new_file)) {
700 temp_file = new_file;
701 output_file = changeExtension(output_file, ext);
703 FileName(changeExtension(source_file.absFileName(), ext));
705 LYXERR(Debug::GRAPHICS, "Could not rename file `"
706 << temp_file << "' to `" << new_file << "'.");
709 // The extension of temp_file might be != ext!
710 runparams.exportdata->addExternalFile(tex_format, source_file,
712 runparams.exportdata->addExternalFile("dvi", source_file,
714 return stripExtensionIfPossible(output_file, to, runparams.nice);
717 // so the source and destination formats are different
718 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
719 string const output_to_file = changeExtension(output_file, ext);
721 // Do we need to perform the conversion?
722 // Yes if to_file does not exist or if temp_file is newer than to_file
723 if (compare_timestamps(temp_file, to_file) < 0) {
725 LYXERR(Debug::GRAPHICS,
726 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
727 from_utf8(rel_file))));
728 runparams.exportdata->addExternalFile(tex_format, to_file,
730 runparams.exportdata->addExternalFile("dvi", to_file,
732 return stripExtensionIfPossible(output_to_file, runparams.nice);
735 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
736 << "\tA copy has been made and convert is to be called with:\n"
737 << "\tfile to convert = " << temp_file << '\n'
738 << "\t from " << from << " to " << to);
740 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
742 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
744 Converters::try_default | Converters::try_cache)) {
745 runparams.exportdata->addExternalFile(tex_format,
746 to_file, output_to_file);
747 runparams.exportdata->addExternalFile("dvi",
748 to_file, output_to_file);
751 return stripExtensionIfPossible(output_to_file, runparams.nice);
755 void InsetGraphics::latex(otexstream & os,
756 OutputParams const & runparams) const
758 // If there is no file specified or not existing,
759 // just output a message about it in the latex output.
760 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
761 << params().filename.absFileName());
763 bool const file_exists = !params().filename.empty()
764 && params().filename.isReadableFile();
767 if (params().bb.empty())
768 message = "bb = 0 0 200 100";
769 if (!params().draft) {
770 if (!message.empty())
774 if (!message.empty())
776 message += "type=eps";
778 // If no existing file "filename" was found LaTeX
779 // draws only a rectangle with the above bb and the
780 // not found filename in it.
781 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
783 // These variables collect all the latex code that should be before and
784 // after the actual includegraphics command.
788 if (runparams.moving_arg)
789 before += "\\protect";
791 // We never use the starred form, we use the "clip" option instead.
792 before += "\\includegraphics";
794 // Write the options if there are any.
795 string const opts = createLatexOptions();
796 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
798 if (!opts.empty() && !message.empty())
799 before += ('[' + opts + ',' + message + ']');
800 else if (!opts.empty() || !message.empty())
801 before += ('[' + opts + message + ']');
803 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
805 string latex_str = before + '{';
806 // Convert the file if necessary.
807 // Remove the extension so LaTeX will use whatever is appropriate
808 // (when there are several versions in different formats)
809 string file_path = prepareFile(runparams);
810 latex_str += file_path;
811 latex_str += '}' + after;
813 os << from_utf8(latex_str);
815 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
819 int InsetGraphics::plaintext(odocstringstream & os,
820 OutputParams const &, size_t) const
822 // No graphics in ascii output. Possible to use gifscii to convert
823 // images to ascii approximation.
824 // 1. Convert file to ascii using gifscii
825 // 2. Read ascii output file and add it to the output stream.
826 // at least we send the filename
828 // FIXME: We have no idea what the encoding of the filename is
830 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
831 from_utf8(params().filename.absFileName()));
832 os << '<' << str << '>';
834 return 2 + str.size();
838 static int writeImageObject(char const * format, odocstream & os,
839 OutputParams const & runparams, docstring const & graphic_label,
840 docstring const & attributes)
842 if (runparams.flavor != OutputParams::XML)
843 os << "<![ %output.print." << format
846 os <<"<imageobject><imagedata fileref=\"&"
853 if (runparams.flavor == OutputParams::XML)
854 os << " role=\"" << format << "\"/>" ;
856 os << " format=\"" << format << "\">" ;
858 os << "</imageobject>";
860 if (runparams.flavor != OutputParams::XML)
861 os << endl << "]]>" ;
863 return runparams.flavor == OutputParams::XML ? 0 : 2;
867 // For explanation on inserting graphics into DocBook checkout:
868 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
869 // See also the docbook guide at http://www.docbook.org/
870 int InsetGraphics::docbook(odocstream & os,
871 OutputParams const & runparams) const
873 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
874 // need to switch to MediaObject. However, for now this is sufficient and
876 if (runparams.flavor == OutputParams::XML)
877 runparams.exportdata->addExternalFile("docbook-xml",
880 runparams.exportdata->addExternalFile("docbook",
883 os << "<inlinemediaobject>";
886 docstring attributes = createDocBookAttributes();
887 r += writeImageObject("png", os, runparams, graphic_label, attributes);
888 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
889 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
890 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
892 os << "</inlinemediaobject>";
897 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
899 // The following code depends on non-empty filenames
900 if (params().filename.empty())
903 string const orig_file = params().filename.absFileName();
905 // The master buffer. This is useful when there are multiple levels
907 Buffer const * masterBuffer = buffer().masterBuffer();
909 if (!params().filename.isReadableFile())
912 // We place all temporary files in the master buffer's temp dir.
913 // This is possible because we use mangled file names.
914 // FIXME We may want to put these files in some special temporary
916 string const temp_path = masterBuffer->temppath();
918 // Copy to temporary directory.
920 GraphicsCopyStatus status;
921 boost::tie(status, temp_file) =
922 copyToDirIfNeeded(params().filename, temp_path);
924 if (status == FAILURE)
927 string output_file = onlyFileName(temp_file.absFileName());
929 string const from = formats.getFormatFromFile(temp_file);
931 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
933 string const to = findTargetFormat(from, runparams);
934 string const ext = formats.extension(to);
935 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
936 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
939 // source and destination formats are the same
940 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
944 // so the source and destination formats are different
945 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
946 string const output_to_file = changeExtension(output_file, ext);
948 // Do we need to perform the conversion?
949 // Yes if to_file does not exist or if temp_file is newer than to_file
950 if (compare_timestamps(temp_file, to_file) < 0) {
952 LYXERR(Debug::GRAPHICS,
953 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
954 from_utf8(orig_file))));
955 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
956 return output_to_file;
959 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
960 << "\tA copy has been made and convert is to be called with:\n"
961 << "\tfile to convert = " << temp_file << '\n'
962 << "\t from " << from << " to " << to);
964 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
967 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
968 from, to, el, Converters::try_default | Converters::try_cache);
971 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
972 return output_to_file;
976 docstring InsetGraphics::xhtml(XHTMLStream & xs, OutputParams const & op) const
978 string const output_file = prepareHTMLFile(op);
980 if (output_file.empty()) {
981 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
982 << params().filename << "' for output. File missing?");
983 string const attr = "src='" + params().filename.absFileName()
984 + "' alt='image: " + output_file + "'";
985 xs << html::CompTag("img", attr);
990 // We aren't doing anything with the crop and rotate parameters, and it would
991 // really be better to do width and height conversion, rather than to output
992 // these parameters here.
994 if (!params().width.zero())
995 imgstyle += "width:" + params().width.asHTMLString() + ";";
996 if (!params().height.zero())
997 imgstyle += " height:" + params().height.asHTMLString() + ";";
998 if (!imgstyle.empty())
999 imgstyle = "style='" + imgstyle + "' ";
1001 string const attr = imgstyle + "src='" + output_file + "' alt='image: "
1002 + output_file + "'";
1003 xs << html::CompTag("img", attr);
1008 void InsetGraphics::validate(LaTeXFeatures & features) const
1010 // If we have no image, we should not require anything.
1011 if (params().filename.empty())
1014 features.includeFile(graphic_label,
1015 removeExtension(params().filename.absFileName()));
1017 features.require("graphicx");
1019 if (features.runparams().nice) {
1020 string const rel_file = params().filename.onlyFileNameWithoutExt();
1021 if (contains(rel_file, "."))
1022 features.require("lyxdot");
1027 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1029 // If nothing is changed, just return and say so.
1030 if (params() == p && !p.filename.empty())
1033 // Copy the new parameters.
1036 // Update the display using the new parameters.
1037 graphic_->update(params().as_grfxParams());
1039 // We have changed data, report it.
1044 InsetGraphicsParams const & InsetGraphics::params() const
1050 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1052 formats.edit(buffer(), p.filename,
1053 formats.getFormatFromFile(p.filename));
1057 void InsetGraphics::addToToc(DocIterator const & cpit, bool output_active) const
1060 docstring const str = from_utf8(params_.filename.onlyFileName());
1061 buffer().tocBackend().toc("graphics").push_back(TocItem(cpit, 0, str, output_active));
1065 string InsetGraphics::contextMenuName() const
1067 return "context-graphics";
1071 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1072 InsetGraphicsParams & params)
1077 istringstream data(in);
1079 lex.setStream(data);
1080 lex.setContext("InsetGraphics::string2params");
1082 params = InsetGraphicsParams();
1083 readInsetGraphics(lex, buffer.filePath(), params);
1087 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1088 Buffer const & buffer)
1091 data << "graphics" << ' ';
1092 params.Write(data, buffer);
1093 data << "\\end_inset\n";
1098 docstring InsetGraphics::toolTip(BufferView const &, int, int) const
1100 return from_utf8(params().filename.onlyFileName());
1103 namespace graphics {
1105 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1107 Inset & inset = b.inset();
1108 InsetIterator it = inset_iterator_begin(inset);
1109 InsetIterator const end = inset_iterator_end(inset);
1110 for (; it != end; ++it)
1111 if (it->lyxCode() == GRAPHICS_CODE) {
1112 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1113 InsetGraphicsParams inspar = ins.getParams();
1114 if (!inspar.groupId.empty())
1115 ids.insert(inspar.groupId);
1120 int countGroupMembers(Buffer const & b, string const & groupId)
1123 if (groupId.empty())
1125 Inset & inset = b.inset();
1126 InsetIterator it = inset_iterator_begin(inset);
1127 InsetIterator const end = inset_iterator_end(inset);
1128 for (; it != end; ++it)
1129 if (it->lyxCode() == GRAPHICS_CODE) {
1130 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1131 if (ins.getParams().groupId == groupId)
1138 string getGroupParams(Buffer const & b, string const & groupId)
1140 if (groupId.empty())
1142 Inset & inset = b.inset();
1143 InsetIterator it = inset_iterator_begin(inset);
1144 InsetIterator const end = inset_iterator_end(inset);
1145 for (; it != end; ++it)
1146 if (it->lyxCode() == GRAPHICS_CODE) {
1147 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1148 InsetGraphicsParams inspar = ins.getParams();
1149 if (inspar.groupId == groupId) {
1150 InsetGraphicsParams tmp = inspar;
1151 tmp.filename.erase();
1152 return InsetGraphics::params2string(tmp, b);
1159 void unifyGraphicsGroups(Buffer & b, string const & argument)
1161 InsetGraphicsParams params;
1162 InsetGraphics::string2params(argument, b, params);
1164 b.undo().beginUndoGroup();
1165 Inset & inset = b.inset();
1166 InsetIterator it = inset_iterator_begin(inset);
1167 InsetIterator const end = inset_iterator_end(inset);
1168 for (; it != end; ++it) {
1169 if (it->lyxCode() == GRAPHICS_CODE) {
1170 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1171 InsetGraphicsParams inspar = ins.getParams();
1172 if (params.groupId == inspar.groupId) {
1173 b.undo().recordUndo(CursorData(it));
1174 params.filename = inspar.filename;
1175 ins.setParams(params);
1179 b.undo().endUndoGroup();
1183 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1185 Inset * instmp = &cur.inset();
1186 if (instmp->lyxCode() != GRAPHICS_CODE)
1187 instmp = cur.nextInset();
1188 if (!instmp || instmp->lyxCode() != GRAPHICS_CODE)
1191 return static_cast<InsetGraphics *>(instmp);
1194 } // namespace graphics