]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsImageXPM.C
Some more fixes to compiler warnings.
[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
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_(other.pixmap_),
58           pixmap_status_(other.pixmap_status_)
59 {}
60
61
62 GImageXPM::~GImageXPM()
63 {
64         if (pixmap_ && pixmap_status_ == PIXMAP_SUCCESS)
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;
192         xpm_col.name = 0;
193         xpm_col.value = "none";
194         xpm_col.pixel = lyxColorHandler->colorPixel(LColor::graphicsbg);
195
196         attrib.numsymbols = 1;
197         attrib.colorsymbols = &xpm_col;
198         attrib.valuemask |= XpmColorSymbols;
199
200         // Load up the pixmap
201         XpmImage xpm_image = image_.get();
202         int const status =
203                 XpmCreatePixmapFromXpmImage(display, 
204                                             XRootWindowOfScreen(screen), 
205                                             &xpm_image, 
206                                             &pixmap, &mask, &attrib);
207
208         XpmFreeAttributes(&attrib);
209
210         if (status != XpmSuccess) {
211                 lyxerr << "Error creating pixmap from xpm_image '" 
212                        << XpmGetErrorString(status) << "'"
213                        << std::endl;
214                 pixmap_status_ = PIXMAP_FAILED;
215                 return false;
216         }
217
218         pixmap_ = pixmap;
219         pixmap_status_ = PIXMAP_SUCCESS;
220         return true;
221 }
222
223
224 void GImageXPM::clip(GParams const & params)
225 {
226         if (image_.empty())
227                 return;
228
229         if (params.bb.empty())
230                 // No clipping is necessary.
231                 return;
232
233         typedef unsigned int dimension;
234
235         dimension const new_width  = params.bb.xr - params.bb.xl;
236         dimension const new_height = params.bb.yt - params.bb.yb;
237
238         if (new_width > image_.width() || new_height > image_.height())
239                 // Bounds are invalid.
240                 return;
241
242         if (new_width == image_.width() && new_height == image_.height())
243                 // Bounds are unchanged.
244                 return;
245
246         dimension * new_data = image_.initialisedData(new_width, new_height);
247         dimension const * old_data = image_.data();
248
249         dimension * it = new_data;
250         dimension const * start_row = old_data;
251         for (size_t row = params.bb.yb; row < params.bb.yt; ++row) {
252                 dimension const * begin = start_row + params.bb.xl;
253                 dimension const * end   = start_row + params.bb.xr;
254                 it = std::copy(begin, end, it);
255                 start_row += image_.width();
256         }
257
258         image_.resetData(new_width, new_height, new_data);
259 }
260
261
262 void GImageXPM::rotate(GParams const & params)
263 {
264         if (image_.empty())
265                 return ;
266
267         if (!params.angle)
268                 // No rotation is necessary.
269                 return;
270
271         // Ascertain the bounding box of the rotated image
272         // Rotate about the bottom-left corner
273         static double const pi = 3.14159265358979323846;
274         double const angle = double(params.angle) * pi / 180.0;
275         double const cos_a = cos(angle);
276         double const sin_a = sin(angle);
277
278         // (0, 0)
279         double max_x = 0; double min_x = 0;
280         double max_y = 0; double min_y = 0;
281
282         // (old_xpm->width, 0)
283         double x_rot = cos_a * image_.width();
284         double y_rot = sin_a * image_.width();
285         max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
286         max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
287
288         // (image_.width, image_.height)
289         x_rot = cos_a * image_.width() - sin_a * image_.height();
290         y_rot = sin_a * image_.width() + cos_a * image_.height();
291         max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
292         max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
293
294         // (0, image_.height)
295         x_rot = - sin_a * image_.height();
296         y_rot =   cos_a * image_.height();
297         max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
298         max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
299
300         typedef unsigned int dimension;
301         
302         dimension const new_width  = 1 + int(max_x - min_x); // round up!
303         dimension const new_height = 1 + int(max_y - min_y);
304
305         dimension * new_data = image_.initialisedData(new_width, new_height);
306         dimension const * old_data = image_.data();
307
308         // rotate the data
309         for (dimension y_old = 0; y_old < image_.height(); ++y_old) {
310                 for (dimension x_old = 0; x_old < image_.width(); ++x_old) {
311                         double const x_pos = cos_a*x_old - sin_a*y_old - min_x;
312                         double const y_pos = sin_a*x_old + cos_a*y_old - min_y;
313
314                         // ensure that there are no rounding errors
315                         dimension x_new = (x_pos > 0) ? dimension(x_pos) : 0;
316                         dimension y_new = (y_pos > 0) ? dimension(y_pos) : 0;
317                         x_new = std::min(new_width  - 1, x_new);
318                         y_new = std::min(new_height - 1, y_new);
319
320                         size_t const id_old = x_old + image_.width() * y_old;
321                         size_t const id_new = x_new + new_width * y_new;
322
323                         new_data[id_new] = old_data[id_old];
324                 }
325         }
326
327         image_.resetData(new_width, new_height, new_data);
328 }
329
330
331 void GImageXPM::scale(GParams const & params)
332 {
333         if (image_.empty())
334                 return;
335
336         typedef unsigned int dimension;
337
338         // boost::tie produces horrible compilation errors on my machine
339         // Angus 25 Feb 2002
340         std::pair<dimension, dimension> d = getScaledDimensions(params);
341         dimension const new_width  = d.first;
342         dimension const new_height = d.second;
343         if (new_width == getWidth() && new_height == getHeight())
344                 // No scaling needed
345                 return;
346
347         dimension * new_data = image_.initialisedData(new_width, new_height);
348         dimension const * old_data = image_.data();
349
350         double const x_scale = double(image_.width())  / double(new_width);
351         double const y_scale = double(image_.height()) / double(new_height);
352
353         // A very simple scaling routine.
354         // Ascertain the old pixel corresponding to the new one.
355         // There is no dithering at all here.
356         for (dimension x_new = 0; x_new < new_width; ++x_new) {
357                 dimension x_old = dimension(x_new * x_scale);
358
359                 for (dimension y_new = 0; y_new < new_height; ++y_new) {
360                         dimension y_old = dimension(y_new * y_scale);
361
362                         size_t const id_old = x_old + image_.width() * y_old;
363                         size_t const id_new = x_new + new_width * y_new;
364
365                         new_data[id_new] = old_data[id_old];
366                 }
367         }
368
369         image_.resetData(new_width, new_height, new_data);
370 }
371
372 } // namespace grfx
373
374
375 namespace {
376
377 void free_color_table(XpmColor * colorTable, size_t size);
378
379 void copy_color_table(XpmColor const * in, size_t size, XpmColor * out);
380
381 bool contains_color_none(XpmImage const & image);
382
383 string const unique_color_string(XpmImage const & image);
384
385 // create a copy (using malloc and strcpy). If (!in) return 0; 
386 char * clone_c_string(char const * in);
387
388 // Given a string of the form #ff0571 create appropriate grayscale and
389 // monochrome colors.
390 void mapcolor(char const * c_color, char ** g_color_ptr, char ** m_color_ptr);
391
392 } // namespace anon
393
394
395 namespace grfx {
396
397 GImageXPM::Data::Data()
398         : width_(0), height_(0), cpp_(0), ncolors_(0)
399 {}
400
401
402 GImageXPM::Data::~Data()
403 {
404         if (colorTable_.unique())
405                 free_color_table(colorTable_.get(), ncolors_);
406 }
407
408
409 void GImageXPM::Data::reset(XpmImage & image)
410 {
411         width_ = image.width;
412         height_ = image.height;
413         cpp_ = image.cpp;
414
415         // Move the data ptr into this store and free up image.data
416         data_.reset(image.data);
417         image.data = 0;
418
419         // Don't just store the color table, but check first that it contains
420         // all that we require of it.
421         // The idea is to store the color table in a shared_ptr and for all
422         // modified images to use the same table.
423         // It must, therefore, have a c_color "none" entry and g_color and
424         // m_color entries corresponding to each and every c_color entry
425         // (except "none"!)
426
427         // 1. Create a copy of the color table.
428         // Add a c_color "none" entry to the table if it isn't already there.
429         bool const add_color = !contains_color_none(image);
430
431         if (add_color) {
432
433                 ncolors_ = 1 + image.ncolors;
434                 size_t const mem_size = sizeof(XpmColor) * ncolors_;
435                 XpmColor * table = static_cast<XpmColor *>(malloc(mem_size));
436
437                 copy_color_table(image.colorTable, image.ncolors, table);
438
439                 XpmColor & color = table[ncolors_ - 1];
440                 color.symbolic = 0;
441                 color.m_color  = 0;
442                 color.g_color  = 0;
443                 color.g4_color = 0;
444                 color.string =
445                         clone_c_string(unique_color_string(image).c_str());
446                 color.c_color = clone_c_string("none");
447
448                 free_color_table(image.colorTable, image.ncolors);
449                 colorTable_.reset(table);
450
451         } else {
452
453                 // Just move the pointer across
454                 ncolors_ = image.ncolors;
455                 colorTable_.reset(image.colorTable);
456                 image.colorTable = 0;
457         }
458
459         // Clean-up the remaining entries of image.
460         image.width = 0;
461         image.height = 0;
462         image.cpp = 0;
463         image.ncolors = 0;
464
465         // 2. Ensure that the color table has g_color and m_color entries
466         XpmColor * table = colorTable_.get();
467         string buggy_color;
468
469         for (size_t i = 0; i < ncolors_; ++i) {
470                 XpmColor & entry = table[i];
471                 if (!entry.c_color)
472                         continue;
473
474                 // A work-around for buggy XPM files that may be created by
475                 // ImageMagick's convert.
476                 string c_color = entry.c_color;
477                 if (c_color[0] == '#' && c_color.size() > 7) {
478                         if (buggy_color.empty())
479                                 buggy_color = c_color;
480
481                         c_color = c_color.substr(0, 7);
482                         free(entry.c_color);
483                         entry.c_color = clone_c_string(c_color.c_str());
484                 }
485
486                 // If the c_color is defined and the equivalent
487                 // grayscale or monochrome ones are not, then define them.
488                 mapcolor(entry.c_color, &entry.g_color, &entry.m_color);
489         }
490
491         if (!buggy_color.empty()) {
492                 lyxerr << "The XPM file contains silly colors, "
493                        << "an example being \""
494                        << buggy_color << "\".\n"
495                        << "This was cropped to \""
496                        << buggy_color.substr(0, 7)
497                        << "\" so you can see something!\n"
498                        << "If this file was created by ImageMagick's convert,\n"
499                        << "then upgrading may cure the problem."
500                        << std::endl;
501         }
502 }
503
504
505 XpmImage GImageXPM::Data::get() const
506 {
507         XpmImage image;
508         image.width = width_;
509         image.height = height_;
510         image.cpp = cpp_;
511         image.ncolors = ncolors_;
512         image.data = data_.get();
513         image.colorTable = colorTable_.get();
514         return image;
515 }
516
517
518 void GImageXPM::Data::resetData(int w, int h, unsigned int * d)
519 {
520         width_  = w;
521         height_ = h;
522         data_.reset(d);
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 // Given a string of the form #ff0571 create appropriate grayscale and
555 // monochrome colors.
556 void mapcolor(char const * c_color, char ** g_color_ptr, char ** m_color_ptr)
557 {
558         if (!c_color)
559                 return;
560
561         char * g_color = *g_color_ptr;
562         char * m_color = *m_color_ptr;
563
564         if (g_color && m_color)
565                 // Already filled.
566                 return;
567
568         Display * display = GUIRunTime::x11Display();
569         Colormap cmap     = GUIRunTime::x11Colormap();
570         XColor xcol;
571         XColor ccol;
572         if (XLookupColor(display, cmap, c_color, &xcol, &ccol) == 0)
573                 // Unable to parse c_color.
574                 return;
575
576         // Note that X stores the RGB values in the range 0 - 65535
577         // whilst we require them in the range 0 - 255.
578         int const r = xcol.red   / 256;
579         int const g = xcol.green / 256;
580         int const b = xcol.blue  / 256;
581
582         // This gives a good match to a human's RGB to luminance conversion.
583         // (From xv's Postscript code --- Mike Ressler.)
584         int const gray = int((0.32 * r) + (0.5 * g) + (0.18 * b));
585
586         ostringstream gray_stream;
587         gray_stream << "#" << std::setbase(16) << std::setfill('0')
588                     << std::setw(2) << gray
589                     << std::setw(2) << gray
590                     << std::setw(2) << gray;
591
592         int const mono = (gray < 128) ? 0 : 255;
593         ostringstream mono_stream;
594         mono_stream << "#" << std::setbase(16) << std::setfill('0')
595                     << std::setw(2) << mono
596                     << std::setw(2) << mono
597                     << std::setw(2) << mono;
598
599         // This string is going into an XpmImage struct, so create copies that
600         // libXPM can free successfully.
601         if (!g_color)
602                 *g_color_ptr = clone_c_string(gray_stream.str().c_str());
603         if (!m_color)
604                 *m_color_ptr = clone_c_string(mono_stream.str().c_str());
605 }
606
607
608 void copy_color_table(XpmColor const * in, size_t size, XpmColor * out)
609 {
610         for (size_t i = 0; i < size; ++i) {
611                 out[i].string   = clone_c_string(in[i].string);
612                 out[i].symbolic = clone_c_string(in[i].symbolic);
613                 out[i].m_color  = clone_c_string(in[i].m_color);
614                 out[i].g_color  = clone_c_string(in[i].g_color);
615                 out[i].g4_color = clone_c_string(in[i].g4_color);
616                 out[i].c_color  = clone_c_string(in[i].c_color);
617         }
618 }
619
620
621 void free_color_table(XpmColor * table, size_t size)
622 {
623         for (size_t i = 0; i < size; ++i) {
624                 free(table[i].string);
625                 free(table[i].symbolic);
626                 free(table[i].m_color);
627                 free(table[i].g_color);
628                 free(table[i].g4_color);
629                 free(table[i].c_color);
630         }
631         // Don't free the table itself. Let the shared_c_ptr do that.
632         // free(table);
633 }
634
635
636 char * clone_c_string(char const * in)
637 {
638         if (!in)
639                 return 0;
640
641         // Don't forget the '\0'
642         char * out = static_cast<char *>(malloc(strlen(in) + 1));
643         return strcpy(out, in);
644 }
645
646
647 bool contains_color_none(XpmImage const & image)
648 {
649         for (size_t i = 0; i < image.ncolors; ++i) {
650                 char const * const color = image.colorTable[i].c_color;
651                 if (color && lowercase(color) == "none")
652                         return true;
653         }
654         return false;
655 }
656
657
658 string const unique_color_string(XpmImage const & image)
659 {
660         string id(image.cpp, ' ');
661
662         for(;;) {
663                 bool found_it = false;
664                 for (size_t i = 0; i < image.ncolors; ++i) {
665                         string const c_id = image.colorTable[i].string;
666                         if (c_id == id) {
667                                 found_it = true;
668                                 break;
669                         }
670                 }
671
672                 if (!found_it)
673                         return id;
674
675                 // Loop over the printable characters in the ASCII table.
676                 // Ie, count from char 32 (' ') to char 126 ('~')
677                 // A base 94 counter!
678                 string::size_type current_index = id.size() - 1;
679                 bool continue_loop = true;
680                 while(continue_loop) {
681                         continue_loop = false;
682
683                         if (id[current_index] == 126) {
684                                 continue_loop = true;
685                                 if (current_index == 0)
686                                         // Unable to find a unique string
687                                         return image.colorTable[0].string;
688
689                                 id[current_index] = 32;
690                                 current_index -= 1;
691                         } else {
692                                 id[current_index] += 1;
693                                 // Note that '"' is an illegal char in this
694                                 // context
695                                 if (id[current_index] == '"')
696                                         id[current_index] += 1;
697                         }
698                 }
699                 if (continue_loop)
700                         // Unable to find a unique string
701                         return string();
702         }
703 }
704
705 } // namespace anon