1 // ==========================================================
2 // XPM Loader and Writer
3 //
4 // Design and implementation by
5 // - Ryan Rubley (ryan@lostreality.org)
6 //
7 // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
8 // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
9 // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
10 // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
11 // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
12 // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
13 // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
14 // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
15 // THIS DISCLAIMER.
16 //
17 // Use at your own risk!
18 // ==========================================================
19 
20 #ifdef _MSC_VER
21 #pragma warning (disable : 4786) // identifier was truncated to 'number' characters
22 #endif
23 
24 // IMPLEMENTATION NOTES:
25 // ------------------------
26 // Initial design and implementation by
27 // - Karl-Heinz Bussian (khbussian@moss.de)
28 // - Herv� Drolon (drolon@infonie.fr)
29 // Completely rewritten from scratch by Ryan Rubley (ryan@lostreality.org)
30 // in order to address the following major fixes:
31 // * Supports any number of chars per pixel (not just 1 or 2)
32 // * Files with 2 chars per pixel but <= 256colors are loaded as 256 color (not 24bit)
33 // * Loads much faster, uses much less memory
34 // * supports #rgb #rrrgggbbb and #rrrrggggbbbb colors (not just #rrggbb)
35 // * supports symbolic color names
36 // ==========================================================
37 
38 #include "FreeImage.h"
39 #include "Utilities.h"
40 
41 // ==========================================================
42 // Plugin Interface
43 // ==========================================================
44 static int s_format_id;
45 
46 // ==========================================================
47 // Internal Functions
48 // ==========================================================
49 
50 // read in and skip all junk until we find a certain char
51 static BOOL
FindChar(FreeImageIO * io,fi_handle handle,BYTE look_for)52 FindChar(FreeImageIO *io, fi_handle handle, BYTE look_for) {
53 	BYTE c;
54 	io->read_proc(&c, sizeof(BYTE), 1, handle);
55 	while(c != look_for) {
56 		if( io->read_proc(&c, sizeof(BYTE), 1, handle) != 1 )
57 			return FALSE;
58 	}
59 	return TRUE;
60 }
61 
62 // find start of string, read data until ending quote found, allocate memory and return a string
63 static char *
ReadString(FreeImageIO * io,fi_handle handle)64 ReadString(FreeImageIO *io, fi_handle handle) {
65 	if( !FindChar(io, handle,'"') )
66 		return NULL;
67 	BYTE c;
68 	std::string s;
69 	io->read_proc(&c, sizeof(BYTE), 1, handle);
70 	while(c != '"') {
71 		s += c;
72 		if( io->read_proc(&c, sizeof(BYTE), 1, handle) != 1 )
73 			return NULL;
74 	}
75 	char *cstr = (char *)malloc(s.length()+1);
76 	strcpy(cstr,s.c_str());
77 	return cstr;
78 }
79 
80 static char *
Base92(unsigned int num)81 Base92(unsigned int num) {
82 	static char b92[16]; //enough for more then 64 bits
83 	static char digit[] = " .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjklzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|";
84 	b92[15] = '\0';
85 	int i = 14;
86 	do {
87 		b92[i--] = digit[num % 92];
88 		num /= 92;
89 	} while( num && i >= 0 );
90 	return b92+i+1;
91 }
92 
93 // ==========================================================
94 // Plugin Implementation
95 // ==========================================================
96 
97 static const char * DLL_CALLCONV
Format()98 Format() {
99 	return "XPM";
100 }
101 
102 static const char * DLL_CALLCONV
Description()103 Description() {
104 	return "X11 Pixmap Format";
105 }
106 
107 static const char * DLL_CALLCONV
Extension()108 Extension() {
109 	return "xpm";
110 }
111 
112 static const char * DLL_CALLCONV
RegExpr()113 RegExpr() {
114 	return "^[ \\t]*/\\* XPM \\*/[ \\t]$";
115 }
116 
117 static const char * DLL_CALLCONV
MimeType()118 MimeType() {
119 	return "image/x-xpixmap";
120 }
121 
122 static BOOL DLL_CALLCONV
Validate(FreeImageIO * io,fi_handle handle)123 Validate(FreeImageIO *io, fi_handle handle) {
124 	char buffer[256];
125 
126 	// checks the first 256 characters for the magic string
127 	int count = io->read_proc(buffer, 1, 256, handle);
128 	if(count <= 9) return FALSE;
129 	for(int i = 0; i < (count - 9); i++) {
130 		if(strncmp(&buffer[i], "/* XPM */", 9) == 0)
131 			return TRUE;
132 	}
133 	return FALSE;
134 }
135 
136 static BOOL DLL_CALLCONV
SupportsExportDepth(int depth)137 SupportsExportDepth(int depth) {
138 	return (
139 			(depth == 8) ||
140 			(depth == 24)
141 		);
142 }
143 
144 static BOOL DLL_CALLCONV
SupportsExportType(FREE_IMAGE_TYPE type)145 SupportsExportType(FREE_IMAGE_TYPE type) {
146 	return (type == FIT_BITMAP) ? TRUE : FALSE;
147 }
148 
149 static BOOL DLL_CALLCONV
SupportsNoPixels()150 SupportsNoPixels() {
151 	return TRUE;
152 }
153 
154 // ----------------------------------------------------------
155 
156 static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO * io,fi_handle handle,int page,int flags,void * data)157 Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
158 	char msg[256];
159     FIBITMAP *dib = NULL;
160 
161     if (!handle) return NULL;
162 
163     try {
164 		char *str;
165 
166 		BOOL header_only = (flags & FIF_LOAD_NOPIXELS) == FIF_LOAD_NOPIXELS;
167 
168 		//find the starting brace
169 		if( !FindChar(io, handle,'{') )
170 			throw "Could not find starting brace";
171 
172 		//read info string
173 		str = ReadString(io, handle);
174 		if(!str)
175 			throw "Error reading info string";
176 
177 		int width, height, colors, cpp;
178 		if( sscanf(str, "%d %d %d %d", &width, &height, &colors, &cpp) != 4 ) {
179 			free(str);
180 			throw "Improperly formed info string";
181 		}
182 		free(str);
183 
184 		// check info string
185 		if((width <= 0) || (height <= 0) || (colors <= 0) || (cpp <= 0)) {
186 			throw "Improperly formed info string";
187 		}
188 
189         if (colors > 256) {
190 			dib = FreeImage_AllocateHeader(header_only, width, height, 24, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK);
191 		} else {
192 			dib = FreeImage_AllocateHeader(header_only, width, height, 8);
193 		}
194 
195 		//build a map of color chars to rgb values
196 		std::map<std::string,FILE_RGBA> rawpal; //will store index in Alpha if 8bpp
197 		for(int i = 0; i < colors; i++ ) {
198 			FILE_RGBA rgba;
199 
200 			str = ReadString(io, handle);
201 			if(!str || (strlen(str) < (size_t)cpp))
202 				throw "Error reading color strings";
203 
204 			std::string chrs(str,cpp); //create a string for the color chars using the first cpp chars
205 			char *keys = str + cpp; //the color keys for these chars start after the first cpp chars
206 
207 			//translate all the tabs to spaces
208 			char *tmp = keys;
209 			while( strchr(tmp,'\t') ) {
210 				tmp = strchr(tmp,'\t');
211 				*tmp++ = ' ';
212 			}
213 
214 			//prefer the color visual
215 			if( strstr(keys," c ") ) {
216 				char *clr = strstr(keys," c ") + 3;
217 				while( *clr == ' ' ) clr++; //find the start of the hex rgb value
218 				if( *clr == '#' ) {
219 					int red = 0, green = 0, blue = 0, n;
220 					clr++;
221 					//end string at first space, if any found
222 					if( strchr(clr,' ') )
223 						*(strchr(clr,' ')) = '\0';
224 					//parse hex color, it can be #rgb #rrggbb #rrrgggbbb or #rrrrggggbbbb
225 					switch( strlen(clr) ) {
226 						case 3:	n = sscanf(clr,"%01x%01x%01x",&red,&green,&blue);
227 							red |= (red << 4);
228 							green |= (green << 4);
229 							blue |= (blue << 4);
230 							break;
231 						case 6:	n = sscanf(clr,"%02x%02x%02x",&red,&green,&blue);
232 							break;
233 						case 9:	n = sscanf(clr,"%03x%03x%03x",&red,&green,&blue);
234 							red >>= 4;
235 							green >>= 4;
236 							blue >>= 4;
237 							break;
238 						case 12: n = sscanf(clr,"%04x%04x%04x",&red,&green,&blue);
239 							red >>= 8;
240 							green >>= 8;
241 							blue >>= 8;
242 							break;
243 						default:
244 							n = 0;
245 							break;
246 					}
247 					if( n != 3 ) {
248 						free(str);
249 						throw "Improperly formed hex color value";
250 					}
251 					rgba.r = (BYTE)red;
252 					rgba.g = (BYTE)green;
253 					rgba.b = (BYTE)blue;
254 				} else if( !strncmp(clr,"None",4) || !strncmp(clr,"none",4) ) {
255 					rgba.r = rgba.g = rgba.b = 0xFF;
256 				} else {
257 					char *tmp = clr;
258 
259 					//scan forward for each space, if its " x " or " xx " end the string there
260 					//this means its probably some other visual data beyond that point and not
261 					//part of the color name.  How many named color end with a 1 or 2 character
262 					//word? Probably none in our list at least.
263 					while( (tmp = strchr(tmp,' ')) != NULL ) {
264 						if( tmp[1] != ' ' ) {
265 							if( (tmp[2] == ' ') || (tmp[2] != ' ' && tmp[3] == ' ') ) {
266 								tmp[0] = '\0';
267 								break;
268 							}
269 						}
270 						tmp++;
271 					}
272 
273 					//remove any trailing spaces
274 					tmp = clr+strlen(clr)-1;
275 					while( *tmp == ' ' ) {
276 						*tmp = '\0';
277 						tmp--;
278 					}
279 
280 					if (!FreeImage_LookupX11Color(clr,  &rgba.r, &rgba.g, &rgba.b)) {
281 						sprintf(msg, "Unknown color name '%s'", str);
282 						free(str);
283 						throw msg;
284 					}
285 				}
286 			} else {
287 				free(str);
288 				throw "Only color visuals are supported";
289 			}
290 
291 			//add color to map
292 			rgba.a = (BYTE)((colors > 256) ? 0 : i);
293 			rawpal[chrs] = rgba;
294 
295 			//build palette if needed
296 			if( colors <= 256 ) {
297 				RGBQUAD *pal = FreeImage_GetPalette(dib);
298 				pal[i].rgbBlue = rgba.b;
299 				pal[i].rgbGreen = rgba.g;
300 				pal[i].rgbRed = rgba.r;
301 			}
302 
303 			free(str);
304 		}
305 		//done parsing color map
306 
307 		if(header_only) {
308 			// header only mode
309 			return dib;
310 		}
311 
312 		//read in pixel data
313 		for(int y = 0; y < height; y++ ) {
314 			BYTE *line = FreeImage_GetScanLine(dib, height - y - 1);
315 			str = ReadString(io, handle);
316 			if(!str)
317 				throw "Error reading pixel strings";
318 			char *pixel_ptr = str;
319 
320 			for(int x = 0; x < width; x++ ) {
321 				//locate the chars in the color map
322 				std::string chrs(pixel_ptr,cpp);
323 				FILE_RGBA rgba = rawpal[chrs];
324 
325 				if( colors > 256 ) {
326 					line[FI_RGBA_BLUE] = rgba.b;
327 					line[FI_RGBA_GREEN] = rgba.g;
328 					line[FI_RGBA_RED] = rgba.r;
329 					line += 3;
330 				} else {
331 					*line = rgba.a;
332 					line++;
333 				}
334 
335 				pixel_ptr += cpp;
336 			}
337 
338 			free(str);
339 		}
340 		//done reading pixel data
341 
342 		return dib;
343 	} catch(const char *text) {
344        FreeImage_OutputMessageProc(s_format_id, text);
345 
346        if( dib != NULL )
347            FreeImage_Unload(dib);
348 
349        return NULL;
350     }
351 }
352 
353 static BOOL DLL_CALLCONV
Save(FreeImageIO * io,FIBITMAP * dib,fi_handle handle,int page,int flags,void * data)354 Save(FreeImageIO *io, FIBITMAP *dib, fi_handle handle, int page, int flags, void *data) {
355 	if ((dib != NULL) && (handle != NULL)) {
356 		char header[] = "/* XPM */\nstatic char *freeimage[] = {\n/* width height num_colors chars_per_pixel */\n\"",
357 		start_colors[] = "\",\n/* colors */\n\"",
358 		start_pixels[] = "\",\n/* pixels */\n\"",
359 		new_line[] = "\",\n\"",
360 		footer[] = "\"\n};\n",
361 		buf[256]; //256 is more then enough to sprintf 4 ints into, or the base-92 chars and #rrggbb line
362 
363 		if( io->write_proc(header, (unsigned int)strlen(header), 1, handle) != 1 )
364 			return FALSE;
365 
366 		int width = FreeImage_GetWidth(dib), height = FreeImage_GetHeight(dib), bpp = FreeImage_GetBPP(dib);
367 		RGBQUAD *pal = FreeImage_GetPalette(dib);
368 		int x,y;
369 
370 		//map base92 chrs to the rgb value to create the palette
371 		std::map<DWORD,FILE_RGB> chrs2color;
372 		//map 8bpp index or 24bpp rgb value to the base92 chrs to create pixel data
373 		typedef union {
374 			DWORD index;
375 			FILE_RGBA rgba;
376 		} DWORDRGBA;
377 		std::map<DWORD,std::string> color2chrs;
378 
379 		//loop thru entire dib, if new color, inc num_colors and add to both maps
380 		int num_colors = 0;
381 		for(y = 0; y < height; y++ ) {
382 			BYTE *line = FreeImage_GetScanLine(dib, height - y - 1);
383 			for(x = 0; x < width; x++ ) {
384 				FILE_RGB rgb;
385 				DWORDRGBA u;
386 				if( bpp > 8 ) {
387 					u.rgba.b = rgb.b = line[FI_RGBA_BLUE];
388 					u.rgba.g = rgb.g = line[FI_RGBA_GREEN];
389 					u.rgba.r = rgb.r = line[FI_RGBA_RED];
390 					u.rgba.a = 0;
391 					line += 3;
392 				} else {
393 					u.index = *line;
394 					rgb.b = pal[u.index].rgbBlue;
395 					rgb.g = pal[u.index].rgbGreen;
396 					rgb.r = pal[u.index].rgbRed;
397 					line++;
398 				}
399 				if( color2chrs.find(u.index) == color2chrs.end() ) { //new color
400 					std::string chrs(Base92(num_colors));
401 					color2chrs[u.index] = chrs;
402 					chrs2color[num_colors] = rgb;
403 					num_colors++;
404 				}
405 			}
406 		}
407 
408 		int cpp = (int)(log((double)num_colors)/log(92.0)) + 1;
409 
410 		sprintf(buf, "%d %d %d %d", FreeImage_GetWidth(dib), FreeImage_GetHeight(dib), num_colors, cpp );
411 		if( io->write_proc(buf, (unsigned int)strlen(buf), 1, handle) != 1 )
412 			return FALSE;
413 
414 		if( io->write_proc(start_colors, (unsigned int)strlen(start_colors), 1, handle) != 1 )
415 			return FALSE;
416 
417 		//write colors, using map of chrs->rgb
418 		for(x = 0; x < num_colors; x++ ) {
419 			sprintf(buf, "%*s c #%02x%02x%02x", cpp, Base92(x), chrs2color[x].r, chrs2color[x].g, chrs2color[x].b );
420 			if( io->write_proc(buf, (unsigned int)strlen(buf), 1, handle) != 1 )
421 				return FALSE;
422 			if( x == num_colors - 1 ) {
423 				if( io->write_proc(start_pixels, (unsigned int)strlen(start_pixels), 1, handle) != 1 )
424 					return FALSE;
425 			} else {
426 				if( io->write_proc(new_line, (unsigned int)strlen(new_line), 1, handle) != 1 )
427 					return FALSE;
428 			}
429 		}
430 
431 
432 		//write pixels, using map of rgb(if 24bpp) or index(if 8bpp)->chrs
433 		for(y = 0; y < height; y++ ) {
434 			BYTE *line = FreeImage_GetScanLine(dib, height - y - 1);
435 			for(x = 0; x < width; x++ ) {
436 				DWORDRGBA u;
437 				if( bpp > 8 ) {
438 					u.rgba.b = line[FI_RGBA_BLUE];
439 					u.rgba.g = line[FI_RGBA_GREEN];
440 					u.rgba.r = line[FI_RGBA_RED];
441 					u.rgba.a = 0;
442 					line += 3;
443 				} else {
444 					u.index = *line;
445 					line++;
446 				}
447 				sprintf(buf, "%*s", cpp, (char *)color2chrs[u.index].c_str());
448 				if( io->write_proc(buf, cpp, 1, handle) != 1 )
449 					return FALSE;
450 			}
451 			if( y == height - 1 ) {
452 				if( io->write_proc(footer, (unsigned int)strlen(footer), 1, handle) != 1 )
453 					return FALSE;
454 			} else {
455 				if( io->write_proc(new_line, (unsigned int)strlen(new_line), 1, handle) != 1 )
456 					return FALSE;
457 			}
458 		}
459 
460 		return TRUE;
461 	} else {
462 		return FALSE;
463 	}
464 }
465 
466 // ==========================================================
467 //   Init
468 // ==========================================================
469 
470 void DLL_CALLCONV
InitXPM(Plugin * plugin,int format_id)471 InitXPM(Plugin *plugin, int format_id)
472 {
473     s_format_id = format_id;
474 
475 	plugin->format_proc = Format;
476 	plugin->description_proc = Description;
477 	plugin->extension_proc = Extension;
478 	plugin->regexpr_proc = RegExpr;
479 	plugin->open_proc = NULL;
480 	plugin->close_proc = NULL;
481 	plugin->pagecount_proc = NULL;
482 	plugin->pagecapability_proc = NULL;
483 	plugin->load_proc = Load;
484 	plugin->save_proc = Save;
485 	plugin->validate_proc = Validate;
486 	plugin->mime_proc = MimeType;
487 	plugin->supports_export_bpp_proc = SupportsExportDepth;
488 	plugin->supports_export_type_proc = SupportsExportType;
489 	plugin->supports_icc_profiles_proc = NULL;
490 	plugin->supports_no_pixels_proc = SupportsNoPixels;
491 }
492 
493