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