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 InsetGraphicsParams p;
207 string2params(to_utf8(cmd.argument()), buffer(), p);
208 if (p.filename.empty()) {
209 cur.noScreenUpdate();
215 // if the inset is part of a graphics group, all the
216 // other members should be updated too.
217 if (!params_.groupId.empty())
218 graphics::unifyGraphicsGroups(buffer(),
219 to_utf8(cmd.argument()));
223 case LFUN_INSET_DIALOG_UPDATE:
224 cur.bv().updateDialog("graphics", params2string(params(), buffer()));
227 case LFUN_GRAPHICS_RELOAD:
228 params_.filename.refresh();
233 Inset::doDispatch(cur, cmd);
239 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
240 FuncStatus & flag) const
242 switch (cmd.action()) {
243 case LFUN_INSET_EDIT:
244 case LFUN_INSET_MODIFY:
245 case LFUN_INSET_DIALOG_UPDATE:
246 case LFUN_GRAPHICS_RELOAD:
247 flag.setEnabled(true);
251 return Inset::getStatus(cur, cmd, flag);
256 bool InsetGraphics::showInsetDialog(BufferView * bv) const
258 bv->showDialog("graphics", params2string(params(), bv->buffer()),
259 const_cast<InsetGraphics *>(this));
265 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
267 graphic_->metrics(mi, dim);
271 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
273 graphic_->draw(pi, x, y);
277 void InsetGraphics::write(ostream & os) const
280 params().Write(os, buffer());
284 void InsetGraphics::read(Lexer & lex)
286 lex.setContext("InsetGraphics::read");
288 readInsetGraphics(lex, buffer().filePath(), params_);
289 graphic_->update(params().as_grfxParams());
293 string InsetGraphics::createLatexOptions() const
295 // Calculate the options part of the command, we must do it to a string
296 // stream since we might have a trailing comma that we would like to remove
297 // before writing it to the output stream.
298 ostringstream options;
299 if (!params().bb.empty())
300 options << "bb=" << rtrim(params().bb) << ',';
306 double const scl = convert<double>(params().scale);
307 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
308 if (!float_equal(scl, 100.0, 0.05))
309 size << "scale=" << scl / 100.0 << ',';
311 if (!params().width.zero())
312 size << "width=" << params().width.asLatexString() << ',';
313 if (!params().height.zero())
314 size << "height=" << params().height.asLatexString() << ',';
315 if (params().keepAspectRatio)
316 size << "keepaspectratio,";
318 if (params().scaleBeforeRotation && !size.str().empty())
319 options << size.str();
321 // Make sure rotation angle is not very close to zero;
322 // a float can be effectively zero but not exactly zero.
323 if (!params().rotateAngle.empty()
324 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
325 options << "angle=" << params().rotateAngle << ',';
326 if (!params().rotateOrigin.empty()) {
327 options << "origin=" << params().rotateOrigin[0];
328 if (contains(params().rotateOrigin,"Top"))
330 else if (contains(params().rotateOrigin,"Bottom"))
332 else if (contains(params().rotateOrigin,"Baseline"))
337 if (!params().scaleBeforeRotation && !size.str().empty())
338 options << size.str();
340 if (!params().special.empty())
341 options << params().special << ',';
343 string opts = options.str();
345 if (suffixIs(opts, ','))
346 opts = opts.substr(0, opts.size() - 1);
352 docstring InsetGraphics::toDocbookLength(Length const & len) const
354 odocstringstream result;
355 switch (len.unit()) {
356 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
357 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
359 case Length::PT: // Point = 1/72.27in = 0.351mm
360 result << len.value() * 72 / 72.27 << "pt";
362 case Length::BP: // Big point (72bp = 1in), also PostScript point
363 result << len.value() << "pt";
365 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
366 result << len.value() * 0.376 << "mm";
368 case Length::MM: // Millimeter = 2.845pt
369 result << len.value() << "mm";
371 case Length::PC: // Pica = 12pt = 4.218mm
372 result << len.value() << "pc";
374 case Length::CC: // Cicero = 12dd = 4.531mm
375 result << len.value() * 4.531 << "mm";
377 case Length::CM: // Centimeter = 10mm = 2.371pc
378 result << len.value() << "cm";
380 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
381 result << len.value() << "in";
383 case Length::EX: // Height of a small "x" for the current font.
384 // Obviously we have to compromise here. Any better ratio than 1.5 ?
385 result << len.value() / 1.5 << "em";
387 case Length::EM: // Width of capital "M" in current font.
388 result << len.value() << "em";
390 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
391 result << len.value() * 18 << "em";
393 case Length::PTW: // Percent of TextWidth
394 case Length::PCW: // Percent of ColumnWidth
395 case Length::PPW: // Percent of PageWidth
396 case Length::PLW: // Percent of LineWidth
397 case Length::PTH: // Percent of TextHeight
398 case Length::PPH: // Percent of PaperHeight
399 // Sigh, this will go wrong.
400 result << len.value() << "%";
403 result << len.asDocstring();
410 docstring InsetGraphics::createDocBookAttributes() const
412 // Calculate the options part of the command, we must do it to a string
413 // stream since we copied the code from createLatexParams() ;-)
415 // FIXME: av: need to translate spec -> Docbook XSL spec
416 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
417 // Right now it only works with my version of db2latex :-)
419 odocstringstream options;
420 double const scl = convert<double>(params().scale);
421 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
422 if (!float_equal(scl, 100.0, 0.05))
423 options << " scale=\""
424 << static_cast<int>( (scl) + 0.5 )
427 if (!params().width.zero()) {
428 options << " width=\"" << toDocbookLength(params().width) << "\" ";
430 if (!params().height.zero()) {
431 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
433 if (params().keepAspectRatio) {
434 // This will be irrelevant unless both width and height are set
435 options << "scalefit=\"1\" ";
440 if (!params().special.empty())
441 options << from_ascii(params().special) << " ";
443 // trailing blanks are ok ...
444 return options.str();
450 enum GraphicsCopyStatus {
458 pair<GraphicsCopyStatus, FileName> const
459 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
461 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
462 unsigned long const checksum_in = file_in.checksum();
463 unsigned long const checksum_out = file_out.checksum();
465 if (checksum_in == checksum_out)
467 return make_pair(IDENTICAL_CONTENTS, file_out);
469 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
470 bool const success = mover.copy(file_in, file_out);
473 LYXERR(Debug::GRAPHICS,
474 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
475 "into the temporary directory."),
476 from_utf8(file_in.absFileName()))));
479 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
480 return make_pair(status, file_out);
484 pair<GraphicsCopyStatus, FileName> const
485 copyToDirIfNeeded(DocFileName const & file, string const & dir)
487 string const file_in = file.absFileName();
488 string const only_path = onlyPath(file_in);
489 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
490 return make_pair(IDENTICAL_PATHS, FileName(file_in));
492 string mangled = file.mangledFileName();
493 if (formats.isZippedFile(file)) {
494 // We need to change _eps.gz to .eps.gz. The mangled name is
495 // still unique because of the counter in mangledFileName().
496 // We can't just call mangledFileName() with the zip
497 // extension removed, because base.eps and base.eps.gz may
498 // have different content but would get the same mangled
499 // name in this case.
500 string const base = removeExtension(file.unzippedFileName());
501 string::size_type const ext_len = file_in.length() - base.length();
502 mangled[mangled.length() - ext_len] = '.';
504 FileName const file_out(makeAbsPath(mangled, dir));
506 return copyFileIfNeeded(file, file_out);
510 string const stripExtensionIfPossible(string const & file, bool nice)
512 // Remove the extension so the LaTeX compiler will use whatever
513 // is appropriate (when there are several versions in different
515 // Do this only if we are not exporting for internal usage, because
516 // pdflatex prefers png over pdf and it would pick up the png images
517 // that we generate for preview.
518 // This works only if the filename contains no dots besides
519 // the just removed one. We can fool here by replacing all
520 // dots with a macro whose definition is just a dot ;-)
521 // The automatic format selection does not work if the file
523 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
524 if (!nice || contains(latex_name, '"'))
526 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
530 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
532 // No conversion is needed. LaTeX can handle the graphic file as is.
533 // This is true even if the orig_file is compressed.
534 string const to_format = formats.getFormat(to)->extension();
535 string const file_format = getExtension(file);
536 // for latex .ps == .eps
537 if (to_format == file_format ||
538 (to_format == "eps" && file_format == "ps") ||
539 (to_format == "ps" && file_format == "eps"))
540 return stripExtensionIfPossible(file, nice);
541 return latex_path(file, EXCLUDE_EXTENSION);
547 string InsetGraphics::prepareFile(OutputParams const & runparams) const
549 // The following code depends on non-empty filenames
550 if (params().filename.empty())
553 string const orig_file = params().filename.absFileName();
554 // this is for dryrun and display purposes, do not use latexFilename
555 string const rel_file = params().filename.relFileName(buffer().filePath());
557 // previewing source code, no file copying or file format conversion
558 if (runparams.dryrun)
559 return stripExtensionIfPossible(rel_file, runparams.nice);
561 // The master buffer. This is useful when there are multiple levels
563 Buffer const * masterBuffer = buffer().masterBuffer();
565 // Return the output name if we are inside a comment or the file does
567 // We are not going to change the extension or using the name of the
568 // temporary file, the code is already complicated enough.
569 if (runparams.inComment || !params().filename.isReadableFile())
570 return params().filename.outputFileName(masterBuffer->filePath());
572 // We place all temporary files in the master buffer's temp dir.
573 // This is possible because we use mangled file names.
574 // This is necessary for DVI export.
575 string const temp_path = masterBuffer->temppath();
577 // temp_file will contain the file for LaTeX to act on if, for example,
578 // we move it to a temp dir or uncompress it.
580 GraphicsCopyStatus status;
581 boost::tie(status, temp_file) =
582 copyToDirIfNeeded(params().filename, temp_path);
584 if (status == FAILURE)
587 // a relative filename should be relative to the master buffer.
588 // "nice" means that the buffer is exported to LaTeX format but not
589 // run through the LaTeX compiler.
590 string output_file = runparams.nice ?
591 params().filename.outputFileName(masterBuffer->filePath()) :
592 onlyFileName(temp_file.absFileName());
594 if (runparams.nice) {
595 if (!isValidLaTeXFileName(output_file)) {
596 frontend::Alert::warning(_("Invalid filename"),
597 _("The following filename will cause troubles "
598 "when running the exported file through LaTeX: ") +
599 from_utf8(output_file));
601 // only show DVI-specific warning when export format is plain latex
602 if (!isValidDVIFileName(output_file)
603 && runparams.flavor == OutputParams::LATEX) {
604 frontend::Alert::warning(_("Problematic filename for DVI"),
605 _("The following filename can cause troubles "
606 "when running the exported file through LaTeX "
607 "and opening the resulting DVI: ") +
608 from_utf8(output_file), true);
612 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
613 // determine the export format
614 string const tex_format = flavor2format(runparams.flavor);
616 // If the file is compressed and we have specified that it
617 // should not be uncompressed, then just return its name and
618 // let LaTeX do the rest!
619 if (formats.isZippedFile(params().filename)) {
620 if (params().noUnzip) {
621 // We don't know whether latex can actually handle
622 // this file, but we can't check, because that would
623 // mean to unzip the file and thereby making the
624 // noUnzip parameter meaningless.
625 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
627 FileName const bb_orig_file =
628 FileName(changeExtension(orig_file, "bb"));
629 if (runparams.nice) {
630 runparams.exportdata->addExternalFile(tex_format,
632 changeExtension(output_file, "bb"));
634 // LaTeX needs the bounding box file in the
637 FileName(changeExtension(temp_file.absFileName(), "bb"));
638 boost::tie(status, bb_file) =
639 copyFileIfNeeded(bb_orig_file, bb_file);
640 if (status == FAILURE)
642 runparams.exportdata->addExternalFile(tex_format,
645 runparams.exportdata->addExternalFile(tex_format,
646 source_file, output_file);
647 runparams.exportdata->addExternalFile("dvi",
648 source_file, output_file);
649 // We can't strip the extension, because we don't know
650 // the unzipped file format
651 return latex_path(output_file, EXCLUDE_EXTENSION);
654 FileName const unzipped_temp_file =
655 FileName(unzippedFileName(temp_file.absFileName()));
656 output_file = unzippedFileName(output_file);
657 source_file = FileName(unzippedFileName(source_file.absFileName()));
658 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
659 // temp_file has been unzipped already and
660 // orig_file has not changed in the meantime.
661 temp_file = unzipped_temp_file;
662 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
664 // unzipped_temp_file does not exist or is too old
665 temp_file = unzipFile(temp_file);
666 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
670 string const from = formats.getFormatFromFile(temp_file);
672 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
674 string const to = findTargetFormat(from, runparams);
675 string const ext = formats.extension(to);
676 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
678 // We're going to be running the exported buffer through the LaTeX
679 // compiler, so must ensure that LaTeX can cope with the graphics
682 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
685 // source and destination formats are the same
686 if (!runparams.nice && !FileName(temp_file).hasExtension(ext)) {
687 // The LaTeX compiler will not be able to determine
688 // the file format from the extension, so we must
690 FileName const new_file =
691 FileName(changeExtension(temp_file.absFileName(), ext));
692 if (temp_file.moveTo(new_file)) {
693 temp_file = new_file;
694 output_file = changeExtension(output_file, ext);
696 FileName(changeExtension(source_file.absFileName(), ext));
698 LYXERR(Debug::GRAPHICS, "Could not rename file `"
699 << temp_file << "' to `" << new_file << "'.");
702 // The extension of temp_file might be != ext!
703 runparams.exportdata->addExternalFile(tex_format, source_file,
705 runparams.exportdata->addExternalFile("dvi", source_file,
707 return stripExtensionIfPossible(output_file, to, runparams.nice);
710 // so the source and destination formats are different
711 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
712 string const output_to_file = changeExtension(output_file, ext);
714 // Do we need to perform the conversion?
715 // Yes if to_file does not exist or if temp_file is newer than to_file
716 if (compare_timestamps(temp_file, to_file) < 0) {
718 LYXERR(Debug::GRAPHICS,
719 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
720 from_utf8(rel_file))));
721 runparams.exportdata->addExternalFile(tex_format, to_file,
723 runparams.exportdata->addExternalFile("dvi", to_file,
725 return stripExtensionIfPossible(output_to_file, runparams.nice);
728 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
729 << "\tA copy has been made and convert is to be called with:\n"
730 << "\tfile to convert = " << temp_file << '\n'
731 << "\t from " << from << " to " << to);
733 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
735 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
737 Converters::try_default | Converters::try_cache)) {
738 runparams.exportdata->addExternalFile(tex_format,
739 to_file, output_to_file);
740 runparams.exportdata->addExternalFile("dvi",
741 to_file, output_to_file);
744 return stripExtensionIfPossible(output_to_file, runparams.nice);
748 void InsetGraphics::latex(otexstream & os,
749 OutputParams const & runparams) const
751 // If there is no file specified or not existing,
752 // just output a message about it in the latex output.
753 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
754 << params().filename.absFileName());
756 bool const file_exists = !params().filename.empty()
757 && params().filename.isReadableFile();
760 if (params().bb.empty())
761 message = "bb = 0 0 200 100";
762 if (!params().draft) {
763 if (!message.empty())
767 if (!message.empty())
769 message += "type=eps";
771 // If no existing file "filename" was found LaTeX
772 // draws only a rectangle with the above bb and the
773 // not found filename in it.
774 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
776 // These variables collect all the latex code that should be before and
777 // after the actual includegraphics command.
781 if (runparams.moving_arg)
782 before += "\\protect";
784 // We never use the starred form, we use the "clip" option instead.
785 before += "\\includegraphics";
787 // Write the options if there are any.
788 string const opts = createLatexOptions();
789 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
791 if (!opts.empty() && !message.empty())
792 before += ('[' + opts + ',' + message + ']');
793 else if (!opts.empty() || !message.empty())
794 before += ('[' + opts + message + ']');
796 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
798 string latex_str = before + '{';
799 // Convert the file if necessary.
800 // Remove the extension so LaTeX will use whatever is appropriate
801 // (when there are several versions in different formats)
802 string file_path = prepareFile(runparams);
803 latex_str += file_path;
804 latex_str += '}' + after;
806 os << from_utf8(latex_str);
808 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
812 int InsetGraphics::plaintext(odocstringstream & os,
813 OutputParams const &, size_t) const
815 // No graphics in ascii output. Possible to use gifscii to convert
816 // images to ascii approximation.
817 // 1. Convert file to ascii using gifscii
818 // 2. Read ascii output file and add it to the output stream.
819 // at least we send the filename
821 // FIXME: We have no idea what the encoding of the filename is
823 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
824 from_utf8(params().filename.absFileName()));
825 os << '<' << str << '>';
827 return 2 + str.size();
831 static int writeImageObject(char const * format, odocstream & os,
832 OutputParams const & runparams, docstring const & graphic_label,
833 docstring const & attributes)
835 if (runparams.flavor != OutputParams::XML)
836 os << "<![ %output.print." << format
839 os <<"<imageobject><imagedata fileref=\"&"
846 if (runparams.flavor == OutputParams::XML)
847 os << " role=\"" << format << "\"/>" ;
849 os << " format=\"" << format << "\">" ;
851 os << "</imageobject>";
853 if (runparams.flavor != OutputParams::XML)
854 os << endl << "]]>" ;
856 return runparams.flavor == OutputParams::XML ? 0 : 2;
860 // For explanation on inserting graphics into DocBook checkout:
861 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
862 // See also the docbook guide at http://www.docbook.org/
863 int InsetGraphics::docbook(odocstream & os,
864 OutputParams const & runparams) const
866 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
867 // need to switch to MediaObject. However, for now this is sufficient and
869 if (runparams.flavor == OutputParams::XML)
870 runparams.exportdata->addExternalFile("docbook-xml",
873 runparams.exportdata->addExternalFile("docbook",
876 os << "<inlinemediaobject>";
879 docstring attributes = createDocBookAttributes();
880 r += writeImageObject("png", os, runparams, graphic_label, attributes);
881 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
882 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
883 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
885 os << "</inlinemediaobject>";
890 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
892 // The following code depends on non-empty filenames
893 if (params().filename.empty())
896 string const orig_file = params().filename.absFileName();
898 // The master buffer. This is useful when there are multiple levels
900 Buffer const * masterBuffer = buffer().masterBuffer();
902 if (!params().filename.isReadableFile())
905 // We place all temporary files in the master buffer's temp dir.
906 // This is possible because we use mangled file names.
907 // FIXME We may want to put these files in some special temporary
909 string const temp_path = masterBuffer->temppath();
911 // Copy to temporary directory.
913 GraphicsCopyStatus status;
914 boost::tie(status, temp_file) =
915 copyToDirIfNeeded(params().filename, temp_path);
917 if (status == FAILURE)
920 string output_file = onlyFileName(temp_file.absFileName());
922 string const from = formats.getFormatFromFile(temp_file);
924 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
926 string const to = findTargetFormat(from, runparams);
927 string const ext = formats.extension(to);
928 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
929 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
932 // source and destination formats are the same
933 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
937 // so the source and destination formats are different
938 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
939 string const output_to_file = changeExtension(output_file, ext);
941 // Do we need to perform the conversion?
942 // Yes if to_file does not exist or if temp_file is newer than to_file
943 if (compare_timestamps(temp_file, to_file) < 0) {
945 LYXERR(Debug::GRAPHICS,
946 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
947 from_utf8(orig_file))));
948 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
949 return output_to_file;
952 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
953 << "\tA copy has been made and convert is to be called with:\n"
954 << "\tfile to convert = " << temp_file << '\n'
955 << "\t from " << from << " to " << to);
957 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
960 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
961 from, to, el, Converters::try_default | Converters::try_cache);
964 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
965 return output_to_file;
969 docstring InsetGraphics::xhtml(XHTMLStream & xs, OutputParams const & op) const
971 string const output_file = prepareHTMLFile(op);
973 if (output_file.empty()) {
974 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
975 << params().filename << "' for output. File missing?");
976 string const attr = "src='" + params().filename.absFileName()
977 + "' alt='image: " + output_file + "'";
978 xs << html::CompTag("img", attr);
983 // We aren't doing anything with the crop and rotate parameters, and it would
984 // really be better to do width and height conversion, rather than to output
985 // these parameters here.
987 if (!params().width.zero())
988 imgstyle += "width:" + params().width.asHTMLString() + ";";
989 if (!params().height.zero())
990 imgstyle += " height:" + params().height.asHTMLString() + ";";
991 if (!imgstyle.empty())
992 imgstyle = "style='" + imgstyle + "' ";
994 string const attr = imgstyle + "src='" + output_file + "' alt='image: "
996 xs << html::CompTag("img", attr);
1001 void InsetGraphics::validate(LaTeXFeatures & features) const
1003 // If we have no image, we should not require anything.
1004 if (params().filename.empty())
1007 features.includeFile(graphic_label,
1008 removeExtension(params().filename.absFileName()));
1010 features.require("graphicx");
1012 if (features.runparams().nice) {
1013 string const rel_file = params().filename.onlyFileNameWithoutExt();
1014 if (contains(rel_file, "."))
1015 features.require("lyxdot");
1020 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1022 // If nothing is changed, just return and say so.
1023 if (params() == p && !p.filename.empty())
1026 // Copy the new parameters.
1029 // Update the display using the new parameters.
1030 graphic_->update(params().as_grfxParams());
1032 // We have changed data, report it.
1037 InsetGraphicsParams const & InsetGraphics::params() const
1043 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1045 formats.edit(buffer(), p.filename,
1046 formats.getFormatFromFile(p.filename));
1050 void InsetGraphics::addToToc(DocIterator const & cpit, bool output_active) const
1053 docstring const str = from_utf8(params_.filename.onlyFileName());
1054 buffer().tocBackend().toc("graphics").push_back(TocItem(cpit, 0, str, output_active));
1058 string InsetGraphics::contextMenuName() const
1060 return "context-graphics";
1064 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1065 InsetGraphicsParams & params)
1070 istringstream data(in);
1072 lex.setStream(data);
1073 lex.setContext("InsetGraphics::string2params");
1075 params = InsetGraphicsParams();
1076 readInsetGraphics(lex, buffer.filePath(), params);
1080 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1081 Buffer const & buffer)
1084 data << "graphics" << ' ';
1085 params.Write(data, buffer);
1086 data << "\\end_inset\n";
1091 docstring InsetGraphics::toolTip(BufferView const &, int, int) const
1093 return from_utf8(params().filename.onlyFileName());
1096 namespace graphics {
1098 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1100 Inset & inset = b.inset();
1101 InsetIterator it = inset_iterator_begin(inset);
1102 InsetIterator const end = inset_iterator_end(inset);
1103 for (; it != end; ++it)
1104 if (it->lyxCode() == GRAPHICS_CODE) {
1105 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1106 InsetGraphicsParams inspar = ins.getParams();
1107 if (!inspar.groupId.empty())
1108 ids.insert(inspar.groupId);
1113 int countGroupMembers(Buffer const & b, string const & groupId)
1116 if (groupId.empty())
1118 Inset & inset = b.inset();
1119 InsetIterator it = inset_iterator_begin(inset);
1120 InsetIterator const end = inset_iterator_end(inset);
1121 for (; it != end; ++it)
1122 if (it->lyxCode() == GRAPHICS_CODE) {
1123 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1124 if (ins.getParams().groupId == groupId)
1131 string getGroupParams(Buffer const & b, string const & groupId)
1133 if (groupId.empty())
1135 Inset & inset = b.inset();
1136 InsetIterator it = inset_iterator_begin(inset);
1137 InsetIterator const end = inset_iterator_end(inset);
1138 for (; it != end; ++it)
1139 if (it->lyxCode() == GRAPHICS_CODE) {
1140 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1141 InsetGraphicsParams inspar = ins.getParams();
1142 if (inspar.groupId == groupId) {
1143 InsetGraphicsParams tmp = inspar;
1144 tmp.filename.erase();
1145 return InsetGraphics::params2string(tmp, b);
1152 void unifyGraphicsGroups(Buffer & b, string const & argument)
1154 InsetGraphicsParams params;
1155 InsetGraphics::string2params(argument, b, params);
1157 b.undo().beginUndoGroup();
1158 Inset & inset = b.inset();
1159 InsetIterator it = inset_iterator_begin(inset);
1160 InsetIterator const end = inset_iterator_end(inset);
1161 for (; it != end; ++it) {
1162 if (it->lyxCode() == GRAPHICS_CODE) {
1163 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1164 InsetGraphicsParams inspar = ins.getParams();
1165 if (params.groupId == inspar.groupId) {
1166 b.undo().recordUndo(CursorData(it));
1167 params.filename = inspar.filename;
1168 ins.setParams(params);
1172 b.undo().endUndoGroup();
1176 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1178 Inset * instmp = &cur.inset();
1179 if (instmp->lyxCode() != GRAPHICS_CODE)
1180 instmp = cur.nextInset();
1181 if (!instmp || instmp->lyxCode() != GRAPHICS_CODE)
1184 return static_cast<InsetGraphics *>(instmp);
1187 } // namespace graphics