/*
    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA  02110-1301, USA.

    ---
    Copyright (C) 2009, Marco Trevisan (Treviño) <mail@3v1n0.net>

    It can be compiled with:
    $CC illume-kbd-show.c $(pkg-config --cflags --libs x11) -o illume-kbd-show
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <X11/Xlib.h>

typedef enum {
	INVOKE_KBD_NONE,
	INVOKE_KBD_SHOW,
	INVOKE_KBD_HIDE,
	INVOKE_KBD_TOGGLE,
} InvokerEvent;

int main(int argc, char **argv) {
	Display *display;
	XEvent *event;
	InvokerEvent invoke;
	int i;
	
	invoke = INVOKE_KBD_SHOW;
	
	for (i = 1; i < argc; i++) {
		if ((!strcmp("-h", argv[i])) || !strcmp("--help", argv[i])) {
			printf("\nIllume-kbd-show - A simple OnScreen Keyboard Invoker\n\n"
				  "  Usage:\n"
				  "\t -h  --help  :  Show this help\n"
				  "\t -s  --show  :  Show the on screen keyboard (default)\n"
				  "\t -k  --hide  :  Hide the on screen keyboard\n\n");
			return 0;
		}
		
		if ((!strcmp("-s", argv[i])) || !strcmp("--show", argv[i])) {
			invoke = INVOKE_KBD_SHOW;
			break;
		}
		
		if ((!strcmp("-k", argv[i])) || !strcmp("--hide", argv[i])) {
			invoke = INVOKE_KBD_HIDE;
			break;
		}
		
		if ((!strcmp("-t", argv[i])) || !strcmp("--toggle", argv[i])) {
			invoke = INVOKE_KBD_TOGGLE;
			break;
		}
	}

	if (!getenv("DISPLAY"))
		display = XOpenDisplay(":0");
	else
		display = XOpenDisplay(NULL);

	if (!display) {
		fprintf(stderr, "Can't open display!\n");
		return 1;
	}
	
	event = (XEvent *) malloc(sizeof(XEvent));
	event->xclient.type = ClientMessage;
	event->xclient.send_event = True;
	event->xclient.display = display;
	event->xclient.window = DefaultRootWindow(display);
	event->xclient.message_type = XInternAtom(display, "_MB_IM_INVOKER_COMMAND", False);
	event->xclient.format = 32;
	event->xclient.data.l[0] = invoke;
	
	XSendEvent(display,
			 DefaultRootWindow(display),
			 False,
			 SubstructureRedirectMask | SubstructureNotifyMask,
			 event);
	
	XFlush(display);
	XSync(display, False);

	return 0;
}

