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