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