# TinyWM is written by Nick Welch <nick@incise.org> in 2005 & 2011.
#
# This software is in the public domain
# and is provided AS IS, with NO WARRANTY.

# I'm keeping it beauty

from Xlib.display import Display
from Xlib import X, XK

dpy = Display()

dpy.screen().root.grab_key(dpy.keysym_to_keycode(XK.string_to_keysym("F1")), X.Mod1Mask, 1,
                           X.GrabModeAsync, X.GrabModeAsync)
dpy.screen().root.grab_button(1, X.Mod1Mask, 1, X.ButtonPressMask | X.ButtonReleaseMask | X.PointerMotionMask,
                              X.GrabModeAsync, X.GrabModeAsync, X.NONE, X.NONE)
dpy.screen().root.grab_button(3, X.Mod1Mask, 1, X.ButtonPressMask | X.ButtonReleaseMask | X.PointerMotionMask,
                              X.GrabModeAsync, X.GrabModeAsync, X.NONE, X.NONE)

start = None
while True:
    ev = dpy.next_event()
    if ev.type == X.KeyPress and ev.child != X.NONE:
        ev.child.configure(stack_mode=X.Above)
    elif ev.type == X.ButtonPress and ev.child != X.NONE:
        attr = ev.child.get_geometry()
        start = ev
    elif ev.type == X.MotionNotify and start:
        x_diff = ev.root_x - start.root_x
        y_diff = ev.root_y - start.root_y
        start.child.configure(
            x=attr.x + (x_diff if start.detail == 1 else 0),
            y=attr.y + (y_diff if start.detail == 1 else 0),
            width=max(1, attr.width + (x_diff if start.detail == 3 else 0)),
            height=max(1, attr.height + (y_diff if start.detail == 3 else 0)))
    elif ev.type == X.ButtonRelease:
        start = None
