dmw

wayland fork of dwm using neuswc/neuwld
git clone https://git.daat.foo/dmw.git
Log | Files | Refs | README | LICENSE

commit 0aa7cfa77e45f0f82c6c5dca14701d2f808b44fb
parent 1563572d1de565ebbe8b8d4eaf9f538f9b68f355
Author: cowmonk <cowmonk@based.pt>
Date:   Mon, 23 Nov 2026 11:37:52 -0700

dmw: inital port dwm to wayland

Use the patched neuswc/neuwld for this version

Diffstat:
A.gitignore | 5+++++
MLICENSE | 2++
MMakefile | 56++++++++++++++++++++++++++++++--------------------------
MREADME | 132++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
ATODO | 26++++++++++++++++++++++++++
Abar.c | 345+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Abar.h | 28++++++++++++++++++++++++++++
Mconfig.def.h | 107++++++++++++++++++++++++++++++++++++++-----------------------------------------
Mconfig.mk | 40++++++++++++----------------------------
Admw.c | 1180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ddrw.c | 471-------------------------------------------------------------------------------
Ddrw.h | 60------------------------------------------------------------
Ddwm.1 | 176-------------------------------------------------------------------------------
Ddwm.c | 2175-------------------------------------------------------------------------------
Ddwm.png | 0
Dtransient.c | 42------------------------------------------
16 files changed, 1779 insertions(+), 3066 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,5 @@ +*.o +config.h +dmw +swc-client-protocol.h +swc-protocol.c diff --git a/LICENSE b/LICENSE @@ -19,6 +19,8 @@ MIT/X Consortium License © 2016-2017 Markus Teich <markus.teich@stusta.mhn.de> © 2020-2022 Chris Down <chris@chrisdown.name> +© 2026 cowmonk <cowmonk@based.pt> + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation diff --git a/Makefile b/Makefile @@ -1,45 +1,49 @@ -# dwm - dynamic window manager -# See LICENSE file for copyright and license details. - include config.mk -SRC = drw.c dwm.c util.c -OBJ = ${SRC:.c=.o} +SRC = dmw.c bar.c util.c +OBJ = ${SRC:.c=.o} swc-protocol.o -all: dwm +all: dmw .c.o: - ${CC} -c ${CFLAGS} $< + ${CC} ${CPPFLAGS} ${CFLAGS} -std=c99 -D_POSIX_C_SOURCE=200809L -DVERSION=\"${VERSION}\" ${INCS} -c $< + +dmw: ${OBJ} + ${CC} ${LDFLAGS} -o $@ ${OBJ} ${LIBS} -${OBJ}: config.h config.mk +dmw.o: config.h bar.h util.h +bar.o: bar.h util.h swc-client-protocol.h +${OBJ}: config.mk +util.o: util.h config.h: cp config.def.h $@ -dwm: ${OBJ} - ${CC} -o $@ ${OBJ} ${LDFLAGS} +swc-client-protocol.h: ${SWC_XML} + wayland-scanner client-header ${SWC_XML} $@ + +swc-protocol.c: ${SWC_XML} + wayland-scanner private-code ${SWC_XML} $@ clean: - rm -f dwm ${OBJ} dwm-${VERSION}.tar.gz + rm -f dmw ${OBJ} swc-client-protocol.h swc-protocol.c dmw-${VERSION}.tar.gz -dist: clean - mkdir -p dwm-${VERSION} - cp -R LICENSE Makefile README config.def.h config.mk\ - dwm.1 drw.h util.h ${SRC} dwm.png transient.c dwm-${VERSION} - tar -cf dwm-${VERSION}.tar dwm-${VERSION} - gzip dwm-${VERSION}.tar - rm -rf dwm-${VERSION} +dist: + mkdir -p dmw-${VERSION} + cp LICENSE Makefile README config.def.h config.mk bar.h util.h ${SRC} dmw-${VERSION}/ + tar -cf dmw-${VERSION}.tar dmw-${VERSION} + gzip -f dmw-${VERSION}.tar + rm -rf dmw-${VERSION} install: all - mkdir -p ${DESTDIR}${PREFIX}/bin - cp -f dwm ${DESTDIR}${PREFIX}/bin - chmod 755 ${DESTDIR}${PREFIX}/bin/dwm - mkdir -p ${DESTDIR}${MANPREFIX}/man1 - sed "s/VERSION/${VERSION}/g" < dwm.1 > ${DESTDIR}${MANPREFIX}/man1/dwm.1 - chmod 644 ${DESTDIR}${MANPREFIX}/man1/dwm.1 + mkdir -p ${DESTDIR}${PREFIX}/bin ${DESTDIR}${MANPREFIX}/man1 + cp dmw ${DESTDIR}${PREFIX}/bin/dmw + chmod 755 ${DESTDIR}${PREFIX}/bin/dmw + # TODO make manpage (reuse dwm?) + # sed 's/VERSION/${VERSION}/g' dwm.1 > ${DESTDIR}${MANPREFIX}/man1/dmw.1 + # chmod 644 ${DESTDIR}${MANPREFIX}/man1/dwm.1 uninstall: - rm -f ${DESTDIR}${PREFIX}/bin/dwm\ - ${DESTDIR}${MANPREFIX}/man1/dwm.1 + rm -f ${DESTDIR}${PREFIX}/bin/dmw ${DESTDIR}${MANPREFIX}/man1/dmw.1 .PHONY: all clean dist install uninstall diff --git a/README b/README @@ -1,48 +1,116 @@ -dwm - dynamic window manager -============================ -dwm is an extremely fast, small, and dynamic window manager for X. +dmw - dwm made in wayland +========================= +dmw ports dwm to suckless Wayland. It uses neuswc for window management and +neuwld to draw the bar. This is a bit more "feature"-full thanks to the extra +neuswc/neuwld patches from MICE (a seperate project). -Requirements ------------- -In order to build dwm you need the Xlib header files. +See: my forks of neuswc/neuwld which apply these patches that haven't been +upstreamed yet (most of the patches com from xplshn): +- https://git.daat.foo/neuswc/file/README.html +- https://git.daat.foo/neuwld/file/README.html -Installation ------------- -Edit config.mk to match your local setup (dwm is installed into -the /usr/local namespace by default). +Disclaimer +---------- + + + +Build +----- + +Install neuswc and neuwld with the MICE port patches, their pkg-config +files (swc.pc and wld.pc), and wayland-scanner. The build reads swc.xml +from the installed neuswc prefix. For a static-only neuswc installation +use make PKG_CONFIG='pkg-config --static'. -Afterwards enter the following command to build and install dwm (if -necessary as root): + make + make install - make clean install +The first build copies config.def.h to config.h. Edit config.h and rebuild +to change bindings, colors, fonts or rules. Rules match substrings of the +Wayland app ID and title. The default commands are `st-wl` and `neumenu_run`. +Run +--- -Running dwm ------------ -Add the following line to your .xinitrc to start dwm using startx: +From a VT with XDG_RUNTIME_DIR set, run: - exec dwm + swc-launch dmw -In order to connect dwm to a specific display, make sure that -the DISPLAY environment variable is set correctly, e.g.: +Inside an existing Wayland session, use the nested backend: - DISPLAY=foo.bar:1 exec dwm + SWC_BACKEND=nested dmw -(This will start dwm on display :1 of the host foo.bar.) +Alt-Shift-Return starts a terminal. Alt-p opens the launcher. +Alt-Shift-q exits. See config.h if you want to change the default MOD key. -In order to display status info in the bar, you can do something -like this in your .xinitrc: +The bar reads one status line at a time from stdin: - while xsetroot -name "`date` `uptime | sed 's/.*,//'`" - do - sleep 1 - done & - exec dwm + while date; do sleep 1; done | swc-launch dmw + +Patches +------- + +This project tries to not overstep it's boundaries with what a tiling wm +should do and implement just like the original dwm. It should be relatively +easy to patch dmw. + +Patches live in https://git.daat.foo/dmw-patches/log.html. See Contributing +below if you would like to contribute to the repository of patches or this +project in particular. + +Contributing +------------ +All development is on the [stagit repo](https://git.daat.foo/dmw/log.html). +However while it is much preferred, you can send PRs in the github mirror. +It's just frowned upon (my me). All contributions should be sent via email. + +Run a quick `git format-patch HEAD~1` and send to *cowmonk@based.pt* with the +subject head of `[PATCH] dmw`. Consider reading the manpages of `git-send-email` +if you are interested in moving towards email for development. + +I *strongly* suggest pgp encrypting your email, in which case my public keys +can be found on `keys.openpgp.org` or here: + +-----BEGIN PGP PUBLIC KEY BLOCK----- +Comment: 52B0 852C 5A4C 823C FAB7 420A 2F73 9BCA BDD5 B880 +Comment: cowmonk@based.pt + +xjMEaSJi8xYJKwYBBAHaRw8BAQdAEVP64bLVXCxZYH5rItmtvThKyTrRZ4HFCZ42 +IqFx+crNEGNvd21vbmtAYmFzZWQucHTCiQQTFggAGgQLCQgHAhUIAhYBAhkABYJp +ImLzAp4BApsDACEJEC9zm8q91biAFiEEUrCFLFpMgjz6t0IKL3Obyr3VuIBOEQEA ++gIa9t3yKL3FAHg5VT2xV8M2VdLf1ZqaFlCPyGhXBZsA+QGGstK6+YsUbmP+H6I5 +r4AgLawGeB9IH7WC0w4dhTsKzjgEaSJi8xIKKwYBBAGXVQEFAQEHQMsmen1ddl9a +ddXu4ktm8BATTlEy2k4zMzo6RnyRB+d4AwEIB8J4BBgWCAAJBYJpImLzApsMACEJ +EC9zm8q91biAFiEEUrCFLFpMgjz6t0IKL3Obyr3VuIA9AQD/S/EL51hMSBI35Lr3 +RjuNFtqnlgYpfkMxgPvp2bWRY60A/2NhDRNUjY2wA4+mESlCIf94FVvqcfclnSZU +A7wM/YAB +=nZZp +-----END PGP PUBLIC KEY BLOCK----- + +see: ./TODO if you want to see what to possibly help out with. + +Credits +------- + +- [dwm](https://dwm.suckless.org/) - greatest tiling wm +- [neulibs](https://sr.ht/~shrub900/neulibs/) - good wayland implementation +- [tohu](https://git.sr.ht/~shrub900/tohu) - good reference impl. +- [wsxwm](https://git.sr.ht/~uint/wsxwm) - really good ref for neuswc compositors + +- dacctal - for the amazing name, also great youtuber +- michaelforney - swc/wld creator <3 +- shrub900 - started derive and wayland.fyi, also made neuswc/neuwld +- uint23 - great programmer, made neumenu +- xplshn - a vast amount of patches for neuswc were created by him + +Relevant +-------- + +- [neumenu](https://git.sr.ht/~uint/neumenu) - really good fork of a fork +- [st-wl](https://github.com/michaelforney/st) - good (enough) wayland st fork +- [dwc](https://git.sr.ht/~corg/DWC) - dwm-like wayland compositor +- [velox](https://github.com/michaelforney/velox) - simple compositor based on swc -Configuration -------------- -The configuration of dwm is done by creating a custom config.h -and (re)compiling the source code. diff --git a/TODO b/TODO @@ -0,0 +1,26 @@ +These TODOs are in no particular order. + +- make manpages (removed dwm.1), unsure whether or not to reuse the dwm + one and just go with the flow or just to not have manpages at all. +- get two monitors going with different tags and layouts. send windows + both ways, including a fullscreen one. watch the focus, borders and bar. + Multimonitor is largely untested. +- bring back urgent tags if neuswc can tell us an app wants attention. + a hidden tag should light up and clear when we focus the window. This + might require patches to neuswc... +- create docs/ for simple stuff. a short config.h example for keys, app-ID + rules and the bar font, plus the VT and nested launch commands. Some other + nice things also are XKB_* stuff and other things that were less unclear + to me personally when I had first used swc/velox and stuff. +- dwm's corner warp on mouse resize is possible on DRM with the existing + swc_cursor_set_position(). In a nested session the outer compositor + owns the physical pointer. dmw currently resizes from the drag origin. +- dwm marks a shortened bar title with three dots; dmw clips it at the + edge. It's probably possible using font advance & clip rectangle to + get this feature back. +- Urgent tags still need an attention request that neuswc can deliver + to dmw. Maybe patch some wlr-* protocols to neuswc? + +already good (maybe) based on feel (and the fact I'm currently trying to daily +drive this): tile, monocle, floating, zoom, tags, app-ID rules, bar clicks, +move/resize, close, fullscreen and live swstatus updates. diff --git a/bar.c b/bar.c @@ -0,0 +1,345 @@ +/* See LICENSE file for copyright and license details. */ +#include "bar.h" +#include "swc-client-protocol.h" + +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/mman.h> +#include <sys/socket.h> +#include <unistd.h> +#include <wayland-client.h> +#include <wayland-server-core.h> +#include <wld/wld.h> +#include <wld/pixman.h> + +#include "util.h" + +struct Canvas { + struct wl_buffer *buffer; + struct wld_buffer *pixels; + void *addr; + size_t size; + int width, busy; + struct Canvas *next; +}; + +static struct wl_client *peer; +static struct wl_display *client; +static struct wl_event_loop *loop; +static struct wl_event_source *source; +static struct wl_registry *registry; +static struct wl_compositor *compositor; +static struct wl_seat *seat; +static struct wl_pointer *pointer; +static struct wl_shm *shm; +static struct swc_panel_manager *panels; +static struct wld_renderer *renderer; +static struct wld_font_context *fonts; +struct wld_font *barfont; +static struct Bar *hover; +static int pointerx, top; + +static void +flush(void) +{ + uint32_t events = WL_EVENT_READABLE; + + if (wl_display_flush(client) < 0) { + if (errno != EAGAIN) + die("dmw: bar connection:"); + events |= WL_EVENT_WRITABLE; + } + wl_event_source_fd_update(source, events); +} + +static int +dispatch(int fd, uint32_t events, void *data) +{ + if (events & (WL_EVENT_HANGUP | WL_EVENT_ERROR) || + ((events & WL_EVENT_READABLE) && wl_display_dispatch(client) < 0)) + die("dmw: bar disconnected"); + flush(); + return 0; +} + +static void +released(void *data, struct wl_buffer *buffer) +{ + struct Canvas *c = data; + c->busy = 0; +} + +static struct Canvas * +canvas(struct Bar *b) +{ + static const struct wl_buffer_listener listener = { .release = released }; + char path[] = "/tmp/dmw-bar-XXXXXX"; + struct Canvas *c; + struct wl_shm_pool *pool; + int fd; + + for (c = b->buffers; c; c = c->next) + if (!c->busy && c->width == b->width) + return c; + c = ecalloc(1, sizeof *c); + c->size = (size_t)b->width * 4 * b->height; + if ((fd = mkstemp(path)) < 0) + die("dmw: creating bar buffer:"); + unlink(path); + if (ftruncate(fd, c->size) < 0 || + (c->addr = mmap(NULL, c->size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED) + die("dmw: mapping bar:"); + pool = wl_shm_create_pool(shm, fd, c->size); + close(fd); + c->width = b->width; + c->buffer = wl_shm_pool_create_buffer(pool, 0, b->width, b->height, b->width * 4, WL_SHM_FORMAT_XRGB8888); + wl_shm_pool_destroy(pool); + c->pixels = wld_import_buffer(wld_pixman_context, WLD_OBJECT_DATA, (union wld_object){ .ptr = c->addr }, + b->width, b->height, WLD_FORMAT_XRGB8888, b->width * 4); + if (!c->pixels) + die("dmw: cannot import bar pixels"); + wl_buffer_add_listener(c->buffer, &listener, c); + c->next = b->buffers; + return b->buffers = c; +} + +static void +freecanvas(struct Canvas *c) +{ + wl_buffer_destroy(c->buffer); + wld_buffer_unreference(c->pixels); + munmap(c->addr, c->size); + free(c); +} + +static void +paint(void *data) +{ + struct Bar *b = data; + struct Canvas *c, **p; + + b->idle = NULL; + for (p = &b->buffers; (c = *p); ) { + if (c->width != b->width) { + *p = c->next; + freecanvas(c); + } else + p = &c->next; + } + if (b->shown != b->wanted) { + b->shown = b->wanted; + swc_panel_set_strut(b->panel, b->shown ? b->height : 0, 0, b->width); + } + if (b->shown) { + c = canvas(b); + if (!wld_set_target_buffer(renderer, c->pixels)) + die("dmw: cannot draw bar"); + bar_paint(b, renderer); + wld_flush(renderer); + wl_surface_attach(b->surface, c->buffer, 0, 0); + wl_surface_damage(b->surface, 0, 0, b->width, b->height); + c->busy = 1; + } else + wl_surface_attach(b->surface, NULL, 0, 0); + wl_surface_commit(b->surface); + flush(); +} + +void +bar_update(struct Bar *b, int show) +{ + b->wanted = show; + if (client && b->width && !b->idle) + b->idle = wl_event_loop_add_idle(loop, paint, b); +} + +static void +docked(void *data, struct swc_panel *panel, uint32_t length) +{ + struct Bar *b = data; + b->width = length; + bar_update(b, b->wanted); +} + +static void +screenbound(void *data, struct wl_callback *sync, uint32_t serial) +{ + static const struct swc_panel_listener listener = { .docked = docked }; + struct swc_screen *output = data; + struct wl_resource *res; + struct Bar *b; + + wl_callback_destroy(sync); + /* the panel protocol omits output coordinates, so match screens by resource: */ + res = wl_client_get_object(peer, wl_proxy_get_id((struct wl_proxy *)output)); + b = res ? bar_for_screen(wl_resource_get_user_data(res)) : NULL; + if (!b) { + swc_screen_destroy(output); + return; + } + b->output = output; + b->height = barfont->height + 2; + b->surface = wl_compositor_create_surface(compositor); + wl_surface_set_user_data(b->surface, b); + b->panel = swc_panel_manager_create_panel(panels, b->surface); + swc_panel_add_listener(b->panel, &listener, b); + swc_panel_dock(b->panel, top ? SWC_PANEL_EDGE_TOP : SWC_PANEL_EDGE_BOTTOM, output, 0); +} + +static void +enter(void *data, struct wl_pointer *ptr, uint32_t serial, struct wl_surface *s, wl_fixed_t x, wl_fixed_t y) +{ + hover = s ? wl_surface_get_user_data(s) : NULL; + pointerx = wl_fixed_to_int(x); +} + +static void +leave(void *data, struct wl_pointer *ptr, uint32_t serial, struct wl_surface *s) +{ + hover = NULL; +} + +static void +motion(void *data, struct wl_pointer *ptr, uint32_t time, wl_fixed_t x, wl_fixed_t y) +{ + pointerx = wl_fixed_to_int(x); +} + +static void +button(void *data, struct wl_pointer *ptr, uint32_t serial, uint32_t time, uint32_t key, uint32_t state) +{ + if (hover && state == WL_POINTER_BUTTON_STATE_PRESSED) + bar_click(hover, pointerx, key); +} + +static void +axis(void *data, struct wl_pointer *ptr, uint32_t time, uint32_t axis, wl_fixed_t value) +{ +} + +static void +capabilities(void *data, struct wl_seat *s, uint32_t caps) +{ + static const struct wl_pointer_listener listener = { + .enter = enter, .leave = leave, .motion = motion, .button = button, .axis = axis, + }; + if ((caps & WL_SEAT_CAPABILITY_POINTER) && !pointer) { + pointer = wl_seat_get_pointer(s); + wl_pointer_add_listener(pointer, &listener, NULL); + } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && pointer) { + wl_pointer_destroy(pointer); + pointer = NULL; + hover = NULL; + } +} + +static void +global(void *data, struct wl_registry *reg, uint32_t name, const char *iface, uint32_t version) +{ + static const struct wl_seat_listener seat_listener = { .capabilities = capabilities }; + static const struct wl_callback_listener bound = { .done = screenbound }; + struct swc_screen *output; + + if (!strcmp(iface, "wl_shm")) + shm = wl_registry_bind(reg, name, &wl_shm_interface, 1); + else if (!strcmp(iface, "wl_compositor")) + compositor = wl_registry_bind(reg, name, &wl_compositor_interface, 1); + else if (!strcmp(iface, "swc_panel_manager")) + panels = wl_registry_bind(reg, name, &swc_panel_manager_interface, 1); + else if (!strcmp(iface, "swc_screen")) { + output = wl_registry_bind(reg, name, &swc_screen_interface, 1); + wl_callback_add_listener(wl_display_sync(client), &bound, output); + } else if (!strcmp(iface, "wl_seat")) { + seat = wl_registry_bind(reg, name, &wl_seat_interface, 1); + wl_seat_add_listener(seat, &seat_listener, NULL); + } +} + +static void +removed(void *data, struct wl_registry *reg, uint32_t name) +{ +} + +void +bar_init(struct wl_display *display, const char *font, int topbar) +{ + static const struct wl_registry_listener listener = { global, removed }; + int fds[2]; + + top = topbar; + loop = wl_display_get_event_loop(display); + fonts = wld_font_create_context(); + if (!fonts || !(barfont = wld_font_open_name(fonts, font)) || + !(renderer = wld_create_renderer(wld_pixman_context))) + die("dmw: cannot initialize bar font %s", font); + if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) + die("dmw: creating bar connection:"); + fcntl(fds[0], F_SETFD, FD_CLOEXEC); + fcntl(fds[1], F_SETFD, FD_CLOEXEC); + if (!(peer = wl_client_create(display, fds[0])) || + !(client = wl_display_connect_to_fd(fds[1]))) + die("dmw: cannot connect bar"); + source = wl_event_loop_add_fd(loop, fds[1], WL_EVENT_READABLE, dispatch, NULL); + if (!source) + die("dmw: cannot watch bar connection:"); + registry = wl_display_get_registry(client); + wl_registry_add_listener(registry, &listener, NULL); + flush(); +} + +int +textwidth(const char *s) +{ + struct wld_extents ext; + wld_font_text_extents(barfont, s, &ext); + return ext.advance; +} + +void +bar_close(struct Bar *b) +{ + struct Canvas *c; + if (hover == b) + hover = NULL; + if (b->idle) + wl_event_source_remove(b->idle); + while ((c = b->buffers)) { + b->buffers = c->next; + freecanvas(c); + } + if (b->panel) { + swc_panel_destroy(b->panel); + wl_surface_destroy(b->surface); + swc_screen_destroy(b->output); + } + b->panel = NULL; + b->width = 0; + b->idle = NULL; + if (client) + flush(); +} + +void +bar_finish(void) +{ + if (pointer) + wl_pointer_destroy(pointer); + if (seat) + wl_seat_destroy(seat); + if (shm) + wl_shm_destroy(shm); + if (panels) + swc_panel_manager_destroy(panels); + if (compositor) + wl_compositor_destroy(compositor); + wl_registry_destroy(registry); + wl_event_source_remove(source); + wl_display_disconnect(client); + client = NULL; + wld_destroy_renderer(renderer); + wld_font_close(barfont); + wld_font_destroy_context(fonts); +} diff --git a/bar.h b/bar.h @@ -0,0 +1,28 @@ +/* See LICENSE file for copyright and license details. */ +#include <stdint.h> + +struct swc_screen; +struct wl_display; +struct wld_font; +struct wld_renderer; + +struct Bar { + struct swc_screen *screen; + struct wl_surface *surface; + struct swc_panel *panel; + struct swc_screen *output; + struct Canvas *buffers; + struct wl_event_source *idle; + int width, height, shown, wanted; +}; + +void bar_init(struct wl_display *, const char *, int); +void bar_finish(void); +void bar_close(struct Bar *); +void bar_update(struct Bar *, int); +int textwidth(const char *); +extern struct wld_font *barfont; + +struct Bar *bar_for_screen(struct swc_screen *); +void bar_paint(struct Bar *, struct wld_renderer *); +void bar_click(struct Bar *, int, uint32_t); diff --git a/config.def.h b/config.def.h @@ -5,7 +5,7 @@ static const unsigned int borderpx = 1; /* border pixel of windows */ static const unsigned int snap = 32; /* snap pixel */ static const int showbar = 1; /* 0 means no bar */ static const int topbar = 1; /* 0 means bottom bar */ -static const char *fonts[] = { "monospace:size=10" }; +static const char font[] = "monospace:size=10"; static const char dmenufont[] = "monospace:size=10"; static const char col_gray1[] = "#222222"; static const char col_gray2[] = "#444444"; @@ -21,24 +21,19 @@ static const char *colors[][3] = { /* tagging */ static const char *tags[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9" }; -static const Rule rules[] = { - /* xprop(1): - * WM_CLASS(STRING) = instance, class - * WM_NAME(STRING) = title - */ - /* class instance title tags mask isfloating monitor */ - { "Gimp", NULL, NULL, 0, 1, -1 }, - { "Firefox", NULL, NULL, 1 << 8, 0, -1 }, +static const struct Rule rules[] = { + /* app_id title tags mask isfloating monitor */ + { "gimp", NULL, 0, 1, -1 }, + { "firefox", NULL, 1 << 8, 0, -1 }, }; /* layout(s) */ static const float mfact = 0.55; /* factor of master area size [0.05..0.95] */ static const int nmaster = 1; /* number of clients in master area */ -static const int resizehints = 1; /* 1 means respect size hints in tiled resizals */ static const int lockfullscreen = 1; /* 1 will force focus on the fullscreen window */ static const int refreshrate = 120; /* refresh rate (per second) for client move/resize */ -static const Layout layouts[] = { +static const struct Layout layouts[] = { /* symbol arrange function */ { "[]=", tile }, /* first entry is default */ { "><>", NULL }, /* no layout function means floating behavior */ @@ -46,61 +41,61 @@ static const Layout layouts[] = { }; /* key definitions */ -#define MODKEY Mod1Mask +#define MODKEY SWC_MOD_ALT /* set to SWC_MOD_LOGO for Super Key */ #define TAGKEYS(KEY,TAG) \ - { MODKEY, KEY, view, {.ui = 1 << TAG} }, \ - { MODKEY|ControlMask, KEY, toggleview, {.ui = 1 << TAG} }, \ - { MODKEY|ShiftMask, KEY, tag, {.ui = 1 << TAG} }, \ - { MODKEY|ControlMask|ShiftMask, KEY, toggletag, {.ui = 1 << TAG} }, + { MODKEY, KEY, view, {.ui = 1 << TAG} }, \ + { MODKEY|SWC_MOD_CTRL, KEY, toggleview, {.ui = 1 << TAG} }, \ + { MODKEY|SWC_MOD_SHIFT, KEY, tag, {.ui = 1 << TAG} }, \ + { MODKEY|SWC_MOD_CTRL|SWC_MOD_SHIFT, KEY, toggletag, {.ui = 1 << TAG} }, -/* helper for spawning shell commands in the pre dwm-5.0 fashion */ +/* helper for spawning shell commands */ #define SHCMD(cmd) { .v = (const char*[]){ "/bin/sh", "-c", cmd, NULL } } /* commands */ -static char dmenumon[8]; /* component of dmenucmd, manipulated in spawn() */ -static const char *dmenucmd[] = { "dmenu_run", "-m", dmenumon, "-fn", dmenufont, "-nb", col_gray1, "-nf", col_gray3, "-sb", col_cyan, "-sf", col_gray4, NULL }; -static const char *termcmd[] = { "st", NULL }; +static const char *dmenucmd[] = { "neumenu_run", "-fn", dmenufont, "-nb", col_gray1, "-nf", col_gray3, "-sb", col_cyan, "-sf", col_gray4, NULL }; +static const char *termcmd[] = { "st-wl", NULL }; -static const Key keys[] = { - /* modifier key function argument */ - { MODKEY, XK_p, spawn, {.v = dmenucmd } }, - { MODKEY|ShiftMask, XK_Return, spawn, {.v = termcmd } }, - { MODKEY, XK_b, togglebar, {0} }, - { MODKEY, XK_j, focusstack, {.i = +1 } }, - { MODKEY, XK_k, focusstack, {.i = -1 } }, - { MODKEY, XK_i, incnmaster, {.i = +1 } }, - { MODKEY, XK_d, incnmaster, {.i = -1 } }, - { MODKEY, XK_h, setmfact, {.f = -0.05} }, - { MODKEY, XK_l, setmfact, {.f = +0.05} }, - { MODKEY, XK_Return, zoom, {0} }, - { MODKEY, XK_Tab, view, {0} }, - { MODKEY|ShiftMask, XK_c, killclient, {0} }, - { MODKEY, XK_t, setlayout, {.v = &layouts[0]} }, - { MODKEY, XK_f, setlayout, {.v = &layouts[1]} }, - { MODKEY, XK_m, setlayout, {.v = &layouts[2]} }, - { MODKEY, XK_space, setlayout, {0} }, - { MODKEY|ShiftMask, XK_space, togglefloating, {0} }, - { MODKEY, XK_0, view, {.ui = ~0 } }, - { MODKEY|ShiftMask, XK_0, tag, {.ui = ~0 } }, - { MODKEY, XK_comma, focusmon, {.i = -1 } }, - { MODKEY, XK_period, focusmon, {.i = +1 } }, - { MODKEY|ShiftMask, XK_comma, tagmon, {.i = -1 } }, - { MODKEY|ShiftMask, XK_period, tagmon, {.i = +1 } }, - TAGKEYS( XK_1, 0) - TAGKEYS( XK_2, 1) - TAGKEYS( XK_3, 2) - TAGKEYS( XK_4, 3) - TAGKEYS( XK_5, 4) - TAGKEYS( XK_6, 5) - TAGKEYS( XK_7, 6) - TAGKEYS( XK_8, 7) - TAGKEYS( XK_9, 8) - { MODKEY|ShiftMask, XK_q, quit, {0} }, +static const struct Key keys[] = { + /* modifier key function argument */ + { MODKEY, XKB_KEY_p, spawn, {.v = dmenucmd } }, + { MODKEY|SWC_MOD_SHIFT, XKB_KEY_Return, spawn, {.v = termcmd } }, + { MODKEY, XKB_KEY_b, togglebar, {0} }, + { MODKEY, XKB_KEY_j, focusstack, {.i = +1 } }, + { MODKEY, XKB_KEY_k, focusstack, {.i = -1 } }, + { MODKEY, XKB_KEY_i, incnmaster, {.i = +1 } }, + { MODKEY, XKB_KEY_d, incnmaster, {.i = -1 } }, + { MODKEY, XKB_KEY_h, setmfact, {.f = -0.05} }, + { MODKEY, XKB_KEY_l, setmfact, {.f = +0.05} }, + { MODKEY, XKB_KEY_Return, zoom, {0} }, + { MODKEY, XKB_KEY_Tab, view, {0} }, + { MODKEY|SWC_MOD_SHIFT, XKB_KEY_c, killclient, {0} }, + { MODKEY, XKB_KEY_t, setlayout, {.v = &layouts[0]} }, + { MODKEY, XKB_KEY_f, setlayout, {.v = &layouts[1]} }, + { MODKEY, XKB_KEY_m, setlayout, {.v = &layouts[2]} }, + { MODKEY|SWC_MOD_SHIFT, XKB_KEY_f, togglefullscreen, {0} }, + { MODKEY, XKB_KEY_space, setlayout, {0} }, + { MODKEY|SWC_MOD_SHIFT, XKB_KEY_space, togglefloating, {0} }, + { MODKEY, XKB_KEY_0, view, {.ui = ~0 } }, + { MODKEY|SWC_MOD_SHIFT, XKB_KEY_0, tag, {.ui = ~0 } }, + { MODKEY, XKB_KEY_comma, focusmon, {.i = -1 } }, + { MODKEY, XKB_KEY_period, focusmon, {.i = +1 } }, + { MODKEY|SWC_MOD_SHIFT, XKB_KEY_comma, tagmon, {.i = -1 } }, + { MODKEY|SWC_MOD_SHIFT, XKB_KEY_period, tagmon, {.i = +1 } }, + TAGKEYS( XKB_KEY_1, 0) + TAGKEYS( XKB_KEY_2, 1) + TAGKEYS( XKB_KEY_3, 2) + TAGKEYS( XKB_KEY_4, 3) + TAGKEYS( XKB_KEY_5, 4) + TAGKEYS( XKB_KEY_6, 5) + TAGKEYS( XKB_KEY_7, 6) + TAGKEYS( XKB_KEY_8, 7) + TAGKEYS( XKB_KEY_9, 8) + { MODKEY|SWC_MOD_SHIFT, XKB_KEY_q, quit, {0} }, }; /* button definitions */ /* click can be ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkClientWin, or ClkRootWin */ -static const Button buttons[] = { +static const struct Button buttons[] = { /* click event mask button function argument */ { ClkLtSymbol, 0, Button1, setlayout, {0} }, { ClkLtSymbol, 0, Button3, setlayout, {.v = &layouts[2]} }, diff --git a/config.mk b/config.mk @@ -1,39 +1,23 @@ -# dwm version -VERSION = 6.8 - -# Customize below to fit your system +# dmw version +VERSION = 0.1 # paths PREFIX = /usr/local MANPREFIX = ${PREFIX}/share/man -X11INC = /usr/X11R6/include -X11LIB = /usr/X11R6/lib - -# Xinerama, comment if you don't want it -XINERAMALIBS = -lXinerama -XINERAMAFLAGS = -DXINERAMA - -# freetype -FREETYPELIBS = -lfontconfig -lXft -FREETYPEINC = /usr/include/freetype2 -# OpenBSD (uncomment) -#FREETYPEINC = ${X11INC}/freetype2 -#MANPREFIX = ${PREFIX}/man +# libraries +PKG_CONFIG = pkg-config +SWC_PREFIX != ${PKG_CONFIG} --variable=prefix swc +SWC_XML = ${SWC_PREFIX}/share/swc/swc.xml +PKGS = swc wld wayland-server wayland-client xkbcommon # includes and libs -INCS = -I${X11INC} -I${FREETYPEINC} -LIBS = -L${X11LIB} -lX11 ${XINERAMALIBS} ${FREETYPELIBS} +INCS != ${PKG_CONFIG} --cflags ${PKGS} +LIBS != ${PKG_CONFIG} --libs ${PKGS} # flags -CPPFLAGS = -D_DEFAULT_SOURCE -D_BSD_SOURCE -D_XOPEN_SOURCE=700L -DVERSION=\"${VERSION}\" ${XINERAMAFLAGS} -#CFLAGS = -g -std=c99 -pedantic -Wall -O0 ${INCS} ${CPPFLAGS} -CFLAGS = -std=c99 -pedantic -Wall -Wno-deprecated-declarations -Os ${INCS} ${CPPFLAGS} -LDFLAGS = ${LIBS} - -# Solaris -#CFLAGS = -fast ${INCS} -DVERSION=\"${VERSION}\" -#LDFLAGS = ${LIBS} +CPPFLAGS ?= -Os -Wall +CFLAGS ?= -Os -Wall # compiler and linker -CC = cc +CC = cproc diff --git a/dmw.c b/dmw.c @@ -0,0 +1,1180 @@ +/* See LICENSE file for copyright and license details. + * + * dwm made in wayland is a proper port/rewrite of the original suckless + * dynamic window manager reimagined in a better display protocol. Unlike + * dwl, this doesn't rely on wlroots (a terrible implementation of the + * wayland protocol) and instead uses neuswc/neuwld which is much more + * minmal and modern. + * + * This tries to be 1:1 to dwm, however given the difference between X and + * wayland, many of the functions had to be rewritten more so than others, + * however the spirit of dwm is still felt. There is some reorganization + * of the original functions, however you will be pleased to see that I + * have tried to preserve as much as possible of the original dwm. + * Unfortunately, some features are lost however, due to neuswc's lack of + * support of various popular wayland protocols (such as urgent tags). + * + * dmw runs on the Wayland event loop. When neuswc finds a new screen or + * window it calls newscreen() or newwindow(). Each sets up a table of + * handlers and gives neuswc the Monitor or Client they act on. That way + * entered() gets the client under the pointer directly. + * + * Each toplevel window dmw manages is a Client. A dialog with a managed + * parent starts out floating on its parent's monitor and tags. As in dwm, + * each monitor keeps two lists of the same clients. One gives the layout + * its tiling order, the other remembers focus so focusing a window leaves + * its place in the layout alone. Each tag is one bit. A client is visible + * when it shares a tag with the monitor's current view. + * + * Keys, buttons and rules live in config.h. When a binding runs spawn(), + * the child starts a new session and runs the command. The event loop + * reaps exited children on SIGCHLD so dmw can keep handling windows. + * + * To understand everything else start reading main(). + */ +#include "bar.h" + +#include <errno.h> +#include <fcntl.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <swc.h> +#include <sys/stat.h> +#include <sys/wait.h> +#include <unistd.h> +#include <wayland-server.h> +#include <wld/wld.h> +#include <xkbcommon/xkbcommon-keysyms.h> + +#include "util.h" + +/* macros */ +#define ISVISIBLE(c) ((c)->tags & (c)->mon->tagset[(c)->mon->seltags]) +#define TAGMASK ((1u << LENGTH(tags)) - 1) + +/* enums */ +enum { Button1 = 0x110, Button2 = 0x112, Button3 = 0x111 }; /* keep config.h button names portable across bsd/linux */ +enum { Stacked, Tiled, Fullscreen }; /* window states */ +enum { SchemeNorm, SchemeSel }; /* color schemes */ +enum { ColFg, ColBg, ColBorder }; /* colors */ +enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkClientWin, ClkRootWin }; /* clicks */ + +typedef union { + int i; + unsigned int ui; + float f; + const void *v; +} Arg; + +struct Monitor; +struct Layout { + const char *symbol; + void (*arrange)(struct Monitor *); +}; +struct Rule { + const char *app_id, *title; + unsigned int tags; + int isfloating, monitor; +}; +struct Key { + unsigned int mod, keysym; + void (*func)(const Arg *); + const Arg arg; +}; +struct Button { + unsigned int click, mask, button; + void (*func)(const Arg *); + const Arg arg; +}; +struct Client { + struct swc_window *win; + struct Monitor *mon; + struct Client *next, *snext; + struct wl_event_source *pending; + struct swc_rectangle saved; + unsigned int tags; + int isfloating, isfullscreen, mapped, mode; +}; +struct Monitor { + struct Bar bar; + struct Client *clients, *stack, *sel; + struct Monitor *next; + const struct Layout *lt[2]; + unsigned int seltags, sellt, tagset[2]; + int num, showbar, nmaster; + float mfact; + char ltsymbol[32]; +}; + +/* function declarations */ +static void arrange(struct Monitor *); +static void focus(struct Client *); +static void focusmon(const Arg *), focusstack(const Arg *), incnmaster(const Arg *); +static void killclient(const Arg *), movemouse(const Arg *), quit(const Arg *); +static void resizemouse(const Arg *), setlayout(const Arg *), setmfact(const Arg *); +static void spawn(const Arg *), tag(const Arg *), tagmon(const Arg *), togglebar(const Arg *); +static void togglefloating(const Arg *), togglefullscreen(const Arg *), toggletag(const Arg *); +static void toggleview(const Arg *), view(const Arg *), zoom(const Arg *); +static void monocle(struct Monitor *), tile(struct Monitor *); + +/* configuration */ +#include "config.h" + +/* compile-time check if all tags fit into an unsigned int bit array. */ +struct NumTags { char limitexceeded[LENGTH(tags) > 31 ? -1 : 1]; }; + +/* global vars */ +static struct Monitor *mons, *selmon; +static int shutting_down; +static struct wl_display *display; +static struct wl_event_loop *loop; +static uint32_t scheme[2][3]; +static char status[256] = "dmw-" VERSION; +static struct { + struct Client *c; + struct wl_event_source *timer; + struct swc_rectangle start; + int x, y, resize, moved; + uint32_t button; +} drag; + +/* function implementations */ +static struct Client * +findclient(struct swc_window *win) +{ + struct Monitor *m; + struct Client *c; + + for (m = mons; m; m = m->next) + for (c = m->clients; c; c = c->next) + if (c->win == win) + return c; + return NULL; +} + +static struct Client * +nexttiled(struct Client *c) +{ + for (; c && (c->isfloating || c->isfullscreen || !ISVISIBLE(c)); c = c->next); + return c; +} + +static void +detach(struct Client *c) +{ + struct Client **p; + + for (p = &c->mon->clients; *p != c; p = &(*p)->next); + *p = c->next; + for (p = &c->mon->stack; *p != c; p = &(*p)->snext); + *p = c->snext; + if (c->mon->sel == c) + c->mon->sel = NULL; +} + +static void +attach(struct Client *c, struct Monitor *m) +{ + c->mon = m; + c->next = m->clients; + m->clients = c; + c->snext = m->stack; + m->stack = c; +} + +static void +drawbar(struct Monitor *m) +{ + bar_update(&m->bar, m->showbar && !(m->sel && m->sel->isfullscreen)); +} + +static void +restack(struct Monitor *m) +{ + struct Client *c = m->sel; + + if (!c || !ISVISIBLE(c)) + return; + if (c->mode != Tiled || m->lt[m->sellt]->arrange == monocle) { + swc_window_raise(c->win); + if (c->mode == Tiled) + for (c = m->stack; c; c = c->snext) + if (c->isfloating && ISVISIBLE(c)) + swc_window_raise(c->win); + } +} + +static void +focus(struct Client *c) +{ + struct Client **p; + struct Monitor *m; + + if (!selmon) + return; + if (!c || !ISVISIBLE(c)) + for (c = selmon->stack; c && !ISVISIBLE(c); c = c->snext); + if (c) { + selmon = c->mon; + for (p = &selmon->stack; *p != c; p = &(*p)->snext); + *p = c->snext; + c->snext = selmon->stack; + selmon->stack = c; + } + selmon->sel = c; + restack(selmon); + swc_window_focus(c ? c->win : NULL); + for (m = mons; m; m = m->next) { + struct Client *i; + for (i = m->clients; i; i = i->next) + swc_window_set_border(i->win, scheme[i == c][ColBorder], + i->isfullscreen ? 0 : borderpx, 0, 0); + drawbar(m); + } +} + +static int +dimension(int value, unsigned int min, unsigned int max) +{ + value = MAX(value, (int)barfont->height + 2); + if (min && (unsigned int)value < min) + value = min; + if (max && (unsigned int)value > max) + value = MAX(min, max); + return value; +} + +static int +place(struct Client *c, int x, int y, int w, int h) +{ + struct swc_rectangle g = { x + borderpx, y + borderpx, + dimension(w - 2 * (int)borderpx, c->win->min_width, c->win->max_width), + dimension(h - 2 * (int)borderpx, c->win->min_height, c->win->max_height) }; + + swc_window_set_geometry(c->win, &g); + return g.height + 2 * borderpx; +} + +static void +tile(struct Monitor *m) +{ + struct swc_rectangle g = m->bar.screen->usable_geometry; + struct Client *c; + int i, n, h, mw, my, ty; + + for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++); + mw = n <= m->nmaster ? g.width : m->nmaster ? g.width * m->mfact : 0; + for (i = my = ty = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++) { + if (i < m->nmaster) { + h = place(c, g.x, g.y + my, mw, ((int)g.height - my) / (MIN(n, m->nmaster) - i)); + if (my + h < (int)g.height) + my += h; + } else { + h = place(c, g.x + mw, g.y + ty, g.width - mw, ((int)g.height - ty) / (n - i)); + if (ty + h < (int)g.height) + ty += h; + } + } +} + +static void +monocle(struct Monitor *m) +{ + struct swc_rectangle g = m->bar.screen->usable_geometry; + struct Client *c; + int n = 0; + + for (c = m->clients; c; c = c->next) + if (ISVISIBLE(c)) + n++; + if (n) + snprintf(m->ltsymbol, sizeof m->ltsymbol, "[%d]", n); + for (c = nexttiled(m->clients); c; c = nexttiled(c->next)) + place(c, g.x, g.y, g.width, g.height); +} + +static void +arrange(struct Monitor *m) +{ + const struct Layout *lt = m->lt[m->sellt]; + struct Client *c; + int mode; + + if (!m->sel || !ISVISIBLE(m->sel)) + for (m->sel = m->stack; m->sel && !ISVISIBLE(m->sel); m->sel = m->sel->snext); + for (c = m->clients; c; c = c->next) { + mode = c->isfullscreen ? Fullscreen : lt->arrange && !c->isfloating ? Tiled : Stacked; + if (mode != c->mode) { + if (mode == Fullscreen) + swc_window_set_fullscreen(c->win, m->bar.screen); + else if (mode == Tiled) + swc_window_set_tiled(c->win); + else + swc_window_set_stacked(c->win); + c->mode = mode; + } + if (ISVISIBLE(c)) { + swc_window_show(c->win); + if (c->isfullscreen) + swc_window_set_geometry(c->win, &m->bar.screen->geometry); + } else + swc_window_hide(c->win); + } + snprintf(m->ltsymbol, sizeof m->ltsymbol, "%s", lt->symbol); + if (lt->arrange) + lt->arrange(m); + restack(m); + drawbar(m); +} + +static struct Monitor * +dirtomon(int dir) +{ + struct Monitor *m; + + if (dir > 0) + return selmon->next ? selmon->next : mons; + for (m = mons; m->next && m->next != selmon; m = m->next); + return m; +} + +static void +focusmon(const Arg *arg) +{ + selmon = dirtomon(arg->i); + focus(NULL); +} + +static void +sendmon(struct Client *c, struct Monitor *m) +{ + struct Monitor *old = c->mon; + + if (m == old) + return; + detach(c); + attach(c, m); + c->tags = m->tagset[m->seltags]; + if (!drag.c) + swc_window_set_position(c->win, m->bar.screen->usable_geometry.x + borderpx, + m->bar.screen->usable_geometry.y + borderpx); + focus(NULL); + arrange(old); + arrange(m); +} + +static void +focusstack(const Arg *arg) +{ + struct Client *c = NULL, *i; + + if (!selmon->sel || (selmon->sel->isfullscreen && lockfullscreen)) + return; + if (arg->i > 0) { + for (c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next); + if (!c) + for (c = selmon->clients; c && !ISVISIBLE(c); c = c->next); + } else { + for (i = selmon->clients; i != selmon->sel; i = i->next) + if (ISVISIBLE(i)) + c = i; + if (!c) + for (; i; i = i->next) + if (ISVISIBLE(i)) + c = i; + } + if (c) + focus(c); +} + +static void +incnmaster(const Arg *arg) +{ + selmon->nmaster = MAX(selmon->nmaster + arg->i, 0); + arrange(selmon); +} + +static void +setlayout(const Arg *arg) +{ + if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt]) + selmon->sellt ^= 1; + if (arg && arg->v) + selmon->lt[selmon->sellt] = arg->v; + arrange(selmon); +} + +static void +setmfact(const Arg *arg) +{ + float f; + + if (!arg || !selmon->lt[selmon->sellt]->arrange) + return; + f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0; + if (f < 0.05 || f > 0.95) + return; + selmon->mfact = f; + arrange(selmon); +} + +static void +tag(const Arg *arg) +{ + if (selmon->sel && arg->ui & TAGMASK) { + selmon->sel->tags = arg->ui & TAGMASK; + focus(NULL); + arrange(selmon); + } +} + +static void +tagmon(const Arg *arg) +{ + if (!selmon->sel || !mons->next) + return; + sendmon(selmon->sel, dirtomon(arg->i)); +} + +static void +toggletag(const Arg *arg) +{ + unsigned int newtags; + + if (!selmon->sel) + return; + newtags = selmon->sel->tags ^ (arg->ui & TAGMASK); + if (newtags) { + selmon->sel->tags = newtags; + focus(NULL); + arrange(selmon); + } +} + +static void +toggleview(const Arg *arg) +{ + unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK); + + if (newtagset) { + selmon->tagset[selmon->seltags] = newtagset; + focus(NULL); + arrange(selmon); + } +} + +static void +view(const Arg *arg) +{ + if ((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags]) + return; + selmon->seltags ^= 1; /* toggle sel tagset */ + if (arg->ui & TAGMASK) + selmon->tagset[selmon->seltags] = arg->ui & TAGMASK; + focus(NULL); + arrange(selmon); +} + +static void +zoom(const Arg *arg) +{ + struct Client *c = selmon->sel; + + if (!selmon->lt[selmon->sellt]->arrange || !c || c->isfloating || c->isfullscreen) + return; + if (c == nexttiled(selmon->clients) && !(c = nexttiled(c->next))) + return; + detach(c); + attach(c, selmon); + focus(c); + arrange(selmon); +} + +static int +fixed(struct Client *c) +{ + return c->win->min_width && c->win->min_height && + c->win->min_width == c->win->max_width && + c->win->min_height == c->win->max_height; +} + +static void +setfullscreen(void *data, bool on) +{ + struct Client *c = data; + + if (c->isfullscreen == on) + return; + if (on) + swc_window_get_geometry(c->win, &c->saved); + c->isfullscreen = on; + arrange(c->mon); + if (!on && c->mode == Stacked && c->saved.width && c->saved.height) + swc_window_set_geometry(c->win, &c->saved); + swc_window_set_border(c->win, scheme[c->mon == selmon && selmon->sel == c][ColBorder], + on ? 0 : borderpx, 0, 0); +} + +static void +togglefullscreen(const Arg *arg) +{ + if (selmon->sel) + setfullscreen(selmon->sel, !selmon->sel->isfullscreen); +} + +static void +togglefloating(const Arg *arg) +{ + struct Client *c = selmon->sel; + if (c && !c->isfullscreen) { + c->isfloating = !c->isfloating || fixed(c); + arrange(selmon); + } +} + +static void +togglebar(const Arg *arg) +{ + selmon->showbar = !selmon->showbar; + drawbar(selmon); +} + +static void +killclient(const Arg *arg) +{ + if (selmon->sel) + swc_window_close(selmon->sel->win); +} + +static void +quit(const Arg *arg) +{ + wl_display_terminate(display); +} + +static void +spawn(const Arg *arg) +{ + char *const *cmd = arg->v; + pid_t pid; + sigset_t mask; + + if ((pid = fork()) < 0) { + perror("dmw: fork"); + return; + } + if (pid == 0) { + setsid(); + sigemptyset(&mask); + sigprocmask(SIG_SETMASK, &mask, NULL); + if (!isatty(STDIN_FILENO)) { + int fd = open("/dev/null", O_RDONLY); + if (fd >= 0 && fd != STDIN_FILENO) { + dup2(fd, STDIN_FILENO); + close(fd); + } + } + execvp(cmd[0], cmd); + perror(cmd[0]); + _exit(127); + } +} + +static void +pointerpos(int *x, int *y) +{ + int32_t fx, fy; + + swc_cursor_position(&fx, &fy); + *x = wl_fixed_to_int(fx); + *y = wl_fixed_to_int(fy); +} + +static struct Monitor * +pointmon(int x, int y) +{ + struct Monitor *m; + struct swc_rectangle g; + + for (m = mons; m; m = m->next) { + g = m->bar.screen->geometry; + if (x >= g.x && y >= g.y && x - g.x < (int)g.width && y - g.y < (int)g.height) + return m; + } + return selmon; +} + +static int +dragmotion(void *data) +{ + struct Client *c = drag.c; + struct swc_rectangle g = drag.start, area; + int x, y, dx, dy, right, bottom; + + if (!c || c->isfullscreen || !ISVISIBLE(c)) + return 0; + pointerpos(&x, &y); + area = pointmon(x, y)->bar.screen->usable_geometry; + dx = x - drag.x; + dy = y - drag.y; + if (!drag.moved && c->mode == Tiled && MAX(abs(dx), abs(dy)) <= (int)snap) + goto next; + if (!drag.moved && (dx || dy)) { + if (c->mode == Tiled) { + c->isfloating = 1; + arrange(c->mon); + } + drag.moved = 1; + } + if (!drag.moved) + goto next; + if (drag.resize) { + g.width = dimension((int)g.width + dx, c->win->min_width, c->win->max_width); + g.height = dimension((int)g.height + dy, c->win->min_height, c->win->max_height); + swc_window_set_size(c->win, g.width, g.height); + } else { + g.x += dx; + g.y += dy; + right = area.x + (int)area.width - borderpx - g.width; + bottom = area.y + (int)area.height - borderpx - g.height; + if (abs(g.x - area.x - (int)borderpx) < (int)snap) + g.x = area.x + borderpx; + else if (abs(g.x - right) < (int)snap) + g.x = right; + if (abs(g.y - area.y - (int)borderpx) < (int)snap) + g.y = area.y + borderpx; + else if (abs(g.y - bottom) < (int)snap) + g.y = bottom; + swc_window_set_position(c->win, g.x, g.y); + } +next: + wl_event_source_timer_update(drag.timer, MAX(1, 1000 / MAX(1, refreshrate))); + return 0; +} + +static void +startdrag(int resize) +{ + struct Client *c = selmon->sel; + if (drag.c || !c || c->isfullscreen || !swc_window_get_geometry(c->win, &drag.start)) + return; + drag.c = c; + drag.resize = resize; + drag.moved = 0; + pointerpos(&drag.x, &drag.y); + dragmotion(NULL); +} + +static void +movemouse(const Arg *arg) +{ + startdrag(0); +} + +static void +resizemouse(const Arg *arg) +{ + startdrag(1); +} + +struct Bar * +bar_for_screen(struct swc_screen *screen) +{ + struct Monitor *m; + + for (m = mons; m; m = m->next) + if (m->bar.screen == screen) + return &m->bar; + return NULL; +} + +static int +label(struct wld_renderer *r, int x, int w, int pad, const char *s, int selected, int box, int filled) +{ + int h = barfont->height + 2; + int size = MAX(2, h / 6); + uint32_t *col = scheme[selected]; + + if (r && w > 0) { + wld_set_clip(r, x, 0, w, h); + wld_fill_rectangle(r, col[ColBg], x, 0, w, h); + wld_draw_text(r, barfont, col[ColFg], x + pad, + (h - (int)barfont->height) / 2 + barfont->ascent, s, -1, NULL); + if (box) { + wld_fill_rectangle(r, col[ColFg], x + 1, 1, size, size); + if (!filled && size > 2) + wld_fill_rectangle(r, col[ColBg], x + 2, 2, size - 2, size - 2); + } + } + return x + w; +} + +static unsigned int +baritems(struct Monitor *m, struct wld_renderer *r, int px, Arg *arg) +{ + struct Client *c; + unsigned int i, occ = 0, bit; + int x = 0, w = m->bar.width, end, pad = barfont->height; + + for (c = m->clients; c; c = c->next) + occ |= c->tags; + for (i = 0; i < LENGTH(tags); i++) { + bit = 1u << i; + x = label(r, x, textwidth(tags[i]) + pad, pad / 2, tags[i], !!(m->tagset[m->seltags] & bit), + occ & bit, m == selmon && m->sel && (m->sel->tags & bit)); + if (px >= 0 && px < x) { + arg->ui = bit; + return ClkTagBar; + } + } + x = label(r, x, textwidth(m->ltsymbol) + pad, pad / 2, m->ltsymbol, 0, 0, 0); + if (px >= 0 && px < x) + return ClkLtSymbol; + end = m == selmon ? MAX(x, w - textwidth(status) - 2) : w; + c = m->sel; + label(r, x, end - x, pad / 2, c && c->win->title ? c->win->title : "", + m == selmon && c, c && c->isfloating, c && fixed(c)); + if (end < w) + label(r, end, w - end, 0, status, 0, 0, 0); + return px >= end ? ClkStatusText : ClkWinTitle; +} + +void +bar_paint(struct Bar *bar, struct wld_renderer *r) +{ + struct Monitor *m = wl_container_of(bar, m, bar); + baritems(m, r, -1, NULL); +} + +static void +click(unsigned int region, unsigned int mask, unsigned int button, const Arg *tagarg) +{ + size_t i; + for (i = 0; i < LENGTH(buttons); i++) { + const struct Button *b = &buttons[i]; + if (b->click == region && b->mask == mask && b->button == button && b->func) + b->func(region == ClkTagBar && !b->arg.ui ? tagarg : &b->arg); + } +} + +static void +clickbar(struct Monitor *m, int x, unsigned int mask, unsigned int button) +{ + Arg arg = {0}; + unsigned int region; + + if (selmon != m) { + selmon = m; + focus(NULL); + } + region = baritems(m, NULL, x, &arg); + click(region, mask, button, &arg); +} + +void +bar_click(struct Bar *bar, int x, uint32_t button) +{ + struct Monitor *m = wl_container_of(bar, m, bar); + clickbar(m, x, 0, button); +} + +static void +buttonbinding(void *data, uint32_t time, uint32_t button, uint32_t state) +{ + const struct Button *binding = data; + struct Client *c; + struct Monitor *m; + struct swc_rectangle g; + int x, y, by; + + pointerpos(&x, &y); + m = pointmon(x, y); + if (!state) { + if (drag.c && button == drag.button) { + c = drag.c; + dragmotion(NULL); + if (drag.moved && m != c->mon) { + sendmon(c, m); + focus(c); + } + drag.c = NULL; + } + return; + } + if (!m) + return; + g = m->bar.screen->geometry; + by = topbar ? g.y : g.y + (int)g.height - m->bar.height; + if (m->bar.shown && y >= by && y < by + m->bar.height) { + clickbar(m, x - g.x, binding->mask, button); + return; + } + c = findclient(swc_window_at(x, y)); + if (c) + focus(c); + if (!drag.c) + drag.button = button; + click(c ? ClkClientWin : ClkRootWin, binding->mask, button, NULL); +} + +static void +keybinding(void *data, uint32_t time, uint32_t key, uint32_t state) +{ + const struct Key *k = data; + if (state && selmon && k->func) + k->func(&k->arg); +} + +static void +bindings(void) +{ + size_t i, j; + for (i = 0; i < LENGTH(keys); i++) + if (swc_add_binding(SWC_BINDING_KEY, keys[i].mod, keys[i].keysym, keybinding, (void *)&keys[i]) < 0) + die("dmw: cannot bind keysym %#x", keys[i].keysym); + for (i = 0; i < LENGTH(buttons); i++) { + if (!buttons[i].mask && buttons[i].click < ClkClientWin) + continue; + for (j = 0; j < i; j++) + if (buttons[j].mask == buttons[i].mask && buttons[j].button == buttons[i].button && + (buttons[j].mask || buttons[j].click >= ClkClientWin)) + break; + if (j == i && swc_add_binding(SWC_BINDING_BUTTON, buttons[i].mask, buttons[i].button, + buttonbinding, (void *)&buttons[i]) < 0) + die("dmw: cannot bind button %u", buttons[i].button); + } +} + +static void +applyrules(struct Client *c) +{ + struct Monitor *m, *target = c->mon; + struct Client *parent = findclient(c->win->parent); + const struct Rule *r; + unsigned int mask = 0; + + if (parent) { + target = parent->mon; + mask = parent->tags; + c->isfloating = 1; + } else { + for (r = rules; r < rules + LENGTH(rules); r++) { + if ((r->title && (!c->win->title || !strstr(c->win->title, r->title))) || + (r->app_id && (!c->win->app_id || !strstr(c->win->app_id, r->app_id)))) + continue; + c->isfloating = r->isfloating; + mask |= r->tags; + for (m = mons; m; m = m->next) + if (m->num == r->monitor) + target = m; + } + } + if (target != c->mon) { + m = c->mon; + detach(c); + attach(c, target); + arrange(m); + } + c->tags = mask & TAGMASK ? mask & TAGMASK : target->tagset[target->seltags]; + c->isfloating |= fixed(c); +} + +static void +manage(void *data) +{ + struct Client *c = data; + struct swc_rectangle g; + + c->pending = NULL; + applyrules(c); + g = c->mon->bar.screen->usable_geometry; + swc_window_set_border(c->win, scheme[SchemeNorm][ColBorder], c->isfullscreen ? 0 : borderpx, 0, 0); + swc_window_set_position(c->win, g.x + borderpx, g.y + borderpx); + if (c->mon == selmon && ISVISIBLE(c)) + focus(c); + else if (ISVISIBLE(c)) + c->mon->sel = c; + arrange(c->mon); +} + +static void +parentchanged(void *data) +{ + struct Client *c = data; + + if (!c->pending && c->win->parent) { + applyrules(c); + arrange(c->mon); + focus(NULL); + } +} + +static void +metadatachanged(void *data) +{ + struct Client *c = data; + + if (!c->pending && !c->mapped) { + applyrules(c); + if (c->mon == selmon) + focus(ISVISIBLE(c) ? c : NULL); + arrange(c->mon); + } else + drawbar(c->mon); +} + +static void +sizechanged(void *data) +{ + struct Client *c = data; + struct swc_rectangle g; + + if (!c->mapped && swc_window_get_geometry(c->win, &g) && g.width && g.height) { + c->mapped = 1; + if (fixed(c) && !c->isfloating) { + c->isfloating = 1; + arrange(c->mon); + } + } +} + +static void +entered(void *data) +{ + struct Client *c = data; + if (!drag.c && !c->pending && ISVISIBLE(c) && (c->mon != selmon || selmon->sel != c)) + focus(c); +} + +static void +unmanage(void *data) +{ + struct Client *c = data; + struct Monitor *m = c->mon; + + if (drag.c == c) + drag.c = NULL; + if (c->pending) + wl_event_source_remove(c->pending); + detach(c); + free(c); + if (shutting_down) + return; + if (m == selmon) + focus(NULL); + arrange(m); +} + +static void +newwindow(struct swc_window *win) +{ + static const struct swc_window_handler handler = { + .destroy = unmanage, .entered = entered, .title_changed = metadatachanged, + .app_id_changed = metadatachanged, .parent_changed = parentchanged, + .size_changed = sizechanged, + }; + struct Client *c; + + if (!selmon) + return; + c = ecalloc(1, sizeof *c); + c->win = win; + c->mode = -1; + attach(c, selmon); + swc_window_set_handler(win, &handler, c); +#ifdef SWC_WINDOW_FULLSCREEN_REQUEST + swc_window_set_fullscreen_handler(win, setfullscreen); +#endif + win->motion_throttle_ms = 1000 / MAX(1, refreshrate); + /* wait for the title and app id before matching rules for a new toplevel: */ + c->pending = wl_event_loop_add_idle(loop, manage, c); + if (!c->pending) + die("dmw: scheduling new window:"); +} + +static void +screenentered(void *data) +{ + if (selmon != data && !drag.c) { + selmon = data; + focus(NULL); + } +} + +static void +screenchanged(void *data) +{ + struct Monitor *m = data; + struct swc_rectangle area = m->bar.screen->usable_geometry, g; + struct Client *c; + int x, y; + + for (c = m->clients; c; c = c->next) { + if (c->mode != Stacked || !swc_window_get_geometry(c->win, &g)) + continue; + x = area.x + (int)borderpx; + y = area.y + (int)borderpx; + swc_window_set_position(c->win, + MAX(x, MIN(g.x, area.x + (int)area.width - (int)g.width - (int)borderpx)), + MAX(y, MIN(g.y, area.y + (int)area.height - (int)g.height - (int)borderpx))); + } + arrange(m); +} + +static void +screenclosed(void *data) +{ + struct Monitor *m = data, **p; + struct Client *c; + + for (p = &mons; *p != m; p = &(*p)->next); + *p = m->next; + if (selmon == m) + selmon = mons; + while ((c = m->clients) && mons) { + detach(c); + attach(c, mons); + c->tags = mons->tagset[mons->seltags]; + } + if (c) + die("dmw: last output removed"); + bar_close(&m->bar); + free(m); + if (mons && !shutting_down) { + arrange(mons); + focus(NULL); + } +} + +static void +newscreen(struct swc_screen *screen) +{ + static const struct swc_screen_handler handler = { + .destroy = screenclosed, .entered = screenentered, + .geometry_changed = screenchanged, .usable_geometry_changed = screenchanged, + }; + struct Monitor **p, *m = ecalloc(1, sizeof *m); + + for (p = &mons; *p; p = &(*p)->next) + m->num = (*p)->num + 1; + *p = m; + m->bar.screen = screen; + m->mfact = mfact; + m->nmaster = nmaster; + m->showbar = showbar; + m->tagset[0] = m->tagset[1] = 1; + m->lt[0] = &layouts[0]; + m->lt[1] = &layouts[1 % LENGTH(layouts)]; + if (!selmon) + selmon = m; + swc_screen_set_handler(screen, &handler, m); + arrange(m); +} + +static struct wl_event_source *status_source; + +static int +readstatus(int fd, uint32_t events, void *data) +{ + static char line[sizeof status]; + static size_t len; + struct Monitor *m; + char buf[4096]; + ssize_t i, n; + + n = read(fd, buf, sizeof buf); + if (n < 0 && (errno == EINTR || errno == EAGAIN)) + return 0; + for (i = 0; i < n; i++) { + if (buf[i] == '\n') { + line[len] = '\0'; + memcpy(status, line, len + 1); + len = 0; + } else if (len + 1 < sizeof line) + line[len++] = buf[i]; + } + if (n <= 0) { + if (len) { + line[len] = '\0'; + memcpy(status, line, len + 1); + } + if (status_source) { + wl_event_source_remove(status_source); + status_source = NULL; + } + } + for (m = mons; m; m = m->next) + drawbar(m); + return n > 0; +} + +static int +signalhandler(int sig, void *data) +{ + if (sig == SIGCHLD) + while (waitpid(-1, NULL, WNOHANG) > 0); + else + quit(NULL); + return 0; +} + +int +main(int argc, char **argv) +{ + static const struct swc_manager manager = { .new_screen = newscreen, .new_window = newwindow }; + const char *socket; + struct stat st; + struct wl_event_source *signals[3]; + int i, j, sig[] = { SIGCHLD, SIGTERM, SIGINT }; + + if (argc == 2 && !strcmp(argv[1], "-v")) { + puts("dmw-" VERSION); + return 0; + } + if (argc != 1) + die("usage: dmw [-v]"); + if (!(display = wl_display_create())) + die("dmw: cannot create Wayland display"); + loop = wl_display_get_event_loop(display); + for (i = 0; i < 2; i++) + for (j = 0; j < 3; j++) + if (!wld_lookup_named_color(colors[i][j], &scheme[i][j])) + die("dmw: unknown color %s", colors[i][j]); + if (!swc_initialize(display, loop, &manager)) + die("dmw: cannot initialize neuswc"); + if (!(socket = wl_display_add_socket_auto(display)) || setenv("WAYLAND_DISPLAY", socket, 1) < 0) + die("dmw: cannot publish Wayland socket:"); + unsetenv("WAYLAND_SOCKET"); + bar_init(display, font, topbar); + bindings(); + drag.timer = wl_event_loop_add_timer(loop, dragmotion, NULL); + if (!drag.timer) + die("dmw: cannot create drag timer:"); + for (i = 0; i < 3; i++) + if (!(signals[i] = wl_event_loop_add_signal(loop, sig[i], signalhandler, NULL))) + die("dmw: cannot watch signal:"); + if (!fstat(STDIN_FILENO, &st)) { + if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) { + status_source = wl_event_loop_add_fd(loop, STDIN_FILENO, WL_EVENT_READABLE, readstatus, NULL); + if (!status_source) + die("dmw: cannot watch status input:"); + } else if (S_ISREG(st.st_mode)) + while (readstatus(STDIN_FILENO, 0, NULL)); + } + wl_display_run(display); + shutting_down = 1; + for (struct Monitor *m = mons; m; m = m->next) + bar_close(&m->bar); + bar_finish(); + wl_display_destroy_clients(display); + for (i = 0; i < 3; i++) + wl_event_source_remove(signals[i]); + if (status_source) + wl_event_source_remove(status_source); + wl_event_source_remove(drag.timer); + swc_finalize(); + wl_display_destroy(display); + return 0; +} diff --git a/drw.c b/drw.c @@ -1,471 +0,0 @@ -/* See LICENSE file for copyright and license details. */ -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <X11/Xlib.h> -#include <X11/Xft/Xft.h> - -#include "drw.h" -#include "util.h" - -#define UTF_INVALID 0xFFFD - -static int -utf8decode(const char *s_in, long *u, int *err) -{ - static const unsigned char lens[] = { - /* 0XXXX */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - /* 10XXX */ 0, 0, 0, 0, 0, 0, 0, 0, /* invalid */ - /* 110XX */ 2, 2, 2, 2, - /* 1110X */ 3, 3, - /* 11110 */ 4, - /* 11111 */ 0, /* invalid */ - }; - static const unsigned char leading_mask[] = { 0x7F, 0x1F, 0x0F, 0x07 }; - static const unsigned int overlong[] = { 0x0, 0x80, 0x0800, 0x10000 }; - - const unsigned char *s = (const unsigned char *)s_in; - int len = lens[*s >> 3]; - *u = UTF_INVALID; - *err = 1; - if (len == 0) - return 1; - - long cp = s[0] & leading_mask[len - 1]; - for (int i = 1; i < len; ++i) { - if (s[i] == '\0' || (s[i] & 0xC0) != 0x80) - return i; - cp = (cp << 6) | (s[i] & 0x3F); - } - /* out of range, surrogate, overlong encoding */ - if (cp > 0x10FFFF || (cp >> 11) == 0x1B || cp < overlong[len - 1]) - return len; - - *err = 0; - *u = cp; - return len; -} - -Drw * -drw_create(Display *dpy, int screen, Window root, unsigned int w, unsigned int h) -{ - Drw *drw = ecalloc(1, sizeof(Drw)); - - drw->dpy = dpy; - drw->screen = screen; - drw->root = root; - drw->w = w; - drw->h = h; - drw->drawable = XCreatePixmap(dpy, root, w, h, DefaultDepth(dpy, screen)); - drw->gc = XCreateGC(dpy, root, 0, NULL); - XSetLineAttributes(dpy, drw->gc, 1, LineSolid, CapButt, JoinMiter); - - return drw; -} - -void -drw_resize(Drw *drw, unsigned int w, unsigned int h) -{ - if (!drw) - return; - - drw->w = w; - drw->h = h; - if (drw->drawable) - XFreePixmap(drw->dpy, drw->drawable); - drw->drawable = XCreatePixmap(drw->dpy, drw->root, w, h, DefaultDepth(drw->dpy, drw->screen)); -} - -void -drw_free(Drw *drw) -{ - XFreePixmap(drw->dpy, drw->drawable); - XFreeGC(drw->dpy, drw->gc); - drw_fontset_free(drw->fonts); - free(drw); -} - -/* This function is an implementation detail. Library users should use - * drw_fontset_create instead. - */ -static Fnt * -xfont_create(Drw *drw, const char *fontname, FcPattern *fontpattern) -{ - Fnt *font; - XftFont *xfont = NULL; - FcPattern *pattern = NULL; - - if (fontname) { - /* Using the pattern found at font->xfont->pattern does not yield the - * same substitution results as using the pattern returned by - * FcNameParse; using the latter results in the desired fallback - * behaviour whereas the former just results in missing-character - * rectangles being drawn, at least with some fonts. */ - if (!(xfont = XftFontOpenName(drw->dpy, drw->screen, fontname))) { - fprintf(stderr, "error, cannot load font from name: '%s'\n", fontname); - return NULL; - } - if (!(pattern = FcNameParse((FcChar8 *) fontname))) { - fprintf(stderr, "error, cannot parse font name to pattern: '%s'\n", fontname); - XftFontClose(drw->dpy, xfont); - return NULL; - } - } else if (fontpattern) { - if (!(xfont = XftFontOpenPattern(drw->dpy, fontpattern))) { - fprintf(stderr, "error, cannot load font from pattern.\n"); - return NULL; - } - } else { - die("no font specified."); - } - - font = ecalloc(1, sizeof(Fnt)); - font->xfont = xfont; - font->pattern = pattern; - font->h = xfont->ascent + xfont->descent; - font->dpy = drw->dpy; - - return font; -} - -static void -xfont_free(Fnt *font) -{ - if (!font) - return; - if (font->pattern) - FcPatternDestroy(font->pattern); - XftFontClose(font->dpy, font->xfont); - free(font); -} - -Fnt* -drw_fontset_create(Drw* drw, const char *fonts[], size_t fontcount) -{ - Fnt *cur, *ret = NULL; - size_t i; - - if (!drw || !fonts) - return NULL; - - for (i = 1; i <= fontcount; i++) { - if ((cur = xfont_create(drw, fonts[fontcount - i], NULL))) { - cur->next = ret; - ret = cur; - } - } - return (drw->fonts = ret); -} - -void -drw_fontset_free(Fnt *font) -{ - if (font) { - drw_fontset_free(font->next); - xfont_free(font); - } -} - -void -drw_clr_create(Drw *drw, Clr *dest, const char *clrname) -{ - if (!drw || !dest || !clrname) - return; - - if (!XftColorAllocName(drw->dpy, DefaultVisual(drw->dpy, drw->screen), - DefaultColormap(drw->dpy, drw->screen), - clrname, dest)) - die("error, cannot allocate color '%s'", clrname); -} - -/* Create color schemes. */ -Clr * -drw_scm_create(Drw *drw, const char *clrnames[], size_t clrcount) -{ - size_t i; - Clr *ret; - - /* need at least two colors for a scheme */ - if (!drw || !clrnames || clrcount < 2 || !(ret = ecalloc(clrcount, sizeof(Clr)))) - return NULL; - - for (i = 0; i < clrcount; i++) - drw_clr_create(drw, &ret[i], clrnames[i]); - return ret; -} - -void -drw_clr_free(Drw *drw, Clr *c) -{ - if (!drw || !c) - return; - - /* c is typedef XftColor Clr */ - XftColorFree(drw->dpy, DefaultVisual(drw->dpy, drw->screen), - DefaultColormap(drw->dpy, drw->screen), c); -} - -void -drw_scm_free(Drw *drw, Clr *scm, size_t clrcount) -{ - size_t i; - - if (!drw || !scm) - return; - - for (i = 0; i < clrcount; i++) - drw_clr_free(drw, &scm[i]); - free(scm); -} - -void -drw_setfontset(Drw *drw, Fnt *set) -{ - if (drw) - drw->fonts = set; -} - -void -drw_setscheme(Drw *drw, Clr *scm) -{ - if (drw) - drw->scheme = scm; -} - -void -drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert) -{ - if (!drw || !drw->scheme) - return; - XSetForeground(drw->dpy, drw->gc, invert ? drw->scheme[ColBg].pixel : drw->scheme[ColFg].pixel); - if (filled) - XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h); - else - XDrawRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w - 1, h - 1); -} - -int -drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lpad, const char *text, int invert) -{ - int ty, ellipsis_x = 0; - unsigned int tmpw, ew, ellipsis_w = 0, ellipsis_len, hash, h0, h1; - XftDraw *d = NULL; - Fnt *usedfont, *curfont, *nextfont; - int utf8strlen, utf8charlen, utf8err, render = x || y || w || h; - long utf8codepoint = 0; - const char *utf8str; - FcCharSet *fccharset; - FcPattern *fcpattern; - FcPattern *match; - XftResult result; - int charexists = 0, overflow = 0; - /* keep track of a couple codepoints for which we have no match. */ - static unsigned int nomatches[128], ellipsis_width, invalid_width; - static const char invalid[] = "�"; - - if (!drw || (render && (!drw->scheme || !w)) || !text || !drw->fonts) - return 0; - - if (!render) { - w = invert ? invert : ~invert; - } else { - XSetForeground(drw->dpy, drw->gc, drw->scheme[invert ? ColFg : ColBg].pixel); - XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h); - if (w < lpad) - return x + w; - d = XftDrawCreate(drw->dpy, drw->drawable, - DefaultVisual(drw->dpy, drw->screen), - DefaultColormap(drw->dpy, drw->screen)); - x += lpad; - w -= lpad; - } - - usedfont = drw->fonts; - if (!ellipsis_width && render) - ellipsis_width = drw_fontset_getwidth(drw, "..."); - if (!invalid_width && render) - invalid_width = drw_fontset_getwidth(drw, invalid); - while (1) { - ew = ellipsis_len = utf8err = utf8charlen = utf8strlen = 0; - utf8str = text; - nextfont = NULL; - while (*text) { - utf8charlen = utf8decode(text, &utf8codepoint, &utf8err); - for (curfont = drw->fonts; curfont; curfont = curfont->next) { - charexists = charexists || XftCharExists(drw->dpy, curfont->xfont, utf8codepoint); - if (charexists) { - drw_font_getexts(curfont, text, utf8charlen, &tmpw, NULL); - if (ew + ellipsis_width <= w) { - /* keep track where the ellipsis still fits */ - ellipsis_x = x + ew; - ellipsis_w = w - ew; - ellipsis_len = utf8strlen; - } - - if (ew + tmpw > w) { - overflow = 1; - /* called from drw_fontset_getwidth_clamp(): - * it wants the width AFTER the overflow - */ - if (!render) - x += tmpw; - else - utf8strlen = ellipsis_len; - } else if (curfont == usedfont) { - text += utf8charlen; - utf8strlen += utf8err ? 0 : utf8charlen; - ew += utf8err ? 0 : tmpw; - } else { - nextfont = curfont; - } - break; - } - } - - if (overflow || !charexists || nextfont || utf8err) - break; - else - charexists = 0; - } - - if (utf8strlen) { - if (render) { - ty = y + (h - usedfont->h) / 2 + usedfont->xfont->ascent; - XftDrawStringUtf8(d, &drw->scheme[invert ? ColBg : ColFg], - usedfont->xfont, x, ty, (XftChar8 *)utf8str, utf8strlen); - } - x += ew; - w -= ew; - } - if (utf8err && (!render || invalid_width < w)) { - if (render) - drw_text(drw, x, y, w, h, 0, invalid, invert); - x += invalid_width; - w -= invalid_width; - } - if (render && overflow) - drw_text(drw, ellipsis_x, y, ellipsis_w, h, 0, "...", invert); - - if (!*text || overflow) { - break; - } else if (nextfont) { - charexists = 0; - usedfont = nextfont; - } else { - /* Regardless of whether or not a fallback font is found, the - * character must be drawn. */ - charexists = 1; - - hash = (unsigned int)utf8codepoint; - hash = ((hash >> 16) ^ hash) * 0x21F0AAAD; - hash = ((hash >> 15) ^ hash) * 0xD35A2D97; - h0 = ((hash >> 15) ^ hash) % LENGTH(nomatches); - h1 = (hash >> 17) % LENGTH(nomatches); - /* avoid expensive XftFontMatch call when we know we won't find a match */ - if (nomatches[h0] == utf8codepoint || nomatches[h1] == utf8codepoint) - goto no_match; - - fccharset = FcCharSetCreate(); - FcCharSetAddChar(fccharset, utf8codepoint); - - if (!drw->fonts->pattern) { - /* Refer to the comment in xfont_create for more information. */ - die("the first font in the cache must be loaded from a font string."); - } - - fcpattern = FcPatternDuplicate(drw->fonts->pattern); - FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset); - FcPatternAddBool(fcpattern, FC_SCALABLE, FcTrue); - - FcConfigSubstitute(NULL, fcpattern, FcMatchPattern); - FcDefaultSubstitute(fcpattern); - match = XftFontMatch(drw->dpy, drw->screen, fcpattern, &result); - - FcCharSetDestroy(fccharset); - FcPatternDestroy(fcpattern); - - if (match) { - usedfont = xfont_create(drw, NULL, match); - if (usedfont && XftCharExists(drw->dpy, usedfont->xfont, utf8codepoint)) { - for (curfont = drw->fonts; curfont->next; curfont = curfont->next) - ; /* NOP */ - curfont->next = usedfont; - } else { - xfont_free(usedfont); - nomatches[nomatches[h0] ? h1 : h0] = utf8codepoint; -no_match: - usedfont = drw->fonts; - } - } - } - } - if (d) - XftDrawDestroy(d); - - return x + (render ? w : 0); -} - -void -drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h) -{ - if (!drw) - return; - - XCopyArea(drw->dpy, drw->drawable, win, drw->gc, x, y, w, h, x, y); - XSync(drw->dpy, False); -} - -unsigned int -drw_fontset_getwidth(Drw *drw, const char *text) -{ - if (!drw || !drw->fonts || !text) - return 0; - return drw_text(drw, 0, 0, 0, 0, 0, text, 0); -} - -unsigned int -drw_fontset_getwidth_clamp(Drw *drw, const char *text, unsigned int n) -{ - unsigned int tmp = 0; - if (drw && drw->fonts && text && n) - tmp = drw_text(drw, 0, 0, 0, 0, 0, text, n); - return MIN(n, tmp); -} - -void -drw_font_getexts(Fnt *font, const char *text, unsigned int len, unsigned int *w, unsigned int *h) -{ - XGlyphInfo ext; - - if (!font || !text) - return; - - XftTextExtentsUtf8(font->dpy, font->xfont, (XftChar8 *)text, len, &ext); - if (w) - *w = ext.xOff; - if (h) - *h = font->h; -} - -Cur * -drw_cur_create(Drw *drw, int shape) -{ - Cur *cur; - - if (!drw || !(cur = ecalloc(1, sizeof(Cur)))) - return NULL; - - cur->cursor = XCreateFontCursor(drw->dpy, shape); - - return cur; -} - -void -drw_cur_free(Drw *drw, Cur *cursor) -{ - if (!cursor) - return; - - XFreeCursor(drw->dpy, cursor->cursor); - free(cursor); -} diff --git a/drw.h b/drw.h @@ -1,60 +0,0 @@ -/* See LICENSE file for copyright and license details. */ - -typedef struct { - Cursor cursor; -} Cur; - -typedef struct Fnt { - Display *dpy; - unsigned int h; - XftFont *xfont; - FcPattern *pattern; - struct Fnt *next; -} Fnt; - -enum { ColFg, ColBg, ColBorder }; /* Clr scheme index */ -typedef XftColor Clr; - -typedef struct { - unsigned int w, h; - Display *dpy; - int screen; - Window root; - Drawable drawable; - GC gc; - Clr *scheme; - Fnt *fonts; -} Drw; - -/* Drawable abstraction */ -Drw *drw_create(Display *dpy, int screen, Window win, unsigned int w, unsigned int h); -void drw_resize(Drw *drw, unsigned int w, unsigned int h); -void drw_free(Drw *drw); - -/* Fnt abstraction */ -Fnt *drw_fontset_create(Drw* drw, const char *fonts[], size_t fontcount); -void drw_fontset_free(Fnt* set); -unsigned int drw_fontset_getwidth(Drw *drw, const char *text); -unsigned int drw_fontset_getwidth_clamp(Drw *drw, const char *text, unsigned int n); -void drw_font_getexts(Fnt *font, const char *text, unsigned int len, unsigned int *w, unsigned int *h); - -/* Colorscheme abstraction */ -void drw_clr_create(Drw *drw, Clr *dest, const char *clrname); -void drw_clr_free(Drw *drw, Clr *c); -Clr *drw_scm_create(Drw *drw, const char *clrnames[], size_t clrcount); -void drw_scm_free(Drw *drw, Clr *scm, size_t clrcount); - -/* Cursor abstraction */ -Cur *drw_cur_create(Drw *drw, int shape); -void drw_cur_free(Drw *drw, Cur *cursor); - -/* Drawing context manipulation */ -void drw_setfontset(Drw *drw, Fnt *set); -void drw_setscheme(Drw *drw, Clr *scm); - -/* Drawing functions */ -void drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert); -int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lpad, const char *text, int invert); - -/* Map functions */ -void drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h); diff --git a/dwm.1 b/dwm.1 @@ -1,176 +0,0 @@ -.TH DWM 1 dwm\-VERSION -.SH NAME -dwm \- dynamic window manager -.SH SYNOPSIS -.B dwm -.RB [ \-v ] -.SH DESCRIPTION -dwm is a dynamic window manager for X. It manages windows in tiled, monocle -and floating layouts. Either layout can be applied dynamically, optimising the -environment for the application in use and the task performed. -.P -In tiled layouts windows are managed in a master and stacking area. The master -area on the left contains one window by default, and the stacking area on the -right contains all other windows. The number of master area windows can be -adjusted from zero to an arbitrary number. In monocle layout all windows are -maximised to the screen size. In floating layout windows can be resized and -moved freely. Dialog windows are always managed floating, regardless of the -layout applied. -.P -Windows are grouped by tags. Each window can be tagged with one or multiple -tags. Selecting certain tags displays all windows with these tags. -.P -Each screen contains a small status bar which displays all available tags, the -layout, the title of the focused window, and the text read from the root window -name property, if the screen is focused. A floating window is indicated with an -empty square and a maximised floating window is indicated with a filled square -before the windows title. The selected tags are indicated with a different -color. The tags of the focused window are indicated with a filled square in the -top left corner. The tags which are applied to one or more windows are -indicated with an empty square in the top left corner. -.P -dwm draws a small border around windows to indicate the focus state. -.SH OPTIONS -.TP -.B \-v -prints version information to stderr, then exits. -.SH USAGE -.SS Status bar -.TP -.B X root window name -is read and displayed in the status text area. It can be set with the -.BR xsetroot (1) -command. -.TP -.B Button1 -click on a tag label to display all windows with that tag, click on the layout -label toggles between tiled and floating layout. -.TP -.B Button3 -click on a tag label adds/removes all windows with that tag to/from the view. -.TP -.B Mod1\-Button1 -click on a tag label applies that tag to the focused window. -.TP -.B Mod1\-Button3 -click on a tag label adds/removes that tag to/from the focused window. -.SS Keyboard commands -.TP -.B Mod1\-Shift\-Return -Start -.BR st(1). -.TP -.B Mod1\-p -Spawn -.BR dmenu(1) -for launching other programs. -.TP -.B Mod1\-, -Focus previous screen, if any. -.TP -.B Mod1\-. -Focus next screen, if any. -.TP -.B Mod1\-Shift\-, -Send focused window to previous screen, if any. -.TP -.B Mod1\-Shift\-. -Send focused window to next screen, if any. -.TP -.B Mod1\-b -Toggles bar on and off. -.TP -.B Mod1\-t -Sets tiled layout. -.TP -.B Mod1\-f -Sets floating layout. -.TP -.B Mod1\-m -Sets monocle layout. -.TP -.B Mod1\-space -Toggles between current and previous layout. -.TP -.B Mod1\-j -Focus next window. -.TP -.B Mod1\-k -Focus previous window. -.TP -.B Mod1\-i -Increase number of windows in master area. -.TP -.B Mod1\-d -Decrease number of windows in master area. -.TP -.B Mod1\-l -Increase master area size. -.TP -.B Mod1\-h -Decrease master area size. -.TP -.B Mod1\-Return -Zooms/cycles focused window to/from master area (tiled layouts only). -.TP -.B Mod1\-Shift\-c -Close focused window. -.TP -.B Mod1\-Shift\-space -Toggle focused window between tiled and floating state. -.TP -.B Mod1\-Tab -Toggles to the previously selected tags. -.TP -.B Mod1\-Shift\-[1..n] -Apply nth tag to focused window. -.TP -.B Mod1\-Shift\-0 -Apply all tags to focused window. -.TP -.B Mod1\-Control\-Shift\-[1..n] -Add/remove nth tag to/from focused window. -.TP -.B Mod1\-[1..n] -View all windows with nth tag. -.TP -.B Mod1\-0 -View all windows with any tag. -.TP -.B Mod1\-Control\-[1..n] -Add/remove all windows with nth tag to/from the view. -.TP -.B Mod1\-Shift\-q -Quit dwm. -.SS Mouse commands -.TP -.B Mod1\-Button1 -Move focused window while dragging. Tiled windows will be toggled to the floating state. -.TP -.B Mod1\-Button2 -Toggles focused window between floating and tiled state. -.TP -.B Mod1\-Button3 -Resize focused window while dragging. Tiled windows will be toggled to the floating state. -.SH CUSTOMIZATION -dwm is customized by creating a custom config.h and (re)compiling the source -code. This keeps it fast, secure and simple. -.SH SEE ALSO -.BR dmenu (1), -.BR st (1) -.SH ISSUES -Java applications which use the XToolkit/XAWT backend may draw grey windows -only. The XToolkit/XAWT backend breaks ICCCM-compliance in recent JDK 1.5 and early -JDK 1.6 versions, because it assumes a reparenting window manager. Possible workarounds -are using JDK 1.4 (which doesn't contain the XToolkit/XAWT backend) or setting the -environment variable -.BR AWT_TOOLKIT=MToolkit -(to use the older Motif backend instead) or running -.B xprop -root -f _NET_WM_NAME 32a -set _NET_WM_NAME LG3D -or -.B wmname LG3D -(to pretend that a non-reparenting window manager is running that the -XToolkit/XAWT backend can recognize) or when using OpenJDK setting the environment variable -.BR _JAVA_AWT_WM_NONREPARENTING=1 . -.SH BUGS -Send all bug reports with a patch to hackers@suckless.org. diff --git a/dwm.c b/dwm.c @@ -1,2175 +0,0 @@ -/* See LICENSE file for copyright and license details. - * - * dynamic window manager is designed like any other X client as well. It is - * driven through handling X events. In contrast to other X clients, a window - * manager selects for SubstructureRedirectMask on the root window, to receive - * events about window (dis-)appearance. Only one X connection at a time is - * allowed to select for this event mask. - * - * The event handlers of dwm are organized in an array which is accessed - * whenever a new event has been fetched. This allows event dispatching - * in O(1) time. - * - * Each child of the root window is called a client, except windows which have - * set the override_redirect flag. Clients are organized in a linked client - * list on each monitor, the focus history is remembered through a stack list - * on each monitor. Each client contains a bit array to indicate the tags of a - * client. - * - * Keys and tagging rules are organized as arrays and defined in config.h. - * - * To understand everything else, start reading main(). - */ -#include <errno.h> -#include <locale.h> -#include <signal.h> -#include <stdarg.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> -#include <sys/types.h> -#include <sys/wait.h> -#include <X11/cursorfont.h> -#include <X11/keysym.h> -#include <X11/Xatom.h> -#include <X11/Xlib.h> -#include <X11/Xproto.h> -#include <X11/Xutil.h> -#ifdef XINERAMA -#include <X11/extensions/Xinerama.h> -#endif /* XINERAMA */ -#include <X11/Xft/Xft.h> - -#include "drw.h" -#include "util.h" - -/* macros */ -#define BUTTONMASK (ButtonPressMask|ButtonReleaseMask) -#define CLEANMASK(mask) (mask & ~(numlockmask|LockMask) & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask)) -#define INTERSECT(x,y,w,h,m) (MAX(0, MIN((x)+(w),(m)->wx+(m)->ww) - MAX((x),(m)->wx)) \ - * MAX(0, MIN((y)+(h),(m)->wy+(m)->wh) - MAX((y),(m)->wy))) -#define ISVISIBLE(C) ((C->tags & C->mon->tagset[C->mon->seltags])) -#define MOUSEMASK (BUTTONMASK|PointerMotionMask) -#define WIDTH(X) ((X)->w + 2 * (X)->bw) -#define HEIGHT(X) ((X)->h + 2 * (X)->bw) -#define TAGMASK ((1 << LENGTH(tags)) - 1) -#define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad) - -/* enums */ -enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */ -enum { SchemeNorm, SchemeSel }; /* color schemes */ -enum { NetSupported, NetWMName, NetWMState, NetWMCheck, - NetWMFullscreen, NetActiveWindow, NetWMWindowType, - NetWMWindowTypeDialog, NetClientList, NetLast }; /* EWMH atoms */ -enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; /* default atoms */ -enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, - ClkClientWin, ClkRootWin, ClkLast }; /* clicks */ - -typedef union { - int i; - unsigned int ui; - float f; - const void *v; -} Arg; - -typedef struct { - unsigned int click; - unsigned int mask; - unsigned int button; - void (*func)(const Arg *arg); - const Arg arg; -} Button; - -typedef struct Monitor Monitor; -typedef struct Client Client; -struct Client { - char name[256]; - float mina, maxa; - int x, y, w, h; - int oldx, oldy, oldw, oldh; - int basew, baseh, incw, inch, maxw, maxh, minw, minh, hintsvalid; - int bw, oldbw; - unsigned int tags; - int isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen; - Client *next; - Client *snext; - Monitor *mon; - Window win; -}; - -typedef struct { - unsigned int mod; - KeySym keysym; - void (*func)(const Arg *); - const Arg arg; -} Key; - -typedef struct { - const char *symbol; - void (*arrange)(Monitor *); -} Layout; - -struct Monitor { - char ltsymbol[16]; - float mfact; - int nmaster; - int num; - int by; /* bar geometry */ - int mx, my, mw, mh; /* screen size */ - int wx, wy, ww, wh; /* window area */ - unsigned int seltags; - unsigned int sellt; - unsigned int tagset[2]; - int showbar; - int topbar; - Client *clients; - Client *sel; - Client *stack; - Monitor *next; - Window barwin; - const Layout *lt[2]; -}; - -typedef struct { - const char *class; - const char *instance; - const char *title; - unsigned int tags; - int isfloating; - int monitor; -} Rule; - -/* function declarations */ -static void applyrules(Client *c); -static int applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact); -static void arrange(Monitor *m); -static void arrangemon(Monitor *m); -static void attach(Client *c); -static void attachstack(Client *c); -static void buttonpress(XEvent *e); -static void checkotherwm(void); -static void cleanup(void); -static void cleanupmon(Monitor *mon); -static void clientmessage(XEvent *e); -static void configure(Client *c); -static void configurenotify(XEvent *e); -static void configurerequest(XEvent *e); -static Monitor *createmon(void); -static void destroynotify(XEvent *e); -static void detach(Client *c); -static void detachstack(Client *c); -static Monitor *dirtomon(int dir); -static void drawbar(Monitor *m); -static void drawbars(void); -static void enternotify(XEvent *e); -static void expose(XEvent *e); -static void focus(Client *c); -static void focusin(XEvent *e); -static void focusmon(const Arg *arg); -static void focusstack(const Arg *arg); -static Atom getatomprop(Client *c, Atom prop); -static int getrootptr(int *x, int *y); -static long getstate(Window w); -static int gettextprop(Window w, Atom atom, char *text, unsigned int size); -static void grabbuttons(Client *c, int focused); -static void grabkeys(void); -static void incnmaster(const Arg *arg); -static void keypress(XEvent *e); -static void killclient(const Arg *arg); -static void manage(Window w, XWindowAttributes *wa); -static void mappingnotify(XEvent *e); -static void maprequest(XEvent *e); -static void monocle(Monitor *m); -static void motionnotify(XEvent *e); -static void movemouse(const Arg *arg); -static Client *nexttiled(Client *c); -static void pop(Client *c); -static void propertynotify(XEvent *e); -static void quit(const Arg *arg); -static Monitor *recttomon(int x, int y, int w, int h); -static void resize(Client *c, int x, int y, int w, int h, int interact); -static void resizeclient(Client *c, int x, int y, int w, int h); -static void resizemouse(const Arg *arg); -static void restack(Monitor *m); -static void run(void); -static void scan(void); -static int sendevent(Client *c, Atom proto); -static void sendmon(Client *c, Monitor *m); -static void setclientstate(Client *c, long state); -static void setfocus(Client *c); -static void setfullscreen(Client *c, int fullscreen); -static void setlayout(const Arg *arg); -static void setmfact(const Arg *arg); -static void setup(void); -static void seturgent(Client *c, int urg); -static void showhide(Client *c); -static void spawn(const Arg *arg); -static void tag(const Arg *arg); -static void tagmon(const Arg *arg); -static void tile(Monitor *m); -static void togglebar(const Arg *arg); -static void togglefloating(const Arg *arg); -static void toggletag(const Arg *arg); -static void toggleview(const Arg *arg); -static void unfocus(Client *c, int setfocus); -static void unmanage(Client *c, int destroyed); -static void unmapnotify(XEvent *e); -static void updatebarpos(Monitor *m); -static void updatebars(void); -static void updateclientlist(void); -static int updategeom(void); -static void updatenumlockmask(void); -static void updatesizehints(Client *c); -static void updatestatus(void); -static void updatetitle(Client *c); -static void updatewindowtype(Client *c); -static void updatewmhints(Client *c); -static void view(const Arg *arg); -static Client *wintoclient(Window w); -static Monitor *wintomon(Window w); -static int xerror(Display *dpy, XErrorEvent *ee); -static int xerrordummy(Display *dpy, XErrorEvent *ee); -static int xerrorstart(Display *dpy, XErrorEvent *ee); -static void zoom(const Arg *arg); - -/* variables */ -static const char broken[] = "broken"; -static char stext[256]; -static int screen; -static int sw, sh; /* X display screen geometry width, height */ -static int bh; /* bar height */ -static int lrpad; /* sum of left and right padding for text */ -static int (*xerrorxlib)(Display *, XErrorEvent *); -static unsigned int numlockmask = 0; -static void (*handler[LASTEvent]) (XEvent *) = { - [ButtonPress] = buttonpress, - [ClientMessage] = clientmessage, - [ConfigureRequest] = configurerequest, - [ConfigureNotify] = configurenotify, - [DestroyNotify] = destroynotify, - [EnterNotify] = enternotify, - [Expose] = expose, - [FocusIn] = focusin, - [KeyPress] = keypress, - [MappingNotify] = mappingnotify, - [MapRequest] = maprequest, - [MotionNotify] = motionnotify, - [PropertyNotify] = propertynotify, - [UnmapNotify] = unmapnotify -}; -static Atom wmatom[WMLast], netatom[NetLast]; -static int running = 1; -static Cur *cursor[CurLast]; -static Clr **scheme; -static Display *dpy; -static Drw *drw; -static Monitor *mons, *selmon; -static Window root, wmcheckwin; - -/* configuration, allows nested code to access above variables */ -#include "config.h" - -/* compile-time check if all tags fit into an unsigned int bit array. */ -struct NumTags { char limitexceeded[LENGTH(tags) > 31 ? -1 : 1]; }; - -/* function implementations */ -void -applyrules(Client *c) -{ - const char *class, *instance; - unsigned int i; - const Rule *r; - Monitor *m; - XClassHint ch = { NULL, NULL }; - - /* rule matching */ - c->isfloating = 0; - c->tags = 0; - XGetClassHint(dpy, c->win, &ch); - class = ch.res_class ? ch.res_class : broken; - instance = ch.res_name ? ch.res_name : broken; - - for (i = 0; i < LENGTH(rules); i++) { - r = &rules[i]; - if ((!r->title || strstr(c->name, r->title)) - && (!r->class || strstr(class, r->class)) - && (!r->instance || strstr(instance, r->instance))) - { - c->isfloating = r->isfloating; - c->tags |= r->tags; - for (m = mons; m && m->num != r->monitor; m = m->next); - if (m) - c->mon = m; - } - } - if (ch.res_class) - XFree(ch.res_class); - if (ch.res_name) - XFree(ch.res_name); - c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : c->mon->tagset[c->mon->seltags]; -} - -int -applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact) -{ - int baseismin; - Monitor *m = c->mon; - - /* set minimum possible */ - *w = MAX(1, *w); - *h = MAX(1, *h); - if (interact) { - if (*x > sw) - *x = sw - WIDTH(c); - if (*y > sh) - *y = sh - HEIGHT(c); - if (*x + *w + 2 * c->bw < 0) - *x = 0; - if (*y + *h + 2 * c->bw < 0) - *y = 0; - } else { - if (*x >= m->wx + m->ww) - *x = m->wx + m->ww - WIDTH(c); - if (*y >= m->wy + m->wh) - *y = m->wy + m->wh - HEIGHT(c); - if (*x + *w + 2 * c->bw <= m->wx) - *x = m->wx; - if (*y + *h + 2 * c->bw <= m->wy) - *y = m->wy; - } - if (*h < bh) - *h = bh; - if (*w < bh) - *w = bh; - if (resizehints || c->isfloating || !c->mon->lt[c->mon->sellt]->arrange) { - if (!c->hintsvalid) - updatesizehints(c); - /* see last two sentences in ICCCM 4.1.2.3 */ - baseismin = c->basew == c->minw && c->baseh == c->minh; - if (!baseismin) { /* temporarily remove base dimensions */ - *w -= c->basew; - *h -= c->baseh; - } - /* adjust for aspect limits */ - if (c->mina > 0 && c->maxa > 0) { - if (c->maxa < (float)*w / *h) - *w = *h * c->maxa + 0.5; - else if (c->mina < (float)*h / *w) - *h = *w * c->mina + 0.5; - } - if (baseismin) { /* increment calculation requires this */ - *w -= c->basew; - *h -= c->baseh; - } - /* adjust for increment value */ - if (c->incw) - *w -= *w % c->incw; - if (c->inch) - *h -= *h % c->inch; - /* restore base dimensions */ - *w = MAX(*w + c->basew, c->minw); - *h = MAX(*h + c->baseh, c->minh); - if (c->maxw) - *w = MIN(*w, c->maxw); - if (c->maxh) - *h = MIN(*h, c->maxh); - } - return *x != c->x || *y != c->y || *w != c->w || *h != c->h; -} - -void -arrange(Monitor *m) -{ - if (m) - showhide(m->stack); - else for (m = mons; m; m = m->next) - showhide(m->stack); - if (m) { - arrangemon(m); - restack(m); - } else for (m = mons; m; m = m->next) - arrangemon(m); -} - -void -arrangemon(Monitor *m) -{ - snprintf(m->ltsymbol, sizeof(m->ltsymbol), "%s", m->lt[m->sellt]->symbol); - if (m->lt[m->sellt]->arrange) - m->lt[m->sellt]->arrange(m); -} - -void -attach(Client *c) -{ - c->next = c->mon->clients; - c->mon->clients = c; -} - -void -attachstack(Client *c) -{ - c->snext = c->mon->stack; - c->mon->stack = c; -} - -void -buttonpress(XEvent *e) -{ - unsigned int i, x, click; - Arg arg = {0}; - Client *c; - Monitor *m; - XButtonPressedEvent *ev = &e->xbutton; - - click = ClkRootWin; - /* focus monitor if necessary */ - if ((m = wintomon(ev->window)) && m != selmon) { - unfocus(selmon->sel, 1); - selmon = m; - focus(NULL); - } - if (ev->window == selmon->barwin) { - i = x = 0; - do - x += TEXTW(tags[i]); - while (ev->x >= x && ++i < LENGTH(tags)); - if (i < LENGTH(tags)) { - click = ClkTagBar; - arg.ui = 1 << i; - } else if (ev->x < x + TEXTW(selmon->ltsymbol)) - click = ClkLtSymbol; - else if (ev->x > selmon->ww - (int)TEXTW(stext) + lrpad - 2) - click = ClkStatusText; - else - click = ClkWinTitle; - } else if ((c = wintoclient(ev->window))) { - focus(c); - restack(selmon); - XAllowEvents(dpy, ReplayPointer, CurrentTime); - click = ClkClientWin; - } - for (i = 0; i < LENGTH(buttons); i++) - if (click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button - && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state)) - buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg); -} - -void -checkotherwm(void) -{ - xerrorxlib = XSetErrorHandler(xerrorstart); - /* this causes an error if some other window manager is running */ - XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask); - XSync(dpy, False); - XSetErrorHandler(xerror); - XSync(dpy, False); -} - -void -cleanup(void) -{ - Arg a = {.ui = ~0}; - Layout foo = { "", NULL }; - Monitor *m; - size_t i; - - view(&a); - selmon->lt[selmon->sellt] = &foo; - for (m = mons; m; m = m->next) - while (m->stack) - unmanage(m->stack, 0); - XUngrabKey(dpy, AnyKey, AnyModifier, root); - while (mons) - cleanupmon(mons); - for (i = 0; i < CurLast; i++) - drw_cur_free(drw, cursor[i]); - for (i = 0; i < LENGTH(colors); i++) - drw_scm_free(drw, scheme[i], 3); - free(scheme); - XDestroyWindow(dpy, wmcheckwin); - drw_free(drw); - XSync(dpy, False); - XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime); - XDeleteProperty(dpy, root, netatom[NetActiveWindow]); -} - -void -cleanupmon(Monitor *mon) -{ - Monitor *m; - - if (mon == mons) - mons = mons->next; - else { - for (m = mons; m && m->next != mon; m = m->next); - m->next = mon->next; - } - XUnmapWindow(dpy, mon->barwin); - XDestroyWindow(dpy, mon->barwin); - free(mon); -} - -void -clientmessage(XEvent *e) -{ - XClientMessageEvent *cme = &e->xclient; - Client *c = wintoclient(cme->window); - - if (!c) - return; - if (cme->message_type == netatom[NetWMState]) { - if (cme->data.l[1] == netatom[NetWMFullscreen] - || cme->data.l[2] == netatom[NetWMFullscreen]) - setfullscreen(c, (cme->data.l[0] == 1 /* _NET_WM_STATE_ADD */ - || (cme->data.l[0] == 2 /* _NET_WM_STATE_TOGGLE */ && !c->isfullscreen))); - } else if (cme->message_type == netatom[NetActiveWindow]) { - if (c != selmon->sel && !c->isurgent) - seturgent(c, 1); - } -} - -void -configure(Client *c) -{ - XConfigureEvent ce; - - ce.type = ConfigureNotify; - ce.display = dpy; - ce.event = c->win; - ce.window = c->win; - ce.x = c->x; - ce.y = c->y; - ce.width = c->w; - ce.height = c->h; - ce.border_width = c->bw; - ce.above = None; - ce.override_redirect = False; - XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce); -} - -void -configurenotify(XEvent *e) -{ - Monitor *m; - Client *c; - XConfigureEvent *ev = &e->xconfigure; - int dirty; - - /* TODO: updategeom handling sucks, needs to be simplified */ - if (ev->window == root) { - if (ev->width <= 0 || ev->height <= 0) - return; - - dirty = (sw != ev->width || sh != ev->height); - sw = ev->width; - sh = ev->height; - if (updategeom() || dirty) { - drw_resize(drw, sw, bh); - updatebars(); - for (m = mons; m; m = m->next) { - for (c = m->clients; c; c = c->next) - if (c->isfullscreen) - resizeclient(c, m->mx, m->my, m->mw, m->mh); - XMoveResizeWindow(dpy, m->barwin, m->wx, m->by, m->ww, bh); - } - focus(NULL); - arrange(NULL); - } - } -} - -void -configurerequest(XEvent *e) -{ - Client *c; - Monitor *m; - XConfigureRequestEvent *ev = &e->xconfigurerequest; - XWindowChanges wc; - - if ((c = wintoclient(ev->window))) { - if (ev->value_mask & CWBorderWidth) - c->bw = ev->border_width; - else if (c->isfloating || !selmon->lt[selmon->sellt]->arrange) { - m = c->mon; - if (ev->value_mask & CWX) { - c->oldx = c->x; - c->x = m->mx + ev->x; - } - if (ev->value_mask & CWY) { - c->oldy = c->y; - c->y = m->my + ev->y; - } - if (ev->value_mask & CWWidth) { - c->oldw = c->w; - c->w = ev->width; - } - if (ev->value_mask & CWHeight) { - c->oldh = c->h; - c->h = ev->height; - } - if ((c->x + c->w) > m->mx + m->mw && c->isfloating) - c->x = m->mx + (m->mw / 2 - WIDTH(c) / 2); /* center in x direction */ - if ((c->y + c->h) > m->my + m->mh && c->isfloating) - c->y = m->my + (m->mh / 2 - HEIGHT(c) / 2); /* center in y direction */ - if ((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight))) - configure(c); - if (ISVISIBLE(c)) - XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); - } else - configure(c); - } else { - wc.x = ev->x; - wc.y = ev->y; - wc.width = ev->width; - wc.height = ev->height; - wc.border_width = ev->border_width; - wc.sibling = ev->above; - wc.stack_mode = ev->detail; - XConfigureWindow(dpy, ev->window, ev->value_mask, &wc); - } - XSync(dpy, False); -} - -Monitor * -createmon(void) -{ - Monitor *m; - - m = ecalloc(1, sizeof(Monitor)); - m->tagset[0] = m->tagset[1] = 1; - m->mfact = mfact; - m->nmaster = nmaster; - m->showbar = showbar; - m->topbar = topbar; - m->lt[0] = &layouts[0]; - m->lt[1] = &layouts[1 % LENGTH(layouts)]; - snprintf(m->ltsymbol, sizeof(m->ltsymbol), "%s", layouts[0].symbol); - return m; -} - -void -destroynotify(XEvent *e) -{ - Client *c; - XDestroyWindowEvent *ev = &e->xdestroywindow; - - if ((c = wintoclient(ev->window))) - unmanage(c, 1); -} - -void -detach(Client *c) -{ - Client **tc; - - for (tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next); - *tc = c->next; -} - -void -detachstack(Client *c) -{ - Client **tc, *t; - - for (tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext); - *tc = c->snext; - - if (c == c->mon->sel) { - for (t = c->mon->stack; t && !ISVISIBLE(t); t = t->snext); - c->mon->sel = t; - } -} - -Monitor * -dirtomon(int dir) -{ - Monitor *m = NULL; - - if (dir > 0) { - if (!(m = selmon->next)) - m = mons; - } else if (selmon == mons) - for (m = mons; m->next; m = m->next); - else - for (m = mons; m->next != selmon; m = m->next); - return m; -} - -void -drawbar(Monitor *m) -{ - int x, w, tw = 0; - int boxs = drw->fonts->h / 9; - int boxw = drw->fonts->h / 6 + 2; - unsigned int i, occ = 0, urg = 0; - Client *c; - - if (!m->showbar) - return; - - /* draw status first so it can be overdrawn by tags later */ - if (m == selmon) { /* status is only drawn on selected monitor */ - drw_setscheme(drw, scheme[SchemeNorm]); - tw = TEXTW(stext) - lrpad + 2; /* 2px right padding */ - drw_text(drw, m->ww - tw, 0, tw, bh, 0, stext, 0); - } - - for (c = m->clients; c; c = c->next) { - occ |= c->tags; - if (c->isurgent) - urg |= c->tags; - } - x = 0; - for (i = 0; i < LENGTH(tags); i++) { - w = TEXTW(tags[i]); - drw_setscheme(drw, scheme[m->tagset[m->seltags] & 1 << i ? SchemeSel : SchemeNorm]); - drw_text(drw, x, 0, w, bh, lrpad / 2, tags[i], urg & 1 << i); - if (occ & 1 << i) - drw_rect(drw, x + boxs, boxs, boxw, boxw, - m == selmon && selmon->sel && selmon->sel->tags & 1 << i, - urg & 1 << i); - x += w; - } - w = TEXTW(m->ltsymbol); - drw_setscheme(drw, scheme[SchemeNorm]); - x = drw_text(drw, x, 0, w, bh, lrpad / 2, m->ltsymbol, 0); - - if ((w = m->ww - tw - x) > bh) { - if (m->sel) { - drw_setscheme(drw, scheme[m == selmon ? SchemeSel : SchemeNorm]); - drw_text(drw, x, 0, w, bh, lrpad / 2, m->sel->name, 0); - if (m->sel->isfloating) - drw_rect(drw, x + boxs, boxs, boxw, boxw, m->sel->isfixed, 0); - } else { - drw_setscheme(drw, scheme[SchemeNorm]); - drw_rect(drw, x, 0, w, bh, 1, 1); - } - } - drw_map(drw, m->barwin, 0, 0, m->ww, bh); -} - -void -drawbars(void) -{ - Monitor *m; - - for (m = mons; m; m = m->next) - drawbar(m); -} - -void -enternotify(XEvent *e) -{ - Client *c; - Monitor *m; - XCrossingEvent *ev = &e->xcrossing; - - if ((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root) - return; - c = wintoclient(ev->window); - m = c ? c->mon : wintomon(ev->window); - if (m != selmon) { - unfocus(selmon->sel, 1); - selmon = m; - } else if (!c || c == selmon->sel) - return; - focus(c); -} - -void -expose(XEvent *e) -{ - Monitor *m; - XExposeEvent *ev = &e->xexpose; - - if (ev->count == 0 && (m = wintomon(ev->window))) - drawbar(m); -} - -void -focus(Client *c) -{ - if (!c || !ISVISIBLE(c)) - for (c = selmon->stack; c && !ISVISIBLE(c); c = c->snext); - if (selmon->sel && selmon->sel != c) - unfocus(selmon->sel, 0); - if (c) { - if (c->mon != selmon) - selmon = c->mon; - if (c->isurgent) - seturgent(c, 0); - detachstack(c); - attachstack(c); - grabbuttons(c, 1); - XSetWindowBorder(dpy, c->win, scheme[SchemeSel][ColBorder].pixel); - setfocus(c); - } else { - XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime); - XDeleteProperty(dpy, root, netatom[NetActiveWindow]); - } - selmon->sel = c; - drawbars(); -} - -/* there are some broken focus acquiring clients needing extra handling */ -void -focusin(XEvent *e) -{ - XFocusChangeEvent *ev = &e->xfocus; - - if (selmon->sel && ev->window != selmon->sel->win) - setfocus(selmon->sel); -} - -void -focusmon(const Arg *arg) -{ - Monitor *m; - - if (!mons->next) - return; - if ((m = dirtomon(arg->i)) == selmon) - return; - unfocus(selmon->sel, 0); - selmon = m; - focus(NULL); -} - -void -focusstack(const Arg *arg) -{ - Client *c = NULL, *i; - - if (!selmon->sel || (selmon->sel->isfullscreen && lockfullscreen)) - return; - if (arg->i > 0) { - for (c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next); - if (!c) - for (c = selmon->clients; c && !ISVISIBLE(c); c = c->next); - } else { - for (i = selmon->clients; i != selmon->sel; i = i->next) - if (ISVISIBLE(i)) - c = i; - if (!c) - for (; i; i = i->next) - if (ISVISIBLE(i)) - c = i; - } - if (c) { - focus(c); - restack(selmon); - } -} - -Atom -getatomprop(Client *c, Atom prop) -{ - int format; - unsigned long nitems, dl; - unsigned char *p = NULL; - Atom da, atom = None; - - if (XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, XA_ATOM, - &da, &format, &nitems, &dl, &p) == Success && p) { - if (nitems > 0 && format == 32) - atom = *(long *)p; - XFree(p); - } - return atom; -} - -int -getrootptr(int *x, int *y) -{ - int di; - unsigned int dui; - Window dummy; - - return XQueryPointer(dpy, root, &dummy, &dummy, x, y, &di, &di, &dui); -} - -long -getstate(Window w) -{ - int format; - long result = -1; - unsigned char *p = NULL; - unsigned long n, extra; - Atom real; - - if (XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState], - &real, &format, &n, &extra, &p) != Success) - return -1; - if (n != 0 && format == 32) - result = *(long *)p; - XFree(p); - return result; -} - -int -gettextprop(Window w, Atom atom, char *text, unsigned int size) -{ - char **list = NULL; - int n; - XTextProperty name; - - if (!text || size == 0) - return 0; - text[0] = '\0'; - if (!XGetTextProperty(dpy, w, &name, atom) || !name.nitems) - return 0; - if (name.encoding == XA_STRING) { - snprintf(text, size, "%s", (char *)name.value); - } else if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success) { - if (n > 0 && *list) - snprintf(text, size, "%s", *list); - XFreeStringList(list); - } - XFree(name.value); - return 1; -} - -void -grabbuttons(Client *c, int focused) -{ - updatenumlockmask(); - { - unsigned int i, j; - unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask }; - XUngrabButton(dpy, AnyButton, AnyModifier, c->win); - if (!focused) - XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, - BUTTONMASK, GrabModeSync, GrabModeSync, None, None); - for (i = 0; i < LENGTH(buttons); i++) - if (buttons[i].click == ClkClientWin) - for (j = 0; j < LENGTH(modifiers); j++) - XGrabButton(dpy, buttons[i].button, - buttons[i].mask | modifiers[j], - c->win, False, BUTTONMASK, - GrabModeAsync, GrabModeSync, None, None); - } -} - -void -grabkeys(void) -{ - updatenumlockmask(); - { - unsigned int i, j, k; - unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask }; - int start, end, skip; - KeySym *syms; - - XUngrabKey(dpy, AnyKey, AnyModifier, root); - XDisplayKeycodes(dpy, &start, &end); - syms = XGetKeyboardMapping(dpy, start, end - start + 1, &skip); - if (!syms) - return; - for (k = start; k <= end; k++) - for (i = 0; i < LENGTH(keys); i++) - /* skip modifier codes, we do that ourselves */ - if (keys[i].keysym == syms[(k - start) * skip]) - for (j = 0; j < LENGTH(modifiers); j++) - XGrabKey(dpy, k, - keys[i].mod | modifiers[j], - root, True, - GrabModeAsync, GrabModeAsync); - XFree(syms); - } -} - -void -incnmaster(const Arg *arg) -{ - selmon->nmaster = MAX(selmon->nmaster + arg->i, 0); - arrange(selmon); -} - -#ifdef XINERAMA -static int -isuniquegeom(XineramaScreenInfo *unique, size_t n, XineramaScreenInfo *info) -{ - while (n--) - if (unique[n].x_org == info->x_org && unique[n].y_org == info->y_org - && unique[n].width == info->width && unique[n].height == info->height) - return 0; - return 1; -} -#endif /* XINERAMA */ - -void -keypress(XEvent *e) -{ - unsigned int i; - KeySym keysym; - XKeyEvent *ev; - - ev = &e->xkey; - keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0); - for (i = 0; i < LENGTH(keys); i++) - if (keysym == keys[i].keysym - && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state) - && keys[i].func) - keys[i].func(&(keys[i].arg)); -} - -void -killclient(const Arg *arg) -{ - if (!selmon->sel) - return; - if (!sendevent(selmon->sel, wmatom[WMDelete])) { - XGrabServer(dpy); - XSetErrorHandler(xerrordummy); - XSetCloseDownMode(dpy, DestroyAll); - XKillClient(dpy, selmon->sel->win); - XSync(dpy, False); - XSetErrorHandler(xerror); - XUngrabServer(dpy); - } -} - -void -manage(Window w, XWindowAttributes *wa) -{ - Client *c, *t = NULL; - Window trans = None; - XWindowChanges wc; - - c = ecalloc(1, sizeof(Client)); - c->win = w; - /* geometry */ - c->x = c->oldx = wa->x; - c->y = c->oldy = wa->y; - c->w = c->oldw = wa->width; - c->h = c->oldh = wa->height; - c->oldbw = wa->border_width; - - updatetitle(c); - if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) { - c->mon = t->mon; - c->tags = t->tags; - } else { - c->mon = selmon; - applyrules(c); - } - - if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww) - c->x = c->mon->wx + c->mon->ww - WIDTH(c); - if (c->y + HEIGHT(c) > c->mon->wy + c->mon->wh) - c->y = c->mon->wy + c->mon->wh - HEIGHT(c); - c->x = MAX(c->x, c->mon->wx); - c->y = MAX(c->y, c->mon->wy); - c->bw = borderpx; - - wc.border_width = c->bw; - XConfigureWindow(dpy, w, CWBorderWidth, &wc); - XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColBorder].pixel); - configure(c); /* propagates border_width, if size doesn't change */ - updatewindowtype(c); - updatesizehints(c); - updatewmhints(c); - XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask); - grabbuttons(c, 0); - if (!c->isfloating) - c->isfloating = c->oldstate = trans != None || c->isfixed; - if (c->isfloating) - XRaiseWindow(dpy, c->win); - attach(c); - attachstack(c); - XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend, - (unsigned char *) &(c->win), 1); - XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */ - setclientstate(c, NormalState); - if (c->mon == selmon) - unfocus(selmon->sel, 0); - c->mon->sel = c; - arrange(c->mon); - XMapWindow(dpy, c->win); - focus(NULL); -} - -void -mappingnotify(XEvent *e) -{ - XMappingEvent *ev = &e->xmapping; - - XRefreshKeyboardMapping(ev); - if (ev->request == MappingKeyboard) - grabkeys(); -} - -void -maprequest(XEvent *e) -{ - static XWindowAttributes wa; - XMapRequestEvent *ev = &e->xmaprequest; - - if (!XGetWindowAttributes(dpy, ev->window, &wa) || wa.override_redirect) - return; - if (!wintoclient(ev->window)) - manage(ev->window, &wa); -} - -void -monocle(Monitor *m) -{ - unsigned int n = 0; - Client *c; - - for (c = m->clients; c; c = c->next) - if (ISVISIBLE(c)) - n++; - if (n > 0) /* override layout symbol */ - snprintf(m->ltsymbol, sizeof m->ltsymbol, "[%d]", n); - for (c = nexttiled(m->clients); c; c = nexttiled(c->next)) - resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, 0); -} - -void -motionnotify(XEvent *e) -{ - static Monitor *mon = NULL; - Monitor *m; - XMotionEvent *ev = &e->xmotion; - - if (ev->window != root) - return; - if ((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) { - unfocus(selmon->sel, 1); - selmon = m; - focus(NULL); - } - mon = m; -} - -void -movemouse(const Arg *arg) -{ - int x, y, ocx, ocy, nx, ny; - Client *c; - Monitor *m; - XEvent ev; - Time lasttime = 0; - - if (!(c = selmon->sel)) - return; - if (c->isfullscreen) /* no support moving fullscreen windows by mouse */ - return; - restack(selmon); - ocx = c->x; - ocy = c->y; - if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync, - None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess) - return; - if (!getrootptr(&x, &y)) - return; - do { - XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev); - switch(ev.type) { - case ConfigureRequest: - case Expose: - case MapRequest: - handler[ev.type](&ev); - break; - case MotionNotify: - if ((ev.xmotion.time - lasttime) <= (1000 / refreshrate)) - continue; - lasttime = ev.xmotion.time; - - nx = ocx + (ev.xmotion.x - x); - ny = ocy + (ev.xmotion.y - y); - if (abs(selmon->wx - nx) < snap) - nx = selmon->wx; - else if (abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap) - nx = selmon->wx + selmon->ww - WIDTH(c); - if (abs(selmon->wy - ny) < snap) - ny = selmon->wy; - else if (abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap) - ny = selmon->wy + selmon->wh - HEIGHT(c); - if (!c->isfloating && selmon->lt[selmon->sellt]->arrange - && (abs(nx - c->x) > snap || abs(ny - c->y) > snap)) - togglefloating(NULL); - if (!selmon->lt[selmon->sellt]->arrange || c->isfloating) - resize(c, nx, ny, c->w, c->h, 1); - break; - } - } while (ev.type != ButtonRelease); - XUngrabPointer(dpy, CurrentTime); - if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) { - sendmon(c, m); - selmon = m; - focus(NULL); - } -} - -Client * -nexttiled(Client *c) -{ - for (; c && (c->isfloating || !ISVISIBLE(c)); c = c->next); - return c; -} - -void -pop(Client *c) -{ - detach(c); - attach(c); - focus(c); - arrange(c->mon); -} - -void -propertynotify(XEvent *e) -{ - Client *c; - Window trans; - XPropertyEvent *ev = &e->xproperty; - - if ((ev->window == root) && (ev->atom == XA_WM_NAME)) - updatestatus(); - else if (ev->state == PropertyDelete) - return; /* ignore */ - else if ((c = wintoclient(ev->window))) { - switch(ev->atom) { - default: break; - case XA_WM_TRANSIENT_FOR: - if (!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) && - (c->isfloating = (wintoclient(trans)) != NULL)) - arrange(c->mon); - break; - case XA_WM_NORMAL_HINTS: - c->hintsvalid = 0; - break; - case XA_WM_HINTS: - updatewmhints(c); - drawbars(); - break; - } - if (ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) { - updatetitle(c); - if (c == c->mon->sel) - drawbar(c->mon); - } - if (ev->atom == netatom[NetWMWindowType]) - updatewindowtype(c); - } -} - -void -quit(const Arg *arg) -{ - running = 0; -} - -Monitor * -recttomon(int x, int y, int w, int h) -{ - Monitor *m, *r = selmon; - int a, area = 0; - - for (m = mons; m; m = m->next) - if ((a = INTERSECT(x, y, w, h, m)) > area) { - area = a; - r = m; - } - return r; -} - -void -resize(Client *c, int x, int y, int w, int h, int interact) -{ - if (applysizehints(c, &x, &y, &w, &h, interact)) - resizeclient(c, x, y, w, h); -} - -void -resizeclient(Client *c, int x, int y, int w, int h) -{ - XWindowChanges wc; - - c->oldx = c->x; c->x = wc.x = x; - c->oldy = c->y; c->y = wc.y = y; - c->oldw = c->w; c->w = wc.width = w; - c->oldh = c->h; c->h = wc.height = h; - wc.border_width = c->bw; - XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc); - configure(c); - XSync(dpy, False); -} - -void -resizemouse(const Arg *arg) -{ - int ocx, ocy, nw, nh; - Client *c; - Monitor *m; - XEvent ev; - Time lasttime = 0; - - if (!(c = selmon->sel)) - return; - if (c->isfullscreen) /* no support resizing fullscreen windows by mouse */ - return; - restack(selmon); - ocx = c->x; - ocy = c->y; - if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync, - None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess) - return; - XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1); - do { - XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev); - switch(ev.type) { - case ConfigureRequest: - case Expose: - case MapRequest: - handler[ev.type](&ev); - break; - case MotionNotify: - if ((ev.xmotion.time - lasttime) <= (1000 / refreshrate)) - continue; - lasttime = ev.xmotion.time; - - nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1); - nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1); - if (c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww - && c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh) - { - if (!c->isfloating && selmon->lt[selmon->sellt]->arrange - && (abs(nw - c->w) > snap || abs(nh - c->h) > snap)) - togglefloating(NULL); - } - if (!selmon->lt[selmon->sellt]->arrange || c->isfloating) - resize(c, c->x, c->y, nw, nh, 1); - break; - } - } while (ev.type != ButtonRelease); - XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1); - XUngrabPointer(dpy, CurrentTime); - while (XCheckMaskEvent(dpy, EnterWindowMask, &ev)); - if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) { - sendmon(c, m); - selmon = m; - focus(NULL); - } -} - -void -restack(Monitor *m) -{ - Client *c; - XEvent ev; - XWindowChanges wc; - - drawbar(m); - if (!m->sel) - return; - if (m->sel->isfloating || !m->lt[m->sellt]->arrange) - XRaiseWindow(dpy, m->sel->win); - if (m->lt[m->sellt]->arrange) { - wc.stack_mode = Below; - wc.sibling = m->barwin; - for (c = m->stack; c; c = c->snext) - if (!c->isfloating && ISVISIBLE(c)) { - XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc); - wc.sibling = c->win; - } - } - XSync(dpy, False); - while (XCheckMaskEvent(dpy, EnterWindowMask, &ev)); -} - -void -run(void) -{ - XEvent ev; - /* main event loop */ - XSync(dpy, False); - while (running && !XNextEvent(dpy, &ev)) - if (handler[ev.type]) - handler[ev.type](&ev); /* call handler */ -} - -void -scan(void) -{ - unsigned int i, num; - Window d1, d2, *wins = NULL; - XWindowAttributes wa; - - if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) { - for (i = 0; i < num; i++) { - if (!XGetWindowAttributes(dpy, wins[i], &wa) - || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1)) - continue; - if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState) - manage(wins[i], &wa); - } - for (i = 0; i < num; i++) { /* now the transients */ - if (!XGetWindowAttributes(dpy, wins[i], &wa)) - continue; - if (XGetTransientForHint(dpy, wins[i], &d1) - && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)) - manage(wins[i], &wa); - } - if (wins) - XFree(wins); - } -} - -void -sendmon(Client *c, Monitor *m) -{ - if (c->mon == m) - return; - unfocus(c, 1); - detach(c); - detachstack(c); - c->mon = m; - c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */ - attach(c); - attachstack(c); - if (c->isfullscreen) - resizeclient(c, m->mx, m->my, m->mw, m->mh); - focus(NULL); - arrange(NULL); -} - -void -setclientstate(Client *c, long state) -{ - long data[] = { state, None }; - - XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32, - PropModeReplace, (unsigned char *)data, 2); -} - -int -sendevent(Client *c, Atom proto) -{ - int n; - Atom *protocols; - int exists = 0; - XEvent ev; - - if (XGetWMProtocols(dpy, c->win, &protocols, &n)) { - while (!exists && n--) - exists = protocols[n] == proto; - XFree(protocols); - } - if (exists) { - ev.type = ClientMessage; - ev.xclient.window = c->win; - ev.xclient.message_type = wmatom[WMProtocols]; - ev.xclient.format = 32; - ev.xclient.data.l[0] = proto; - ev.xclient.data.l[1] = CurrentTime; - XSendEvent(dpy, c->win, False, NoEventMask, &ev); - } - return exists; -} - -void -setfocus(Client *c) -{ - if (!c->neverfocus) - XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime); - XChangeProperty(dpy, root, netatom[NetActiveWindow], XA_WINDOW, 32, - PropModeReplace, (unsigned char *)&c->win, 1); - sendevent(c, wmatom[WMTakeFocus]); -} - -void -setfullscreen(Client *c, int fullscreen) -{ - if (fullscreen && !c->isfullscreen) { - XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, - PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1); - c->isfullscreen = 1; - c->oldstate = c->isfloating; - c->oldbw = c->bw; - c->bw = 0; - c->isfloating = 1; - resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh); - XRaiseWindow(dpy, c->win); - } else if (!fullscreen && c->isfullscreen){ - XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, - PropModeReplace, (unsigned char*)0, 0); - c->isfullscreen = 0; - c->isfloating = c->oldstate; - c->bw = c->oldbw; - c->x = c->oldx; - c->y = c->oldy; - c->w = c->oldw; - c->h = c->oldh; - resizeclient(c, c->x, c->y, c->w, c->h); - arrange(c->mon); - } -} - -void -setlayout(const Arg *arg) -{ - if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt]) - selmon->sellt ^= 1; - if (arg && arg->v) - selmon->lt[selmon->sellt] = (Layout *)arg->v; - snprintf(selmon->ltsymbol, sizeof(selmon->ltsymbol), "%s", selmon->lt[selmon->sellt]->symbol); - if (selmon->sel) - arrange(selmon); - else - drawbar(selmon); -} - -/* arg > 1.0 will set mfact absolutely */ -void -setmfact(const Arg *arg) -{ - float f; - - if (!arg || !selmon->lt[selmon->sellt]->arrange) - return; - f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0; - if (f < 0.05 || f > 0.95) - return; - selmon->mfact = f; - arrange(selmon); -} - -void -setup(void) -{ - int i; - XSetWindowAttributes wa; - Atom utf8string; - struct sigaction sa; - - /* do not transform children into zombies when they terminate */ - sigemptyset(&sa.sa_mask); - sa.sa_flags = SA_NOCLDSTOP | SA_NOCLDWAIT | SA_RESTART; - sa.sa_handler = SIG_IGN; - sigaction(SIGCHLD, &sa, NULL); - - /* clean up any zombies (inherited from .xinitrc etc) immediately */ - while (waitpid(-1, NULL, WNOHANG) > 0); - - /* init screen */ - screen = DefaultScreen(dpy); - sw = DisplayWidth(dpy, screen); - sh = DisplayHeight(dpy, screen); - root = RootWindow(dpy, screen); - drw = drw_create(dpy, screen, root, sw, sh); - if (!drw_fontset_create(drw, fonts, LENGTH(fonts))) - die("no fonts could be loaded."); - lrpad = drw->fonts->h; - bh = drw->fonts->h + 2; - updategeom(); - /* init atoms */ - utf8string = XInternAtom(dpy, "UTF8_STRING", False); - wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False); - wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False); - wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False); - wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False); - netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False); - netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False); - netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False); - netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False); - netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False); - netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False); - netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False); - netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False); - netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False); - /* init cursors */ - cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr); - cursor[CurResize] = drw_cur_create(drw, XC_sizing); - cursor[CurMove] = drw_cur_create(drw, XC_fleur); - /* init appearance */ - scheme = ecalloc(LENGTH(colors), sizeof(Clr *)); - for (i = 0; i < LENGTH(colors); i++) - scheme[i] = drw_scm_create(drw, colors[i], 3); - /* init bars */ - updatebars(); - updatestatus(); - /* supporting window for NetWMCheck */ - wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0); - XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32, - PropModeReplace, (unsigned char *) &wmcheckwin, 1); - XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8, - PropModeReplace, (unsigned char *) "dwm", 3); - XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32, - PropModeReplace, (unsigned char *) &wmcheckwin, 1); - /* EWMH support per view */ - XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32, - PropModeReplace, (unsigned char *) netatom, NetLast); - XDeleteProperty(dpy, root, netatom[NetClientList]); - /* select events */ - wa.cursor = cursor[CurNormal]->cursor; - wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask - |ButtonPressMask|PointerMotionMask|EnterWindowMask - |LeaveWindowMask|StructureNotifyMask|PropertyChangeMask; - XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa); - XSelectInput(dpy, root, wa.event_mask); - grabkeys(); - focus(NULL); -} - -void -seturgent(Client *c, int urg) -{ - XWMHints *wmh; - - c->isurgent = urg; - if (!(wmh = XGetWMHints(dpy, c->win))) - return; - wmh->flags = urg ? (wmh->flags | XUrgencyHint) : (wmh->flags & ~XUrgencyHint); - XSetWMHints(dpy, c->win, wmh); - XFree(wmh); -} - -void -showhide(Client *c) -{ - if (!c) - return; - if (ISVISIBLE(c)) { - /* show clients top down */ - XMoveWindow(dpy, c->win, c->x, c->y); - if ((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) && !c->isfullscreen) - resize(c, c->x, c->y, c->w, c->h, 0); - showhide(c->snext); - } else { - /* hide clients bottom up */ - showhide(c->snext); - XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y); - } -} - -void -spawn(const Arg *arg) -{ - struct sigaction sa; - pid_t pid; - - if (arg->v == dmenucmd) - snprintf(dmenumon, sizeof(dmenumon), "%d", selmon->num); - - if ((pid = fork()) == -1) { - fprintf(stderr, "dwm: fork failed: %s\n", strerror(errno)); - return; - } - if (pid == 0) { - if (dpy) - close(ConnectionNumber(dpy)); - setsid(); - - sigemptyset(&sa.sa_mask); - sa.sa_flags = 0; - sa.sa_handler = SIG_DFL; - sigaction(SIGCHLD, &sa, NULL); - - execvp(((char **)arg->v)[0], (char **)arg->v); - die("dwm: execvp '%s' failed:", ((char **)arg->v)[0]); - } -} - -void -tag(const Arg *arg) -{ - if (selmon->sel && arg->ui & TAGMASK) { - selmon->sel->tags = arg->ui & TAGMASK; - focus(NULL); - arrange(selmon); - } -} - -void -tagmon(const Arg *arg) -{ - if (!selmon->sel || !mons->next) - return; - sendmon(selmon->sel, dirtomon(arg->i)); -} - -void -tile(Monitor *m) -{ - unsigned int i, n, h, mw, my, ty; - Client *c; - - for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++); - if (n == 0) - return; - - if (n > m->nmaster) - mw = m->nmaster ? m->ww * m->mfact : 0; - else - mw = m->ww; - for (i = my = ty = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++) - if (i < m->nmaster) { - h = (m->wh - my) / (MIN(n, m->nmaster) - i); - resize(c, m->wx, m->wy + my, mw - (2*c->bw), h - (2*c->bw), 0); - if (my + HEIGHT(c) < m->wh) - my += HEIGHT(c); - } else { - h = (m->wh - ty) / (n - i); - resize(c, m->wx + mw, m->wy + ty, m->ww - mw - (2*c->bw), h - (2*c->bw), 0); - if (ty + HEIGHT(c) < m->wh) - ty += HEIGHT(c); - } -} - -void -togglebar(const Arg *arg) -{ - selmon->showbar = !selmon->showbar; - updatebarpos(selmon); - XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh); - arrange(selmon); -} - -void -togglefloating(const Arg *arg) -{ - if (!selmon->sel) - return; - if (selmon->sel->isfullscreen) /* no support for fullscreen windows */ - return; - selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed; - if (selmon->sel->isfloating) - resize(selmon->sel, selmon->sel->x, selmon->sel->y, - selmon->sel->w, selmon->sel->h, 0); - arrange(selmon); -} - -void -toggletag(const Arg *arg) -{ - unsigned int newtags; - - if (!selmon->sel) - return; - newtags = selmon->sel->tags ^ (arg->ui & TAGMASK); - if (newtags) { - selmon->sel->tags = newtags; - focus(NULL); - arrange(selmon); - } -} - -void -toggleview(const Arg *arg) -{ - unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK); - - if (newtagset) { - selmon->tagset[selmon->seltags] = newtagset; - focus(NULL); - arrange(selmon); - } -} - -void -unfocus(Client *c, int setfocus) -{ - if (!c) - return; - grabbuttons(c, 0); - XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColBorder].pixel); - if (setfocus) { - XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime); - XDeleteProperty(dpy, root, netatom[NetActiveWindow]); - } -} - -void -unmanage(Client *c, int destroyed) -{ - Monitor *m = c->mon; - XWindowChanges wc; - - detach(c); - detachstack(c); - if (!destroyed) { - wc.border_width = c->oldbw; - XGrabServer(dpy); /* avoid race conditions */ - XSetErrorHandler(xerrordummy); - XSelectInput(dpy, c->win, NoEventMask); - XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */ - XUngrabButton(dpy, AnyButton, AnyModifier, c->win); - setclientstate(c, WithdrawnState); - XSync(dpy, False); - XSetErrorHandler(xerror); - XUngrabServer(dpy); - } - free(c); - focus(NULL); - updateclientlist(); - arrange(m); -} - -void -unmapnotify(XEvent *e) -{ - Client *c; - XUnmapEvent *ev = &e->xunmap; - - if ((c = wintoclient(ev->window))) { - if (ev->send_event) - setclientstate(c, WithdrawnState); - else - unmanage(c, 0); - } -} - -void -updatebars(void) -{ - Monitor *m; - XSetWindowAttributes wa = { - .override_redirect = True, - .background_pixmap = ParentRelative, - .event_mask = ButtonPressMask|ExposureMask - }; - XClassHint ch = {"dwm", "dwm"}; - for (m = mons; m; m = m->next) { - if (m->barwin) - continue; - m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen), - CopyFromParent, DefaultVisual(dpy, screen), - CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa); - XDefineCursor(dpy, m->barwin, cursor[CurNormal]->cursor); - XMapRaised(dpy, m->barwin); - XSetClassHint(dpy, m->barwin, &ch); - } -} - -void -updatebarpos(Monitor *m) -{ - m->wy = m->my; - m->wh = m->mh; - if (m->showbar) { - m->wh -= bh; - m->by = m->topbar ? m->wy : m->wy + m->wh; - m->wy = m->topbar ? m->wy + bh : m->wy; - } else - m->by = -bh; -} - -void -updateclientlist(void) -{ - Client *c; - Monitor *m; - - XDeleteProperty(dpy, root, netatom[NetClientList]); - for (m = mons; m; m = m->next) - for (c = m->clients; c; c = c->next) - XChangeProperty(dpy, root, netatom[NetClientList], - XA_WINDOW, 32, PropModeAppend, - (unsigned char *) &(c->win), 1); -} - -int -updategeom(void) -{ - int dirty = 0; - -#ifdef XINERAMA - if (XineramaIsActive(dpy)) { - int i, j, n, nn; - Client *c; - Monitor *m; - XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn); - XineramaScreenInfo *unique = NULL; - - for (n = 0, m = mons; m; m = m->next, n++); - /* only consider unique geometries as separate screens */ - unique = ecalloc(nn, sizeof(XineramaScreenInfo)); - for (i = 0, j = 0; i < nn; i++) - if (isuniquegeom(unique, j, &info[i])) - memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo)); - XFree(info); - nn = j; - - /* new monitors if nn > n */ - for (i = n; i < nn; i++) { - for (m = mons; m && m->next; m = m->next); - if (m) - m->next = createmon(); - else - mons = createmon(); - } - for (i = 0, m = mons; i < nn && m; m = m->next, i++) - if (i >= n - || unique[i].x_org != m->mx || unique[i].y_org != m->my - || unique[i].width != m->mw || unique[i].height != m->mh) - { - dirty = 1; - m->num = i; - m->mx = m->wx = unique[i].x_org; - m->my = m->wy = unique[i].y_org; - m->mw = m->ww = unique[i].width; - m->mh = m->wh = unique[i].height; - updatebarpos(m); - } - /* removed monitors if n > nn */ - for (i = nn; i < n; i++) { - for (m = mons; m && m->next; m = m->next); - while ((c = m->clients)) { - dirty = 1; - m->clients = c->next; - detachstack(c); - c->mon = mons; - attach(c); - attachstack(c); - } - if (m == selmon) - selmon = mons; - cleanupmon(m); - } - free(unique); - } else -#endif /* XINERAMA */ - { /* default monitor setup */ - if (!mons) - mons = createmon(); - if (mons->mw != sw || mons->mh != sh) { - dirty = 1; - mons->mw = mons->ww = sw; - mons->mh = mons->wh = sh; - updatebarpos(mons); - } - } - if (dirty) { - selmon = mons; - selmon = wintomon(root); - } - return dirty; -} - -void -updatenumlockmask(void) -{ - unsigned int i, j; - XModifierKeymap *modmap; - - numlockmask = 0; - if (!(modmap = XGetModifierMapping(dpy))) - return; - for (i = 0; i < 8; i++) - for (j = 0; j < modmap->max_keypermod; j++) - if (modmap->modifiermap[i * modmap->max_keypermod + j] - == XKeysymToKeycode(dpy, XK_Num_Lock)) - numlockmask = (1 << i); - XFreeModifiermap(modmap); -} - -void -updatesizehints(Client *c) -{ - long msize; - XSizeHints size; - - if (!XGetWMNormalHints(dpy, c->win, &size, &msize)) - /* size is uninitialized, ensure that size.flags aren't used */ - size.flags = PSize; - if (size.flags & PBaseSize) { - c->basew = MAX(0, size.base_width); - c->baseh = MAX(0, size.base_height); - } else if (size.flags & PMinSize) { - c->basew = MAX(0, size.min_width); - c->baseh = MAX(0, size.min_height); - } else - c->basew = c->baseh = 0; - if (size.flags & PResizeInc) { - c->incw = MAX(0, size.width_inc); - c->inch = MAX(0, size.height_inc); - } else - c->incw = c->inch = 0; - if (size.flags & PMaxSize) { - c->maxw = MAX(0, size.max_width); - c->maxh = MAX(0, size.max_height); - } else - c->maxw = c->maxh = 0; - if (size.flags & PMinSize) { - c->minw = MAX(0, size.min_width); - c->minh = MAX(0, size.min_height); - } else if (size.flags & PBaseSize) { - c->minw = MAX(0, size.base_width); - c->minh = MAX(0, size.base_height); - } else - c->minw = c->minh = 0; - if ((size.flags & PAspect) && size.min_aspect.x > 0 && size.max_aspect.y > 0) { - c->mina = (float)size.min_aspect.y / size.min_aspect.x; - c->maxa = (float)size.max_aspect.x / size.max_aspect.y; - } else - c->maxa = c->mina = 0.0; - c->isfixed = (c->maxw && c->maxh && c->maxw == c->minw && c->maxh == c->minh); - c->hintsvalid = 1; -} - -void -updatestatus(void) -{ - if (!gettextprop(root, XA_WM_NAME, stext, sizeof(stext))) - strcpy(stext, "dwm-"VERSION); - drawbar(selmon); -} - -void -updatetitle(Client *c) -{ - if (!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name)) - gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name); - if (c->name[0] == '\0') /* hack to mark broken clients */ - strcpy(c->name, broken); -} - -void -updatewindowtype(Client *c) -{ - Atom state = getatomprop(c, netatom[NetWMState]); - Atom wtype = getatomprop(c, netatom[NetWMWindowType]); - - if (state == netatom[NetWMFullscreen]) - setfullscreen(c, 1); - if (wtype == netatom[NetWMWindowTypeDialog]) - c->isfloating = 1; -} - -void -updatewmhints(Client *c) -{ - XWMHints *wmh; - - if ((wmh = XGetWMHints(dpy, c->win))) { - if (c == selmon->sel && wmh->flags & XUrgencyHint) { - wmh->flags &= ~XUrgencyHint; - XSetWMHints(dpy, c->win, wmh); - } else - c->isurgent = (wmh->flags & XUrgencyHint) ? 1 : 0; - if (wmh->flags & InputHint) - c->neverfocus = !wmh->input; - else - c->neverfocus = 0; - XFree(wmh); - } -} - -void -view(const Arg *arg) -{ - if ((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags]) - return; - selmon->seltags ^= 1; /* toggle sel tagset */ - if (arg->ui & TAGMASK) - selmon->tagset[selmon->seltags] = arg->ui & TAGMASK; - focus(NULL); - arrange(selmon); -} - -Client * -wintoclient(Window w) -{ - Client *c; - Monitor *m; - - for (m = mons; m; m = m->next) - for (c = m->clients; c; c = c->next) - if (c->win == w) - return c; - return NULL; -} - -Monitor * -wintomon(Window w) -{ - int x, y; - Client *c; - Monitor *m; - - if (w == root && getrootptr(&x, &y)) - return recttomon(x, y, 1, 1); - for (m = mons; m; m = m->next) - if (w == m->barwin) - return m; - if ((c = wintoclient(w))) - return c->mon; - return selmon; -} - -/* There's no way to check accesses to destroyed windows, thus those cases are - * ignored (especially on UnmapNotify's). Other types of errors call Xlibs - * default error handler, which may call exit. */ -int -xerror(Display *dpy, XErrorEvent *ee) -{ - if (ee->error_code == BadWindow - || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch) - || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable) - || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable) - || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable) - || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch) - || (ee->request_code == X_GrabButton && ee->error_code == BadAccess) - || (ee->request_code == X_GrabKey && ee->error_code == BadAccess) - || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable)) - return 0; - fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n", - ee->request_code, ee->error_code); - return xerrorxlib(dpy, ee); /* may call exit */ -} - -int -xerrordummy(Display *dpy, XErrorEvent *ee) -{ - return 0; -} - -/* Startup Error handler to check if another window manager - * is already running. */ -int -xerrorstart(Display *dpy, XErrorEvent *ee) -{ - die("dwm: another window manager is already running"); - return -1; -} - -void -zoom(const Arg *arg) -{ - Client *c = selmon->sel; - - if (!selmon->lt[selmon->sellt]->arrange || !c || c->isfloating) - return; - if (c == nexttiled(selmon->clients) && !(c = nexttiled(c->next))) - return; - pop(c); -} - -int -main(int argc, char *argv[]) -{ - if (argc == 2 && !strcmp("-v", argv[1])) - die("dwm-"VERSION); - else if (argc != 1) - die("usage: dwm [-v]"); - if (!setlocale(LC_CTYPE, "") || !XSupportsLocale()) - fputs("warning: no locale support\n", stderr); - if (!(dpy = XOpenDisplay(NULL))) - die("dwm: cannot open display"); - checkotherwm(); - setup(); -#ifdef __OpenBSD__ - if (pledge("stdio rpath proc exec", NULL) == -1) - die("pledge"); -#endif /* __OpenBSD__ */ - scan(); - run(); - cleanup(); - XCloseDisplay(dpy); - return EXIT_SUCCESS; -} diff --git a/dwm.png b/dwm.png Binary files differ. diff --git a/transient.c b/transient.c @@ -1,42 +0,0 @@ -/* cc transient.c -o transient -lX11 */ - -#include <stdlib.h> -#include <unistd.h> -#include <X11/Xlib.h> -#include <X11/Xutil.h> - -int main(void) { - Display *d; - Window r, f, t = None; - XSizeHints h; - XEvent e; - - d = XOpenDisplay(NULL); - if (!d) - exit(1); - r = DefaultRootWindow(d); - - f = XCreateSimpleWindow(d, r, 100, 100, 400, 400, 0, 0, 0); - h.min_width = h.max_width = h.min_height = h.max_height = 400; - h.flags = PMinSize | PMaxSize; - XSetWMNormalHints(d, f, &h); - XStoreName(d, f, "floating"); - XMapWindow(d, f); - - XSelectInput(d, f, ExposureMask); - while (1) { - XNextEvent(d, &e); - - if (t == None) { - sleep(5); - t = XCreateSimpleWindow(d, r, 50, 50, 100, 100, 0, 0, 0); - XSetTransientForHint(d, t, f); - XStoreName(d, t, "transient"); - XMapWindow(d, t); - XSelectInput(d, t, ExposureMask); - } - } - - XCloseDisplay(d); - exit(0); -}