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