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