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