]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsImageXPM.C
* Make the graphics files conform strictly to the Pimpl idiom by moving
[lyx.git] / src / graphics / GraphicsImageXPM.C
1 /*
2  * \file GraphicsImageXPM.C
3  * Copyright 2002 the LyX Team
4  * Read the file COPYING
5  *
6  * \author Baruch Even <baruch.even@writeme.com>
7  * \author Angus Leeming <leeming@lyx.org>
8  */
9
10 #include <config.h>
11
12 #ifdef __GNUG__
13 #pragma implementation
14 #endif
15
16 #include "GraphicsImageXPM.h"
17 #include "GraphicsParams.h"
18 #include "frontends/xforms/ColorHandler.h"
19 #include "debug.h"
20 #include "support/filetools.h"    // IsFileReadable
21 #include "support/lstrings.h"
22 #include "Lsstream.h"
23 #include <iomanip>                // std::setfill, etc
24 #include <cmath>                  // cos, sin
25 #include <cstdlib>                // malloc, free
26
27 #include <boost/tuple/tuple.hpp>
28
29 #include FORMS_H_LOCATION
30
31 #ifndef CXX_GLOBAL_CSTD
32 using std::cos;
33 using std::sin;
34 using std::malloc;
35 using std::strcpy;
36 using std::strlen;
37 #endif
38
39 namespace grfx {
40
41 /// Access to this class is through this static method.
42 Image::ImagePtr ImageXPM::newImage()
43 {
44         ImagePtr ptr;
45         ptr.reset(new ImageXPM);
46         return ptr;
47 }
48
49
50 /// Return the list of loadable formats.
51 Image::FormatList ImageXPM::loadableFormats()
52 {
53         FormatList formats(1);
54         formats[0] = "xpm";
55         return formats;
56 }
57
58
59 ImageXPM::ImageXPM()
60         : pixmap_(0),
61           pixmap_status_(PIXMAP_UNINITIALISED)
62 {}
63
64
65 ImageXPM::ImageXPM(ImageXPM const & other)
66         : Image(other),
67           image_(other.image_),
68           pixmap_(0),
69           pixmap_status_(PIXMAP_UNINITIALISED)
70 {}
71
72
73 ImageXPM::~ImageXPM()
74 {
75         if (pixmap_)
76                 XFreePixmap(fl_get_display(), pixmap_);
77 }
78
79
80 Image * ImageXPM::clone() const
81 {
82         return new ImageXPM(*this);
83 }
84
85
86 unsigned int ImageXPM::getWidth() const
87 {
88         return image_.width();
89 }
90
91
92 unsigned int ImageXPM::getHeight() const
93 {
94         return image_.height();
95 }
96
97
98 bool ImageXPM::isDrawable() const
99 {
100         return pixmap_;
101 }
102
103
104 Pixmap ImageXPM::getPixmap() const
105 {
106         if (!pixmap_status_ == PIXMAP_SUCCESS)
107                 return 0;
108         return pixmap_;
109 }
110
111
112 void ImageXPM::load(string const & filename)
113 {
114         if (filename.empty()) {
115                 finishedLoading(false);
116                 return;
117         }
118
119         if (!image_.empty()) {
120                 lyxerr[Debug::GRAPHICS]
121                         << "Image is loaded already!" << std::endl;
122                 finishedLoading(false);
123                 return;
124         }
125
126         XpmImage * xpm_image = new XpmImage;
127
128         int const success =
129                 XpmReadFileToXpmImage(const_cast<char *>(filename.c_str()),
130                                       xpm_image, 0);
131
132         switch (success) {
133         case XpmOpenFailed:
134                 lyxerr[Debug::GRAPHICS]
135                         << "No XPM image file found." << std::endl;
136                 break;
137
138         case XpmFileInvalid:
139                 lyxerr[Debug::GRAPHICS]
140                         << "File format is invalid" << std::endl;
141                 break;
142
143         case XpmNoMemory:
144                 lyxerr[Debug::GRAPHICS]
145                         << "Insufficient memory to read in XPM file"
146                         << std::endl;
147                 break;
148         }
149
150         if (success != XpmSuccess) {
151                 XpmFreeXpmImage(xpm_image);
152                 delete xpm_image;
153
154                 lyxerr[Debug::GRAPHICS]
155                         << "Error reading XPM file '"
156                         << XpmGetErrorString(success) << "'"
157                         << std::endl;
158         } else {
159                 image_.reset(*xpm_image);
160         }
161
162         finishedLoading(success == XpmSuccess);
163 }
164
165
166 bool ImageXPM::setPixmap(Params const & params)
167 {
168         if (image_.empty() || params.display == NoDisplay) {
169                 return false;
170         }
171
172         Display * display = fl_get_display();
173
174         if (pixmap_ && pixmap_status_ == PIXMAP_SUCCESS)
175                 XFreePixmap(display, pixmap_);
176
177         //(BE 2000-08-05)
178         // This might be a dirty thing, but I dont know any other solution.
179         Screen * screen = ScreenOfDisplay(display, fl_screen);
180
181         Pixmap pixmap;
182         Pixmap mask;
183
184         XpmAttributes attrib;
185
186         // Allow libXPM lots of leeway when trying to allocate colors.
187         attrib.closeness = 10000;
188         attrib.valuemask = XpmCloseness;
189
190         // The XPM file format allows multiple pixel colours to be defined
191         // as c_color, g_color or m_color.
192         switch (params.display) {
193         case MonochromeDisplay:
194                 attrib.color_key = XPM_MONO;
195                 break;
196         case GrayscaleDisplay:
197                 attrib.color_key = XPM_GRAY;
198                 break;
199         case ColorDisplay:
200         default: // NoDisplay cannot happen!
201                 attrib.color_key = XPM_COLOR;
202                 break;
203         }
204
205         attrib.valuemask |= XpmColorKey;
206
207         // Set the color "none" entry to the color of the background.
208         XpmColorSymbol xpm_col[2];
209         xpm_col[0].name = 0;
210         xpm_col[0].value = "none";
211         xpm_col[0].pixel = lyxColorHandler->colorPixel(LColor::graphicsbg);
212
213         // some image magick versions use this
214         xpm_col[1].name = 0;
215         xpm_col[1].value = "opaque";
216         xpm_col[1].pixel = lyxColorHandler->colorPixel(LColor::black);
217
218         attrib.numsymbols = 2;
219         attrib.colorsymbols = xpm_col;
220         attrib.valuemask |= XpmColorSymbols;
221
222         // Load up the pixmap
223         XpmImage xpm_image = image_.get();
224         int const status =
225                 XpmCreatePixmapFromXpmImage(display,
226                                             XRootWindowOfScreen(screen),
227                                             &xpm_image,
228                                             &pixmap, &mask, &attrib);
229
230         XpmFreeAttributes(&attrib);
231
232         if (status != XpmSuccess) {
233                 lyxerr << "Error creating pixmap from xpm_image '"
234                        << XpmGetErrorString(status) << "'"
235                        << std::endl;
236                 pixmap_status_ = PIXMAP_FAILED;
237                 return false;
238         }
239
240         pixmap_ = pixmap;
241         pixmap_status_ = PIXMAP_SUCCESS;
242         return true;
243 }
244
245
246 void ImageXPM::clip(Params const & params)
247 {
248         if (image_.empty())
249                 return;
250
251         if (params.bb.empty())
252                 // No clipping is necessary.
253                 return;
254
255         typedef unsigned int dimension;
256
257         dimension const new_width  = params.bb.xr - params.bb.xl;
258         dimension const new_height = params.bb.yt - params.bb.yb;
259
260         if (new_width > image_.width() || new_height > image_.height())
261                 // Bounds are invalid.
262                 return;
263
264         if (new_width == image_.width() && new_height == image_.height())
265                 // Bounds are unchanged.
266                 return;
267
268         dimension * new_data = image_.initialisedData(new_width, new_height);
269         dimension * it = new_data;
270
271         // The image is stored in memory from upper-left to lower-right,
272         // so we loop from yt to yb.
273         dimension const * old_data = image_.data();
274         dimension const * start_row = old_data +
275                 image_.width() * (image_.height() - params.bb.yt);
276
277         // the Bounding Box dimensions are never less than zero, so we can use
278         // "unsigned int row" here
279         for (dimension row = params.bb.yb; row < params.bb.yt; ++row) {
280                 dimension const * begin = start_row + params.bb.xl;
281                 dimension const * end   = start_row + params.bb.xr;
282                 it = std::copy(begin, end, it);
283                 start_row += image_.width();
284         }
285
286         image_.resetData(new_width, new_height, new_data);
287 }
288
289
290 void ImageXPM::rotate(Params const & params)
291 {
292         if (image_.empty())
293                 return ;
294
295         if (!params.angle)
296                 // No rotation is necessary.
297                 return;
298
299         // Ascertain the bounding box of the rotated image
300         // Rotate about the bottom-left corner
301         static double const pi = 3.14159265358979323846;
302         // The minus sign is needed to rotate in the same sense as xdvi et al.
303         double const angle = -double(params.angle) * pi / 180.0;
304         double const cos_a = cos(angle);
305         double const sin_a = sin(angle);
306
307         // (0, 0)
308         double max_x = 0; double min_x = 0;
309         double max_y = 0; double min_y = 0;
310
311         // (old_xpm->width, 0)
312         double x_rot = cos_a * image_.width();
313         double y_rot = sin_a * image_.width();
314         max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
315         max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
316
317         // (image_.width, image_.height)
318         x_rot = cos_a * image_.width() - sin_a * image_.height();
319         y_rot = sin_a * image_.width() + cos_a * image_.height();
320         max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
321         max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
322
323         // (0, image_.height)
324         x_rot = - sin_a * image_.height();
325         y_rot =   cos_a * image_.height();
326         max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
327         max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
328
329         typedef unsigned int dimension;
330
331         dimension const new_width  = 1 + int(max_x - min_x); // round up!
332         dimension const new_height = 1 + int(max_y - min_y);
333
334         dimension * new_data = image_.initialisedData(new_width, new_height);
335         dimension const * old_data = image_.data();
336
337         // rotate the data
338         for (dimension y_old = 0; y_old < image_.height(); ++y_old) {
339                 for (dimension x_old = 0; x_old < image_.width(); ++x_old) {
340                         double const x_pos = cos_a*x_old - sin_a*y_old - min_x;
341                         double const y_pos = sin_a*x_old + cos_a*y_old - min_y;
342
343                         // ensure that there are no rounding errors
344                         dimension x_new = (x_pos > 0) ? dimension(x_pos) : 0;
345                         dimension y_new = (y_pos > 0) ? dimension(y_pos) : 0;
346                         x_new = std::min(new_width  - 1, x_new);
347                         y_new = std::min(new_height - 1, y_new);
348
349                         size_t const id_old = x_old + image_.width() * y_old;
350                         size_t const id_new = x_new + new_width * y_new;
351
352                         new_data[id_new] = old_data[id_old];
353                 }
354         }
355
356         image_.resetData(new_width, new_height, new_data);
357 }
358
359
360 void ImageXPM::scale(Params const & params)
361 {
362         if (image_.empty())
363                 return;
364
365         typedef unsigned int dimension;
366
367         dimension new_width;
368         dimension new_height;
369         boost::tie(new_width, new_height) = getScaledDimensions(params);
370
371         if (new_width == getWidth() && new_height == getHeight())
372                 // No scaling needed
373                 return;
374
375         dimension * new_data = image_.initialisedData(new_width, new_height);
376         dimension const * old_data = image_.data();
377
378         double const x_scale = double(image_.width())  / double(new_width);
379         double const y_scale = double(image_.height()) / double(new_height);
380
381         // A very simple scaling routine.
382         // Ascertain the old pixel corresponding to the new one.
383         // There is no dithering at all here.
384         for (dimension x_new = 0; x_new < new_width; ++x_new) {
385                 dimension x_old = dimension(x_new * x_scale);
386
387                 for (dimension y_new = 0; y_new < new_height; ++y_new) {
388                         dimension y_old = dimension(y_new * y_scale);
389
390                         size_t const id_old = x_old + image_.width() * y_old;
391                         size_t const id_new = x_new + new_width * y_new;
392
393                         new_data[id_new] = old_data[id_old];
394                 }
395         }
396
397         image_.resetData(new_width, new_height, new_data);
398 }
399
400 } // namespace grfx
401
402
403 namespace {
404
405 void free_color_table(XpmColor * colorTable, size_t size);
406
407 void copy_color_table(XpmColor const * in, size_t size, XpmColor * out);
408
409 bool contains_color_none(XpmImage const & image);
410
411 string const unique_color_string(XpmImage const & image);
412
413 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
414 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
415 string const convertTo7chars(string const &);
416
417 // create a copy (using malloc and strcpy). If (!in) return 0;
418 char * clone_c_string(char const * in);
419
420 // Given a string of the form #ff0571 create appropriate grayscale and
421 // monochrome colors.
422 void mapcolor(char const * c_color, char ** g_color_ptr, char ** m_color_ptr);
423
424 } // namespace anon
425
426
427 namespace grfx {
428
429 ImageXPM::Data::Data()
430         : width_(0), height_(0), cpp_(0), ncolors_(0)
431 {}
432
433
434 ImageXPM::Data::~Data()
435 {
436         if (colorTable_.unique())
437                 free_color_table(colorTable_.get(), ncolors_);
438 }
439
440
441 void ImageXPM::Data::reset(XpmImage & image)
442 {
443         width_ = image.width;
444         height_ = image.height;
445         cpp_ = image.cpp;
446
447         // Move the data ptr into this store and free up image.data
448         data_.reset(image.data);
449         image.data = 0;
450
451         // Don't just store the color table, but check first that it contains
452         // all that we require of it.
453         // The idea is to store the color table in a shared_ptr and for all
454         // modified images to use the same table.
455         // It must, therefore, have a c_color "none" entry and g_color and
456         // m_color entries corresponding to each and every c_color entry
457         // (except "none"!)
458
459         // 1. Create a copy of the color table.
460         // Add a c_color "none" entry to the table if it isn't already there.
461         bool const add_color = !contains_color_none(image);
462
463         if (add_color) {
464
465                 ncolors_ = 1 + image.ncolors;
466                 size_t const mem_size = sizeof(XpmColor) * ncolors_;
467                 XpmColor * table = static_cast<XpmColor *>(malloc(mem_size));
468
469                 copy_color_table(image.colorTable, image.ncolors, table);
470
471                 XpmColor & color = table[ncolors_ - 1];
472                 color.symbolic = 0;
473                 color.m_color  = 0;
474                 color.g_color  = 0;
475                 color.g4_color = 0;
476                 color.string =
477                         clone_c_string(unique_color_string(image).c_str());
478                 color.c_color = clone_c_string("none");
479
480                 free_color_table(image.colorTable, image.ncolors);
481                 colorTable_.reset(table);
482
483         } else {
484
485                 // Just move the pointer across
486                 ncolors_ = image.ncolors;
487                 colorTable_.reset(image.colorTable);
488                 image.colorTable = 0;
489         }
490
491         // Clean-up the remaining entries of image.
492         image.width = 0;
493         image.height = 0;
494         image.cpp = 0;
495         image.ncolors = 0;
496
497         // 2. Ensure that the color table has g_color and m_color entries
498         XpmColor * table = colorTable_.get();
499
500         for (size_t i = 0; i < ncolors_; ++i) {
501                 XpmColor & entry = table[i];
502                 if (!entry.c_color)
503                         continue;
504
505                 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
506                 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
507                 string c_color = entry.c_color;
508                 if (c_color[0] == '#' && c_color.size() != 7) {
509                         c_color = convertTo7chars(c_color);
510                         free(entry.c_color);
511                         entry.c_color = clone_c_string(c_color.c_str());
512                 }
513
514                 // If the c_color is defined and the equivalent
515                 // grayscale or monochrome ones are not, then define them.
516                 mapcolor(entry.c_color, &entry.g_color, &entry.m_color);
517         }
518 }
519
520
521 XpmImage ImageXPM::Data::get() const
522 {
523         XpmImage image;
524         image.width = width_;
525         image.height = height_;
526         image.cpp = cpp_;
527         image.ncolors = ncolors_;
528         image.data = data_.get();
529         image.colorTable = colorTable_.get();
530         return image;
531 }
532
533
534 void ImageXPM::Data::resetData(int w, int h, unsigned int * d)
535 {
536         width_  = w;
537         height_ = h;
538         data_.reset(d);
539 }
540
541
542 unsigned int * ImageXPM::Data::initialisedData(int w, int h) const
543 {
544         size_t const data_size = w * h;
545
546         size_t const mem_size  = sizeof(unsigned int) * data_size;
547         unsigned int * ptr = static_cast<unsigned int *>(malloc(mem_size));
548
549         unsigned int none_id = color_none_id();
550         std::fill(ptr, ptr + data_size, none_id);
551
552         return ptr;
553 }
554
555
556 unsigned int ImageXPM::Data::color_none_id() const
557 {
558         XpmColor * table = colorTable_.get();
559         for (size_t i = 0; i < ncolors_; ++i) {
560                 char const * const color = table[i].c_color;
561                 if (color && ascii_lowercase(color) == "none")
562                         return uint(i);
563         }
564         return 0;
565 }
566
567 } // namespace grfx
568
569 namespace {
570
571 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
572 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
573 string const convertTo7chars(string const & input)
574 {
575         string::size_type size = input.size();
576         if (size != 13 && size != 10 && size != 9 && size != 4)
577                 // Can't deal with it.
578                 return input;
579
580         if (input[0] != '#')
581                 // Can't deal with it.
582                 return input;
583
584         string format(input);
585
586         switch (size) {
587         case 13: // #rrrrggggbbbb
588                 format.erase(3, 2);
589                 format.erase(5, 2);
590                 format.erase(7, 2);
591                 break;
592         case 10: // #rrrgggbbb
593                 format.erase(3, 1);
594                 format.erase(5, 1);
595                 format.erase(7, 1);
596                 break;
597         case 9: //
598                 format.erase(7);
599                 break;
600         case 4: // #rgb
601                 format.insert(2, 1, '0');
602                 format.insert(4, 1, '0');
603                 format.append(1, '0');
604                 break;
605         }
606
607         return format;
608 }
609
610
611 // Given a string of the form #ff0571 create appropriate grayscale and
612 // monochrome colors.
613 void mapcolor(char const * c_color, char ** g_color_ptr, char ** m_color_ptr)
614 {
615         if (!c_color)
616                 return;
617
618         char * g_color = *g_color_ptr;
619         char * m_color = *m_color_ptr;
620
621         if (g_color && m_color)
622                 // Already filled.
623                 return;
624
625         Display * display = fl_get_display();
626         Colormap cmap     = fl_state[fl_get_vclass()].colormap;
627         XColor xcol;
628         XColor ccol;
629         if (XLookupColor(display, cmap, c_color, &xcol, &ccol) == 0)
630                 // Unable to parse c_color.
631                 return;
632
633         // Note that X stores the RGB values in the range 0 - 65535
634         // whilst we require them in the range 0 - 255.
635         int const r = xcol.red   / 256;
636         int const g = xcol.green / 256;
637         int const b = xcol.blue  / 256;
638
639         // This gives a good match to a human's RGB to luminance conversion.
640         // (From xv's Postscript code --- Mike Ressler.)
641         int const gray = int((0.32 * r) + (0.5 * g) + (0.18 * b));
642
643         ostringstream gray_stream;
644         gray_stream << "#" << std::setbase(16) << std::setfill('0')
645                     << std::setw(2) << gray
646                     << std::setw(2) << gray
647                     << std::setw(2) << gray;
648
649         int const mono = (gray < 128) ? 0 : 255;
650         ostringstream mono_stream;
651         mono_stream << "#" << std::setbase(16) << std::setfill('0')
652                     << std::setw(2) << mono
653                     << std::setw(2) << mono
654                     << std::setw(2) << mono;
655
656         // This string is going into an XpmImage struct, so create copies that
657         // libXPM can free successfully.
658         if (!g_color)
659                 *g_color_ptr = clone_c_string(gray_stream.str().c_str());
660         if (!m_color)
661                 *m_color_ptr = clone_c_string(mono_stream.str().c_str());
662 }
663
664
665 void copy_color_table(XpmColor const * in, size_t size, XpmColor * out)
666 {
667         for (size_t i = 0; i < size; ++i) {
668                 out[i].string   = clone_c_string(in[i].string);
669                 out[i].symbolic = clone_c_string(in[i].symbolic);
670                 out[i].m_color  = clone_c_string(in[i].m_color);
671                 out[i].g_color  = clone_c_string(in[i].g_color);
672                 out[i].g4_color = clone_c_string(in[i].g4_color);
673                 out[i].c_color  = clone_c_string(in[i].c_color);
674         }
675 }
676
677
678 void free_color_table(XpmColor * table, size_t size)
679 {
680         for (size_t i = 0; i < size; ++i) {
681                 free(table[i].string);
682                 free(table[i].symbolic);
683                 free(table[i].m_color);
684                 free(table[i].g_color);
685                 free(table[i].g4_color);
686                 free(table[i].c_color);
687         }
688         // Don't free the table itself. Let the shared_c_ptr do that.
689         // free(table);
690 }
691
692
693 char * clone_c_string(char const * in)
694 {
695         if (!in)
696                 return 0;
697
698         // Don't forget the '\0'
699         char * out = static_cast<char *>(malloc(strlen(in) + 1));
700         return strcpy(out, in);
701 }
702
703
704 bool contains_color_none(XpmImage const & image)
705 {
706         for (size_t i = 0; i < image.ncolors; ++i) {
707                 char const * const color = image.colorTable[i].c_color;
708                 if (color && ascii_lowercase(color) == "none")
709                         return true;
710         }
711         return false;
712 }
713
714
715 string const unique_color_string(XpmImage const & image)
716 {
717         string id(image.cpp, ' ');
718
719         for(;;) {
720                 bool found_it = false;
721                 for (size_t i = 0; i < image.ncolors; ++i) {
722                         string const c_id = image.colorTable[i].string;
723                         if (c_id == id) {
724                                 found_it = true;
725                                 break;
726                         }
727                 }
728
729                 if (!found_it)
730                         return id;
731
732                 // Loop over the printable characters in the ASCII table.
733                 // Ie, count from char 32 (' ') to char 126 ('~')
734                 // A base 94 counter!
735                 string::size_type current_index = id.size() - 1;
736                 bool continue_loop = true;
737                 while(continue_loop) {
738                         continue_loop = false;
739
740                         if (id[current_index] == 126) {
741                                 continue_loop = true;
742                                 if (current_index == 0)
743                                         // Unable to find a unique string
744                                         return image.colorTable[0].string;
745
746                                 id[current_index] = 32;
747                                 current_index -= 1;
748                         } else {
749                                 id[current_index] += 1;
750                                 // Note that '"' is an illegal char in this
751                                 // context
752                                 if (id[current_index] == '"')
753                                         id[current_index] += 1;
754                         }
755                 }
756                 if (continue_loop)
757                         // Unable to find a unique string
758                         return string();
759         }
760 }
761
762 } // namespace anon