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();
214 // if the inset is part of a graphics group, all the
215 // other members should be updated too.
216 if (!params_.groupId.empty())
217 graphics::unifyGraphicsGroups(buffer(),
218 to_utf8(cmd.argument()));
222 case LFUN_INSET_DIALOG_UPDATE:
223 cur.bv().updateDialog("graphics", params2string(params(), buffer()));
226 case LFUN_GRAPHICS_RELOAD:
227 params_.filename.refresh();
232 Inset::doDispatch(cur, cmd);
238 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
239 FuncStatus & flag) const
241 switch (cmd.action()) {
242 case LFUN_INSET_EDIT:
243 case LFUN_INSET_MODIFY:
244 case LFUN_INSET_DIALOG_UPDATE:
245 case LFUN_GRAPHICS_RELOAD:
246 flag.setEnabled(true);
250 return Inset::getStatus(cur, cmd, flag);
255 bool InsetGraphics::showInsetDialog(BufferView * bv) const
257 bv->showDialog("graphics", params2string(params(), bv->buffer()),
258 const_cast<InsetGraphics *>(this));
264 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
266 graphic_->metrics(mi, dim);
270 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
272 graphic_->draw(pi, x, y);
276 void InsetGraphics::write(ostream & os) const
279 params().Write(os, buffer());
283 void InsetGraphics::read(Lexer & lex)
285 lex.setContext("InsetGraphics::read");
287 readInsetGraphics(lex, buffer().filePath(), params_);
288 graphic_->update(params().as_grfxParams());
292 string InsetGraphics::createLatexOptions() const
294 // Calculate the options part of the command, we must do it to a string
295 // stream since we might have a trailing comma that we would like to remove
296 // before writing it to the output stream.
297 ostringstream options;
298 if (!params().bb.empty())
299 options << "bb=" << rtrim(params().bb) << ',';
305 double const scl = convert<double>(params().scale);
306 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
307 if (!float_equal(scl, 100.0, 0.05))
308 size << "scale=" << scl / 100.0 << ',';
310 if (!params().width.zero())
311 size << "width=" << params().width.asLatexString() << ',';
312 if (!params().height.zero())
313 size << "height=" << params().height.asLatexString() << ',';
314 if (params().keepAspectRatio)
315 size << "keepaspectratio,";
317 if (params().scaleBeforeRotation && !size.str().empty())
318 options << size.str();
320 // Make sure rotation angle is not very close to zero;
321 // a float can be effectively zero but not exactly zero.
322 if (!params().rotateAngle.empty()
323 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
324 options << "angle=" << params().rotateAngle << ',';
325 if (!params().rotateOrigin.empty()) {
326 options << "origin=" << params().rotateOrigin[0];
327 if (contains(params().rotateOrigin,"Top"))
329 else if (contains(params().rotateOrigin,"Bottom"))
331 else if (contains(params().rotateOrigin,"Baseline"))
336 if (!params().scaleBeforeRotation && !size.str().empty())
337 options << size.str();
339 if (!params().special.empty())
340 options << params().special << ',';
342 string opts = options.str();
344 if (suffixIs(opts, ','))
345 opts = opts.substr(0, opts.size() - 1);
351 docstring InsetGraphics::toDocbookLength(Length const & len) const
353 odocstringstream result;
354 switch (len.unit()) {
355 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
356 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
358 case Length::PT: // Point = 1/72.27in = 0.351mm
359 result << len.value() * 72 / 72.27 << "pt";
361 case Length::BP: // Big point (72bp = 1in), also PostScript point
362 result << len.value() << "pt";
364 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
365 result << len.value() * 0.376 << "mm";
367 case Length::MM: // Millimeter = 2.845pt
368 result << len.value() << "mm";
370 case Length::PC: // Pica = 12pt = 4.218mm
371 result << len.value() << "pc";
373 case Length::CC: // Cicero = 12dd = 4.531mm
374 result << len.value() * 4.531 << "mm";
376 case Length::CM: // Centimeter = 10mm = 2.371pc
377 result << len.value() << "cm";
379 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
380 result << len.value() << "in";
382 case Length::EX: // Height of a small "x" for the current font.
383 // Obviously we have to compromise here. Any better ratio than 1.5 ?
384 result << len.value() / 1.5 << "em";
386 case Length::EM: // Width of capital "M" in current font.
387 result << len.value() << "em";
389 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
390 result << len.value() * 18 << "em";
392 case Length::PTW: // Percent of TextWidth
393 case Length::PCW: // Percent of ColumnWidth
394 case Length::PPW: // Percent of PageWidth
395 case Length::PLW: // Percent of LineWidth
396 case Length::PTH: // Percent of TextHeight
397 case Length::PPH: // Percent of PaperHeight
398 // Sigh, this will go wrong.
399 result << len.value() << "%";
402 result << len.asDocstring();
409 docstring InsetGraphics::createDocBookAttributes() const
411 // Calculate the options part of the command, we must do it to a string
412 // stream since we copied the code from createLatexParams() ;-)
414 // FIXME: av: need to translate spec -> Docbook XSL spec
415 // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
416 // Right now it only works with my version of db2latex :-)
418 odocstringstream options;
419 double const scl = convert<double>(params().scale);
420 if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
421 if (!float_equal(scl, 100.0, 0.05))
422 options << " scale=\""
423 << static_cast<int>( (scl) + 0.5 )
426 if (!params().width.zero()) {
427 options << " width=\"" << toDocbookLength(params().width) << "\" ";
429 if (!params().height.zero()) {
430 options << " depth=\"" << toDocbookLength(params().height) << "\" ";
432 if (params().keepAspectRatio) {
433 // This will be irrelevant unless both width and height are set
434 options << "scalefit=\"1\" ";
439 if (!params().special.empty())
440 options << from_ascii(params().special) << " ";
442 // trailing blanks are ok ...
443 return options.str();
449 enum GraphicsCopyStatus {
457 pair<GraphicsCopyStatus, FileName> const
458 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
460 LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
461 unsigned long const checksum_in = file_in.checksum();
462 unsigned long const checksum_out = file_out.checksum();
464 if (checksum_in == checksum_out)
466 return make_pair(IDENTICAL_CONTENTS, file_out);
468 Mover const & mover = getMover(formats.getFormatFromFile(file_in));
469 bool const success = mover.copy(file_in, file_out);
472 LYXERR(Debug::GRAPHICS,
473 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
474 "into the temporary directory."),
475 from_utf8(file_in.absFileName()))));
478 GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
479 return make_pair(status, file_out);
483 pair<GraphicsCopyStatus, FileName> const
484 copyToDirIfNeeded(DocFileName const & file, string const & dir)
486 string const file_in = file.absFileName();
487 string const only_path = onlyPath(file_in);
488 if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
489 return make_pair(IDENTICAL_PATHS, file_in);
491 string mangled = file.mangledFileName();
492 if (file.isZipped()) {
493 // We need to change _eps.gz to .eps.gz. The mangled name is
494 // still unique because of the counter in mangledFileName().
495 // We can't just call mangledFileName() with the zip
496 // extension removed, because base.eps and base.eps.gz may
497 // have different content but would get the same mangled
498 // name in this case.
499 string const base = removeExtension(file.unzippedFileName());
500 string::size_type const ext_len = file_in.length() - base.length();
501 mangled[mangled.length() - ext_len] = '.';
503 FileName const file_out(makeAbsPath(mangled, dir));
505 return copyFileIfNeeded(file, file_out);
509 string const stripExtensionIfPossible(string const & file, bool nice)
511 // Remove the extension so the LaTeX compiler will use whatever
512 // is appropriate (when there are several versions in different
514 // Do this only if we are not exporting for internal usage, because
515 // pdflatex prefers png over pdf and it would pick up the png images
516 // that we generate for preview.
517 // This works only if the filename contains no dots besides
518 // the just removed one. We can fool here by replacing all
519 // dots with a macro whose definition is just a dot ;-)
520 // The automatic format selection does not work if the file
522 string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
523 if (!nice || contains(latex_name, '"'))
525 return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
529 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
531 // No conversion is needed. LaTeX can handle the graphic file as is.
532 // This is true even if the orig_file is compressed.
533 string const to_format = formats.getFormat(to)->extension();
534 string const file_format = getExtension(file);
535 // for latex .ps == .eps
536 if (to_format == file_format ||
537 (to_format == "eps" && file_format == "ps") ||
538 (to_format == "ps" && file_format == "eps"))
539 return stripExtensionIfPossible(file, nice);
540 return latex_path(file, EXCLUDE_EXTENSION);
546 string InsetGraphics::prepareFile(OutputParams const & runparams) const
548 // The following code depends on non-empty filenames
549 if (params().filename.empty())
552 string const orig_file = params().filename.absFileName();
553 // this is for dryrun and display purposes, do not use latexFilename
554 string const rel_file = params().filename.relFileName(buffer().filePath());
556 // previewing source code, no file copying or file format conversion
557 if (runparams.dryrun)
558 return stripExtensionIfPossible(rel_file, runparams.nice);
560 // The master buffer. This is useful when there are multiple levels
562 Buffer const * masterBuffer = buffer().masterBuffer();
564 // Return the output name if we are inside a comment or the file does
566 // We are not going to change the extension or using the name of the
567 // temporary file, the code is already complicated enough.
568 if (runparams.inComment || !params().filename.isReadableFile())
569 return params().filename.outputFileName(masterBuffer->filePath());
571 // We place all temporary files in the master buffer's temp dir.
572 // This is possible because we use mangled file names.
573 // This is necessary for DVI export.
574 string const temp_path = masterBuffer->temppath();
576 // temp_file will contain the file for LaTeX to act on if, for example,
577 // we move it to a temp dir or uncompress it.
579 GraphicsCopyStatus status;
580 boost::tie(status, temp_file) =
581 copyToDirIfNeeded(params().filename, temp_path);
583 if (status == FAILURE)
586 // a relative filename should be relative to the master buffer.
587 // "nice" means that the buffer is exported to LaTeX format but not
588 // run through the LaTeX compiler.
589 string output_file = runparams.nice ?
590 params().filename.outputFileName(masterBuffer->filePath()) :
591 onlyFileName(temp_file.absFileName());
593 if (runparams.nice) {
594 if (!isValidLaTeXFileName(output_file)) {
595 frontend::Alert::warning(_("Invalid filename"),
596 _("The following filename will cause troubles "
597 "when running the exported file through LaTeX: ") +
598 from_utf8(output_file));
600 // only show DVI-specific warning when export format is plain latex
601 if (!isValidDVIFileName(output_file)
602 && runparams.flavor == OutputParams::LATEX) {
603 frontend::Alert::warning(_("Problematic filename for DVI"),
604 _("The following filename can cause troubles "
605 "when running the exported file through LaTeX "
606 "and opening the resulting DVI: ") +
607 from_utf8(output_file), true);
611 FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
612 // determine the export format
613 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
614 "latex" : "pdflatex";
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 (params().filename.isZipped()) {
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 int InsetGraphics::latex(odocstream & 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();
758 string const message = file_exists ?
759 string() : string("bb = 0 0 200 100, draft, type=eps");
760 // if !message.empty() then there was no existing file
761 // "filename" found. In this case LaTeX
762 // draws only a rectangle with the above bb and the
763 // not found filename in it.
764 LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
766 // These variables collect all the latex code that should be before and
767 // after the actual includegraphics command.
771 if (runparams.moving_arg)
772 before += "\\protect";
774 // We never use the starred form, we use the "clip" option instead.
775 before += "\\includegraphics";
777 // Write the options if there are any.
778 string const opts = createLatexOptions();
779 LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
781 if (!opts.empty() && !message.empty())
782 before += ('[' + opts + ',' + message + ']');
783 else if (!opts.empty() || !message.empty())
784 before += ('[' + opts + message + ']');
786 LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
788 string latex_str = before + '{';
789 // Convert the file if necessary.
790 // Remove the extension so LaTeX will use whatever is appropriate
791 // (when there are several versions in different formats)
792 latex_str += prepareFile(runparams);
793 latex_str += '}' + after;
795 os << from_utf8(latex_str);
797 LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
798 // Return how many newlines we issued.
799 return int(count(latex_str.begin(), latex_str.end(),'\n'));
803 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
805 // No graphics in ascii output. Possible to use gifscii to convert
806 // images to ascii approximation.
807 // 1. Convert file to ascii using gifscii
808 // 2. Read ascii output file and add it to the output stream.
809 // at least we send the filename
811 // FIXME: We have no idea what the encoding of the filename is
813 docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
814 from_utf8(params().filename.absFileName()));
815 os << '<' << str << '>';
817 return 2 + str.size();
821 static int writeImageObject(char const * format, odocstream & os,
822 OutputParams const & runparams, docstring const & graphic_label,
823 docstring const & attributes)
825 if (runparams.flavor != OutputParams::XML)
826 os << "<![ %output.print." << format
829 os <<"<imageobject><imagedata fileref=\"&"
836 if (runparams.flavor == OutputParams::XML)
837 os << " role=\"" << format << "\"/>" ;
839 os << " format=\"" << format << "\">" ;
841 os << "</imageobject>";
843 if (runparams.flavor != OutputParams::XML)
844 os << endl << "]]>" ;
846 return runparams.flavor == OutputParams::XML ? 0 : 2;
850 // For explanation on inserting graphics into DocBook checkout:
851 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
852 // See also the docbook guide at http://www.docbook.org/
853 int InsetGraphics::docbook(odocstream & os,
854 OutputParams const & runparams) const
856 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
857 // need to switch to MediaObject. However, for now this is sufficient and
859 if (runparams.flavor == OutputParams::XML)
860 runparams.exportdata->addExternalFile("docbook-xml",
863 runparams.exportdata->addExternalFile("docbook",
866 os << "<inlinemediaobject>";
869 docstring attributes = createDocBookAttributes();
870 r += writeImageObject("png", os, runparams, graphic_label, attributes);
871 r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
872 r += writeImageObject("eps", os, runparams, graphic_label, attributes);
873 r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
875 os << "</inlinemediaobject>";
880 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
882 // The following code depends on non-empty filenames
883 if (params().filename.empty())
886 string const orig_file = params().filename.absFileName();
888 // The master buffer. This is useful when there are multiple levels
890 Buffer const * masterBuffer = buffer().masterBuffer();
892 if (!params().filename.isReadableFile())
895 // We place all temporary files in the master buffer's temp dir.
896 // This is possible because we use mangled file names.
897 // FIXME We may want to put these files in some special temporary
899 string const temp_path = masterBuffer->temppath();
901 // Copy to temporary directory.
903 GraphicsCopyStatus status;
904 boost::tie(status, temp_file) =
905 copyToDirIfNeeded(params().filename, temp_path);
907 if (status == FAILURE)
910 string output_file = onlyFileName(temp_file.absFileName());
912 string const from = formats.getFormatFromFile(temp_file);
914 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
916 string const to = findTargetFormat(from, runparams);
917 string const ext = formats.extension(to);
918 LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
919 LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
922 // source and destination formats are the same
923 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
927 // so the source and destination formats are different
928 FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
929 string const output_to_file = changeExtension(output_file, ext);
931 // Do we need to perform the conversion?
932 // Yes if to_file does not exist or if temp_file is newer than to_file
933 if (compare_timestamps(temp_file, to_file) < 0) {
935 LYXERR(Debug::GRAPHICS,
936 to_utf8(bformat(_("No conversion of %1$s is needed after all"),
937 from_utf8(orig_file))));
938 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
939 return output_to_file;
942 LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
943 << "\tA copy has been made and convert is to be called with:\n"
944 << "\tfile to convert = " << temp_file << '\n'
945 << "\t from " << from << " to " << to);
947 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
950 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
951 from, to, el, Converters::try_default | Converters::try_cache);
954 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
955 return output_to_file;
959 docstring InsetGraphics::xhtml(XHTMLStream & xs, OutputParams const & op) const
961 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 // Do we want to do something with the parameters, other than use them to
973 // crop, etc, the image?
974 // Speaking of which: Do the cropping, rotating, etc.
975 string const attr = "src='" + output_file + "' alt='image: "
977 xs << html::CompTag("img", attr);
982 void InsetGraphics::validate(LaTeXFeatures & features) const
984 // If we have no image, we should not require anything.
985 if (params().filename.empty())
988 features.includeFile(graphic_label,
989 removeExtension(params().filename.absFileName()));
991 features.require("graphicx");
993 if (features.runparams().nice) {
994 Buffer const * masterBuffer = features.buffer().masterBuffer();
995 string const rel_file = removeExtension(
996 params().filename.relFileName(masterBuffer->filePath()));
997 if (contains(rel_file, "."))
998 features.require("lyxdot");
1003 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1005 // If nothing is changed, just return and say so.
1006 if (params() == p && !p.filename.empty())
1009 // Copy the new parameters.
1012 // Update the display using the new parameters.
1013 graphic_->update(params().as_grfxParams());
1015 // We have changed data, report it.
1020 InsetGraphicsParams const & InsetGraphics::params() const
1026 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1028 formats.edit(buffer(), p.filename,
1029 formats.getFormatFromFile(p.filename));
1033 void InsetGraphics::addToToc(DocIterator const & cpit)
1035 TocBackend & backend = buffer().tocBackend();
1038 docstring const str = from_utf8(params_.filename.onlyFileName());
1039 backend.toc("graphics").push_back(TocItem(cpit, 0, str));
1043 docstring InsetGraphics::contextMenuName() const
1045 return from_ascii("context-graphics");
1049 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1050 InsetGraphicsParams & params)
1055 istringstream data(in);
1057 lex.setStream(data);
1058 lex.setContext("InsetGraphics::string2params");
1060 params = InsetGraphicsParams();
1061 readInsetGraphics(lex, buffer.filePath(), params);
1065 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1066 Buffer const & buffer)
1069 data << "graphics" << ' ';
1070 params.Write(data, buffer);
1071 data << "\\end_inset\n";
1075 namespace graphics {
1077 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1079 Inset & inset = b.inset();
1080 InsetIterator it = inset_iterator_begin(inset);
1081 InsetIterator const end = inset_iterator_end(inset);
1082 for (; it != end; ++it)
1083 if (it->lyxCode() == GRAPHICS_CODE) {
1084 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1085 InsetGraphicsParams inspar = ins.getParams();
1086 if (!inspar.groupId.empty())
1087 ids.insert(inspar.groupId);
1092 int countGroupMembers(Buffer const & b, string const & groupId)
1095 if (groupId.empty())
1097 Inset & inset = b.inset();
1098 InsetIterator it = inset_iterator_begin(inset);
1099 InsetIterator const end = inset_iterator_end(inset);
1100 for (; it != end; ++it)
1101 if (it->lyxCode() == GRAPHICS_CODE) {
1102 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1103 if (ins.getParams().groupId == groupId)
1110 string getGroupParams(Buffer const & b, string const & groupId)
1112 if (groupId.empty())
1114 Inset & inset = b.inset();
1115 InsetIterator it = inset_iterator_begin(inset);
1116 InsetIterator const end = inset_iterator_end(inset);
1117 for (; it != end; ++it)
1118 if (it->lyxCode() == GRAPHICS_CODE) {
1119 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1120 InsetGraphicsParams inspar = ins.getParams();
1121 if (inspar.groupId == groupId) {
1122 InsetGraphicsParams tmp = inspar;
1123 tmp.filename.erase();
1124 return InsetGraphics::params2string(tmp, b);
1131 void unifyGraphicsGroups(Buffer & b, string const & argument)
1133 InsetGraphicsParams params;
1134 InsetGraphics::string2params(argument, b, params);
1136 b.undo().beginUndoGroup();
1137 Inset & inset = b.inset();
1138 InsetIterator it = inset_iterator_begin(inset);
1139 InsetIterator const end = inset_iterator_end(inset);
1140 for (; it != end; ++it) {
1141 if (it->lyxCode() == GRAPHICS_CODE) {
1142 InsetGraphics & ins = static_cast<InsetGraphics &>(*it);
1143 InsetGraphicsParams inspar = ins.getParams();
1144 if (params.groupId == inspar.groupId) {
1145 b.undo().recordUndo(it);
1146 params.filename = inspar.filename;
1147 ins.setParams(params);
1151 b.undo().endUndoGroup();
1155 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1157 Inset * instmp = &cur.inset();
1158 if (instmp->lyxCode() != GRAPHICS_CODE)
1159 instmp = cur.nextInset();
1160 if (!instmp || instmp->lyxCode() != GRAPHICS_CODE)
1163 return static_cast<InsetGraphics *>(instmp);
1166 } // namespace graphics