/*
File:	xpointer.c
Author:	MIZUNO J.Y. <http://p.mjy.name/>
Date:	2009/05/24
Compile/gcc:
	gcc -ansi -pedantic -Wall -lX11 -D_POSIX_C_SOURCE=2 xpointer.c -o xpointer
Compile/tcc:
	tcc -Wall -lX11 xpointer.c -o xpointer

License "The MIT License":
	Copyright (c) 2009 MIZUNO J.Y.

	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 or substantial portions of the Software.

	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 OR COPYRIGHT HOLDERS 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <X11/Xlib.h>

static const char *help_string =
	"xpointer 1.1 - moves/displays coordinates of the pointer\n"
	"Usage:\n"
	"       xpointer -x N -y N\n"
	"       xpointer N N\n"
	"       xpointer\n"
	"Options:\n"
	"-h     show this help message and exit\n"
	"-x N   X coordinate\n"
	"-y N   Y coordinate\n"
	"-@     shebang trick\n"
	"       ex.  #! /usr/bin/xpointer -@_-x10_-y20_-@\n"
	;

#define UNREACHABLE 1

/* bool */
typedef int bool;
#define true    1
#define false   0

/*
 * { START StringList
 */

typedef struct _StringListItem {
	char *string;
	struct _StringListItem *next;
} *StringListItem;

typedef StringListItem *StringListIter;

typedef struct _StringList {
	StringListItem _top;
	StringListItem _bottom;
	int _len;
} *StringList;

StringList StringList_new(void)
{
	StringList list = malloc(sizeof(struct _StringList));
	list->_top = NULL;
	list->_bottom = NULL;
	list->_len = 0;
	return list;
}

void StringList_append(StringList list, char *string)
{
	StringListItem new = malloc(sizeof(struct _StringListItem));
	StringListItem bottom = list->_bottom;

	new->string = string;
	new->next = NULL;
	list->_bottom = new;

	if (0 == list->_len) {
		list->_top = new;
	} else {
		bottom->next = new;
	}
	list->_len++;
}

int StringList_len(StringList list)
{
	return list->_len;
}

StringListIter StringListIter_new(StringList list)
{
	StringListIter iter = malloc(sizeof(StringListItem));
	*iter = list->_top;
	return iter;
}

char *StringListIter_next(StringListIter iter)
{
	if (NULL != (*iter)) {
		char *r = (*iter)->string;
		*iter = (*iter)->next;
		return r;
	} else {
		return NULL;
	}
}

char **StringList_to_array(StringList list)
{
	char **array = malloc(sizeof(char *) * StringList_len(list));
	StringListIter iter = StringListIter_new(list);
	int c = 0;
	char * s;

	while (NULL != (s = StringListIter_next(iter))) {
		array[c] = s;
		c++;
	}
	return array;
}

/*
 * END StringList }
 */


void error(char *fmt, ...)
{
	va_list arg;

	fputs("xpointer: error: ", stderr);

	va_start(arg, fmt);
	vfprintf(stderr, fmt, arg);
	va_end(arg);

	fputs("\n", stderr);
	exit(EXIT_FAILURE);
}

void warp(Display *disp, int x, int y)
{
	Window root = XRootWindow(disp, DefaultScreen(disp));
	XWarpPointer(disp, None, root, 0, 0, 0, 0, x, y);
	XFlush(disp);
	exit(EXIT_SUCCESS);
}

void print(Display *disp)
{
	Window root = XRootWindow(disp, DefaultScreen(disp));
	Window nouse_win, nouse_win2;
	int nouse_int, nouse_int2;
	unsigned int nouse_uint;
	int x, y;

	if (XQueryPointer(
	disp, root,
	&nouse_win, &nouse_win2,
	&x, &y,
	&nouse_int, &nouse_int2, &nouse_uint)) {
		printf("%d %d\n", x, y);
		exit(EXIT_SUCCESS);
	} else {
		error("the pointer is not on the same screen"
			" as the specified window.");
	}
}

void shebang_trick(int *argc_ptr, char ***argv_ptr)
{

	char sep[2] = {'\0', '\0'};
	char *s;
	int i;
	char **argv = *argv_ptr;
	bool dash_dash_flg = false;
	StringList arg_list = StringList_new();

	StringList_append(arg_list, argv[0]);

	for (i = 1; i < *argc_ptr; i++) {
		if (0 == strcmp(argv[i], "--")) dash_dash_flg = true;

		if ((strlen(argv[i]) <= 3)
		|| (0 != strncmp(argv[i], "-@", 2))
		|| dash_dash_flg) {
			StringList_append(arg_list, argv[i]);
		} else {
			sep[0] = argv[i][2];
			strtok(argv[i], sep);
			while (NULL != (s = strtok(NULL, sep))) {

				StringList_append(arg_list, s);
			}
		}
	}

	*argc_ptr = StringList_len(arg_list);
	*argv_ptr = StringList_to_array(arg_list);
}

int to_int(char *str)
{
	char *end;
	int n = strtol(str, &end, 0);
	if ('\0' == *end) {
		return n;
	} else {
		error("invalid integer value: %s", str);
	}

	return UNREACHABLE;
}

void proc_opts(int *x_ptr, int *y_ptr, bool *do_warp_ptr,
	int argc, char **argv)
{
	int opt;
	int i;

	shebang_trick(&argc, &argv);
	*do_warp_ptr = false;
	opterr = 0;
	while (-1 != (opt = getopt(argc, argv, "x:y:h@:"))) {
		switch (opt) {
		case 'x':
			*x_ptr = to_int(optarg);
			*do_warp_ptr = true;
			break;
		case 'y':
			*y_ptr = to_int(optarg);
			*do_warp_ptr = true;
			break;
		case 'h':
			fputs(help_string, stdout);
			exit(EXIT_SUCCESS);
			break;
		case '@':
			break;
		default:
			error("invalid option: %c", optopt);
		}
	}

	for (i = 0; optind < argc; optind++, i++) {
		switch (i) {

		case 0:
			*x_ptr = to_int(argv[optind]);
			*do_warp_ptr = true;
			break;
		case 1:
			*y_ptr = to_int(argv[optind]);
			break;
		default:
			error("lot of arguments");
		}
	}
}

int main(int argc, char **argv)
{
	int x = 0;
	int y = 0;
	bool do_warp = false;
	Display *disp = XOpenDisplay(NULL);

	if (disp == NULL) error("cannot open X display");

	proc_opts(&x, &y, &do_warp, argc, argv);

	if (do_warp) warp(disp, x, y);
	print(disp);

	return UNREACHABLE;
}


