]> Pileus Git - wmpus/blob - sys-win32.c
Windows testing
[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 "sys.h"
30 #include "wm.h"
31
32 /* Configuration */
33 static int no_capture = 0;
34 static int stack      = 25;
35
36 /* Internal structures */
37 struct win_sys {
38         HWND hwnd;
39 };
40
41 typedef struct {
42         event_t ev;
43         int     vk;
44 } event_map_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 event_map_t ev2vk[] = {
54         {EV_MOUSE1  , VK_LBUTTON },
55         {EV_MOUSE2  , VK_MBUTTON },
56         {EV_MOUSE3  , VK_RBUTTON },
57         {EV_LEFT    , VK_LEFT    },
58         {EV_RIGHT   , VK_RIGHT   },
59         {EV_UP      , VK_UP      },
60         {EV_DOWN    , VK_DOWN    },
61         {EV_HOME    , VK_HOME    },
62         {EV_END     , VK_END     },
63         {EV_PAGEUP  , VK_PRIOR   },
64         {EV_PAGEDOWN, VK_NEXT    },
65         {EV_F1      , VK_F1      },
66         {EV_F2      , VK_F2      },
67         {EV_F3      , VK_F3      },
68         {EV_F4      , VK_F4      },
69         {EV_F5      , VK_F5      },
70         {EV_F6      , VK_F6      },
71         {EV_F7      , VK_F7      },
72         {EV_F8      , VK_F8      },
73         {EV_F9      , VK_F9      },
74         {EV_F10     , VK_F10     },
75         {EV_F11     , VK_F11     },
76         {EV_F12     , VK_F12     },
77         {EV_SHIFT   , VK_SHIFT   },
78         {EV_SHIFT   , VK_LSHIFT  },
79         {EV_SHIFT   , VK_RSHIFT  },
80         {EV_CTRL    , VK_CONTROL },
81         {EV_CTRL    , VK_LCONTROL},
82         {EV_CTRL    , VK_RCONTROL},
83         {EV_ALT     , VK_MENU    },
84         {EV_ALT     , VK_LMENU   },
85         {EV_ALT     , VK_RMENU   },
86         {EV_WIN     , VK_LWIN    },
87         {EV_WIN     , VK_RWIN    },
88 };
89
90 /* - Keycodes */
91 static event_t w2ev(UINT vk)
92 {
93         event_map_t *em = map_getr(ev2vk,vk);
94         return em ? em->ev : tolower(vk);
95 }
96
97 static UINT ev2w(event_t ev)
98 {
99         event_map_t *em = map_get(ev2vk,ev);
100         return em ? em->vk : toupper(ev);
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         WINDOWINFO info = { .cbSize = sizeof(info) };
126
127         if (checkwin) {
128                 char winclass[256];
129                 GetWindowInfo(hwnd, &info);
130                 GetClassName(hwnd, winclass, sizeof(winclass));
131                 printf("skip?");
132                 if (!IsWindowVisible(hwnd))
133                         return NULL; // Invisible stuff..
134                 if (!strcmp("#32770", winclass))
135                         return NULL; // Message boxes
136                 if (info.dwExStyle & WS_EX_TOOLWINDOW)
137                         return NULL; // Floating toolbars
138         }
139
140         RECT rect = {};
141         GetWindowRect(hwnd, &rect);
142         win_t *win = new0(win_t);
143         win->x         = rect.left;
144         win->y         = rect.top;
145         win->w         = rect.right  - rect.left;
146         win->h         = rect.bottom - rect.top;
147         win->sys       = new0(win_sys_t);
148         win->sys->hwnd = hwnd;
149
150         if (checkwin) {
151                 if (info.dwStyle & WS_POPUP)
152                         win->type = TYPE_DIALOG;
153                 if (!(info.dwStyle & WS_MINIMIZEBOX))
154                         win->type = TYPE_DIALOG;
155         }
156
157         printf("win_new: %p = %p (%d,%d %dx%d)\n", win, hwnd,
158                         win->x, win->y, win->w, win->h);
159         return win;
160 }
161
162 static int win_cmp(const void *_a, const void *_b)
163 {
164         const win_t *a = _a, *b = _b;
165         if (a->sys->hwnd < b->sys->hwnd) return -1;
166         if (a->sys->hwnd > b->sys->hwnd) return  1;
167         return 0;
168 }
169
170 static win_t *win_find(HWND hwnd, int create)
171 {
172         if (!hwnd)
173                 return NULL;
174         //printf("win_find: %p, %d\n", dpy, (int)xid);
175         win_sys_t sys = {.hwnd=hwnd};
176         win_t     tmp = {.sys=&sys};
177         win_t **old = NULL, *new = NULL;
178         if ((old = tfind(&tmp, &cache, win_cmp)))
179                 return *old;
180         if (create && (new = win_new(hwnd,1)))
181                 tsearch(new, &cache, win_cmp);
182         return new;
183 }
184
185 static void win_remove(win_t *win)
186 {
187         wm_remove(win);
188         tdelete(win, &cache, win_cmp);
189         free(win->sys);
190         free(win);
191 }
192
193 static win_t *win_cursor(void)
194 {
195         POINT wptr;
196         GetCursorPos(&wptr);
197         return win_find(GetAncestor(WindowFromPoint(wptr),GA_ROOT),0);
198 }
199
200 static win_t *win_focused(void)
201 {
202         return win_find(GetForegroundWindow(),0);
203 }
204
205 /* Callbacks */
206 LRESULT CALLBACK KbdProc(int msg, WPARAM wParam, LPARAM lParam)
207 {
208         KBDLLHOOKSTRUCT *st = (KBDLLHOOKSTRUCT *)lParam;
209         event_t ev = w2ev(st->vkCode);
210         mod_t mod = getmod();
211         mod.up = !!(st->flags & 0x80);
212         printf("KbdProc: %d,%x,%lx - %lx,%lx,%lx - %x,%02x\n",
213                         msg, wParam, lParam,
214                         st->vkCode, st->scanCode, st->flags,
215                         ev, mod2int(mod));
216         if (wm_handle_event(win_focused() ?: root, ev, mod, getptr())) {
217                 printf("handled\n");
218                 return 1;
219         }
220         return CallNextHookEx(0, msg, wParam, lParam);
221 }
222
223 LRESULT CALLBACK MllProc(int msg, WPARAM wParam, LPARAM lParam)
224 {
225         event_t ev = EV_NONE;
226         mod_t  mod = getmod();
227         win_t *win = win_cursor();
228
229         /* Update modifiers */
230         switch (wParam) {
231         case WM_LBUTTONDOWN: mod.up = 0; ev = EV_MOUSE1; break;
232         case WM_LBUTTONUP:   mod.up = 1; ev = EV_MOUSE1; break;
233         case WM_RBUTTONDOWN: mod.up = 0; ev = EV_MOUSE3; break;
234         case WM_RBUTTONUP:   mod.up = 1; ev = EV_MOUSE3; break;
235         }
236
237         /* Check for focus-in/focus-out */
238         static win_t *old = NULL;
239         if (win && win != old) {
240                 wm_handle_event(old, EV_LEAVE, mod, getptr());
241                 wm_handle_event(win, EV_ENTER, mod, getptr());
242         }
243         old = win;
244
245         /* Send mouse movement event */
246         if (wParam == WM_MOUSEMOVE)
247                 return wm_handle_ptr(win_cursor(), getptr());
248         else if (ev != EV_NONE)
249                 return wm_handle_event(win_cursor(), ev, mod, getptr());
250         else
251                 return CallNextHookEx(0, msg, wParam, lParam);
252 }
253
254 LRESULT CALLBACK ShlProc(int msg, WPARAM wParam, LPARAM lParam)
255 {
256         HWND hwnd = (HWND)wParam;
257         win_t *win = NULL;
258         switch (msg) {
259         case HSHELL_REDRAW:
260         case HSHELL_WINDOWCREATED:
261                 printf("ShlProc: %p - %s\n", hwnd, msg == HSHELL_REDRAW ?
262                                 "redraw" : "window created");
263                 if (!(win = win_find(hwnd,0)))
264                         if ((win = win_find(hwnd,1)))
265                                 wm_insert(win);
266                 return 1;
267         case HSHELL_WINDOWREPLACED:
268         case HSHELL_WINDOWDESTROYED:
269                 printf("ShlProc: %p - %s\n", hwnd, msg == HSHELL_WINDOWREPLACED ?
270                                 "window replaced" : "window destroyed");
271                 if ((win = win_find(hwnd,0)) &&
272                     (win->state != ST_HIDE))
273                         win_remove(win);
274                 return 1;
275         case HSHELL_WINDOWACTIVATED:
276                 printf("ShlProc: %p - window activated\n", hwnd);
277                 if ((win = win_find(hwnd,0))) {
278                         wm_handle_state(win, win->state, ST_SHOW);
279                         win->state = ST_SHOW;
280                         // Fake button-click (causes crazy switching)
281                         // wm_handle_event(win, EV_MOUSE1, MOD(), getptr());
282                 }
283                 return 0;
284         case HSHELL_GETMINRECT:
285                 printf("ShlProc: %p - window minimize\n", hwnd);
286                 wm_handle_state(win, win->state, ST_ICON);
287                 win->state = ST_ICON;
288                 return 0;
289         default:
290                 printf("ShlProc: %p - unknown msg, %d\n", hwnd, msg);
291                 return 0;
292         }
293 }
294
295 LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
296 {
297         //printf("WndProc: %d, %x, %lx\n", msg, wParam, lParam);
298         switch (msg) {
299         case WM_CREATE:  printf("WndProc: %p - create\n",  hwnd); return 0;
300         case WM_CLOSE:   printf("WndProc: %p - close\n",   hwnd); return 0;
301         case WM_DESTROY: printf("WndProc: %p - destroy\n", hwnd); return 0;
302         case WM_HOTKEY:  printf("WndProc: %p - hotkey\n",  hwnd); return 0;
303         }
304         if (msg == shellhookid)
305                 if (ShlProc(wParam, lParam, 0))
306                         return 1;
307         return DefWindowProc(hwnd, msg, wParam, lParam);
308 }
309
310 BOOL CALLBACK MonProc(HMONITOR mon, HDC dc, LPRECT rect, LPARAM _screens)
311 {
312         MONITORINFO info = {.cbSize=sizeof(MONITORINFO)};
313         GetMonitorInfo(mon, &info);
314         RECT *work = &info.rcWork;
315
316         list_t **screens = (list_t**)_screens;
317         win_t *screen = new0(win_t);
318         screen->x = work->left;
319         screen->y = work->top;
320         screen->z = !!(info.dwFlags & MONITORINFOF_PRIMARY);
321         screen->w = work->right  - work->left;
322         screen->h = work->bottom - work->top;
323         *screens = list_append(*screens, screen);
324         printf("mon_proc: %d,%d %dx%d\n",
325                 screen->x, screen->y, screen->w, screen->h);
326         return TRUE;
327 }
328
329 BOOL CALLBACK LoopProc(HWND hwnd, LPARAM user)
330 {
331         win_t *win;
332         if ((win = win_find(hwnd,1)))
333                 wm_insert(win);
334         return TRUE;
335 }
336
337 BOOL WINAPI CtrlProc(DWORD type)
338 {
339         sys_exit();
340         return TRUE;
341 }
342
343 /********************
344  * System functions *
345  ********************/
346 void sys_move(win_t *win, int x, int y, int w, int h)
347 {
348         printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
349         win->x = x; win->y = y;
350         win->w = MAX(w,1); win->h = MAX(h,1);
351         MoveWindow(win->sys->hwnd, win->x, win->y, win->w, win->h, TRUE);
352         SetWindowRgn(win->sys->hwnd, CreateRectRgn(0,0,win->w,win->h), TRUE);
353 }
354
355 void sys_raise(win_t *win)
356 {
357         printf("sys_raise: %p\n", win);
358
359         /* See note in sys_focus */
360         DWORD oldId = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
361         DWORD newId = GetCurrentThreadId();
362         AttachThreadInput(oldId, newId, TRUE);
363
364         SetWindowPos(win->sys->hwnd, NULL, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
365
366         AttachThreadInput(oldId, newId, FALSE);
367 }
368
369 void sys_focus(win_t *win)
370 {
371         printf("sys_focus: %p\n", win);
372
373         /* Windows prevents a thread from using SetForegroundInput under
374          * certain circumstances and instead flashes the windows toolbar icon.
375          * Attaching the thread input queues avoids this behavior */
376         HWND  fgWin = GetForegroundWindow();
377         if (fgWin == win->sys->hwnd)
378                 return; // already focused
379         DWORD oldId = GetWindowThreadProcessId(fgWin, NULL);
380         DWORD newId = GetCurrentThreadId();
381         if (oldId != newId)
382                 AttachThreadInput(oldId, newId, TRUE);
383
384         HWND next = GetWindow(win->sys->hwnd, GW_HWNDNEXT);
385         SetWindowPos(win->sys->hwnd, NULL, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
386         if (next)
387                 SetWindowPos(win->sys->hwnd, next, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
388
389         if (oldId != newId)
390                 AttachThreadInput(oldId, newId, FALSE);
391 }
392
393 void sys_show(win_t *win, state_t state)
394 {
395         static struct {
396                 char *str;
397                 int   cmd;
398         } map[] = {
399                 [ST_HIDE ] {"hide ", SW_HIDE          },
400                 [ST_SHOW ] {"show ", SW_SHOWNOACTIVATE},
401                 [ST_FULL ] {"full ", SW_MAXIMIZE      }, // TODO
402                 [ST_MAX  ] {"max  ", SW_MAXIMIZE      },
403                 [ST_SHADE] {"shade", SW_SHOWNOACTIVATE}, // TODO
404                 [ST_ICON ] {"icon ", SW_MINIMIZE      },
405                 [ST_CLOSE] {"close", SW_HIDE          },
406         };
407
408         printf("sys_show: %p: %s -> %s\n", win,
409                         map[win->state].str, map[state].str);
410
411         /* Show window */
412         if ((win->state == ST_MAX || win->state == ST_ICON) && state == ST_SHOW)
413                 ShowWindowAsync(win->sys->hwnd, SW_RESTORE);
414         else
415                 ShowWindowAsync(win->sys->hwnd, map[state].cmd);
416
417         /* Set/reset clipping */
418         if (state == ST_SHADE)
419                 SetWindowRgn(win->sys->hwnd, CreateRectRgn(3,3,win->w-3,22), TRUE);
420         else if (state != win->state && state != ST_CLOSE)
421                 SetWindowRgn(win->sys->hwnd, NULL, TRUE);
422
423         /* Update window state (used by ShlProc) */
424         win->state = state;
425
426         /* Close the window */
427         if (state == ST_CLOSE)
428                 SendMessage(win->sys->hwnd, WM_CLOSE, 0, 0);
429 }
430
431 void sys_watch(win_t *win, event_t ev, mod_t mod)
432 {
433         (void)ev2w; // TODO
434         //printf("sys_watch: %p\n", win);
435 }
436
437 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
438 {
439         (void)ev2w; // TODO
440         //printf("sys_unwatch: %p\n", win);
441 }
442
443 list_t *sys_info(win_t *win)
444 {
445         if (screens == NULL)
446                 EnumDisplayMonitors(NULL, NULL, MonProc, (LPARAM)&screens);
447         return screens;
448 }
449
450 win_t *sys_init(void)
451 {
452         HINSTANCE hInst = GetModuleHandle(NULL);
453         HWND      hwnd  = NULL;
454
455         /* Load configuration */
456         no_capture = conf_get_int("main.no-capture", no_capture);
457         stack      = conf_get_int("main.stack",      stack);
458
459         /* Setup window class */
460         WNDCLASSEX wc    = {
461                 .cbSize        = sizeof(WNDCLASSEX),
462                 .lpfnWndProc   = WndProc,
463                 .hInstance     = hInst,
464                 .lpszClassName = "wmpus_class",
465         };
466         if (!RegisterClassEx(&wc))
467                 printf("sys_init: Error Registering Class - %lu\n", GetLastError());
468
469         /* Get work area */
470         RECT rc;
471         SystemParametersInfo(SPI_GETWORKAREA, 0, &rc, 0);
472
473         /* Create shell hook window */
474         if (!(hwnd = CreateWindowEx(0, "wmpus_class", "wmpus", 0,
475                         rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top,
476                         HWND_MESSAGE, NULL, hInst, NULL)))
477                 printf("sys_init: Error Creating Shell Hook Window - %lu\n", GetLastError());
478
479         /* Register shell hook */
480         BOOL (*RegisterShellHookWindow)(HWND) = (void*)GetProcAddress(
481                         GetModuleHandle("USER32.DLL"), "RegisterShellHookWindow");
482         if (!RegisterShellHookWindow)
483                 printf("sys_init: Error Finding RegisterShellHookWindow - %lu\n", GetLastError());
484         if (!RegisterShellHookWindow(hwnd))
485                 printf("sys_init: Error Registering ShellHook Window - %lu\n", GetLastError());
486         shellhookid = RegisterWindowMessage("SHELLHOOK");
487
488         /* Input hooks */
489         SetWindowsHookEx(WH_KEYBOARD_LL, KbdProc, hInst, 0);
490         SetWindowsHookEx(WH_MOUSE_LL,    MllProc, hInst, 0);
491         //SetWindowsHookEx(WH_SHELL,       ShlProc, hInst, 0);
492
493         /* Alternate ways to get input */
494         //if (!RegisterHotKey(hwnd, 123, MOD_CONTROL, VK_LBUTTON))
495         //      printf("sys_init: Error Registering Hotkey - %lu\n", GetLastError());
496         //if (!RegisterHotKey(NULL, 123, MOD_CONTROL, VK_LBUTTON))
497         //      printf("sys_init: Error Registering Hotkey - %lu\n", GetLastError());
498
499         /* Capture ctrl-c and console widnow close */
500         SetConsoleCtrlHandler(CtrlProc, TRUE);
501
502         return root = win_new(hwnd,0);
503 }
504
505 void sys_run(win_t *root)
506 {
507         MSG msg = {};
508         if (!no_capture)
509                 EnumWindows(LoopProc, 0);
510         while (GetMessage(&msg, NULL, 0, 0) > 0 &&
511                msg.message != WM_QUIT) {
512                 TranslateMessage(&msg);
513                 DispatchMessage(&msg);
514         }
515 }
516
517 void sys_exit(void)
518 {
519         PostMessage(root->sys->hwnd, WM_QUIT, 0, 0);
520 }
521
522 void sys_free(win_t *root)
523 {
524         /* I don't really care about this
525          * since I don't know how to use
526          * valgrind on win32 anyway.. */
527 }