nixos-dotfiles

nixos-dotfiles

https://git.tonybtw.com/nixos-dotfiles.git git://git.tonybtw.com/nixos-dotfiles.git
117,708 bytes raw
1
#include <getopt.h>
2
#include <libinput.h>
3
#include <linux/input-event-codes.h>
4
#include <math.h>
5
#include <libdrm/drm_fourcc.h>
6
#include <signal.h>
7
#include <stdio.h>
8
#include <stdlib.h>
9
#include <sys/wait.h>
10
#include <time.h>
11
#include <unistd.h>
12
#include <wayland-server-core.h>
13
#include <wlr/backend.h>
14
#include <wlr/backend/libinput.h>
15
#include <wlr/render/allocator.h>
16
#include <wlr/render/wlr_renderer.h>
17
#include <wlr/types/wlr_alpha_modifier_v1.h>
18
#include <wlr/types/wlr_compositor.h>
19
#include <wlr/types/wlr_cursor.h>
20
#include <wlr/types/wlr_cursor_shape_v1.h>
21
#include <wlr/types/wlr_data_control_v1.h>
22
#include <wlr/types/wlr_data_device.h>
23
#include <wlr/types/wlr_drm.h>
24
#include <wlr/types/wlr_export_dmabuf_v1.h>
25
#include <wlr/types/wlr_fractional_scale_v1.h>
26
#include <wlr/types/wlr_gamma_control_v1.h>
27
#include <wlr/types/wlr_idle_inhibit_v1.h>
28
#include <wlr/types/wlr_idle_notify_v1.h>
29
#include <wlr/types/wlr_input_device.h>
30
#include <wlr/types/wlr_keyboard.h>
31
#include <wlr/types/wlr_keyboard_group.h>
32
#include <wlr/types/wlr_layer_shell_v1.h>
33
#include <wlr/types/wlr_linux_dmabuf_v1.h>
34
#include <wlr/types/wlr_linux_drm_syncobj_v1.h>
35
#include <wlr/types/wlr_output.h>
36
#include <wlr/types/wlr_output_layout.h>
37
#include <wlr/types/wlr_output_management_v1.h>
38
#include <wlr/types/wlr_output_power_management_v1.h>
39
#include <wlr/types/wlr_pointer.h>
40
#include <wlr/types/wlr_pointer_constraints_v1.h>
41
#include <wlr/types/wlr_presentation_time.h>
42
#include <wlr/types/wlr_primary_selection.h>
43
#include <wlr/types/wlr_primary_selection_v1.h>
44
#include <wlr/types/wlr_relative_pointer_v1.h>
45
#include <wlr/types/wlr_scene.h>
46
#include <wlr/types/wlr_screencopy_v1.h>
47
#include <wlr/types/wlr_seat.h>
48
#include <wlr/types/wlr_server_decoration.h>
49
#include <wlr/types/wlr_session_lock_v1.h>
50
#include <wlr/types/wlr_single_pixel_buffer_v1.h>
51
#include <wlr/types/wlr_subcompositor.h>
52
#include <wlr/types/wlr_viewporter.h>
53
#include <wlr/types/wlr_virtual_keyboard_v1.h>
54
#include <wlr/types/wlr_virtual_pointer_v1.h>
55
#include <wlr/types/wlr_xcursor_manager.h>
56
#include <wlr/types/wlr_xdg_activation_v1.h>
57
#include <wlr/types/wlr_xdg_decoration_v1.h>
58
#include <wlr/types/wlr_xdg_output_v1.h>
59
#include <wlr/types/wlr_xdg_shell.h>
60
#include <wlr/interfaces/wlr_buffer.h>
61
#include <wlr/util/log.h>
62
#include <wlr/util/region.h>
63
#include <xkbcommon/xkbcommon.h>
64
#ifdef XWAYLAND
65
#include <wlr/xwayland.h>
66
#include <xcb/xcb.h>
67
#include <xcb/xcb_icccm.h>
68
#endif
69
70
#include "util.h"
71
#include "drwl.h"
72
73
/* macros */
74
#define MAX(A, B)               ((A) > (B) ? (A) : (B))
75
#define MIN(A, B)               ((A) < (B) ? (A) : (B))
76
#define CLEANMASK(mask)         (mask & ~WLR_MODIFIER_CAPS)
77
#define VISIBLEON(C, M)         ((M) && (C)->mon == (M) && ((C)->tags & (M)->tagset[(M)->seltags]))
78
#define LENGTH(X)               (sizeof X / sizeof X[0])
79
#define END(A)                  ((A) + LENGTH(A))
80
#define TAGMASK                 ((1u << LENGTH(tags)) - 1)
81
#define LISTEN(E, L, H)         wl_signal_add((E), ((L)->notify = (H), (L)))
82
#define LISTEN_STATIC(E, H)     do { struct wl_listener *_l = ecalloc(1, sizeof(*_l)); _l->notify = (H); wl_signal_add((E), _l); } while (0)
83
#define TEXTW(mon, text)        (drwl_font_getwidth(mon->drw, text) + mon->lrpad)
84
85
/* enums */
86
enum { SchemeNorm, SchemeSel, SchemeOcc, SchemeUrg, SchemeUnder, SchemeLast, SchemeBg };
87
// enum { SchemeNorm, SchemeSel, SchemeUrg }; /* color schemes */
88
enum { CurNormal, CurPressed, CurMove, CurResize }; /* cursor */
89
enum { XDGShell, LayerShell, X11 }; /* client types */
90
enum { LyrBg, LyrBottom, LyrTile, LyrFloat, LyrTop, LyrFS, LyrOverlay, LyrBlock, NUM_LAYERS }; /* scene layers */
91
enum { ClkTagBar, ClkLtSymbol, ClkStatus, ClkTitle, ClkClient, ClkRoot }; /* clicks */
92
93
typedef union {
94
	int i;
95
	uint32_t ui;
96
	float f;
97
	const void *v;
98
} Arg;
99
100
typedef struct {
101
	unsigned int click;
102
	unsigned int mod;
103
	unsigned int button;
104
	void (*func)(const Arg *);
105
	const Arg arg;
106
} Button;
107
108
typedef struct Monitor Monitor;
109
typedef struct {
110
	/* Must keep this field first */
111
	unsigned int type; /* XDGShell or X11* */
112
113
	Monitor *mon;
114
	struct wlr_scene_tree *scene;
115
	struct wlr_scene_rect *border[4]; /* top, bottom, left, right */
116
	struct wlr_scene_tree *scene_surface;
117
	struct wl_list link;
118
	struct wl_list flink;
119
	struct wlr_box geom; /* layout-relative, includes border */
120
	struct wlr_box prev; /* layout-relative, includes border */
121
	struct wlr_box bounds; /* only width and height are used */
122
	union {
123
		struct wlr_xdg_surface *xdg;
124
		struct wlr_xwayland_surface *xwayland;
125
	} surface;
126
	struct wlr_xdg_toplevel_decoration_v1 *decoration;
127
	struct wl_listener commit;
128
	struct wl_listener map;
129
	struct wl_listener maximize;
130
	struct wl_listener unmap;
131
	struct wl_listener destroy;
132
	struct wl_listener set_title;
133
	struct wl_listener fullscreen;
134
	struct wl_listener set_decoration_mode;
135
	struct wl_listener destroy_decoration;
136
#ifdef XWAYLAND
137
	struct wl_listener activate;
138
	struct wl_listener associate;
139
	struct wl_listener dissociate;
140
	struct wl_listener configure;
141
	struct wl_listener set_hints;
142
#endif
143
	unsigned int bw;
144
	uint32_t tags;
145
	int isfloating, isurgent, isfullscreen;
146
	uint32_t resize; /* configure serial of a pending resize */
147
} Client;
148
149
typedef struct {
150
	uint32_t mod;
151
	xkb_keysym_t keysym;
152
	void (*func)(const Arg *);
153
	const Arg arg;
154
} Key;
155
156
typedef struct {
157
	struct wlr_keyboard_group *wlr_group;
158
159
	int nsyms;
160
	const xkb_keysym_t *keysyms; /* invalid if nsyms == 0 */
161
	uint32_t mods; /* invalid if nsyms == 0 */
162
	struct wl_event_source *key_repeat_source;
163
164
	struct wl_listener modifiers;
165
	struct wl_listener key;
166
	struct wl_listener destroy;
167
} KeyboardGroup;
168
169
typedef struct {
170
	/* Must keep this field first */
171
	unsigned int type; /* LayerShell */
172
173
	Monitor *mon;
174
	struct wlr_scene_tree *scene;
175
	struct wlr_scene_tree *popups;
176
	struct wlr_scene_layer_surface_v1 *scene_layer;
177
	struct wl_list link;
178
	int mapped;
179
	struct wlr_layer_surface_v1 *layer_surface;
180
181
	struct wl_listener destroy;
182
	struct wl_listener unmap;
183
	struct wl_listener surface_commit;
184
} LayerSurface;
185
186
typedef struct {
187
	const char *symbol;
188
	void (*arrange)(Monitor *);
189
} Layout;
190
191
typedef struct {
192
	struct wlr_buffer base;
193
	struct wl_listener release;
194
	bool busy;
195
	Img *image;
196
	uint32_t data[];
197
} Buffer;
198
199
struct Monitor {
200
	struct wl_list link;
201
	struct wlr_output *wlr_output;
202
	struct wlr_scene_output *scene_output;
203
	struct wlr_scene_buffer *scene_buffer; /* bar buffer */
204
	struct wlr_scene_rect *fullscreen_bg; /* See createmon() for info */
205
	struct wl_listener frame;
206
	struct wl_listener destroy;
207
	struct wl_listener request_state;
208
	struct wl_listener destroy_lock_surface;
209
	struct wlr_session_lock_surface_v1 *lock_surface;
210
	struct wlr_box m; /* monitor area, layout-relative */
211
	struct {
212
		int width, height;
213
		int real_width, real_height; /* non-scaled */
214
		float scale;
215
	} b; /* bar area */
216
	struct wlr_box w; /* window area, layout-relative */
217
	struct wl_list layers[4]; /* LayerSurface.link */
218
	const Layout *lt[2];
219
	int gaps;
220
	unsigned int seltags;
221
	unsigned int sellt;
222
	uint32_t tagset[2];
223
	float mfact;
224
	int gamma_lut_changed;
225
	int nmaster;
226
	char ltsymbol[16];
227
	int asleep;
228
	Drwl *drw;
229
	Buffer *pool[2];
230
	int lrpad;
231
};
232
233
typedef struct {
234
	const char *name;
235
	float mfact;
236
	int nmaster;
237
	float scale;
238
	const Layout *lt;
239
	enum wl_output_transform rr;
240
	int x, y;
241
} MonitorRule;
242
243
typedef struct {
244
	struct wlr_pointer_constraint_v1 *constraint;
245
	struct wl_listener destroy;
246
} PointerConstraint;
247
248
typedef struct {
249
	const char *id;
250
	const char *title;
251
	uint32_t tags;
252
	int isfloating;
253
	int monitor;
254
} Rule;
255
256
typedef struct {
257
	struct wlr_scene_tree *scene;
258
259
	struct wlr_session_lock_v1 *lock;
260
	struct wl_listener new_surface;
261
	struct wl_listener unlock;
262
	struct wl_listener destroy;
263
} SessionLock;
264
265
/* function declarations */
266
static void applybounds(Client *c, struct wlr_box *bbox);
267
static void applyrules(Client *c);
268
static void arrange(Monitor *m);
269
static void arrangelayer(Monitor *m, struct wl_list *list,
270
		struct wlr_box *usable_area, int exclusive);
271
static void arrangelayers(Monitor *m);
272
static void axisnotify(struct wl_listener *listener, void *data);
273
static bool baracceptsinput(struct wlr_scene_buffer *buffer, double *sx, double *sy);
274
static void bufdestroy(struct wlr_buffer *buffer);
275
static bool bufdatabegin(struct wlr_buffer *buffer, uint32_t flags,
276
		void **data, uint32_t *format, size_t *stride);
277
static void bufdataend(struct wlr_buffer *buffer);
278
static Buffer *bufmon(Monitor *m);
279
static void bufrelease(struct wl_listener *listener, void *data);
280
static void buttonpress(struct wl_listener *listener, void *data);
281
static void chvt(const Arg *arg);
282
static void checkidleinhibitor(struct wlr_surface *exclude);
283
static void cleanup(void);
284
static void cleanupmon(struct wl_listener *listener, void *data);
285
static void cleanuplisteners(void);
286
static void closemon(Monitor *m);
287
static void commitlayersurfacenotify(struct wl_listener *listener, void *data);
288
static void commitnotify(struct wl_listener *listener, void *data);
289
static void commitpopup(struct wl_listener *listener, void *data);
290
static void createdecoration(struct wl_listener *listener, void *data);
291
static void createidleinhibitor(struct wl_listener *listener, void *data);
292
static void createkeyboard(struct wlr_keyboard *keyboard);
293
static KeyboardGroup *createkeyboardgroup(void);
294
static void createlayersurface(struct wl_listener *listener, void *data);
295
static void createlocksurface(struct wl_listener *listener, void *data);
296
static void createmon(struct wl_listener *listener, void *data);
297
static void createnotify(struct wl_listener *listener, void *data);
298
static void createpointer(struct wlr_pointer *pointer);
299
static void createpointerconstraint(struct wl_listener *listener, void *data);
300
static void createpopup(struct wl_listener *listener, void *data);
301
static void cursorconstrain(struct wlr_pointer_constraint_v1 *constraint);
302
static void cursorframe(struct wl_listener *listener, void *data);
303
static void cursorwarptohint(void);
304
static void destroydecoration(struct wl_listener *listener, void *data);
305
static void destroydragicon(struct wl_listener *listener, void *data);
306
static void destroyidleinhibitor(struct wl_listener *listener, void *data);
307
static void destroylayersurfacenotify(struct wl_listener *listener, void *data);
308
static void destroylock(SessionLock *lock, int unlocked);
309
static void destroylocksurface(struct wl_listener *listener, void *data);
310
static void destroynotify(struct wl_listener *listener, void *data);
311
static void destroypointerconstraint(struct wl_listener *listener, void *data);
312
static void destroysessionlock(struct wl_listener *listener, void *data);
313
static void destroykeyboardgroup(struct wl_listener *listener, void *data);
314
static Monitor *dirtomon(enum wlr_direction dir);
315
static void drawbar(Monitor *m);
316
static void drawbars(void);
317
static void focusclient(Client *c, int lift);
318
static void focusmon(const Arg *arg);
319
static void focusstack(const Arg *arg);
320
static Client *focustop(Monitor *m);
321
static void fullscreennotify(struct wl_listener *listener, void *data);
322
static void gpureset(struct wl_listener *listener, void *data);
323
static void handlesig(int signo);
324
static void incnmaster(const Arg *arg);
325
static void inputdevice(struct wl_listener *listener, void *data);
326
static int keybinding(uint32_t mods, xkb_keysym_t sym);
327
static void keypress(struct wl_listener *listener, void *data);
328
static void keypressmod(struct wl_listener *listener, void *data);
329
static int keyrepeat(void *data);
330
static void killclient(const Arg *arg);
331
static void locksession(struct wl_listener *listener, void *data);
332
static void mapnotify(struct wl_listener *listener, void *data);
333
static void maximizenotify(struct wl_listener *listener, void *data);
334
static void monocle(Monitor *m);
335
static void motionabsolute(struct wl_listener *listener, void *data);
336
static void motionnotify(uint32_t time, struct wlr_input_device *device, double sx,
337
		double sy, double sx_unaccel, double sy_unaccel);
338
static void motionrelative(struct wl_listener *listener, void *data);
339
static void moveresize(const Arg *arg);
340
static void outputmgrapply(struct wl_listener *listener, void *data);
341
static void outputmgrapplyortest(struct wlr_output_configuration_v1 *config, int test);
342
static void outputmgrtest(struct wl_listener *listener, void *data);
343
static void pointerfocus(Client *c, struct wlr_surface *surface,
344
		double sx, double sy, uint32_t time);
345
static void powermgrsetmode(struct wl_listener *listener, void *data);
346
static void quit(const Arg *arg);
347
static void rendermon(struct wl_listener *listener, void *data);
348
static void requestdecorationmode(struct wl_listener *listener, void *data);
349
static void requeststartdrag(struct wl_listener *listener, void *data);
350
static void requestmonstate(struct wl_listener *listener, void *data);
351
static void resize(Client *c, struct wlr_box geo, int interact);
352
static void run(char *startup_cmd);
353
static void setcursor(struct wl_listener *listener, void *data);
354
static void setcursorshape(struct wl_listener *listener, void *data);
355
static void setfloating(Client *c, int floating);
356
static void setfullscreen(Client *c, int fullscreen);
357
static void setlayout(const Arg *arg);
358
static void setmfact(const Arg *arg);
359
static void setmon(Client *c, Monitor *m, uint32_t newtags);
360
static void setpsel(struct wl_listener *listener, void *data);
361
static void setsel(struct wl_listener *listener, void *data);
362
static void setup(void);
363
static void spawn(const Arg *arg);
364
static void startdrag(struct wl_listener *listener, void *data);
365
static int statusin(int fd, unsigned int mask, void *data);
366
static void tag(const Arg *arg);
367
static void tagmon(const Arg *arg);
368
static void tile(Monitor *m);
369
static void togglebar(const Arg *arg);
370
static void togglefloating(const Arg *arg);
371
static void togglefullscreen(const Arg *arg);
372
static void togglegaps(const Arg *arg);
373
static void toggletag(const Arg *arg);
374
static void toggleview(const Arg *arg);
375
static void unlocksession(struct wl_listener *listener, void *data);
376
static void unmaplayersurfacenotify(struct wl_listener *listener, void *data);
377
static void unmapnotify(struct wl_listener *listener, void *data);
378
static void updatemons(struct wl_listener *listener, void *data);
379
static void updatebar(Monitor *m);
380
static void updatetitle(struct wl_listener *listener, void *data);
381
static void urgent(struct wl_listener *listener, void *data);
382
static void view(const Arg *arg);
383
static void virtualkeyboard(struct wl_listener *listener, void *data);
384
static void virtualpointer(struct wl_listener *listener, void *data);
385
static Monitor *xytomon(double x, double y);
386
static void xytonode(double x, double y, struct wlr_surface **psurface,
387
		Client **pc, LayerSurface **pl, double *nx, double *ny);
388
static void zoom(const Arg *arg);
389
390
/* variables */
391
static pid_t child_pid = -1;
392
static int locked;
393
static void *exclusive_focus;
394
static struct wl_display *dpy;
395
static struct wl_event_loop *event_loop;
396
static struct wlr_backend *backend;
397
static struct wlr_scene *scene;
398
static struct wlr_scene_tree *layers[NUM_LAYERS];
399
static struct wlr_scene_tree *drag_icon;
400
/* Map from ZWLR_LAYER_SHELL_* constants to Lyr* enum */
401
static const int layermap[] = { LyrBg, LyrBottom, LyrTop, LyrOverlay };
402
static struct wlr_renderer *drw;
403
static struct wlr_allocator *alloc;
404
static struct wlr_compositor *compositor;
405
static struct wlr_session *session;
406
407
static struct wlr_xdg_shell *xdg_shell;
408
static struct wlr_xdg_activation_v1 *activation;
409
static struct wlr_xdg_decoration_manager_v1 *xdg_decoration_mgr;
410
static struct wl_list clients; /* tiling order */
411
static struct wl_list fstack;  /* focus order */
412
static struct wlr_idle_notifier_v1 *idle_notifier;
413
static struct wlr_idle_inhibit_manager_v1 *idle_inhibit_mgr;
414
static struct wlr_layer_shell_v1 *layer_shell;
415
static struct wlr_output_manager_v1 *output_mgr;
416
static struct wlr_virtual_keyboard_manager_v1 *virtual_keyboard_mgr;
417
static struct wlr_virtual_pointer_manager_v1 *virtual_pointer_mgr;
418
static struct wlr_cursor_shape_manager_v1 *cursor_shape_mgr;
419
static struct wlr_output_power_manager_v1 *power_mgr;
420
421
static struct wlr_pointer_constraints_v1 *pointer_constraints;
422
static struct wlr_relative_pointer_manager_v1 *relative_pointer_mgr;
423
static struct wlr_pointer_constraint_v1 *active_constraint;
424
425
static struct wlr_cursor *cursor;
426
static struct wlr_xcursor_manager *cursor_mgr;
427
428
static struct wlr_scene_rect *root_bg;
429
static struct wlr_session_lock_manager_v1 *session_lock_mgr;
430
static struct wlr_scene_rect *locked_bg;
431
static struct wlr_session_lock_v1 *cur_lock;
432
433
static struct wlr_seat *seat;
434
static KeyboardGroup *kb_group;
435
static unsigned int cursor_mode;
436
static Client *grabc;
437
static int grabcx, grabcy; /* client-relative */
438
439
static struct wlr_output_layout *output_layout;
440
static struct wlr_box sgeom;
441
static struct wl_list mons;
442
static Monitor *selmon;
443
444
static char stext[256];
445
static struct wl_event_source *status_event_source;
446
447
static const struct wlr_buffer_impl buffer_impl = {
448
    .destroy = bufdestroy,
449
    .begin_data_ptr_access = bufdatabegin,
450
    .end_data_ptr_access = bufdataend,
451
};
452
453
/* global event handlers */
454
static struct wl_listener cursor_axis = {.notify = axisnotify};
455
static struct wl_listener cursor_button = {.notify = buttonpress};
456
static struct wl_listener cursor_frame = {.notify = cursorframe};
457
static struct wl_listener cursor_motion = {.notify = motionrelative};
458
static struct wl_listener cursor_motion_absolute = {.notify = motionabsolute};
459
static struct wl_listener gpu_reset = {.notify = gpureset};
460
static struct wl_listener layout_change = {.notify = updatemons};
461
static struct wl_listener new_idle_inhibitor = {.notify = createidleinhibitor};
462
static struct wl_listener new_input_device = {.notify = inputdevice};
463
static struct wl_listener new_virtual_keyboard = {.notify = virtualkeyboard};
464
static struct wl_listener new_virtual_pointer = {.notify = virtualpointer};
465
static struct wl_listener new_pointer_constraint = {.notify = createpointerconstraint};
466
static struct wl_listener new_output = {.notify = createmon};
467
static struct wl_listener new_xdg_toplevel = {.notify = createnotify};
468
static struct wl_listener new_xdg_popup = {.notify = createpopup};
469
static struct wl_listener new_xdg_decoration = {.notify = createdecoration};
470
static struct wl_listener new_layer_surface = {.notify = createlayersurface};
471
static struct wl_listener output_mgr_apply = {.notify = outputmgrapply};
472
static struct wl_listener output_mgr_test = {.notify = outputmgrtest};
473
static struct wl_listener output_power_mgr_set_mode = {.notify = powermgrsetmode};
474
static struct wl_listener request_activate = {.notify = urgent};
475
static struct wl_listener request_cursor = {.notify = setcursor};
476
static struct wl_listener request_set_psel = {.notify = setpsel};
477
static struct wl_listener request_set_sel = {.notify = setsel};
478
static struct wl_listener request_set_cursor_shape = {.notify = setcursorshape};
479
static struct wl_listener request_start_drag = {.notify = requeststartdrag};
480
static struct wl_listener start_drag = {.notify = startdrag};
481
static struct wl_listener new_session_lock = {.notify = locksession};
482
483
#ifdef XWAYLAND
484
static void activatex11(struct wl_listener *listener, void *data);
485
static void associatex11(struct wl_listener *listener, void *data);
486
static void configurex11(struct wl_listener *listener, void *data);
487
static void createnotifyx11(struct wl_listener *listener, void *data);
488
static void dissociatex11(struct wl_listener *listener, void *data);
489
static void sethints(struct wl_listener *listener, void *data);
490
static void xwaylandready(struct wl_listener *listener, void *data);
491
static struct wl_listener new_xwayland_surface = {.notify = createnotifyx11};
492
static struct wl_listener xwayland_ready = {.notify = xwaylandready};
493
static struct wlr_xwayland *xwayland;
494
#endif
495
496
/* configuration, allows nested code to access above variables */
497
#include "config.h"
498
499
/* attempt to encapsulate suck into one file */
500
#include "client.h"
501
502
/* function implementations */
503
void
504
applybounds(Client *c, struct wlr_box *bbox)
505
{
506
	/* set minimum possible */
507
	c->geom.width = MAX(1 + 2 * (int)c->bw, c->geom.width);
508
	c->geom.height = MAX(1 + 2 * (int)c->bw, c->geom.height);
509
510
	if (c->geom.x >= bbox->x + bbox->width)
511
		c->geom.x = bbox->x + bbox->width - c->geom.width;
512
	if (c->geom.y >= bbox->y + bbox->height)
513
		c->geom.y = bbox->y + bbox->height - c->geom.height;
514
	if (c->geom.x + c->geom.width <= bbox->x)
515
		c->geom.x = bbox->x;
516
	if (c->geom.y + c->geom.height <= bbox->y)
517
		c->geom.y = bbox->y;
518
}
519
520
void
521
applyrules(Client *c)
522
{
523
	/* rule matching */
524
	const char *appid, *title;
525
	uint32_t newtags = 0;
526
	int i;
527
	const Rule *r;
528
	Monitor *mon = selmon, *m;
529
530
	appid = client_get_appid(c);
531
	title = client_get_title(c);
532
533
	for (r = rules; r < END(rules); r++) {
534
		if ((!r->title || strstr(title, r->title))
535
				&& (!r->id || strstr(appid, r->id))) {
536
			c->isfloating = r->isfloating;
537
			newtags |= r->tags;
538
			i = 0;
539
			wl_list_for_each(m, &mons, link) {
540
				if (r->monitor == i++)
541
					mon = m;
542
			}
543
		}
544
	}
545
546
	c->isfloating |= client_is_float_type(c);
547
	setmon(c, mon, newtags);
548
}
549
550
static int
551
textw_no_ansi(Monitor *m, const char *text)
552
{
553
    char buffer[256];
554
    int wr = 0, rd = 0;
555
    
556
    while (text[rd] && wr < sizeof(buffer) - 1) {
557
        if (text[rd] == '\033' && text[rd + 1] == '[') {
558
            size_t alen = strspn(text + rd + 2, "0123456789;");
559
            if (text[rd + alen + 2] == 'm') {
560
                rd += alen + 3;
561
                continue;
562
            }
563
        }
564
        buffer[wr++] = text[rd++];
565
    }
566
    buffer[wr] = '\0';
567
568
    return TEXTW(m, buffer) - m->lrpad;
569
}
570
571
572
static void 
573
draw_ansi_segment(Monitor *m, const char *text, int *x, int height, int lrpad)
574
{
575
    int fg = 7, bg = 0, fmt = 0;
576
    uint32_t pw;
577
    int left_padding = 0; 
578
    char buffer[256];
579
    int wr = 0, rd = 0;
580
581
    while (text[rd] && wr < sizeof(buffer) - 1) {
582
        if (text[rd] == '\033' && text[rd + 1] == '[') {
583
            // Find the end of the escape sequence
584
            int seq_start = rd;
585
            rd += 2; // skip \033[
586
587
            // Parse the sequence more carefully
588
            char *seq_end = strchr(text + rd, 'm');
589
            if (seq_end) {
590
                // Draw any accumulated text first
591
                if (wr > 0) {
592
                    buffer[wr] = '\0';
593
                    pw = TEXTW(m, buffer) - lrpad;
594
                    drwl_setscheme(m->drw, (uint32_t[]){
595
                        barcolors[fg],
596
                        barcolors[bg],
597
                        barcolors[bg]
598
                    });
599
                    drwl_text(m->drw, *x, 0, pw + left_padding, height, left_padding, buffer, fmt & 1);
600
601
                    if (fmt & 2) { 
602
                        drwl_setscheme(m->drw, (uint32_t[]){
603
                            barcolors[fg],
604
                            barcolors[fg],
605
                            barcolors[fg]
606
                        });
607
                        drwl_rect(m->drw, *x + left_padding, height - 2, pw, 1, 1, 0);
608
                    }
609
610
                    *x += pw;
611
                    left_padding = 0;
612
                    wr = 0;
613
                }
614
615
                char *p = (char*)text + seq_start + 2;
616
                while (p < seq_end) {
617
                    unsigned v = strtoul(p, &p, 10);
618
                    if (v == 0) {
619
                        fg = 7; bg = 0; fmt = 0;
620
                    } else if (v == 1) {
621
                        fg |= 8;
622
                    } else if (v == 4) {
623
                        fmt |= 2; 
624
                    } else if (v == 7) {
625
                        fmt |= 1;
626
                    } else if (v == 24) {
627
                        fmt &= ~2; 
628
                    } else if (v == 27) {
629
                        fmt &= ~1;
630
                    } else if (v >= 30 && v <= 37) {
631
                        fg = (v % 10) | (fg & 8);
632
                    } else if (v >= 40 && v <= 47) {
633
                        bg = v % 10;
634
                    }
635
636
                    if (*p == ';') p++;
637
                }
638
639
                rd = seq_end - text + 1;
640
                continue;
641
            }
642
        }
643
        buffer[wr++] = text[rd++];
644
    }
645
646
    if (wr > 0) {
647
        buffer[wr] = '\0';
648
        pw = TEXTW(m, buffer) - lrpad;
649
        drwl_setscheme(m->drw, (uint32_t[]){
650
            barcolors[fg],
651
            barcolors[bg],
652
            barcolors[bg]
653
        });
654
        drwl_text(m->drw, *x, 0, pw + left_padding, height, left_padding, buffer, fmt & 1);
655
656
        if (fmt & 2) { 
657
            drwl_setscheme(m->drw, (uint32_t[]){
658
                barcolors[fg],
659
                barcolors[fg],
660
                barcolors[fg]
661
            });
662
            drwl_rect(m->drw, *x + left_padding, height - 2, pw, 1, 1, 0);
663
        }
664
665
        *x += pw;
666
    }
667
}
668
669
void
670
arrange(Monitor *m)
671
{
672
	Client *c;
673
674
	if (!m->wlr_output->enabled)
675
		return;
676
677
	wl_list_for_each(c, &clients, link) {
678
		if (c->mon == m) {
679
			wlr_scene_node_set_enabled(&c->scene->node, VISIBLEON(c, m));
680
			client_set_suspended(c, !VISIBLEON(c, m));
681
		}
682
	}
683
684
	wlr_scene_node_set_enabled(&m->fullscreen_bg->node,
685
			(c = focustop(m)) && c->isfullscreen);
686
687
	strncpy(m->ltsymbol, m->lt[m->sellt]->symbol, sizeof(m->ltsymbol));
688
689
	/* We move all clients (except fullscreen and unmanaged) to LyrTile while
690
	 * in floating layout to avoid "real" floating clients be always on top */
691
	wl_list_for_each(c, &clients, link) {
692
		if (c->mon != m || c->scene->node.parent == layers[LyrFS])
693
			continue;
694
695
		wlr_scene_node_reparent(&c->scene->node,
696
				(!m->lt[m->sellt]->arrange && c->isfloating)
697
						? layers[LyrTile]
698
						: (m->lt[m->sellt]->arrange && c->isfloating)
699
								? layers[LyrFloat]
700
								: c->scene->node.parent);
701
	}
702
703
	if (m->lt[m->sellt]->arrange)
704
		m->lt[m->sellt]->arrange(m);
705
	motionnotify(0, NULL, 0, 0, 0, 0);
706
	checkidleinhibitor(NULL);
707
}
708
709
void
710
arrangelayer(Monitor *m, struct wl_list *list, struct wlr_box *usable_area, int exclusive)
711
{
712
	LayerSurface *l;
713
	struct wlr_box full_area = m->m;
714
715
	wl_list_for_each(l, list, link) {
716
		struct wlr_layer_surface_v1 *layer_surface = l->layer_surface;
717
718
		if (!layer_surface->initialized)
719
			continue;
720
721
		if (exclusive != (layer_surface->current.exclusive_zone > 0))
722
			continue;
723
724
		wlr_scene_layer_surface_v1_configure(l->scene_layer, &full_area, usable_area);
725
		wlr_scene_node_set_position(&l->popups->node, l->scene->node.x, l->scene->node.y);
726
	}
727
}
728
729
void
730
arrangelayers(Monitor *m)
731
{
732
	int i;
733
	struct wlr_box usable_area = m->m;
734
	LayerSurface *l;
735
	uint32_t layers_above_shell[] = {
736
		ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY,
737
		ZWLR_LAYER_SHELL_V1_LAYER_TOP,
738
	};
739
	if (!m->wlr_output->enabled)
740
		return;
741
742
	if (m->scene_buffer->node.enabled) {
743
		usable_area.height -= m->b.real_height;
744
		usable_area.y += topbar ? m->b.real_height : 0;
745
	}
746
747
	/* Arrange exclusive surfaces from top->bottom */
748
	for (i = 3; i >= 0; i--)
749
		arrangelayer(m, &m->layers[i], &usable_area, 1);
750
751
	if (!wlr_box_equal(&usable_area, &m->w)) {
752
		m->w = usable_area;
753
		arrange(m);
754
	}
755
756
	/* Arrange non-exlusive surfaces from top->bottom */
757
	for (i = 3; i >= 0; i--)
758
		arrangelayer(m, &m->layers[i], &usable_area, 0);
759
760
	/* Find topmost keyboard interactive layer, if such a layer exists */
761
	for (i = 0; i < (int)LENGTH(layers_above_shell); i++) {
762
		wl_list_for_each_reverse(l, &m->layers[layers_above_shell[i]], link) {
763
			if (locked || !l->layer_surface->current.keyboard_interactive || !l->mapped)
764
				continue;
765
			/* Deactivate the focused client. */
766
			focusclient(NULL, 0);
767
			exclusive_focus = l;
768
			client_notify_enter(l->layer_surface->surface, wlr_seat_get_keyboard(seat));
769
			return;
770
		}
771
	}
772
}
773
774
void
775
axisnotify(struct wl_listener *listener, void *data)
776
{
777
	/* This event is forwarded by the cursor when a pointer emits an axis event,
778
	 * for example when you move the scroll wheel. */
779
	struct wlr_pointer_axis_event *event = data;
780
	wlr_idle_notifier_v1_notify_activity(idle_notifier, seat);
781
	/* TODO: allow usage of scroll wheel for mousebindings, it can be implemented
782
	 * by checking the event's orientation and the delta of the event */
783
	/* Notify the client with pointer focus of the axis event. */
784
	wlr_seat_pointer_notify_axis(seat,
785
			event->time_msec, event->orientation, event->delta,
786
			event->delta_discrete, event->source, event->relative_direction);
787
}
788
789
bool
790
baracceptsinput(struct wlr_scene_buffer *buffer, double *sx, double *sy)
791
{
792
	return true;
793
}
794
795
void
796
bufdestroy(struct wlr_buffer *wlr_buffer)
797
{
798
	Buffer *buf = wl_container_of(wlr_buffer, buf, base);
799
	if (buf->busy)
800
		wl_list_remove(&buf->release.link);
801
	drwl_image_destroy(buf->image);
802
	free(buf);
803
}
804
805
bool
806
bufdatabegin(struct wlr_buffer *wlr_buffer, uint32_t flags,
807
		void **data, uint32_t *format, size_t *stride)
808
{
809
	Buffer *buf = wl_container_of(wlr_buffer, buf, base);
810
811
	if (flags & WLR_BUFFER_DATA_PTR_ACCESS_WRITE) return false;
812
813
	*data   = buf->data;
814
	*stride = wlr_buffer->width * 4;
815
	*format = DRM_FORMAT_ARGB8888;
816
817
	return true;
818
}
819
820
void
821
bufdataend(struct wlr_buffer *wlr_buffer)
822
{
823
}
824
825
Buffer *
826
bufmon(Monitor *m)
827
{
828
	size_t i;
829
	Buffer *buf = NULL;
830
831
	for (i = 0; i < LENGTH(m->pool); i++) {
832
		if (m->pool[i]) {
833
			if (m->pool[i]->busy)
834
				continue;
835
			buf = m->pool[i];
836
			break;
837
		}
838
839
		buf = ecalloc(1, sizeof(Buffer) + (m->b.width * 4 * m->b.height));
840
		buf->image = drwl_image_create(NULL, m->b.width, m->b.height, buf->data);
841
		wlr_buffer_init(&buf->base, &buffer_impl, m->b.width, m->b.height);
842
		m->pool[i] = buf;
843
		break;
844
	}
845
	if (!buf)
846
		return NULL;
847
848
	buf->busy = true;
849
	LISTEN(&buf->base.events.release, &buf->release, bufrelease);
850
	wlr_buffer_lock(&buf->base);
851
	drwl_setimage(m->drw, buf->image);
852
	return buf;
853
}
854
855
void
856
bufrelease(struct wl_listener *listener, void *data)
857
{
858
	Buffer *buf = wl_container_of(listener, buf, release);
859
	buf->busy = false;
860
	wl_list_remove(&buf->release.link);
861
}
862
863
void
864
buttonpress(struct wl_listener *listener, void *data)
865
{
866
	unsigned int i = 0, x = 0;
867
	double cx;
868
	unsigned int click;
869
	struct wlr_pointer_button_event *event = data;
870
	struct wlr_keyboard *keyboard;
871
	struct wlr_scene_node *node;
872
	struct wlr_scene_buffer *buffer;
873
	uint32_t mods;
874
	Arg arg = {0};
875
	Client *c;
876
	const Button *b;
877
878
	wlr_idle_notifier_v1_notify_activity(idle_notifier, seat);
879
880
	click = ClkRoot;
881
	xytonode(cursor->x, cursor->y, NULL, &c, NULL, NULL, NULL);
882
	if (c)
883
		click = ClkClient;
884
885
	switch (event->state) {
886
	case WL_POINTER_BUTTON_STATE_PRESSED:
887
		cursor_mode = CurPressed;
888
		selmon = xytomon(cursor->x, cursor->y);
889
		if (locked)
890
			break;
891
892
		if (!c && !exclusive_focus &&
893
			(node = wlr_scene_node_at(&layers[LyrBottom]->node, cursor->x, cursor->y, NULL, NULL)) &&
894
			(buffer = wlr_scene_buffer_from_node(node)) && buffer == selmon->scene_buffer) {
895
			cx = (cursor->x - selmon->m.x) * selmon->wlr_output->scale;
896
			do
897
				x += TEXTW(selmon, tags[i]);
898
			while (cx >= x && ++i < LENGTH(tags));
899
			if (i < LENGTH(tags)) {
900
				click = ClkTagBar;
901
				arg.ui = 1 << i;
902
			} else if (cx < x + TEXTW(selmon, selmon->ltsymbol))
903
				click = ClkLtSymbol;
904
			else if (cx > selmon->b.width - (TEXTW(selmon, stext) - selmon->lrpad + 2)) {
905
				click = ClkStatus;
906
			} else
907
				click = ClkTitle;
908
		}
909
910
		/* Change focus if the button was _pressed_ over a client */
911
		xytonode(cursor->x, cursor->y, NULL, &c, NULL, NULL, NULL);
912
		if (click == ClkClient && (!client_is_unmanaged(c) || client_wants_focus(c)))
913
			focusclient(c, 1);
914
915
		keyboard = wlr_seat_get_keyboard(seat);
916
		mods = keyboard ? wlr_keyboard_get_modifiers(keyboard) : 0;
917
		for (b = buttons; b < END(buttons); b++) {
918
			if (CLEANMASK(mods) == CLEANMASK(b->mod) && event->button == b->button && click == b->click && b->func) {
919
				b->func(click == ClkTagBar && b->arg.i == 0 ? &arg : &b->arg);
920
				return;
921
			}
922
		}
923
		break;
924
	case WL_POINTER_BUTTON_STATE_RELEASED:
925
		/* If you released any buttons, we exit interactive move/resize mode. */
926
		/* TODO: should reset to the pointer focus's current setcursor */
927
		if (!locked && cursor_mode != CurNormal && cursor_mode != CurPressed) {
928
			wlr_cursor_set_xcursor(cursor, cursor_mgr, "default");
929
			cursor_mode = CurNormal;
930
			/* Drop the window off on its new monitor */
931
			selmon = xytomon(cursor->x, cursor->y);
932
			setmon(grabc, selmon, 0);
933
			grabc = NULL;
934
			return;
935
		}
936
		cursor_mode = CurNormal;
937
		break;
938
	}
939
	/* If the event wasn't handled by the compositor, notify the client with
940
	 * pointer focus that a button press has occurred */
941
	wlr_seat_pointer_notify_button(seat,
942
			event->time_msec, event->button, event->state);
943
}
944
945
void
946
chvt(const Arg *arg)
947
{
948
	wlr_session_change_vt(session, arg->ui);
949
}
950
951
void
952
checkidleinhibitor(struct wlr_surface *exclude)
953
{
954
	int inhibited = 0, unused_lx, unused_ly;
955
	struct wlr_idle_inhibitor_v1 *inhibitor;
956
	wl_list_for_each(inhibitor, &idle_inhibit_mgr->inhibitors, link) {
957
		struct wlr_surface *surface = wlr_surface_get_root_surface(inhibitor->surface);
958
		struct wlr_scene_tree *tree = surface->data;
959
		if (exclude != surface && (bypass_surface_visibility || (!tree
960
				|| wlr_scene_node_coords(&tree->node, &unused_lx, &unused_ly)))) {
961
			inhibited = 1;
962
			break;
963
		}
964
	}
965
966
	wlr_idle_notifier_v1_set_inhibited(idle_notifier, inhibited);
967
}
968
969
void
970
cleanup(void)
971
{
972
	cleanuplisteners();
973
#ifdef XWAYLAND
974
	wlr_xwayland_destroy(xwayland);
975
	xwayland = NULL;
976
#endif
977
	wl_display_destroy_clients(dpy);
978
	if (child_pid > 0) {
979
		kill(-child_pid, SIGTERM);
980
		waitpid(child_pid, NULL, 0);
981
	}
982
	wlr_xcursor_manager_destroy(cursor_mgr);
983
984
	destroykeyboardgroup(&kb_group->destroy, NULL);
985
986
	/* If it's not destroyed manually, it will cause a use-after-free of wlr_seat.
987
	 * Destroy it until it's fixed on the wlroots side */
988
	wlr_backend_destroy(backend);
989
990
	wl_display_destroy(dpy);
991
	/* Destroy after the wayland display (when the monitors are already destroyed)
992
	   to avoid destroying them with an invalid scene output. */
993
	wlr_scene_node_destroy(&scene->tree.node);
994
995
	drwl_fini();
996
}
997
998
void
999
cleanupmon(struct wl_listener *listener, void *data)
1000
{
1001
	Monitor *m = wl_container_of(listener, m, destroy);
1002
	LayerSurface *l, *tmp;
1003
	size_t i;
1004
1005
	/* m->layers[i] are intentionally not unlinked */
1006
	for (i = 0; i < LENGTH(m->layers); i++) {
1007
		wl_list_for_each_safe(l, tmp, &m->layers[i], link)
1008
			wlr_layer_surface_v1_destroy(l->layer_surface);
1009
	}
1010
1011
	for (i = 0; i < LENGTH(m->pool); i++)
1012
		wlr_buffer_drop(&m->pool[i]->base);
1013
1014
	drwl_setimage(m->drw, NULL);
1015
	drwl_destroy(m->drw);
1016
1017
	wl_list_remove(&m->destroy.link);
1018
	wl_list_remove(&m->frame.link);
1019
	wl_list_remove(&m->link);
1020
	wl_list_remove(&m->request_state.link);
1021
	if (m->lock_surface)
1022
		destroylocksurface(&m->destroy_lock_surface, NULL);
1023
	m->wlr_output->data = NULL;
1024
	wlr_output_layout_remove(output_layout, m->wlr_output);
1025
	wlr_scene_output_destroy(m->scene_output);
1026
1027
	closemon(m);
1028
	wlr_scene_node_destroy(&m->fullscreen_bg->node);
1029
	wlr_scene_node_destroy(&m->scene_buffer->node);
1030
	free(m);
1031
}
1032
1033
void
1034
cleanuplisteners(void)
1035
{
1036
	wl_list_remove(&cursor_axis.link);
1037
	wl_list_remove(&cursor_button.link);
1038
	wl_list_remove(&cursor_frame.link);
1039
	wl_list_remove(&cursor_motion.link);
1040
	wl_list_remove(&cursor_motion_absolute.link);
1041
	wl_list_remove(&gpu_reset.link);
1042
	wl_list_remove(&new_idle_inhibitor.link);
1043
	wl_list_remove(&layout_change.link);
1044
	wl_list_remove(&new_input_device.link);
1045
	wl_list_remove(&new_virtual_keyboard.link);
1046
	wl_list_remove(&new_virtual_pointer.link);
1047
	wl_list_remove(&new_pointer_constraint.link);
1048
	wl_list_remove(&new_output.link);
1049
	wl_list_remove(&new_xdg_toplevel.link);
1050
	wl_list_remove(&new_xdg_decoration.link);
1051
	wl_list_remove(&new_xdg_popup.link);
1052
	wl_list_remove(&new_layer_surface.link);
1053
	wl_list_remove(&output_mgr_apply.link);
1054
	wl_list_remove(&output_mgr_test.link);
1055
	wl_list_remove(&output_power_mgr_set_mode.link);
1056
	wl_list_remove(&request_activate.link);
1057
	wl_list_remove(&request_cursor.link);
1058
	wl_list_remove(&request_set_psel.link);
1059
	wl_list_remove(&request_set_sel.link);
1060
	wl_list_remove(&request_set_cursor_shape.link);
1061
	wl_list_remove(&request_start_drag.link);
1062
	wl_list_remove(&start_drag.link);
1063
	wl_list_remove(&new_session_lock.link);
1064
#ifdef XWAYLAND
1065
	wl_list_remove(&new_xwayland_surface.link);
1066
	wl_list_remove(&xwayland_ready.link);
1067
#endif
1068
}
1069
1070
void
1071
closemon(Monitor *m)
1072
{
1073
	/* update selmon if needed and
1074
	 * move closed monitor's clients to the focused one */
1075
	Client *c;
1076
	int i = 0, nmons = wl_list_length(&mons);
1077
	if (!nmons) {
1078
		selmon = NULL;
1079
	} else if (m == selmon) {
1080
		do /* don't switch to disabled mons */
1081
			selmon = wl_container_of(mons.next, selmon, link);
1082
		while (!selmon->wlr_output->enabled && i++ < nmons);
1083
1084
		if (!selmon->wlr_output->enabled)
1085
			selmon = NULL;
1086
	}
1087
1088
	wl_list_for_each(c, &clients, link) {
1089
		if (c->isfloating && c->geom.x > m->m.width)
1090
			resize(c, (struct wlr_box){.x = c->geom.x - m->w.width, .y = c->geom.y,
1091
					.width = c->geom.width, .height = c->geom.height}, 0);
1092
		if (c->mon == m)
1093
			setmon(c, selmon, c->tags);
1094
	}
1095
	focusclient(focustop(selmon), 1);
1096
	drawbars();
1097
}
1098
1099
void
1100
commitlayersurfacenotify(struct wl_listener *listener, void *data)
1101
{
1102
	LayerSurface *l = wl_container_of(listener, l, surface_commit);
1103
	struct wlr_layer_surface_v1 *layer_surface = l->layer_surface;
1104
	struct wlr_scene_tree *scene_layer = layers[layermap[layer_surface->current.layer]];
1105
	struct wlr_layer_surface_v1_state old_state;
1106
1107
	if (l->layer_surface->initial_commit) {
1108
		client_set_scale(layer_surface->surface, l->mon->wlr_output->scale);
1109
1110
		/* Temporarily set the layer's current state to pending
1111
		 * so that we can easily arrange it */
1112
		old_state = l->layer_surface->current;
1113
		l->layer_surface->current = l->layer_surface->pending;
1114
		arrangelayers(l->mon);
1115
		l->layer_surface->current = old_state;
1116
		return;
1117
	}
1118
1119
	if (layer_surface->current.committed == 0 && l->mapped == layer_surface->surface->mapped)
1120
		return;
1121
	l->mapped = layer_surface->surface->mapped;
1122
1123
	if (scene_layer != l->scene->node.parent) {
1124
		wlr_scene_node_reparent(&l->scene->node, scene_layer);
1125
		wl_list_remove(&l->link);
1126
		wl_list_insert(&l->mon->layers[layer_surface->current.layer], &l->link);
1127
		wlr_scene_node_reparent(&l->popups->node, (layer_surface->current.layer
1128
				< ZWLR_LAYER_SHELL_V1_LAYER_TOP ? layers[LyrTop] : scene_layer));
1129
	}
1130
1131
	arrangelayers(l->mon);
1132
}
1133
1134
void
1135
commitnotify(struct wl_listener *listener, void *data)
1136
{
1137
	Client *c = wl_container_of(listener, c, commit);
1138
1139
	if (c->surface.xdg->initial_commit) {
1140
		/*
1141
		 * Get the monitor this client will be rendered on
1142
		 * Note that if the user set a rule in which the client is placed on
1143
		 * a different monitor based on its title, this will likely select
1144
		 * a wrong monitor.
1145
		 */
1146
		applyrules(c);
1147
		if (c->mon) {
1148
			client_set_scale(client_surface(c), c->mon->wlr_output->scale);
1149
		}
1150
		setmon(c, NULL, 0); /* Make sure to reapply rules in mapnotify() */
1151
1152
		wlr_xdg_toplevel_set_wm_capabilities(c->surface.xdg->toplevel,
1153
				WLR_XDG_TOPLEVEL_WM_CAPABILITIES_FULLSCREEN);
1154
		if (c->decoration)
1155
			requestdecorationmode(&c->set_decoration_mode, c->decoration);
1156
		wlr_xdg_toplevel_set_size(c->surface.xdg->toplevel, 0, 0);
1157
		return;
1158
	}
1159
1160
	resize(c, c->geom, (c->isfloating && !c->isfullscreen));
1161
1162
	/* mark a pending resize as completed */
1163
	if (c->resize && c->resize <= c->surface.xdg->current.configure_serial)
1164
		c->resize = 0;
1165
}
1166
1167
void
1168
commitpopup(struct wl_listener *listener, void *data)
1169
{
1170
	struct wlr_surface *surface = data;
1171
	struct wlr_xdg_popup *popup = wlr_xdg_popup_try_from_wlr_surface(surface);
1172
	LayerSurface *l = NULL;
1173
	Client *c = NULL;
1174
	struct wlr_box box;
1175
	int type = -1;
1176
1177
	if (!popup->base->initial_commit)
1178
		return;
1179
1180
	type = toplevel_from_wlr_surface(popup->base->surface, &c, &l);
1181
	if (!popup->parent || type < 0)
1182
		return;
1183
	popup->base->surface->data = wlr_scene_xdg_surface_create(
1184
			popup->parent->data, popup->base);
1185
	if ((l && !l->mon) || (c && !c->mon)) {
1186
		wlr_xdg_popup_destroy(popup);
1187
		return;
1188
	}
1189
	box = type == LayerShell ? l->mon->m : c->mon->w;
1190
	box.x -= (type == LayerShell ? l->scene->node.x : c->geom.x);
1191
	box.y -= (type == LayerShell ? l->scene->node.y : c->geom.y);
1192
	wlr_xdg_popup_unconstrain_from_box(popup, &box);
1193
	wl_list_remove(&listener->link);
1194
	free(listener);
1195
}
1196
1197
void
1198
createdecoration(struct wl_listener *listener, void *data)
1199
{
1200
	struct wlr_xdg_toplevel_decoration_v1 *deco = data;
1201
	Client *c = deco->toplevel->base->data;
1202
	c->decoration = deco;
1203
1204
	LISTEN(&deco->events.request_mode, &c->set_decoration_mode, requestdecorationmode);
1205
	LISTEN(&deco->events.destroy, &c->destroy_decoration, destroydecoration);
1206
1207
	requestdecorationmode(&c->set_decoration_mode, deco);
1208
}
1209
1210
void
1211
createidleinhibitor(struct wl_listener *listener, void *data)
1212
{
1213
	struct wlr_idle_inhibitor_v1 *idle_inhibitor = data;
1214
	LISTEN_STATIC(&idle_inhibitor->events.destroy, destroyidleinhibitor);
1215
1216
	checkidleinhibitor(NULL);
1217
}
1218
1219
void
1220
createkeyboard(struct wlr_keyboard *keyboard)
1221
{
1222
	/* Set the keymap to match the group keymap */
1223
	wlr_keyboard_set_keymap(keyboard, kb_group->wlr_group->keyboard.keymap);
1224
1225
	/* Add the new keyboard to the group */
1226
	wlr_keyboard_group_add_keyboard(kb_group->wlr_group, keyboard);
1227
}
1228
1229
KeyboardGroup *
1230
createkeyboardgroup(void)
1231
{
1232
	KeyboardGroup *group = ecalloc(1, sizeof(*group));
1233
	struct xkb_context *context;
1234
	struct xkb_keymap *keymap;
1235
1236
	group->wlr_group = wlr_keyboard_group_create();
1237
	group->wlr_group->data = group;
1238
1239
	/* Prepare an XKB keymap and assign it to the keyboard group. */
1240
	context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
1241
	if (!(keymap = xkb_keymap_new_from_names(context, &xkb_rules,
1242
				XKB_KEYMAP_COMPILE_NO_FLAGS)))
1243
		die("failed to compile keymap");
1244
1245
	wlr_keyboard_set_keymap(&group->wlr_group->keyboard, keymap);
1246
	xkb_keymap_unref(keymap);
1247
	xkb_context_unref(context);
1248
1249
	wlr_keyboard_set_repeat_info(&group->wlr_group->keyboard, repeat_rate, repeat_delay);
1250
1251
	/* Set up listeners for keyboard events */
1252
	LISTEN(&group->wlr_group->keyboard.events.key, &group->key, keypress);
1253
	LISTEN(&group->wlr_group->keyboard.events.modifiers, &group->modifiers, keypressmod);
1254
1255
	group->key_repeat_source = wl_event_loop_add_timer(event_loop, keyrepeat, group);
1256
1257
	/* A seat can only have one keyboard, but this is a limitation of the
1258
	 * Wayland protocol - not wlroots. We assign all connected keyboards to the
1259
	 * same wlr_keyboard_group, which provides a single wlr_keyboard interface for
1260
	 * all of them. Set this combined wlr_keyboard as the seat keyboard.
1261
	 */
1262
	wlr_seat_set_keyboard(seat, &group->wlr_group->keyboard);
1263
	return group;
1264
}
1265
1266
void
1267
createlayersurface(struct wl_listener *listener, void *data)
1268
{
1269
	struct wlr_layer_surface_v1 *layer_surface = data;
1270
	LayerSurface *l;
1271
	struct wlr_surface *surface = layer_surface->surface;
1272
	struct wlr_scene_tree *scene_layer = layers[layermap[layer_surface->pending.layer]];
1273
1274
	if (!layer_surface->output
1275
			&& !(layer_surface->output = selmon ? selmon->wlr_output : NULL)) {
1276
		wlr_layer_surface_v1_destroy(layer_surface);
1277
		return;
1278
	}
1279
1280
	l = layer_surface->data = ecalloc(1, sizeof(*l));
1281
	l->type = LayerShell;
1282
	LISTEN(&surface->events.commit, &l->surface_commit, commitlayersurfacenotify);
1283
	LISTEN(&surface->events.unmap, &l->unmap, unmaplayersurfacenotify);
1284
	LISTEN(&layer_surface->events.destroy, &l->destroy, destroylayersurfacenotify);
1285
1286
	l->layer_surface = layer_surface;
1287
	l->mon = layer_surface->output->data;
1288
	l->scene_layer = wlr_scene_layer_surface_v1_create(scene_layer, layer_surface);
1289
	l->scene = l->scene_layer->tree;
1290
	l->popups = surface->data = wlr_scene_tree_create(layer_surface->current.layer
1291
			< ZWLR_LAYER_SHELL_V1_LAYER_TOP ? layers[LyrTop] : scene_layer);
1292
	l->scene->node.data = l->popups->node.data = l;
1293
1294
	wl_list_insert(&l->mon->layers[layer_surface->pending.layer],&l->link);
1295
	wlr_surface_send_enter(surface, layer_surface->output);
1296
}
1297
1298
void
1299
createlocksurface(struct wl_listener *listener, void *data)
1300
{
1301
	SessionLock *lock = wl_container_of(listener, lock, new_surface);
1302
	struct wlr_session_lock_surface_v1 *lock_surface = data;
1303
	Monitor *m = lock_surface->output->data;
1304
	struct wlr_scene_tree *scene_tree = lock_surface->surface->data
1305
			= wlr_scene_subsurface_tree_create(lock->scene, lock_surface->surface);
1306
	m->lock_surface = lock_surface;
1307
1308
	wlr_scene_node_set_position(&scene_tree->node, m->m.x, m->m.y);
1309
	wlr_session_lock_surface_v1_configure(lock_surface, m->m.width, m->m.height);
1310
1311
	LISTEN(&lock_surface->events.destroy, &m->destroy_lock_surface, destroylocksurface);
1312
1313
	if (m == selmon)
1314
		client_notify_enter(lock_surface->surface, wlr_seat_get_keyboard(seat));
1315
}
1316
1317
void
1318
createmon(struct wl_listener *listener, void *data)
1319
{
1320
	/* This event is raised by the backend when a new output (aka a display or
1321
	 * monitor) becomes available. */
1322
	struct wlr_output *wlr_output = data;
1323
	const MonitorRule *r;
1324
	size_t i;
1325
	struct wlr_output_state state;
1326
	Monitor *m;
1327
1328
	if (!wlr_output_init_render(wlr_output, alloc, drw))
1329
		return;
1330
1331
	m = wlr_output->data = ecalloc(1, sizeof(*m));
1332
	m->wlr_output = wlr_output;
1333
1334
	for (i = 0; i < LENGTH(m->layers); i++)
1335
		wl_list_init(&m->layers[i]);
1336
1337
	wlr_output_state_init(&state);
1338
	/* Initialize monitor state using configured rules */
1339
	m->gaps = gaps;
1340
1341
	m->tagset[0] = m->tagset[1] = 1;
1342
	for (r = monrules; r < END(monrules); r++) {
1343
		if (!r->name || strstr(wlr_output->name, r->name)) {
1344
			m->m.x = r->x;
1345
			m->m.y = r->y;
1346
			m->mfact = r->mfact;
1347
			m->nmaster = r->nmaster;
1348
			m->lt[0] = r->lt;
1349
			m->lt[1] = &layouts[LENGTH(layouts) > 1 && r->lt != &layouts[1]];
1350
			strncpy(m->ltsymbol, m->lt[m->sellt]->symbol, sizeof(m->ltsymbol));
1351
			wlr_output_state_set_scale(&state, r->scale);
1352
			wlr_output_state_set_transform(&state, r->rr);
1353
			break;
1354
		}
1355
	}
1356
1357
	/* The mode is a tuple of (width, height, refresh rate), and each
1358
	 * monitor supports only a specific set of modes. We just pick the
1359
	 * monitor's preferred mode; a more sophisticated compositor would let
1360
	 * the user configure it. */
1361
	wlr_output_state_set_mode(&state, wlr_output_preferred_mode(wlr_output));
1362
1363
	/* Set up event listeners */
1364
	LISTEN(&wlr_output->events.frame, &m->frame, rendermon);
1365
	LISTEN(&wlr_output->events.destroy, &m->destroy, cleanupmon);
1366
	LISTEN(&wlr_output->events.request_state, &m->request_state, requestmonstate);
1367
1368
	wlr_output_state_set_enabled(&state, 1);
1369
	wlr_output_commit_state(wlr_output, &state);
1370
	wlr_output_state_finish(&state);
1371
1372
	if (!(m->drw = drwl_create()))
1373
		die("failed to create drwl context");
1374
1375
	m->scene_buffer = wlr_scene_buffer_create(layers[LyrBottom], NULL);
1376
	m->scene_buffer->point_accepts_input = baracceptsinput;
1377
	updatebar(m);
1378
1379
	wl_list_insert(&mons, &m->link);
1380
	drawbars();
1381
1382
	/* The xdg-protocol specifies:
1383
	 *
1384
	 * If the fullscreened surface is not opaque, the compositor must make
1385
	 * sure that other screen content not part of the same surface tree (made
1386
	 * up of subsurfaces, popups or similarly coupled surfaces) are not
1387
	 * visible below the fullscreened surface.
1388
	 *
1389
	 */
1390
	/* updatemons() will resize and set correct position */
1391
	m->fullscreen_bg = wlr_scene_rect_create(layers[LyrFS], 0, 0, fullscreen_bg);
1392
	wlr_scene_node_set_enabled(&m->fullscreen_bg->node, 0);
1393
1394
	/* Adds this to the output layout in the order it was configured.
1395
	 *
1396
	 * The output layout utility automatically adds a wl_output global to the
1397
	 * display, which Wayland clients can see to find out information about the
1398
	 * output (such as DPI, scale factor, manufacturer, etc).
1399
	 */
1400
	m->scene_output = wlr_scene_output_create(scene, wlr_output);
1401
	if (m->m.x == -1 && m->m.y == -1)
1402
		wlr_output_layout_add_auto(output_layout, wlr_output);
1403
	else
1404
		wlr_output_layout_add(output_layout, wlr_output, m->m.x, m->m.y);
1405
}
1406
1407
void
1408
createnotify(struct wl_listener *listener, void *data)
1409
{
1410
	/* This event is raised when a client creates a new toplevel (application window). */
1411
	struct wlr_xdg_toplevel *toplevel = data;
1412
	Client *c = NULL;
1413
1414
	/* Allocate a Client for this surface */
1415
	c = toplevel->base->data = ecalloc(1, sizeof(*c));
1416
	c->surface.xdg = toplevel->base;
1417
	c->bw = borderpx;
1418
1419
	LISTEN(&toplevel->base->surface->events.commit, &c->commit, commitnotify);
1420
	LISTEN(&toplevel->base->surface->events.map, &c->map, mapnotify);
1421
	LISTEN(&toplevel->base->surface->events.unmap, &c->unmap, unmapnotify);
1422
	LISTEN(&toplevel->events.destroy, &c->destroy, destroynotify);
1423
	LISTEN(&toplevel->events.request_fullscreen, &c->fullscreen, fullscreennotify);
1424
	LISTEN(&toplevel->events.request_maximize, &c->maximize, maximizenotify);
1425
	LISTEN(&toplevel->events.set_title, &c->set_title, updatetitle);
1426
}
1427
1428
void
1429
createpointer(struct wlr_pointer *pointer)
1430
{
1431
	struct libinput_device *device;
1432
	if (wlr_input_device_is_libinput(&pointer->base)
1433
			&& (device = wlr_libinput_get_device_handle(&pointer->base))) {
1434
1435
		if (libinput_device_config_tap_get_finger_count(device)) {
1436
			libinput_device_config_tap_set_enabled(device, tap_to_click);
1437
			libinput_device_config_tap_set_drag_enabled(device, tap_and_drag);
1438
			libinput_device_config_tap_set_drag_lock_enabled(device, drag_lock);
1439
			libinput_device_config_tap_set_button_map(device, button_map);
1440
		}
1441
1442
		if (libinput_device_config_scroll_has_natural_scroll(device))
1443
			libinput_device_config_scroll_set_natural_scroll_enabled(device, natural_scrolling);
1444
1445
		if (libinput_device_config_dwt_is_available(device))
1446
			libinput_device_config_dwt_set_enabled(device, disable_while_typing);
1447
1448
		if (libinput_device_config_left_handed_is_available(device))
1449
			libinput_device_config_left_handed_set(device, left_handed);
1450
1451
		if (libinput_device_config_middle_emulation_is_available(device))
1452
			libinput_device_config_middle_emulation_set_enabled(device, middle_button_emulation);
1453
1454
		if (libinput_device_config_scroll_get_methods(device) != LIBINPUT_CONFIG_SCROLL_NO_SCROLL)
1455
			libinput_device_config_scroll_set_method(device, scroll_method);
1456
1457
		if (libinput_device_config_click_get_methods(device) != LIBINPUT_CONFIG_CLICK_METHOD_NONE)
1458
			libinput_device_config_click_set_method(device, click_method);
1459
1460
		if (libinput_device_config_send_events_get_modes(device))
1461
			libinput_device_config_send_events_set_mode(device, send_events_mode);
1462
1463
		if (libinput_device_config_accel_is_available(device)) {
1464
			libinput_device_config_accel_set_profile(device, accel_profile);
1465
			libinput_device_config_accel_set_speed(device, accel_speed);
1466
		}
1467
	}
1468
1469
	wlr_cursor_attach_input_device(cursor, &pointer->base);
1470
}
1471
1472
void
1473
createpointerconstraint(struct wl_listener *listener, void *data)
1474
{
1475
	PointerConstraint *pointer_constraint = ecalloc(1, sizeof(*pointer_constraint));
1476
	pointer_constraint->constraint = data;
1477
	LISTEN(&pointer_constraint->constraint->events.destroy,
1478
			&pointer_constraint->destroy, destroypointerconstraint);
1479
}
1480
1481
void
1482
createpopup(struct wl_listener *listener, void *data)
1483
{
1484
	/* This event is raised when a client (either xdg-shell or layer-shell)
1485
	 * creates a new popup. */
1486
	struct wlr_xdg_popup *popup = data;
1487
	LISTEN_STATIC(&popup->base->surface->events.commit, commitpopup);
1488
}
1489
1490
void
1491
cursorconstrain(struct wlr_pointer_constraint_v1 *constraint)
1492
{
1493
	if (active_constraint == constraint)
1494
		return;
1495
1496
	if (active_constraint)
1497
		wlr_pointer_constraint_v1_send_deactivated(active_constraint);
1498
1499
	active_constraint = constraint;
1500
	wlr_pointer_constraint_v1_send_activated(constraint);
1501
}
1502
1503
void
1504
cursorframe(struct wl_listener *listener, void *data)
1505
{
1506
	/* This event is forwarded by the cursor when a pointer emits a frame
1507
	 * event. Frame events are sent after regular pointer events to group
1508
	 * multiple events together. For instance, two axis events may happen at the
1509
	 * same time, in which case a frame event won't be sent in between. */
1510
	/* Notify the client with pointer focus of the frame event. */
1511
	wlr_seat_pointer_notify_frame(seat);
1512
}
1513
1514
void
1515
cursorwarptohint(void)
1516
{
1517
	Client *c = NULL;
1518
	double sx = active_constraint->current.cursor_hint.x;
1519
	double sy = active_constraint->current.cursor_hint.y;
1520
1521
	toplevel_from_wlr_surface(active_constraint->surface, &c, NULL);
1522
	if (c && active_constraint->current.cursor_hint.enabled) {
1523
		wlr_cursor_warp(cursor, NULL, sx + c->geom.x + c->bw, sy + c->geom.y + c->bw);
1524
		wlr_seat_pointer_warp(active_constraint->seat, sx, sy);
1525
	}
1526
}
1527
1528
void
1529
destroydecoration(struct wl_listener *listener, void *data)
1530
{
1531
	Client *c = wl_container_of(listener, c, destroy_decoration);
1532
1533
	wl_list_remove(&c->destroy_decoration.link);
1534
	wl_list_remove(&c->set_decoration_mode.link);
1535
}
1536
1537
void
1538
destroydragicon(struct wl_listener *listener, void *data)
1539
{
1540
	/* Focus enter isn't sent during drag, so refocus the focused node. */
1541
	focusclient(focustop(selmon), 1);
1542
	motionnotify(0, NULL, 0, 0, 0, 0);
1543
	wl_list_remove(&listener->link);
1544
	free(listener);
1545
}
1546
1547
void
1548
destroyidleinhibitor(struct wl_listener *listener, void *data)
1549
{
1550
	/* `data` is the wlr_surface of the idle inhibitor being destroyed,
1551
	 * at this point the idle inhibitor is still in the list of the manager */
1552
	checkidleinhibitor(wlr_surface_get_root_surface(data));
1553
	wl_list_remove(&listener->link);
1554
	free(listener);
1555
}
1556
1557
void
1558
destroylayersurfacenotify(struct wl_listener *listener, void *data)
1559
{
1560
	LayerSurface *l = wl_container_of(listener, l, destroy);
1561
1562
	wl_list_remove(&l->link);
1563
	wl_list_remove(&l->destroy.link);
1564
	wl_list_remove(&l->unmap.link);
1565
	wl_list_remove(&l->surface_commit.link);
1566
	wlr_scene_node_destroy(&l->scene->node);
1567
	wlr_scene_node_destroy(&l->popups->node);
1568
	free(l);
1569
}
1570
1571
void
1572
destroylock(SessionLock *lock, int unlock)
1573
{
1574
	wlr_seat_keyboard_notify_clear_focus(seat);
1575
	if ((locked = !unlock))
1576
		goto destroy;
1577
1578
	wlr_scene_node_set_enabled(&locked_bg->node, 0);
1579
1580
	focusclient(focustop(selmon), 0);
1581
	motionnotify(0, NULL, 0, 0, 0, 0);
1582
1583
destroy:
1584
	wl_list_remove(&lock->new_surface.link);
1585
	wl_list_remove(&lock->unlock.link);
1586
	wl_list_remove(&lock->destroy.link);
1587
1588
	wlr_scene_node_destroy(&lock->scene->node);
1589
	cur_lock = NULL;
1590
	free(lock);
1591
}
1592
1593
void
1594
destroylocksurface(struct wl_listener *listener, void *data)
1595
{
1596
	Monitor *m = wl_container_of(listener, m, destroy_lock_surface);
1597
	struct wlr_session_lock_surface_v1 *surface, *lock_surface = m->lock_surface;
1598
1599
	m->lock_surface = NULL;
1600
	wl_list_remove(&m->destroy_lock_surface.link);
1601
1602
	if (lock_surface->surface != seat->keyboard_state.focused_surface)
1603
		return;
1604
1605
	if (locked && cur_lock && !wl_list_empty(&cur_lock->surfaces)) {
1606
		surface = wl_container_of(cur_lock->surfaces.next, surface, link);
1607
		client_notify_enter(surface->surface, wlr_seat_get_keyboard(seat));
1608
	} else if (!locked) {
1609
		focusclient(focustop(selmon), 1);
1610
	} else {
1611
		wlr_seat_keyboard_clear_focus(seat);
1612
	}
1613
}
1614
1615
void
1616
destroynotify(struct wl_listener *listener, void *data)
1617
{
1618
	/* Called when the xdg_toplevel is destroyed. */
1619
	Client *c = wl_container_of(listener, c, destroy);
1620
	wl_list_remove(&c->destroy.link);
1621
	wl_list_remove(&c->set_title.link);
1622
	wl_list_remove(&c->fullscreen.link);
1623
#ifdef XWAYLAND
1624
	if (c->type != XDGShell) {
1625
		wl_list_remove(&c->activate.link);
1626
		wl_list_remove(&c->associate.link);
1627
		wl_list_remove(&c->configure.link);
1628
		wl_list_remove(&c->dissociate.link);
1629
		wl_list_remove(&c->set_hints.link);
1630
	} else
1631
#endif
1632
	{
1633
		wl_list_remove(&c->commit.link);
1634
		wl_list_remove(&c->map.link);
1635
		wl_list_remove(&c->unmap.link);
1636
		wl_list_remove(&c->maximize.link);
1637
	}
1638
	free(c);
1639
}
1640
1641
void
1642
destroypointerconstraint(struct wl_listener *listener, void *data)
1643
{
1644
	PointerConstraint *pointer_constraint = wl_container_of(listener, pointer_constraint, destroy);
1645
1646
	if (active_constraint == pointer_constraint->constraint) {
1647
		cursorwarptohint();
1648
		active_constraint = NULL;
1649
	}
1650
1651
	wl_list_remove(&pointer_constraint->destroy.link);
1652
	free(pointer_constraint);
1653
}
1654
1655
void
1656
destroysessionlock(struct wl_listener *listener, void *data)
1657
{
1658
	SessionLock *lock = wl_container_of(listener, lock, destroy);
1659
	destroylock(lock, 0);
1660
}
1661
1662
void
1663
destroykeyboardgroup(struct wl_listener *listener, void *data)
1664
{
1665
	KeyboardGroup *group = wl_container_of(listener, group, destroy);
1666
	wl_event_source_remove(group->key_repeat_source);
1667
	wl_list_remove(&group->key.link);
1668
	wl_list_remove(&group->modifiers.link);
1669
	wl_list_remove(&group->destroy.link);
1670
	wlr_keyboard_group_destroy(group->wlr_group);
1671
	free(group);
1672
}
1673
1674
Monitor *
1675
dirtomon(enum wlr_direction dir)
1676
{
1677
	struct wlr_output *next;
1678
	if (!wlr_output_layout_get(output_layout, selmon->wlr_output))
1679
		return selmon;
1680
	if ((next = wlr_output_layout_adjacent_output(output_layout,
1681
			dir, selmon->wlr_output, selmon->m.x, selmon->m.y)))
1682
		return next->data;
1683
	if ((next = wlr_output_layout_farthest_output(output_layout,
1684
			dir ^ (WLR_DIRECTION_LEFT|WLR_DIRECTION_RIGHT),
1685
			selmon->wlr_output, selmon->m.x, selmon->m.y)))
1686
		return next->data;
1687
	return selmon;
1688
}
1689
1690
void
1691
drawbar(Monitor *m)
1692
{
1693
    int x, w, tw = 0;
1694
    int boxs = m->drw->font->height / 9;
1695
    int boxw = m->drw->font->height / 6 + 2;
1696
    uint32_t i, occ = 0, urg = 0;
1697
    Client *c;
1698
    Buffer *buf;
1699
    
1700
    if (!m->scene_buffer->node.enabled)
1701
        return;
1702
    if (!(buf = bufmon(m)))
1703
        return;
1704
1705
    // Always clear the entire bar with background color first
1706
    drwl_setscheme(m->drw, colors[SchemeBg]); // or any scheme that uses col_bg
1707
    drwl_rect(m->drw, 0, 0, m->b.width, m->b.height, 1, 0);
1708
    
1709
    if (m == selmon) {
1710
        char stext_copy[sizeof(stext)];
1711
        memset(stext_copy, 0, sizeof(stext_copy));
1712
        strncpy(stext_copy, stext, sizeof(stext_copy) - 1);
1713
        char *segment = strtok(stext_copy, "|");
1714
        int x_pos;
1715
1716
        /* first calculate total width WITHOUT ansi codes */
1717
        tw = 0;
1718
        while (segment) {
1719
            tw += textw_no_ansi(m, segment);  // Use the new function here
1720
            segment = strtok(NULL, "|");
1721
        }
1722
        x_pos = m->b.width - tw;
1723
1724
        /* draw each segment with color reset */
1725
        memset(stext_copy, 0, sizeof(stext_copy));
1726
        strncpy(stext_copy, stext, sizeof(stext_copy) - 1);
1727
        segment = strtok(stext_copy, "|");
1728
        while (segment) {
1729
            draw_ansi_segment(m, segment, &x_pos, m->b.height, m->lrpad);
1730
            segment = strtok(NULL, "|");
1731
        }
1732
    }
1733
1734
    wl_list_for_each(c, &clients, link) {
1735
        if (c->mon != m)
1736
            continue;
1737
        occ |= c->tags;
1738
        if (c->isurgent)
1739
            urg |= c->tags;
1740
    }
1741
    x = 0;
1742
    c = focustop(m);
1743
    for (i = 0; i < LENGTH(tags); i++) {
1744
        const int selected = (m->tagset[m->seltags] & (1 << i)) != 0;
1745
        const int occupied = (occ & (1 << i)) != 0;
1746
        w = TEXTW(m, tags[i]);
1747
        if (selected) {
1748
            drwl_setscheme(m->drw, colors[SchemeSel]);
1749
        } else if (occupied) {
1750
            drwl_setscheme(m->drw, colors[SchemeOcc]);
1751
        } else {
1752
            drwl_setscheme(m->drw, colors[SchemeNorm]);
1753
        }
1754
        drwl_text(m->drw, x, 0, w, m->b.height, m->lrpad / 2, tags[i], urg & (1 << i));
1755
        if(selected){
1756
            const int ulh = 2; /* underline height (px) */
1757
            drwl_setscheme(m->drw, colors[SchemeUnder]);
1758
            drwl_rect(m->drw, x, m->b.height - ulh, w, ulh, 1, 0);
1759
        }
1760
		x += w;
1761
	}
1762
	w = TEXTW(m, m->ltsymbol);
1763
	drwl_setscheme(m->drw, colors[SchemeNorm]);
1764
	x = drwl_text(m->drw, x, 0, w, m->b.height, m->lrpad / 2, m->ltsymbol, 0);
1765
1766
	if ((w = m->b.width - tw - x) > m->b.height) {
1767
		if (c) {
1768
			drwl_setscheme(m->drw, colors[m == selmon ? SchemeSel : SchemeNorm]);
1769
			drwl_text(m->drw, x, 0, w, m->b.height, m->lrpad / 2, client_get_title(c), 0);
1770
		} else {
1771
			drwl_setscheme(m->drw, colors[SchemeNorm]);
1772
		}
1773
	}
1774
1775
	wlr_scene_buffer_set_dest_size(m->scene_buffer,
1776
		m->b.real_width, m->b.real_height);
1777
	wlr_scene_node_set_position(&m->scene_buffer->node, m->m.x,
1778
		m->m.y + (topbar ? 0 : m->m.height - m->b.real_height));
1779
	wlr_scene_buffer_set_buffer(m->scene_buffer, &buf->base);
1780
	wlr_buffer_unlock(&buf->base);
1781
}
1782
1783
void
1784
drawbars(void)
1785
{
1786
	Monitor *m = NULL;
1787
1788
	wl_list_for_each(m, &mons, link)
1789
		drawbar(m);
1790
}
1791
1792
void
1793
focusclient(Client *c, int lift)
1794
{
1795
	struct wlr_surface *old = seat->keyboard_state.focused_surface;
1796
	int unused_lx, unused_ly, old_client_type;
1797
	Client *old_c = NULL;
1798
	LayerSurface *old_l = NULL;
1799
1800
	if (locked)
1801
		return;
1802
1803
	/* Raise client in stacking order if requested */
1804
	if (c && lift)
1805
		wlr_scene_node_raise_to_top(&c->scene->node);
1806
1807
	if (c && client_surface(c) == old)
1808
		return;
1809
1810
	if ((old_client_type = toplevel_from_wlr_surface(old, &old_c, &old_l)) == XDGShell) {
1811
		struct wlr_xdg_popup *popup, *tmp;
1812
		wl_list_for_each_safe(popup, tmp, &old_c->surface.xdg->popups, link)
1813
			wlr_xdg_popup_destroy(popup);
1814
	}
1815
1816
	/* Put the new client atop the focus stack and select its monitor */
1817
	if (c && !client_is_unmanaged(c)) {
1818
		wl_list_remove(&c->flink);
1819
		wl_list_insert(&fstack, &c->flink);
1820
		selmon = c->mon;
1821
		c->isurgent = 0;
1822
1823
		/* Don't change border color if there is an exclusive focus or we are
1824
		 * handling a drag operation */
1825
		if (!exclusive_focus && !seat->drag)
1826
			client_set_border_color(c, (float[])COLOR(colors[SchemeSel][ColBorder]));
1827
	}
1828
1829
	/* Deactivate old client if focus is changing */
1830
	if (old && (!c || client_surface(c) != old)) {
1831
		/* If an overlay is focused, don't focus or activate the client,
1832
		 * but only update its position in fstack to render its border with its color
1833
		 * and focus it after the overlay is closed. */
1834
		if (old_client_type == LayerShell && wlr_scene_node_coords(
1835
					&old_l->scene->node, &unused_lx, &unused_ly)
1836
				&& old_l->layer_surface->current.layer >= ZWLR_LAYER_SHELL_V1_LAYER_TOP) {
1837
			return;
1838
		} else if (old_c && old_c == exclusive_focus && client_wants_focus(old_c)) {
1839
			return;
1840
		/* Don't deactivate old client if the new one wants focus, as this causes issues with winecfg
1841
		 * and probably other clients */
1842
		} else if (old_c && !client_is_unmanaged(old_c) && (!c || !client_wants_focus(c))) {
1843
			client_set_border_color(old_c, (float[])COLOR(colors[SchemeNorm][ColBorder]));
1844
			client_activate_surface(old, 0);
1845
		}
1846
	}
1847
	drawbars();
1848
1849
	if (!c) {
1850
		/* With no client, all we have left is to clear focus */
1851
		wlr_seat_keyboard_notify_clear_focus(seat);
1852
		return;
1853
	}
1854
1855
	/* Change cursor surface */
1856
	motionnotify(0, NULL, 0, 0, 0, 0);
1857
1858
	/* Have a client, so focus its top-level wlr_surface */
1859
	client_notify_enter(client_surface(c), wlr_seat_get_keyboard(seat));
1860
1861
	/* Activate the new client */
1862
	client_activate_surface(client_surface(c), 1);
1863
}
1864
1865
void
1866
focusmon(const Arg *arg)
1867
{
1868
	int i = 0, nmons = wl_list_length(&mons);
1869
	if (nmons) {
1870
		do /* don't switch to disabled mons */
1871
			selmon = dirtomon(arg->i);
1872
		while (!selmon->wlr_output->enabled && i++ < nmons);
1873
	}
1874
	focusclient(focustop(selmon), 1);
1875
}
1876
1877
void
1878
focusstack(const Arg *arg)
1879
{
1880
	/* Focus the next or previous client (in tiling order) on selmon */
1881
	Client *c, *sel = focustop(selmon);
1882
	if (!sel || (sel->isfullscreen && !client_has_children(sel)))
1883
		return;
1884
	if (arg->i > 0) {
1885
		wl_list_for_each(c, &sel->link, link) {
1886
			if (&c->link == &clients)
1887
				continue; /* wrap past the sentinel node */
1888
			if (VISIBLEON(c, selmon))
1889
				break; /* found it */
1890
		}
1891
	} else {
1892
		wl_list_for_each_reverse(c, &sel->link, link) {
1893
			if (&c->link == &clients)
1894
				continue; /* wrap past the sentinel node */
1895
			if (VISIBLEON(c, selmon))
1896
				break; /* found it */
1897
		}
1898
	}
1899
	/* If only one client is visible on selmon, then c == sel */
1900
	focusclient(c, 1);
1901
}
1902
1903
/* We probably should change the name of this: it sounds like it
1904
 * will focus the topmost client of this mon, when actually will
1905
 * only return that client */
1906
Client *
1907
focustop(Monitor *m)
1908
{
1909
	Client *c;
1910
	wl_list_for_each(c, &fstack, flink) {
1911
		if (VISIBLEON(c, m))
1912
			return c;
1913
	}
1914
	return NULL;
1915
}
1916
1917
void
1918
fullscreennotify(struct wl_listener *listener, void *data)
1919
{
1920
	Client *c = wl_container_of(listener, c, fullscreen);
1921
	setfullscreen(c, client_wants_fullscreen(c));
1922
}
1923
1924
void
1925
gpureset(struct wl_listener *listener, void *data)
1926
{
1927
	struct wlr_renderer *old_drw = drw;
1928
	struct wlr_allocator *old_alloc = alloc;
1929
	struct Monitor *m;
1930
	if (!(drw = wlr_renderer_autocreate(backend)))
1931
		die("couldn't recreate renderer");
1932
1933
	if (!(alloc = wlr_allocator_autocreate(backend, drw)))
1934
		die("couldn't recreate allocator");
1935
1936
	wl_list_remove(&gpu_reset.link);
1937
	wl_signal_add(&drw->events.lost, &gpu_reset);
1938
1939
	wlr_compositor_set_renderer(compositor, drw);
1940
1941
	wl_list_for_each(m, &mons, link) {
1942
		wlr_output_init_render(m->wlr_output, alloc, drw);
1943
	}
1944
1945
	wlr_allocator_destroy(old_alloc);
1946
	wlr_renderer_destroy(old_drw);
1947
}
1948
1949
void
1950
handlesig(int signo)
1951
{
1952
	if (signo == SIGCHLD)
1953
		while (waitpid(-1, NULL, WNOHANG) > 0);
1954
	else if (signo == SIGINT || signo == SIGTERM)
1955
		quit(NULL);
1956
}
1957
1958
void
1959
incnmaster(const Arg *arg)
1960
{
1961
	if (!arg || !selmon)
1962
		return;
1963
	selmon->nmaster = MAX(selmon->nmaster + arg->i, 0);
1964
	arrange(selmon);
1965
}
1966
1967
void
1968
inputdevice(struct wl_listener *listener, void *data)
1969
{
1970
	/* This event is raised by the backend when a new input device becomes
1971
	 * available. */
1972
	struct wlr_input_device *device = data;
1973
	uint32_t caps;
1974
1975
	switch (device->type) {
1976
	case WLR_INPUT_DEVICE_KEYBOARD:
1977
		createkeyboard(wlr_keyboard_from_input_device(device));
1978
		break;
1979
	case WLR_INPUT_DEVICE_POINTER:
1980
		createpointer(wlr_pointer_from_input_device(device));
1981
		break;
1982
	default:
1983
		/* TODO handle other input device types */
1984
		break;
1985
	}
1986
1987
	/* We need to let the wlr_seat know what our capabilities are, which is
1988
	 * communiciated to the client. In dwl we always have a cursor, even if
1989
	 * there are no pointer devices, so we always include that capability. */
1990
	/* TODO do we actually require a cursor? */
1991
	caps = WL_SEAT_CAPABILITY_POINTER;
1992
	if (!wl_list_empty(&kb_group->wlr_group->devices))
1993
		caps |= WL_SEAT_CAPABILITY_KEYBOARD;
1994
	wlr_seat_set_capabilities(seat, caps);
1995
}
1996
1997
int
1998
keybinding(uint32_t mods, xkb_keysym_t sym)
1999
{
2000
	/*
2001
	 * Here we handle compositor keybindings. This is when the compositor is
2002
	 * processing keys, rather than passing them on to the client for its own
2003
	 * processing.
2004
	 */
2005
	const Key *k;
2006
	for (k = keys; k < END(keys); k++) {
2007
		if (CLEANMASK(mods) == CLEANMASK(k->mod)
2008
				&& sym == k->keysym && k->func) {
2009
			k->func(&k->arg);
2010
			return 1;
2011
		}
2012
	}
2013
	return 0;
2014
}
2015
2016
void
2017
keypress(struct wl_listener *listener, void *data)
2018
{
2019
	int i;
2020
	/* This event is raised when a key is pressed or released. */
2021
	KeyboardGroup *group = wl_container_of(listener, group, key);
2022
	struct wlr_keyboard_key_event *event = data;
2023
2024
	/* Translate libinput keycode -> xkbcommon */
2025
	uint32_t keycode = event->keycode + 8;
2026
	/* Get a list of keysyms based on the keymap for this keyboard */
2027
	const xkb_keysym_t *syms;
2028
	int nsyms = xkb_state_key_get_syms(
2029
			group->wlr_group->keyboard.xkb_state, keycode, &syms);
2030
2031
	int handled = 0;
2032
	uint32_t mods = wlr_keyboard_get_modifiers(&group->wlr_group->keyboard);
2033
2034
	wlr_idle_notifier_v1_notify_activity(idle_notifier, seat);
2035
2036
	/* On _press_ if there is no active screen locker,
2037
	 * attempt to process a compositor keybinding. */
2038
	if (!locked && event->state == WL_KEYBOARD_KEY_STATE_PRESSED) {
2039
		for (i = 0; i < nsyms; i++)
2040
			handled = keybinding(mods, syms[i]) || handled;
2041
	}
2042
2043
	if (handled && group->wlr_group->keyboard.repeat_info.delay > 0) {
2044
		group->mods = mods;
2045
		group->keysyms = syms;
2046
		group->nsyms = nsyms;
2047
		wl_event_source_timer_update(group->key_repeat_source,
2048
				group->wlr_group->keyboard.repeat_info.delay);
2049
	} else {
2050
		group->nsyms = 0;
2051
		wl_event_source_timer_update(group->key_repeat_source, 0);
2052
	}
2053
2054
	if (handled)
2055
		return;
2056
2057
	wlr_seat_set_keyboard(seat, &group->wlr_group->keyboard);
2058
	/* Pass unhandled keycodes along to the client. */
2059
	wlr_seat_keyboard_notify_key(seat, event->time_msec,
2060
			event->keycode, event->state);
2061
}
2062
2063
void
2064
keypressmod(struct wl_listener *listener, void *data)
2065
{
2066
	/* This event is raised when a modifier key, such as shift or alt, is
2067
	 * pressed. We simply communicate this to the client. */
2068
	KeyboardGroup *group = wl_container_of(listener, group, modifiers);
2069
2070
	wlr_seat_set_keyboard(seat, &group->wlr_group->keyboard);
2071
	/* Send modifiers to the client. */
2072
	wlr_seat_keyboard_notify_modifiers(seat,
2073
			&group->wlr_group->keyboard.modifiers);
2074
}
2075
2076
int
2077
keyrepeat(void *data)
2078
{
2079
	KeyboardGroup *group = data;
2080
	int i;
2081
	if (!group->nsyms || group->wlr_group->keyboard.repeat_info.rate <= 0)
2082
		return 0;
2083
2084
	wl_event_source_timer_update(group->key_repeat_source,
2085
			1000 / group->wlr_group->keyboard.repeat_info.rate);
2086
2087
	for (i = 0; i < group->nsyms; i++)
2088
		keybinding(group->mods, group->keysyms[i]);
2089
2090
	return 0;
2091
}
2092
2093
void
2094
killclient(const Arg *arg)
2095
{
2096
	Client *sel = focustop(selmon);
2097
	if (sel)
2098
		client_send_close(sel);
2099
}
2100
2101
void
2102
locksession(struct wl_listener *listener, void *data)
2103
{
2104
	struct wlr_session_lock_v1 *session_lock = data;
2105
	SessionLock *lock;
2106
	wlr_scene_node_set_enabled(&locked_bg->node, 1);
2107
	if (cur_lock) {
2108
		wlr_session_lock_v1_destroy(session_lock);
2109
		return;
2110
	}
2111
	lock = session_lock->data = ecalloc(1, sizeof(*lock));
2112
	focusclient(NULL, 0);
2113
2114
	lock->scene = wlr_scene_tree_create(layers[LyrBlock]);
2115
	cur_lock = lock->lock = session_lock;
2116
	locked = 1;
2117
2118
	LISTEN(&session_lock->events.new_surface, &lock->new_surface, createlocksurface);
2119
	LISTEN(&session_lock->events.destroy, &lock->destroy, destroysessionlock);
2120
	LISTEN(&session_lock->events.unlock, &lock->unlock, unlocksession);
2121
2122
	wlr_session_lock_v1_send_locked(session_lock);
2123
}
2124
2125
static Client *
2126
nexttagged(Client *c) {
2127
	Client *walked;
2128
	wl_list_for_each(walked, &clients, link) {
2129
		if (walked->isfloating || !VISIBLEON(walked, c->mon))
2130
			continue;
2131
		return walked;
2132
	}
2133
	return NULL;
2134
}
2135
2136
static void
2137
attachaside(Client *c) {
2138
	Client *at = nexttagged(c);
2139
	if (!at) {
2140
		/* No tiled clients, insert at head */
2141
		wl_list_insert(&clients, &c->link);
2142
		return;
2143
	}
2144
	/* Insert after the first tiled client */
2145
	wl_list_insert(&at->link, &c->link);
2146
}
2147
2148
void
2149
mapnotify(struct wl_listener *listener, void *data)
2150
{
2151
	/* Called when the surface is mapped, or ready to display on-screen. */
2152
	Client *p = NULL;
2153
	Client *w, *c = wl_container_of(listener, c, map);
2154
	Monitor *m;
2155
	int i;
2156
2157
	/* Create scene tree for this client and its border */
2158
	c->scene = client_surface(c)->data = wlr_scene_tree_create(layers[LyrTile]);
2159
	/* Enabled later by a call to arrange() */
2160
	wlr_scene_node_set_enabled(&c->scene->node, client_is_unmanaged(c));
2161
	c->scene_surface = c->type == XDGShell
2162
			? wlr_scene_xdg_surface_create(c->scene, c->surface.xdg)
2163
			: wlr_scene_subsurface_tree_create(c->scene, client_surface(c));
2164
	c->scene->node.data = c->scene_surface->node.data = c;
2165
2166
	client_get_geometry(c, &c->geom);
2167
2168
	/* Handle unmanaged clients first so we can return prior create borders */
2169
	if (client_is_unmanaged(c)) {
2170
		/* Unmanaged clients always are floating */
2171
		wlr_scene_node_reparent(&c->scene->node, layers[LyrFloat]);
2172
		wlr_scene_node_set_position(&c->scene->node, c->geom.x, c->geom.y);
2173
		client_set_size(c, c->geom.width, c->geom.height);
2174
		if (client_wants_focus(c)) {
2175
			focusclient(c, 1);
2176
			exclusive_focus = c;
2177
		}
2178
		goto unset_fullscreen;
2179
	}
2180
2181
	for (i = 0; i < 4; i++) {
2182
		c->border[i] = wlr_scene_rect_create(c->scene, 0, 0,
2183
			(float[])COLOR(colors[c->isurgent ? SchemeUrg : SchemeNorm][ColBorder]));
2184
		c->border[i]->node.data = c;
2185
	}
2186
2187
	/* Initialize client geometry with room for border */
2188
	client_set_tiled(c, WLR_EDGE_TOP | WLR_EDGE_BOTTOM | WLR_EDGE_LEFT | WLR_EDGE_RIGHT);
2189
	c->geom.width += 2 * c->bw;
2190
	c->geom.height += 2 * c->bw;
2191
2192
	/* Insert this client into client lists. */
2193
	// wl_list_insert(&clients, &c->link);
2194
    if (clients.prev)
2195
		// tile at the bottom
2196
		wl_list_insert(clients.prev, &c->link);
2197
	else
2198
		wl_list_insert(&clients, &c->link);
2199
	wl_list_insert(&fstack, &c->flink);
2200
2201
	/* Set initial monitor, tags, floating status, and focus:
2202
	 * we always consider floating, clients that have parent and thus
2203
	 * we set the same tags and monitor as its parent.
2204
	 * If there is no parent, apply rules */
2205
	if ((p = client_get_parent(c))) {
2206
		c->isfloating = 1;
2207
		setmon(c, p->mon, p->tags);
2208
	} else {
2209
		applyrules(c);
2210
	}
2211
	drawbars();
2212
2213
unset_fullscreen:
2214
	m = c->mon ? c->mon : xytomon(c->geom.x, c->geom.y);
2215
	wl_list_for_each(w, &clients, link) {
2216
		if (w != c && w != p && w->isfullscreen && m == w->mon && (w->tags & c->tags))
2217
			setfullscreen(w, 0);
2218
	}
2219
}
2220
2221
void
2222
maximizenotify(struct wl_listener *listener, void *data)
2223
{
2224
	/* This event is raised when a client would like to maximize itself,
2225
	 * typically because the user clicked on the maximize button on
2226
	 * client-side decorations. dwl doesn't support maximization, but
2227
	 * to conform to xdg-shell protocol we still must send a configure.
2228
	 * Since xdg-shell protocol v5 we should ignore request of unsupported
2229
	 * capabilities, just schedule a empty configure when the client uses <5
2230
	 * protocol version
2231
	 * wlr_xdg_surface_schedule_configure() is used to send an empty reply. */
2232
	Client *c = wl_container_of(listener, c, maximize);
2233
	if (c->surface.xdg->initialized
2234
			&& wl_resource_get_version(c->surface.xdg->toplevel->resource)
2235
					< XDG_TOPLEVEL_WM_CAPABILITIES_SINCE_VERSION)
2236
		wlr_xdg_surface_schedule_configure(c->surface.xdg);
2237
}
2238
2239
void
2240
monocle(Monitor *m)
2241
{
2242
	Client *c;
2243
	int n = 0;
2244
2245
	wl_list_for_each(c, &clients, link) {
2246
		if (!VISIBLEON(c, m) || c->isfloating || c->isfullscreen)
2247
			continue;
2248
		resize(c, m->w, 0);
2249
		n++;
2250
	}
2251
	if (n)
2252
		snprintf(m->ltsymbol, LENGTH(m->ltsymbol), "[%d]", n);
2253
	if ((c = focustop(m)))
2254
		wlr_scene_node_raise_to_top(&c->scene->node);
2255
}
2256
2257
void
2258
motionabsolute(struct wl_listener *listener, void *data)
2259
{
2260
	/* This event is forwarded by the cursor when a pointer emits an _absolute_
2261
	 * motion event, from 0..1 on each axis. This happens, for example, when
2262
	 * wlroots is running under a Wayland window rather than KMS+DRM, and you
2263
	 * move the mouse over the window. You could enter the window from any edge,
2264
	 * so we have to warp the mouse there. Also, some hardware emits these events. */
2265
	struct wlr_pointer_motion_absolute_event *event = data;
2266
	double lx, ly, dx, dy;
2267
2268
	if (!event->time_msec) /* this is 0 with virtual pointers */
2269
		wlr_cursor_warp_absolute(cursor, &event->pointer->base, event->x, event->y);
2270
2271
	wlr_cursor_absolute_to_layout_coords(cursor, &event->pointer->base, event->x, event->y, &lx, &ly);
2272
	dx = lx - cursor->x;
2273
	dy = ly - cursor->y;
2274
	motionnotify(event->time_msec, &event->pointer->base, dx, dy, dx, dy);
2275
}
2276
2277
void
2278
motionnotify(uint32_t time, struct wlr_input_device *device, double dx, double dy,
2279
		double dx_unaccel, double dy_unaccel)
2280
{
2281
	double sx = 0, sy = 0, sx_confined, sy_confined;
2282
	Client *c = NULL, *w = NULL;
2283
	LayerSurface *l = NULL;
2284
	struct wlr_surface *surface = NULL;
2285
	struct wlr_pointer_constraint_v1 *constraint;
2286
2287
	/* Find the client under the pointer and send the event along. */
2288
	xytonode(cursor->x, cursor->y, &surface, &c, NULL, &sx, &sy);
2289
2290
	if (cursor_mode == CurPressed && !seat->drag
2291
			&& surface != seat->pointer_state.focused_surface
2292
			&& toplevel_from_wlr_surface(seat->pointer_state.focused_surface, &w, &l) >= 0) {
2293
		c = w;
2294
		surface = seat->pointer_state.focused_surface;
2295
		sx = cursor->x - (l ? l->scene->node.x : w->geom.x);
2296
		sy = cursor->y - (l ? l->scene->node.y : w->geom.y);
2297
	}
2298
2299
	/* time is 0 in internal calls meant to restore pointer focus. */
2300
	if (time) {
2301
		wlr_relative_pointer_manager_v1_send_relative_motion(
2302
				relative_pointer_mgr, seat, (uint64_t)time * 1000,
2303
				dx, dy, dx_unaccel, dy_unaccel);
2304
2305
		wl_list_for_each(constraint, &pointer_constraints->constraints, link)
2306
			cursorconstrain(constraint);
2307
2308
		if (active_constraint && cursor_mode != CurResize && cursor_mode != CurMove) {
2309
			toplevel_from_wlr_surface(active_constraint->surface, &c, NULL);
2310
			if (c && active_constraint->surface == seat->pointer_state.focused_surface) {
2311
				sx = cursor->x - c->geom.x - c->bw;
2312
				sy = cursor->y - c->geom.y - c->bw;
2313
				if (wlr_region_confine(&active_constraint->region, sx, sy,
2314
						sx + dx, sy + dy, &sx_confined, &sy_confined)) {
2315
					dx = sx_confined - sx;
2316
					dy = sy_confined - sy;
2317
				}
2318
2319
				if (active_constraint->type == WLR_POINTER_CONSTRAINT_V1_LOCKED)
2320
					return;
2321
			}
2322
		}
2323
2324
		wlr_cursor_move(cursor, device, dx, dy);
2325
		wlr_idle_notifier_v1_notify_activity(idle_notifier, seat);
2326
2327
		/* Update selmon (even while dragging a window) */
2328
		if (sloppyfocus)
2329
			selmon = xytomon(cursor->x, cursor->y);
2330
	}
2331
2332
	/* Update drag icon's position */
2333
	wlr_scene_node_set_position(&drag_icon->node, (int)round(cursor->x), (int)round(cursor->y));
2334
2335
	/* If we are currently grabbing the mouse, handle and return */
2336
	if (cursor_mode == CurMove) {
2337
		/* Move the grabbed client to the new position. */
2338
		resize(grabc, (struct wlr_box){.x = (int)round(cursor->x) - grabcx, .y = (int)round(cursor->y) - grabcy,
2339
			.width = grabc->geom.width, .height = grabc->geom.height}, 1);
2340
		return;
2341
	} else if (cursor_mode == CurResize) {
2342
		resize(grabc, (struct wlr_box){.x = grabc->geom.x, .y = grabc->geom.y,
2343
			.width = (int)round(cursor->x) - grabc->geom.x, .height = (int)round(cursor->y) - grabc->geom.y}, 1);
2344
		return;
2345
	}
2346
2347
	/* If there's no client surface under the cursor, set the cursor image to a
2348
	 * default. This is what makes the cursor image appear when you move it
2349
	 * off of a client or over its border. */
2350
	if (!surface && !seat->drag)
2351
		wlr_cursor_set_xcursor(cursor, cursor_mgr, "default");
2352
2353
	pointerfocus(c, surface, sx, sy, time);
2354
}
2355
2356
void
2357
motionrelative(struct wl_listener *listener, void *data)
2358
{
2359
	/* This event is forwarded by the cursor when a pointer emits a _relative_
2360
	 * pointer motion event (i.e. a delta) */
2361
	struct wlr_pointer_motion_event *event = data;
2362
	/* The cursor doesn't move unless we tell it to. The cursor automatically
2363
	 * handles constraining the motion to the output layout, as well as any
2364
	 * special configuration applied for the specific input device which
2365
	 * generated the event. You can pass NULL for the device if you want to move
2366
	 * the cursor around without any input. */
2367
	motionnotify(event->time_msec, &event->pointer->base, event->delta_x, event->delta_y,
2368
			event->unaccel_dx, event->unaccel_dy);
2369
}
2370
2371
void
2372
moveresize(const Arg *arg)
2373
{
2374
	if (cursor_mode != CurNormal && cursor_mode != CurPressed)
2375
		return;
2376
	xytonode(cursor->x, cursor->y, NULL, &grabc, NULL, NULL, NULL);
2377
	if (!grabc || client_is_unmanaged(grabc) || grabc->isfullscreen)
2378
		return;
2379
2380
	/* Float the window and tell motionnotify to grab it */
2381
	setfloating(grabc, 1);
2382
	switch (cursor_mode = arg->ui) {
2383
	case CurMove:
2384
		grabcx = (int)round(cursor->x) - grabc->geom.x;
2385
		grabcy = (int)round(cursor->y) - grabc->geom.y;
2386
		wlr_cursor_set_xcursor(cursor, cursor_mgr, "all-scroll");
2387
		break;
2388
	case CurResize:
2389
		/* Doesn't work for X11 output - the next absolute motion event
2390
		 * returns the cursor to where it started */
2391
		wlr_cursor_warp_closest(cursor, NULL,
2392
				grabc->geom.x + grabc->geom.width,
2393
				grabc->geom.y + grabc->geom.height);
2394
		wlr_cursor_set_xcursor(cursor, cursor_mgr, "se-resize");
2395
		break;
2396
	}
2397
}
2398
2399
void
2400
outputmgrapply(struct wl_listener *listener, void *data)
2401
{
2402
	struct wlr_output_configuration_v1 *config = data;
2403
	outputmgrapplyortest(config, 0);
2404
}
2405
2406
void
2407
outputmgrapplyortest(struct wlr_output_configuration_v1 *config, int test)
2408
{
2409
	/*
2410
	 * Called when a client such as wlr-randr requests a change in output
2411
	 * configuration. This is only one way that the layout can be changed,
2412
	 * so any Monitor information should be updated by updatemons() after an
2413
	 * output_layout.change event, not here.
2414
	 */
2415
	struct wlr_output_configuration_head_v1 *config_head;
2416
	int ok = 1;
2417
2418
	wl_list_for_each(config_head, &config->heads, link) {
2419
		struct wlr_output *wlr_output = config_head->state.output;
2420
		Monitor *m = wlr_output->data;
2421
		struct wlr_output_state state;
2422
2423
		/* Ensure displays previously disabled by wlr-output-power-management-v1
2424
		 * are properly handled*/
2425
		m->asleep = 0;
2426
2427
		wlr_output_state_init(&state);
2428
		wlr_output_state_set_enabled(&state, config_head->state.enabled);
2429
		if (!config_head->state.enabled)
2430
			goto apply_or_test;
2431
2432
		if (config_head->state.mode)
2433
			wlr_output_state_set_mode(&state, config_head->state.mode);
2434
		else
2435
			wlr_output_state_set_custom_mode(&state,
2436
					config_head->state.custom_mode.width,
2437
					config_head->state.custom_mode.height,
2438
					config_head->state.custom_mode.refresh);
2439
2440
		wlr_output_state_set_transform(&state, config_head->state.transform);
2441
		wlr_output_state_set_scale(&state, config_head->state.scale);
2442
		wlr_output_state_set_adaptive_sync_enabled(&state,
2443
				config_head->state.adaptive_sync_enabled);
2444
2445
apply_or_test:
2446
		ok &= test ? wlr_output_test_state(wlr_output, &state)
2447
				: wlr_output_commit_state(wlr_output, &state);
2448
2449
		/* Don't move monitors if position wouldn't change. This avoids
2450
		 * wlroots marking the output as manually configured.
2451
		 * wlr_output_layout_add does not like disabled outputs */
2452
		if (!test && wlr_output->enabled && (m->m.x != config_head->state.x || m->m.y != config_head->state.y))
2453
			wlr_output_layout_add(output_layout, wlr_output,
2454
					config_head->state.x, config_head->state.y);
2455
2456
		wlr_output_state_finish(&state);
2457
	}
2458
2459
	if (ok)
2460
		wlr_output_configuration_v1_send_succeeded(config);
2461
	else
2462
		wlr_output_configuration_v1_send_failed(config);
2463
	wlr_output_configuration_v1_destroy(config);
2464
2465
	/* https://codeberg.org/dwl/dwl/issues/577 */
2466
	updatemons(NULL, NULL);
2467
}
2468
2469
void
2470
outputmgrtest(struct wl_listener *listener, void *data)
2471
{
2472
	struct wlr_output_configuration_v1 *config = data;
2473
	outputmgrapplyortest(config, 1);
2474
}
2475
2476
void
2477
pointerfocus(Client *c, struct wlr_surface *surface, double sx, double sy,
2478
		uint32_t time)
2479
{
2480
	struct timespec now;
2481
2482
	if (surface != seat->pointer_state.focused_surface &&
2483
			sloppyfocus && time && c && !client_is_unmanaged(c))
2484
		focusclient(c, 0);
2485
2486
	/* If surface is NULL, clear pointer focus */
2487
	if (!surface) {
2488
		wlr_seat_pointer_notify_clear_focus(seat);
2489
		return;
2490
	}
2491
2492
	if (!time) {
2493
		clock_gettime(CLOCK_MONOTONIC, &now);
2494
		time = now.tv_sec * 1000 + now.tv_nsec / 1000000;
2495
	}
2496
2497
	/* Let the client know that the mouse cursor has entered one
2498
	 * of its surfaces, and make keyboard focus follow if desired.
2499
	 * wlroots makes this a no-op if surface is already focused */
2500
	wlr_seat_pointer_notify_enter(seat, surface, sx, sy);
2501
	wlr_seat_pointer_notify_motion(seat, time, sx, sy);
2502
}
2503
2504
void
2505
powermgrsetmode(struct wl_listener *listener, void *data)
2506
{
2507
	struct wlr_output_power_v1_set_mode_event *event = data;
2508
	struct wlr_output_state state = {0};
2509
	Monitor *m = event->output->data;
2510
2511
	if (!m)
2512
		return;
2513
2514
	m->gamma_lut_changed = 1; /* Reapply gamma LUT when re-enabling the ouput */
2515
	wlr_output_state_set_enabled(&state, event->mode);
2516
	wlr_output_commit_state(m->wlr_output, &state);
2517
2518
	m->asleep = !event->mode;
2519
	updatemons(NULL, NULL);
2520
}
2521
2522
void
2523
quit(const Arg *arg)
2524
{
2525
	wl_display_terminate(dpy);
2526
}
2527
2528
void
2529
rendermon(struct wl_listener *listener, void *data)
2530
{
2531
	/* This function is called every time an output is ready to display a frame,
2532
	 * generally at the output's refresh rate (e.g. 60Hz). */
2533
	Monitor *m = wl_container_of(listener, m, frame);
2534
	Client *c;
2535
	struct wlr_output_state pending = {0};
2536
	struct timespec now;
2537
2538
	/* Render if no XDG clients have an outstanding resize and are visible on
2539
	 * this monitor. */
2540
	wl_list_for_each(c, &clients, link) {
2541
		if (c->resize && !c->isfloating && client_is_rendered_on_mon(c, m) && !client_is_stopped(c))
2542
			goto skip;
2543
	}
2544
2545
	wlr_scene_output_commit(m->scene_output, NULL);
2546
2547
skip:
2548
	/* Let clients know a frame has been rendered */
2549
	clock_gettime(CLOCK_MONOTONIC, &now);
2550
	wlr_scene_output_send_frame_done(m->scene_output, &now);
2551
	wlr_output_state_finish(&pending);
2552
}
2553
2554
void
2555
requestdecorationmode(struct wl_listener *listener, void *data)
2556
{
2557
	Client *c = wl_container_of(listener, c, set_decoration_mode);
2558
	if (c->surface.xdg->initialized)
2559
		wlr_xdg_toplevel_decoration_v1_set_mode(c->decoration,
2560
				WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2561
}
2562
2563
void
2564
requeststartdrag(struct wl_listener *listener, void *data)
2565
{
2566
	struct wlr_seat_request_start_drag_event *event = data;
2567
2568
	if (wlr_seat_validate_pointer_grab_serial(seat, event->origin,
2569
			event->serial))
2570
		wlr_seat_start_pointer_drag(seat, event->drag, event->serial);
2571
	else
2572
		wlr_data_source_destroy(event->drag->source);
2573
}
2574
2575
void
2576
requestmonstate(struct wl_listener *listener, void *data)
2577
{
2578
	struct wlr_output_event_request_state *event = data;
2579
	wlr_output_commit_state(event->output, event->state);
2580
	updatemons(NULL, NULL);
2581
}
2582
2583
void
2584
resize(Client *c, struct wlr_box geo, int interact)
2585
{
2586
	struct wlr_box *bbox;
2587
	struct wlr_box clip;
2588
2589
	if (!c->mon || !client_surface(c)->mapped)
2590
		return;
2591
2592
	bbox = interact ? &sgeom : &c->mon->w;
2593
2594
	client_set_bounds(c, geo.width, geo.height);
2595
	c->geom = geo;
2596
	applybounds(c, bbox);
2597
2598
	/* Update scene-graph, including borders */
2599
	wlr_scene_node_set_position(&c->scene->node, c->geom.x, c->geom.y);
2600
	wlr_scene_node_set_position(&c->scene_surface->node, c->bw, c->bw);
2601
	wlr_scene_rect_set_size(c->border[0], c->geom.width, c->bw);
2602
	wlr_scene_rect_set_size(c->border[1], c->geom.width, c->bw);
2603
	wlr_scene_rect_set_size(c->border[2], c->bw, c->geom.height - 2 * c->bw);
2604
	wlr_scene_rect_set_size(c->border[3], c->bw, c->geom.height - 2 * c->bw);
2605
	wlr_scene_node_set_position(&c->border[1]->node, 0, c->geom.height - c->bw);
2606
	wlr_scene_node_set_position(&c->border[2]->node, 0, c->bw);
2607
	wlr_scene_node_set_position(&c->border[3]->node, c->geom.width - c->bw, c->bw);
2608
2609
	/* this is a no-op if size hasn't changed */
2610
	c->resize = client_set_size(c, c->geom.width - 2 * c->bw,
2611
			c->geom.height - 2 * c->bw);
2612
	client_get_clip(c, &clip);
2613
	wlr_scene_subsurface_tree_set_clip(&c->scene_surface->node, &clip);
2614
}
2615
2616
void
2617
run(char *startup_cmd)
2618
{
2619
	/* Add a Unix socket to the Wayland display. */
2620
	const char *socket = wl_display_add_socket_auto(dpy);
2621
	if (!socket)
2622
		die("startup: display_add_socket_auto");
2623
	setenv("WAYLAND_DISPLAY", socket, 1);
2624
2625
	/* Start the backend. This will enumerate outputs and inputs, become the DRM
2626
	 * master, etc */
2627
	if (!wlr_backend_start(backend))
2628
		die("startup: backend_start");
2629
2630
	/* Now that the socket exists and the backend is started, run the startup command */
2631
	if (startup_cmd) {
2632
		if ((child_pid = fork()) < 0)
2633
			die("startup: fork:");
2634
		if (child_pid == 0) {
2635
			close(STDIN_FILENO);
2636
			setsid();
2637
			execl("/bin/sh", "/bin/sh", "-c", startup_cmd, NULL);
2638
			die("startup: execl:");
2639
		}
2640
	}
2641
2642
	/* Mark stdout as non-blocking to avoid the startup script
2643
	 * causing dwl to freeze when a user neither closes stdin
2644
	 * nor consumes standard input in his startup script */
2645
2646
	if (fd_set_nonblock(STDOUT_FILENO) < 0)
2647
		close(STDOUT_FILENO);
2648
2649
	drawbars();
2650
2651
	/* At this point the outputs are initialized, choose initial selmon based on
2652
	 * cursor position, and set default cursor image */
2653
	selmon = xytomon(cursor->x, cursor->y);
2654
2655
	/* TODO hack to get cursor to display in its initial location (100, 100)
2656
	 * instead of (0, 0) and then jumping. Still may not be fully
2657
	 * initialized, as the image/coordinates are not transformed for the
2658
	 * monitor when displayed here */
2659
	wlr_cursor_warp_closest(cursor, NULL, cursor->x, cursor->y);
2660
	wlr_cursor_set_xcursor(cursor, cursor_mgr, "default");
2661
2662
	/* Run the Wayland event loop. This does not return until you exit the
2663
	 * compositor. Starting the backend rigged up all of the necessary event
2664
	 * loop configuration to listen to libinput events, DRM events, generate
2665
	 * frame events at the refresh rate, and so on. */
2666
	wl_display_run(dpy);
2667
}
2668
2669
void
2670
setcursor(struct wl_listener *listener, void *data)
2671
{
2672
	/* This event is raised by the seat when a client provides a cursor image */
2673
	struct wlr_seat_pointer_request_set_cursor_event *event = data;
2674
	/* If we're "grabbing" the cursor, don't use the client's image, we will
2675
	 * restore it after "grabbing" sending a leave event, followed by a enter
2676
	 * event, which will result in the client requesting set the cursor surface */
2677
	if (cursor_mode != CurNormal && cursor_mode != CurPressed)
2678
		return;
2679
	/* This can be sent by any client, so we check to make sure this one
2680
	 * actually has pointer focus first. If so, we can tell the cursor to
2681
	 * use the provided surface as the cursor image. It will set the
2682
	 * hardware cursor on the output that it's currently on and continue to
2683
	 * do so as the cursor moves between outputs. */
2684
	if (event->seat_client == seat->pointer_state.focused_client)
2685
		wlr_cursor_set_surface(cursor, event->surface,
2686
				event->hotspot_x, event->hotspot_y);
2687
}
2688
2689
void
2690
setcursorshape(struct wl_listener *listener, void *data)
2691
{
2692
	struct wlr_cursor_shape_manager_v1_request_set_shape_event *event = data;
2693
	if (cursor_mode != CurNormal && cursor_mode != CurPressed)
2694
		return;
2695
	/* This can be sent by any client, so we check to make sure this one
2696
	 * actually has pointer focus first. If so, we can tell the cursor to
2697
	 * use the provided cursor shape. */
2698
	if (event->seat_client == seat->pointer_state.focused_client)
2699
		wlr_cursor_set_xcursor(cursor, cursor_mgr,
2700
				wlr_cursor_shape_v1_name(event->shape));
2701
}
2702
2703
void
2704
setfloating(Client *c, int floating)
2705
{
2706
	Client *p = client_get_parent(c);
2707
	c->isfloating = floating;
2708
	/* If in floating layout do not change the client's layer */
2709
	if (!c->mon || !client_surface(c)->mapped || !c->mon->lt[c->mon->sellt]->arrange)
2710
		return;
2711
	wlr_scene_node_reparent(&c->scene->node, layers[c->isfullscreen ||
2712
			(p && p->isfullscreen) ? LyrFS
2713
			: c->isfloating ? LyrFloat : LyrTile]);
2714
	arrange(c->mon);
2715
	drawbars();
2716
}
2717
2718
void
2719
setfullscreen(Client *c, int fullscreen)
2720
{
2721
	c->isfullscreen = fullscreen;
2722
	if (!c->mon || !client_surface(c)->mapped)
2723
		return;
2724
	c->bw = fullscreen ? 0 : borderpx;
2725
	client_set_fullscreen(c, fullscreen);
2726
	wlr_scene_node_reparent(&c->scene->node, layers[c->isfullscreen
2727
			? LyrFS : c->isfloating ? LyrFloat : LyrTile]);
2728
2729
	if (fullscreen) {
2730
		c->prev = c->geom;
2731
		resize(c, c->mon->m, 0);
2732
	} else {
2733
		/* restore previous size instead of arrange for floating windows since
2734
		 * client positions are set by the user and cannot be recalculated */
2735
		resize(c, c->prev, 0);
2736
	}
2737
	arrange(c->mon);
2738
	drawbars();
2739
}
2740
2741
void
2742
setlayout(const Arg *arg)
2743
{
2744
	if (!selmon)
2745
		return;
2746
	if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt])
2747
		selmon->sellt ^= 1;
2748
	if (arg && arg->v)
2749
		selmon->lt[selmon->sellt] = (Layout *)arg->v;
2750
	strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof(selmon->ltsymbol));
2751
	arrange(selmon);
2752
	drawbar(selmon);
2753
}
2754
2755
/* arg > 1.0 will set mfact absolutely */
2756
void
2757
setmfact(const Arg *arg)
2758
{
2759
	float f;
2760
2761
	if (!arg || !selmon || !selmon->lt[selmon->sellt]->arrange)
2762
		return;
2763
	f = arg->f < 1.0f ? arg->f + selmon->mfact : arg->f - 1.0f;
2764
	if (f < 0.1 || f > 0.9)
2765
		return;
2766
	selmon->mfact = f;
2767
	arrange(selmon);
2768
}
2769
2770
void
2771
setmon(Client *c, Monitor *m, uint32_t newtags)
2772
{
2773
	Monitor *oldmon = c->mon;
2774
2775
	if (oldmon == m)
2776
		return;
2777
	c->mon = m;
2778
	c->prev = c->geom;
2779
2780
	/* Scene graph sends surface leave/enter events on move and resize */
2781
	if (oldmon)
2782
		arrange(oldmon);
2783
	if (m) {
2784
		/* Make sure window actually overlaps with the monitor */
2785
		resize(c, c->geom, 0);
2786
		c->tags = newtags ? newtags : m->tagset[m->seltags]; /* assign tags of target monitor */
2787
		setfullscreen(c, c->isfullscreen); /* This will call arrange(c->mon) */
2788
		setfloating(c, c->isfloating);
2789
	}
2790
	focusclient(focustop(selmon), 1);
2791
}
2792
2793
void
2794
setpsel(struct wl_listener *listener, void *data)
2795
{
2796
	/* This event is raised by the seat when a client wants to set the selection,
2797
	 * usually when the user copies something. wlroots allows compositors to
2798
	 * ignore such requests if they so choose, but in dwl we always honor them
2799
	 */
2800
	struct wlr_seat_request_set_primary_selection_event *event = data;
2801
	wlr_seat_set_primary_selection(seat, event->source, event->serial);
2802
}
2803
2804
void
2805
setsel(struct wl_listener *listener, void *data)
2806
{
2807
	/* This event is raised by the seat when a client wants to set the selection,
2808
	 * usually when the user copies something. wlroots allows compositors to
2809
	 * ignore such requests if they so choose, but in dwl we always honor them
2810
	 */
2811
	struct wlr_seat_request_set_selection_event *event = data;
2812
	wlr_seat_set_selection(seat, event->source, event->serial);
2813
}
2814
2815
2816
void
2817
setup(void)
2818
{
2819
    int drm_fd, i, sig[] = {SIGCHLD, SIGINT, SIGTERM, SIGPIPE};
2820
    struct sigaction sa = {.sa_flags = SA_RESTART, .sa_handler = handlesig};
2821
    sigemptyset(&sa.sa_mask);
2822
2823
	for (i = 0; i < (int)LENGTH(sig); i++)
2824
		sigaction(sig[i], &sa, NULL);
2825
2826
2827
	wlr_log_init(log_level, NULL);
2828
2829
	/* The Wayland display is managed by libwayland. It handles accepting
2830
	 * clients from the Unix socket, manging Wayland globals, and so on. */
2831
	dpy = wl_display_create();
2832
	event_loop = wl_display_get_event_loop(dpy);
2833
2834
	/* The backend is a wlroots feature which abstracts the underlying input and
2835
	 * output hardware. The autocreate option will choose the most suitable
2836
	 * backend based on the current environment, such as opening an X11 window
2837
	 * if an X11 server is running. */
2838
	if (!(backend = wlr_backend_autocreate(event_loop, &session)))
2839
		die("couldn't create backend");
2840
2841
	/* Initialize the scene graph used to lay out windows */
2842
	scene = wlr_scene_create();
2843
	root_bg = wlr_scene_rect_create(&scene->tree, 0, 0, rootcolor);
2844
	for (i = 0; i < NUM_LAYERS; i++)
2845
		layers[i] = wlr_scene_tree_create(&scene->tree);
2846
	drag_icon = wlr_scene_tree_create(&scene->tree);
2847
	wlr_scene_node_place_below(&drag_icon->node, &layers[LyrBlock]->node);
2848
2849
	/* Autocreates a renderer, either Pixman, GLES2 or Vulkan for us. The user
2850
	 * can also specify a renderer using the WLR_RENDERER env var.
2851
	 * The renderer is responsible for defining the various pixel formats it
2852
	 * supports for shared memory, this configures that for clients. */
2853
	if (!(drw = wlr_renderer_autocreate(backend)))
2854
		die("couldn't create renderer");
2855
	wl_signal_add(&drw->events.lost, &gpu_reset);
2856
2857
	/* Create shm, drm and linux_dmabuf interfaces by ourselves.
2858
	 * The simplest way is to call:
2859
	 *      wlr_renderer_init_wl_display(drw);
2860
	 * but we need to create the linux_dmabuf interface manually to integrate it
2861
	 * with wlr_scene. */
2862
	wlr_renderer_init_wl_shm(drw, dpy);
2863
2864
	if (wlr_renderer_get_texture_formats(drw, WLR_BUFFER_CAP_DMABUF)) {
2865
		wlr_drm_create(dpy, drw);
2866
		wlr_scene_set_linux_dmabuf_v1(scene,
2867
				wlr_linux_dmabuf_v1_create_with_renderer(dpy, 5, drw));
2868
	}
2869
2870
	if ((drm_fd = wlr_renderer_get_drm_fd(drw)) >= 0 && drw->features.timeline
2871
			&& backend->features.timeline)
2872
		wlr_linux_drm_syncobj_manager_v1_create(dpy, 1, drm_fd);
2873
2874
	/* Autocreates an allocator for us.
2875
	 * The allocator is the bridge between the renderer and the backend. It
2876
	 * handles the buffer creation, allowing wlroots to render onto the
2877
	 * screen */
2878
	if (!(alloc = wlr_allocator_autocreate(backend, drw)))
2879
		die("couldn't create allocator");
2880
2881
	/* This creates some hands-off wlroots interfaces. The compositor is
2882
	 * necessary for clients to allocate surfaces and the data device manager
2883
	 * handles the clipboard. Each of these wlroots interfaces has room for you
2884
	 * to dig your fingers in and play with their behavior if you want. Note that
2885
	 * the clients cannot set the selection directly without compositor approval,
2886
	 * see the setsel() function. */
2887
	compositor = wlr_compositor_create(dpy, 6, drw);
2888
	wlr_subcompositor_create(dpy);
2889
	wlr_data_device_manager_create(dpy);
2890
	wlr_export_dmabuf_manager_v1_create(dpy);
2891
	wlr_screencopy_manager_v1_create(dpy);
2892
	wlr_data_control_manager_v1_create(dpy);
2893
	wlr_primary_selection_v1_device_manager_create(dpy);
2894
	wlr_viewporter_create(dpy);
2895
	wlr_single_pixel_buffer_manager_v1_create(dpy);
2896
	wlr_fractional_scale_manager_v1_create(dpy, 1);
2897
	wlr_presentation_create(dpy, backend, 2);
2898
	wlr_alpha_modifier_v1_create(dpy);
2899
2900
	/* Initializes the interface used to implement urgency hints */
2901
	activation = wlr_xdg_activation_v1_create(dpy);
2902
	wl_signal_add(&activation->events.request_activate, &request_activate);
2903
2904
	wlr_scene_set_gamma_control_manager_v1(scene, wlr_gamma_control_manager_v1_create(dpy));
2905
2906
	power_mgr = wlr_output_power_manager_v1_create(dpy);
2907
	wl_signal_add(&power_mgr->events.set_mode, &output_power_mgr_set_mode);
2908
2909
	/* Creates an output layout, which is a wlroots utility for working with an
2910
	 * arrangement of screens in a physical layout. */
2911
	output_layout = wlr_output_layout_create(dpy);
2912
	wl_signal_add(&output_layout->events.change, &layout_change);
2913
2914
    wlr_xdg_output_manager_v1_create(dpy, output_layout);
2915
2916
	/* Configure a listener to be notified when new outputs are available on the
2917
	 * backend. */
2918
	wl_list_init(&mons);
2919
	wl_signal_add(&backend->events.new_output, &new_output);
2920
2921
	/* Set up our client lists, the xdg-shell and the layer-shell. The xdg-shell is a
2922
	 * Wayland protocol which is used for application windows. For more
2923
	 * detail on shells, refer to the article:
2924
	 *
2925
	 * https://drewdevault.com/2018/07/29/Wayland-shells.html
2926
	 */
2927
	wl_list_init(&clients);
2928
	wl_list_init(&fstack);
2929
2930
	xdg_shell = wlr_xdg_shell_create(dpy, 6);
2931
	wl_signal_add(&xdg_shell->events.new_toplevel, &new_xdg_toplevel);
2932
	wl_signal_add(&xdg_shell->events.new_popup, &new_xdg_popup);
2933
2934
	layer_shell = wlr_layer_shell_v1_create(dpy, 3);
2935
	wl_signal_add(&layer_shell->events.new_surface, &new_layer_surface);
2936
2937
	idle_notifier = wlr_idle_notifier_v1_create(dpy);
2938
2939
	idle_inhibit_mgr = wlr_idle_inhibit_v1_create(dpy);
2940
	wl_signal_add(&idle_inhibit_mgr->events.new_inhibitor, &new_idle_inhibitor);
2941
2942
	session_lock_mgr = wlr_session_lock_manager_v1_create(dpy);
2943
	wl_signal_add(&session_lock_mgr->events.new_lock, &new_session_lock);
2944
	locked_bg = wlr_scene_rect_create(layers[LyrBlock], sgeom.width, sgeom.height,
2945
			(float [4]){0.1f, 0.1f, 0.1f, 1.0f});
2946
	wlr_scene_node_set_enabled(&locked_bg->node, 0);
2947
2948
	/* Use decoration protocols to negotiate server-side decorations */
2949
	wlr_server_decoration_manager_set_default_mode(
2950
			wlr_server_decoration_manager_create(dpy),
2951
			WLR_SERVER_DECORATION_MANAGER_MODE_SERVER);
2952
	xdg_decoration_mgr = wlr_xdg_decoration_manager_v1_create(dpy);
2953
	wl_signal_add(&xdg_decoration_mgr->events.new_toplevel_decoration, &new_xdg_decoration);
2954
2955
	pointer_constraints = wlr_pointer_constraints_v1_create(dpy);
2956
	wl_signal_add(&pointer_constraints->events.new_constraint, &new_pointer_constraint);
2957
2958
	relative_pointer_mgr = wlr_relative_pointer_manager_v1_create(dpy);
2959
2960
	/*
2961
	 * Creates a cursor, which is a wlroots utility for tracking the cursor
2962
	 * image shown on screen.
2963
	 */
2964
	cursor = wlr_cursor_create();
2965
	wlr_cursor_attach_output_layout(cursor, output_layout);
2966
2967
	/* Creates an xcursor manager, another wlroots utility which loads up
2968
	 * Xcursor themes to source cursor images from and makes sure that cursor
2969
	 * images are available at all scale factors on the screen (necessary for
2970
	 * HiDPI support). Scaled cursors will be loaded with each output. */
2971
	cursor_mgr = wlr_xcursor_manager_create(NULL, 24);
2972
	setenv("XCURSOR_SIZE", "24", 1);
2973
2974
	/*
2975
	 * wlr_cursor *only* displays an image on screen. It does not move around
2976
	 * when the pointer moves. However, we can attach input devices to it, and
2977
	 * it will generate aggregate events for all of them. In these events, we
2978
	 * can choose how we want to process them, forwarding them to clients and
2979
	 * moving the cursor around. More detail on this process is described in
2980
	 * https://drewdevault.com/2018/07/17/Input-handling-in-wlroots.html
2981
	 *
2982
	 * And more comments are sprinkled throughout the notify functions above.
2983
	 */
2984
	wl_signal_add(&cursor->events.motion, &cursor_motion);
2985
	wl_signal_add(&cursor->events.motion_absolute, &cursor_motion_absolute);
2986
	wl_signal_add(&cursor->events.button, &cursor_button);
2987
	wl_signal_add(&cursor->events.axis, &cursor_axis);
2988
	wl_signal_add(&cursor->events.frame, &cursor_frame);
2989
2990
	cursor_shape_mgr = wlr_cursor_shape_manager_v1_create(dpy, 1);
2991
	wl_signal_add(&cursor_shape_mgr->events.request_set_shape, &request_set_cursor_shape);
2992
2993
	/*
2994
	 * Configures a seat, which is a single "seat" at which a user sits and
2995
	 * operates the computer. This conceptually includes up to one keyboard,
2996
	 * pointer, touch, and drawing tablet device. We also rig up a listener to
2997
	 * let us know when new input devices are available on the backend.
2998
	 */
2999
	wl_signal_add(&backend->events.new_input, &new_input_device);
3000
	virtual_keyboard_mgr = wlr_virtual_keyboard_manager_v1_create(dpy);
3001
	wl_signal_add(&virtual_keyboard_mgr->events.new_virtual_keyboard,
3002
			&new_virtual_keyboard);
3003
	virtual_pointer_mgr = wlr_virtual_pointer_manager_v1_create(dpy);
3004
    wl_signal_add(&virtual_pointer_mgr->events.new_virtual_pointer,
3005
            &new_virtual_pointer);
3006
3007
	seat = wlr_seat_create(dpy, "seat0");
3008
	wl_signal_add(&seat->events.request_set_cursor, &request_cursor);
3009
	wl_signal_add(&seat->events.request_set_selection, &request_set_sel);
3010
	wl_signal_add(&seat->events.request_set_primary_selection, &request_set_psel);
3011
	wl_signal_add(&seat->events.request_start_drag, &request_start_drag);
3012
	wl_signal_add(&seat->events.start_drag, &start_drag);
3013
3014
	kb_group = createkeyboardgroup();
3015
	wl_list_init(&kb_group->destroy.link);
3016
3017
	output_mgr = wlr_output_manager_v1_create(dpy);
3018
	wl_signal_add(&output_mgr->events.apply, &output_mgr_apply);
3019
	wl_signal_add(&output_mgr->events.test, &output_mgr_test);
3020
3021
	drwl_init();
3022
3023
	status_event_source = wl_event_loop_add_fd(wl_display_get_event_loop(dpy),
3024
		STDIN_FILENO, WL_EVENT_READABLE, statusin, NULL);
3025
3026
	/* Make sure XWayland clients don't connect to the parent X server,
3027
	 * e.g when running in the x11 backend or the wayland backend and the
3028
	 * compositor has Xwayland support */
3029
	unsetenv("DISPLAY");
3030
#ifdef XWAYLAND
3031
	/*
3032
	 * Initialise the XWayland X server.
3033
	 * It will be started when the first X client is started.
3034
	 */
3035
	if ((xwayland = wlr_xwayland_create(dpy, compositor, 1))) {
3036
		wl_signal_add(&xwayland->events.ready, &xwayland_ready);
3037
		wl_signal_add(&xwayland->events.new_surface, &new_xwayland_surface);
3038
3039
		setenv("DISPLAY", xwayland->display_name, 1);
3040
	} else {
3041
		fprintf(stderr, "failed to setup XWayland X server, continuing without it\n");
3042
	}
3043
#endif
3044
}
3045
3046
void
3047
spawn(const Arg *arg)
3048
{
3049
	if (fork() == 0) {
3050
		close(STDIN_FILENO);
3051
		dup2(STDERR_FILENO, STDOUT_FILENO);
3052
		setsid();
3053
		execvp(((char **)arg->v)[0], (char **)arg->v);
3054
		die("dwl: execvp %s failed:", ((char **)arg->v)[0]);
3055
	}
3056
}
3057
3058
void
3059
startdrag(struct wl_listener *listener, void *data)
3060
{
3061
	struct wlr_drag *drag = data;
3062
	if (!drag->icon)
3063
		return;
3064
3065
	drag->icon->data = &wlr_scene_drag_icon_create(drag_icon, drag->icon)->node;
3066
	LISTEN_STATIC(&drag->icon->events.destroy, destroydragicon);
3067
}
3068
3069
int
3070
statusin(int fd, unsigned int mask, void *data)
3071
{
3072
	char status[256];
3073
	ssize_t n;
3074
3075
	if (mask & WL_EVENT_ERROR)
3076
		die("status in event error");
3077
	if (mask & WL_EVENT_HANGUP)
3078
		wl_event_source_remove(status_event_source);
3079
3080
	n = read(fd, status, sizeof(status) - 1);
3081
	if (n < 0 && errno != EWOULDBLOCK)
3082
		die("read:");
3083
3084
	status[n] = '\0';
3085
	status[strcspn(status, "\n")] = '\0';
3086
3087
	strncpy(stext, status, sizeof(stext));
3088
	drawbars();
3089
3090
	return 0;
3091
}
3092
3093
void
3094
tag(const Arg *arg)
3095
{
3096
	Client *sel = focustop(selmon);
3097
	if (!sel || (arg->ui & TAGMASK) == 0)
3098
		return;
3099
3100
	sel->tags = arg->ui & TAGMASK;
3101
	focusclient(focustop(selmon), 1);
3102
	arrange(selmon);
3103
	drawbars();
3104
}
3105
3106
void
3107
tagmon(const Arg *arg)
3108
{
3109
	Client *sel = focustop(selmon);
3110
	if (sel)
3111
		setmon(sel, dirtomon(arg->i), 0);
3112
}
3113
3114
void
3115
tile(Monitor *m)
3116
{
3117
	unsigned int h, r, e = m->gaps, mw, my, ty;
3118
	int i, n = 0;
3119
	Client *c;
3120
3121
	wl_list_for_each(c, &clients, link)
3122
		if (VISIBLEON(c, m) && !c->isfloating && !c->isfullscreen)
3123
			n++;
3124
	if (n == 0)
3125
		return;
3126
	if (smartgaps == n)
3127
		e = 0;
3128
3129
	if (n > m->nmaster)
3130
		mw = m->nmaster ? (int)roundf((m->w.width + gappx*e) * m->mfact) : 0;
3131
	else
3132
		mw = m->w.width;
3133
	i = 0;
3134
	my = ty = gappx*e;
3135
	wl_list_for_each(c, &clients, link) {
3136
		if (!VISIBLEON(c, m) || c->isfloating || c->isfullscreen)
3137
			continue;
3138
		if (i < m->nmaster) {
3139
			r = MIN(n, m->nmaster) - i;
3140
			h = (m->w.height - my - gappx*e - gappx*e * (r - 1)) / r;
3141
			resize(c, (struct wlr_box){.x = m->w.x + gappx*e, .y = m->w.y + my,
3142
				.width = mw - 2*gappx*e, .height = h}, 0);
3143
			my += c->geom.height + gappx*e;
3144
		} else {
3145
			r = n - i;
3146
			h = (m->w.height - ty - gappx*e - gappx*e * (r - 1)) / r;
3147
			resize(c, (struct wlr_box){.x = m->w.x + mw, .y = m->w.y + ty,
3148
				.width = m->w.width - mw - gappx*e, .height = h}, 0);
3149
			ty += c->geom.height + gappx*e;
3150
		}
3151
		i++;
3152
	}
3153
}
3154
3155
void
3156
togglebar(const Arg *arg)
3157
{
3158
	wlr_scene_node_set_enabled(&selmon->scene_buffer->node,
3159
		!selmon->scene_buffer->node.enabled);
3160
	arrangelayers(selmon);
3161
}
3162
3163
void
3164
togglefloating(const Arg *arg)
3165
{
3166
	Client *sel = focustop(selmon);
3167
	/* return if fullscreen */
3168
	if (sel && !sel->isfullscreen)
3169
		setfloating(sel, !sel->isfloating);
3170
}
3171
3172
void
3173
togglefullscreen(const Arg *arg)
3174
{
3175
	Client *sel = focustop(selmon);
3176
	if (sel)
3177
		setfullscreen(sel, !sel->isfullscreen);
3178
}
3179
3180
void
3181
togglegaps(const Arg *arg)
3182
{
3183
	selmon->gaps = !selmon->gaps;
3184
	arrange(selmon);
3185
}
3186
3187
void
3188
toggletag(const Arg *arg)
3189
{
3190
	uint32_t newtags;
3191
	Client *sel = focustop(selmon);
3192
	if (!sel || !(newtags = sel->tags ^ (arg->ui & TAGMASK)))
3193
		return;
3194
3195
	sel->tags = newtags;
3196
	focusclient(focustop(selmon), 1);
3197
	arrange(selmon);
3198
	drawbars();
3199
}
3200
3201
void
3202
toggleview(const Arg *arg)
3203
{
3204
	uint32_t newtagset;
3205
	if (!(newtagset = selmon ? selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK) : 0))
3206
		return;
3207
3208
	selmon->tagset[selmon->seltags] = newtagset;
3209
	focusclient(focustop(selmon), 1);
3210
	arrange(selmon);
3211
	drawbars();
3212
}
3213
3214
void
3215
unlocksession(struct wl_listener *listener, void *data)
3216
{
3217
	SessionLock *lock = wl_container_of(listener, lock, unlock);
3218
	destroylock(lock, 1);
3219
}
3220
3221
void
3222
unmaplayersurfacenotify(struct wl_listener *listener, void *data)
3223
{
3224
	LayerSurface *l = wl_container_of(listener, l, unmap);
3225
3226
	l->mapped = 0;
3227
	wlr_scene_node_set_enabled(&l->scene->node, 0);
3228
	if (l == exclusive_focus)
3229
		exclusive_focus = NULL;
3230
	if (l->layer_surface->output && (l->mon = l->layer_surface->output->data))
3231
		arrangelayers(l->mon);
3232
	if (l->layer_surface->surface == seat->keyboard_state.focused_surface)
3233
		focusclient(focustop(selmon), 1);
3234
	motionnotify(0, NULL, 0, 0, 0, 0);
3235
}
3236
3237
void
3238
unmapnotify(struct wl_listener *listener, void *data)
3239
{
3240
	/* Called when the surface is unmapped, and should no longer be shown. */
3241
	Client *c = wl_container_of(listener, c, unmap);
3242
	if (c == grabc) {
3243
		cursor_mode = CurNormal;
3244
		grabc = NULL;
3245
	}
3246
3247
	if (client_is_unmanaged(c)) {
3248
		if (c == exclusive_focus) {
3249
			exclusive_focus = NULL;
3250
			focusclient(focustop(selmon), 1);
3251
		}
3252
	} else {
3253
		wl_list_remove(&c->link);
3254
		setmon(c, NULL, 0);
3255
		wl_list_remove(&c->flink);
3256
	}
3257
3258
	wlr_scene_node_destroy(&c->scene->node);
3259
	drawbars();
3260
	motionnotify(0, NULL, 0, 0, 0, 0);
3261
}
3262
3263
void
3264
updatemons(struct wl_listener *listener, void *data)
3265
{
3266
	/*
3267
	 * Called whenever the output layout changes: adding or removing a
3268
	 * monitor, changing an output's mode or position, etc. This is where
3269
	 * the change officially happens and we update geometry, window
3270
	 * positions, focus, and the stored configuration in wlroots'
3271
	 * output-manager implementation.
3272
	 */
3273
	struct wlr_output_configuration_v1 *config
3274
			= wlr_output_configuration_v1_create();
3275
	Client *c;
3276
	struct wlr_output_configuration_head_v1 *config_head;
3277
	Monitor *m;
3278
3279
	/* First remove from the layout the disabled monitors */
3280
	wl_list_for_each(m, &mons, link) {
3281
		if (m->wlr_output->enabled || m->asleep)
3282
			continue;
3283
		config_head = wlr_output_configuration_head_v1_create(config, m->wlr_output);
3284
		config_head->state.enabled = 0;
3285
		/* Remove this output from the layout to avoid cursor enter inside it */
3286
		wlr_output_layout_remove(output_layout, m->wlr_output);
3287
		closemon(m);
3288
		m->m = m->w = (struct wlr_box){0};
3289
	}
3290
	/* Insert outputs that need to */
3291
	wl_list_for_each(m, &mons, link) {
3292
		if (m->wlr_output->enabled
3293
				&& !wlr_output_layout_get(output_layout, m->wlr_output))
3294
			wlr_output_layout_add_auto(output_layout, m->wlr_output);
3295
	}
3296
3297
	/* Now that we update the output layout we can get its box */
3298
	wlr_output_layout_get_box(output_layout, NULL, &sgeom);
3299
3300
	wlr_scene_node_set_position(&root_bg->node, sgeom.x, sgeom.y);
3301
	wlr_scene_rect_set_size(root_bg, sgeom.width, sgeom.height);
3302
3303
	/* Make sure the clients are hidden when dwl is locked */
3304
	wlr_scene_node_set_position(&locked_bg->node, sgeom.x, sgeom.y);
3305
	wlr_scene_rect_set_size(locked_bg, sgeom.width, sgeom.height);
3306
3307
	wl_list_for_each(m, &mons, link) {
3308
		if (!m->wlr_output->enabled)
3309
			continue;
3310
		config_head = wlr_output_configuration_head_v1_create(config, m->wlr_output);
3311
3312
		/* Get the effective monitor geometry to use for surfaces */
3313
		wlr_output_layout_get_box(output_layout, m->wlr_output, &m->m);
3314
		m->w = m->m;
3315
		wlr_scene_output_set_position(m->scene_output, m->m.x, m->m.y);
3316
3317
		wlr_scene_node_set_position(&m->fullscreen_bg->node, m->m.x, m->m.y);
3318
		wlr_scene_rect_set_size(m->fullscreen_bg, m->m.width, m->m.height);
3319
3320
		if (m->lock_surface) {
3321
			struct wlr_scene_tree *scene_tree = m->lock_surface->surface->data;
3322
			wlr_scene_node_set_position(&scene_tree->node, m->m.x, m->m.y);
3323
			wlr_session_lock_surface_v1_configure(m->lock_surface, m->m.width, m->m.height);
3324
		}
3325
3326
		/* Calculate the effective monitor geometry to use for clients */
3327
		arrangelayers(m);
3328
		/* Don't move clients to the left output when plugging monitors */
3329
		arrange(m);
3330
		/* make sure fullscreen clients have the right size */
3331
		if ((c = focustop(m)) && c->isfullscreen)
3332
			resize(c, m->m, 0);
3333
3334
		/* Try to re-set the gamma LUT when updating monitors,
3335
		 * it's only really needed when enabling a disabled output, but meh. */
3336
		m->gamma_lut_changed = 1;
3337
3338
		config_head->state.x = m->m.x;
3339
		config_head->state.y = m->m.y;
3340
3341
		if (!selmon) {
3342
			selmon = m;
3343
		}
3344
	}
3345
3346
	if (selmon && selmon->wlr_output->enabled) {
3347
		wl_list_for_each(c, &clients, link) {
3348
			if (!c->mon && client_surface(c)->mapped)
3349
				setmon(c, selmon, c->tags);
3350
		}
3351
		focusclient(focustop(selmon), 1);
3352
		if (selmon->lock_surface) {
3353
			client_notify_enter(selmon->lock_surface->surface,
3354
					wlr_seat_get_keyboard(seat));
3355
			client_activate_surface(selmon->lock_surface->surface, 1);
3356
		}
3357
	}
3358
3359
	wl_list_for_each(m, &mons, link) {
3360
		updatebar(m);
3361
		drawbar(m);
3362
	}
3363
3364
	/* FIXME: figure out why the cursor image is at 0,0 after turning all
3365
	 * the monitors on.
3366
	 * Move the cursor image where it used to be. It does not generate a
3367
	 * wl_pointer.motion event for the clients, it's only the image what it's
3368
	 * at the wrong position after all. */
3369
	wlr_cursor_move(cursor, NULL, 0, 0);
3370
3371
	wlr_output_manager_v1_set_configuration(output_mgr, config);
3372
}
3373
3374
void
3375
updatebar(Monitor *m)
3376
{
3377
	size_t i;
3378
	int rw, rh;
3379
	char fontattrs[12];
3380
3381
	wlr_output_transformed_resolution(m->wlr_output, &rw, &rh);
3382
	m->b.width = rw;
3383
	m->b.real_width = (int)((float)m->b.width / m->wlr_output->scale);
3384
3385
	wlr_scene_node_set_enabled(&m->scene_buffer->node, m->wlr_output->enabled ? showbar : 0);
3386
3387
	for (i = 0; i < LENGTH(m->pool); i++)
3388
		if (m->pool[i]) {
3389
			wlr_buffer_drop(&m->pool[i]->base);
3390
			m->pool[i] = NULL;
3391
		}
3392
3393
	if (m->b.scale == m->wlr_output->scale && m->drw)
3394
		return;
3395
3396
	drwl_font_destroy(m->drw->font);
3397
	snprintf(fontattrs, sizeof(fontattrs), "dpi=%.2f", 96. * m->wlr_output->scale);
3398
	if (!(drwl_font_create(m->drw, LENGTH(fonts), fonts, fontattrs)))
3399
		die("Could not load font");
3400
3401
	m->b.scale = m->wlr_output->scale;
3402
	m->lrpad = m->drw->font->height;
3403
	m->b.height = m->drw->font->height + 2;
3404
	m->b.real_height = (int)((float)m->b.height / m->wlr_output->scale);
3405
}
3406
3407
void
3408
updatetitle(struct wl_listener *listener, void *data)
3409
{
3410
	Client *c = wl_container_of(listener, c, set_title);
3411
	if (c == focustop(c->mon))
3412
		drawbars();
3413
}
3414
3415
void
3416
urgent(struct wl_listener *listener, void *data)
3417
{
3418
	struct wlr_xdg_activation_v1_request_activate_event *event = data;
3419
	Client *c = NULL;
3420
	toplevel_from_wlr_surface(event->surface, &c, NULL);
3421
	if (!c || c == focustop(selmon))
3422
		return;
3423
3424
	c->isurgent = 1;
3425
	drawbars();
3426
3427
	if (client_surface(c)->mapped)
3428
		client_set_border_color(c, (float[])COLOR(colors[SchemeUrg][ColBorder]));
3429
}
3430
3431
void
3432
view(const Arg *arg)
3433
{
3434
	if (!selmon || (arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
3435
		return;
3436
	selmon->seltags ^= 1; /* toggle sel tagset */
3437
	if (arg->ui & TAGMASK)
3438
		selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
3439
	focusclient(focustop(selmon), 1);
3440
	arrange(selmon);
3441
	drawbars();
3442
}
3443
3444
void
3445
virtualkeyboard(struct wl_listener *listener, void *data)
3446
{
3447
	struct wlr_virtual_keyboard_v1 *kb = data;
3448
	/* virtual keyboards shouldn't share keyboard group */
3449
	KeyboardGroup *group = createkeyboardgroup();
3450
	/* Set the keymap to match the group keymap */
3451
	wlr_keyboard_set_keymap(&kb->keyboard, group->wlr_group->keyboard.keymap);
3452
	LISTEN(&kb->keyboard.base.events.destroy, &group->destroy, destroykeyboardgroup);
3453
3454
	/* Add the new keyboard to the group */
3455
	wlr_keyboard_group_add_keyboard(group->wlr_group, &kb->keyboard);
3456
}
3457
3458
void
3459
virtualpointer(struct wl_listener *listener, void *data)
3460
{
3461
	struct wlr_virtual_pointer_v1_new_pointer_event *event = data;
3462
	struct wlr_input_device *device = &event->new_pointer->pointer.base;
3463
3464
	wlr_cursor_attach_input_device(cursor, device);
3465
	if (event->suggested_output)
3466
		wlr_cursor_map_input_to_output(cursor, device, event->suggested_output);
3467
}
3468
3469
Monitor *
3470
xytomon(double x, double y)
3471
{
3472
	struct wlr_output *o = wlr_output_layout_output_at(output_layout, x, y);
3473
	return o ? o->data : NULL;
3474
}
3475
3476
void
3477
xytonode(double x, double y, struct wlr_surface **psurface,
3478
		Client **pc, LayerSurface **pl, double *nx, double *ny)
3479
{
3480
	struct wlr_scene_node *node, *pnode;
3481
	struct wlr_surface *surface = NULL;
3482
	struct wlr_scene_surface *scene_surface = NULL;
3483
	Client *c = NULL;
3484
	LayerSurface *l = NULL;
3485
	int layer;
3486
3487
	for (layer = NUM_LAYERS - 1; !surface && layer >= 0; layer--) {
3488
		if (!(node = wlr_scene_node_at(&layers[layer]->node, x, y, nx, ny)))
3489
			continue;
3490
3491
		if (node->type == WLR_SCENE_NODE_BUFFER) {
3492
			scene_surface = wlr_scene_surface_try_from_buffer(
3493
					wlr_scene_buffer_from_node(node));
3494
			if (!scene_surface) continue;
3495
			surface = scene_surface->surface;
3496
		}
3497
		/* Walk the tree to find a node that knows the client */
3498
		for (pnode = node; pnode && !c; pnode = &pnode->parent->node)
3499
			c = pnode->data;
3500
		if (c && c->type == LayerShell) {
3501
			c = NULL;
3502
			l = pnode->data;
3503
		}
3504
	}
3505
3506
	if (psurface) *psurface = surface;
3507
	if (pc) *pc = c;
3508
	if (pl) *pl = l;
3509
}
3510
3511
void
3512
zoom(const Arg *arg)
3513
{
3514
	Client *c, *sel = focustop(selmon);
3515
3516
	if (!sel || !selmon || !selmon->lt[selmon->sellt]->arrange || sel->isfloating)
3517
		return;
3518
3519
	/* Search for the first tiled window that is not sel, marking sel as
3520
	 * NULL if we pass it along the way */
3521
	wl_list_for_each(c, &clients, link) {
3522
		if (VISIBLEON(c, selmon) && !c->isfloating) {
3523
			if (c != sel)
3524
				break;
3525
			sel = NULL;
3526
		}
3527
	}
3528
3529
	/* Return if no other tiled window was found */
3530
	if (&c->link == &clients)
3531
		return;
3532
3533
	/* If we passed sel, move c to the front; otherwise, move sel to the
3534
	 * front */
3535
	if (!sel)
3536
		sel = c;
3537
	wl_list_remove(&sel->link);
3538
	wl_list_insert(&clients, &sel->link);
3539
3540
	focusclient(sel, 1);
3541
	arrange(selmon);
3542
}
3543
3544
#ifdef XWAYLAND
3545
void
3546
activatex11(struct wl_listener *listener, void *data)
3547
{
3548
	Client *c = wl_container_of(listener, c, activate);
3549
3550
	/* Only "managed" windows can be activated */
3551
	if (!client_is_unmanaged(c))
3552
		wlr_xwayland_surface_activate(c->surface.xwayland, 1);
3553
}
3554
3555
void
3556
associatex11(struct wl_listener *listener, void *data)
3557
{
3558
	Client *c = wl_container_of(listener, c, associate);
3559
3560
	LISTEN(&client_surface(c)->events.map, &c->map, mapnotify);
3561
	LISTEN(&client_surface(c)->events.unmap, &c->unmap, unmapnotify);
3562
}
3563
3564
void
3565
configurex11(struct wl_listener *listener, void *data)
3566
{
3567
	Client *c = wl_container_of(listener, c, configure);
3568
	struct wlr_xwayland_surface_configure_event *event = data;
3569
	if (!client_surface(c) || !client_surface(c)->mapped) {
3570
		wlr_xwayland_surface_configure(c->surface.xwayland,
3571
				event->x, event->y, event->width, event->height);
3572
		return;
3573
	}
3574
	if (client_is_unmanaged(c)) {
3575
		wlr_scene_node_set_position(&c->scene->node, event->x, event->y);
3576
		wlr_xwayland_surface_configure(c->surface.xwayland,
3577
				event->x, event->y, event->width, event->height);
3578
		return;
3579
	}
3580
	if ((c->isfloating && c != grabc) || !c->mon->lt[c->mon->sellt]->arrange) {
3581
		resize(c, (struct wlr_box){.x = event->x - c->bw,
3582
				.y = event->y - c->bw, .width = event->width + c->bw * 2,
3583
				.height = event->height + c->bw * 2}, 0);
3584
	} else {
3585
		arrange(c->mon);
3586
	}
3587
}
3588
3589
void
3590
createnotifyx11(struct wl_listener *listener, void *data)
3591
{
3592
	struct wlr_xwayland_surface *xsurface = data;
3593
	Client *c;
3594
3595
	/* Allocate a Client for this surface */
3596
	c = xsurface->data = ecalloc(1, sizeof(*c));
3597
	c->surface.xwayland = xsurface;
3598
	c->type = X11;
3599
	c->bw = client_is_unmanaged(c) ? 0 : borderpx;
3600
3601
	/* Listen to the various events it can emit */
3602
	LISTEN(&xsurface->events.associate, &c->associate, associatex11);
3603
	LISTEN(&xsurface->events.destroy, &c->destroy, destroynotify);
3604
	LISTEN(&xsurface->events.dissociate, &c->dissociate, dissociatex11);
3605
	LISTEN(&xsurface->events.request_activate, &c->activate, activatex11);
3606
	LISTEN(&xsurface->events.request_configure, &c->configure, configurex11);
3607
	LISTEN(&xsurface->events.request_fullscreen, &c->fullscreen, fullscreennotify);
3608
	LISTEN(&xsurface->events.set_hints, &c->set_hints, sethints);
3609
	LISTEN(&xsurface->events.set_title, &c->set_title, updatetitle);
3610
}
3611
3612
void
3613
dissociatex11(struct wl_listener *listener, void *data)
3614
{
3615
	Client *c = wl_container_of(listener, c, dissociate);
3616
	wl_list_remove(&c->map.link);
3617
	wl_list_remove(&c->unmap.link);
3618
}
3619
3620
void
3621
sethints(struct wl_listener *listener, void *data)
3622
{
3623
	Client *c = wl_container_of(listener, c, set_hints);
3624
	struct wlr_surface *surface = client_surface(c);
3625
	if (c == focustop(selmon) || !c->surface.xwayland->hints)
3626
		return;
3627
3628
	c->isurgent = xcb_icccm_wm_hints_get_urgency(c->surface.xwayland->hints);
3629
	drawbars();
3630
3631
	if (c->isurgent && surface && surface->mapped)
3632
		client_set_border_color(c, (float[])COLOR(colors[SchemeUrg][ColBorder]));
3633
}
3634
3635
void
3636
xwaylandready(struct wl_listener *listener, void *data)
3637
{
3638
	struct wlr_xcursor *xcursor;
3639
3640
	/* assign the one and only seat */
3641
	wlr_xwayland_set_seat(xwayland, seat);
3642
3643
	/* Set the default XWayland cursor to match the rest of dwl. */
3644
	if ((xcursor = wlr_xcursor_manager_get_xcursor(cursor_mgr, "default", 1)))
3645
		wlr_xwayland_set_cursor(xwayland,
3646
				xcursor->images[0]->buffer, xcursor->images[0]->width * 4,
3647
				xcursor->images[0]->width, xcursor->images[0]->height,
3648
				xcursor->images[0]->hotspot_x, xcursor->images[0]->hotspot_y);
3649
}
3650
#endif
3651
3652
int
3653
main(int argc, char *argv[])
3654
{
3655
	char *startup_cmd = NULL;
3656
	int c;
3657
3658
	while ((c = getopt(argc, argv, "s:hdv")) != -1) {
3659
		if (c == 's')
3660
			startup_cmd = optarg;
3661
		else if (c == 'd')
3662
			log_level = WLR_DEBUG;
3663
		else if (c == 'v')
3664
			die("dwl " VERSION);
3665
		else
3666
			goto usage;
3667
	}
3668
	if (optind < argc)
3669
		goto usage;
3670
3671
	/* Wayland requires XDG_RUNTIME_DIR for creating its communications socket */
3672
	if (!getenv("XDG_RUNTIME_DIR"))
3673
		die("XDG_RUNTIME_DIR must be set");
3674
	setup();
3675
	run(startup_cmd);
3676
	cleanup();
3677
	return EXIT_SUCCESS;
3678
3679
usage:
3680
	die("Usage: %s [-v] [-d] [-s startup command]", argv[0]);
3681
}