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