1 /* Copyright 2011, 2012 Bert Muennich
2  *
3  * This file is a part of nsxiv.
4  *
5  * nsxiv is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published
7  * by the Free Software Foundation; either version 2 of the License,
8  * or (at your option) any later version.
9  *
10  * nsxiv is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with nsxiv.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #include "nsxiv.h"
20 #define _IMAGE_CONFIG
21 #include "config.h"
22 
23 #include <errno.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29 
30 #if HAVE_LIBEXIF
31 #include <libexif/exif-data.h>
32 #endif
33 
34 #if HAVE_LIBGIF
35 #include <gif_lib.h>
36 enum { DEF_GIF_DELAY = 75 };
37 #endif
38 
39 #if HAVE_LIBWEBP
40 #include <webp/decode.h>
41 #include <webp/demux.h>
42 enum { DEF_WEBP_DELAY = 75 };
43 #endif
44 
img_init(img_t * img,win_t * win)45 void img_init(img_t *img, win_t *win)
46 {
47 	imlib_context_set_display(win->env.dpy);
48 	imlib_context_set_visual(win->env.vis);
49 	imlib_context_set_colormap(win->env.cmap);
50 
51 	img->im = NULL;
52 	img->win = win;
53 	img->scalemode = options->scalemode;
54 	img->zoom = options->zoom;
55 	img->zoom = MAX(img->zoom, ZOOM_MIN);
56 	img->zoom = MIN(img->zoom, ZOOM_MAX);
57 	img->checkpan = false;
58 	img->dirty = false;
59 	img->aa = ANTI_ALIAS;
60 	img->alpha = ALPHA_LAYER;
61 	img->multi.cap = img->multi.cnt = 0;
62 	img->multi.animate = options->animate;
63 	img->multi.framedelay = options->framerate > 0 ? 1000 / options->framerate : 0;
64 	img->multi.length = 0;
65 
66 	img->cmod = imlib_create_color_modifier();
67 	imlib_context_set_color_modifier(img->cmod);
68 	img_change_gamma(img, options->gamma);
69 
70 	img->ss.on = options->slideshow > 0;
71 	img->ss.delay = options->slideshow > 0 ? options->slideshow : SLIDESHOW_DELAY * 10;
72 }
73 
74 #if HAVE_LIBEXIF
exif_auto_orientate(const fileinfo_t * file)75 void exif_auto_orientate(const fileinfo_t *file)
76 {
77 	ExifData *ed;
78 	ExifEntry *entry;
79 	int byte_order, orientation = 0;
80 
81 	if ((ed = exif_data_new_from_file(file->path)) == NULL)
82 		return;
83 	byte_order = exif_data_get_byte_order(ed);
84 	entry = exif_content_get_entry(ed->ifd[EXIF_IFD_0], EXIF_TAG_ORIENTATION);
85 	if (entry != NULL)
86 		orientation = exif_get_short(entry->data, byte_order);
87 	exif_data_unref(ed);
88 
89 	switch (orientation) {
90 		case 5:
91 			imlib_image_orientate(1);
92 		case 2:
93 			imlib_image_flip_vertical();
94 			break;
95 		case 3:
96 			imlib_image_orientate(2);
97 			break;
98 		case 7:
99 			imlib_image_orientate(1);
100 		case 4:
101 			imlib_image_flip_horizontal();
102 			break;
103 		case 6:
104 			imlib_image_orientate(1);
105 			break;
106 		case 8:
107 			imlib_image_orientate(3);
108 			break;
109 	}
110 }
111 #endif
112 
113 #if HAVE_LIBGIF
img_load_gif(img_t * img,const fileinfo_t * file)114 bool img_load_gif(img_t *img, const fileinfo_t *file)
115 {
116 	GifFileType *gif;
117 	GifRowType *rows = NULL;
118 	GifRecordType rec;
119 	ColorMapObject *cmap;
120 	DATA32 bgpixel, *data, *ptr;
121 	DATA32 *prev_frame = NULL;
122 	Imlib_Image im;
123 	int i, j, bg, r, g, b;
124 	int x, y, w, h, sw, sh;
125 	int px, py, pw, ph;
126 	int intoffset[] = { 0, 4, 2, 1 };
127 	int intjump[] = { 8, 8, 4, 2 };
128 	int transp = -1;
129 	unsigned int disposal = 0, prev_disposal = 0;
130 	unsigned int delay = 0;
131 	bool err = false;
132 
133 	if (img->multi.cap == 0) {
134 		img->multi.cap = 8;
135 		img->multi.frames = (img_frame_t*)
136 		                    emalloc(sizeof(img_frame_t) * img->multi.cap);
137 	}
138 	img->multi.cnt = img->multi.sel = 0;
139 	img->multi.length = 0;
140 
141 #if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5
142 	gif = DGifOpenFileName(file->path, NULL);
143 #else
144 	gif = DGifOpenFileName(file->path);
145 #endif
146 	if (gif == NULL) {
147 		error(0, 0, "%s: Error opening gif image", file->name);
148 		return false;
149 	}
150 	bg = gif->SBackGroundColor;
151 	sw = gif->SWidth;
152 	sh = gif->SHeight;
153 	px = py = pw = ph = 0;
154 
155 	do {
156 		if (DGifGetRecordType(gif, &rec) == GIF_ERROR) {
157 			err = true;
158 			break;
159 		}
160 		if (rec == EXTENSION_RECORD_TYPE) {
161 			int ext_code;
162 			GifByteType *ext = NULL;
163 
164 			DGifGetExtension(gif, &ext_code, &ext);
165 			while (ext) {
166 				if (ext_code == GRAPHICS_EXT_FUNC_CODE) {
167 					if (ext[1] & 1)
168 						transp = (int) ext[4];
169 					else
170 						transp = -1;
171 
172 					delay = 10 * ((unsigned int) ext[3] << 8 | (unsigned int) ext[2]);
173 					disposal = (unsigned int) ext[1] >> 2 & 0x7;
174 				}
175 				ext = NULL;
176 				DGifGetExtensionNext(gif, &ext);
177 			}
178 		} else if (rec == IMAGE_DESC_RECORD_TYPE) {
179 			if (DGifGetImageDesc(gif) == GIF_ERROR) {
180 				err = true;
181 				break;
182 			}
183 			x = gif->Image.Left;
184 			y = gif->Image.Top;
185 			w = gif->Image.Width;
186 			h = gif->Image.Height;
187 
188 			rows = (GifRowType*) emalloc(h * sizeof(GifRowType));
189 			for (i = 0; i < h; i++)
190 				rows[i] = (GifRowType) emalloc(w * sizeof(GifPixelType));
191 			if (gif->Image.Interlace) {
192 				for (i = 0; i < 4; i++) {
193 					for (j = intoffset[i]; j < h; j += intjump[i])
194 						DGifGetLine(gif, rows[j], w);
195 				}
196 			} else {
197 				for (i = 0; i < h; i++)
198 					DGifGetLine(gif, rows[i], w);
199 			}
200 
201 			ptr = data = (DATA32*) emalloc(sizeof(DATA32) * sw * sh);
202 			cmap = gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap;
203 			if (bg >= cmap->ColorCount) {
204 				err = true;
205 				break;
206 			}
207 			r = cmap->Colors[bg].Red;
208 			g = cmap->Colors[bg].Green;
209 			b = cmap->Colors[bg].Blue;
210 			bgpixel = 0x00ffffff & (r << 16 | g << 8 | b);
211 
212 			for (i = 0; i < sh; i++) {
213 				for (j = 0; j < sw; j++) {
214 					if (i < y || i >= y + h || j < x || j >= x + w ||
215 					    rows[i-y][j-x] == transp)
216 					{
217 						if (prev_frame != NULL && (prev_disposal != 2 ||
218 						    i < py || i >= py + ph || j < px || j >= px + pw))
219 						{
220 							*ptr = prev_frame[i * sw + j];
221 						} else {
222 							*ptr = bgpixel;
223 						}
224 					} else {
225 						r = cmap->Colors[rows[i-y][j-x]].Red;
226 						g = cmap->Colors[rows[i-y][j-x]].Green;
227 						b = cmap->Colors[rows[i-y][j-x]].Blue;
228 						*ptr = 0xffu << 24 | r << 16 | g << 8 | b;
229 					}
230 					ptr++;
231 				}
232 			}
233 
234 			im = imlib_create_image_using_copied_data(sw, sh, data);
235 
236 			for (i = 0; i < h; i++)
237 				free(rows[i]);
238 			free(rows);
239 			free(data);
240 
241 			if (im == NULL) {
242 				err = true;
243 				break;
244 			}
245 
246 			imlib_context_set_image(im);
247 			imlib_image_set_format("gif");
248 			if (transp >= 0)
249 				imlib_image_set_has_alpha(1);
250 
251 			if (disposal != 3)
252 				prev_frame = imlib_image_get_data_for_reading_only();
253 			prev_disposal = disposal;
254 			px = x, py = y, pw = w, ph = h;
255 
256 			if (img->multi.cnt == img->multi.cap) {
257 				img->multi.cap *= 2;
258 				img->multi.frames = (img_frame_t*)
259 				                    erealloc(img->multi.frames,
260 				                             img->multi.cap * sizeof(img_frame_t));
261 			}
262 			img->multi.frames[img->multi.cnt].im = im;
263 			delay = img->multi.framedelay > 0 ? img->multi.framedelay : delay;
264 			img->multi.frames[img->multi.cnt].delay = delay > 0 ? delay : DEF_GIF_DELAY;
265 			img->multi.length += img->multi.frames[img->multi.cnt].delay;
266 			img->multi.cnt++;
267 		}
268 	} while (rec != TERMINATE_RECORD_TYPE);
269 
270 #if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5 && GIFLIB_MINOR >= 1
271 	DGifCloseFile(gif, NULL);
272 #else
273 	DGifCloseFile(gif);
274 #endif
275 
276 	if (err && (file->flags & FF_WARN))
277 		error(0, 0, "%s: Corrupted gif file", file->name);
278 
279 	if (img->multi.cnt > 1) {
280 		imlib_context_set_image(img->im);
281 		imlib_free_image();
282 		img->im = img->multi.frames[0].im;
283 	} else if (img->multi.cnt == 1) {
284 		imlib_context_set_image(img->multi.frames[0].im);
285 		imlib_free_image();
286 		img->multi.cnt = 0;
287 	}
288 
289 	imlib_context_set_image(img->im);
290 
291 	return !err;
292 }
293 #endif /* HAVE_LIBGIF */
294 
295 
296 #if HAVE_LIBWEBP
is_webp(const char * path)297 bool is_webp(const char *path)
298 {
299 	/* The size (in bytes) of the largest amount of data required to verify a WebP image. */
300 	enum { max = 30 };
301 	const unsigned char fmt[max];
302 	bool ret = false;
303 	FILE *f;
304 
305 	if ((f = fopen(path, "rb")) != NULL) {
306 		if (fread((unsigned char *) fmt, 1, max, f) == max)
307 			ret = WebPGetInfo(fmt, max, NULL, NULL);
308 		fclose(f);
309 	}
310 	return ret;
311 }
312 
313 /* fframe   img
314  * NULL     NULL  = do nothing
315  * x        NULL  = load the first frame as an Imlib_Image
316  * NULL     x     = load all frames into img->multi.
317  */
img_load_webp(const fileinfo_t * file,Imlib_Image * fframe,img_t * img)318 bool img_load_webp(const fileinfo_t *file, Imlib_Image *fframe, img_t *img)
319 {
320 	FILE *webp_file;
321 	WebPData data;
322 	data.bytes = NULL;
323 
324 	Imlib_Image im = NULL;
325 	struct WebPAnimDecoderOptions opts;
326 	WebPAnimDecoder *dec = NULL;
327 	struct WebPAnimInfo info;
328 	unsigned char *buf = NULL;
329 	int ts;
330 	const WebPDemuxer *demux;
331 	WebPIterator iter;
332 	unsigned long flags;
333 	unsigned int delay;
334 	bool err = false;
335 
336 	if ((err = fframe == NULL && img == NULL))
337 		goto fail;
338 
339 	if ((err = (webp_file = fopen(file->path, "rb")) == NULL)) {
340 		error(0, 0, "%s: Error opening webp image", file->name);
341 		goto fail;
342 	}
343 	fseek(webp_file, 0L, SEEK_END);
344 	data.size = ftell(webp_file);
345 	rewind(webp_file);
346 	data.bytes = emalloc(data.size);
347 	if ((err = fread((unsigned char *)data.bytes, 1, data.size, webp_file) != data.size)) {
348 		error(0, 0, "%s: Error reading webp image", file->name);
349 		goto fail;
350 	}
351 
352 	/* Setup the WebP Animation Decoder */
353 	if ((err = !WebPAnimDecoderOptionsInit(&opts))) {
354 		error(0, 0, "%s: WebP library version mismatch", file->name);
355 		goto fail;
356 	}
357 	opts.color_mode = MODE_BGRA;
358 	/* NOTE: Multi-threaded decoding may cause problems on some system */
359 	opts.use_threads = true;
360 	dec = WebPAnimDecoderNew(&data, &opts);
361 	if ((err = (dec == NULL) || !WebPAnimDecoderGetInfo(dec, &info))) {
362 		error(0, 0, "%s: WebP parsing or memory error (file is corrupt?)", file->name);
363 		goto fail;
364 	}
365 	demux = WebPAnimDecoderGetDemuxer(dec);
366 
367 	if (img == NULL) { /* Only get the first frame and put it into fframe. */
368 		if ((err = !WebPAnimDecoderGetNext(dec, &buf, &ts))) {
369 			error(0, 0, "%s: Error loading first frame", file->name);
370 			goto fail;
371 		}
372 		*fframe = imlib_create_image_using_copied_data(
373 		          info.canvas_width, info.canvas_height, (DATA32*)buf);
374 		imlib_context_set_image(*fframe);
375 		imlib_image_set_has_alpha(WebPDemuxGetI(demux, WEBP_FF_FORMAT_FLAGS) & ALPHA_FLAG);
376 	} else {
377 		/* Get global information for the image */
378 		flags = WebPDemuxGetI(demux, WEBP_FF_FORMAT_FLAGS);
379 		img->w = WebPDemuxGetI(demux, WEBP_FF_CANVAS_WIDTH);
380 		img->h = WebPDemuxGetI(demux, WEBP_FF_CANVAS_HEIGHT);
381 		img->multi.cap = info.frame_count;
382 		img->multi.sel = 0;
383 		img->multi.frames = emalloc(info.frame_count * sizeof(img_frame_t));
384 
385 		/* Load and decode frames (also works on images with only 1 frame) */
386 		img->multi.cnt = 0;
387 		while (WebPAnimDecoderGetNext(dec, &buf, &ts)) {
388 			im = imlib_create_image_using_copied_data(
389 			     info.canvas_width, info.canvas_height, (DATA32*)buf);
390 			imlib_context_set_image(im);
391 			imlib_image_set_format("webp");
392 			/* Get an iterator of this frame - used for frame info (duration, etc.) */
393 			WebPDemuxGetFrame(demux, img->multi.cnt+1, &iter);
394 			imlib_image_set_has_alpha((flags & ALPHA_FLAG) == ALPHA_FLAG);
395 			/* Store info for this frame */
396 			img->multi.frames[img->multi.cnt].im = im;
397 			delay = iter.duration > 0 ? iter.duration : DEF_WEBP_DELAY;
398 			img->multi.frames[img->multi.cnt].delay = delay;
399 			img->multi.length += img->multi.frames[img->multi.cnt].delay;
400 			img->multi.cnt++;
401 		}
402 		WebPDemuxReleaseIterator(&iter);
403 
404 		if (img->multi.cnt > 1) {
405 			imlib_context_set_image(img->im);
406 			imlib_free_image();
407 			img->im = img->multi.frames[0].im;
408 		} else if (img->multi.cnt == 1) {
409 			imlib_context_set_image(img->multi.frames[0].im);
410 			imlib_free_image();
411 			img->multi.cnt = 0;
412 		}
413 		imlib_context_set_image(img->im);
414 	}
415 	imlib_image_set_format("webp");
416 fail:
417 	if (dec != NULL)
418 		WebPAnimDecoderDelete(dec);
419 	free((unsigned char *)data.bytes);
420 	return !err;
421 }
422 #endif /* HAVE_LIBWEBP */
423 
img_open(const fileinfo_t * file)424 Imlib_Image img_open(const fileinfo_t *file)
425 {
426 	struct stat st;
427 	Imlib_Image im = NULL;
428 
429 	if (access(file->path, R_OK) == 0 &&
430 	    stat(file->path, &st) == 0 && S_ISREG(st.st_mode))
431 	{
432 #if HAVE_LIBWEBP
433 		if (is_webp(file->path))
434 			img_load_webp(file, &im, NULL);
435 		else
436 #endif
437 			im = imlib_load_image(file->path);
438 		if (im != NULL) {
439 			imlib_context_set_image(im);
440 #if HAVE_LIBWEBP
441 			const char *fmt;
442 			if ((fmt = imlib_image_format()) != NULL && !STREQ(fmt, "webp") &&
443 			    imlib_image_get_data_for_reading_only() == NULL) {
444 #else
445 			if (imlib_image_get_data_for_reading_only() == NULL) {
446 #endif
447 				imlib_free_image();
448 				im = NULL;
449 			}
450 		}
451 	}
452 	if (im == NULL && (file->flags & FF_WARN))
453 		error(0, 0, "%s: Error opening image", file->name);
454 	return im;
455 }
456 
457 bool img_load(img_t *img, const fileinfo_t *file)
458 {
459 	const char *fmt;
460 
461 	if ((img->im = img_open(file)) == NULL)
462 		return false;
463 
464 	imlib_image_set_changes_on_disk();
465 
466 #if HAVE_LIBEXIF
467 	exif_auto_orientate(file);
468 #endif
469 
470 	if ((fmt = imlib_image_format()) != NULL) {
471 #if HAVE_LIBGIF
472 		if (STREQ(fmt, "gif"))
473 			img_load_gif(img, file);
474 #endif
475 #if HAVE_LIBWEBP
476 		if (STREQ(fmt, "webp"))
477 			img_load_webp(file, NULL, img);
478 #endif
479 	}
480 	img->w = imlib_image_get_width();
481 	img->h = imlib_image_get_height();
482 	img->checkpan = true;
483 	img->dirty = true;
484 
485 	return true;
486 }
487 
488 CLEANUP void img_close(img_t *img, bool decache)
489 {
490 	int i;
491 
492 	if (img->multi.cnt > 0) {
493 		for (i = 0; i < img->multi.cnt; i++) {
494 			imlib_context_set_image(img->multi.frames[i].im);
495 			imlib_free_image();
496 		}
497 		img->multi.cnt = 0;
498 		img->im = NULL;
499 	} else if (img->im != NULL) {
500 		imlib_context_set_image(img->im);
501 		if (decache)
502 			imlib_free_image_and_decache();
503 		else
504 			imlib_free_image();
505 		img->im = NULL;
506 	}
507 }
508 
509 void img_check_pan(img_t *img, bool moved)
510 {
511 	win_t *win;
512 	float w, h, ox, oy;
513 
514 	win = img->win;
515 	w = img->w * img->zoom;
516 	h = img->h * img->zoom;
517 	ox = img->x;
518 	oy = img->y;
519 
520 	if (w < win->w)
521 		img->x = (win->w - w) / 2;
522 	else if (img->x > 0)
523 		img->x = 0;
524 	else if (img->x + w < win->w)
525 		img->x = win->w - w;
526 	if (h < win->h)
527 		img->y = (win->h - h) / 2;
528 	else if (img->y > 0)
529 		img->y = 0;
530 	else if (img->y + h < win->h)
531 		img->y = win->h - h;
532 
533 	if (!moved && (ox != img->x || oy != img->y))
534 		img->dirty = true;
535 }
536 
537 bool img_fit(img_t *img)
538 {
539 	float z, zw, zh;
540 
541 	if (img->scalemode == SCALE_ZOOM)
542 		return false;
543 
544 	zw = (float) img->win->w / (float) img->w;
545 	zh = (float) img->win->h / (float) img->h;
546 
547 	switch (img->scalemode) {
548 		case SCALE_FILL:
549 			z = MAX(zw, zh);
550 			break;
551 		case SCALE_WIDTH:
552 			z = zw;
553 			break;
554 		case SCALE_HEIGHT:
555 			z = zh;
556 			break;
557 		default:
558 			z = MIN(zw, zh);
559 			break;
560 	}
561 	z = MIN(z, img->scalemode == SCALE_DOWN ? 1.0 : ZOOM_MAX);
562 
563 	if (ABS(img->zoom - z) > 1.0/MAX(img->w, img->h)) {
564 		img->zoom = z;
565 		img->dirty = true;
566 		return true;
567 	} else {
568 		return false;
569 	}
570 }
571 
572 void img_render(img_t *img)
573 {
574 	win_t *win;
575 	int sx, sy, sw, sh;
576 	int dx, dy, dw, dh;
577 	Imlib_Image bg;
578 	unsigned long c;
579 
580 	win = img->win;
581 	img_fit(img);
582 
583 	if (img->checkpan) {
584 		img_check_pan(img, false);
585 		img->checkpan = false;
586 	}
587 
588 	if (!img->dirty)
589 		return;
590 
591 	/* calculate source and destination offsets:
592 	 *   - part of image drawn on full window, or
593 	 *   - full image drawn on part of window
594 	 */
595 	if (img->x <= 0) {
596 		sx = -img->x / img->zoom + 0.5;
597 		sw = win->w / img->zoom;
598 		dx = 0;
599 		dw = win->w;
600 	} else {
601 		sx = 0;
602 		sw = img->w;
603 		dx = img->x;
604 		dw = img->w * img->zoom;
605 	}
606 	if (img->y <= 0) {
607 		sy = -img->y / img->zoom + 0.5;
608 		sh = win->h / img->zoom;
609 		dy = 0;
610 		dh = win->h;
611 	} else {
612 		sy = 0;
613 		sh = img->h;
614 		dy = img->y;
615 		dh = img->h * img->zoom;
616 	}
617 
618 	win_clear(win);
619 
620 	imlib_context_set_image(img->im);
621 	imlib_context_set_anti_alias(img->aa);
622 	imlib_context_set_drawable(win->buf.pm);
623 
624 	if (imlib_image_has_alpha()) {
625 		if ((bg = imlib_create_image(dw, dh)) == NULL)
626 			error(EXIT_FAILURE, ENOMEM, NULL);
627 		imlib_context_set_image(bg);
628 		imlib_image_set_has_alpha(1);
629 
630 		if (img->alpha) {
631 			int i, c, r;
632 			DATA32 col[2] = { 0xFF666666, 0xFF999999 };
633 			DATA32 * data = imlib_image_get_data();
634 
635 			for (r = 0; r < dh; r++) {
636 				i = r * dw;
637 				if (r == 0 || r == 8) {
638 					for (c = 0; c < dw; c++)
639 						data[i++] = col[!(c & 8) ^ !r];
640 				} else {
641 					memcpy(&data[i], &data[(r & 8) * dw], dw * sizeof(data[0]));
642 				}
643 			}
644 			imlib_image_put_back_data(data);
645 		} else {
646 			c = win->win_bg.pixel;
647 			imlib_context_set_color(c >> 16 & 0xFF, c >> 8 & 0xFF, c & 0xFF, 0xFF);
648 			imlib_image_fill_rectangle(0, 0, dw, dh);
649 		}
650 		imlib_blend_image_onto_image(img->im, 0, sx, sy, sw, sh, 0, 0, dw, dh);
651 		imlib_context_set_color_modifier(NULL);
652 		imlib_render_image_on_drawable(dx, dy);
653 		imlib_free_image();
654 		imlib_context_set_color_modifier(img->cmod);
655 	} else {
656 		imlib_image_set_has_alpha(1);
657 		imlib_render_image_part_on_drawable_at_size(sx, sy, sw, sh, dx, dy, dw, dh);
658 	}
659 	img->dirty = false;
660 }
661 
662 bool img_fit_win(img_t *img, scalemode_t sm)
663 {
664 	float oz;
665 
666 	oz = img->zoom;
667 	img->scalemode = sm;
668 
669 	if (img_fit(img)) {
670 		img->x = img->win->w / 2 - (img->win->w / 2 - img->x) * img->zoom / oz;
671 		img->y = img->win->h / 2 - (img->win->h / 2 - img->y) * img->zoom / oz;
672 		img->checkpan = true;
673 		return true;
674 	} else {
675 		return false;
676 	}
677 }
678 
679 bool img_zoom_to(img_t *img, float z)
680 {
681 	int x, y;
682 	if (ZOOM_MIN <= z && z <= ZOOM_MAX) {
683 		win_cursor_pos(img->win, &x, &y);
684 		if (x < 0 || x >= img->win->w || y < 0 || y >= img->win->h) {
685 			x = img->win->w / 2;
686 			y = img->win->h / 2;
687 		}
688 		img->x = x - (x - img->x) * z / img->zoom;
689 		img->y = y - (y - img->y) * z / img->zoom;
690 		img->zoom = z;
691 		img->scalemode = SCALE_ZOOM;
692 		img->checkpan = true;
693 		img->dirty = true;
694 		return true;
695 	} else {
696 		return false;
697 	}
698 }
699 
700 bool img_zoom(img_t *img, int d)
701 {
702 	const float z = img->zoom * (d > 0 ? ZOOM_STEP : 1/ZOOM_STEP);
703 	return img_zoom_to(img, z);
704 }
705 
706 bool img_pos(img_t *img, float x, float y)
707 {
708 	float ox, oy;
709 
710 	ox = img->x;
711 	oy = img->y;
712 
713 	img->x = x;
714 	img->y = y;
715 
716 	img_check_pan(img, true);
717 
718 	if (ox != img->x || oy != img->y) {
719 		img->dirty = true;
720 		return true;
721 	} else {
722 		return false;
723 	}
724 }
725 
726 bool img_move(img_t *img, float dx, float dy)
727 {
728 	return img_pos(img, img->x + dx, img->y + dy);
729 }
730 
731 bool img_pan(img_t *img, direction_t dir, int d)
732 {
733 	/* d < 0: screen-wise
734 	 * d = 0: 1/PAN_FRACTION of screen
735 	 * d > 0: num of pixels
736 	 */
737 	float x, y;
738 
739 	if (d > 0) {
740 		x = y = MAX(1, (float) d * img->zoom);
741 	} else {
742 		x = img->win->w / (d < 0 ? 1 : PAN_FRACTION);
743 		y = img->win->h / (d < 0 ? 1 : PAN_FRACTION);
744 	}
745 
746 	switch (dir) {
747 		case DIR_LEFT:
748 			return img_move(img, x, 0.0);
749 		case DIR_RIGHT:
750 			return img_move(img, -x, 0.0);
751 		case DIR_UP:
752 			return img_move(img, 0.0, y);
753 		case DIR_DOWN:
754 			return img_move(img, 0.0, -y);
755 	}
756 	return false;
757 }
758 
759 bool img_pan_edge(img_t *img, direction_t dir)
760 {
761 	float ox, oy;
762 
763 	ox = img->x;
764 	oy = img->y;
765 
766 	if (dir & DIR_LEFT)
767 		img->x = 0;
768 	if (dir & DIR_RIGHT)
769 		img->x = img->win->w - img->w * img->zoom;
770 	if (dir & DIR_UP)
771 		img->y = 0;
772 	if (dir & DIR_DOWN)
773 		img->y = img->win->h - img->h * img->zoom;
774 
775 	img_check_pan(img, true);
776 
777 	if (ox != img->x || oy != img->y) {
778 		img->dirty = true;
779 		return true;
780 	} else {
781 		return false;
782 	}
783 }
784 
785 void img_rotate(img_t *img, degree_t d)
786 {
787 	int i, tmp;
788 	float ox, oy;
789 
790 	imlib_context_set_image(img->im);
791 	imlib_image_orientate(d);
792 
793 	for (i = 0; i < img->multi.cnt; i++) {
794 		if (i != img->multi.sel) {
795 			imlib_context_set_image(img->multi.frames[i].im);
796 			imlib_image_orientate(d);
797 		}
798 	}
799 	if (d == DEGREE_90 || d == DEGREE_270) {
800 		ox = d == DEGREE_90  ? img->x : img->win->w - img->x - img->w * img->zoom;
801 		oy = d == DEGREE_270 ? img->y : img->win->h - img->y - img->h * img->zoom;
802 
803 		img->x = oy + (img->win->w - img->win->h) / 2;
804 		img->y = ox + (img->win->h - img->win->w) / 2;
805 
806 		tmp = img->w;
807 		img->w = img->h;
808 		img->h = tmp;
809 		img->checkpan = true;
810 	}
811 	img->dirty = true;
812 }
813 
814 void img_flip(img_t *img, flipdir_t d)
815 {
816 	int i;
817 	void (*imlib_flip_op[3])(void) = {
818 		imlib_image_flip_horizontal,
819 		imlib_image_flip_vertical,
820 		imlib_image_flip_diagonal
821 	};
822 
823 	d = (d & (FLIP_HORIZONTAL | FLIP_VERTICAL)) - 1;
824 
825 	if (d < 0 || d >= ARRLEN(imlib_flip_op))
826 		return;
827 
828 	imlib_context_set_image(img->im);
829 	imlib_flip_op[d]();
830 
831 	for (i = 0; i < img->multi.cnt; i++) {
832 		if (i != img->multi.sel) {
833 			imlib_context_set_image(img->multi.frames[i].im);
834 			imlib_flip_op[d]();
835 		}
836 	}
837 	img->dirty = true;
838 }
839 
840 void img_toggle_antialias(img_t *img)
841 {
842 	img->aa = !img->aa;
843 	imlib_context_set_image(img->im);
844 	imlib_context_set_anti_alias(img->aa);
845 	img->dirty = true;
846 }
847 
848 bool img_change_gamma(img_t *img, int d)
849 {
850 	/* d < 0: decrease gamma
851 	 * d = 0: reset gamma
852 	 * d > 0: increase gamma
853 	 */
854 	int gamma;
855 	double range;
856 
857 	if (d == 0)
858 		gamma = 0;
859 	else
860 		gamma = MIN(MAX(img->gamma + d, -GAMMA_RANGE), GAMMA_RANGE);
861 
862 	if (img->gamma != gamma) {
863 		imlib_reset_color_modifier();
864 		if (gamma != 0) {
865 			range = gamma <= 0 ? 1.0 : GAMMA_MAX - 1.0;
866 			imlib_modify_color_modifier_gamma(1.0 + gamma * (range / GAMMA_RANGE));
867 		}
868 		img->gamma = gamma;
869 		img->dirty = true;
870 		return true;
871 	} else {
872 		return false;
873 	}
874 }
875 
876 bool img_frame_goto(img_t *img, int n)
877 {
878 	if (n < 0 || n >= img->multi.cnt || n == img->multi.sel)
879 		return false;
880 
881 	img->multi.sel = n;
882 	img->im = img->multi.frames[n].im;
883 
884 	imlib_context_set_image(img->im);
885 	img->w = imlib_image_get_width();
886 	img->h = imlib_image_get_height();
887 	img->checkpan = true;
888 	img->dirty = true;
889 
890 	return true;
891 }
892 
893 bool img_frame_navigate(img_t *img, int d)
894 {
895 	if (img->multi.cnt == 0 || d == 0)
896 		return false;
897 
898 	d += img->multi.sel;
899 	if (d < 0)
900 		d = 0;
901 	else if (d >= img->multi.cnt)
902 		d = img->multi.cnt - 1;
903 
904 	return img_frame_goto(img, d);
905 }
906 
907 bool img_frame_animate(img_t *img)
908 {
909 	if (img->multi.cnt == 0)
910 		return false;
911 
912 	if (img->multi.sel + 1 >= img->multi.cnt)
913 		img_frame_goto(img, 0);
914 	else
915 		img_frame_goto(img, img->multi.sel + 1);
916 	img->dirty = true;
917 	return true;
918 }
919 
920