]> Pileus Git - wmpus/blob - sys-win32.c
Add signal handlers
[wmpus] / sys-win32.c
1 /*
2  * Copyright (c) 2011, 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 0x0500
23 #include <windows.h>
24 #include <winbase.h>
25 #include <winuser.h>
26
27 #include "util.h"
28 #include "conf.h"
29 #include "sys.h"
30 #include "wm.h"
31
32 /* Configuration */
33 static int NO_CAPTURE = 0;
34
35 /* Internal structures */
36 struct win_sys {
37         HWND hwnd;
38         state_t state;
39 };
40
41 typedef struct {
42         Key_t key;
43         int   vk;
44 } keymap_t;
45
46 /* Global data */
47 static int     shellhookid;
48 static void   *cache;
49 static win_t  *root;
50 static list_t *screens;
51
52 /* Conversion functions */
53 static keymap_t key2vk[] = {
54         {key_mouse1  , VK_LBUTTON },
55         {key_mouse2  , VK_MBUTTON },
56         {key_mouse3  , VK_RBUTTON },
57         {key_left    , VK_LEFT    },
58         {key_right   , VK_RIGHT   },
59         {key_up      , VK_UP      },
60         {key_down    , VK_DOWN    },
61         {key_home    , VK_HOME    },
62         {key_end     , VK_END     },
63         {key_pageup  , VK_PRIOR   },
64         {key_pagedown, VK_NEXT    },
65         {key_f1      , VK_F1      },
66         {key_f2      , VK_F2      },
67         {key_f3      , VK_F3      },
68         {key_f4      , VK_F4      },
69         {key_f5      , VK_F5      },
70         {key_f6      , VK_F6      },
71         {key_f7      , VK_F7      },
72         {key_f8      , VK_F8      },
73         {key_f9      , VK_F9      },
74         {key_f10     , VK_F10     },
75         {key_f11     , VK_F11     },
76         {key_f12     , VK_F12     },
77         {key_shift   , VK_SHIFT   },
78         {key_shift   , VK_LSHIFT  },
79         {key_shift   , VK_RSHIFT  },
80         {key_ctrl    , VK_CONTROL },
81         {key_ctrl    , VK_LCONTROL},
82         {key_ctrl    , VK_RCONTROL},
83         {key_alt     , VK_MENU    },
84         {key_alt     , VK_LMENU   },
85         {key_alt     , VK_RMENU   },
86         {key_win     , VK_LWIN    },
87         {key_win     , VK_RWIN    },
88 };
89
90 /* - Keycodes */
91 static Key_t w2key(UINT vk)
92 {
93         keymap_t *km = map_getr(key2vk,vk);
94         return km ? km->key : tolower(vk);
95 }
96
97 static UINT key2w(Key_t key)
98 {
99         keymap_t *km = map_get(key2vk,key);
100         return km ? km->vk : toupper(key);
101 }
102
103 static mod_t getmod(void)
104 {
105         return (mod_t){
106                 .alt   = GetKeyState(VK_MENU)    < 0,
107                 .ctrl  = GetKeyState(VK_CONTROL) < 0,
108                 .shift = GetKeyState(VK_SHIFT)   < 0,
109                 .win   = GetKeyState(VK_LWIN)    < 0 ||
110                          GetKeyState(VK_RWIN)    < 0,
111         };
112 }
113
114 /* - Pointers */
115 static ptr_t getptr(void)
116 {
117         POINT wptr;
118         GetCursorPos(&wptr);
119         return (ptr_t){-1, -1, wptr.x, wptr.y};
120 }
121
122 /* Window functions */
123 static win_t *win_new(HWND hwnd, int checkwin)
124 {
125         if (checkwin) {
126                 char winclass[256];
127                 int exstyle = GetWindowLong(hwnd, GWL_EXSTYLE);
128                 GetClassName(hwnd, winclass, sizeof(winclass));
129                 if (!IsWindowVisible(hwnd))      return NULL; // Invisible stuff..
130                 if (!strcmp("#32770", winclass)) return NULL; // Message boxes
131                 if (GetWindow(hwnd, GW_OWNER))   return NULL; // Dialog boxes, etc
132                 if (exstyle & WS_EX_TOOLWINDOW)  return NULL; // Floating toolbars
133         }
134
135         RECT rect = {};
136         GetWindowRect(hwnd, &rect);
137         win_t *win = new0(win_t);
138         win->x         = rect.left;
139         win->y         = rect.top;
140         win->w         = rect.right  - rect.left;
141         win->h         = rect.bottom - rect.top;
142         win->sys       = new0(win_sys_t);
143         win->sys->hwnd = hwnd;
144         printf("win_new: %p = %p (%d,%d %dx%d)\n", win, hwnd,
145                         win->x, win->y, win->w, win->h);
146         return win;
147 }
148
149 static int win_cmp(const void *_a, const void *_b)
150 {
151         const win_t *a = _a, *b = _b;
152         if (a->sys->hwnd < b->sys->hwnd) return -1;
153         if (a->sys->hwnd > b->sys->hwnd) return  1;
154         return 0;
155 }
156
157 static win_t *win_find(HWND hwnd, int create)
158 {
159         if (!hwnd)
160                 return NULL;
161         //printf("win_find: %p, %d\n", dpy, (int)xid);
162         win_sys_t sys = {.hwnd=hwnd};
163         win_t     tmp = {.sys=&sys};
164         win_t **old = NULL, *new = NULL;
165         if ((old = tfind(&tmp, &cache, win_cmp)))
166                 return *old;
167         if (create && (new = win_new(hwnd,1)))
168                 tsearch(new, &cache, win_cmp);
169         return new;
170 }
171
172 static void win_remove(win_t *win)
173 {
174         tdelete(win, &cache, win_cmp);
175         free(win->sys);
176         free(win);
177 }
178
179 static win_t *win_cursor(void)
180 {
181         POINT wptr;
182         GetCursorPos(&wptr);
183         return win_find(GetAncestor(WindowFromPoint(wptr),GA_ROOT),0);
184 }
185
186 static win_t *win_focused(void)
187 {
188         return win_find(GetForegroundWindow(),0);
189 }
190
191 /* Callbacks */
192 LRESULT CALLBACK KbdProc(int msg, WPARAM wParam, LPARAM lParam)
193 {
194         KBDLLHOOKSTRUCT *st = (KBDLLHOOKSTRUCT *)lParam;
195         Key_t key = w2key(st->vkCode);
196         mod_t mod = getmod();
197         mod.up = !!(st->flags & 0x80);
198         printf("KbdProc: %d,%x,%lx - %lx,%lx,%lx - %x,%x\n",
199                         msg, wParam, lParam,
200                         st->vkCode, st->scanCode, st->flags,
201                         key, mod2int(mod));
202         return wm_handle_key(win_focused() ?: root, key, mod, getptr())
203                 || CallNextHookEx(0, msg, wParam, lParam);
204 }
205
206 LRESULT CALLBACK MllProc(int msg, WPARAM wParam, LPARAM lParam)
207 {
208         Key_t  key = key_none;
209         mod_t  mod = getmod();
210         win_t *win = win_cursor();
211
212         /* Update modifiers */
213         switch (wParam) {
214         case WM_LBUTTONDOWN: mod.up = 0; key = key_mouse1; break;
215         case WM_LBUTTONUP:   mod.up = 1; key = key_mouse1; break;
216         case WM_RBUTTONDOWN: mod.up = 0; key = key_mouse3; break;
217         case WM_RBUTTONUP:   mod.up = 1; key = key_mouse3; break;
218         }
219
220         /* Check for focus-in/focus-out */
221         static win_t *old = NULL;
222         if (win && win != old) {
223                 wm_handle_key(old, key_leave, mod, getptr());
224                 wm_handle_key(win, key_enter, mod, getptr());
225         }
226         old = win;
227
228         /* Send mouse movement event */
229         if (wParam == WM_MOUSEMOVE)
230                 return wm_handle_ptr(win_cursor(), getptr());
231         else if (key != key_none)
232                 return wm_handle_key(win_cursor(), key, mod, getptr());
233         else
234                 return CallNextHookEx(0, msg, wParam, lParam);
235 }
236
237 LRESULT CALLBACK ShlProc(int msg, WPARAM wParam, LPARAM lParam)
238 {
239         HWND hwnd = (HWND)wParam;
240         win_t *win = NULL;
241         switch (msg) {
242         case HSHELL_WINDOWCREATED:
243         case HSHELL_REDRAW:
244                 printf("ShlProc: %p - %s\n", hwnd, msg == HSHELL_REDRAW ?
245                                 "redraw" : "window created");
246                 if (!(win = win_find(hwnd,0)))
247                         if ((win = win_find(hwnd,1)))
248                                 wm_insert(win);
249                 return 1;
250         case HSHELL_WINDOWDESTROYED:
251                 printf("ShlProc: %p - window destroyed\n", hwnd);
252                 if ((win = win_find(hwnd,0)) &&
253                     win->sys->state == st_show) {
254                         wm_remove(win);
255                         win_remove(win);
256                 }
257                 return 1;
258         case HSHELL_WINDOWACTIVATED:
259                 printf("ShlProc: %p - window activated\n", hwnd);
260                 return 0;
261         default:
262                 printf("ShlProc: %p - unknown msg, %d\n", hwnd, msg);
263                 return 0;
264         }
265 }
266
267 LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
268 {
269         //printf("WndProc: %d, %x, %lx\n", msg, wParam, lParam);
270         switch (msg) {
271         case WM_CREATE:  printf("WndProc: %p - create\n",  hwnd); return 0;
272         case WM_CLOSE:   printf("WndProc: %p - close\n",   hwnd); return 0;
273         case WM_DESTROY: printf("WndProc: %p - destroy\n", hwnd); return 0;
274         case WM_HOTKEY:  printf("WndProc: %p - hotkey\n",  hwnd); return 0;
275         }
276         if (msg == shellhookid)
277                 if (ShlProc(wParam, lParam, 0))
278                         return 1;
279         return DefWindowProc(hwnd, msg, wParam, lParam);
280 }
281
282 BOOL CALLBACK MonProc(HMONITOR mon, HDC dc, LPRECT rect, LPARAM _screens)
283 {
284         MONITORINFO info = {.cbSize=sizeof(MONITORINFO)};
285         GetMonitorInfo(mon, &info);
286         RECT *work = &info.rcWork;
287
288         list_t **screens = (list_t**)_screens;
289         win_t *screen = new0(win_t);
290         screen->x = work->left;
291         screen->y = work->top;
292         screen->w = work->right  - work->left;
293         screen->h = work->bottom - work->top;
294         *screens = list_append(*screens, screen);
295         printf("mon_proc: %d,%d %dx%d\n",
296                 screen->x, screen->y, screen->w, screen->h);
297         return TRUE;
298 }
299
300 BOOL CALLBACK LoopProc(HWND hwnd, LPARAM user)
301 {
302         win_t *win;
303         if ((win = win_find(hwnd,1)))
304                 wm_insert(win);
305         return TRUE;
306 }
307
308 BOOL WINAPI CtrlProc(DWORD type)
309 {
310         sys_exit();
311         return TRUE;
312 }
313
314 /********************
315  * System functions *
316  ********************/
317 void sys_move(win_t *win, int x, int y, int w, int h)
318 {
319         printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
320         win->x = x; win->y = y;
321         win->w = MAX(w,1); win->h = MAX(h,1);
322         MoveWindow(win->sys->hwnd, win->x, win->y, win->w, win->h, TRUE);
323 }
324
325 void sys_raise(win_t *win)
326 {
327         printf("sys_raise: %p\n", win);
328         SetForegroundWindow(win->sys->hwnd);
329
330         //HWND hwnd = win->sys->hwnd;
331         //HWND top  = GetAncestor(hwnd,GA_ROOT);
332         //SetWindowPos(top, HWND_TOPMOST, 0, 0, 0, 0,
333         //              SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
334 }
335
336 void sys_focus(win_t *win)
337 {
338         printf("sys_focus: %p\n", win);
339
340         /* Windows prevents a thread from using SetForegroundInput under
341          * certain circumstances and instead flashes the windows toolbar icon.
342          * Attaching the thread input queues avoids this behavior */
343         DWORD oldId = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
344         DWORD newId = GetCurrentThreadId();
345         AttachThreadInput(oldId, newId, TRUE);
346
347         BringWindowToTop(win->sys->hwnd);
348         SetForegroundWindow(win->sys->hwnd);
349         SetFocus(win->sys->hwnd);
350
351         AttachThreadInput(oldId, newId, FALSE);
352 }
353
354 void sys_show(win_t *win, state_t state)
355 {
356         static struct {
357                 char *str;
358                 int   cmd;
359         } map[] = {
360                 [st_show ] {"show" , SW_SHOW    },
361                 [st_full ] {"full" , SW_MAXIMIZE},
362                 [st_shade] {"shade", SW_SHOW    },
363                 [st_icon ] {"icon" , SW_MINIMIZE},
364                 [st_hide ] {"hide" , SW_HIDE    },
365         };
366         win->sys->state = state;
367         printf("sys_show: %s\n", map[state].str);
368         ShowWindow(win->sys->hwnd, map[state].cmd);
369 }
370
371 void sys_watch(win_t *win, Key_t key, mod_t mod)
372 {
373         (void)key2w; // TODO
374         //printf("sys_watch: %p\n", win);
375 }
376
377 void sys_unwatch(win_t *win, Key_t key, mod_t mod)
378 {
379         (void)key2w; // TODO
380         //printf("sys_unwatch: %p\n", win);
381 }
382
383 list_t *sys_info(win_t *win)
384 {
385         if (screens == NULL)
386                 EnumDisplayMonitors(NULL, NULL, MonProc, (LPARAM)&screens);
387         return screens;
388 }
389
390 win_t *sys_init(void)
391 {
392         HINSTANCE hInst = GetModuleHandle(NULL);
393         HWND      hwnd  = NULL;
394
395         /* Load configuration */
396         NO_CAPTURE = conf_get_int("main.no-capture", NO_CAPTURE);
397
398         /* Setup window class */
399         WNDCLASSEX wc    = {
400                 .cbSize        = sizeof(WNDCLASSEX),
401                 .lpfnWndProc   = WndProc,
402                 .hInstance     = hInst,
403                 .lpszClassName = "wmpus_class",
404         };
405         if (!RegisterClassEx(&wc))
406                 printf("sys_init: Error Registering Class - %lu\n", GetLastError());
407
408         /* Get work area */
409         RECT rc;
410         SystemParametersInfo(SPI_GETWORKAREA, 0, &rc, 0);
411
412         /* Create shell hook window */
413         if (!(hwnd = CreateWindowEx(0, "wmpus_class", "wmpus", 0,
414                         rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top,
415                         HWND_MESSAGE, NULL, hInst, NULL)))
416                 printf("sys_init: Error Creating Shell Hook Window - %lu\n", GetLastError());
417
418         /* Register shell hook */
419         BOOL (*RegisterShellHookWindow)(HWND) = (void*)GetProcAddress(
420                         GetModuleHandle("USER32.DLL"), "RegisterShellHookWindow");
421         if (!RegisterShellHookWindow)
422                 printf("sys_init: Error Finding RegisterShellHookWindow - %lu\n", GetLastError());
423         if (!RegisterShellHookWindow(hwnd))
424                 printf("sys_init: Error Registering ShellHook Window - %lu\n", GetLastError());
425         shellhookid = RegisterWindowMessage("SHELLHOOK");
426
427         /* Input hooks */
428         SetWindowsHookEx(WH_KEYBOARD_LL, KbdProc, hInst, 0);
429         SetWindowsHookEx(WH_MOUSE_LL,    MllProc, hInst, 0);
430         //SetWindowsHookEx(WH_SHELL,       ShlProc, hInst, 0);
431
432         /* Alternate ways to get input */
433         //if (!RegisterHotKey(hwnd, 123, MOD_CONTROL, VK_LBUTTON))
434         //      printf("sys_init: Error Registering Hotkey - %lu\n", GetLastError());
435         //if (!RegisterHotKey(NULL, 123, MOD_CONTROL, VK_LBUTTON))
436         //      printf("sys_init: Error Registering Hotkey - %lu\n", GetLastError());
437
438         /* Capture ctrl-c and console widnow close */
439         SetConsoleCtrlHandler(CtrlProc, TRUE);
440
441         return root = win_new(hwnd,0);
442 }
443
444 void sys_run(win_t *root)
445 {
446         MSG msg = {};
447         if (!NO_CAPTURE)
448                 EnumWindows(LoopProc, 0);
449         while (GetMessage(&msg, NULL, 0, 0) > 0 &&
450                msg.message != WM_QUIT) {
451                 TranslateMessage(&msg);
452                 DispatchMessage(&msg);
453         }
454 }
455
456 void sys_exit(void)
457 {
458         PostMessage(root->sys->hwnd, WM_QUIT, 0, 0);
459 }
460
461 void sys_free(win_t *root)
462 {
463         /* I don't really care about this
464          * since I don't know how to use
465          * valgrind on win32 anyway.. */
466 }