]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsImageXPM.C
just massage the input format
[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;
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 * it = new_data;
248
249         // The image is stored in memory from upper-left to lower-right,
250         // so we loop from yt to yb.
251         dimension const * old_data = image_.data();
252         dimension const * start_row = old_data +
253                 image_.width() * (image_.height() - params.bb.yt);
254
255         // the Bounding Box dimensions are never less than zero, so we can use
256         // "unsigned int row" here
257         for (dimension row = params.bb.yb; row < params.bb.yt; ++row) {
258                 dimension const * begin = start_row + params.bb.xl;
259                 dimension const * end   = start_row + params.bb.xr;
260                 it = std::copy(begin, end, it);
261                 start_row += image_.width();
262         }
263
264         image_.resetData(new_width, new_height, new_data);
265 }
266
267
268 void GImageXPM::rotate(GParams const & params)
269 {
270         if (image_.empty())
271                 return ;
272
273         if (!params.angle)
274                 // No rotation is necessary.
275                 return;
276
277         // Ascertain the bounding box of the rotated image
278         // Rotate about the bottom-left corner
279         static double const pi = 3.14159265358979323846;
280         double const angle = double(params.angle) * pi / 180.0;
281         double const cos_a = cos(angle);
282         double const sin_a = sin(angle);
283
284         // (0, 0)
285         double max_x = 0; double min_x = 0;
286         double max_y = 0; double min_y = 0;
287
288         // (old_xpm->width, 0)
289         double x_rot = cos_a * image_.width();
290         double y_rot = sin_a * image_.width();
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         // (image_.width, image_.height)
295         x_rot = cos_a * image_.width() - sin_a * image_.height();
296         y_rot = sin_a * image_.width() + 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         // (0, image_.height)
301         x_rot = - sin_a * image_.height();
302         y_rot =   cos_a * image_.height();
303         max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
304         max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
305
306         typedef unsigned int dimension;
307
308         dimension const new_width  = 1 + int(max_x - min_x); // round up!
309         dimension const new_height = 1 + int(max_y - min_y);
310
311         dimension * new_data = image_.initialisedData(new_width, new_height);
312         dimension const * old_data = image_.data();
313
314         // rotate the data
315         for (dimension y_old = 0; y_old < image_.height(); ++y_old) {
316                 for (dimension x_old = 0; x_old < image_.width(); ++x_old) {
317                         double const x_pos = cos_a*x_old - sin_a*y_old - min_x;
318                         double const y_pos = sin_a*x_old + cos_a*y_old - min_y;
319
320                         // ensure that there are no rounding errors
321                         dimension x_new = (x_pos > 0) ? dimension(x_pos) : 0;
322                         dimension y_new = (y_pos > 0) ? dimension(y_pos) : 0;
323                         x_new = std::min(new_width  - 1, x_new);
324                         y_new = std::min(new_height - 1, y_new);
325
326                         size_t const id_old = x_old + image_.width() * y_old;
327                         size_t const id_new = x_new + new_width * y_new;
328
329                         new_data[id_new] = old_data[id_old];
330                 }
331         }
332
333         image_.resetData(new_width, new_height, new_data);
334 }
335
336
337 void GImageXPM::scale(GParams const & params)
338 {
339         if (image_.empty())
340                 return;
341
342         typedef unsigned int dimension;
343
344         // boost::tie produces horrible compilation errors on my machine
345         // Angus 25 Feb 2002
346         std::pair<dimension, dimension> d = getScaledDimensions(params);
347         dimension const new_width  = d.first;
348         dimension const new_height = d.second;
349         if (new_width == getWidth() && new_height == getHeight())
350                 // No scaling needed
351                 return;
352
353         dimension * new_data = image_.initialisedData(new_width, new_height);
354         dimension const * old_data = image_.data();
355
356         double const x_scale = double(image_.width())  / double(new_width);
357         double const y_scale = double(image_.height()) / double(new_height);
358
359         // A very simple scaling routine.
360         // Ascertain the old pixel corresponding to the new one.
361         // There is no dithering at all here.
362         for (dimension x_new = 0; x_new < new_width; ++x_new) {
363                 dimension x_old = dimension(x_new * x_scale);
364
365                 for (dimension y_new = 0; y_new < new_height; ++y_new) {
366                         dimension y_old = dimension(y_new * y_scale);
367
368                         size_t const id_old = x_old + image_.width() * y_old;
369                         size_t const id_new = x_new + new_width * y_new;
370
371                         new_data[id_new] = old_data[id_old];
372                 }
373         }
374
375         image_.resetData(new_width, new_height, new_data);
376 }
377
378 } // namespace grfx
379
380
381 namespace {
382
383 void free_color_table(XpmColor * colorTable, size_t size);
384
385 void copy_color_table(XpmColor const * in, size_t size, XpmColor * out);
386
387 bool contains_color_none(XpmImage const & image);
388
389 string const unique_color_string(XpmImage const & image);
390
391 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
392 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
393 string const convertTo7chars(string const &);
394
395 // create a copy (using malloc and strcpy). If (!in) return 0;
396 char * clone_c_string(char const * in);
397
398 // Given a string of the form #ff0571 create appropriate grayscale and
399 // monochrome colors.
400 void mapcolor(char const * c_color, char ** g_color_ptr, char ** m_color_ptr);
401
402 } // namespace anon
403
404
405 namespace grfx {
406
407 GImageXPM::Data::Data()
408         : width_(0), height_(0), cpp_(0), ncolors_(0)
409 {}
410
411
412 GImageXPM::Data::~Data()
413 {
414         if (colorTable_.unique())
415                 free_color_table(colorTable_.get(), ncolors_);
416 }
417
418
419 void GImageXPM::Data::reset(XpmImage & image)
420 {
421         width_ = image.width;
422         height_ = image.height;
423         cpp_ = image.cpp;
424
425         // Move the data ptr into this store and free up image.data
426         data_.reset(image.data);
427         image.data = 0;
428
429         // Don't just store the color table, but check first that it contains
430         // all that we require of it.
431         // The idea is to store the color table in a shared_ptr and for all
432         // modified images to use the same table.
433         // It must, therefore, have a c_color "none" entry and g_color and
434         // m_color entries corresponding to each and every c_color entry
435         // (except "none"!)
436
437         // 1. Create a copy of the color table.
438         // Add a c_color "none" entry to the table if it isn't already there.
439         bool const add_color = !contains_color_none(image);
440
441         if (add_color) {
442
443                 ncolors_ = 1 + image.ncolors;
444                 size_t const mem_size = sizeof(XpmColor) * ncolors_;
445                 XpmColor * table = static_cast<XpmColor *>(malloc(mem_size));
446
447                 copy_color_table(image.colorTable, image.ncolors, table);
448
449                 XpmColor & color = table[ncolors_ - 1];
450                 color.symbolic = 0;
451                 color.m_color  = 0;
452                 color.g_color  = 0;
453                 color.g4_color = 0;
454                 color.string =
455                         clone_c_string(unique_color_string(image).c_str());
456                 color.c_color = clone_c_string("none");
457
458                 free_color_table(image.colorTable, image.ncolors);
459                 colorTable_.reset(table);
460
461         } else {
462
463                 // Just move the pointer across
464                 ncolors_ = image.ncolors;
465                 colorTable_.reset(image.colorTable);
466                 image.colorTable = 0;
467         }
468
469         // Clean-up the remaining entries of image.
470         image.width = 0;
471         image.height = 0;
472         image.cpp = 0;
473         image.ncolors = 0;
474
475         // 2. Ensure that the color table has g_color and m_color entries
476         XpmColor * table = colorTable_.get();
477
478         for (size_t i = 0; i < ncolors_; ++i) {
479                 XpmColor & entry = table[i];
480                 if (!entry.c_color)
481                         continue;
482
483                 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
484                 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
485                 string c_color = entry.c_color;
486                 if (c_color[0] == '#' && c_color.size() != 7) {
487                         c_color = convertTo7chars(c_color);
488                         free(entry.c_color);
489                         entry.c_color = clone_c_string(c_color.c_str());
490                 }
491
492                 // If the c_color is defined and the equivalent
493                 // grayscale or monochrome ones are not, then define them.
494                 mapcolor(entry.c_color, &entry.g_color, &entry.m_color);
495         }
496 }
497
498
499 XpmImage GImageXPM::Data::get() const
500 {
501         XpmImage image;
502         image.width = width_;
503         image.height = height_;
504         image.cpp = cpp_;
505         image.ncolors = ncolors_;
506         image.data = data_.get();
507         image.colorTable = colorTable_.get();
508         return image;
509 }
510
511
512 void GImageXPM::Data::resetData(int w, int h, unsigned int * d)
513 {
514         width_  = w;
515         height_ = h;
516         data_.reset(d);
517 }
518
519
520 unsigned int * GImageXPM::Data::initialisedData(int w, int h) const
521 {
522         size_t const data_size = w * h;
523
524         size_t const mem_size  = sizeof(unsigned int) * data_size;
525         unsigned int * ptr = static_cast<unsigned int *>(malloc(mem_size));
526
527         unsigned int none_id = color_none_id();
528         std::fill(ptr, ptr + data_size, none_id);
529
530         return ptr;
531 }
532
533
534 unsigned int GImageXPM::Data::color_none_id() const
535 {
536         XpmColor * table = colorTable_.get();
537         for (size_t i = 0; i < ncolors_; ++i) {
538                 char const * const color = table[i].c_color;
539                 if (color && lowercase(color) == "none")
540                         return uint(i);
541         }
542         return 0;
543 }
544
545 } // namespace grfx
546
547 namespace {
548
549 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
550 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
551 string const convertTo7chars(string const & input)
552 {
553         string::size_type size = input.size();
554         if (size != 13 && size != 10 && size != 4)
555                 // Can't deal with it.
556                 return input;
557
558         if (input[0] != '#')
559                 // Can't deal with it.
560                 return input;
561
562         string format(input);
563
564         switch (size) {
565         case 13: // #rrrrggggbbbb
566                 format.erase(3, 2);
567                 format.erase(5, 2);
568                 format.erase(7, 2);
569                 break;
570         case 10: // #rrrgggbbb
571                 format.erase(3, 1);
572                 format.erase(5, 1);
573                 format.erase(7, 1);
574                 break;
575         case 4: // #rgb
576                 format.insert(2, 1, '0');
577                 format.insert(4, 1, '0');
578                 format.append(1, '0');
579                 break;
580         }
581
582         return format;
583 }
584
585
586 // Given a string of the form #ff0571 create appropriate grayscale and
587 // monochrome colors.
588 void mapcolor(char const * c_color, char ** g_color_ptr, char ** m_color_ptr)
589 {
590         if (!c_color)
591                 return;
592
593         char * g_color = *g_color_ptr;
594         char * m_color = *m_color_ptr;
595
596         if (g_color && m_color)
597                 // Already filled.
598                 return;
599
600         Display * display = GUIRunTime::x11Display();
601         Colormap cmap     = GUIRunTime::x11Colormap();
602         XColor xcol;
603         XColor ccol;
604         if (XLookupColor(display, cmap, c_color, &xcol, &ccol) == 0)
605                 // Unable to parse c_color.
606                 return;
607
608         // Note that X stores the RGB values in the range 0 - 65535
609         // whilst we require them in the range 0 - 255.
610         int const r = xcol.red   / 256;
611         int const g = xcol.green / 256;
612         int const b = xcol.blue  / 256;
613
614         // This gives a good match to a human's RGB to luminance conversion.
615         // (From xv's Postscript code --- Mike Ressler.)
616         int const gray = int((0.32 * r) + (0.5 * g) + (0.18 * b));
617
618         ostringstream gray_stream;
619         gray_stream << "#" << std::setbase(16) << std::setfill('0')
620                     << std::setw(2) << gray
621                     << std::setw(2) << gray
622                     << std::setw(2) << gray;
623
624         int const mono = (gray < 128) ? 0 : 255;
625         ostringstream mono_stream;
626         mono_stream << "#" << std::setbase(16) << std::setfill('0')
627                     << std::setw(2) << mono
628                     << std::setw(2) << mono
629                     << std::setw(2) << mono;
630
631         // This string is going into an XpmImage struct, so create copies that
632         // libXPM can free successfully.
633         if (!g_color)
634                 *g_color_ptr = clone_c_string(gray_stream.str().c_str());
635         if (!m_color)
636                 *m_color_ptr = clone_c_string(mono_stream.str().c_str());
637 }
638
639
640 void copy_color_table(XpmColor const * in, size_t size, XpmColor * out)
641 {
642         for (size_t i = 0; i < size; ++i) {
643                 out[i].string   = clone_c_string(in[i].string);
644                 out[i].symbolic = clone_c_string(in[i].symbolic);
645                 out[i].m_color  = clone_c_string(in[i].m_color);
646                 out[i].g_color  = clone_c_string(in[i].g_color);
647                 out[i].g4_color = clone_c_string(in[i].g4_color);
648                 out[i].c_color  = clone_c_string(in[i].c_color);
649         }
650 }
651
652
653 void free_color_table(XpmColor * table, size_t size)
654 {
655         for (size_t i = 0; i < size; ++i) {
656                 free(table[i].string);
657                 free(table[i].symbolic);
658                 free(table[i].m_color);
659                 free(table[i].g_color);
660                 free(table[i].g4_color);
661                 free(table[i].c_color);
662         }
663         // Don't free the table itself. Let the shared_c_ptr do that.
664         // free(table);
665 }
666
667
668 char * clone_c_string(char const * in)
669 {
670         if (!in)
671                 return 0;
672
673         // Don't forget the '\0'
674         char * out = static_cast<char *>(malloc(strlen(in) + 1));
675         return strcpy(out, in);
676 }
677
678
679 bool contains_color_none(XpmImage const & image)
680 {
681         for (size_t i = 0; i < image.ncolors; ++i) {
682                 char const * const color = image.colorTable[i].c_color;
683                 if (color && lowercase(color) == "none")
684                         return true;
685         }
686         return false;
687 }
688
689
690 string const unique_color_string(XpmImage const & image)
691 {
692         string id(image.cpp, ' ');
693
694         for(;;) {
695                 bool found_it = false;
696                 for (size_t i = 0; i < image.ncolors; ++i) {
697                         string const c_id = image.colorTable[i].string;
698                         if (c_id == id) {
699                                 found_it = true;
700                                 break;
701                         }
702                 }
703
704                 if (!found_it)
705                         return id;
706
707                 // Loop over the printable characters in the ASCII table.
708                 // Ie, count from char 32 (' ') to char 126 ('~')
709                 // A base 94 counter!
710                 string::size_type current_index = id.size() - 1;
711                 bool continue_loop = true;
712                 while(continue_loop) {
713                         continue_loop = false;
714
715                         if (id[current_index] == 126) {
716                                 continue_loop = true;
717                                 if (current_index == 0)
718                                         // Unable to find a unique string
719                                         return image.colorTable[0].string;
720
721                                 id[current_index] = 32;
722                                 current_index -= 1;
723                         } else {
724                                 id[current_index] += 1;
725                                 // Note that '"' is an illegal char in this
726                                 // context
727                                 if (id[current_index] == '"')
728                                         id[current_index] += 1;
729                         }
730                 }
731                 if (continue_loop)
732                         // Unable to find a unique string
733                         return string();
734         }
735 }
736
737 } // namespace anon