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