/* MUSWM.C
 * Copyright (c) 2015, 2018 Jesse McClure <code@jessemcclure.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <X11/Xlib.h>

int main(int argc, const char **argv) {
	Display *dpy;
	if(!(dpy = XOpenDisplay(0x0))) return 1;
	Window root = DefaultRootWindow(dpy);
	XGrabButton(dpy, AnyButton, Mod4Mask, root, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None);
	XEvent ev;
	Window win;
	int button, ex, ey, sw, sh;
	sw = DisplayWidth(dpy, DefaultScreen(dpy));
	sh = DisplayHeight(dpy, DefaultScreen(dpy));
	XWindowAttributes wa;
	while (!XNextEvent(dpy,&ev)) {
		win = ev.xbutton.subwindow;
		if (ev.xbutton.button) button = ev.xbutton.button;
		ex = ev.xbutton.x_root;
		ey = ev.xbutton.y_root;
		if (button == 2)
			XMoveResizeWindow(dpy, win, 0, 0, sw, sh);
		else if (button < 4) switch (ev.type) {
		case ButtonPress:
			XGrabPointer(dpy, ev.xbutton.subwindow, True, PointerMotionMask|ButtonReleaseMask,
				GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
			XGetWindowAttributes(dpy, ev.xbutton.subwindow, &wa);
			wa.x -= ex; wa.width -= ex;
			wa.y -= ey; wa.height -= ey;
			button = ev.xbutton.button;
			break;
		case ButtonRelease:
			XUngrabPointer(dpy, CurrentTime);
		case MotionNotify:
			while (XCheckTypedEvent(dpy, MotionNotify, &ev));
			if (button == 1) XMoveWindow(dpy, ev.xmotion.window, wa.x + ex, wa.y + ey);
			else if (button == 3) XResizeWindow(dpy, ev.xmotion.window, wa.width + ex, wa.height + ey);
		}
	}
	return 0;
}