rpng-x.c 30 KB

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