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, file_in);
492 string mangled = file.mangledFileName();
493 if (file.isZipped()) {
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 = (runparams.flavor == OutputParams::LATEX) ?
615 "latex" : "pdflatex";
617 // If the file is compressed and we have specified that it
618 // should not be uncompressed, then just return its name and
619 // let LaTeX do the rest!
620 if (params().filename.isZipped()) {
621 if (params().noUnzip) {
622 // We don't know whether latex can actually handle
623 // this file, but we can't check, because that would
624 // mean to unzip the file and thereby making the
625 // noUnzip parameter meaningless.
626 LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
628 FileName const bb_orig_file =
629 FileName(changeExtension(orig_file, "bb"));
630 if (runparams.nice) {
631 runparams.exportdata->addExternalFile(tex_format,
633 changeExtension(output_file, "bb"));
635 // LaTeX needs the bounding box file in the
638 FileName(changeExtension(temp_file.absFileName(), "bb"));
639 boost::tie(status, bb_file) =
640 copyFileIfNeeded(bb_orig_file, bb_file);
641 if (status == FAILURE)
643 runparams.exportdata->addExternalFile(tex_format,
646 runparams.exportdata->addExternalFile(tex_format,
647 source_file, output_file);
648 runparams.exportdata->addExternalFile("dvi",
649 source_file, output_file);
650 // We can't strip the extension, because we don't know
651 // the unzipped file format
652 return latex_path(output_file, EXCLUDE_EXTENSION);
655 FileName const unzipped_temp_file =
656 FileName(unzippedFileName(temp_file.absFileName()));
657 output_file = unzippedFileName(output_file);
658 source_file = FileName(unzippedFileName(source_file.absFileName()));
659 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
660 // temp_file has been unzipped already and
661 // orig_file has not changed in the meantime.
662 temp_file = unzipped_temp_file;
663 LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
665 // unzipped_temp_file does not exist or is too old
666 temp_file = unzipFile(temp_file);
667 LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
671 string const from = formats.getFormatFromFile(temp_file);
673 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
675 string const to = findTargetFormat(from, runparams);
676 string const ext = formats.extension(to);
677 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
679 // We're going to be running the exported buffer through the LaTeX
680 // compiler, so must ensure that LaTeX can cope with the graphics
683 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
686 // source and destination formats are the same
687 if (!runparams.nice && !FileName(temp_file).hasExtension(ext)) {
688 // The LaTeX compiler will not be able to determine
689 // the file format from the extension, so we must
691 FileName const new_file =
692 FileName(changeExtension(temp_file.absFileName(), ext));
693 if (temp_file.moveTo(new_file)) {
694 temp_file = new_file;
695 output_file = changeExtension(output_file, ext);
697 FileName(changeExtension(source_file.absFileName(), ext));
699 LYXERR(Debug::GRAPHICS, "Could not rename file `"
700 << temp_file << "' to `" << new_file << "'.");
703 // The extension of temp_file might be != ext!
704 runparams.exportdata->addExternalFile(tex_format, source_file,
706 runparams.exportdata->addExternalFile("dvi", source_file,
708 return stripExtensionIfPossible(output_file, to, runparams.nice);
711 // so the source and destination formats are different
712 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
713 string const output_to_file = changeExtension(output_file, ext);
715 // Do we need to perform the conversion?
716 // Yes if to_file does not exist or if temp_file is newer than to_file
717 if (compare_timestamps(temp_file, to_file) < 0) {
719 LYXERR(Debug::GRAPHICS,
720 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
721 from_utf8(rel_file))));
722 runparams.exportdata->addExternalFile(tex_format, to_file,
724 runparams.exportdata->addExternalFile("dvi", to_file,
726 return stripExtensionIfPossible(output_to_file, runparams.nice);
729 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
730 << "\tA copy has been made and convert is to be called with:\n"
731 << "\tfile to convert = " << temp_file << '\n'
732 << "\t from " << from << " to " << to);
734 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
736 if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
738 Converters::try_default | Converters::try_cache)) {
739 runparams.exportdata->addExternalFile(tex_format,
740 to_file, output_to_file);
741 runparams.exportdata->addExternalFile("dvi",
742 to_file, output_to_file);
745 return stripExtensionIfPossible(output_to_file, runparams.nice);
749 void InsetGraphics::latex(otexstream & os,
750 OutputParams const & runparams) const
752 // If there is no file specified or not existing,
753 // just output a message about it in the latex output.
754 LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
755 << params().filename.absFileName());
757 bool const file_exists = !params().filename.empty()
758 && params().filename.isReadableFile();
759 string const message = file_exists ?
760 string() : string("bb = 0 0 200 100, draft, type=eps");
761 // if !message.empty() then there was no existing file
762 // "filename" found. In this case LaTeX
763 // draws only a rectangle with the above bb and the
764 // not found filename in it.
765 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
767 // These variables collect all the latex code that should be before and
768 // after the actual includegraphics command.
772 if (runparams.moving_arg)
773 before += "\\protect";
775 // We never use the starred form, we use the "clip" option instead.
776 before += "\\includegraphics";
778 // Write the options if there are any.
779 string const opts = createLatexOptions();
780 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
782 if (!opts.empty() && !message.empty())
783 before += ('[' + opts + ',' + message + ']');
784 else if (!opts.empty() || !message.empty())
785 before += ('[' + opts + message + ']');
787 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
789 string latex_str = before + '{';
790 // Convert the file if necessary.
791 // Remove the extension so LaTeX will use whatever is appropriate
792 // (when there are several versions in different formats)
793 latex_str += prepareFile(runparams);
794 latex_str += '}' + after;
796 os << from_utf8(latex_str);
798 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
802 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
804 // No graphics in ascii output. Possible to use gifscii to convert
805 // images to ascii approximation.
806 // 1. Convert file to ascii using gifscii
807 // 2. Read ascii output file and add it to the output stream.
808 // at least we send the filename
810 // FIXME: We have no idea what the encoding of the filename is
812 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
813 from_utf8(params().filename.absFileName()));
814 os << '<' << str << '>';
816 return 2 + str.size();
820 static int writeImageObject(char const * format, odocstream & os,
821 OutputParams const & runparams, docstring const & graphic_label,
822 docstring const & attributes)
824 if (runparams.flavor != OutputParams::XML)
825 os << "<![ %output.print." << format
828 os <<"<imageobject><imagedata fileref=\"&"
835 if (runparams.flavor == OutputParams::XML)
836 os << " role=\"" << format << "\"/>" ;
838 os << " format=\"" << format << "\">" ;
840 os << "</imageobject>";
842 if (runparams.flavor != OutputParams::XML)
843 os << endl << "]]>" ;
845 return runparams.flavor == OutputParams::XML ? 0 : 2;
849 // For explanation on inserting graphics into DocBook checkout:
850 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
851 // See also the docbook guide at http://www.docbook.org/
852 int InsetGraphics::docbook(odocstream & os,
853 OutputParams const & runparams) const
855 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
856 // need to switch to MediaObject. However, for now this is sufficient and
858 if (runparams.flavor == OutputParams::XML)
859 runparams.exportdata->addExternalFile("docbook-xml",
862 runparams.exportdata->addExternalFile("docbook",
865 os << "<inlinemediaobject>";
868 docstring attributes = createDocBookAttributes();
869 r += writeImageObject("png", os, runparams, graphic_label, attributes);
870 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
871 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
872 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
874 os << "</inlinemediaobject>";
879 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
881 // The following code depends on non-empty filenames
882 if (params().filename.empty())
885 string const orig_file = params().filename.absFileName();
887 // The master buffer. This is useful when there are multiple levels
889 Buffer const * masterBuffer = buffer().masterBuffer();
891 if (!params().filename.isReadableFile())
894 // We place all temporary files in the master buffer's temp dir.
895 // This is possible because we use mangled file names.
896 // FIXME We may want to put these files in some special temporary
898 string const temp_path = masterBuffer->temppath();
900 // Copy to temporary directory.
902 GraphicsCopyStatus status;
903 boost::tie(status, temp_file) =
904 copyToDirIfNeeded(params().filename, temp_path);
906 if (status == FAILURE)
909 string output_file = onlyFileName(temp_file.absFileName());
911 string const from = formats.getFormatFromFile(temp_file);
913 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
915 string const to = findTargetFormat(from, runparams);
916 string const ext = formats.extension(to);
917 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
918 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
921 // source and destination formats are the same
922 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
926 // so the source and destination formats are different
927 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
928 string const output_to_file = changeExtension(output_file, ext);
930 // Do we need to perform the conversion?
931 // Yes if to_file does not exist or if temp_file is newer than to_file
932 if (compare_timestamps(temp_file, to_file) < 0) {
934 LYXERR(Debug::GRAPHICS,
935 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
936 from_utf8(orig_file))));
937 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
938 return output_to_file;
941 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
942 << "\tA copy has been made and convert is to be called with:\n"
943 << "\tfile to convert = " << temp_file << '\n'
944 << "\t from " << from << " to " << to);
946 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
949 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
950 from, to, el, Converters::try_default | Converters::try_cache);
953 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
954 return output_to_file;
958 docstring InsetGraphics::xhtml(XHTMLStream & xs, OutputParams const & op) const
960 string const output_file = prepareHTMLFile(op);
962 if (output_file.empty()) {
963 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
964 << params().filename << "' for output. File missing?");
965 string const attr = "src='" + params().filename.absFileName()
966 + "' alt='image: " + output_file + "'";
967 xs << html::CompTag("img", attr);
972 // We aren't doing anything with the crop and rotate parameters, and it would
973 // really be better to do width and height conversion, rather than to output
974 // these parameters here.
976 if (!params().width.zero())
977 imgstyle += "width:" + params().width.asHTMLString() + ";";
978 if (!params().height.zero())
979 imgstyle += " height:" + params().height.asHTMLString() + ";";
980 if (!imgstyle.empty())
981 imgstyle = "style='" + imgstyle + "' ";
983 string const attr = imgstyle + "src='" + output_file + "' alt='image: "
985 xs << html::CompTag("img", attr);
990 void InsetGraphics::validate(LaTeXFeatures & features) const
992 // If we have no image, we should not require anything.
993 if (params().filename.empty())
996 features.includeFile(graphic_label,
997 removeExtension(params().filename.absFileName()));
999 features.require("graphicx");
1001 if (features.runparams().nice) {
1002 Buffer const * masterBuffer = features.buffer().masterBuffer();
1003 string const rel_file = removeExtension(
1004 params().filename.relFileName(masterBuffer->filePath()));
1005 if (contains(rel_file, "."))
1006 features.require("lyxdot");
1011 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1013 // If nothing is changed, just return and say so.
1014 if (params() == p && !p.filename.empty())
1017 // Copy the new parameters.
1020 // Update the display using the new parameters.
1021 graphic_->update(params().as_grfxParams());
1023 // We have changed data, report it.
1028 InsetGraphicsParams const & InsetGraphics::params() const
1034 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1036 formats.edit(buffer(), p.filename,
1037 formats.getFormatFromFile(p.filename));
1041 void InsetGraphics::addToToc(DocIterator const & cpit) const
1043 TocBackend & backend = buffer().tocBackend();
1046 docstring const str = from_utf8(params_.filename.onlyFileName());
1047 backend.toc("graphics").push_back(TocItem(cpit, 0, str));
1051 docstring InsetGraphics::contextMenuName() const
1053 return from_ascii("context-graphics");
1057 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1058 InsetGraphicsParams & params)
1063 istringstream data(in);
1065 lex.setStream(data);
1066 lex.setContext("InsetGraphics::string2params");
1068 params = InsetGraphicsParams();
1069 readInsetGraphics(lex, buffer.filePath(), params);
1073 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1074 Buffer const & buffer)
1077 data << "graphics" << ' ';
1078 params.Write(data, buffer);
1079 data << "\\end_inset\n";
1083 namespace graphics {
1085 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1087 Inset & inset = b.inset();
1088 InsetIterator it = inset_iterator_begin(inset);
1089 InsetIterator const end = inset_iterator_end(inset);
1090 for (; it != end; ++it)
1091 if (it->lyxCode() == GRAPHICS_CODE) {
1092 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1093 InsetGraphicsParams inspar = ins.getParams();
1094 if (!inspar.groupId.empty())
1095 ids.insert(inspar.groupId);
1100 int countGroupMembers(Buffer const & b, string const & groupId)
1103 if (groupId.empty())
1105 Inset & inset = b.inset();
1106 InsetIterator it = inset_iterator_begin(inset);
1107 InsetIterator const end = inset_iterator_end(inset);
1108 for (; it != end; ++it)
1109 if (it->lyxCode() == GRAPHICS_CODE) {
1110 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1111 if (ins.getParams().groupId == groupId)
1118 string getGroupParams(Buffer const & b, string const & groupId)
1120 if (groupId.empty())
1122 Inset & inset = b.inset();
1123 InsetIterator it = inset_iterator_begin(inset);
1124 InsetIterator const end = inset_iterator_end(inset);
1125 for (; it != end; ++it)
1126 if (it->lyxCode() == GRAPHICS_CODE) {
1127 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1128 InsetGraphicsParams inspar = ins.getParams();
1129 if (inspar.groupId == groupId) {
1130 InsetGraphicsParams tmp = inspar;
1131 tmp.filename.erase();
1132 return InsetGraphics::params2string(tmp, b);
1139 void unifyGraphicsGroups(Buffer & b, string const & argument)
1141 InsetGraphicsParams params;
1142 InsetGraphics::string2params(argument, b, params);
1144 b.undo().beginUndoGroup();
1145 Inset & inset = b.inset();
1146 InsetIterator it = inset_iterator_begin(inset);
1147 InsetIterator const end = inset_iterator_end(inset);
1148 for (; it != end; ++it) {
1149 if (it->lyxCode() == GRAPHICS_CODE) {
1150 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1151 InsetGraphicsParams inspar = ins.getParams();
1152 if (params.groupId == inspar.groupId) {
1153 b.undo().recordUndo(it);
1154 params.filename = inspar.filename;
1155 ins.setParams(params);
1159 b.undo().endUndoGroup();
1163 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1165 Inset * instmp = &cur.inset();
1166 if (instmp->lyxCode() != GRAPHICS_CODE)
1167 instmp = cur.nextInset();
1168 if (!instmp || instmp->lyxCode() != GRAPHICS_CODE)
1171 return static_cast<InsetGraphics *>(instmp);
1174 } // namespace graphics