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