2 * \file GraphicsImageXPM.C
3 * Copyright 2002 the LyX Team
4 * Read the file COPYING
6 * \author Baruch Even <baruch.even@writeme.com>
7 * \author Angus Leeming <a.leeming@ic.ac.uk>
13 #pragma implementation
16 #include "GraphicsImageXPM.h"
17 #include "GraphicsParams.h"
18 #include "frontends/xforms/ColorHandler.h"
20 #include "frontends/GUIRunTime.h" // x11Display, x11Screen
21 #include "support/filetools.h" // IsFileReadable
22 #include "support/lstrings.h"
24 #include <iomanip> // std::setfill, etc
25 #include <cmath> // cos, sin
26 #include <cstdlib> // malloc, free
30 /// Access to this class is through this static method.
31 ImagePtr GImageXPM::newImage()
34 ptr.reset(new GImageXPM);
39 /// Return the list of loadable formats.
40 GImage::FormatList GImageXPM::loadableFormats()
42 FormatList formats(1);
48 GImageXPM::GImageXPM()
50 pixmap_status_(PIXMAP_UNINITIALISED)
54 GImageXPM::GImageXPM(GImageXPM const & other)
58 pixmap_status_(PIXMAP_UNINITIALISED)
62 GImageXPM::~GImageXPM()
65 XFreePixmap(GUIRunTime::x11Display(), pixmap_);
69 GImage * GImageXPM::clone() const
71 return new GImageXPM(*this);
75 unsigned int GImageXPM::getWidth() const
77 return image_.width();
81 unsigned int GImageXPM::getHeight() const
83 return image_.height();
87 Pixmap GImageXPM::getPixmap() const
89 if (!pixmap_status_ == PIXMAP_SUCCESS)
95 void GImageXPM::load(string const & filename, GImage::SignalTypePtr on_finish)
97 if (filename.empty()) {
98 on_finish->operator()(false);
102 if (!image_.empty()) {
103 lyxerr[Debug::GRAPHICS]
104 << "Image is loaded already!" << std::endl;
105 on_finish->operator()(false);
109 XpmImage * xpm_image = new XpmImage;
112 XpmReadFileToXpmImage(const_cast<char *>(filename.c_str()),
117 lyxerr[Debug::GRAPHICS]
118 << "No XPM image file found." << std::endl;
122 lyxerr[Debug::GRAPHICS]
123 << "File format is invalid" << std::endl;
127 lyxerr[Debug::GRAPHICS]
128 << "Insufficient memory to read in XPM file"
133 if (success != XpmSuccess) {
134 XpmFreeXpmImage(xpm_image);
137 lyxerr[Debug::GRAPHICS]
138 << "Error reading XPM file '"
139 << XpmGetErrorString(success) << "'"
142 image_.reset(*xpm_image);
145 on_finish->operator()(success == XpmSuccess);
149 bool GImageXPM::setPixmap(GParams const & params)
151 if (image_.empty() || params.display == GParams::NONE) {
155 Display * display = GUIRunTime::x11Display();
157 if (pixmap_ && pixmap_status_ == PIXMAP_SUCCESS)
158 XFreePixmap(display, pixmap_);
161 // This might be a dirty thing, but I dont know any other solution.
162 Screen * screen = ScreenOfDisplay(display, GUIRunTime::x11Screen());
167 XpmAttributes attrib;
169 // Allow libXPM lots of leeway when trying to allocate colors.
170 attrib.closeness = 10000;
171 attrib.valuemask = XpmCloseness;
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;
179 case GParams::GRAYSCALE:
180 attrib.color_key = XPM_GRAY;
183 default: // NONE cannot happen!
184 attrib.color_key = XPM_COLOR;
188 attrib.valuemask |= XpmColorKey;
190 // Set the color "none" entry to the color of the background.
191 XpmColorSymbol xpm_col[2];
193 xpm_col[0].value = "none";
194 xpm_col[0].pixel = lyxColorHandler->colorPixel(LColor::graphicsbg);
196 // some image magick versions use this
198 xpm_col[1].value = "opaque";
199 xpm_col[1].pixel = lyxColorHandler->colorPixel(LColor::white);
201 attrib.numsymbols = 2;
202 attrib.colorsymbols = xpm_col;
203 attrib.valuemask |= XpmColorSymbols;
205 // Load up the pixmap
206 XpmImage xpm_image = image_.get();
208 XpmCreatePixmapFromXpmImage(display,
209 XRootWindowOfScreen(screen),
211 &pixmap, &mask, &attrib);
213 XpmFreeAttributes(&attrib);
215 if (status != XpmSuccess) {
216 lyxerr << "Error creating pixmap from xpm_image '"
217 << XpmGetErrorString(status) << "'"
219 pixmap_status_ = PIXMAP_FAILED;
224 pixmap_status_ = PIXMAP_SUCCESS;
229 void GImageXPM::clip(GParams const & params)
234 if (params.bb.empty())
235 // No clipping is necessary.
238 typedef unsigned int dimension;
240 dimension const new_width = params.bb.xr - params.bb.xl;
241 dimension const new_height = params.bb.yt - params.bb.yb;
243 if (new_width > image_.width() || new_height > image_.height())
244 // Bounds are invalid.
247 if (new_width == image_.width() && new_height == image_.height())
248 // Bounds are unchanged.
251 dimension * new_data = image_.initialisedData(new_width, new_height);
252 dimension * it = new_data;
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);
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();
269 image_.resetData(new_width, new_height, new_data);
273 void GImageXPM::rotate(GParams const & params)
279 // No rotation is necessary.
282 // Ascertain the bounding box of the rotated image
283 // Rotate about the bottom-left corner
284 static double const pi = 3.14159265358979323846;
285 // The minus sign is needed to rotate in the same sense as xdvi et al.
286 double const angle = -double(params.angle) * pi / 180.0;
287 double const cos_a = cos(angle);
288 double const sin_a = sin(angle);
291 double max_x = 0; double min_x = 0;
292 double max_y = 0; double min_y = 0;
294 // (old_xpm->width, 0)
295 double x_rot = cos_a * image_.width();
296 double y_rot = sin_a * image_.width();
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);
300 // (image_.width, image_.height)
301 x_rot = cos_a * image_.width() - sin_a * image_.height();
302 y_rot = sin_a * image_.width() + 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);
306 // (0, image_.height)
307 x_rot = - sin_a * image_.height();
308 y_rot = cos_a * image_.height();
309 max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
310 max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
312 typedef unsigned int dimension;
314 dimension const new_width = 1 + int(max_x - min_x); // round up!
315 dimension const new_height = 1 + int(max_y - min_y);
317 dimension * new_data = image_.initialisedData(new_width, new_height);
318 dimension const * old_data = image_.data();
321 for (dimension y_old = 0; y_old < image_.height(); ++y_old) {
322 for (dimension x_old = 0; x_old < image_.width(); ++x_old) {
323 double const x_pos = cos_a*x_old - sin_a*y_old - min_x;
324 double const y_pos = sin_a*x_old + cos_a*y_old - min_y;
326 // ensure that there are no rounding errors
327 dimension x_new = (x_pos > 0) ? dimension(x_pos) : 0;
328 dimension y_new = (y_pos > 0) ? dimension(y_pos) : 0;
329 x_new = std::min(new_width - 1, x_new);
330 y_new = std::min(new_height - 1, y_new);
332 size_t const id_old = x_old + image_.width() * y_old;
333 size_t const id_new = x_new + new_width * y_new;
335 new_data[id_new] = old_data[id_old];
339 image_.resetData(new_width, new_height, new_data);
343 void GImageXPM::scale(GParams const & params)
348 typedef unsigned int dimension;
350 // boost::tie produces horrible compilation errors on my machine
352 std::pair<dimension, dimension> d = getScaledDimensions(params);
353 dimension const new_width = d.first;
354 dimension const new_height = d.second;
355 if (new_width == getWidth() && new_height == getHeight())
359 dimension * new_data = image_.initialisedData(new_width, new_height);
360 dimension const * old_data = image_.data();
362 double const x_scale = double(image_.width()) / double(new_width);
363 double const y_scale = double(image_.height()) / double(new_height);
365 // A very simple scaling routine.
366 // Ascertain the old pixel corresponding to the new one.
367 // There is no dithering at all here.
368 for (dimension x_new = 0; x_new < new_width; ++x_new) {
369 dimension x_old = dimension(x_new * x_scale);
371 for (dimension y_new = 0; y_new < new_height; ++y_new) {
372 dimension y_old = dimension(y_new * y_scale);
374 size_t const id_old = x_old + image_.width() * y_old;
375 size_t const id_new = x_new + new_width * y_new;
377 new_data[id_new] = old_data[id_old];
381 image_.resetData(new_width, new_height, new_data);
389 void free_color_table(XpmColor * colorTable, size_t size);
391 void copy_color_table(XpmColor const * in, size_t size, XpmColor * out);
393 bool contains_color_none(XpmImage const & image);
395 string const unique_color_string(XpmImage const & image);
397 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
398 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
399 string const convertTo7chars(string const &);
401 // create a copy (using malloc and strcpy). If (!in) return 0;
402 char * clone_c_string(char const * in);
404 // Given a string of the form #ff0571 create appropriate grayscale and
405 // monochrome colors.
406 void mapcolor(char const * c_color, char ** g_color_ptr, char ** m_color_ptr);
413 GImageXPM::Data::Data()
414 : width_(0), height_(0), cpp_(0), ncolors_(0)
418 GImageXPM::Data::~Data()
420 if (colorTable_.unique())
421 free_color_table(colorTable_.get(), ncolors_);
425 void GImageXPM::Data::reset(XpmImage & image)
427 width_ = image.width;
428 height_ = image.height;
431 // Move the data ptr into this store and free up image.data
432 data_.reset(image.data);
435 // Don't just store the color table, but check first that it contains
436 // all that we require of it.
437 // The idea is to store the color table in a shared_ptr and for all
438 // modified images to use the same table.
439 // It must, therefore, have a c_color "none" entry and g_color and
440 // m_color entries corresponding to each and every c_color entry
443 // 1. Create a copy of the color table.
444 // Add a c_color "none" entry to the table if it isn't already there.
445 bool const add_color = !contains_color_none(image);
449 ncolors_ = 1 + image.ncolors;
450 size_t const mem_size = sizeof(XpmColor) * ncolors_;
451 XpmColor * table = static_cast<XpmColor *>(malloc(mem_size));
453 copy_color_table(image.colorTable, image.ncolors, table);
455 XpmColor & color = table[ncolors_ - 1];
461 clone_c_string(unique_color_string(image).c_str());
462 color.c_color = clone_c_string("none");
464 free_color_table(image.colorTable, image.ncolors);
465 colorTable_.reset(table);
469 // Just move the pointer across
470 ncolors_ = image.ncolors;
471 colorTable_.reset(image.colorTable);
472 image.colorTable = 0;
475 // Clean-up the remaining entries of image.
481 // 2. Ensure that the color table has g_color and m_color entries
482 XpmColor * table = colorTable_.get();
484 for (size_t i = 0; i < ncolors_; ++i) {
485 XpmColor & entry = table[i];
489 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
490 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
491 string c_color = entry.c_color;
492 if (c_color[0] == '#' && c_color.size() != 7) {
493 c_color = convertTo7chars(c_color);
495 entry.c_color = clone_c_string(c_color.c_str());
498 // If the c_color is defined and the equivalent
499 // grayscale or monochrome ones are not, then define them.
500 mapcolor(entry.c_color, &entry.g_color, &entry.m_color);
505 XpmImage GImageXPM::Data::get() const
508 image.width = width_;
509 image.height = height_;
511 image.ncolors = ncolors_;
512 image.data = data_.get();
513 image.colorTable = colorTable_.get();
518 void GImageXPM::Data::resetData(int w, int h, unsigned int * d)
526 unsigned int * GImageXPM::Data::initialisedData(int w, int h) const
528 size_t const data_size = w * h;
530 size_t const mem_size = sizeof(unsigned int) * data_size;
531 unsigned int * ptr = static_cast<unsigned int *>(malloc(mem_size));
533 unsigned int none_id = color_none_id();
534 std::fill(ptr, ptr + data_size, none_id);
540 unsigned int GImageXPM::Data::color_none_id() const
542 XpmColor * table = colorTable_.get();
543 for (size_t i = 0; i < ncolors_; ++i) {
544 char const * const color = table[i].c_color;
545 if (color && lowercase(color) == "none")
555 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
556 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
557 string const convertTo7chars(string const & input)
559 string::size_type size = input.size();
560 if (size != 13 && size != 10 && size != 4)
561 // Can't deal with it.
565 // Can't deal with it.
568 string format(input);
571 case 13: // #rrrrggggbbbb
576 case 10: // #rrrgggbbb
582 format.insert(2, 1, '0');
583 format.insert(4, 1, '0');
584 format.append(1, '0');
592 // Given a string of the form #ff0571 create appropriate grayscale and
593 // monochrome colors.
594 void mapcolor(char const * c_color, char ** g_color_ptr, char ** m_color_ptr)
599 char * g_color = *g_color_ptr;
600 char * m_color = *m_color_ptr;
602 if (g_color && m_color)
606 Display * display = GUIRunTime::x11Display();
607 Colormap cmap = GUIRunTime::x11Colormap();
610 if (XLookupColor(display, cmap, c_color, &xcol, &ccol) == 0)
611 // Unable to parse c_color.
614 // Note that X stores the RGB values in the range 0 - 65535
615 // whilst we require them in the range 0 - 255.
616 int const r = xcol.red / 256;
617 int const g = xcol.green / 256;
618 int const b = xcol.blue / 256;
620 // This gives a good match to a human's RGB to luminance conversion.
621 // (From xv's Postscript code --- Mike Ressler.)
622 int const gray = int((0.32 * r) + (0.5 * g) + (0.18 * b));
624 ostringstream gray_stream;
625 gray_stream << "#" << std::setbase(16) << std::setfill('0')
626 << std::setw(2) << gray
627 << std::setw(2) << gray
628 << std::setw(2) << gray;
630 int const mono = (gray < 128) ? 0 : 255;
631 ostringstream mono_stream;
632 mono_stream << "#" << std::setbase(16) << std::setfill('0')
633 << std::setw(2) << mono
634 << std::setw(2) << mono
635 << std::setw(2) << mono;
637 // This string is going into an XpmImage struct, so create copies that
638 // libXPM can free successfully.
640 *g_color_ptr = clone_c_string(gray_stream.str().c_str());
642 *m_color_ptr = clone_c_string(mono_stream.str().c_str());
646 void copy_color_table(XpmColor const * in, size_t size, XpmColor * out)
648 for (size_t i = 0; i < size; ++i) {
649 out[i].string = clone_c_string(in[i].string);
650 out[i].symbolic = clone_c_string(in[i].symbolic);
651 out[i].m_color = clone_c_string(in[i].m_color);
652 out[i].g_color = clone_c_string(in[i].g_color);
653 out[i].g4_color = clone_c_string(in[i].g4_color);
654 out[i].c_color = clone_c_string(in[i].c_color);
659 void free_color_table(XpmColor * table, size_t size)
661 for (size_t i = 0; i < size; ++i) {
662 free(table[i].string);
663 free(table[i].symbolic);
664 free(table[i].m_color);
665 free(table[i].g_color);
666 free(table[i].g4_color);
667 free(table[i].c_color);
669 // Don't free the table itself. Let the shared_c_ptr do that.
674 char * clone_c_string(char const * in)
679 // Don't forget the '\0'
680 char * out = static_cast<char *>(malloc(strlen(in) + 1));
681 return strcpy(out, in);
685 bool contains_color_none(XpmImage const & image)
687 for (size_t i = 0; i < image.ncolors; ++i) {
688 char const * const color = image.colorTable[i].c_color;
689 if (color && lowercase(color) == "none")
696 string const unique_color_string(XpmImage const & image)
698 string id(image.cpp, ' ');
701 bool found_it = false;
702 for (size_t i = 0; i < image.ncolors; ++i) {
703 string const c_id = image.colorTable[i].string;
713 // Loop over the printable characters in the ASCII table.
714 // Ie, count from char 32 (' ') to char 126 ('~')
715 // A base 94 counter!
716 string::size_type current_index = id.size() - 1;
717 bool continue_loop = true;
718 while(continue_loop) {
719 continue_loop = false;
721 if (id[current_index] == 126) {
722 continue_loop = true;
723 if (current_index == 0)
724 // Unable to find a unique string
725 return image.colorTable[0].string;
727 id[current_index] = 32;
730 id[current_index] += 1;
731 // Note that '"' is an illegal char in this
733 if (id[current_index] == '"')
734 id[current_index] += 1;
738 // Unable to find a unique string