]> Pileus Git - wmpus/blob - sys-win32.c
1562a5e044f1946a62b5c6f4b368e7991201d99f
[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     running;
48 static int     shellhookid;
49 static void   *cache;
50 static win_t  *root;
51 static list_t *screens;
52
53 /* Conversion functions */
54 static keymap_t key2vk[] = {
55         {key_mouse1  , VK_LBUTTON },
56         {key_mouse2  , VK_MBUTTON },
57         {key_mouse3  , VK_RBUTTON },
58         {key_left    , VK_LEFT    },
59         {key_right   , VK_RIGHT   },
60         {key_up      , VK_UP      },
61         {key_down    , VK_DOWN    },
62         {key_home    , VK_HOME    },
63         {key_end     , VK_END     },
64         {key_pageup  , VK_PRIOR   },
65         {key_pagedown, VK_NEXT    },
66         {key_f1      , VK_F1      },
67         {key_f2      , VK_F2      },
68         {key_f3      , VK_F3      },
69         {key_f4      , VK_F4      },
70         {key_f5      , VK_F5      },
71         {key_f6      , VK_F6      },
72         {key_f7      , VK_F7      },
73         {key_f8      , VK_F8      },
74         {key_f9      , VK_F9      },
75         {key_f10     , VK_F10     },
76         {key_f11     , VK_F11     },
77         {key_f12     , VK_F12     },
78         {key_shift   , VK_SHIFT   },
79         {key_shift   , VK_LSHIFT  },
80         {key_shift   , VK_RSHIFT  },
81         {key_ctrl    , VK_CONTROL },
82         {key_ctrl    , VK_LCONTROL},
83         {key_ctrl    , VK_RCONTROL},
84         {key_alt     , VK_MENU    },
85         {key_alt     , VK_LMENU   },
86         {key_alt     , VK_RMENU   },
87         {key_win     , VK_LWIN    },
88         {key_win     , VK_RWIN    },
89 };
90
91 /* - Keycodes */
92 static Key_t w2key(UINT vk)
93 {
94         keymap_t *km = map_getr(key2vk,vk);
95         return km ? km->key : tolower(vk);
96 }
97
98 static UINT key2w(Key_t key)
99 {
100         keymap_t *km = map_get(key2vk,key);
101         return km ? km->vk : toupper(key);
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         Key_t key = w2key(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                         key, mod2int(mod));
203         return wm_handle_key(win_focused() ?: root, key, mod, getptr())
204                 || CallNextHookEx(0, msg, wParam, lParam);
205 }
206
207 LRESULT CALLBACK MllProc(int msg, WPARAM wParam, LPARAM lParam)
208 {
209         Key_t  key = key_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; key = key_mouse1; break;
216         case WM_LBUTTONUP:   mod.up = 1; key = key_mouse1; break;
217         case WM_RBUTTONDOWN: mod.up = 0; key = key_mouse3; break;
218         case WM_RBUTTONUP:   mod.up = 1; key = key_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_key(old, key_leave, mod, getptr());
225                 wm_handle_key(win, key_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 (key != key_none)
233                 return wm_handle_key(win_cursor(), key, 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_WINDOWCREATED:
244         case HSHELL_REDRAW:
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_WINDOWDESTROYED:
252                 printf("ShlProc: %p - window destroyed\n", hwnd);
253                 if ((win = win_find(hwnd,0)) &&
254                     win->sys->state == st_show) {
255                         wm_remove(win);
256                         win_remove(win);
257                 }
258                 return 1;
259         case HSHELL_WINDOWACTIVATED:
260                 printf("ShlProc: %p - window activated\n", hwnd);
261                 return 0;
262         default:
263                 printf("ShlProc: %p - unknown msg, %d\n", hwnd, msg);
264                 return 0;
265         }
266 }
267
268 LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
269 {
270         //printf("WndProc: %d, %x, %lx\n", msg, wParam, lParam);
271         switch (msg) {
272         case WM_CREATE:  printf("WndProc: %p - create\n",  hwnd); return 0;
273         case WM_CLOSE:   printf("WndProc: %p - close\n",   hwnd); return 0;
274         case WM_DESTROY: printf("WndProc: %p - destroy\n", hwnd); return 0;
275         case WM_HOTKEY:  printf("WndProc: %p - hotkey\n",  hwnd); return 0;
276         }
277         if (msg == shellhookid)
278                 if (ShlProc(wParam, lParam, 0))
279                         return 1;
280         return DefWindowProc(hwnd, msg, wParam, lParam);
281 }
282
283 BOOL CALLBACK MonProc(HMONITOR mon, HDC dc, LPRECT rect, LPARAM _screens)
284 {
285         MONITORINFO info = {.cbSize=sizeof(MONITORINFO)};
286         GetMonitorInfo(mon, &info);
287         RECT *work = &info.rcWork;
288
289         list_t **screens = (list_t**)_screens;
290         win_t *screen = new0(win_t);
291         screen->x = work->left;
292         screen->y = work->top;
293         screen->w = work->right  - work->left;
294         screen->h = work->bottom - work->top;
295         *screens = list_append(*screens, screen);
296         printf("mon_proc: %d,%d %dx%d\n",
297                 screen->x, screen->y, screen->w, screen->h);
298         return TRUE;
299 }
300
301 BOOL CALLBACK LoopProc(HWND hwnd, LPARAM user)
302 {
303         win_t *win;
304         if ((win = win_find(hwnd,1)))
305                 wm_insert(win);
306         return TRUE;
307 }
308
309 /********************
310  * System functions *
311  ********************/
312 void sys_move(win_t *win, int x, int y, int w, int h)
313 {
314         printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
315         win->x = x; win->y = y;
316         win->w = MAX(w,1); win->h = MAX(h,1);
317         MoveWindow(win->sys->hwnd, win->x, win->y, win->w, win->h, TRUE);
318 }
319
320 void sys_raise(win_t *win)
321 {
322         printf("sys_raise: %p\n", win);
323         SetForegroundWindow(win->sys->hwnd);
324
325         //HWND hwnd = win->sys->hwnd;
326         //HWND top  = GetAncestor(hwnd,GA_ROOT);
327         //SetWindowPos(top, HWND_TOPMOST, 0, 0, 0, 0,
328         //              SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
329 }
330
331 void sys_focus(win_t *win)
332 {
333         printf("sys_focus: %p\n", win);
334
335         /* Windows prevents a thread from using SetForegroundInput under
336          * certain circumstances and instead flashes the windows toolbar icon.
337          * Attaching the thread input queues avoids this behavior */
338         DWORD oldId = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
339         DWORD newId = GetCurrentThreadId();
340         AttachThreadInput(oldId, newId, TRUE);
341
342         BringWindowToTop(win->sys->hwnd);
343         SetForegroundWindow(win->sys->hwnd);
344         SetFocus(win->sys->hwnd);
345
346         AttachThreadInput(oldId, newId, FALSE);
347 }
348
349 void sys_show(win_t *win, state_t state)
350 {
351         static struct {
352                 char *str;
353                 int   cmd;
354         } map[] = {
355                 [st_show ] {"show" , SW_SHOW    },
356                 [st_full ] {"full" , SW_MAXIMIZE},
357                 [st_shade] {"shade", SW_SHOW    },
358                 [st_icon ] {"icon" , SW_MINIMIZE},
359                 [st_hide ] {"hide" , SW_HIDE    },
360         };
361         win->sys->state = state;
362         printf("sys_show: %s\n", map[state].str);
363         ShowWindow(win->sys->hwnd, map[state].cmd);
364 }
365
366 void sys_watch(win_t *win, Key_t key, mod_t mod)
367 {
368         (void)key2w; // TODO
369         //printf("sys_watch: %p\n", win);
370 }
371
372 void sys_unwatch(win_t *win, Key_t key, mod_t mod)
373 {
374         (void)key2w; // TODO
375         //printf("sys_unwatch: %p\n", win);
376 }
377
378 list_t *sys_info(win_t *win)
379 {
380         if (screens == NULL)
381                 EnumDisplayMonitors(NULL, NULL, MonProc, (LPARAM)&screens);
382         return screens;
383 }
384
385 win_t *sys_init(void)
386 {
387         HINSTANCE hInst = GetModuleHandle(NULL);
388         HWND      hwnd  = NULL;
389
390         /* Load configuration */
391         NO_CAPTURE = conf_get_int("main.no-capture", NO_CAPTURE);
392
393         /* Setup window class */
394         WNDCLASSEX wc    = {
395                 .cbSize        = sizeof(WNDCLASSEX),
396                 .lpfnWndProc   = WndProc,
397                 .hInstance     = hInst,
398                 .lpszClassName = "wmpus_class",
399         };
400         if (!RegisterClassEx(&wc))
401                 printf("sys_init: Error Registering Class - %lu\n", GetLastError());
402
403         /* Get work area */
404         RECT rc;
405         SystemParametersInfo(SPI_GETWORKAREA, 0, &rc, 0);
406
407         /* Create shell hook window */
408         if (!(hwnd = CreateWindowEx(0, "wmpus_class", "wmpus", 0,
409                         rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top,
410                         HWND_MESSAGE, NULL, hInst, NULL)))
411                 printf("sys_init: Error Creating Shell Hook Window - %lu\n", GetLastError());
412
413         /* Register shell hook */
414         BOOL (*RegisterShellHookWindow)(HWND) = (void*)GetProcAddress(
415                         GetModuleHandle("USER32.DLL"), "RegisterShellHookWindow");
416         if (!RegisterShellHookWindow)
417                 printf("sys_init: Error Finding RegisterShellHookWindow - %lu\n", GetLastError());
418         if (!RegisterShellHookWindow(hwnd))
419                 printf("sys_init: Error Registering ShellHook Window - %lu\n", GetLastError());
420         shellhookid = RegisterWindowMessage("SHELLHOOK");
421
422         /* Input hooks */
423         SetWindowsHookEx(WH_KEYBOARD_LL, KbdProc, hInst, 0);
424         SetWindowsHookEx(WH_MOUSE_LL,    MllProc, hInst, 0);
425         //SetWindowsHookEx(WH_SHELL,       ShlProc, hInst, 0);
426
427         /* Alternate ways to get input */
428         //if (!RegisterHotKey(hwnd, 123, MOD_CONTROL, VK_LBUTTON))
429         //      printf("sys_init: Error Registering Hotkey - %lu\n", GetLastError());
430         //if (!RegisterHotKey(NULL, 123, MOD_CONTROL, VK_LBUTTON))
431         //      printf("sys_init: Error Registering Hotkey - %lu\n", GetLastError());
432
433         return root = win_new(hwnd,0);
434 }
435
436 void sys_run(win_t *root)
437 {
438         MSG msg;
439
440         if (!NO_CAPTURE)
441                 EnumWindows(LoopProc, 0);
442
443         running = 1;
444         while (running && GetMessage(&msg, NULL, 0, 0) > 0) {
445                 TranslateMessage(&msg);
446                 DispatchMessage(&msg);
447         }
448 }
449
450 void sys_exit(void)
451 {
452         running = 0;
453 }
454
455 void sys_free(win_t *root)
456 {
457         /* I don't really care about this
458          * since I don't know how to use
459          * valgrind on win32 anyway.. */
460 }