Skip to content
imlib.c 36.5 KiB
Newer Older
/* imlib.c

Copyright (C) 1999-2003 Tom Gilbert.
Copyright (C) 2010-2018 Daniel Friesel.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies of the Software and its documentation and acknowledgment shall be
given in the documentation and software packages that this Software was
used.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

#include "feh.h"
#include "filelist.h"
#include "winwidget.h"
#include "options.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
Andrew Potter's avatar
Andrew Potter committed
#include <curl/curl.h>
Display *disp = NULL;
Visual *vis = NULL;
Screen *scr = NULL;
Colormap cm;
int depth;
Atom wmDeleteWindow;
XContext xid_context = 0;
Window root = 0;

/* Xinerama support */
#ifdef HAVE_LIBXINERAMA
XineramaScreenInfo *xinerama_screens = NULL;
int xinerama_screen;
int num_xinerama_screens;
static int feh_file_is_raw(char *filename);
static char *feh_http_load_image(char *url);
static char *feh_dcraw_load_image(char *filename);
static char *feh_magick_load_image(char *filename);

#ifdef HAVE_LIBXINERAMA
	if (opt.xinerama && XineramaIsActive(disp)) {
		int major, minor, px, py, i;

		/* discarded */
		Window dw;
		int di;
		unsigned int du;

		XineramaQueryVersion(disp, &major, &minor);
		xinerama_screens = XineramaQueryScreens(disp, &num_xinerama_screens);

		if (opt.xinerama_index >= 0)
			xinerama_screen = opt.xinerama_index;
			XQueryPointer(disp, root, &dw, &dw, &px, &py, &di, &di, &du);
			for (i = 0; i < num_xinerama_screens; i++) {
				if (XY_IN_RECT(px, py,
							xinerama_screens[i].x_org,
							xinerama_screens[i].y_org,
							xinerama_screens[i].width,
							xinerama_screens[i].height)) {
					xinerama_screen = i;
					break;
				}
			}
		}
	/* Set up the font stuff */
	imlib_add_path_to_font_path(".");
	imlib_add_path_to_font_path(PREFIX "/share/feh/fonts");
	disp = XOpenDisplay(NULL);
	if (!disp)
		eprintf("Can't open X display. It *is* running, yeah?");
	vis = DefaultVisual(disp, DefaultScreen(disp));
	depth = DefaultDepth(disp, DefaultScreen(disp));
	cm = DefaultColormap(disp, DefaultScreen(disp));
	root = RootWindow(disp, DefaultScreen(disp));
	scr = ScreenOfDisplay(disp, DefaultScreen(disp));
	xid_context = XUniqueContext();

#ifdef HAVE_LIBXINERAMA
	init_xinerama();
#endif				/* HAVE_LIBXINERAMA */
	imlib_context_set_display(disp);
	imlib_context_set_visual(vis);
	imlib_context_set_colormap(cm);
	imlib_context_set_color_modifier(NULL);
	imlib_context_set_progress_function(NULL);
	imlib_context_set_operation(IMLIB_OP_COPY);
	wmDeleteWindow = XInternAtom(disp, "WM_DELETE_WINDOW", False);
	imlib_set_cache_size(opt.cache_size * 1024 * 1024);

int feh_should_ignore_image(Imlib_Image * im)
{
	if (opt.filter_by_dimensions) {
		unsigned int w = gib_imlib_image_get_width(im);
		unsigned int h = gib_imlib_image_get_height(im);
		if (w < opt.min_width || w > opt.max_width || h < opt.min_height || h > opt.max_height) {
			return 1;
		}
	}
	return 0;
}

int feh_load_image_char(Imlib_Image * im, char *filename)
	feh_file *file;
	int i;

	file = feh_file_new(filename);
	i = feh_load_image(im, file);
	feh_file_free(file);
void feh_imlib_print_load_error(char *file, winwidget w, Imlib_Load_Error err)
{
	if (err == IMLIB_LOAD_ERROR_OUT_OF_FILE_DESCRIPTORS)
		eprintf("%s - Out of file descriptors while loading", file);
	else if (!opt.quiet || w) {
		switch (err) {
		case IMLIB_LOAD_ERROR_FILE_DOES_NOT_EXIST:
			im_weprintf(w, "%s - File does not exist", file);
			break;
		case IMLIB_LOAD_ERROR_FILE_IS_DIRECTORY:
			im_weprintf(w, "%s - Directory specified for image filename", file);
			break;
		case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_READ:
			im_weprintf(w, "%s - No read access", file);
			break;
		case IMLIB_LOAD_ERROR_UNKNOWN:
		case IMLIB_LOAD_ERROR_NO_LOADER_FOR_FILE_FORMAT:
			im_weprintf(w, "%s - No Imlib2 loader for that file format", file);
			break;
		case IMLIB_LOAD_ERROR_PATH_TOO_LONG:
			im_weprintf(w, "%s - Path specified is too long", file);
			break;
		case IMLIB_LOAD_ERROR_PATH_COMPONENT_NON_EXISTANT:
			im_weprintf(w, "%s - Path component does not exist", file);
			break;
		case IMLIB_LOAD_ERROR_PATH_COMPONENT_NOT_DIRECTORY:
			im_weprintf(w, "%s - Path component is not a directory", file);
			break;
		case IMLIB_LOAD_ERROR_PATH_POINTS_OUTSIDE_ADDRESS_SPACE:
			im_weprintf(w, "%s - Path points outside address space", file);
			break;
		case IMLIB_LOAD_ERROR_TOO_MANY_SYMBOLIC_LINKS:
			im_weprintf(w, "%s - Too many levels of symbolic links", file);
			break;
		case IMLIB_LOAD_ERROR_OUT_OF_MEMORY:
			im_weprintf(w, "While loading %s - Out of memory", file);
			break;
		case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_WRITE:
			im_weprintf(w, "%s - Cannot write to directory", file);
			break;
		case IMLIB_LOAD_ERROR_OUT_OF_DISK_SPACE:
			im_weprintf(w, "%s - Cannot write - out of disk space", file);
			break;
		default:
			im_weprintf(w, "While loading %s - Unknown error (%d)",
					file, err);
			break;
		}
	}
}

int feh_load_image(Imlib_Image * im, feh_file * file)
	Imlib_Load_Error err = IMLIB_LOAD_ERROR_NONE;
	enum { SRC_IMLIB, SRC_HTTP, SRC_MAGICK, SRC_DCRAW } image_source = SRC_IMLIB;
	char *tmpname = NULL;
	char *real_filename = NULL;
	D(("filename is %s, image is %p\n", file->filename, im));
	if (path_is_url(file->filename)) {
		if ((tmpname = feh_http_load_image(file->filename)) == NULL)
			err = IMLIB_LOAD_ERROR_FILE_DOES_NOT_EXIST;
	else if (opt.dcraw_timeout >= 0 && feh_file_is_raw(file->filename)) {
		image_source = SRC_DCRAW;
		tmpname = feh_dcraw_load_image(file->filename);
		if (!tmpname)
			err = IMLIB_LOAD_ERROR_NO_LOADER_FOR_FILE_FORMAT;
	}
	else
		*im = imlib_load_image_with_error_return(file->filename, &err);

	if (opt.magick_timeout >= 0 && (
			(err == IMLIB_LOAD_ERROR_UNKNOWN) ||
			(err == IMLIB_LOAD_ERROR_NO_LOADER_FOR_FILE_FORMAT))) {
		image_source = SRC_MAGICK;
		tmpname = feh_magick_load_image(file->filename);
	}

	if (tmpname) {
		*im = imlib_load_image_with_error_return(tmpname, &err);
ulteq's avatar
ulteq committed
		if (!err && im) {
			real_filename = file->filename;
			file->filename = tmpname;
			feh_file_info_load(file, *im);
			file->filename = real_filename;
#ifdef HAVE_LIBEXIF
			file->ed = exif_get_data(tmpname);
ulteq's avatar
ulteq committed
		if ((image_source != SRC_HTTP) || !opt.keep_http)
		free(tmpname);
	}

	if ((err) || (!im)) {
		if (opt.verbose && !opt.quiet) {
			fputs("\n", stderr);
		feh_imlib_print_load_error(file->filename, NULL, err);
		D(("Load *failed*\n"));
	/*
	 * By default, Imlib2 unconditionally loads a cached file without checking
	 * if it was modified on disk. However, feh (or rather its users) should
	 * expect image changes to appear at the next reload. So we tell Imlib2 to
	 * always check the file modification time and only use a cached image if
	 * the mtime was not changed. The performance penalty is usually negligible.
	 */
	imlib_context_set_image(*im);
	imlib_image_set_changes_on_disk();

	ExifData *exifData = exif_data_new_from_file(file->filename);
	if (exifData) {
		ExifByteOrder byteOrder = exif_data_get_byte_order(exifData);
		ExifEntry *exifEntry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION);
		if (exifEntry && opt.auto_rotate)
			orientation = exif_get_short(exifEntry->data, byteOrder);
	file->ed = exifData;
	if (orientation == 3)
		gib_imlib_image_orientate(*im, 2);
	else if (orientation == 6)
		gib_imlib_image_orientate(*im, 1);
	else if (orientation == 8)
		gib_imlib_image_orientate(*im, 3);
	D(("Loaded ok\n"));
static int feh_file_is_raw(char *filename)
{
	childpid = fork();
	if (childpid == -1) {
		perror("fork");
		return 0;
	}

	if (childpid == 0) {
		if (opt.quiet) {
			int devnull = open("/dev/null", O_WRONLY);
			dup2(devnull, 1);
			dup2(devnull, 2);
		}
		execlp("dcraw", "dcraw", "-i", filename, NULL);
		_exit(1);
	} else {
		int status;
		do {
			waitpid(childpid, &status, WUNTRACED);
			if (WIFEXITED(status)) {
				return !WEXITSTATUS(status);
			}
		} while (!WIFEXITED(status) && !WIFSIGNALED(status));
	}

	return 0;
}

static char *feh_dcraw_load_image(char *filename)
{
	char *basename;
	char *tmpname;
	char *sfn;
	int fd = -1;

	basename = strrchr(filename, '/');

	if (basename == NULL)
		basename = filename;
	else
		basename++;

	tmpname = feh_unique_filename("/tmp/", basename);

	if (strlen(tmpname) > (NAME_MAX-6))
		tmpname[NAME_MAX-7] = '\0';

	sfn = estrjoin("_", tmpname, "XXXXXX", NULL);
	free(tmpname);

	fd = mkstemp(sfn);

	if (fd == -1) {
		free(sfn);
		return NULL;
	}

	childpid = fork();
	if (childpid == -1) {
		weprintf("%s: Can't load with dcraw. Fork failed:", filename);
		unlink(sfn);
		free(sfn);
		close(fd);
		return NULL;
	} else if (childpid == 0) {

		close(1);
		dup(fd);
		close(fd);

		alarm(opt.dcraw_timeout);
		execlp("dcraw", "dcraw", "-c", "-e", filename, NULL);
		_exit(1);
	}

	int status;
	waitpid(-1, &status, 0);
	if (WIFSIGNALED(status)) {
		unlink(sfn);
		free(sfn);
		sfn = NULL;
		if (!opt.quiet)
			weprintf("%s - Conversion took too long, skipping", filename);
	}

	return sfn;
}

static char *feh_magick_load_image(char *filename)
{
	char *basename;
	char *tmpname;
	char *sfn;
	char tempdir[] = "/tmp/.feh-magick-tmp-XXXXXX";
	basename = strrchr(filename, '/');

	if (basename == NULL)
		basename = filename;
	else
		basename++;

	tmpname = feh_unique_filename("/tmp/", basename);

	if (strlen(tmpname) > (NAME_MAX-6))
		tmpname[NAME_MAX-7] = '\0';

	sfn = estrjoin("_", tmpname, "XXXXXX", NULL);
	free(tmpname);

	fd = mkstemp(sfn);

	/*
	 * We could use png:fd:(whatever mkstemp returned) as target filename
	 * for convert, but this seems to be broken in some ImageMagick versions.
	 * So we resort to png:(sfn) instead.
	 */
	argv_fn = estrjoin(":", "png", sfn, NULL);
	/*
	 * By default, ImageMagick saves (occasionally lots of) temporary files
	 * in /tmp. It doesn't remove them if it runs into a timeout and is killed
	 * by us, no matter whether we use SIGINT, SIGTERM or SIGKILL. So, unless
	 * MAGICK_TMPDIR has already been set by the user, we create our own
	 * temporary directory for ImageMagick and remove its contents at the end of
	 * this function.
	 */
	if (getenv("MAGICK_TMPDIR") == NULL) {
		if (mkdtemp(tempdir) == NULL) {
			weprintf("%s: ImageMagick may leave temporary files in /tmp. mkdtemp failed:", filename);
		} else {
			created_tempdir = 1;
		}
	}

	if ((childpid = fork()) < 0) {
		weprintf("%s: Can't load with imagemagick. Fork failed:", filename);
		unlink(sfn);
		free(sfn);
		sfn = NULL;
	}
	else if (childpid == 0) {

		devnull = open("/dev/null", O_WRONLY);
		if (opt.quiet) {
			/* discard convert output */
			dup2(devnull, 1);
			dup2(devnull, 2);
		}
		/*
		 * convert only accepts SIGINT via killpg, a normal kill doesn't work
		 */
		if (created_tempdir) {
			// no error checking - this is a best-effort code path
			setenv("MAGICK_TMPDIR", tempdir, 0);
		}

		execlp("convert", "convert", filename, argv_fn, NULL);
		alarm(opt.magick_timeout);
		waitpid(childpid, &status, 0);
ulteq's avatar
ulteq committed
		kill(childpid, SIGKILL);
		if (opt.magick_timeout > 0 && !alarm(0)) {
				weprintf("%s: Conversion took too long, skipping", filename);
ulteq's avatar
ulteq committed
		close(fd);
	if (created_tempdir) {
		DIR *dir;
		struct dirent *de;
		if ((dir = opendir(tempdir)) == NULL) {
			weprintf("%s: Cannot remove temporary ImageMagick files from %s:", filename, tempdir);
		} else {
			while ((de = readdir(dir)) != NULL) {
				if (de->d_name[0] != '.') {
					char *temporary_file_name = estrjoin("/", tempdir, de->d_name, NULL);
					/*
					 * We assume that ImageMagick only creates temporary files and
					 * not directories.
					 */
					if (unlink(temporary_file_name) == -1) {
						weprintf("unlink %s:", temporary_file_name);
					}
					free(temporary_file_name);
				}
			}
			if (rmdir(tempdir) == -1) {
				weprintf("rmdir %s:", tempdir);
			}
		}
		closedir(dir);
	}

#ifdef HAVE_LIBCURL

static char *feh_http_load_image(char *url)
	CURL *curl;
	CURLcode res;
	char *sfn;
	FILE *sfp;
	int fd = -1;
	char *ebuff;
	char *tmpname;
	char *basename;
	char *path = NULL;

	if (opt.keep_http) {
		if (opt.output_dir)
			path = opt.output_dir;
		else
			path = "";
	} else
		path = "/tmp/";

	curl = curl_easy_init();
	if (!curl) {
		weprintf("open url: libcurl initialization failure");
		return NULL;
	}
	basename = strrchr(url, '/') + 1;
	tmpname = feh_unique_filename(path, basename);

	if (strlen(tmpname) > (NAME_MAX-6))
		tmpname[NAME_MAX-7] = '\0';
William Woodruff's avatar
William Woodruff committed

	sfn = estrjoin("_", tmpname, "XXXXXX", NULL);
	free(tmpname);
	fd = mkstemp(sfn);
	if (fd != -1) {
		sfp = fdopen(fd, "w+");
		if (sfp != NULL) {
#ifdef DEBUG
			curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
#endif
			curl_easy_setopt(curl, CURLOPT_URL, url);
			curl_easy_setopt(curl, CURLOPT_WRITEDATA, sfp);
			ebuff = emalloc(CURL_ERROR_SIZE);
			curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, ebuff);
			curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
			curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
William Woodruff's avatar
William Woodruff committed
			if (opt.insecure_ssl) {
				curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
				curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
			} else if (getenv("CURL_CA_BUNDLE") != NULL) {
				// Allow the user to specify custom CA certificates.
				curl_easy_setopt(curl, CURLOPT_CAINFO,
						getenv("CURL_CA_BUNDLE"));
William Woodruff's avatar
William Woodruff committed
			}

			res = curl_easy_perform(curl);
			curl_easy_cleanup(curl);
			if (res != CURLE_OK) {
				weprintf("open url: %s", ebuff);
				unlink(sfn);
				close(fd);
				free(sfn);
				sfn = NULL;

			free(ebuff);
			fclose(sfp);
			return sfn;
Andrew Potter's avatar
Andrew Potter committed
		} else {
			weprintf("open url: fdopen failed:");
			unlink(sfn);
Andrew Potter's avatar
Andrew Potter committed
			free(sfn);
			close(fd);
		weprintf("open url: mkstemp failed:");
		free(sfn);
	curl_easy_cleanup(curl);
	return NULL;
}

#else				/* HAVE_LIBCURL */
char *feh_http_load_image(char *url)
{
	weprintf(
		"Cannot load image %s\nPlease recompile feh with libcurl support",
		url
	);
	return NULL;
#endif				/* HAVE_LIBCURL */

void feh_imlib_image_fill_text_bg(Imlib_Image im, int w, int h)
{
	gib_imlib_image_set_has_alpha(im, 1);


	if (opt.text_bg == TEXT_BG_CLEAR)
		gib_imlib_image_fill_rectangle(im, 0, 0, w, h, 0, 0, 0, 0);
	else
		gib_imlib_image_fill_rectangle(im, 0, 0, w, h, 0, 0, 0, 127);
static Imlib_Font feh_load_font(winwidget w)
	if (opt.font)
		fn = gib_imlib_load_font(opt.font);

		if (w && w->full_screen)
			fn = gib_imlib_load_font(DEFAULT_FONT_BIG);
		else
			fn = gib_imlib_load_font(DEFAULT_FONT);
		eprintf("Couldn't load font to draw a message");
	return fn;
}


void feh_draw_zoom(winwidget w)
{
	static Imlib_Font fn = NULL;
	int tw = 0, th = 0;
	Imlib_Image im = NULL;
	char buf[100];

	if (!w->im)
		return;

	fn = feh_load_font(w);

	snprintf(buf, sizeof(buf), "%.0f%%, %dx%d", w->zoom * 100,
			(int) (w->im_w * w->zoom), (int) (w->im_h * w->zoom));

	/* Work out how high the font is */
	gib_imlib_get_text_size(fn, buf, NULL, &tw, &th, IMLIB_TEXT_TO_RIGHT);

	tw += 3;
	th += 3;
	im = imlib_create_image(tw, th);
	if (!im)
		eprintf("Couldn't create image. Out of memory?");


	gib_imlib_text_draw(im, fn, NULL, 2, 2, buf, IMLIB_TEXT_TO_RIGHT, 0, 0, 0, 255);
	gib_imlib_text_draw(im, fn, NULL, 1, 1, buf, IMLIB_TEXT_TO_RIGHT, 255, 255, 255, 255);
	gib_imlib_render_image_on_drawable(w->bg_pmap, im, 0, w->h - th, 1, 1, 0);
	gib_imlib_free_image_and_decache(im);
void im_weprintf(winwidget w, char *fmt, ...)
{
	va_list args;
	char *errstr = emalloc(1024);

	fflush(stdout);
	fputs(PACKAGE " WARNING: ", stderr);

	va_start(args, fmt);
	vsnprintf(errstr, 1024, fmt, args);
	va_end(args);

	if (w)
		w->errstr = errstr;

	fputs(errstr, stderr);
	if (fmt[0] != '\0' && fmt[strlen(fmt) - 1] == ':')
		fprintf(stderr, " %s", strerror(errno));
	fputs("\n", stderr);
}


void feh_draw_errstr(winwidget w)
{
	static Imlib_Font fn = NULL;
	int tw = 0, th = 0;
	Imlib_Image im = NULL;

	if (!w->im)
		return;


	/* Work out how high the font is */
	gib_imlib_get_text_size(fn, w->errstr, NULL, &tw, &th, IMLIB_TEXT_TO_RIGHT);

	tw += 3;
	th += 3;
	im = imlib_create_image(tw, th);
	if (!im)
		eprintf("Couldn't create errstr image. Out of memory?");


	gib_imlib_text_draw(im, fn, NULL, 2, 2, w->errstr, IMLIB_TEXT_TO_RIGHT, 0, 0, 0, 255);
	gib_imlib_text_draw(im, fn, NULL, 1, 1, w->errstr, IMLIB_TEXT_TO_RIGHT, 255, 0, 0, 255);
	free(w->errstr);
	w->errstr = NULL;
	gib_imlib_render_image_on_drawable(w->bg_pmap, im, 0, w->h - th, 1, 1, 0);
	gib_imlib_free_image_and_decache(im);
}

void feh_draw_filename(winwidget w)
	Imlib_Image im = NULL;
	char *s = NULL;
	int len = 0;

	if ((!w->file) || (!FEH_FILE(w->file->data))
			|| (!FEH_FILE(w->file->data)->filename))
	gib_imlib_get_text_size(fn, FEH_FILE(w->file->data)->filename, NULL, &tw,
			&th, IMLIB_TEXT_TO_RIGHT);

	if (gib_list_length(filelist) > 1) {
		len = snprintf(NULL, 0, "%d of %d",  gib_list_length(filelist),
				gib_list_length(filelist)) + 1;
		s = emalloc(len);
		if (w->file)
			snprintf(s, len, "%d of %d", gib_list_num(filelist, w->file) +
					1, gib_list_length(filelist));
		else
			snprintf(s, len, "%d of %d", gib_list_num(filelist, current_file) +
					1, gib_list_length(filelist));

		gib_imlib_get_text_size(fn, s, NULL, &nw, NULL, IMLIB_TEXT_TO_RIGHT);

		if (nw > tw)
			tw = nw;
	}

	tw += 3;
	th += 3;
	im = imlib_create_image(tw, 2 * th);
	if (!im)
		eprintf("Couldn't create image. Out of memory?");


	gib_imlib_text_draw(im, fn, NULL, 2, 2, FEH_FILE(w->file->data)->filename,
			IMLIB_TEXT_TO_RIGHT, 0, 0, 0, 255);
	gib_imlib_text_draw(im, fn, NULL, 1, 1, FEH_FILE(w->file->data)->filename,
			IMLIB_TEXT_TO_RIGHT, 255, 255, 255, 255);
		gib_imlib_text_draw(im, fn, NULL, 2, th + 1, s, IMLIB_TEXT_TO_RIGHT, 0, 0, 0, 255);
		gib_imlib_text_draw(im, fn, NULL, 1, th, s, IMLIB_TEXT_TO_RIGHT, 255, 255, 255, 255);
		free(s);
	}

	gib_imlib_render_image_on_drawable(w->bg_pmap, im, 0, 0, 1, 1, 0);

	gib_imlib_free_image_and_decache(im);
William Woodruff's avatar
William Woodruff committed
#ifdef HAVE_LIBEXIF
void feh_draw_exif(winwidget w)
{
	static Imlib_Font fn = NULL;
	int width = 0, height = 0, line_width = 0, line_height = 0;
	Imlib_Image im = NULL;
	int no_lines = 0, i;
	int pos = 0;
	int pos2 = 0;
	char info_line[256];
	char *info_buf[128];

	if ( (!w->file) || (!FEH_FILE(w->file->data))
			 || (!FEH_FILE(w->file->data)->filename) )
	{
		return;
	}

	exif_get_info(FEH_FILE(w->file->data)->ed, buffer, EXIF_MAX_DATA);
Niclas Zeising's avatar
Niclas Zeising committed
	if (buffer[0] == '\0')
		snprintf(buffer, EXIF_MAX_DATA, "%s", estrdup("Failed to run exif command"));
Niclas Zeising's avatar
Niclas Zeising committed
		gib_imlib_get_text_size(fn, buffer, NULL, &width, &height, IMLIB_TEXT_TO_RIGHT);
		info_buf[no_lines] = estrdup(buffer);
		no_lines++;
William Woodruff's avatar
William Woodruff committed
	else
		while ( (no_lines < 128) && (pos < EXIF_MAX_DATA) )
		{
			/* max 128 lines */
			pos2 = 0;
			while ( pos2 < 256 ) /* max 256 chars per line */
			{
				if ( (buffer[pos] != '\n')
				      && (buffer[pos] != '\0') )
				{
			    info_line[pos2] = buffer[pos];
			  }
			  else if ( buffer[pos] == '\0' )
			  {
			    pos = EXIF_MAX_DATA; /* all data seen */
			    info_line[pos2] = '\0';
				}
			  else
			  {
			  	info_line[pos2] = '\0'; /* line finished, continue with next line*/

			    pos++;
			    break;
			  }
William Woodruff's avatar
William Woodruff committed

William Woodruff's avatar
William Woodruff committed
			   pos2++;
			}

			gib_imlib_get_text_size(fn, info_line, NULL, &line_width,
                              &line_height, IMLIB_TEXT_TO_RIGHT);

			if (line_height > height)
				height = line_height;
			if (line_width > width)
				width = line_width;
			info_buf[no_lines] = estrdup(info_line);

			no_lines++;
		}
	}

	if (no_lines == 0)
		return;

	height *= no_lines;
	width += 4;

	im = imlib_create_image(width, height);
	if (!im)
	{
		eprintf("Couldn't create image. Out of memory?");
	}

	feh_imlib_image_fill_text_bg(im, width, height);

William Woodruff's avatar
William Woodruff committed
	for (i = 0; i < no_lines; i++)
	{
		gib_imlib_text_draw(im, fn, NULL, 2, (i * line_height) + 2,
				info_buf[i], IMLIB_TEXT_TO_RIGHT, 0, 0, 0, 255);
		gib_imlib_text_draw(im, fn, NULL, 1, (i * line_height) + 1,
				info_buf[i], IMLIB_TEXT_TO_RIGHT, 255, 255, 255, 255);

	}

	gib_imlib_render_image_on_drawable(w->bg_pmap, im, 0, w->h - height, 1, 1, 0);

	gib_imlib_free_image_and_decache(im);
	return;

}
#endif

void feh_draw_info(winwidget w)
{
	static Imlib_Font fn = NULL;
	int width = 0, height = 0, line_width = 0, line_height = 0;
	Imlib_Image im = NULL;
	char *info_cmd;
	FILE *info_pipe;

	if ((!w->file) || (!FEH_FILE(w->file->data))
			|| (!FEH_FILE(w->file->data)->filename))
		return;

	info_cmd = feh_printf(opt.info_cmd, FEH_FILE(w->file->data), w);

	info_pipe = popen(info_cmd, "r");

	if (!info_pipe) {
		info_buf[0] = estrdup("Failed to run info command");
		gib_imlib_get_text_size(fn, info_buf[0], NULL, &width, &height, IMLIB_TEXT_TO_RIGHT);
		no_lines = 1;
	}
	else {
		while ((no_lines < 128) && fgets(info_line, 256, info_pipe)) {
			if (info_line[strlen(info_line)-1] == '\n')
				info_line[strlen(info_line)-1] = '\0';

			gib_imlib_get_text_size(fn, info_line, NULL, &line_width,
					&line_height, IMLIB_TEXT_TO_RIGHT);

			if (line_height > height)
				height = line_height;
			if (line_width > width)
				width = line_width;

			info_buf[no_lines] = estrdup(info_line);

			no_lines++;
		}
		pclose(info_pipe);
	}

	height *= no_lines;
	width += 4;

	im = imlib_create_image(width, height);
	if (!im)
		eprintf("Couldn't create image. Out of memory?");

	feh_imlib_image_fill_text_bg(im, width, height);

	for (i = 0; i < no_lines; i++) {
		gib_imlib_text_draw(im, fn, NULL, 2, (i * line_height) + 2,
				info_buf[i], IMLIB_TEXT_TO_RIGHT, 0, 0, 0, 255);
		gib_imlib_text_draw(im, fn, NULL, 1, (i * line_height) + 1,
				info_buf[i], IMLIB_TEXT_TO_RIGHT, 255, 255, 255, 255);

		free(info_buf[i]);
	}
	gib_imlib_render_image_on_drawable(w->bg_pmap, im, 0,

	gib_imlib_free_image_and_decache(im);
	return;
}

char *build_caption_filename(feh_file * file, short create_dir)
	char *s, *dir, *caption_dir;
	struct stat cdir_stat;
	s = strrchr(file->filename, '/');
	if (s) {
		dir = estrdup(file->filename);