aboutsummaryrefslogtreecommitdiff
path: root/src/window_manager.c
blob: ec26842629b7ddc9c5243bf450f2744f2fdb8bf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
#include "../include/window_manager.h"

#include <X11/keysym.h>
#include <X11/XF86keysym.h>
#include <X11/cursorfont.h>
/*
#include <X11/Xproto.h>
#include <X11/Xatom.h>
*/

/* TODO: Check xrandr version */
#include <X11/extensions/Xrandr.h>
#include <X11/extensions/XI2.h>
#include <X11/extensions/XInput2.h>

#include <unistd.h>
#include <sys/wait.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <signal.h>

#define MAX(a, b) ((a) > (b) ? (a) : (b))
#ifndef NULL
#define NULL ((void*)0)
#endif

static char *const menu_args[] = { "rofi", "-modi", "window,drun,combi", "-show", "combi", "-combi-modi", "window,drun", "-show-icons", NULL };

/* TODO: Pipe stdout and stderr to /dev/null. Right now the output is seen in the window manager log */
static void spawn(Display *dpy, char *const args[]) {
    pid_t pid = fork();
    if(pid == 0) { /* child */
        if (dpy)
			close(ConnectionNumber(dpy));
        setsid();
        signal(SIGHUP, SIG_IGN);

        // Daemonize child to make the parent the init process which will reap the zombie child
        pid_t second_child = fork();
        if(second_child == 0) { // child
            execvp(args[0], (char* const*)args);
            perror("execvp");
            _exit(127);
        } else if(second_child != -1) {
            _exit(0);
        }
    } else if(pid != -1) { /* parent */
        waitpid(pid, NULL, 0);
    }
}

/* Returns the id of the window or -1 */
static int window_manager_get_window_index(WindowManager *self, Window window) {
    for(int i = 0; i < WINDOW_MANAGER_MAX_WINDOWS; ++i) {
        if(self->window_data[i].window == window)
            return i;
    }
    return -1;
}

/* Returns the id to the added window, or -1 */
static int window_manager_add_window(WindowManager *self, Window window) {
    if(window_manager_get_window_index(self, window) != -1)
        return 0;

    for(int i = 0; i < WINDOW_MANAGER_MAX_WINDOWS; ++i) {
        if(self->window_data[i].window == None) {
            self->window_data[i].window = window;
            self->window_data[i].visible = 0;
            return i;
        }
    }

    fprintf(stderr, "Window manager error: failed to add window: %ld. The window manager is already handling the max number of windows (%d)", window, WINDOW_MANAGER_MAX_WINDOWS);
    return -1;
}

static int window_manager_remove_window(WindowManager *self, Window window) {
    int window_index = window_manager_get_window_index(self, window);
    if(window_index != -1) {
        self->window_data[window_index].window = None;
        self->window_data[window_index].visible = 0;
        return 1;
    }
    return 0;
}

static int window_manager_show_window(WindowManager *self, Window window, Display *display) {
    int window_index = window_manager_get_window_index(self, window);
    if(window_index != -1) {
        self->window_data[window_index].visible = 1;
        /* TODO: Also set NET_ACTIVE_WINDOW */
        XMoveResizeWindow(display, window, 0, 0, self->window_width, self->window_height);
        XRaiseWindow(display, window);
        XSetInputFocus(display, window, RevertToPointerRoot, CurrentTime);
        return 1;
    }
    return 0;
}

static int window_manager_hide_window(WindowManager *self, Window window, Display *display) {
    int window_index = window_manager_get_window_index(self, window);
    if(window_index != -1) {
        self->window_data[window_index].visible = 0;
        XMoveResizeWindow(display, window, -self->window_width - 100, 0, self->window_width, self->window_height);
        XLowerWindow(display, window);
        XSetInputFocus(display, DefaultRootWindow(display), RevertToPointerRoot, CurrentTime);
        return 1;
    }
    return 0;
}

static int window_manager_update_visiblity(WindowManager *self, Window window, Display *display) {
    int window_index = window_manager_get_window_index(self, window);
    if(window_index != -1) {
        if(self->window_data[window_index].visible) {
            XMoveResizeWindow(display, window, 0, 0, self->window_width, self->window_height);
            XRaiseWindow(display, window);
        } else {
            XMoveResizeWindow(display, window, -self->window_width - 100, 0, self->window_width, self->window_height);
            XLowerWindow(display, window);
        }
        return 1;
    }
    return 0;
}

static int xerrordummy(Display *dpy, XErrorEvent *ee) {
	return 0;
}

static void window_manager_on_cursor_move(WindowManager *window_manager, Display *dpy, Window root, int root_x, int root_y, XIRawEvent *raw_ev) {
    int diff_x = root_x - window_manager->cursor_prev_x;
    int diff_y = root_y - window_manager->cursor_prev_y;
    double diff_x_raw = diff_x;
    if(raw_ev)
        diff_x_raw = raw_ev->raw_values[0];

    /* TODO: Detect fast cursor movement and move it that distance from the edge?. It it needed? */
    int new_cursor_x = root_x;
    CursorWrapSide cursor_wrap_side = CURSOR_WRAP_NONE;
    if(new_cursor_x <= 0 && diff_x_raw < 0.0) {
        new_cursor_x = window_manager->window_width;
        cursor_wrap_side = CURSOR_WRAP_LEFT;
    } else if(new_cursor_x >= window_manager->window_width - 1 && diff_x_raw > 0.0) {
        new_cursor_x = 0;
        cursor_wrap_side = CURSOR_WRAP_RIGHT;
    }

    window_manager->cursor_prev_x = new_cursor_x;
    window_manager->cursor_prev_y = root_y;

    if(cursor_wrap_side != CURSOR_WRAP_NONE) {
        XWarpPointer(dpy, root, root, 0, 0, window_manager->window_width, window_manager->window_height, new_cursor_x, root_y);
        XSync(dpy, False);
    }

    Window new_focused_window = window_manager->callback.move_cursor_callback(dpy, diff_x, diff_y, cursor_wrap_side, window_manager->userdata);
    if(new_focused_window != window_manager->focused_window) {
        window_manager_hide_window(window_manager, window_manager->focused_window, dpy);
        window_manager_show_window(window_manager, new_focused_window, dpy);
        window_manager->focused_window = new_focused_window;
    }
}

/* TODO: XRRSetCrtcTransform, XRRSetCrtcConfig (see ~/xrandr-test.c) */

static void* thread_main(void *userdata) {
    WindowManager *window_manager = userdata;

    Display * dpy;
    Window root;
    XEvent ev;
    Window focused_window = None;

    if(!(dpy = XOpenDisplay(NULL))) {
        fprintf(stderr, "Failed to open x11 display!");
        abort();
        return NULL;
    }

    int xiOpcode, queryEvent, queryError;
    if (!XQueryExtension(dpy, "XInputExtension", &xiOpcode,
                &queryEvent, &queryError)) {
        fprintf(stderr, "X Input extension not available\n");
        abort();
        return NULL;
    }

    /* Check XInput 2.0 */
    int major = 2;
    int minor = 0;
    int retval = XIQueryVersion(dpy, &major, &minor);
    if (retval != Success) {
        fprintf(stderr, "Error: XInput 2.0 is not supported (ancient X11?)\n");
        abort();
        return NULL;
    }

    root = DefaultRootWindow(dpy);

#if 0
    XSelectInput(dpy, root, SubstructureRedirectMask | SubstructureNotifyMask /*| ResizeRedirectMask*/);
    XSync(dpy, False);
#endif

    KeyCode q_key = XKeysymToKeycode(dpy, XStringToKeysym("q"));
    KeyCode f1_key = XKeysymToKeycode(dpy, XStringToKeysym("F1"));
    KeyCode f12_key = XKeysymToKeycode(dpy, XStringToKeysym("F12"));

    XGrabKey(dpy, q_key, Mod1Mask, root, True, GrabModeAsync, GrabModeAsync);
    XGrabKey(dpy, f1_key, Mod1Mask, root, True, GrabModeAsync, GrabModeAsync);
    XGrabKey(dpy, f12_key, Mod1Mask, root, True, GrabModeAsync, GrabModeAsync);
    XGrabButton(dpy, Button1, Mod1Mask, root, True, ButtonPressMask|ButtonReleaseMask,
        GrabModeAsync,
        GrabModeAsync, None, None);

    window_manager->cursor_prev_x = 0;
    window_manager->cursor_prev_y = 0;
    Window dummy_w;
    int dummy_int;
    unsigned int dummy_m;
    XWarpPointer(dpy, root, root, 0, 0, window_manager->window_width, window_manager->window_height, 0, 0);
    XSync(dpy, False);
    /*XQueryPointer(dpy, root, &dummy_w, &dummy_w, &cursor_prev_x, &cursor_prev_y, &dummy_int, &dummy_int, &dummy_m);*/


    XIEventMask xi_masks;
    unsigned char mask[(XI_LASTEVENT + 7)/8];
    memset(mask, 0, sizeof(mask));
    /* TODO: Use XI_Motion instead. It doesn't seem to work now for some reason. Or use XI_RawMotion without XQueryPointer and detect absolute position from relative position sum */
    XISetMask(mask, XI_RawMotion);

    xi_masks.deviceid = XIAllMasterDevices;
    xi_masks.mask_len = sizeof(mask);
    xi_masks.mask = mask;

    XISelectEvents(dpy, root, &xi_masks, 1);

    int x11_fd = ConnectionNumber(dpy);
    fd_set in_fds;
    struct timeval tv;

    int pointer_grabbed = 0;

    window_manager->cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
    window_manager->cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
    window_manager->cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);

    XSetWindowAttributes wa;
    wa.cursor = window_manager->cursor[CurNormal];
    wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
		|ButtonPressMask|PointerMotionMask|EnterWindowMask
		|LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
    XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
    XSelectInput(dpy, root, wa.event_mask);

    while(window_manager->running) {
        FD_ZERO(&in_fds);
        FD_SET(x11_fd, &in_fds);

        /* Wake up thread every 500ms ms if no events are received */
        tv.tv_usec = 1000 * 500;
        tv.tv_sec = 0;

        int num_ready_fds = select(x11_fd + 1, &in_fds, NULL, NULL, &tv);
        if (num_ready_fds > 0) {
            /* Event received! */
        } else if (num_ready_fds == 0) {
            continue;
        } else {
            fprintf(stderr, "Window manager error: select failed on display file descriptor!\n");
            continue;
        }

        while(window_manager->running && XPending(dpy)) {
            XNextEvent(dpy, &ev);
            XGenericEventCookie *cookie = (XGenericEventCookie*)&ev.xcookie;

            Bool got_event_data = XGetEventData(dpy, cookie);
            if(got_event_data && cookie->type == GenericEvent && cookie->extension == xiOpcode && cookie->evtype == XI_RawMotion) {
                /* TODO: while(XCheckTypedWindowEvent(dpy, ev.xmotion.window, MotionNotify, &ev)); ? */
                XIRawEvent *raw_ev = cookie->data;
                //printf("move cursor, %f, %f\n", raw_ev->raw_values[0], raw_ev->raw_values[1]);

                Window root_return, child_return;
                int root_x_return, root_y_return;
                int win_x_return, win_y_return;
                unsigned int mask_return;
                int retval = XQueryPointer(dpy, root, &root_return, &child_return,
                                        &root_x_return, &root_y_return,
                                        &win_x_return, &win_y_return,
                                        &mask_return);
                if(retval) {
                    window_manager_on_cursor_move(window_manager, dpy, root, root_x_return, root_y_return, raw_ev);
                }
            }
            if(got_event_data)
                XFreeEventData(dpy, cookie);

            if(ev.type == MotionNotify) {
                while(XCheckTypedWindowEvent(dpy, ev.xmotion.window, MotionNotify, &ev));
                window_manager_on_cursor_move(window_manager, dpy, root, ev.xmotion.x_root, ev.xmotion.y_root, NULL);
            }

            if(ev.type == ButtonPress || ev.type == ButtonRelease) {
                if(ev.xbutton.state & Mod1Mask) {
                    if(ev.type == ButtonPress)
                        pointer_grabbed = XGrabPointer(dpy, root, False, ButtonPressMask|ButtonReleaseMask|PointerMotionMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
                }
                if(ev.type == ButtonRelease) {
                    XUngrabPointer(dpy, CurrentTime);
                    pointer_grabbed = 0;
                }
                window_manager->callback.button_callback(dpy, ev.xbutton.type, ev.xbutton.state, ev.xbutton.button, window_manager->userdata);
            }

            if(ev.type == KeyPress) {
                if(ev.xkey.keycode == f1_key) {
                    window_manager->callback.reset_camera_callback(window_manager->userdata);
                } else if(ev.xkey.keycode == f12_key) {
                    spawn(dpy, menu_args);
                } else if(ev.xkey.keycode == q_key && ev.xkey.subwindow) {
                    /* TODO: Check if this is needed. Wont DestroyNotify be called anyways where this is also done? */
                    /*
                    if(window_manager_remove_window(window_manager, ev.xkey.subwindow)) {
                        Window new_focused_window = window_manager->callback.remove_window_callback(ev.xkey.subwindow, window_manager->userdata);
                        if(new_focused_window != focused_window) {
                            window_manager_hide_window(window_manager, focused_window, dpy);
                            window_manager_show_window(window_manager, new_focused_window, dpy);
                            focused_window = new_focused_window;
                        }
                    }
                    */

                    XGrabServer(dpy);
                    XErrorHandler prev_err_handler = XSetErrorHandler(xerrordummy);
                    XSetCloseDownMode(dpy, DestroyAll);
                    XKillClient(dpy, ev.xkey.subwindow);
                    XSync(dpy, False);
                    XSetErrorHandler(prev_err_handler);
                    XUngrabServer(dpy);

                    Window new_focused_window = window_manager->callback.move_cursor_callback(dpy, 0, 0, CURSOR_WRAP_NONE, window_manager->userdata);
                    if(new_focused_window != focused_window) {
                        window_manager_hide_window(window_manager, focused_window, dpy);
                        window_manager_show_window(window_manager, new_focused_window, dpy);
                        focused_window = new_focused_window;
                    }
                } else {
                    /*window_manager->callback.key_callback(dpy, ev.xkey.type, ev.xkey.state, ev.xkey.keycode, window_manager->userdata);*/
                }
            /*} else if(ev.type == ButtonPress && ev.xbutton.subwindow != None) {
                XGrabPointer(dpy, ev.xbutton.subwindow, True,
                        PointerMotionMask|ButtonReleaseMask, GrabModeAsync,
                        GrabModeAsync, None, None, CurrentTime);
                XGetWindowAttributes(dpy, ev.xbutton.subwindow, &attr);
                start = ev.xbutton;
            } else if(ev.type == MotionNotify) {
                int xdiff, ydiff;
                while(XCheckTypedEvent(dpy, MotionNotify, &ev));
                xdiff = ev.xbutton.x_root - start.x_root;
                ydiff = ev.xbutton.y_root - start.y_root;
                XMoveResizeWindow(dpy, ev.xmotion.window,
                    attr.x + (start.button==1 ? xdiff : 0),
                    attr.y + (start.button==1 ? ydiff : 0),
                    MAX(1, attr.width + (start.button==3 ? xdiff : 0)),
                    MAX(1, attr.height + (start.button==3 ? ydiff : 0)));
            } else if(ev.type == ButtonRelease) {
                XUngrabPointer(dpy, CurrentTime);
                */
            } else if(ev.type == KeyRelease) {
                /*window_manager->callback.key_callback(dpy, ev.xkey.type, ev.xkey.state, ev.xkey.keycode, window_manager->userdata);*/
            } else if(ev.type == MapRequest) {
                fprintf(stderr, "map request 1\n");
                fflush(stderr);
                Window window = ev.xmaprequest.window;
                XWindowAttributes wa;
                if (!XGetWindowAttributes(dpy, window, &wa))
                    continue;
                if (wa.override_redirect)
                    continue;

                int window_index = window_manager_add_window(window_manager, window);
                if(window_index != -1) {
                    if(!focused_window) {
                        focused_window = window;
                        window_manager->window_data[window_index].visible = 1;
                        XMoveResizeWindow(dpy, window, 0, 0, window_manager->window_width, window_manager->window_height);
                        XRaiseWindow(dpy, window);
                    } else {
                        XMoveResizeWindow(dpy, window, -window_manager->window_width - 100, 0, window_manager->window_width, window_manager->window_height);
                        XLowerWindow(dpy, window);
                    }
                    XMapWindow(dpy, window);
                    fprintf(stderr, "added window\n");
                    fflush(stderr);
                    window_manager->callback.add_window_callback(window, window_manager->userdata);
                }
                /* TODO: Do we need to map if window_index == -1 ? */
            } else if(ev.type == DestroyNotify) {
                Window window = ev.xdestroywindow.window;
                if(window_manager_remove_window(window_manager, window)) {
                    Window new_focused_window = window_manager->callback.remove_window_callback(window, window_manager->userdata);
                    if(new_focused_window != focused_window) {
                        window_manager_hide_window(window_manager, focused_window, dpy);
                        window_manager_show_window(window_manager, new_focused_window, dpy);
                        focused_window = new_focused_window;
                    }
                }
            } else if(ev.type == ConfigureNotify) {
                Window window = ev.xconfigure.window;
                while(XCheckTypedWindowEvent(dpy, window, ConfigureNotify, &ev));
                window_manager_update_visiblity(window_manager, window, dpy);
            }
            /* TODO: Override unmap to not allow programs to hide windows (if the window is a child of the root window! sub windows such as popup windows should be allowed to hide, or maybe check window type?) */
        }
    }

    XCloseDisplay(dpy);
    return NULL;
}

int window_manager_init(WindowManager *self, int window_width, int window_height, WindowManagerCallback *callback, void *userdata) {
    assert(callback);
    assert(callback->add_window_callback);
    assert(callback->remove_window_callback);
    assert(callback->reset_camera_callback);
    assert(callback->move_cursor_callback);
    assert(callback->button_callback);

    /* TODO: Temporary! Replace with xrandr calls */
    #if 0
    char command[2048];
    snprintf(command, sizeof(command), "xrandr --output DP-0 --mode 1920x1080 --pos 0x0 --panning %dx%d+0+0 --rate 144 --scale-from %dx%d", window_width, window_height, window_width, window_height);
    system(command);

    snprintf(command, sizeof(command), "xrandr --output DP-4 --mode 3840x2160 --pos 0x0 --panning %dx%d+0+0 --rate 60 --scale-from %dx%d", window_width, window_height, window_width, window_height);
    system(command);
    #endif

    memset(self->window_data, 0, sizeof(self->window_data));
    self->callback = *callback;
    self->window_width = window_width;
    self->window_height = window_height;
    self->userdata = userdata;
    self->running = 1;
    fprintf(stderr, "window manager initialized, window width: %d, window height: %d\n", window_width, window_height);
    return pthread_create(&self->thread, NULL, thread_main, self);
}

void window_manager_deinit(WindowManager *self) {
    self->running = 0;
    /* May take up to 100ms (thread wakeup timeout) */
    pthread_join(self->thread, NULL);
}