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