]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
Added some known bugs to the listed ones.
[lyx.git] / src / insets / insetgraphics.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *       
6  *           Copyright 1995-2000 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
149 extern string system_tempdir;
150
151 using std::ostream;
152
153 // This function is a utility function
154 inline
155 string const RemoveExtension(string const & filename)
156 {
157         return ChangeExtension(filename, string());
158 }
159
160
161 // Initialize only those variables that do not have a constructor.
162 InsetGraphics::InsetGraphics()
163         : cacheHandle(0), imageLoaded(false)
164 {}
165
166 InsetGraphics::~InsetGraphics()
167 {
168         // Emits the hide signal to the dialog connected (if any)
169         hideDialog();
170 }
171
172 char const *
173 InsetGraphics::statusMessage() const
174 {
175         char const * msg = 0;
176
177         if (cacheHandle.get()) {
178                 switch (cacheHandle->getImageStatus()) {
179                 case GraphicsCacheItem::UnknownError:
180                         msg = _("Unknown Error");
181                         break;
182
183                 case GraphicsCacheItem::Loading:
184                         msg = _("Loading...");
185                         break;
186
187                 case GraphicsCacheItem::ErrorReading:
188                         msg = _("Error reading");
189                         break;
190
191                 case GraphicsCacheItem::ErrorConverting:
192                         msg = _("Error converting");
193                         break;
194
195                 case GraphicsCacheItem::Loaded:
196                         // No message to write.
197                         break;
198                 }
199         }
200
201         return msg;
202 }
203
204 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
205 {
206         LyXImage * pixmap = 0;
207         if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
208                 return pixmap->getHeight();
209         else
210                 return 50;
211 }
212
213
214 int InsetGraphics::descent(BufferView *, LyXFont const &) const
215 {
216         // this is not true if viewport is used and clip is not.
217         return 0;
218 }
219
220
221 int InsetGraphics::width(BufferView *, LyXFont const & font) const
222 {
223         LyXImage * pixmap = 0;
224         
225         if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
226                 return pixmap->getWidth();
227         else {
228                 char const * msg = statusMessage();
229                 int font_width = 0;
230                 
231                 if (msg)
232                         font_width = lyxfont::width(msg, font);
233                 
234                 return std::max(50, font_width + 15);
235         }
236 }
237
238 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
239                          int baseline, float & x, bool) const
240 {
241         Painter & paint = bv->painter();
242
243         int ldescent = descent(bv, font);
244         int lascent = ascent(bv, font);
245         int lwidth = width(bv, font);
246
247         // Make sure x is updated upon exit from this routine
248         float old_x = x;
249         x += lwidth;
250
251         // This will draw the graphics. If the graphics has not been loaded yet,
252         // we draw just a rectangle.
253         if (imageLoaded) {
254
255                 paint.image(int(old_x) + 2, baseline - lascent,
256                              lwidth - 4, lascent + ldescent,
257                                          cacheHandle->getImage());
258         } else {
259                 
260                 // Get the image status, default to unknown error.
261                 GraphicsCacheItem::ImageStatus status = GraphicsCacheItem::UnknownError;
262                 if (cacheHandle.get())
263                         status = cacheHandle->getImageStatus();
264                 
265                 // Check if the image is now ready.
266                 if (status == GraphicsCacheItem::Loaded) {
267                         imageLoaded = true;
268
269                         // Tell BufferView we need to be updated!
270                         bv->text->status = LyXText::CHANGED_IN_DRAW;
271                         return;
272                 }
273
274                 char const * msg = statusMessage();
275                 
276                 paint.rectangle(int(old_x) + 2, baseline - lascent,
277                                 lwidth - 4,
278                                 lascent + ldescent);
279
280                 if (msg) {
281                         // Print the message.
282                         LyXFont msgFont(font);
283                         msgFont.setFamily(LyXFont::SANS_FAMILY);
284                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
285                         string const justname = OnlyFilename (params.filename);
286                         paint.text(int(old_x) + 8, 
287                                         baseline - lyxfont::maxAscent(msgFont) - 4,
288                                     justname, msgFont);
289
290                         msgFont.setSize(LyXFont::SIZE_TINY);
291                         paint.text(int(old_x) + 8, baseline - 4, 
292                                         msg, strlen(msg), msgFont);
293                 }
294         }
295 }
296
297
298 void InsetGraphics::Edit(BufferView *bv, int, int, unsigned int)
299 {
300         bv->owner()->getDialogs()->showGraphics(this);
301 }
302
303
304 Inset::EDITABLE InsetGraphics::Editable() const
305 {
306         return IS_EDITABLE;
307 }
308
309
310 void InsetGraphics::Write(Buffer const * buf, ostream & os) const
311 {
312         os << "GRAPHICS FormatVersion 1\n";
313
314         params.Write(buf, os);
315 }
316
317
318 void InsetGraphics::Read(Buffer const * buf, LyXLex & lex)
319 {
320         bool finished = false;
321
322         while (lex.IsOK() && !finished) {
323                 lex.next();
324
325                 string const token = lex.GetString();
326                 lyxerr.debug() << "Token: '" << token << '\'' << std::endl;
327
328                 if (token.empty()) {
329                         continue;
330                 } else if (token == "\\end_inset") {
331                         finished = true;
332                 } else if (token == "FormatVersion") {
333                         lex.next();
334                         int version = lex.GetInteger();
335                         if (version > 1)
336                                 lyxerr
337                                 << "This document was created with a newer Graphics widget"
338                                 ", You should use a newer version of LyX to read this"
339                                 " file."
340                                 << std::endl;
341                         // TODO: Possibly open up a dialog?
342                 }
343                 else {
344                         if (! params.Read(buf, lex, token))
345                                 lyxerr << "Unknown token, " << token << ", skipping." 
346                                         << std::endl;
347                 }
348         }
349
350         updateInset();
351 }
352
353
354 namespace {
355
356 void formatResize(ostream & os, string const & key,
357                   InsetGraphicsParams::Resize resizeType, double size)
358 {
359         switch (resizeType) {
360         case InsetGraphicsParams::DEFAULT_SIZE:
361                 break;
362
363         case InsetGraphicsParams::CM:
364                 os << key << '=' << size << "cm,";
365                 break;
366
367         case InsetGraphicsParams::INCH:
368                 os << key << '=' << size << "in,";
369                 break;
370
371         case InsetGraphicsParams::PERCENT_PAGE:
372                 os << key << '=' << size / 100 << "\\text" << key << ',';
373                 break;
374
375         case InsetGraphicsParams::PERCENT_COLUMN:
376                 os << key << '=' << size / 100 << "\\column" << key << ',';
377                 break;
378
379         }
380 }
381
382 } // namespace anon
383
384
385 string const
386 InsetGraphics::createLatexOptions() const
387 {
388         // Calculate the options part of the command, we must do it to a string
389         // stream since we might have a trailing comma that we would like to remove
390         // before writing it to the output stream.
391         std::ostringstream options;
392
393         formatResize(options, "width", params.widthResize, params.widthSize);
394         formatResize(options, "height", params.heightResize, params.heightSize);
395
396         if (params.rotateAngle != 0) {
397                 options << "angle="
398                         << params.rotateAngle << ',';
399         }
400
401         string opts = options.str().c_str();
402         opts = strip(opts, ',');
403
404         return opts;
405 }
406
407
408
409 string const 
410 InsetGraphics::prepareFile(Buffer const *buf) const
411 {
412
413         // do_convert = Do we need to convert the file?
414         // nice = Do we create a nice version?
415         //        This is used when exporting the latex file only.
416         // 
417         // 
418         // if (!do_convert)
419         //   return original filename
420         // 
421         // if (!nice)
422         //   convert_place = temp directory
423         //   return new filename in temp directory
424         // else
425         //   convert_place = original file directory
426         //   return original filename without the extension
427         //
428         
429         // Get the extension (format) of the original file.
430         string const extension = GetExtension(params.filename);
431         
432         // Are we creating a PDF or a PS file?
433         // (Should actually mean, are we usind latex or pdflatex).
434         string const image_target = (lyxrc.pdf_mode ? "png" : "eps");
435
436         if (extension == image_target)
437                 return params.filename;
438
439         string outfile;
440         if (!buf->niceFile) {
441                 string const temp = AddName(buf->tmppath, params.filename);
442                 outfile = RemoveExtension(temp);
443                 
444                 //lyxerr << "buf::tmppath = " << buf->tmppath << "\n";
445                 //lyxerr << "filename = " << params.filename << "\n";
446                 //lyxerr << "temp = " << temp << "\n";
447                 //lyxerr << "outfile = " << outfile << endl;
448         } else {
449                 string const path = OnlyPath(buf->fileName());
450                 string const relname = MakeRelPath(params.filename, path);
451                 outfile = RemoveExtension(relname);
452         }
453
454         converters.Convert(buf, params.filename, outfile, extension, image_target);
455         
456         return outfile;
457 }
458
459 int InsetGraphics::Latex(Buffer const *buf, ostream & os,
460                 bool /*fragile*/, bool/*fs*/) const
461 {
462         // MISSING: We have to decide how to do the order of the options
463         // that is dependent of order, like width, height, angle. Should
464         // we rotate before scale? Should we let the user decide?
465         // bool rot_before_scale; ?
466
467         // (BE) As a first step we should do a scale before rotate since this is
468         // more like the natural thought of how to do it.
469         // (BE) I believe that a priority list presented to the user with
470         // a default order would be the best, though it would be better to
471         // hide such a thing in an "Advanced options" dialog.
472         // (BE) This should go an advanced LaTeX options dialog.
473
474         // If there is no file specified, just output a message about it in
475         // the latex output.
476         if (params.filename.empty()) {
477                 os  << "\\fbox{\\rule[-0.5in]{0pt}{1in}"
478                         << _("empty figure path")
479                         << "}\n";
480
481                 return 1; // One end of line marker added to the stream.
482         }
483
484         // Keep count of newlines that we issued.
485         int newlines = 0;
486
487         // This variables collect all the latex code that should be before and
488         // after the actual includegraphics command.
489         string before;
490         string after;
491
492         // If it's not an inline image, surround it with the centering paragraph.
493         if (! params.inlineFigure) {
494                 before += "\n" "\\vspace{0.3cm}\n" "{\\par\\centering ";
495                 after = " \\par}\n" "\\vspace{0.3cm}\n" + after;
496                 newlines += 4;
497         }
498
499         // Do we want subcaptions?
500         if (params.subcaption) {
501                 before += "\\subfigure[" + params.subcaptionText + "]{";
502                 after = '}' + after;
503         }
504
505         // We never use the starred form, we use the "clip" option instead.
506         os << before << "\\includegraphics";
507
508         // Write the options if there are any.
509         string const opts = createLatexOptions();
510         if (!opts.empty()) {
511                 os << '[' << opts << ']';
512         }
513
514         // Make the filename relative to the lyx file
515         // and remove the extension so the LaTeX will use whatever is
516         // appropriate (when there are several versions in different formats)
517         string const filename = prepareFile(buf);
518         
519         os << '{' << filename << '}' << after;
520
521         // Return how many newlines we issued.
522         return newlines;
523 }
524
525
526 int InsetGraphics::Ascii(Buffer const *, ostream &, int) const
527 {
528         // No graphics in ascii output. Possible to use gifscii to convert
529         // images to ascii approximation.
530         
531         // 1. Convert file to ascii using gifscii
532         // 2. Read ascii output file and add it to the output stream.
533         
534         return 0;
535 }
536
537
538 int InsetGraphics::Linuxdoc(Buffer const *, ostream &) const
539 {
540         // No graphics in LinuxDoc output. Should check how/what to add.
541         return 0;
542 }
543
544 // For explanation on inserting graphics into DocBook checkout:
545 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
546 // See also the docbook guide at http://www.docbook.org/
547 int InsetGraphics::DocBook(Buffer const * buf, ostream & os) const
548 {
549         // Change the path to be relative to the main file.
550         string const buffer_dir = OnlyPath(buf->fileName());
551         string const filename = RemoveExtension(MakeRelPath(params.filename, buffer_dir));
552
553         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will 
554         // need to switch to MediaObject. However, for now this is sufficient and 
555         // easier to use.
556         os << "<graphic fileref=\"" << filename << "\"></graphic>";
557         return 0;
558 }
559
560
561 void InsetGraphics::Validate(LaTeXFeatures & features) const
562 {
563         // If we have no image, we should not require anything.
564         if (params.filename.empty())
565                 return ;
566
567         features.graphicx = true;
568
569         if (params.subcaption)
570                 features.subfigure = true;
571 }
572
573 // Update the inset after parameters changed (read from file or changed in
574 // dialog.
575 void InsetGraphics::updateInset() const
576 {
577         GraphicsCache & gc = GraphicsCache::getInstance();
578         boost::shared_ptr<GraphicsCacheItem> temp(0);
579
580         // We do it this way so that in the face of some error, we will still
581         // be in a valid state.
582         if (!params.filename.empty()) {
583                 temp = gc.addFile(params.filename);
584         }
585
586         // Mark the image as unloaded so that it gets updated.
587         imageLoaded = false;
588
589         cacheHandle = temp;
590 }
591
592 bool InsetGraphics::setParams(InsetGraphicsParams const & params)
593 {
594         // If nothing is changed, just return and say so.
595         if (this->params == params)
596                 return false;
597
598         // Copy the new parameters.
599         this->params = params;
600
601         // Update the inset with the new parameters.
602         updateInset();
603
604         // We have changed data, report it.
605         return true;
606 }
607
608 InsetGraphicsParams InsetGraphics::getParams() const
609 {
610         return params;
611 }
612
613 Inset * InsetGraphics::Clone(Buffer const &) const
614 {
615         InsetGraphics * newInset = new InsetGraphics;
616
617         newInset->cacheHandle = cacheHandle;
618         newInset->imageLoaded = imageLoaded;
619
620         newInset->setParams(getParams());
621
622         return newInset;
623 }