]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
Prevent an assert when opening the citation dialog if the bibtex
[lyx.git] / src / insets / insetgraphics.C
1 /**
2  * \file insetgraphics.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Baruch Even
7  * \author Herbert Voß
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 /*
13 TODO
14
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     * Add a way to roll the image file into the file format.
19     * When loading, if the image is not found in the expected place, try
20       to find it in the clipart, or in the same directory with the image.
21     * The image choosing dialog could show thumbnails of the image formats
22       it knows of, thus selection based on the image instead of based on
23       filename.
24     * Add support for the 'picins' package.
25     * Add support for the 'picinpar' package.
26     * Improve support for 'subfigure' - Allow to set the various options
27       that are possible.
28 */
29
30 /* NOTES:
31  * Fileformat:
32  * Current version is 1 (inset file format version), when changing it
33  * it should be changed in the Write() function when writing in one place
34  * and when reading one should change the version check and the error message.
35  * The filename is kept in  the lyx file in a relative way, so as to allow
36  * moving the document file and its images with no problem.
37  *
38  *
39  * Conversions:
40  *   Postscript output means EPS figures.
41  *
42  *   PDF output is best done with PDF figures if it's a direct conversion
43  *   or PNG figures otherwise.
44  *      Image format
45  *      from        to
46  *      EPS         epstopdf
47  *      PS          ps2pdf
48  *      JPG/PNG     direct
49  *      PDF         direct
50  *      others      PNG
51  */
52
53 #include <config.h>
54
55 #include "insets/insetgraphics.h"
56 #include "insets/render_graphic.h"
57
58 #include "buffer.h"
59 #include "BufferView.h"
60 #include "converter.h"
61 #include "debug.h"
62 #include "dispatchresult.h"
63 #include "format.h"
64 #include "funcrequest.h"
65 #include "gettext.h"
66 #include "LaTeXFeatures.h"
67 #include "lyx_main.h"
68 #include "lyxlex.h"
69 #include "lyxrc.h"
70 #include "metricsinfo.h"
71 #include "outputparams.h"
72
73 #include "frontends/Alert.h"
74 #include "frontends/LyXView.h"
75
76 #include "support/filetools.h"
77 #include "support/lyxalgo.h" // lyx::count
78 #include "support/lyxlib.h" // float_equal
79 #include "support/os.h"
80 #include "support/systemcall.h"
81 #include "support/tostr.h"
82
83 #include <boost/bind.hpp>
84 #include <boost/tuple/tuple.hpp>
85
86 #include "support/std_sstream.h"
87
88 namespace support = lyx::support;
89 using lyx::support::AbsolutePath;
90 using lyx::support::bformat;
91 using lyx::support::ChangeExtension;
92 using lyx::support::contains;
93 using lyx::support::FileName;
94 using lyx::support::float_equal;
95 using lyx::support::GetExtension;
96 using lyx::support::getExtFromContents;
97 using lyx::support::IsFileReadable;
98 using lyx::support::LibFileSearch;
99 using lyx::support::rtrim;
100 using lyx::support::Systemcall;
101 using lyx::support::unzipFile;
102 using lyx::support::unzippedFileName;
103
104 namespace os = lyx::support::os;
105
106 using std::endl;
107 using std::string;
108 using std::auto_ptr;
109 using std::istringstream;
110 using std::ostream;
111 using std::ostringstream;
112
113
114 namespace {
115
116 ///////////////////////////////////////////////////////////////////////////
117 int const VersionNumber = 1;
118 ///////////////////////////////////////////////////////////////////////////
119
120 // This function is a utility function
121 // ... that should be with ChangeExtension ...
122 inline
123 string const RemoveExtension(string const & filename)
124 {
125         return ChangeExtension(filename, string());
126 }
127
128
129 string const uniqueID()
130 {
131         static unsigned int seed = 1000;
132         return "graph" + tostr(++seed);
133 }
134
135
136 string findTargetFormat(string const & suffix, OutputParams const & runparams)
137 {
138         // Are we using latex or pdflatex).
139         if (runparams.flavor == OutputParams::PDFLATEX) {
140                 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
141                 if (contains(suffix, "ps") || suffix == "pdf")
142                         return "pdf";
143                 if (suffix == "jpg")    // pdflatex can use jpeg
144                         return suffix;
145                 return "png";         // and also png
146         }
147         // If it's postscript, we always do eps.
148         lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
149         if (suffix != "ps")     // any other than ps
150                 return "eps";         // is changed to eps
151         return suffix;          // let ps untouched
152 }
153
154 } // namespace anon
155
156
157 InsetGraphics::InsetGraphics()
158         : graphic_label(uniqueID()),
159           graphic_(new RenderGraphic)
160 {
161         graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
162 }
163
164
165 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
166         : InsetOld(ig),
167           boost::signals::trackable(),
168           graphic_label(uniqueID()),
169           graphic_(new RenderGraphic(*ig.graphic_))
170 {
171         graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
172         setParams(ig.params());
173 }
174
175
176 auto_ptr<InsetBase> InsetGraphics::clone() const
177 {
178         return auto_ptr<InsetBase>(new InsetGraphics(*this));
179 }
180
181
182 InsetGraphics::~InsetGraphics()
183 {
184         InsetGraphicsMailer(*this).hideDialog();
185 }
186
187
188 void InsetGraphics::statusChanged() const
189 {
190         LyX::cref().updateInset(this);
191 }
192
193
194 DispatchResult
195 InsetGraphics::priv_dispatch(FuncRequest const & cmd, idx_type &, pos_type &)
196 {
197         switch (cmd.action) {
198         case LFUN_INSET_MODIFY: {
199                 Buffer const & buffer = *cmd.view()->buffer();
200                 InsetGraphicsParams p;
201                 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
202                 if (!p.filename.empty()) {
203                         setParams(p);
204                         cmd.view()->update();
205                 }
206                 return DispatchResult(true, true);
207         }
208
209         case LFUN_INSET_DIALOG_UPDATE:
210                 InsetGraphicsMailer(*this).updateDialog(cmd.view());
211                 return DispatchResult(true, true);
212
213         case LFUN_MOUSE_RELEASE:
214                 InsetGraphicsMailer(*this).showDialog(cmd.view());
215                 return DispatchResult(true, true);
216
217         default:
218                 return DispatchResult(false);
219         }
220 }
221
222
223 void InsetGraphics::edit(BufferView * bv, bool)
224 {
225         InsetGraphicsMailer(*this).showDialog(bv);
226 }
227
228
229 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
230 {
231         graphic_->metrics(mi, dim);
232         dim_ = dim;
233 }
234
235
236 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
237 {
238         xo_ = x;
239         yo_ = y;
240         graphic_->draw(pi, x, y);
241 }
242
243
244 InsetOld::EDITABLE InsetGraphics::editable() const
245 {
246         return IS_EDITABLE;
247 }
248
249
250 void InsetGraphics::write(Buffer const & buf, ostream & os) const
251 {
252         os << "Graphics\n";
253         params().Write(os, buf.filePath());
254 }
255
256
257 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
258 {
259         string const token = lex.getString();
260
261         if (token == "Graphics")
262                 readInsetGraphics(lex, buf.filePath());
263         else
264                 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
265
266         graphic_->update(params().as_grfxParams());
267 }
268
269
270 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
271 {
272         bool finished = false;
273
274         while (lex.isOK() && !finished) {
275                 lex.next();
276
277                 string const token = lex.getString();
278                 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
279                                     << endl;
280
281                 if (token.empty()) {
282                         continue;
283                 } else if (token == "\\end_inset") {
284                         finished = true;
285                 } else if (token == "FormatVersion") {
286                         lex.next();
287                         int version = lex.getInteger();
288                         if (version > VersionNumber)
289                                 lyxerr
290                                 << "This document was created with a newer Graphics widget"
291                                 ", You should use a newer version of LyX to read this"
292                                 " file."
293                                 << endl;
294                         // TODO: Possibly open up a dialog?
295                 }
296                 else {
297                         if (!params_.Read(lex, token, bufpath))
298                                 lyxerr << "Unknown token, " << token << ", skipping."
299                                         << std::endl;
300                 }
301         }
302 }
303
304
305 string const InsetGraphics::createLatexOptions() const
306 {
307         // Calculate the options part of the command, we must do it to a string
308         // stream since we might have a trailing comma that we would like to remove
309         // before writing it to the output stream.
310         ostringstream options;
311         if (!params().bb.empty())
312             options << "  bb=" << rtrim(params().bb) << ",\n";
313         if (params().draft)
314             options << "  draft,\n";
315         if (params().clip)
316             options << "  clip,\n";
317         if (!float_equal(params().scale, 0.0, 0.05)) {
318                 if (!float_equal(params().scale, 100.0, 0.05))
319                         options << "  scale=" << params().scale / 100.0
320                                 << ",\n";
321         } else {
322                 if (!params().width.zero())
323                         options << "  width=" << params().width.asLatexString() << ",\n";
324                 if (!params().height.zero())
325                         options << "  height=" << params().height.asLatexString() << ",\n";
326                 if (params().keepAspectRatio)
327                         options << "  keepaspectratio,\n";
328         }
329
330         // Make sure rotation angle is not very close to zero;
331         // a float can be effectively zero but not exactly zero.
332         if (!float_equal(params().rotateAngle, 0, 0.001)) {
333             options << "  angle=" << params().rotateAngle << ",\n";
334             if (!params().rotateOrigin.empty()) {
335                 options << "  origin=" << params().rotateOrigin[0];
336                 if (contains(params().rotateOrigin,"Top"))
337                     options << 't';
338                 else if (contains(params().rotateOrigin,"Bottom"))
339                     options << 'b';
340                 else if (contains(params().rotateOrigin,"Baseline"))
341                     options << 'B';
342                 options << ",\n";
343             }
344         }
345
346         if (!params().special.empty())
347             options << params().special << ",\n";
348
349         string opts = options.str();
350         // delete last ",\n"
351         return opts.substr(0, opts.size() - 2);
352 }
353
354
355 namespace {
356
357 enum CopyStatus {
358         SUCCESS,
359         FAILURE,
360         IDENTICAL_PATHS,
361         IDENTICAL_CONTENTS
362 };
363
364
365 std::pair<CopyStatus, string> const
366 copyToDirIfNeeded(string const & file_in, string const & dir)
367 {
368         using support::rtrim;
369
370         BOOST_ASSERT(AbsolutePath(file_in));
371
372         string const only_path = support::OnlyPath(file_in);
373         if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
374                 return std::make_pair(IDENTICAL_PATHS, file_in);
375
376         string mangled;
377         if (support::zippedFile(file_in)) {
378                 string const ext = GetExtension(file_in);
379                 string const unzipped = support::unzippedFileName(file_in);
380                 mangled = FileName(unzipped).mangledFilename();
381                 mangled += "." + ext;
382         } else
383                 mangled = FileName(file_in).mangledFilename();
384
385         string const file_out = support::MakeAbsPath(mangled, dir);
386
387         unsigned long const checksum_in  = support::sum(file_in);
388         unsigned long const checksum_out = support::sum(file_out);
389
390         if (checksum_in == checksum_out)
391                 // Nothing to do...
392                 return std::make_pair(IDENTICAL_CONTENTS, file_out);
393
394         bool const success = support::copy(file_in, file_out);
395         if (!success) {
396                 lyxerr[Debug::GRAPHICS]
397                         << support::bformat(_("Could not copy the file\n%1$s\n"
398                                               "into the temporary directory."),
399                                             file_in)
400                         << std::endl;
401         }
402
403         CopyStatus status = success ? SUCCESS : FAILURE;
404         return std::make_pair(status, file_out);
405 }
406
407
408 string const stripExtensionIfPossible(string const & file, string const & to)
409 {
410         // No conversion is needed. LaTeX can handle the graphic file as is.
411         // This is true even if the orig_file is compressed.
412         if (formats.getFormat(to)->extension() == GetExtension(file))
413                 return RemoveExtension(file);
414         return file;
415 }
416
417 } // namespace anon
418
419
420 string const InsetGraphics::prepareFile(Buffer const & buf,
421                                         OutputParams const & runparams) const
422 {
423         string orig_file = params().filename.absFilename();
424         string const rel_file = params().filename.relFilename(buf.filePath());
425
426         // LaTeX can cope if the graphics file doesn't exist, so just return the
427         // filename.
428         if (!IsFileReadable(orig_file)) {
429                 lyxerr[Debug::GRAPHICS]
430                         << "InsetGraphics::prepareFile\n"
431                         << "No file '" << orig_file << "' can be found!" << endl;
432                 return rel_file;
433         }
434
435         // If the file is compressed and we have specified that it
436         // should not be uncompressed, then just return its name and
437         // let LaTeX do the rest!
438         bool const zipped = params().filename.isZipped();
439
440         if (zipped && params().noUnzip) {
441                 lyxerr[Debug::GRAPHICS]
442                         << "\tpass zipped file to LaTeX but with full path.\n";
443                 // LaTeX needs an absolute path, otherwise the
444                 // coresponding *.eps.bb file isn't found
445                 return orig_file;
446         }
447
448         // temp_file will contain the file for LaTeX to act on if, for example,
449         // we move it to a temp dir or uncompress it.
450         string temp_file = orig_file;
451
452         if (zipped) {
453                 CopyStatus status;
454                 boost::tie(status, temp_file) =
455                         copyToDirIfNeeded(orig_file, buf.temppath());
456
457                 if (status == FAILURE)
458                         return orig_file;
459
460                 orig_file = unzippedFileName(temp_file);
461                 if (!IsFileReadable(orig_file)) {
462                         unzipFile(temp_file);
463                         lyxerr[Debug::GRAPHICS]
464                                 << "\tunzipped to " << orig_file << endl;
465                 }
466         }
467
468         string const from = getExtFromContents(orig_file);
469         string const to   = findTargetFormat(from, runparams);
470         lyxerr[Debug::GRAPHICS]
471                 << "\t we have: from " << from << " to " << to << '\n';
472
473         if (from == to && !lyxrc.use_tempdir)
474                 return stripExtensionIfPossible(orig_file, to);
475
476         // We're going to be running the exported buffer through the LaTeX
477         // compiler, so must ensure that LaTeX can cope with the graphics
478         // file format.
479
480         lyxerr[Debug::GRAPHICS]
481                 << "\tthe orig file is: " << orig_file << endl;
482
483         bool conversion_needed = true;
484         if (lyxrc.use_tempdir) {
485                 CopyStatus status;
486                 boost::tie(status, temp_file) =
487                         copyToDirIfNeeded(orig_file, buf.temppath());
488
489                 if (status == FAILURE)
490                         return orig_file;
491                 else if (status == IDENTICAL_CONTENTS)
492                         conversion_needed = false;
493         }
494
495         if (from == to)
496                 return stripExtensionIfPossible(temp_file, to);
497
498         string const to_file_base = RemoveExtension(temp_file);
499         string const to_file = ChangeExtension(to_file_base, to);
500
501         // Do we need to perform the conversion?
502         // Yes if to_file does not exist or if temp_file is newer than to_file
503         if (!conversion_needed ||
504             support::compare_timestamps(temp_file, to_file) < 0) {
505                 lyxerr[Debug::GRAPHICS]
506                         << bformat(_("No conversion of %1$s is needed after all"),
507                                    rel_file)
508                         << std::endl;
509                 return to_file_base;
510         }
511
512         lyxerr[Debug::GRAPHICS]
513                 << "\tThe original file is " << orig_file << "\n"
514                 << "\tA copy has been made and convert is to be called with:\n"
515                 << "\tfile to convert = " << temp_file << '\n'
516                 << "\tto_file_base = " << to_file_base << '\n'
517                 << "\t from " << from << " to " << to << '\n';
518
519         // if no special converter defined, than we take the default one
520         // from ImageMagic: convert from:inname.from to:outname.to
521         if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
522                 string const command =
523                         "sh " + LibFileSearch("scripts", "convertDefault.sh") +
524                                 ' ' + from + ':' + temp_file + ' ' +
525                                 to + ':' + to_file_base + '.' + to;
526                 lyxerr[Debug::GRAPHICS]
527                         << "No converter defined! I use convertDefault.sh:\n\t"
528                         << command << endl;
529                 Systemcall one;
530                 one.startscript(Systemcall::Wait, command);
531                 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
532                         string str = bformat(_("No information for converting %1$s "
533                                 "format files to %2$s.\n"
534                                 "Try defining a convertor in the preferences."), from, to);
535                         Alert::error(_("Could not convert image"), str);
536                 }
537         }
538
539         return to_file_base;
540 }
541
542
543 int InsetGraphics::latex(Buffer const & buf, ostream & os,
544                          OutputParams const & runparams) const
545 {
546         // If there is no file specified or not existing,
547         // just output a message about it in the latex output.
548         lyxerr[Debug::GRAPHICS]
549                 << "insetgraphics::latex: Filename = "
550                 << params().filename.absFilename() << endl;
551
552         string const relative_file =
553                 params().filename.relFilename(buf.filePath());
554
555         // A missing (e)ps-extension is no problem for LaTeX, so
556         // we have to test three different cases
557 #warning uh, but can our cache handle it ? no.
558         string const file_ = params().filename.absFilename();
559         bool const file_exists =
560                 !file_.empty() &&
561                 (IsFileReadable(file_) ||               // original
562                  IsFileReadable(file_ + ".eps") ||      // original.eps
563                  IsFileReadable(file_ + ".ps"));        // original.ps
564         string const message = file_exists ?
565                 string() : string("bb = 0 0 200 100, draft, type=eps");
566         // if !message.empty() than there was no existing file
567         // "filename(.(e)ps)" found. In this case LaTeX
568         // draws only a rectangle with the above bb and the
569         // not found filename in it.
570         lyxerr[Debug::GRAPHICS]
571                 << "\tMessage = \"" << message << '\"' << endl;
572
573         // These variables collect all the latex code that should be before and
574         // after the actual includegraphics command.
575         string before;
576         string after;
577         // Do we want subcaptions?
578         if (params().subcaption) {
579                 before += "\\subfigure[" + params().subcaptionText + "]{";
580                 after = '}';
581         }
582         // We never use the starred form, we use the "clip" option instead.
583         before += "\\includegraphics";
584
585         // Write the options if there are any.
586         string const opts = createLatexOptions();
587         lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
588
589         if (!opts.empty() && !message.empty())
590                 before += ("[%\n" + opts + ',' + message + ']');
591         else if (!opts.empty() || !message.empty())
592                 before += ("[%\n" + opts + message + ']');
593
594         lyxerr[Debug::GRAPHICS]
595                 << "\tBefore = " << before
596                 << "\n\tafter = " << after << endl;
597
598
599         // "nice" means that the buffer is exported to LaTeX format but not
600         //        run through the LaTeX compiler.
601         if (runparams.nice) {
602                 os << before <<'{' << relative_file << '}' << after;
603                 return 1;
604         }
605
606         // Make the filename relative to the lyx file
607         // and remove the extension so the LaTeX will use whatever is
608         // appropriate (when there are several versions in different formats)
609         string const latex_str = message.empty() ?
610                 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
611                 (before + '{' + relative_file + " not found!}" + after);
612         os << latex_str;
613
614         lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
615                                 << latex_str << endl;
616         // Return how many newlines we issued.
617         return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
618 }
619
620
621 int InsetGraphics::plaintext(Buffer const &, ostream & os,
622                          OutputParams const &) const
623 {
624         // No graphics in ascii output. Possible to use gifscii to convert
625         // images to ascii approximation.
626         // 1. Convert file to ascii using gifscii
627         // 2. Read ascii output file and add it to the output stream.
628         // at least we send the filename
629         os << '<' << bformat(_("Graphics file: %1$s"),
630                              params().filename.absFilename()) << ">\n";
631         return 0;
632 }
633
634
635 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os,
636                             OutputParams const &) const
637 {
638         string const file_name = buf.niceFile() ?
639                                 params().filename.relFilename(buf.filePath()):
640                                 params().filename.absFilename();
641
642         os << "<eps file=\"" << file_name << "\">\n";
643         os << "<img src=\"" << file_name << "\">";
644         return 0;
645 }
646
647
648 // For explanation on inserting graphics into DocBook checkout:
649 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
650 // See also the docbook guide at http://www.docbook.org/
651 int InsetGraphics::docbook(Buffer const &, ostream & os,
652                            OutputParams const &) const
653 {
654         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
655         // need to switch to MediaObject. However, for now this is sufficient and
656         // easier to use.
657         os << "<graphic fileref=\"&" << graphic_label << ";\">";
658         return 0;
659 }
660
661
662 void InsetGraphics::validate(LaTeXFeatures & features) const
663 {
664         // If we have no image, we should not require anything.
665         if (params().filename.empty())
666                 return;
667
668         features.includeFile(graphic_label,
669                              RemoveExtension(params().filename.absFilename()));
670
671         features.require("graphicx");
672
673         if (params().subcaption)
674                 features.require("subfigure");
675 }
676
677
678 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
679 {
680         // If nothing is changed, just return and say so.
681         if (params() == p && !p.filename.empty())
682                 return false;
683
684         // Copy the new parameters.
685         params_ = p;
686
687         // Update the display using the new parameters.
688         graphic_->update(params().as_grfxParams());
689
690         // We have changed data, report it.
691         return true;
692 }
693
694
695 InsetGraphicsParams const & InsetGraphics::params() const
696 {
697         return params_;
698 }
699
700
701 string const InsetGraphicsMailer::name_("graphics");
702
703 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
704         : inset_(inset)
705 {}
706
707
708 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
709 {
710         return params2string(inset_.params(), buffer);
711 }
712
713
714 void InsetGraphicsMailer::string2params(string const & in,
715                                         Buffer const & buffer,
716                                         InsetGraphicsParams & params)
717 {
718         params = InsetGraphicsParams();
719
720         if (in.empty())
721                 return;
722
723         istringstream data(in);
724         LyXLex lex(0,0);
725         lex.setStream(data);
726
727         if (lex.isOK()) {
728                 lex.next();
729                 string const token = lex.getString();
730                 if (token != name_)
731                         return;
732         }
733
734         if (lex.isOK()) {
735                 InsetGraphics inset;
736                 inset.readInsetGraphics(lex, buffer.filePath());
737                 params = inset.params();
738         }
739 }
740
741
742 string const
743 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
744                                    Buffer const & buffer)
745 {
746         ostringstream data;
747         data << name_ << ' ';
748         params.Write(data, buffer.filePath());
749         data << "\\end_inset\n";
750         return data.str();
751 }