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