]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
6333d45e8336e0fb7a8a68d1c04958463f3c024c
[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         // Garst has many eps files with various extensions, we just assume
532         // whatever goes in (except those we know to be otherwise) is eps
533         if (in_fmt == "gif" || in_fmt == "png" || in_fmt == "jpg")
534                 return "eps";
535         return in_fmt;
536 }
537
538 } // Anon. namespace
539
540 string const 
541 InsetGraphics::prepareFile(Buffer const *buf) const
542 {
543
544         // do_convert = Do we need to convert the file?
545         // nice = Do we create a nice version?
546         //        This is used when exporting the latex file only.
547         // 
548         // 
549         // if (!do_convert)
550         //   return original filename
551         // 
552         // if (!nice)
553         //   convert_place = temp directory
554         //   return new filename in temp directory
555         // else
556         //   convert_place = original file directory
557         //   return original filename without the extension
558         //
559         
560         // Get the extension (format) of the original file.
561         string const extension = GetExtension(params.filename);
562         
563         // Are we creating a PDF or a PS file?
564         // (Should actually mean, are we usind latex or pdflatex).
565         string const image_target = decideOutputImageFormat(extension);
566
567         if (extension == image_target)
568                 return params.filename;
569
570         string outfile;
571         if (!buf->niceFile) {
572                 string const temp = AddName(buf->tmppath, params.filename);
573                 outfile = RemoveExtension(temp);
574                 
575                 //lyxerr << "buf::tmppath = " << buf->tmppath << "\n";
576                 //lyxerr << "filename = " << params.filename << "\n";
577                 //lyxerr << "temp = " << temp << "\n";
578                 //lyxerr << "outfile = " << outfile << endl;
579         } else {
580                 string const path = OnlyPath(buf->fileName());
581                 string const relname = MakeRelPath(params.filename, path);
582                 outfile = RemoveExtension(relname);
583         }
584
585         converters.Convert(buf, params.filename, outfile, extension, image_target);
586         
587         return outfile;
588 }
589
590
591 int InsetGraphics::latex(Buffer const *buf, ostream & os,
592                          bool /*fragile*/, bool/*fs*/) const
593 {
594         // MISSING: We have to decide how to do the order of the options
595         // that is dependent of order, like width, height, angle. Should
596         // we rotate before scale? Should we let the user decide?
597         // bool rot_before_scale; ?
598
599         // (BE) As a first step we should do a scale before rotate since this is
600         // more like the natural thought of how to do it.
601         // (BE) I believe that a priority list presented to the user with
602         // a default order would be the best, though it would be better to
603         // hide such a thing in an "Advanced options" dialog.
604         // (BE) This should go an advanced LaTeX options dialog.
605
606         // If there is no file specified, just output a message about it in
607         // the latex output.
608         if (params.filename.empty()) {
609                 os  << "\\fbox{\\rule[-0.5in]{0pt}{1in}"
610                         << _("empty figure path")
611                         << "}\n";
612
613                 return 1; // One end of line marker added to the stream.
614         }
615
616         // Keep count of newlines that we issued.
617         int newlines = 0;
618
619         // This variables collect all the latex code that should be before and
620         // after the actual includegraphics command.
621         string before;
622         string after;
623
624         // Do we want subcaptions?
625         if (params.subcaption) {
626                 before += "\\subfigure[" + params.subcaptionText + "]{";
627                 after = '}' + after;
628         }
629
630         // We never use the starred form, we use the "clip" option instead.
631         os << before << "\\includegraphics";
632
633         // Write the options if there are any.
634         string const opts = createLatexOptions();
635         if (!opts.empty()) {
636                 os << '[' << opts << ']';
637         }
638
639         // Make the filename relative to the lyx file
640         // and remove the extension so the LaTeX will use whatever is
641         // appropriate (when there are several versions in different formats)
642         string const filename = prepareFile(buf);
643         
644         os << '{' << filename << '}' << after;
645
646         // Return how many newlines we issued.
647         return newlines;
648 }
649
650
651 int InsetGraphics::ascii(Buffer const *, ostream &, int) const
652 {
653         // No graphics in ascii output. Possible to use gifscii to convert
654         // images to ascii approximation.
655         
656         // 1. Convert file to ascii using gifscii
657         // 2. Read ascii output file and add it to the output stream.
658         
659         return 0;
660 }
661
662
663 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
664 {
665         // No graphics in LinuxDoc output. Should check how/what to add.
666         return 0;
667 }
668
669
670 // For explanation on inserting graphics into DocBook checkout:
671 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
672 // See also the docbook guide at http://www.docbook.org/
673 int InsetGraphics::docBook(Buffer const * buf, ostream & os) const
674 {
675         // Change the path to be relative to the main file.
676         string const buffer_dir = OnlyPath(buf->fileName());
677         string const filename = RemoveExtension(
678                                    MakeRelPath(params.filename, buffer_dir));
679
680         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will 
681         // need to switch to MediaObject. However, for now this is sufficient and 
682         // easier to use.
683         os << "<graphic fileref=\"" << filename << "\"></graphic>";
684         return 0;
685 }
686
687
688 void InsetGraphics::validate(LaTeXFeatures & features) const
689 {
690         // If we have no image, we should not require anything.
691         if (params.filename.empty())
692                 return ;
693
694         features.graphicx = true;
695
696         if (params.subcaption)
697                 features.subfigure = true;
698 }
699
700
701 // Update the inset after parameters changed (read from file or changed in
702 // dialog.
703 void InsetGraphics::updateInset() const
704 {
705         GraphicsCache & gc = GraphicsCache::getInstance();
706         boost::shared_ptr<GraphicsCacheItem> temp(0);
707
708         // We do it this way so that in the face of some error, we will still
709         // be in a valid state.
710         if (!params.filename.empty()) {
711                 temp = gc.addFile(params.filename);
712         }
713
714         // Mark the image as unloaded so that it gets updated.
715         imageLoaded = false;
716
717         cacheHandle = temp;
718 }
719
720
721 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
722 {
723         // If nothing is changed, just return and say so.
724         if (params == p)
725                 return false;
726
727         // Copy the new parameters.
728         params = p;
729
730         // Update the inset with the new parameters.
731         updateInset();
732
733         // We have changed data, report it.
734         return true;
735 }
736
737
738 InsetGraphicsParams InsetGraphics::getParams() const
739 {
740         return params;
741 }
742
743
744 Inset * InsetGraphics::clone(Buffer const &, bool same_id) const
745 {
746         return new InsetGraphics(*this, same_id);
747 }