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