]> Pileus Git - wmpus/blob - sys-win32.c
Start adding support for atoms
[wmpus] / sys-win32.c
1 /*
2  * Copyright (c) 2011-2012, Andy Spencer <andy753421@gmail.com>
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  */
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <ctype.h>
19 #include <search.h>
20
21 #define WIN32_LEAN_AND_MEAN
22 #define _WIN32_WINNT 0x0501
23 #include <windows.h>
24 #include <winbase.h>
25 #include <winuser.h>
26
27 #include "util.h"
28 #include "conf.h"
29 #include "types.h"
30 #include "sys.h"
31 #include "wm.h"
32
33 /* Configuration */
34 static int no_capture = 0;
35 static int stack      = 25;
36
37 /* Internal structures */
38 struct win_sys {
39         HWND hwnd;
40 };
41
42 typedef struct {
43         event_t ev;
44         int     vk;
45 } event_map_t;
46
47 /* Global data */
48 static int     shellhookid;
49 static void   *cache;
50 static HWND    root;
51 static list_t *screens;
52
53 /* Conversion functions */
54 static event_map_t ev2vk[] = {
55         {EV_MOUSE1  , VK_LBUTTON },
56         {EV_MOUSE2  , VK_MBUTTON },
57         {EV_MOUSE3  , VK_RBUTTON },
58         {EV_LEFT    , VK_LEFT    },
59         {EV_RIGHT   , VK_RIGHT   },
60         {EV_UP      , VK_UP      },
61         {EV_DOWN    , VK_DOWN    },
62         {EV_HOME    , VK_HOME    },
63         {EV_END     , VK_END     },
64         {EV_PAGEUP  , VK_PRIOR   },
65         {EV_PAGEDOWN, VK_NEXT    },
66         {EV_F1      , VK_F1      },
67         {EV_F2      , VK_F2      },
68         {EV_F3      , VK_F3      },
69         {EV_F4      , VK_F4      },
70         {EV_F5      , VK_F5      },
71         {EV_F6      , VK_F6      },
72         {EV_F7      , VK_F7      },
73         {EV_F8      , VK_F8      },
74         {EV_F9      , VK_F9      },
75         {EV_F10     , VK_F10     },
76         {EV_F11     , VK_F11     },
77         {EV_F12     , VK_F12     },
78         {EV_SHIFT   , VK_SHIFT   },
79         {EV_SHIFT   , VK_LSHIFT  },
80         {EV_SHIFT   , VK_RSHIFT  },
81         {EV_CTRL    , VK_CONTROL },
82         {EV_CTRL    , VK_LCONTROL},
83         {EV_CTRL    , VK_RCONTROL},
84         {EV_ALT     , VK_MENU    },
85         {EV_ALT     , VK_LMENU   },
86         {EV_ALT     , VK_RMENU   },
87         {EV_WIN     , VK_LWIN    },
88         {EV_WIN     , VK_RWIN    },
89 };
90
91 /* - Keycodes */
92 static event_t w2ev(UINT vk)
93 {
94         event_map_t *em = map_getr(ev2vk,vk);
95         return em ? em->ev : tolower(vk);
96 }
97
98 static UINT ev2w(event_t ev)
99 {
100         event_map_t *em = map_get(ev2vk,ev);
101         return em ? em->vk : toupper(ev);
102 }
103
104 static mod_t getmod(void)
105 {
106         return (mod_t){
107                 .alt   = GetKeyState(VK_MENU)    < 0,
108                 .ctrl  = GetKeyState(VK_CONTROL) < 0,
109                 .shift = GetKeyState(VK_SHIFT)   < 0,
110                 .win   = GetKeyState(VK_LWIN)    < 0 ||
111                          GetKeyState(VK_RWIN)    < 0,
112         };
113 }
114
115 /* - Pointers */
116 static ptr_t getptr(void)
117 {
118         POINT wptr;
119         GetCursorPos(&wptr);
120         return (ptr_t){-1, -1, wptr.x, wptr.y};
121 }
122
123 /* Window functions */
124 static win_t *win_new(HWND hwnd, int checkwin)
125 {
126         if (checkwin) {
127                 char winclass[256];
128                 int exstyle = GetWindowLong(hwnd, GWL_EXSTYLE);
129                 GetClassName(hwnd, winclass, sizeof(winclass));
130                 if (!IsWindowVisible(hwnd))      return NULL; // Invisible stuff..
131                 if (!strcmp("#32770", winclass)) return NULL; // Message boxes
132                 if (GetWindow(hwnd, GW_OWNER))   return NULL; // Dialog boxes, etc
133                 if (exstyle & WS_EX_TOOLWINDOW)  return NULL; // Floating toolbars
134         }
135
136         RECT rect = {};
137         GetWindowRect(hwnd, &rect);
138         win_t *win = new0(win_t);
139         win->x         = rect.left;
140         win->y         = rect.top;
141         win->w         = rect.right  - rect.left;
142         win->h         = rect.bottom - rect.top;
143         win->sys       = new0(win_sys_t);
144         win->sys->hwnd = hwnd;
145         printf("win_new: %p = %p (%d,%d %dx%d)\n", win, hwnd,
146                         win->x, win->y, win->w, win->h);
147         return win;
148 }
149
150 static int win_cmp(const void *_a, const void *_b)
151 {
152         const win_t *a = _a, *b = _b;
153         if (a->sys->hwnd < b->sys->hwnd) return -1;
154         if (a->sys->hwnd > b->sys->hwnd) return  1;
155         return 0;
156 }
157
158 static win_t *win_find(HWND hwnd, int create)
159 {
160         if (!hwnd)
161                 return NULL;
162         //printf("win_find: %p, %d\n", dpy, (int)xid);
163         win_sys_t sys = {.hwnd=hwnd};
164         win_t     tmp = {.sys=&sys};
165         win_t **old = NULL, *new = NULL;
166         if ((old = tfind(&tmp, &cache, win_cmp)))
167                 return *old;
168         if (create && (new = win_new(hwnd,1)))
169                 tsearch(new, &cache, win_cmp);
170         return new;
171 }
172
173 static void win_remove(win_t *win)
174 {
175         tdelete(win, &cache, win_cmp);
176         free(win->sys);
177         free(win);
178 }
179
180 static win_t *win_cursor(void)
181 {
182         POINT wptr;
183         GetCursorPos(&wptr);
184         return win_find(GetAncestor(WindowFromPoint(wptr),GA_ROOT),0);
185 }
186
187 static win_t *win_focused(void)
188 {
189         return win_find(GetForegroundWindow(),0);
190 }
191
192 /* Callbacks */
193 LRESULT CALLBACK KbdProc(int msg, WPARAM wParam, LPARAM lParam)
194 {
195         KBDLLHOOKSTRUCT *st = (KBDLLHOOKSTRUCT *)lParam;
196         event_t ev = w2ev(st->vkCode);
197         mod_t mod = getmod();
198         mod.up = !!(st->flags & 0x80);
199         printf("KbdProc: %d,%x,%lx - %lx,%lx,%lx - %x,%x\n",
200                         msg, wParam, lParam,
201                         st->vkCode, st->scanCode, st->flags,
202                         ev, mod2int(mod));
203         return wm_handle_event(win_focused(), ev, mod, getptr())
204                 || CallNextHookEx(0, msg, wParam, lParam);
205 }
206
207 LRESULT CALLBACK MllProc(int msg, WPARAM wParam, LPARAM lParam)
208 {
209         event_t ev = EV_NONE;
210         mod_t  mod = getmod();
211         win_t *win = win_cursor();
212
213         /* Update modifiers */
214         switch (wParam) {
215         case WM_LBUTTONDOWN: mod.up = 0; ev = EV_MOUSE1; break;
216         case WM_LBUTTONUP:   mod.up = 1; ev = EV_MOUSE1; break;
217         case WM_RBUTTONDOWN: mod.up = 0; ev = EV_MOUSE3; break;
218         case WM_RBUTTONUP:   mod.up = 1; ev = EV_MOUSE3; break;
219         }
220
221         /* Check for focus-in/focus-out */
222         static win_t *old = NULL;
223         if (win && win != old) {
224                 wm_handle_event(old, EV_LEAVE, mod, getptr());
225                 wm_handle_event(win, EV_ENTER, mod, getptr());
226         }
227         old = win;
228
229         /* Send mouse movement event */
230         if (wParam == WM_MOUSEMOVE)
231                 return wm_handle_ptr(win_cursor(), getptr());
232         else if (ev != EV_NONE)
233                 return wm_handle_event(win_cursor(), ev, mod, getptr());
234         else
235                 return CallNextHookEx(0, msg, wParam, lParam);
236 }
237
238 LRESULT CALLBACK ShlProc(int msg, WPARAM wParam, LPARAM lParam)
239 {
240         HWND hwnd = (HWND)wParam;
241         win_t *win = NULL;
242         switch (msg) {
243         case HSHELL_REDRAW:
244         case HSHELL_WINDOWCREATED:
245                 printf("ShlProc: %p - %s\n", hwnd, msg == HSHELL_REDRAW ?
246                                 "redraw" : "window created");
247                 if (!(win = win_find(hwnd,0)))
248                         if ((win = win_find(hwnd,1)))
249                                 wm_insert(win);
250                 return 1;
251         case HSHELL_WINDOWREPLACED:
252         case HSHELL_WINDOWDESTROYED:
253                 printf("ShlProc: %p - %s\n", hwnd, msg == HSHELL_WINDOWREPLACED ?
254                                 "window replaced" : "window destroyed");
255                 if ((win = win_find(hwnd,0)) &&
256                     (win->state == ST_SHOW ||
257                      win->state == ST_SHADE)) {
258                         wm_remove(win);
259                         win_remove(win);
260                 }
261                 return 1;
262         case HSHELL_WINDOWACTIVATED:
263                 printf("ShlProc: %p - window activated\n", hwnd);
264                 // Fake button-click (causes crazy switching)
265                 //if ((win = win_find(hwnd,0)))
266                 //      wm_handle_event(win, EV_MOUSE1, MOD(), getptr());
267                 return 0;
268         default:
269                 printf("ShlProc: %p - unknown msg, %d\n", hwnd, msg);
270                 return 0;
271         }
272 }
273
274 LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
275 {
276         //printf("WndProc: %d, %x, %lx\n", msg, wParam, lParam);
277         switch (msg) {
278         case WM_CREATE:  printf("WndProc: %p - create\n",  hwnd); return 0;
279         case WM_CLOSE:   printf("WndProc: %p - close\n",   hwnd); return 0;
280         case WM_DESTROY: printf("WndProc: %p - destroy\n", hwnd); return 0;
281         case WM_HOTKEY:  printf("WndProc: %p - hotkey\n",  hwnd); return 0;
282         }
283         if (msg == shellhookid)
284                 if (ShlProc(wParam, lParam, 0))
285                         return 1;
286         return DefWindowProc(hwnd, msg, wParam, lParam);
287 }
288
289 BOOL CALLBACK MonProc(HMONITOR mon, HDC dc, LPRECT rect, LPARAM _screens)
290 {
291         MONITORINFO info = {.cbSize=sizeof(MONITORINFO)};
292         GetMonitorInfo(mon, &info);
293         RECT *work = &info.rcWork;
294
295         list_t **screens = (list_t**)_screens;
296         win_t *screen = new0(win_t);
297         screen->x = work->left;
298         screen->y = work->top;
299         screen->z = !!(info.dwFlags & MONITORINFOF_PRIMARY);
300         screen->w = work->right  - work->left;
301         screen->h = work->bottom - work->top;
302         *screens = list_append(*screens, screen);
303         printf("mon_proc: %d,%d %dx%d\n",
304                 screen->x, screen->y, screen->w, screen->h);
305         return TRUE;
306 }
307
308 BOOL CALLBACK LoopProc(HWND hwnd, LPARAM user)
309 {
310         win_t *win;
311         if ((win = win_find(hwnd,1)))
312                 wm_insert(win);
313         return TRUE;
314 }
315
316 BOOL WINAPI CtrlProc(DWORD type)
317 {
318         sys_exit();
319         return TRUE;
320 }
321
322 /********************
323  * System functions *
324  ********************/
325 void sys_move(win_t *win, int x, int y, int w, int h)
326 {
327         printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
328         win->x = x; win->y = y;
329         win->w = MAX(w,1); win->h = MAX(h,1);
330         MoveWindow(win->sys->hwnd, win->x, win->y, win->w, win->h, TRUE);
331 }
332
333 void sys_raise(win_t *win)
334 {
335         printf("sys_raise: %p\n", win);
336
337         /* See note in sys_focus */
338         DWORD oldId = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
339         DWORD newId = GetCurrentThreadId();
340         AttachThreadInput(oldId, newId, TRUE);
341
342         SetWindowPos(win->sys->hwnd, NULL, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
343
344         AttachThreadInput(oldId, newId, FALSE);
345 }
346
347 void sys_focus(win_t *win)
348 {
349         printf("sys_focus: %p\n", win);
350
351         /* Windows prevents a thread from using SetForegroundInput under
352          * certain circumstances and instead flashes the windows toolbar icon.
353          * Attaching the thread input queues avoids this behavior */
354         HWND  fgWin = GetForegroundWindow();
355         if (fgWin == win->sys->hwnd)
356                 return; // already focused
357         DWORD oldId = GetWindowThreadProcessId(fgWin, NULL);
358         DWORD newId = GetCurrentThreadId();
359         if (oldId != newId)
360                 AttachThreadInput(oldId, newId, TRUE);
361
362         HWND next = GetWindow(win->sys->hwnd, GW_HWNDNEXT);
363         SetWindowPos(win->sys->hwnd, NULL, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
364         if (next)
365                 SetWindowPos(win->sys->hwnd, next, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
366
367         if (oldId != newId)
368                 AttachThreadInput(oldId, newId, FALSE);
369 }
370
371 void sys_show(win_t *win, state_t state)
372 {
373         static struct {
374                 char *str;
375                 int   cmd;
376         } map[] = {
377                 [ST_SHOW ] {"show" , SW_SHOW    },
378                 [ST_FULL ] {"full" , SW_MAXIMIZE},
379                 [ST_SHADE] {"shade", SW_SHOW    },
380                 [ST_ICON ] {"icon" , SW_MINIMIZE},
381                 [ST_HIDE ] {"hide" , SW_HIDE    },
382         };
383         if (win->state != state && win->state == ST_SHADE)
384                 SetWindowRgn(win->sys->hwnd, NULL, TRUE);
385         win->state = state;
386         printf("sys_show: %s\n", map[state].str);
387         ShowWindow(win->sys->hwnd, map[state].cmd);
388         if (state == ST_SHADE)
389                 SetWindowRgn(win->sys->hwnd, CreateRectRgn(0,0,win->w,stack), TRUE);
390 }
391
392 void sys_watch(win_t *win, event_t ev, mod_t mod)
393 {
394         (void)ev2w; // TODO
395         //printf("sys_watch: %p\n", win);
396 }
397
398 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
399 {
400         (void)ev2w; // TODO
401         //printf("sys_unwatch: %p\n", win);
402 }
403
404 list_t *sys_info(void)
405 {
406         if (screens == NULL)
407                 EnumDisplayMonitors(NULL, NULL, MonProc, (LPARAM)&screens);
408         return screens;
409 }
410
411 void sys_init(void)
412 {
413         HINSTANCE hInst = GetModuleHandle(NULL);
414
415         /* Load configuration */
416         no_capture = conf_get_int("main.no-capture", no_capture);
417         stack      = conf_get_int("main.stack",      stack);
418
419         /* Setup window class */
420         WNDCLASSEX wc    = {
421                 .cbSize        = sizeof(WNDCLASSEX),
422                 .lpfnWndProc   = WndProc,
423                 .hInstance     = hInst,
424                 .lpszClassName = "wmpus_class",
425         };
426         if (!RegisterClassEx(&wc))
427                 printf("sys_init: Error Registering Class - %lu\n", GetLastError());
428
429         /* Get work area */
430         RECT rc;
431         SystemParametersInfo(SPI_GETWORKAREA, 0, &rc, 0);
432
433         /* Create shell hook window */
434         if (!(root = CreateWindowEx(0, "wmpus_class", "wmpus", 0,
435                         rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top,
436                         HWND_MESSAGE, NULL, hInst, NULL)))
437                 printf("sys_init: Error Creating Shell Hook Window - %lu\n", GetLastError());
438
439         /* Register shell hook */
440         BOOL (*RegisterShellHookWindow)(HWND) = (void*)GetProcAddress(
441                         GetModuleHandle("USER32.DLL"), "RegisterShellHookWindow");
442         if (!RegisterShellHookWindow)
443                 printf("sys_init: Error Finding RegisterShellHookWindow - %lu\n", GetLastError());
444         if (!RegisterShellHookWindow(root))
445                 printf("sys_init: Error Registering ShellHook Window - %lu\n", GetLastError());
446         shellhookid = RegisterWindowMessage("SHELLHOOK");
447
448         /* Input hooks */
449         SetWindowsHookEx(WH_KEYBOARD_LL, KbdProc, hInst, 0);
450         SetWindowsHookEx(WH_MOUSE_LL,    MllProc, hInst, 0);
451         //SetWindowsHookEx(WH_SHELL,       ShlProc, hInst, 0);
452
453         /* Alternate ways to get input */
454         //if (!RegisterHotKey(root, 123, MOD_CONTROL, VK_LBUTTON))
455         //      printf("sys_init: Error Registering Hotkey - %lu\n", GetLastError());
456         //if (!RegisterHotKey(NULL, 123, MOD_CONTROL, VK_LBUTTON))
457         //      printf("sys_init: Error Registering Hotkey - %lu\n", GetLastError());
458
459         /* Capture ctrl-c and console widnow close */
460         SetConsoleCtrlHandler(CtrlProc, TRUE);
461 }
462
463 void sys_run(void)
464 {
465         MSG msg = {};
466         if (!no_capture)
467                 EnumWindows(LoopProc, 0);
468         while (GetMessage(&msg, NULL, 0, 0) > 0 &&
469                msg.message != WM_QUIT) {
470                 TranslateMessage(&msg);
471                 DispatchMessage(&msg);
472         }
473 }
474
475 void sys_exit(void)
476 {
477         PostMessage(root, WM_QUIT, 0, 0);
478 }
479
480 void sys_free(void)
481 {
482         /* I don't really care about this
483          * since I don't know how to use
484          * valgrind on win32 anyway.. */
485 }