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