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