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