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 <leeming@lyx.org>
13 #pragma implementation
16 #include "GraphicsImageXPM.h"
17 #include "GraphicsParams.h"
18 #include "frontends/xforms/ColorHandler.h"
20 #include "support/filetools.h" // IsFileReadable
21 #include "support/lstrings.h"
23 #include <iomanip> // std::setfill, etc
24 #include <cmath> // cos, sin
25 #include <cstdlib> // malloc, free
27 #include <boost/tuple/tuple.hpp>
29 #include FORMS_H_LOCATION
31 #ifndef CXX_GLOBAL_CSTD
41 /// Access to this class is through this static method.
42 Image::ImagePtr ImageXPM::newImage()
45 ptr.reset(new ImageXPM);
50 /// Return the list of loadable formats.
51 Image::FormatList ImageXPM::loadableFormats()
53 FormatList formats(1);
61 pixmap_status_(PIXMAP_UNINITIALISED)
65 ImageXPM::ImageXPM(ImageXPM const & other)
69 pixmap_status_(PIXMAP_UNINITIALISED)
76 XFreePixmap(fl_get_display(), pixmap_);
80 Image * ImageXPM::clone() const
82 return new ImageXPM(*this);
86 unsigned int ImageXPM::getWidth() const
88 return image_.width();
92 unsigned int ImageXPM::getHeight() const
94 return image_.height();
98 bool ImageXPM::isDrawable() const
104 Pixmap ImageXPM::getPixmap() const
106 if (!pixmap_status_ == PIXMAP_SUCCESS)
112 void ImageXPM::load(string const & filename)
114 if (filename.empty()) {
115 finishedLoading(false);
119 if (!image_.empty()) {
120 lyxerr[Debug::GRAPHICS]
121 << "Image is loaded already!" << std::endl;
122 finishedLoading(false);
126 XpmImage * xpm_image = new XpmImage;
129 XpmReadFileToXpmImage(const_cast<char *>(filename.c_str()),
134 lyxerr[Debug::GRAPHICS]
135 << "No XPM image file found." << std::endl;
139 lyxerr[Debug::GRAPHICS]
140 << "File format is invalid" << std::endl;
144 lyxerr[Debug::GRAPHICS]
145 << "Insufficient memory to read in XPM file"
150 if (success != XpmSuccess) {
151 XpmFreeXpmImage(xpm_image);
154 lyxerr[Debug::GRAPHICS]
155 << "Error reading XPM file '"
156 << XpmGetErrorString(success) << "'"
159 image_.reset(*xpm_image);
162 finishedLoading(success == XpmSuccess);
166 bool ImageXPM::setPixmap(Params const & params)
168 if (image_.empty() || params.display == NoDisplay) {
172 Display * display = fl_get_display();
174 if (pixmap_ && pixmap_status_ == PIXMAP_SUCCESS)
175 XFreePixmap(display, pixmap_);
178 // This might be a dirty thing, but I dont know any other solution.
179 Screen * screen = ScreenOfDisplay(display, fl_screen);
184 XpmAttributes attrib;
186 // Allow libXPM lots of leeway when trying to allocate colors.
187 attrib.closeness = 10000;
188 attrib.valuemask = XpmCloseness;
190 // The XPM file format allows multiple pixel colours to be defined
191 // as c_color, g_color or m_color.
192 switch (params.display) {
193 case MonochromeDisplay:
194 attrib.color_key = XPM_MONO;
196 case GrayscaleDisplay:
197 attrib.color_key = XPM_GRAY;
200 default: // NoDisplay cannot happen!
201 attrib.color_key = XPM_COLOR;
205 attrib.valuemask |= XpmColorKey;
207 // Set the color "none" entry to the color of the background.
208 XpmColorSymbol xpm_col[2];
210 xpm_col[0].value = "none";
211 xpm_col[0].pixel = lyxColorHandler->colorPixel(LColor::graphicsbg);
213 // some image magick versions use this
215 xpm_col[1].value = "opaque";
216 xpm_col[1].pixel = lyxColorHandler->colorPixel(LColor::black);
218 attrib.numsymbols = 2;
219 attrib.colorsymbols = xpm_col;
220 attrib.valuemask |= XpmColorSymbols;
222 // Load up the pixmap
223 XpmImage xpm_image = image_.get();
225 XpmCreatePixmapFromXpmImage(display,
226 XRootWindowOfScreen(screen),
228 &pixmap, &mask, &attrib);
230 XpmFreeAttributes(&attrib);
232 if (status != XpmSuccess) {
233 lyxerr << "Error creating pixmap from xpm_image '"
234 << XpmGetErrorString(status) << "'"
236 pixmap_status_ = PIXMAP_FAILED;
241 pixmap_status_ = PIXMAP_SUCCESS;
246 void ImageXPM::clip(Params const & params)
251 if (params.bb.empty())
252 // No clipping is necessary.
255 typedef unsigned int dimension;
257 dimension const new_width = params.bb.xr - params.bb.xl;
258 dimension const new_height = params.bb.yt - params.bb.yb;
260 if (new_width > image_.width() || new_height > image_.height())
261 // Bounds are invalid.
264 if (new_width == image_.width() && new_height == image_.height())
265 // Bounds are unchanged.
268 dimension * new_data = image_.initialisedData(new_width, new_height);
269 dimension * it = new_data;
271 // The image is stored in memory from upper-left to lower-right,
272 // so we loop from yt to yb.
273 dimension const * old_data = image_.data();
274 dimension const * start_row = old_data +
275 image_.width() * (image_.height() - params.bb.yt);
277 // the Bounding Box dimensions are never less than zero, so we can use
278 // "unsigned int row" here
279 for (dimension row = params.bb.yb; row < params.bb.yt; ++row) {
280 dimension const * begin = start_row + params.bb.xl;
281 dimension const * end = start_row + params.bb.xr;
282 it = std::copy(begin, end, it);
283 start_row += image_.width();
286 image_.resetData(new_width, new_height, new_data);
290 void ImageXPM::rotate(Params const & params)
296 // No rotation is necessary.
299 // Ascertain the bounding box of the rotated image
300 // Rotate about the bottom-left corner
301 static double const pi = 3.14159265358979323846;
302 // The minus sign is needed to rotate in the same sense as xdvi et al.
303 double const angle = -double(params.angle) * pi / 180.0;
304 double const cos_a = cos(angle);
305 double const sin_a = sin(angle);
308 double max_x = 0; double min_x = 0;
309 double max_y = 0; double min_y = 0;
311 // (old_xpm->width, 0)
312 double x_rot = cos_a * image_.width();
313 double y_rot = sin_a * image_.width();
314 max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
315 max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
317 // (image_.width, image_.height)
318 x_rot = cos_a * image_.width() - sin_a * image_.height();
319 y_rot = sin_a * image_.width() + cos_a * image_.height();
320 max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
321 max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
323 // (0, image_.height)
324 x_rot = - sin_a * image_.height();
325 y_rot = cos_a * image_.height();
326 max_x = std::max(max_x, x_rot); min_x = std::min(min_x, x_rot);
327 max_y = std::max(max_y, y_rot); min_y = std::min(min_y, y_rot);
329 typedef unsigned int dimension;
331 dimension const new_width = 1 + int(max_x - min_x); // round up!
332 dimension const new_height = 1 + int(max_y - min_y);
334 dimension * new_data = image_.initialisedData(new_width, new_height);
335 dimension const * old_data = image_.data();
338 for (dimension y_old = 0; y_old < image_.height(); ++y_old) {
339 for (dimension x_old = 0; x_old < image_.width(); ++x_old) {
340 double const x_pos = cos_a*x_old - sin_a*y_old - min_x;
341 double const y_pos = sin_a*x_old + cos_a*y_old - min_y;
343 // ensure that there are no rounding errors
344 dimension x_new = (x_pos > 0) ? dimension(x_pos) : 0;
345 dimension y_new = (y_pos > 0) ? dimension(y_pos) : 0;
346 x_new = std::min(new_width - 1, x_new);
347 y_new = std::min(new_height - 1, y_new);
349 size_t const id_old = x_old + image_.width() * y_old;
350 size_t const id_new = x_new + new_width * y_new;
352 new_data[id_new] = old_data[id_old];
356 image_.resetData(new_width, new_height, new_data);
360 void ImageXPM::scale(Params const & params)
365 typedef unsigned int dimension;
368 dimension new_height;
369 boost::tie(new_width, new_height) = getScaledDimensions(params);
371 if (new_width == getWidth() && new_height == getHeight())
375 dimension * new_data = image_.initialisedData(new_width, new_height);
376 dimension const * old_data = image_.data();
378 double const x_scale = double(image_.width()) / double(new_width);
379 double const y_scale = double(image_.height()) / double(new_height);
381 // A very simple scaling routine.
382 // Ascertain the old pixel corresponding to the new one.
383 // There is no dithering at all here.
384 for (dimension x_new = 0; x_new < new_width; ++x_new) {
385 dimension x_old = dimension(x_new * x_scale);
387 for (dimension y_new = 0; y_new < new_height; ++y_new) {
388 dimension y_old = dimension(y_new * y_scale);
390 size_t const id_old = x_old + image_.width() * y_old;
391 size_t const id_new = x_new + new_width * y_new;
393 new_data[id_new] = old_data[id_old];
397 image_.resetData(new_width, new_height, new_data);
405 void free_color_table(XpmColor * colorTable, size_t size);
407 void copy_color_table(XpmColor const * in, size_t size, XpmColor * out);
409 bool contains_color_none(XpmImage const & image);
411 string const unique_color_string(XpmImage const & image);
413 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
414 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
415 string const convertTo7chars(string const &);
417 // create a copy (using malloc and strcpy). If (!in) return 0;
418 char * clone_c_string(char const * in);
420 // Given a string of the form #ff0571 create appropriate grayscale and
421 // monochrome colors.
422 void mapcolor(char const * c_color, char ** g_color_ptr, char ** m_color_ptr);
429 ImageXPM::Data::Data()
430 : width_(0), height_(0), cpp_(0), ncolors_(0)
434 ImageXPM::Data::~Data()
436 if (colorTable_.unique())
437 free_color_table(colorTable_.get(), ncolors_);
441 void ImageXPM::Data::reset(XpmImage & image)
443 width_ = image.width;
444 height_ = image.height;
447 // Move the data ptr into this store and free up image.data
448 data_.reset(image.data);
451 // Don't just store the color table, but check first that it contains
452 // all that we require of it.
453 // The idea is to store the color table in a shared_ptr and for all
454 // modified images to use the same table.
455 // It must, therefore, have a c_color "none" entry and g_color and
456 // m_color entries corresponding to each and every c_color entry
459 // 1. Create a copy of the color table.
460 // Add a c_color "none" entry to the table if it isn't already there.
461 bool const add_color = !contains_color_none(image);
465 ncolors_ = 1 + image.ncolors;
466 size_t const mem_size = sizeof(XpmColor) * ncolors_;
467 XpmColor * table = static_cast<XpmColor *>(malloc(mem_size));
469 copy_color_table(image.colorTable, image.ncolors, table);
471 XpmColor & color = table[ncolors_ - 1];
477 clone_c_string(unique_color_string(image).c_str());
478 color.c_color = clone_c_string("none");
480 free_color_table(image.colorTable, image.ncolors);
481 colorTable_.reset(table);
485 // Just move the pointer across
486 ncolors_ = image.ncolors;
487 colorTable_.reset(image.colorTable);
488 image.colorTable = 0;
491 // Clean-up the remaining entries of image.
497 // 2. Ensure that the color table has g_color and m_color entries
498 XpmColor * table = colorTable_.get();
500 for (size_t i = 0; i < ncolors_; ++i) {
501 XpmColor & entry = table[i];
505 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
506 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
507 string c_color = entry.c_color;
508 if (c_color[0] == '#' && c_color.size() != 7) {
509 c_color = convertTo7chars(c_color);
511 entry.c_color = clone_c_string(c_color.c_str());
514 // If the c_color is defined and the equivalent
515 // grayscale or monochrome ones are not, then define them.
516 mapcolor(entry.c_color, &entry.g_color, &entry.m_color);
521 XpmImage ImageXPM::Data::get() const
524 image.width = width_;
525 image.height = height_;
527 image.ncolors = ncolors_;
528 image.data = data_.get();
529 image.colorTable = colorTable_.get();
534 void ImageXPM::Data::resetData(int w, int h, unsigned int * d)
542 unsigned int * ImageXPM::Data::initialisedData(int w, int h) const
544 size_t const data_size = w * h;
546 size_t const mem_size = sizeof(unsigned int) * data_size;
547 unsigned int * ptr = static_cast<unsigned int *>(malloc(mem_size));
549 unsigned int none_id = color_none_id();
550 std::fill(ptr, ptr + data_size, none_id);
556 unsigned int ImageXPM::Data::color_none_id() const
558 XpmColor * table = colorTable_.get();
559 for (size_t i = 0; i < ncolors_; ++i) {
560 char const * const color = table[i].c_color;
561 if (color && ascii_lowercase(color) == "none")
571 // libXpm cannot cope with strings of the form #rrrrggggbbbb,
572 // #rrrgggbbb or #rgb, so convert them to #rrggbb.
573 string const convertTo7chars(string const & input)
575 string::size_type size = input.size();
576 if (size != 13 && size != 10 && size != 9 && size != 4)
577 // Can't deal with it.
581 // Can't deal with it.
584 string format(input);
587 case 13: // #rrrrggggbbbb
592 case 10: // #rrrgggbbb
601 format.insert(2, 1, '0');
602 format.insert(4, 1, '0');
603 format.append(1, '0');
611 // Given a string of the form #ff0571 create appropriate grayscale and
612 // monochrome colors.
613 void mapcolor(char const * c_color, char ** g_color_ptr, char ** m_color_ptr)
618 char * g_color = *g_color_ptr;
619 char * m_color = *m_color_ptr;
621 if (g_color && m_color)
625 Display * display = fl_get_display();
626 Colormap cmap = fl_state[fl_get_vclass()].colormap;
629 if (XLookupColor(display, cmap, c_color, &xcol, &ccol) == 0)
630 // Unable to parse c_color.
633 // Note that X stores the RGB values in the range 0 - 65535
634 // whilst we require them in the range 0 - 255.
635 int const r = xcol.red / 256;
636 int const g = xcol.green / 256;
637 int const b = xcol.blue / 256;
639 // This gives a good match to a human's RGB to luminance conversion.
640 // (From xv's Postscript code --- Mike Ressler.)
641 int const gray = int((0.32 * r) + (0.5 * g) + (0.18 * b));
643 ostringstream gray_stream;
644 gray_stream << "#" << std::setbase(16) << std::setfill('0')
645 << std::setw(2) << gray
646 << std::setw(2) << gray
647 << std::setw(2) << gray;
649 int const mono = (gray < 128) ? 0 : 255;
650 ostringstream mono_stream;
651 mono_stream << "#" << std::setbase(16) << std::setfill('0')
652 << std::setw(2) << mono
653 << std::setw(2) << mono
654 << std::setw(2) << mono;
656 // This string is going into an XpmImage struct, so create copies that
657 // libXPM can free successfully.
659 *g_color_ptr = clone_c_string(gray_stream.str().c_str());
661 *m_color_ptr = clone_c_string(mono_stream.str().c_str());
665 void copy_color_table(XpmColor const * in, size_t size, XpmColor * out)
667 for (size_t i = 0; i < size; ++i) {
668 out[i].string = clone_c_string(in[i].string);
669 out[i].symbolic = clone_c_string(in[i].symbolic);
670 out[i].m_color = clone_c_string(in[i].m_color);
671 out[i].g_color = clone_c_string(in[i].g_color);
672 out[i].g4_color = clone_c_string(in[i].g4_color);
673 out[i].c_color = clone_c_string(in[i].c_color);
678 void free_color_table(XpmColor * table, size_t size)
680 for (size_t i = 0; i < size; ++i) {
681 free(table[i].string);
682 free(table[i].symbolic);
683 free(table[i].m_color);
684 free(table[i].g_color);
685 free(table[i].g4_color);
686 free(table[i].c_color);
688 // Don't free the table itself. Let the shared_c_ptr do that.
693 char * clone_c_string(char const * in)
698 // Don't forget the '\0'
699 char * out = static_cast<char *>(malloc(strlen(in) + 1));
700 return strcpy(out, in);
704 bool contains_color_none(XpmImage const & image)
706 for (size_t i = 0; i < image.ncolors; ++i) {
707 char const * const color = image.colorTable[i].c_color;
708 if (color && ascii_lowercase(color) == "none")
715 string const unique_color_string(XpmImage const & image)
717 string id(image.cpp, ' ');
720 bool found_it = false;
721 for (size_t i = 0; i < image.ncolors; ++i) {
722 string const c_id = image.colorTable[i].string;
732 // Loop over the printable characters in the ASCII table.
733 // Ie, count from char 32 (' ') to char 126 ('~')
734 // A base 94 counter!
735 string::size_type current_index = id.size() - 1;
736 bool continue_loop = true;
737 while(continue_loop) {
738 continue_loop = false;
740 if (id[current_index] == 126) {
741 continue_loop = true;
742 if (current_index == 0)
743 // Unable to find a unique string
744 return image.colorTable[0].string;
746 id[current_index] = 32;
749 id[current_index] += 1;
750 // Note that '"' is an illegal char in this
752 if (id[current_index] == '"')
753 id[current_index] += 1;
757 // Unable to find a unique string