]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
73644321168fdc19a44fb75e2a7b74eb4201d776
[lyx.git] / src / insets / insetgraphics.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *       
6  *           Copyright 1995-2001 the LyX Team.
7  *           
8  *           This file Copyright 2000 Baruch Even.
9  * ====================================================== */
10
11 /*
12 Major tasks:
13         * Switch to convert the images in the background, this requires work on
14                 the converter, the systemcontroller and the graphics cache.
15
16 Minor tasks:
17     * Pop up a dialog if the widget version is higher than what we accept.
18         * Provide sed/awk/C code to downgrade from InsetGraphics to FigInset(?)
19         
20 */
21
22 /*
23 Known BUGS:
24     
25     * If the image is from the clipart, and the document is moved to another
26        directory, the user is screwed. Need a way to handle it.
27        This amounts to a problem of when to use relative or absolute file paths
28        We should probably use what the user asks to use... but when he chooses
29        by the file dialog we normally get an absolute path and this may not be 
30        what the user meant.
31     * Bug in FileDlg class (src/filedlg.[hC]) when selecting a file and then
32         pressing ok, it counts as if no real selection done. Apparently
33         when choosing a file it doesn't update the select file input line.
34                 
35         * If we are trying to create a file in a read-only directory and there
36                 are graphics that need converting, the converting will fail because
37                 it is done in-place, into the same directory as the original image.
38                 This needs to be fixed in the src/converter.C file
39                 [ This is presumed to be fixed, needs testing.]
40
41         * We do not dither or resize the image in a WYSIWYM way, we load it at
42                 its original size and color, resizing is done in the final output,
43                 but not in the LyX window.
44                 
45 TODO Before initial production release:
46     * Replace insetfig everywhere
47         * Search for comments of the form
48             // INSET_GRAPHICS: remove this when InsetFig is thrown.
49           And act upon them. Make sure not to remove InsetFig code for the 
50                   1.2.0 release, only afterwards, after deployment shows InsetGraphics
51                   to be ok.
52  
53 TODO Extended features:
54  
55     * Advanced Latex tab folder.
56     * Add support for more features so that it will be better than insetfig.
57         * Keep aspect ratio radio button
58         * Support for complete control over the latex parameters for TeXperts
59         * What advanced features the users want to do?
60             Implement them in a non latex dependent way, but a logical way.
61             LyX should translate it to latex or any other fitting format.
62     * Add a way to roll the image file into the file format.
63     * When loading, if the image is not found in the expected place, try
64        to find it in the clipart, or in the same directory with the image.
65     * Keep a tab on the image file, if it changes, update the lyx view.
66         * The image choosing dialog could show thumbnails of the image formats
67                 it knows of, thus selection based on the image instead of based on
68                 filename.
69         * Add support for the 'picins' package.
70         * Add support for the 'picinpar' package.
71         * Improve support for 'subfigure' - Allow to set the various options
72                 that are possible.
73         * Add resizing by percentage of image size (50%, 150%) - usefull for two
74                 images of different size to be resized where they both should have
75                 the same scale compared to each other.
76  */
77
78 /* NOTES:
79  *
80  * Intentions:
81  *  This is currently a moving target, I'm trying stuff and learning what
82  *  is needed and how to accomplish it, since there is no predefined goal or
83  *  way to go I invent it as I go.
84  *
85  *  My current intention is for seperation from LaTeX, the basic needs are 
86  *  resizing and rotating, displaying on screen in various depths and printing
87  *  conversion of depths (independent of the display depth). For this I'll 
88  *  provide a simple interface.
89  *
90  *  The medium level includes clipping of the image, but in a limited way.
91  *
92  *  For the LaTeX gurus I'll provide a complete control over the output, but
93  *  this is latex dependent and guru dependent so I'd rather avoid doing this
94  *  for the normal user. This stuff includes clipping, special image size
95  *  specifications (\textwidth\minus 2in) which I see no way to generalize
96  *  to non-latex specific way.
97  *
98  * Used packages:
99  *  'graphicx' for the graphics inclusion.
100  *  'subfigure' for the subfigures.
101  *
102  * Fileformat:
103  *
104  * Current version is 1 (inset file format version), when changing it
105  * it should be changed in the Write() function when writing in one place
106  * and when reading one should change the version check and the error message.
107  *
108  * The filename is kept in  the lyx file in a relative way, so as to allow
109  * moving the document file and its images with no problem.
110  *
111  * Conversions:
112  *   Postscript output means EPS figures.
113  *
114  *   PDF output is best done with PDF figures if it's a direct conversion
115  *   or PNG figures otherwise.
116  *      Image format
117  *      from        to
118  *      EPS         epstopdf
119  *      JPG/PNG     direct
120  *      PDF         direct
121  *      others      PNG
122  */
123
124 #include <config.h> 
125
126 #ifdef __GNUG__
127 #pragma implementation
128 #endif 
129
130 #include "insets/insetgraphics.h"
131 #include "insets/insetgraphicsParams.h"
132 #include "graphics/GraphicsCache.h"
133 #include "graphics/GraphicsCacheItem.h"
134
135 #include "frontends/Dialogs.h"
136 #include "LyXView.h"
137 #include "buffer.h"
138 #include "BufferView.h"
139 #include "converter.h"
140 #include "frontends/support/LyXImage.h"
141 #include "Painter.h"
142 #include "lyx_gui_misc.h"
143 #include "support/FileInfo.h"
144 #include "support/filetools.h"
145 #include "support/lyxlib.h"
146 #include "lyxtext.h"
147 #include "lyxrc.h"
148 #include "font.h" // For the lyxfont class.
149 #include <algorithm> // For the std::max
150 #include "support/lyxmanip.h"
151 #include "debug.h"
152 #include "gettext.h"
153
154 extern string system_tempdir;
155
156 using std::ostream;
157 using std::endl;
158
159
160 // This function is a utility function
161 inline
162 string const RemoveExtension(string const & filename)
163 {
164         return ChangeExtension(filename, string());
165 }
166
167
168 // Initialize only those variables that do not have a constructor.
169 InsetGraphics::InsetGraphics()
170         : cacheHandle(0), imageLoaded(false)
171 {}
172
173
174 InsetGraphics::InsetGraphics(InsetGraphics const & ig, bool same_id)
175         : Inset(), SigC::Object()
176         , cacheHandle(ig.cacheHandle)
177         , imageLoaded(ig.imageLoaded)
178 {
179         setParams(ig.getParams());
180         if (same_id)
181                 id_ = ig.id_;
182 }
183
184
185 InsetGraphics::~InsetGraphics()
186 {
187         // Emits the hide signal to the dialog connected (if any)
188         hideDialog();
189 }
190
191
192 string const
193 InsetGraphics::statusMessage() const
194 {
195         string msg;
196
197         if (cacheHandle.get()) {
198                 switch (cacheHandle->getImageStatus()) {
199                 case GraphicsCacheItem::UnknownError:
200                         msg = _("Unknown Error");
201                         break;
202
203                 case GraphicsCacheItem::Loading:
204                         msg = _("Loading...");
205                         break;
206
207                 case GraphicsCacheItem::ErrorReading:
208                         msg = _("Error reading");
209                         break;
210
211                 case GraphicsCacheItem::ErrorConverting:
212                         msg = _("Error converting");
213                         break;
214
215                 case GraphicsCacheItem::Loaded:
216                         // No message to write.
217                         break;
218                 }
219         }
220
221         return msg;
222 }
223
224
225 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
226 {
227         LyXImage * pixmap = 0;
228         if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
229                 return pixmap->getHeight();
230         else
231                 return 50;
232 }
233
234
235 int InsetGraphics::descent(BufferView *, LyXFont const &) const
236 {
237         // this is not true if viewport is used and clip is not.
238         return 0;
239 }
240
241
242 int InsetGraphics::width(BufferView *, LyXFont const & font) const
243 {
244         LyXImage * pixmap = 0;
245         
246         if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
247                 return pixmap->getWidth();
248         else {
249                 string const msg = statusMessage();
250                 int font_width = 0;
251                 
252                 if (!msg.empty())
253                         font_width = lyxfont::width(msg, font);
254                 
255                 return std::max(50, font_width + 15);
256         }
257 }
258
259
260 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
261                          int baseline, float & x, bool) const
262 {
263         Painter & paint = bv->painter();
264
265         int ldescent = descent(bv, font);
266         int lascent = ascent(bv, font);
267         int lwidth = width(bv, font);
268
269         // Make sure x is updated upon exit from this routine
270         int old_x = int(x);
271         x += lwidth;
272
273         // This will draw the graphics. If the graphics has not been loaded yet,
274         // we draw just a rectangle.
275         if (imageLoaded) {
276
277                 paint.image(old_x + 2, baseline - lascent,
278                             lwidth - 4, lascent + ldescent,
279                             cacheHandle->getImage());
280         } else {
281                 
282                 // Get the image status, default to unknown error.
283                 GraphicsCacheItem::ImageStatus status = GraphicsCacheItem::UnknownError;
284                 if (cacheHandle.get())
285                         status = cacheHandle->getImageStatus();
286                 
287                 // Check if the image is now ready.
288                 if (status == GraphicsCacheItem::Loaded) {
289                         imageLoaded = true;
290
291                         // Tell BufferView we need to be updated!
292                         bv->text->status(bv, LyXText::CHANGED_IN_DRAW);
293                         return;
294                 }
295
296                 
297                 paint.rectangle(old_x + 2, baseline - lascent,
298                                 lwidth - 4,
299                                 lascent + ldescent);
300
301                 string const msg = statusMessage();
302                 if (!msg.empty()) {
303                         // Print the message.
304                         LyXFont msgFont(font);
305                         msgFont.setFamily(LyXFont::SANS_FAMILY);
306                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
307                         string const justname = OnlyFilename (params.filename);
308                         paint.text(old_x + 8, 
309                                    baseline - lyxfont::maxAscent(msgFont) - 4,
310                                    justname, msgFont);
311
312                         msgFont.setSize(LyXFont::SIZE_TINY);
313                         paint.text(old_x + 8, baseline - 4, msg, msgFont);
314                 }
315         }
316 }
317
318
319 void InsetGraphics::edit(BufferView *bv, int, int, unsigned int)
320 {
321         bv->owner()->getDialogs()->showGraphics(this);
322 }
323
324
325 void InsetGraphics::edit(BufferView * bv, bool)
326 {
327         edit(bv, 0, 0, 0);
328 }
329
330
331 Inset::EDITABLE InsetGraphics::editable() const
332 {
333         return IS_EDITABLE;
334 }
335
336
337 void InsetGraphics::write(Buffer const * buf, ostream & os) const
338 {
339         os << "Graphics FormatVersion 1\n";
340
341         params.Write(buf, os);
342 }
343
344
345 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
346 {
347         string const token = lex.GetString();
348
349         if (token == "Graphics")
350                 readInsetGraphics(buf, lex);
351         else if (token == "Figure") // Compatibility reading of FigInset figures.
352                 readFigInset(buf, lex);
353         else
354                 lyxerr[Debug::INFO] << "Not a Graphics or Figure inset!\n";
355
356         updateInset();
357 }
358
359 void InsetGraphics::readInsetGraphics(Buffer const * buf, LyXLex & lex)
360 {
361         bool finished = false;
362
363         while (lex.IsOK() && !finished) {
364                 lex.next();
365
366                 string const token = lex.GetString();
367                 lyxerr[Debug::INFO] << "Token: '" << token << '\'' 
368                                     << std::endl;
369
370                 if (token.empty()) {
371                         continue;
372                 } else if (token == "\\end_inset") {
373                         finished = true;
374                 } else if (token == "FormatVersion") {
375                         lex.next();
376                         int version = lex.GetInteger();
377                         if (version > 1)
378                                 lyxerr
379                                 << "This document was created with a newer Graphics widget"
380                                 ", You should use a newer version of LyX to read this"
381                                 " file."
382                                 << std::endl;
383                         // TODO: Possibly open up a dialog?
384                 }
385                 else {
386                         if (! params.Read(buf, lex, token))
387                                 lyxerr << "Unknown token, " << token << ", skipping." 
388                                         << std::endl;
389                 }
390         }
391 }
392
393
394 void InsetGraphics::readFigInset(Buffer const * buf, LyXLex & lex)
395 {
396         bool finished = false;
397         
398         while (lex.IsOK() && !finished) {
399                 lex.next();
400
401                 string const token = lex.GetString();
402                 lyxerr[Debug::INFO] << "Token: " << token << endl;
403                 
404                 if (token.empty())
405                         continue;
406                 else if (token == "\\end_inset") {
407                         finished = true;
408                 } else if (token == "file") {
409                         if (lex.next()) {
410                                 string const name = lex.GetString();
411                                 string const path = OnlyPath(buf->fileName());
412                                 params.filename = MakeAbsPath(name, path);
413                         }
414                 } else if (token == "extra") {
415                         if (lex.next());
416                         // kept for backwards compability. Delete in 0.13.x
417                 } else if (token == "subcaption") {
418                         if (lex.EatLine())
419                                 params.subcaptionText = lex.GetString();
420                 } else if (token == "label") {
421                         if (lex.next());
422                         // kept for backwards compability. Delete in 0.13.x
423                 } else if (token == "angle") {
424                         if (lex.next())
425                                 params.rotateAngle = lex.GetFloat();
426                 } else if (token == "size") {
427                         // Size of image on screen is ignored in InsetGraphics, just eat
428                         // the input.
429                         if (lex.next())
430                                 lex.GetInteger();
431                         if (lex.next())
432                                 lex.GetInteger();
433                 } else if (token == "flags") {
434                         InsetGraphicsParams::DisplayType tmp = InsetGraphicsParams::COLOR;
435                         if (lex.next())
436                                 switch (lex.GetInteger()) {
437                                 case 1: tmp = InsetGraphicsParams::MONOCHROME; break;
438                                 case 2: tmp = InsetGraphicsParams::GRAYSCALE; break;
439                                 }
440                         params.display = tmp;
441                 } else if (token == "subfigure") {
442                         params.subcaption = true;
443                 } else if (token == "width") {
444                         if (lex.next())
445                                 params.widthResize = static_cast<InsetGraphicsParams::Resize>(lex.GetInteger());
446                         if (lex.next())
447                                 params.widthSize = lex.GetFloat();
448                 } else if (token == "height") {
449                         if (lex.next())
450                                 params.heightResize = static_cast<InsetGraphicsParams::Resize>(lex.GetInteger());
451                         if (lex.next())
452                                 params.heightSize = lex.GetFloat();
453                 }
454         }
455 }
456
457
458 namespace {
459
460 void formatResize(ostream & os, string const & key,
461                   InsetGraphicsParams::Resize resizeType, double size)
462 {
463         switch (resizeType) {
464         case InsetGraphicsParams::DEFAULT_SIZE:
465                 break;
466
467         case InsetGraphicsParams::CM:
468                 os << key << '=' << size << "cm,";
469                 break;
470
471         case InsetGraphicsParams::INCH:
472                 os << key << '=' << size << "in,";
473                 break;
474
475         case InsetGraphicsParams::PERCENT_PAGE:
476                 os << key << '=' << size / 100 << "\\text" << key << ',';
477                 break;
478
479         case InsetGraphicsParams::PERCENT_COLUMN:
480                 os << key << '=' << size / 100 << "\\column" << key << ',';
481                 break;
482
483         }
484 }
485
486 } // namespace anon
487
488
489 string const
490 InsetGraphics::createLatexOptions() const
491 {
492         // Calculate the options part of the command, we must do it to a string
493         // stream since we might have a trailing comma that we would like to remove
494         // before writing it to the output stream.
495         ostringstream options;
496
497         formatResize(options, "width", params.widthResize, params.widthSize);
498         formatResize(options, "height", params.heightResize, params.heightSize);
499
500         // Make sure it's not very close to zero, a float can be effectively
501         // zero but not exactly zero.
502         if (lyx::float_equal(params.rotateAngle, 0, 0.001)) {
503                 options << "angle="
504                         << params.rotateAngle << ',';
505         }
506
507         string opts = options.str().c_str();
508         opts = strip(opts, ',');
509
510         return opts;
511 }
512
513 namespace {
514         
515 string decideOutputImageFormat(string const & in_fmt)
516 {
517         // lyxrc.pdf_mode means:
518         // Are we creating a PDF or a PS file?
519         // (Should actually mean, are we using latex or pdflatex).
520         
521         if (lyxrc.pdf_mode) {
522                 if (in_fmt == "eps" || in_fmt == "epsi" || in_fmt == "pdf")
523                         return "pdf";
524                 else if (in_fmt == "jpg" || in_fmt == "jpeg")
525                         return in_fmt;
526                 else
527                         return "png";
528         }
529
530         // If it's postscript, we always do eps.
531         if (in_fmt == "eps" || in_fmt == "epsi")
532                 return in_fmt; // eps & epsi are both eps, but different extension.
533         return "eps";
534 }
535
536 } // Anon. namespace
537
538 string const 
539 InsetGraphics::prepareFile(Buffer const *buf) const
540 {
541
542         // do_convert = Do we need to convert the file?
543         // nice = Do we create a nice version?
544         //        This is used when exporting the latex file only.
545         // 
546         // 
547         // if (!do_convert)
548         //   return original filename
549         // 
550         // if (!nice)
551         //   convert_place = temp directory
552         //   return new filename in temp directory
553         // else
554         //   convert_place = original file directory
555         //   return original filename without the extension
556         //
557         
558         // Get the extension (format) of the original file.
559         string const extension = GetExtension(params.filename);
560         
561         // Are we creating a PDF or a PS file?
562         // (Should actually mean, are we usind latex or pdflatex).
563         string const image_target = decideOutputImageFormat(extension);
564
565         if (extension == image_target)
566                 return params.filename;
567
568         string outfile;
569         if (!buf->niceFile) {
570                 string const temp = AddName(buf->tmppath, params.filename);
571                 outfile = RemoveExtension(temp);
572                 
573                 //lyxerr << "buf::tmppath = " << buf->tmppath << "\n";
574                 //lyxerr << "filename = " << params.filename << "\n";
575                 //lyxerr << "temp = " << temp << "\n";
576                 //lyxerr << "outfile = " << outfile << endl;
577         } else {
578                 string const path = OnlyPath(buf->fileName());
579                 string const relname = MakeRelPath(params.filename, path);
580                 outfile = RemoveExtension(relname);
581         }
582
583         converters.Convert(buf, params.filename, outfile, extension, image_target);
584         
585         return outfile;
586 }
587
588
589 int InsetGraphics::latex(Buffer const *buf, ostream & os,
590                          bool /*fragile*/, bool/*fs*/) const
591 {
592         // MISSING: We have to decide how to do the order of the options
593         // that is dependent of order, like width, height, angle. Should
594         // we rotate before scale? Should we let the user decide?
595         // bool rot_before_scale; ?
596
597         // (BE) As a first step we should do a scale before rotate since this is
598         // more like the natural thought of how to do it.
599         // (BE) I believe that a priority list presented to the user with
600         // a default order would be the best, though it would be better to
601         // hide such a thing in an "Advanced options" dialog.
602         // (BE) This should go an advanced LaTeX options dialog.
603
604         // If there is no file specified, just output a message about it in
605         // the latex output.
606         if (params.filename.empty()) {
607                 os  << "\\fbox{\\rule[-0.5in]{0pt}{1in}"
608                         << _("empty figure path")
609                         << "}\n";
610
611                 return 1; // One end of line marker added to the stream.
612         }
613
614         // Keep count of newlines that we issued.
615         int newlines = 0;
616
617         // This variables collect all the latex code that should be before and
618         // after the actual includegraphics command.
619         string before;
620         string after;
621
622         // Do we want subcaptions?
623         if (params.subcaption) {
624                 before += "\\subfigure[" + params.subcaptionText + "]{";
625                 after = '}' + after;
626         }
627
628         // We never use the starred form, we use the "clip" option instead.
629         os << before << "\\includegraphics";
630
631         // Write the options if there are any.
632         string const opts = createLatexOptions();
633         if (!opts.empty()) {
634                 os << '[' << opts << ']';
635         }
636
637         // Make the filename relative to the lyx file
638         // and remove the extension so the LaTeX will use whatever is
639         // appropriate (when there are several versions in different formats)
640         string const filename = prepareFile(buf);
641         
642         os << '{' << filename << '}' << after;
643
644         // Return how many newlines we issued.
645         return newlines;
646 }
647
648
649 int InsetGraphics::ascii(Buffer const *, ostream &, int) const
650 {
651         // No graphics in ascii output. Possible to use gifscii to convert
652         // images to ascii approximation.
653         
654         // 1. Convert file to ascii using gifscii
655         // 2. Read ascii output file and add it to the output stream.
656         
657         return 0;
658 }
659
660
661 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
662 {
663         // No graphics in LinuxDoc output. Should check how/what to add.
664         return 0;
665 }
666
667
668 // For explanation on inserting graphics into DocBook checkout:
669 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
670 // See also the docbook guide at http://www.docbook.org/
671 int InsetGraphics::docBook(Buffer const * buf, ostream & os) const
672 {
673         // Change the path to be relative to the main file.
674         string const buffer_dir = OnlyPath(buf->fileName());
675         string const filename = RemoveExtension(
676                                    MakeRelPath(params.filename, buffer_dir));
677
678         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will 
679         // need to switch to MediaObject. However, for now this is sufficient and 
680         // easier to use.
681         os << "<graphic fileref=\"" << filename << "\"></graphic>";
682         return 0;
683 }
684
685
686 void InsetGraphics::validate(LaTeXFeatures & features) const
687 {
688         // If we have no image, we should not require anything.
689         if (params.filename.empty())
690                 return ;
691
692         features.graphicx = true;
693
694         if (params.subcaption)
695                 features.subfigure = true;
696 }
697
698
699 // Update the inset after parameters changed (read from file or changed in
700 // dialog.
701 void InsetGraphics::updateInset() const
702 {
703         GraphicsCache & gc = GraphicsCache::getInstance();
704         boost::shared_ptr<GraphicsCacheItem> temp(0);
705
706         // We do it this way so that in the face of some error, we will still
707         // be in a valid state.
708         if (!params.filename.empty()) {
709                 temp = gc.addFile(params.filename);
710         }
711
712         // Mark the image as unloaded so that it gets updated.
713         imageLoaded = false;
714
715         cacheHandle = temp;
716 }
717
718
719 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
720 {
721         // If nothing is changed, just return and say so.
722         if (params == p)
723                 return false;
724
725         // Copy the new parameters.
726         params = p;
727
728         // Update the inset with the new parameters.
729         updateInset();
730
731         // We have changed data, report it.
732         return true;
733 }
734
735
736 InsetGraphicsParams InsetGraphics::getParams() const
737 {
738         return params;
739 }
740
741
742 Inset * InsetGraphics::clone(Buffer const &, bool same_id) const
743 {
744         return new InsetGraphics(*this, same_id);
745 }