2 * \file GraphicsImageXPM.C
3 * Read the file COPYING
6 * \author Angus Leeming
8 * Full author contact details available in file CREDITS
14 #pragma implementation
17 #include "GraphicsImageXPM.h"
18 #include "GraphicsParams.h"
19 #include "frontends/xforms/ColorHandler.h"
21 #include "support/filetools.h" // IsFileReadable
22 #include "support/lstrings.h"
25 #include <boost/tuple/tuple.hpp>
26 #include <boost/bind.hpp>
28 #include FORMS_H_LOCATION
30 #include <iomanip> // std::setfill, etc
31 #include <cmath> // cos, sin
32 #include <cstdlib> // malloc, free
34 #ifndef CXX_GLOBAL_CSTD
44 /// Access to this class is through this static method.
45 Image::ImagePtr ImageXPM::newImage()
48 ptr.reset(new ImageXPM);
53 /// Return the list of loadable formats.
54 Image::FormatList ImageXPM::loadableFormats()
56 FormatList formats(1);
64 pixmap_status_(PIXMAP_UNINITIALISED)
68 ImageXPM::ImageXPM(ImageXPM const & other)
72 pixmap_status_(PIXMAP_UNINITIALISED)
79 XFreePixmap(fl_get_display(), pixmap_);
83 Image * ImageXPM::clone() const
85 return new ImageXPM(*this);
89 unsigned int ImageXPM::getWidth() const
91 return image_.width();
95 unsigned int ImageXPM::getHeight() const
97 return image_.height();
101 bool ImageXPM::isDrawable() const
107 Pixmap ImageXPM::getPixmap() const
109 if (!pixmap_status_ == PIXMAP_SUCCESS)
115 void ImageXPM::load(string const & filename)
117 if (filename.empty()) {
118 finishedLoading(false);
122 if (!image_.empty()) {
123 lyxerr[Debug::GRAPHICS]
124 << "Image is loaded already!" << std::endl;
125 finishedLoading(false);
129 XpmImage * xpm_image = new XpmImage;
132 XpmReadFileToXpmImage(const_cast<char *>(filename.c_str()),
137 lyxerr[Debug::GRAPHICS]
138 << "No XPM image file found." << std::endl;
142 lyxerr[Debug::GRAPHICS]
143 << "File format is invalid" << std::endl;
147 lyxerr[Debug::GRAPHICS]
148 << "Insufficient memory to read in XPM file"
153 if (success != XpmSuccess) {
154 XpmFreeXpmImage(xpm_image);
157 lyxerr[Debug::GRAPHICS]
158 << "Error reading XPM file '"
159 << XpmGetErrorString(success) << "'"
162 image_.reset(*xpm_image);
165 finishedLoading(success == XpmSuccess);
169 bool ImageXPM::setPixmap(Params const & params)
171 if (image_.empty() || params.display == NoDisplay) {
175 Display * display = fl_get_display();
177 if (pixmap_ && pixmap_status_ == PIXMAP_SUCCESS)
178 XFreePixmap(display, pixmap_);
181 // This might be a dirty thing, but I dont know any other solution.
182 Screen * screen = ScreenOfDisplay(display, fl_screen);
187 XpmAttributes attrib;
189 // Allow libXPM lots of leeway when trying to allocate colors.
190 attrib.closeness = 10000;
191 attrib.valuemask = XpmCloseness;
193 // The XPM file format allows multiple pixel colours to be defined
194 // as c_color, g_color or m_color.
195 switch (params.display) {
196 case MonochromeDisplay:
197 attrib.color_key = XPM_MONO;
199 case GrayscaleDisplay:
200 attrib.color_key = XPM_GRAY;
203 default: // NoDisplay cannot happen!
204 attrib.color_key = XPM_COLOR;
208 attrib.valuemask |= XpmColorKey;
210 // Set the color "none" entry to the color of the background.
211 XpmColorSymbol xpm_col[2];
213 xpm_col[0].value = "none";
214 xpm_col[0].pixel = lyxColorHandler->colorPixel(LColor::graphicsbg);
216 // some image magick versions use this
218 xpm_col[1].value = "opaque";
219 xpm_col[1].pixel = lyxColorHandler->colorPixel(LColor::black);
221 attrib.numsymbols = 2;
222 attrib.colorsymbols = xpm_col;
223 attrib.valuemask |= XpmColorSymbols;
225 // Load up the pixmap
226 XpmImage xpm_image = image_.get();
228 XpmCreatePixmapFromXpmImage(display,
229 XRootWindowOfScreen(screen),
231 &pixmap, &mask, &attrib);
233 XpmFreeAttributes(&attrib);
235 if (status != XpmSuccess) {
236 lyxerr << "Error creating pixmap from xpm_image '"
237 << XpmGetErrorString(status) << "'"
239 pixmap_status_ = PIXMAP_FAILED;
244 pixmap_status_ = PIXMAP_SUCCESS;
249 void ImageXPM::clip(Params const & params)
254 if (params.bb.empty())
255 // No clipping is necessary.
258 typedef unsigned int dimension;
260 dimension const new_width = params.bb.xr - params.bb.xl;
261 dimension const new_height = params.bb.yt - params.bb.yb;
263 if (new_width > image_.width() || new_height > image_.height())
264 // Bounds are invalid.
267 if (new_width == image_.width() && new_height == image_.height())
268 // Bounds are unchanged.
271 dimension * new_data = image_.initialisedData(new_width, new_height);
272 dimension * it = new_data;
274 // The image is stored in memory from upper-left to lower-right,
275 // so we loop from yt to yb.
276 dimension const * old_data = image_.data();
277 dimension const * start_row = old_data +
278 image_.width() * (image_.height() - params.bb.yt);
280 // the Bounding Box dimensions are never less than zero, so we can use
281 // "unsigned int row" here
282 for (dimension row = params.bb.yb; row < params.bb.yt; ++row) {
283 dimension const * begin = start_row + params.bb.xl;
284 dimension const * end = start_row + params.bb.xr;
285 it = std::copy(begin, end, it);
286 start_row += image_.width();
289 image_.resetData(new_width, new_height, new_data);
293 void ImageXPM::rotate(Params const & params)
299 // No rotation is necessary.
302 // Ascertain the bounding box of the rotated image
303 // Rotate about the bottom-left corner
304 static double const pi = 3.14159265358979323846;
305 // The minus sign is needed to rotate in the same sense as xdvi et al.
306 double const angle = -double(params.angle) * pi / 180.0;
307 double const cos_a = cos(angle);
308 double const sin_a = sin(angle);
311 double max_x = 0; double min_x = 0;
312 double max_y = 0; double min_y = 0;
314 // (old_xpm->width, 0)
315 double x_rot = cos_a * image_.width();
316 double y_rot = sin_a * image_.width();
317 max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
318 max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
320 // (image_.width, image_.height)
321 x_rot = cos_a * image_.width() - sin_a * image_.height();
322 y_rot = sin_a * image_.width() + cos_a * image_.height();
323 max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
324 max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
326 // (0, image_.height)
327 x_rot = - sin_a * image_.height();
328 y_rot = cos_a * image_.height();
329 max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
330 max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
332 typedef unsigned int dimension;
334 dimension const new_width = 1 + int(max_x - min_x); // round up!
335 dimension const new_height = 1 + int(max_y - min_y);
337 dimension * new_data = image_.initialisedData(new_width, new_height);
338 dimension const * old_data = image_.data();
341 for (dimension y_old = 0; y_old < image_.height(); ++y_old) {
342 for (dimension x_old = 0; x_old < image_.width(); ++x_old) {
343 double const x_pos = cos_a*x_old - sin_a*y_old - min_x;
344 double const y_pos = sin_a*x_old + cos_a*y_old - min_y;
346 // ensure that there are no rounding errors
347 dimension x_new = (x_pos > 0) ? dimension(x_pos) : 0;
348 dimension y_new = (y_pos > 0) ? dimension(y_pos) : 0;
349 x_new = std::min(new_width - 1, x_new);
350 y_new = std::min(new_height - 1, y_new);
352 size_t const id_old = x_old + image_.width() * y_old;
353 size_t const id_new = x_new + new_width * y_new;
355 new_data[id_new] = old_data[id_old];
359 image_.resetData(new_width, new_height, new_data);
363 void ImageXPM::scale(Params const & params)
368 typedef unsigned int dimension;
371 dimension new_height;
372 boost::tie(new_width, new_height) = getScaledDimensions(params);
374 if (new_width == getWidth() && new_height == getHeight())
378 dimension * new_data = image_.initialisedData(new_width, new_height);
379 dimension const * old_data = image_.data();
381 double const x_scale = double(image_.width()) / double(new_width);
382 double const y_scale = double(image_.height()) / double(new_height);
384 // A very simple scaling routine.
385 // Ascertain the old pixel corresponding to the new one.
386 // There is no dithering at all here.
387 for (dimension x_new = 0; x_new < new_width; ++x_new) {
388 dimension x_old = dimension(x_new * x_scale);
390 for (dimension y_new = 0; y_new < new_height; ++y_new) {
391 dimension y_old = dimension(y_new * y_scale);
393 size_t const id_old = x_old + image_.width() * y_old;
394 size_t const id_new = x_new + new_width * y_new;
396 new_data[id_new] = old_data[id_old];
400 image_.resetData(new_width, new_height, new_data);
408 void free_color_table(XpmColor * colorTable, size_t size);
410 void copy_color_table(XpmColor const * in, size_t size, XpmColor * out);
412 bool contains_color_none(XpmImage const & image);
414 string const unique_color_string(XpmImage const & image);
416 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
417 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
418 string const convertTo7chars(string const &);
420 // create a copy (using malloc and strcpy). If (!in) return 0;
421 char * clone_c_string(char const * in);
423 // Given a string of the form #ff0571 create appropriate grayscale and
424 // monochrome colors.
425 void mapcolor(char const * c_color, char ** g_color_ptr, char ** m_color_ptr);
432 ImageXPM::Data::Data()
433 : width_(0), height_(0), cpp_(0), ncolors_(0)
437 ImageXPM::Data::~Data()
442 void ImageXPM::Data::reset(XpmImage & image)
444 width_ = image.width;
445 height_ = image.height;
448 // Move the data ptr into this store and free up image.data
449 data_.reset(image.data, free);
452 // Don't just store the color table, but check first that it contains
453 // all that we require of it.
454 // The idea is to store the color table in a shared_ptr and for all
455 // modified images to use the same table.
456 // It must, therefore, have a c_color "none" entry and g_color and
457 // m_color entries corresponding to each and every c_color entry
460 // 1. Create a copy of the color table.
461 // Add a c_color "none" entry to the table if it isn't already there.
462 bool const add_color = !contains_color_none(image);
466 ncolors_ = 1 + image.ncolors;
467 size_t const mem_size = sizeof(XpmColor) * ncolors_;
468 XpmColor * table = static_cast<XpmColor *>(malloc(mem_size));
470 copy_color_table(image.colorTable, image.ncolors, table);
472 XpmColor & color = table[ncolors_ - 1];
478 clone_c_string(unique_color_string(image).c_str());
479 color.c_color = clone_c_string("none");
481 free_color_table(image.colorTable, image.ncolors);
482 colorTable_.reset(table, boost::bind(free_color_table, _1, ncolors_));
486 // Just move the pointer across
487 ncolors_ = image.ncolors;
488 colorTable_.reset(image.colorTable,
489 boost::bind(free_color_table, _1, ncolors_));
490 image.colorTable = 0;
493 // Clean-up the remaining entries of image.
499 // 2. Ensure that the color table has g_color and m_color entries
500 XpmColor * table = colorTable_.get();
502 for (size_t i = 0; i < ncolors_; ++i) {
503 XpmColor & entry = table[i];
507 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
508 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
509 string c_color = entry.c_color;
510 if (c_color[0] == '#' && c_color.size() != 7) {
511 c_color = convertTo7chars(c_color);
513 entry.c_color = clone_c_string(c_color.c_str());
516 // If the c_color is defined and the equivalent
517 // grayscale or monochrome ones are not, then define them.
518 mapcolor(entry.c_color, &entry.g_color, &entry.m_color);
523 XpmImage ImageXPM::Data::get() const
526 image.width = width_;
527 image.height = height_;
529 image.ncolors = ncolors_;
530 image.data = data_.get();
531 image.colorTable = colorTable_.get();
536 void ImageXPM::Data::resetData(int w, int h, unsigned int * d)
540 data_.reset(d, free);
544 unsigned int * ImageXPM::Data::initialisedData(int w, int h) const
546 size_t const data_size = w * h;
548 size_t const mem_size = sizeof(unsigned int) * data_size;
549 unsigned int * ptr = static_cast<unsigned int *>(malloc(mem_size));
551 unsigned int none_id = color_none_id();
552 std::fill(ptr, ptr + data_size, none_id);
558 unsigned int ImageXPM::Data::color_none_id() const
560 XpmColor * table = colorTable_.get();
561 for (size_t i = 0; i < ncolors_; ++i) {
562 char const * const color = table[i].c_color;
563 if (color && ascii_lowercase(color) == "none")
564 return static_cast<unsigned int>(i);
573 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
574 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
575 string const convertTo7chars(string const & input)
577 string::size_type size = input.size();
578 if (size != 13 && size != 10 && size != 9 && size != 4)
579 // Can't deal with it.
583 // Can't deal with it.
586 string format(input);
589 case 13: // #rrrrggggbbbb
594 case 10: // #rrrgggbbb
603 format.insert(2, 1, '0');
604 format.insert(4, 1, '0');
605 format.append(1, '0');
613 // Given a string of the form #ff0571 create appropriate grayscale and
614 // monochrome colors.
615 void mapcolor(char const * c_color, char ** g_color_ptr, char ** m_color_ptr)
620 char * g_color = *g_color_ptr;
621 char * m_color = *m_color_ptr;
623 if (g_color && m_color)
627 Display * display = fl_get_display();
628 Colormap cmap = fl_state[fl_get_vclass()].colormap;
631 if (XLookupColor(display, cmap, c_color, &xcol, &ccol) == 0)
632 // Unable to parse c_color.
635 // Note that X stores the RGB values in the range 0 - 65535
636 // whilst we require them in the range 0 - 255.
637 int const r = xcol.red / 256;
638 int const g = xcol.green / 256;
639 int const b = xcol.blue / 256;
641 // This gives a good match to a human's RGB to luminance conversion.
642 // (From xv's Postscript code --- Mike Ressler.)
643 int const gray = int((0.32 * r) + (0.5 * g) + (0.18 * b));
645 ostringstream gray_stream;
646 gray_stream << "#" << std::setbase(16) << std::setfill('0')
647 << std::setw(2) << gray
648 << std::setw(2) << gray
649 << std::setw(2) << gray;
651 int const mono = (gray < 128) ? 0 : 255;
652 ostringstream mono_stream;
653 mono_stream << "#" << std::setbase(16) << std::setfill('0')
654 << std::setw(2) << mono
655 << std::setw(2) << mono
656 << std::setw(2) << mono;
658 // This string is going into an XpmImage struct, so create copies that
659 // libXPM can free successfully.
661 *g_color_ptr = clone_c_string(gray_stream.str().c_str());
663 *m_color_ptr = clone_c_string(mono_stream.str().c_str());
667 void copy_color_table(XpmColor const * in, size_t size, XpmColor * out)
669 for (size_t i = 0; i < size; ++i) {
670 out[i].string = clone_c_string(in[i].string);
671 out[i].symbolic = clone_c_string(in[i].symbolic);
672 out[i].m_color = clone_c_string(in[i].m_color);
673 out[i].g_color = clone_c_string(in[i].g_color);
674 out[i].g4_color = clone_c_string(in[i].g4_color);
675 out[i].c_color = clone_c_string(in[i].c_color);
680 void free_color_table(XpmColor * table, size_t size)
682 for (size_t i = 0; i < size; ++i) {
683 free(table[i].string);
684 free(table[i].symbolic);
685 free(table[i].m_color);
686 free(table[i].g_color);
687 free(table[i].g4_color);
688 free(table[i].c_color);
694 char * clone_c_string(char const * in)
699 // Don't forget the '\0'
700 char * out = static_cast<char *>(malloc(strlen(in) + 1));
701 return strcpy(out, in);
705 bool contains_color_none(XpmImage const & image)
707 for (size_t i = 0; i < image.ncolors; ++i) {
708 char const * const color = image.colorTable[i].c_color;
709 if (color && ascii_lowercase(color) == "none")
716 string const unique_color_string(XpmImage const & image)
718 string id(image.cpp, ' ');
721 bool found_it = false;
722 for (size_t i = 0; i < image.ncolors; ++i) {
723 string const c_id = image.colorTable[i].string;
733 // Loop over the printable characters in the ASCII table.
734 // Ie, count from char 32 (' ') to char 126 ('~')
735 // A base 94 counter!
736 string::size_type current_index = id.size() - 1;
737 bool continue_loop = true;
738 while(continue_loop) {
739 continue_loop = false;
741 if (id[current_index] == 126) {
742 continue_loop = true;
743 if (current_index == 0)
744 // Unable to find a unique string
745 return image.colorTable[0].string;
747 id[current_index] = 32;
750 id[current_index] += 1;
751 // Note that '"' is an illegal char in this
753 if (id[current_index] == '"')
754 id[current_index] += 1;
758 // Unable to find a unique string