rpng-x.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. /*---------------------------------------------------------------------------
  2. rpng - simple PNG display program rpng-x.c
  3. This program decodes and displays PNG images, with gamma correction and
  4. optionally with a user-specified background color (in case the image has
  5. transparency). It is very nearly the most basic PNG viewer possible.
  6. This version is for the X Window System (tested by author under Unix and
  7. by Martin Zinser under OpenVMS; may work under OS/2 with some tweaking).
  8. to do:
  9. - 8-bit (colormapped) X support
  10. - use %.1023s to simplify truncation of title-bar string?
  11. ---------------------------------------------------------------------------
  12. Changelog:
  13. - 1.01: initial public release
  14. - 1.02: modified to allow abbreviated options; fixed long/ulong mis-
  15. match; switched to png_jmpbuf() macro
  16. - 1.10: added support for non-default visuals; fixed X pixel-conversion
  17. - 1.11: added extra set of parentheses to png_jmpbuf() macro; fixed
  18. command-line parsing bug
  19. - 1.12: fixed some small X memory leaks (thanks to François Petitjean)
  20. - 1.13: fixed XFreeGC() crash bug (thanks to Patrick Welche)
  21. - 1.14: added support for X resources (thanks to Gerhard Niklasch)
  22. - 2.00: dual-licensed (added GNU GPL)
  23. - 2.01: fixed improper display of usage screen on PNG error(s)
  24. - 2.02: Added "void(argc);" statement to quiet pedantic compiler warnings
  25. about unused variable (GR-P)
  26. ---------------------------------------------------------------------------
  27. Copyright (c) 1998-2008 Greg Roelofs. All rights reserved.
  28. This software is provided "as is," without warranty of any kind,
  29. express or implied. In no event shall the author or contributors
  30. be held liable for any damages arising in any way from the use of
  31. this software.
  32. The contents of this file are DUAL-LICENSED. You may modify and/or
  33. redistribute this software according to the terms of one of the
  34. following two licenses (at your option):
  35. LICENSE 1 ("BSD-like with advertising clause"):
  36. Permission is granted to anyone to use this software for any purpose,
  37. including commercial applications, and to alter it and redistribute
  38. it freely, subject to the following restrictions:
  39. 1. Redistributions of source code must retain the above copyright
  40. notice, disclaimer, and this list of conditions.
  41. 2. Redistributions in binary form must reproduce the above copyright
  42. notice, disclaimer, and this list of conditions in the documenta-
  43. tion and/or other materials provided with the distribution.
  44. 3. All advertising materials mentioning features or use of this
  45. software must display the following acknowledgment:
  46. This product includes software developed by Greg Roelofs
  47. and contributors for the book, "PNG: The Definitive Guide,"
  48. published by O'Reilly and Associates.
  49. LICENSE 2 (GNU GPL v2 or later):
  50. This program is free software; you can redistribute it and/or modify
  51. it under the terms of the GNU General Public License as published by
  52. the Free Software Foundation; either version 2 of the License, or
  53. (at your option) any later version.
  54. This program is distributed in the hope that it will be useful,
  55. but WITHOUT ANY WARRANTY; without even the implied warranty of
  56. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  57. GNU General Public License for more details.
  58. You should have received a copy of the GNU General Public License
  59. along with this program; if not, write to the Free Software Foundation,
  60. Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  61. ---------------------------------------------------------------------------*/
  62. #define PROGNAME "rpng-x"
  63. #define LONGNAME "Simple PNG Viewer for X"
  64. #define VERSION "2.02 of 15 June 2014"
  65. #define RESNAME "rpng" /* our X resource application name */
  66. #define RESCLASS "Rpng" /* our X resource class name */
  67. #include <stdio.h>
  68. #include <stdlib.h>
  69. #include <string.h>
  70. #include <time.h>
  71. #include <X11/Xlib.h>
  72. #include <X11/Xutil.h>
  73. #include <X11/Xos.h>
  74. #include <X11/keysym.h>
  75. /* #define DEBUG : this enables the Trace() macros */
  76. #include "readpng.h" /* typedefs, common macros, readpng prototypes */
  77. /* could just include png.h, but this macro is the only thing we need
  78. * (name and typedefs changed to local versions); note that side effects
  79. * only happen with alpha (which could easily be avoided with
  80. * "ush acopy = (alpha);") */
  81. #define alpha_composite(composite, fg, alpha, bg) { \
  82. ush temp = ((ush)(fg)*(ush)(alpha) + \
  83. (ush)(bg)*(ush)(255 - (ush)(alpha)) + (ush)128); \
  84. (composite) = (uch)((temp + (temp >> 8)) >> 8); \
  85. }
  86. /* local prototypes */
  87. static int rpng_x_create_window(void);
  88. static int rpng_x_display_image(void);
  89. static void rpng_x_cleanup(void);
  90. static int rpng_x_msb(ulg u32val);
  91. static char titlebar[1024], *window_name = titlebar;
  92. static char *appname = LONGNAME;
  93. static char *icon_name = PROGNAME;
  94. static char *res_name = RESNAME;
  95. static char *res_class = RESCLASS;
  96. static char *filename;
  97. static FILE *infile;
  98. static char *bgstr;
  99. static uch bg_red=0, bg_green=0, bg_blue=0;
  100. static double display_exponent;
  101. static ulg image_width, image_height, image_rowbytes;
  102. static int image_channels;
  103. static uch *image_data;
  104. /* X-specific variables */
  105. static char *displayname;
  106. static XImage *ximage;
  107. static Display *display;
  108. static int depth;
  109. static Visual *visual;
  110. static XVisualInfo *visual_list;
  111. static int RShift, GShift, BShift;
  112. static ulg RMask, GMask, BMask;
  113. static Window window;
  114. static GC gc;
  115. static Colormap colormap;
  116. static int have_nondefault_visual = FALSE;
  117. static int have_colormap = FALSE;
  118. static int have_window = FALSE;
  119. static int have_gc = FALSE;
  120. /*
  121. ulg numcolors=0, pixels[256];
  122. ush reds[256], greens[256], blues[256];
  123. */
  124. int main(int argc, char **argv)
  125. {
  126. #ifdef sgi
  127. char tmpline[80];
  128. #endif
  129. char *p;
  130. int rc, alen, flen;
  131. int error = 0;
  132. int have_bg = FALSE;
  133. double LUT_exponent; /* just the lookup table */
  134. double CRT_exponent = 2.2; /* just the monitor */
  135. double default_display_exponent; /* whole display system */
  136. XEvent e;
  137. KeySym k;
  138. displayname = (char *)NULL;
  139. filename = (char *)NULL;
  140. /* First set the default value for our display-system exponent, i.e.,
  141. * the product of the CRT exponent and the exponent corresponding to
  142. * the frame-buffer's lookup table (LUT), if any. This is not an
  143. * exhaustive list of LUT values (e.g., OpenStep has a lot of weird
  144. * ones), but it should cover 99% of the current possibilities. */
  145. #if defined(NeXT)
  146. LUT_exponent = 1.0 / 2.2;
  147. /*
  148. if (some_next_function_that_returns_gamma(&next_gamma))
  149. LUT_exponent = 1.0 / next_gamma;
  150. */
  151. #elif defined(sgi)
  152. LUT_exponent = 1.0 / 1.7;
  153. /* there doesn't seem to be any documented function to get the
  154. * "gamma" value, so we do it the hard way */
  155. infile = fopen("/etc/config/system.glGammaVal", "r");
  156. if (infile) {
  157. double sgi_gamma;
  158. fgets(tmpline, 80, infile);
  159. fclose(infile);
  160. sgi_gamma = atof(tmpline);
  161. if (sgi_gamma > 0.0)
  162. LUT_exponent = 1.0 / sgi_gamma;
  163. }
  164. #elif defined(Macintosh)
  165. LUT_exponent = 1.8 / 2.61;
  166. /*
  167. if (some_mac_function_that_returns_gamma(&mac_gamma))
  168. LUT_exponent = mac_gamma / 2.61;
  169. */
  170. #else
  171. LUT_exponent = 1.0; /* assume no LUT: most PCs */
  172. #endif
  173. /* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */
  174. default_display_exponent = LUT_exponent * CRT_exponent;
  175. /* If the user has set the SCREEN_GAMMA environment variable as suggested
  176. * (somewhat imprecisely) in the libpng documentation, use that; otherwise
  177. * use the default value we just calculated. Either way, the user may
  178. * override this via a command-line option. */
  179. if ((p = getenv("SCREEN_GAMMA")) != NULL)
  180. display_exponent = atof(p);
  181. else
  182. display_exponent = default_display_exponent;
  183. /* Now parse the command line for options and the PNG filename. */
  184. while (*++argv && !error) {
  185. if (!strncmp(*argv, "-display", 2)) {
  186. if (!*++argv)
  187. ++error;
  188. else
  189. displayname = *argv;
  190. } else if (!strncmp(*argv, "-gamma", 2)) {
  191. if (!*++argv)
  192. ++error;
  193. else {
  194. display_exponent = atof(*argv);
  195. if (display_exponent <= 0.0)
  196. ++error;
  197. }
  198. } else if (!strncmp(*argv, "-bgcolor", 2)) {
  199. if (!*++argv)
  200. ++error;
  201. else {
  202. bgstr = *argv;
  203. if (strlen(bgstr) != 7 || bgstr[0] != '#')
  204. ++error;
  205. else
  206. have_bg = TRUE;
  207. }
  208. } else {
  209. if (**argv != '-') {
  210. filename = *argv;
  211. if (argv[1]) /* shouldn't be any more args after filename */
  212. ++error;
  213. } else
  214. ++error; /* not expecting any other options */
  215. }
  216. }
  217. if (!filename)
  218. ++error;
  219. /* print usage screen if any errors up to this point */
  220. if (error) {
  221. fprintf(stderr, "\n%s %s: %s\n", PROGNAME, VERSION, appname);
  222. readpng_version_info();
  223. fprintf(stderr, "\n"
  224. "Usage: %s [-display xdpy] [-gamma exp] [-bgcolor bg] file.png\n"
  225. " xdpy\tname of the target X display (e.g., ``hostname:0'')\n"
  226. " exp \ttransfer-function exponent (``gamma'') of the display\n"
  227. "\t\t system in floating-point format (e.g., ``%.1f''); equal\n",
  228. PROGNAME, default_display_exponent);
  229. fprintf(stderr, "\n"
  230. "\t\t to the product of the lookup-table exponent (varies)\n"
  231. "\t\t and the CRT exponent (usually 2.2); must be positive\n"
  232. " bg \tdesired background color in 7-character hex RGB format\n"
  233. "\t\t (e.g., ``#ff7700'' for orange: same as HTML colors);\n"
  234. "\t\t used with transparent images\n"
  235. "\nPress Q, Esc or mouse button 1 (within image window, after image\n"
  236. "is displayed) to quit.\n");
  237. exit(1);
  238. }
  239. if (!(infile = fopen(filename, "rb"))) {
  240. fprintf(stderr, PROGNAME ": can't open PNG file [%s]\n", filename);
  241. ++error;
  242. } else {
  243. if ((rc = readpng_init(infile, &image_width, &image_height)) != 0) {
  244. switch (rc) {
  245. case 1:
  246. fprintf(stderr, PROGNAME
  247. ": [%s] is not a PNG file: incorrect signature\n",
  248. filename);
  249. break;
  250. case 2:
  251. fprintf(stderr, PROGNAME
  252. ": [%s] has bad IHDR (libpng longjmp)\n", filename);
  253. break;
  254. case 4:
  255. fprintf(stderr, PROGNAME ": insufficient memory\n");
  256. break;
  257. default:
  258. fprintf(stderr, PROGNAME
  259. ": unknown readpng_init() error\n");
  260. break;
  261. }
  262. ++error;
  263. } else {
  264. display = XOpenDisplay(displayname);
  265. if (!display) {
  266. readpng_cleanup(TRUE);
  267. fprintf(stderr, PROGNAME ": can't open X display [%s]\n",
  268. displayname? displayname : "default");
  269. ++error;
  270. }
  271. }
  272. if (error)
  273. fclose(infile);
  274. }
  275. if (error) {
  276. fprintf(stderr, PROGNAME ": aborting.\n");
  277. exit(2);
  278. }
  279. /* set the title-bar string, but make sure buffer doesn't overflow */
  280. alen = strlen(appname);
  281. flen = strlen(filename);
  282. if (alen + flen + 3 > 1023)
  283. sprintf(titlebar, "%s: ...%s", appname, filename+(alen+flen+6-1023));
  284. else
  285. sprintf(titlebar, "%s: %s", appname, filename);
  286. /* if the user didn't specify a background color on the command line,
  287. * check for one in the PNG file--if not, the initialized values of 0
  288. * (black) will be used */
  289. if (have_bg) {
  290. unsigned r, g, b; /* this approach quiets compiler warnings */
  291. sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b);
  292. bg_red = (uch)r;
  293. bg_green = (uch)g;
  294. bg_blue = (uch)b;
  295. } else if (readpng_get_bgcolor(&bg_red, &bg_green, &bg_blue) > 1) {
  296. readpng_cleanup(TRUE);
  297. fprintf(stderr, PROGNAME
  298. ": libpng error while checking for background color\n");
  299. exit(2);
  300. }
  301. /* do the basic X initialization stuff, make the window and fill it
  302. * with the background color */
  303. if (rpng_x_create_window())
  304. exit(2);
  305. /* decode the image, all at once */
  306. Trace((stderr, "calling readpng_get_image()\n"))
  307. image_data = readpng_get_image(display_exponent, &image_channels,
  308. &image_rowbytes);
  309. Trace((stderr, "done with readpng_get_image()\n"))
  310. /* done with PNG file, so clean up to minimize memory usage (but do NOT
  311. * nuke image_data!) */
  312. readpng_cleanup(FALSE);
  313. fclose(infile);
  314. if (!image_data) {
  315. fprintf(stderr, PROGNAME ": unable to decode PNG image\n");
  316. exit(3);
  317. }
  318. /* display image (composite with background if requested) */
  319. Trace((stderr, "calling rpng_x_display_image()\n"))
  320. if (rpng_x_display_image()) {
  321. free(image_data);
  322. exit(4);
  323. }
  324. Trace((stderr, "done with rpng_x_display_image()\n"))
  325. /* wait for the user to tell us when to quit */
  326. printf(
  327. "Done. Press Q, Esc or mouse button 1 (within image window) to quit.\n");
  328. fflush(stdout);
  329. do
  330. XNextEvent(display, &e);
  331. while (!(e.type == ButtonPress && e.xbutton.button == Button1) &&
  332. !(e.type == KeyPress && /* v--- or 1 for shifted keys */
  333. ((k = XLookupKeysym(&e.xkey, 0)) == XK_q || k == XK_Escape) ));
  334. /* OK, we're done: clean up all image and X resources and go away */
  335. rpng_x_cleanup();
  336. (void)argc; /* Unused */
  337. return 0;
  338. }
  339. static int rpng_x_create_window(void)
  340. {
  341. uch *xdata;
  342. int need_colormap = FALSE;
  343. int screen, pad;
  344. ulg bg_pixel = 0L;
  345. ulg attrmask;
  346. Window root;
  347. XEvent e;
  348. XGCValues gcvalues;
  349. XSetWindowAttributes attr;
  350. XTextProperty windowName, *pWindowName = &windowName;
  351. XTextProperty iconName, *pIconName = &iconName;
  352. XVisualInfo visual_info;
  353. XSizeHints *size_hints;
  354. XWMHints *wm_hints;
  355. XClassHint *class_hints;
  356. screen = DefaultScreen(display);
  357. depth = DisplayPlanes(display, screen);
  358. root = RootWindow(display, screen);
  359. #ifdef DEBUG
  360. XSynchronize(display, True);
  361. #endif
  362. #if 0
  363. /* GRR: add 8-bit support */
  364. if (/* depth != 8 && */ depth != 16 && depth != 24 && depth != 32) {
  365. fprintf(stderr,
  366. "screen depth %d not supported (only 16-, 24- or 32-bit TrueColor)\n",
  367. depth);
  368. return 2;
  369. }
  370. XMatchVisualInfo(display, screen, depth,
  371. (depth == 8)? PseudoColor : TrueColor, &visual_info);
  372. visual = visual_info.visual;
  373. #else
  374. if (depth != 16 && depth != 24 && depth != 32) {
  375. int visuals_matched = 0;
  376. Trace((stderr, "default depth is %d: checking other visuals\n",
  377. depth))
  378. /* 24-bit first */
  379. visual_info.screen = screen;
  380. visual_info.depth = 24;
  381. visual_list = XGetVisualInfo(display,
  382. VisualScreenMask | VisualDepthMask, &visual_info, &visuals_matched);
  383. if (visuals_matched == 0) {
  384. /* GRR: add 15-, 16- and 32-bit TrueColor visuals (also DirectColor?) */
  385. fprintf(stderr, "default screen depth %d not supported, and no"
  386. " 24-bit visuals found\n", depth);
  387. return 2;
  388. }
  389. Trace((stderr, "XGetVisualInfo() returned %d 24-bit visuals\n",
  390. visuals_matched))
  391. visual = visual_list[0].visual;
  392. depth = visual_list[0].depth;
  393. /*
  394. colormap_size = visual_list[0].colormap_size;
  395. visual_class = visual->class;
  396. visualID = XVisualIDFromVisual(visual);
  397. */
  398. have_nondefault_visual = TRUE;
  399. need_colormap = TRUE;
  400. } else {
  401. XMatchVisualInfo(display, screen, depth, TrueColor, &visual_info);
  402. visual = visual_info.visual;
  403. }
  404. #endif
  405. RMask = visual->red_mask;
  406. GMask = visual->green_mask;
  407. BMask = visual->blue_mask;
  408. /* GRR: add/check 8-bit support */
  409. if (depth == 8 || need_colormap) {
  410. colormap = XCreateColormap(display, root, visual, AllocNone);
  411. if (!colormap) {
  412. fprintf(stderr, "XCreateColormap() failed\n");
  413. return 2;
  414. }
  415. have_colormap = TRUE;
  416. }
  417. if (depth == 15 || depth == 16) {
  418. RShift = 15 - rpng_x_msb(RMask); /* these are right-shifts */
  419. GShift = 15 - rpng_x_msb(GMask);
  420. BShift = 15 - rpng_x_msb(BMask);
  421. } else if (depth > 16) {
  422. #define NO_24BIT_MASKS
  423. #ifdef NO_24BIT_MASKS
  424. RShift = rpng_x_msb(RMask) - 7; /* these are left-shifts */
  425. GShift = rpng_x_msb(GMask) - 7;
  426. BShift = rpng_x_msb(BMask) - 7;
  427. #else
  428. RShift = 7 - rpng_x_msb(RMask); /* these are right-shifts, too */
  429. GShift = 7 - rpng_x_msb(GMask);
  430. BShift = 7 - rpng_x_msb(BMask);
  431. #endif
  432. }
  433. if (depth >= 15 && (RShift < 0 || GShift < 0 || BShift < 0)) {
  434. fprintf(stderr, "rpng internal logic error: negative X shift(s)!\n");
  435. return 2;
  436. }
  437. /*---------------------------------------------------------------------------
  438. Finally, create the window.
  439. ---------------------------------------------------------------------------*/
  440. attr.backing_store = Always;
  441. attr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask;
  442. attrmask = CWBackingStore | CWEventMask;
  443. if (have_nondefault_visual) {
  444. attr.colormap = colormap;
  445. attr.background_pixel = 0;
  446. attr.border_pixel = 1;
  447. attrmask |= CWColormap | CWBackPixel | CWBorderPixel;
  448. }
  449. window = XCreateWindow(display, root, 0, 0, image_width, image_height, 0,
  450. depth, InputOutput, visual, attrmask, &attr);
  451. if (window == None) {
  452. fprintf(stderr, "XCreateWindow() failed\n");
  453. return 2;
  454. } else
  455. have_window = TRUE;
  456. if (depth == 8)
  457. XSetWindowColormap(display, window, colormap);
  458. if (!XStringListToTextProperty(&window_name, 1, pWindowName))
  459. pWindowName = NULL;
  460. if (!XStringListToTextProperty(&icon_name, 1, pIconName))
  461. pIconName = NULL;
  462. /* OK if any hints allocation fails; XSetWMProperties() allows NULLs */
  463. if ((size_hints = XAllocSizeHints()) != NULL) {
  464. /* window will not be resizable */
  465. size_hints->flags = PMinSize | PMaxSize;
  466. size_hints->min_width = size_hints->max_width = (int)image_width;
  467. size_hints->min_height = size_hints->max_height = (int)image_height;
  468. }
  469. if ((wm_hints = XAllocWMHints()) != NULL) {
  470. wm_hints->initial_state = NormalState;
  471. wm_hints->input = True;
  472. /* wm_hints->icon_pixmap = icon_pixmap; */
  473. wm_hints->flags = StateHint | InputHint /* | IconPixmapHint */ ;
  474. }
  475. if ((class_hints = XAllocClassHint()) != NULL) {
  476. class_hints->res_name = res_name;
  477. class_hints->res_class = res_class;
  478. }
  479. XSetWMProperties(display, window, pWindowName, pIconName, NULL, 0,
  480. size_hints, wm_hints, class_hints);
  481. /* various properties and hints no longer needed; free memory */
  482. if (pWindowName)
  483. XFree(pWindowName->value);
  484. if (pIconName)
  485. XFree(pIconName->value);
  486. if (size_hints)
  487. XFree(size_hints);
  488. if (wm_hints)
  489. XFree(wm_hints);
  490. if (class_hints)
  491. XFree(class_hints);
  492. XMapWindow(display, window);
  493. gc = XCreateGC(display, window, 0, &gcvalues);
  494. have_gc = TRUE;
  495. /*---------------------------------------------------------------------------
  496. Fill window with the specified background color.
  497. ---------------------------------------------------------------------------*/
  498. if (depth == 24 || depth == 32) {
  499. bg_pixel = ((ulg)bg_red << RShift) |
  500. ((ulg)bg_green << GShift) |
  501. ((ulg)bg_blue << BShift);
  502. } else if (depth == 16) {
  503. bg_pixel = ((((ulg)bg_red << 8) >> RShift) & RMask) |
  504. ((((ulg)bg_green << 8) >> GShift) & GMask) |
  505. ((((ulg)bg_blue << 8) >> BShift) & BMask);
  506. } else /* depth == 8 */ {
  507. /* GRR: add 8-bit support */
  508. }
  509. XSetForeground(display, gc, bg_pixel);
  510. XFillRectangle(display, window, gc, 0, 0, image_width, image_height);
  511. /*---------------------------------------------------------------------------
  512. Wait for first Expose event to do any drawing, then flush.
  513. ---------------------------------------------------------------------------*/
  514. do
  515. XNextEvent(display, &e);
  516. while (e.type != Expose || e.xexpose.count);
  517. XFlush(display);
  518. /*---------------------------------------------------------------------------
  519. Allocate memory for the X- and display-specific version of the image.
  520. ---------------------------------------------------------------------------*/
  521. if (depth == 24 || depth == 32) {
  522. xdata = (uch *)malloc(4*image_width*image_height);
  523. pad = 32;
  524. } else if (depth == 16) {
  525. xdata = (uch *)malloc(2*image_width*image_height);
  526. pad = 16;
  527. } else /* depth == 8 */ {
  528. xdata = (uch *)malloc(image_width*image_height);
  529. pad = 8;
  530. }
  531. if (!xdata) {
  532. fprintf(stderr, PROGNAME ": unable to allocate image memory\n");
  533. return 4;
  534. }
  535. ximage = XCreateImage(display, visual, depth, ZPixmap, 0,
  536. (char *)xdata, image_width, image_height, pad, 0);
  537. if (!ximage) {
  538. fprintf(stderr, PROGNAME ": XCreateImage() failed\n");
  539. free(xdata);
  540. return 3;
  541. }
  542. /* to avoid testing the byte order every pixel (or doubling the size of
  543. * the drawing routine with a giant if-test), we arbitrarily set the byte
  544. * order to MSBFirst and let Xlib worry about inverting things on little-
  545. * endian machines (like Linux/x86, old VAXen, etc.)--this is not the most
  546. * efficient approach (the giant if-test would be better), but in the
  547. * interest of clarity, we take the easy way out... */
  548. ximage->byte_order = MSBFirst;
  549. return 0;
  550. } /* end function rpng_x_create_window() */
  551. static int rpng_x_display_image(void)
  552. {
  553. uch *src;
  554. char *dest;
  555. uch r, g, b, a;
  556. ulg i, row, lastrow = 0;
  557. ulg pixel;
  558. int ximage_rowbytes = ximage->bytes_per_line;
  559. /* int bpp = ximage->bits_per_pixel; */
  560. Trace((stderr, "beginning display loop (image_channels == %d)\n",
  561. image_channels))
  562. Trace((stderr, " (width = %ld, rowbytes = %ld, ximage_rowbytes = %d)\n",
  563. image_width, image_rowbytes, ximage_rowbytes))
  564. Trace((stderr, " (bpp = %d)\n", ximage->bits_per_pixel))
  565. Trace((stderr, " (byte_order = %s)\n", ximage->byte_order == MSBFirst?
  566. "MSBFirst" : (ximage->byte_order == LSBFirst? "LSBFirst" : "unknown")))
  567. if (depth == 24 || depth == 32) {
  568. ulg red, green, blue;
  569. for (lastrow = row = 0; row < image_height; ++row) {
  570. src = image_data + row*image_rowbytes;
  571. dest = ximage->data + row*ximage_rowbytes;
  572. if (image_channels == 3) {
  573. for (i = image_width; i > 0; --i) {
  574. red = *src++;
  575. green = *src++;
  576. blue = *src++;
  577. #ifdef NO_24BIT_MASKS
  578. pixel = (red << RShift) |
  579. (green << GShift) |
  580. (blue << BShift);
  581. /* recall that we set ximage->byte_order = MSBFirst above */
  582. /* GRR BUG: this assumes bpp == 32, but may be 24: */
  583. *dest++ = (char)((pixel >> 24) & 0xff);
  584. *dest++ = (char)((pixel >> 16) & 0xff);
  585. *dest++ = (char)((pixel >> 8) & 0xff);
  586. *dest++ = (char)( pixel & 0xff);
  587. #else
  588. red = (RShift < 0)? red << (-RShift) : red >> RShift;
  589. green = (GShift < 0)? green << (-GShift) : green >> GShift;
  590. blue = (BShift < 0)? blue << (-BShift) : blue >> BShift;
  591. pixel = (red & RMask) | (green & GMask) | (blue & BMask);
  592. /* recall that we set ximage->byte_order = MSBFirst above */
  593. *dest++ = (char)((pixel >> 24) & 0xff);
  594. *dest++ = (char)((pixel >> 16) & 0xff);
  595. *dest++ = (char)((pixel >> 8) & 0xff);
  596. *dest++ = (char)( pixel & 0xff);
  597. #endif
  598. }
  599. } else /* if (image_channels == 4) */ {
  600. for (i = image_width; i > 0; --i) {
  601. r = *src++;
  602. g = *src++;
  603. b = *src++;
  604. a = *src++;
  605. if (a == 255) {
  606. red = r;
  607. green = g;
  608. blue = b;
  609. } else if (a == 0) {
  610. red = bg_red;
  611. green = bg_green;
  612. blue = bg_blue;
  613. } else {
  614. /* this macro (from png.h) composites the foreground
  615. * and background values and puts the result into the
  616. * first argument */
  617. alpha_composite(red, r, a, bg_red);
  618. alpha_composite(green, g, a, bg_green);
  619. alpha_composite(blue, b, a, bg_blue);
  620. }
  621. pixel = (red << RShift) |
  622. (green << GShift) |
  623. (blue << BShift);
  624. /* recall that we set ximage->byte_order = MSBFirst above */
  625. *dest++ = (char)((pixel >> 24) & 0xff);
  626. *dest++ = (char)((pixel >> 16) & 0xff);
  627. *dest++ = (char)((pixel >> 8) & 0xff);
  628. *dest++ = (char)( pixel & 0xff);
  629. }
  630. }
  631. /* display after every 16 lines */
  632. if (((row+1) & 0xf) == 0) {
  633. XPutImage(display, window, gc, ximage, 0, (int)lastrow, 0,
  634. (int)lastrow, image_width, 16);
  635. XFlush(display);
  636. lastrow = row + 1;
  637. }
  638. }
  639. } else if (depth == 16) {
  640. ush red, green, blue;
  641. for (lastrow = row = 0; row < image_height; ++row) {
  642. src = image_data + row*image_rowbytes;
  643. dest = ximage->data + row*ximage_rowbytes;
  644. if (image_channels == 3) {
  645. for (i = image_width; i > 0; --i) {
  646. red = ((ush)(*src) << 8);
  647. ++src;
  648. green = ((ush)(*src) << 8);
  649. ++src;
  650. blue = ((ush)(*src) << 8);
  651. ++src;
  652. pixel = ((red >> RShift) & RMask) |
  653. ((green >> GShift) & GMask) |
  654. ((blue >> BShift) & BMask);
  655. /* recall that we set ximage->byte_order = MSBFirst above */
  656. *dest++ = (char)((pixel >> 8) & 0xff);
  657. *dest++ = (char)( pixel & 0xff);
  658. }
  659. } else /* if (image_channels == 4) */ {
  660. for (i = image_width; i > 0; --i) {
  661. r = *src++;
  662. g = *src++;
  663. b = *src++;
  664. a = *src++;
  665. if (a == 255) {
  666. red = ((ush)r << 8);
  667. green = ((ush)g << 8);
  668. blue = ((ush)b << 8);
  669. } else if (a == 0) {
  670. red = ((ush)bg_red << 8);
  671. green = ((ush)bg_green << 8);
  672. blue = ((ush)bg_blue << 8);
  673. } else {
  674. /* this macro (from png.h) composites the foreground
  675. * and background values and puts the result back into
  676. * the first argument (== fg byte here: safe) */
  677. alpha_composite(r, r, a, bg_red);
  678. alpha_composite(g, g, a, bg_green);
  679. alpha_composite(b, b, a, bg_blue);
  680. red = ((ush)r << 8);
  681. green = ((ush)g << 8);
  682. blue = ((ush)b << 8);
  683. }
  684. pixel = ((red >> RShift) & RMask) |
  685. ((green >> GShift) & GMask) |
  686. ((blue >> BShift) & BMask);
  687. /* recall that we set ximage->byte_order = MSBFirst above */
  688. *dest++ = (char)((pixel >> 8) & 0xff);
  689. *dest++ = (char)( pixel & 0xff);
  690. }
  691. }
  692. /* display after every 16 lines */
  693. if (((row+1) & 0xf) == 0) {
  694. XPutImage(display, window, gc, ximage, 0, (int)lastrow, 0,
  695. (int)lastrow, image_width, 16);
  696. XFlush(display);
  697. lastrow = row + 1;
  698. }
  699. }
  700. } else /* depth == 8 */ {
  701. /* GRR: add 8-bit support */
  702. }
  703. Trace((stderr, "calling final XPutImage()\n"))
  704. if (lastrow < image_height) {
  705. XPutImage(display, window, gc, ximage, 0, (int)lastrow, 0,
  706. (int)lastrow, image_width, image_height-lastrow);
  707. XFlush(display);
  708. }
  709. return 0;
  710. }
  711. static void rpng_x_cleanup(void)
  712. {
  713. if (image_data) {
  714. free(image_data);
  715. image_data = NULL;
  716. }
  717. if (ximage) {
  718. if (ximage->data) {
  719. free(ximage->data); /* we allocated it, so we free it */
  720. ximage->data = (char *)NULL; /* instead of XDestroyImage() */
  721. }
  722. XDestroyImage(ximage);
  723. ximage = NULL;
  724. }
  725. if (have_gc)
  726. XFreeGC(display, gc);
  727. if (have_window)
  728. XDestroyWindow(display, window);
  729. if (have_colormap)
  730. XFreeColormap(display, colormap);
  731. if (have_nondefault_visual)
  732. XFree(visual_list);
  733. }
  734. static int rpng_x_msb(ulg u32val)
  735. {
  736. int i;
  737. for (i = 31; i >= 0; --i) {
  738. if (u32val & 0x80000000L)
  739. break;
  740. u32val <<= 1;
  741. }
  742. return i;
  743. }