feat: add XKB layout indicator, live X11 session replace, and ANODE WM/DE identity

This commit is contained in:
Luxferre committed 2026-11-26 12:37:25 +02:00
1 parent 8d6236a63f
commit 158345c168
12 files changed
+1303 -48

No files matched your search

+198
View File
@@ -0,0 +1,198 @@
#ifndef ANODE_XKB_PARSE_H
#define ANODE_XKB_PARSE_H
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
static inline bool anode_xkb_ascii_is_ws(char c) {
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
static inline bool anode_xkb_ascii_eq_ci(const char *a, size_t alen, const char *b) {
size_t blen = strlen(b);
if (alen != blen) return false;
for (size_t i = 0; i < alen; i++) {
char ca = a[i];
char cb = b[i];
if (ca >= 'A' && ca <= 'Z') ca = (char)(ca + ('a' - 'A'));
if (cb >= 'A' && cb <= 'Z') cb = (char)(cb + ('a' - 'A'));
if (ca != cb) return false;
}
return true;
}
static inline bool anode_xkb_normalize_code(const char *src, size_t len, char *out, size_t out_sz) {
if (!out || out_sz == 0) return false;
out[0] = '\0';
if (!src || len == 0) return false;
size_t start = 0;
size_t end = len;
while (start < end && anode_xkb_ascii_is_ws(src[start])) start++;
while (end > start && anode_xkb_ascii_is_ws(src[end - 1])) end--;
for (size_t i = start; i < end; i++) {
if (src[i] == ':' || src[i] == '(') {
end = i;
break;
}
}
while (end > start && anode_xkb_ascii_is_ws(src[end - 1])) end--;
for (size_t i = start; i < end; i++) {
if (src[i] == '/') start = i + 1;
}
size_t n = 0;
for (size_t i = start; i < end && n + 1 < out_sz; i++) {
char c = src[i];
if (c >= 'A' && c <= 'Z') {
out[n++] = (char)(c + ('a' - 'A'));
} else if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {
out[n++] = c;
}
}
out[n] = '\0';
return n > 0;
}
static inline bool anode_xkb_is_ignored_sym(const char *tok, size_t len) {
static const char *const ignored[] = {
"pc", "base", "evdev", "inet", "group", "compose", "level2", "level3", "level5",
"ctrl", "caps", "capslock", "altwin", "shift", "keypad", "kpdl", "nbsp",
"eurosign", "rupeesign", "terminate", "srvr_ctrl", "esperanto", "parens",
"misc", "typo", "compat", "complete", "empty", "default", "basic", "olpc",
"extra", "grab", "hyper", "scrolllock", "fkeys", "mod_led", "japan", "korean",
"solaris", "sun_vndr", "sgi_vndr", "macintosh_vndr", "digital_vndr",
"fujitsu_vndr", "hp_vndr", "sony_vndr", "sharp_vndr", "nokia_vndr",
"xfree68_vndr", "nec_vndr", "apple"
};
for (size_t i = 0; i < sizeof(ignored) / sizeof(ignored[0]); i++) {
if (anode_xkb_ascii_eq_ci(tok, len, ignored[i])) return true;
}
return false;
}
static inline bool anode_xkb_layout_from_symbols(const char *symbols, unsigned int group,
char *out, size_t out_sz) {
if (!out || out_sz == 0) return false;
out[0] = '\0';
if (!symbols || !symbols[0]) return false;
const char *p = symbols;
while (*p) {
while (*p == '+' || *p == '|' || anode_xkb_ascii_is_ws(*p)) p++;
if (!*p) break;
const char *tok_start = p;
while (*p && *p != '+' && *p != '|') p++;
const char *tok_end = p;
while (tok_end > tok_start && anode_xkb_ascii_is_ws(tok_end[-1])) tok_end--;
if (tok_end <= tok_start) continue;
/* Check for trailing :N XKB group selector */
unsigned int tok_grp = 1;
const char *eff_end = tok_end;
const char *colon = NULL;
for (const char *q = tok_end; q > tok_start; q--) {
if (q[-1] == ':') {
colon = q - 1;
break;
}
}
if (colon && colon + 1 < tok_end) {
bool all_digits = true;
unsigned int val = 0;
for (const char *q = colon + 1; q < tok_end; q++) {
if (*q < '0' || *q > '9') {
all_digits = false;
break;
}
val = val * 10U + (unsigned int)(*q - '0');
}
if (all_digits && val > 0) {
tok_grp = val;
eff_end = colon;
}
}
/* Strip optional (variant) suffix before matching component name */
size_t base_len = (size_t)(eff_end - tok_start);
for (size_t i = 0; i < base_len; i++) {
if (tok_start[i] == '(') {
base_len = i;
break;
}
}
while (base_len > 0 && anode_xkb_ascii_is_ws(tok_start[base_len - 1])) base_len--;
if (base_len == 0) continue;
if (anode_xkb_is_ignored_sym(tok_start, base_len)) continue;
if (tok_grp == group + 1U) {
if (anode_xkb_normalize_code(tok_start, base_len, out, out_sz)) return true;
}
}
return false;
}
static inline bool anode_xkb_layout_from_rules_prop(const unsigned char *prop,
unsigned long nbytes,
unsigned int group,
char *out, size_t out_sz) {
if (!out || out_sz == 0) return false;
out[0] = '\0';
if (!prop || nbytes == 0) return false;
/* _XKB_RULES_NAMES stores NUL-separated: rules, model, layouts, variants, options */
unsigned long pos = 0;
unsigned int field = 0;
while (pos < nbytes && field < 2) {
if (prop[pos] == '\0') field++;
pos++;
}
if (field != 2 || pos >= nbytes) return false;
unsigned long lay_start = pos;
unsigned long lay_end = lay_start;
while (lay_end < nbytes && prop[lay_end] != '\0') lay_end++;
unsigned long cur = lay_start;
unsigned int idx = 0;
while (cur <= lay_end) {
unsigned long seg_end = cur;
while (seg_end < lay_end && prop[seg_end] != ',') seg_end++;
if (idx == group) {
return anode_xkb_normalize_code((const char *)(prop + cur),
(size_t)(seg_end - cur), out, out_sz);
}
if (seg_end >= lay_end) break;
cur = seg_end + 1;
idx++;
}
return false;
}
static inline bool anode_xkb_layout_from_group_name(const char *gname, char *out, size_t out_sz) {
if (!out || out_sz < 2) {
if (out && out_sz > 0) out[0] = '\0';
return false;
}
out[0] = '\0';
if (!gname) return false;
size_t n = 0;
for (const char *p = gname; *p && n < 2 && n + 1 < out_sz; p++) {
char c = *p;
if (c >= 'A' && c <= 'Z') {
out[n++] = (char)(c + ('a' - 'A'));
} else if (c >= 'a' && c <= 'z') {
out[n++] = c;
}
}
out[n] = '\0';
return n > 0;
}
#endif /* ANODE_XKB_PARSE_H */
+93 -7
View File
@@ -1,5 +1,6 @@
#define _POSIX_C_SOURCE 200809L
#include "anode_plat.h"
#include "anode_xkb_parse.h"
#include <errno.h>
#include <fcntl.h>
@@ -12,6 +13,8 @@
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include <X11/Xatom.h>
#include <X11/XKBlib.h>
#include <X11/Xlib.h>
#ifdef __linux__
@@ -59,7 +62,65 @@ static int open_net_watch_fd(void) {
return -1;
}
static void build_status(char *out, size_t sz) {
static bool query_xkb_layout(Display *dpy, Window root, bool has_xkb, char *out, size_t out_sz) {
if (!out || out_sz == 0) return false;
out[0] = '\0';
if (!has_xkb || !dpy) return false;
XkbStateRec state;
memset(&state, 0, sizeof(state));
if (XkbGetState(dpy, XkbUseCoreKbd, &state) != Success) return false;
unsigned int grp = (unsigned int)state.group;
bool ok = false;
XkbDescPtr desc = XkbAllocKeyboard();
if (desc) {
if (XkbGetNames(dpy, XkbSymbolsNameMask | XkbGroupNamesMask, desc) != Success) {
XkbFreeKeyboard(desc, 0, True);
desc = NULL;
}
}
/* Priority 1: XKB symbols name (tracks active groups cleanly across setxkbmap / xkbcomp) */
if (desc && desc->names && desc->names->symbols != None) {
char *sym = XGetAtomName(dpy, desc->names->symbols);
if (sym) {
ok = anode_xkb_layout_from_symbols(sym, grp, out, out_sz);
XFree(sym);
}
}
/* Priority 2: root _XKB_RULES_NAMES property layouts CSV */
if (!ok) {
Atom r_atom = XInternAtom(dpy, "_XKB_RULES_NAMES", True);
if (r_atom != None) {
Atom act_type = None;
int act_fmt = 0;
unsigned long nitems = 0, bytes_after = 0;
unsigned char *prop = NULL;
if (XGetWindowProperty(dpy, root, r_atom, 0, 1024, False, XA_STRING,
&act_type, &act_fmt, &nitems, &bytes_after, &prop) == Success &&
prop && act_type == XA_STRING && act_fmt == 8 && nitems > 0) {
ok = anode_xkb_layout_from_rules_prop(prop, nitems, grp, out, out_sz);
}
if (prop) XFree(prop);
}
}
/* Priority 3: first two ASCII letters of the XKB group name */
if (!ok && desc && desc->names && grp < XkbNumKbdGroups && desc->names->groups[grp] != None) {
char *gname = XGetAtomName(dpy, desc->names->groups[grp]);
if (gname) {
ok = anode_xkb_layout_from_group_name(gname, out, out_sz);
XFree(gname);
}
}
if (desc) XkbFreeKeyboard(desc, 0, True);
return ok;
}
static void build_status(Display *dpy, Window root, bool has_xkb, char *out, size_t sz) {
int vol = 0;
bool muted = false;
char vol_str[32] = "";
@@ -100,13 +161,20 @@ static void build_status(char *out, size_t sz) {
snprintf(bat_str, sizeof(bat_str), "AC");
}
char kbd_str[16] = "";
query_xkb_layout(dpy, root, has_xkb, kbd_str, sizeof(kbd_str));
time_t now = time(NULL);
struct tm tmbuf;
localtime_r(&now, &tmbuf);
char time_str[32];
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M", &tmbuf);
if (vol_str[0]) {
if (vol_str[0] && kbd_str[0]) {
snprintf(out, sz, " %s | %s | %s | %s | %s ", vol_str, net_str, bat_str, kbd_str, time_str);
} else if (kbd_str[0]) {
snprintf(out, sz, " %s | %s | %s | %s ", net_str, bat_str, kbd_str, time_str);
} else if (vol_str[0]) {
snprintf(out, sz, " %s | %s | %s | %s ", vol_str, net_str, bat_str, time_str);
} else {
snprintf(out, sz, " %s | %s | %s ", net_str, bat_str, time_str);
@@ -133,6 +201,19 @@ int main(void) {
fprintf(stderr, "anode-statusd: cannot open X11 display\n");
return 1;
}
int xkb_op = 0, xkb_ev = 0, xkb_err = 0;
int xkb_maj = XkbMajorVersion, xkb_min = XkbMinorVersion;
bool has_xkb = XkbQueryExtension(dpy, &xkb_op, &xkb_ev, &xkb_err, &xkb_maj, &xkb_min) != 0;
if (has_xkb) {
XkbSelectEvents(dpy, XkbUseCoreKbd,
XkbNewKeyboardNotifyMask | XkbMapNotifyMask | XkbNamesNotifyMask,
XkbNewKeyboardNotifyMask | XkbMapNotifyMask | XkbNamesNotifyMask);
XkbSelectEventDetails(dpy, XkbUseCoreKbd, XkbStateNotify,
XkbAllStateComponentsMask, XkbGroupStateMask);
XSync(dpy, False);
}
Window root = DefaultRootWindow(dpy);
int xfd = ConnectionNumber(dpy);
int netfd = open_net_watch_fd();
@@ -141,18 +222,20 @@ int main(void) {
bool running = true;
while (running) {
while (XPending(dpy) > 0) {
XEvent ev;
XNextEvent(dpy, &ev);
}
char cur[512];
build_status(cur, sizeof(cur));
build_status(dpy, root, has_xkb, cur, sizeof(cur));
if (strcmp(cur, last_status) != 0) {
snprintf(last_status, sizeof(last_status), "%s", cur);
XStoreName(dpy, root, cur);
XFlush(dpy);
}
while (XPending(dpy) > 0) {
XEvent ev;
XNextEvent(dpy, &ev);
}
if (XPending(dpy) > 0) continue;
time_t now = time(NULL);
struct tm tmbuf;
@@ -178,6 +261,9 @@ int main(void) {
}
}
}
if (pfds[1].revents & (POLLERR | POLLHUP)) {
running = false;
}
if (netfd >= 0 && nfds > 2 && (pfds[2].revents & POLLIN)) {
char nbuf[1024];
while (read(netfd, nbuf, sizeof(nbuf)) > 0) {}
+154 -17
View File
@@ -62,7 +62,7 @@ enum { NetSupported, NetWMName, NetWMState, NetWMCheck,
NetSystemTrayOrientationHorz, NetSystemTrayVisual,
NetWMFullscreen, NetActiveWindow, NetWorkarea,
NetWMWindowType, NetWMWindowTypeDialog, NetWMWindowTypeDock,
NetWMStrutPartial, NetWMStrut, NetClientList, NetLast };
NetWMStrutPartial, NetWMStrut, NetClientList, NetWMPid, NetLast };
enum { Manager, Xembed, XembedInfo, XLast };
enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast };
enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkLauncher,
@@ -167,7 +167,7 @@ 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 acquirewm(void);
static void cleanup(void);
static void cleanupmon(Monitor *mon);
static void clientmessage(XEvent *e);
@@ -274,7 +274,10 @@ static void view(const Arg *arg);
static Client *wintoclient(Window w);
static Monitor *wintomon(Window w);
static Client *wintosystrayicon(Window w);
static Time getservertime(Window w);
static void selectionclear(XEvent *e);
static int xerror(Display *dpy, XErrorEvent *ee);
static int xerrorcheckother(Display *dpy, XErrorEvent *ee);
static int xerrordummy(Display *dpy, XErrorEvent *ee);
static int xerrorstart(Display *dpy, XErrorEvent *ee);
static void zoom(const Arg *arg);
@@ -296,6 +299,8 @@ static int (*xerrorxlib)(Display *, XErrorEvent *);
static unsigned int numlockmask = 0;
static volatile sig_atomic_t reload_pending = 0;
static volatile sig_atomic_t restart_dwm = 0;
static int replace_wm = 0;
static int otherwm_err = 0;
static int super_down = 0;
static int super_dirty = 0;
static unsigned long long super_down_ms = 0;
@@ -320,9 +325,11 @@ static void (*handler[LASTEvent])(XEvent *) = {
[PropertyNotify] = propertynotify,
[ReparentNotify] = reparentnotify,
[ResizeRequest] = resizerequest,
[SelectionClear] = selectionclear,
[UnmapNotify] = unmapnotify
};
static Atom wmatom[WMLast], netatom[NetLast], xatom[XLast];
static Atom utf8string = None, wmselatom = None;
static int running = 1;
static Cur *cursor[CurLast];
static Clr **scheme;
@@ -495,12 +502,125 @@ static void buttonpress(XEvent *e) {
}
}
static void checkotherwm(void) {
xerrorxlib = XSetErrorHandler(xerrorstart);
XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
XSync(dpy, False);
XSetErrorHandler(xerror);
XSync(dpy, False);
static Time getservertime(Window w) {
XEvent ev;
XSelectInput(dpy, w, PropertyChangeMask);
XChangeProperty(dpy, w, netatom[NetWMName], utf8string, 8,
PropModeAppend, (unsigned char *)"", 0);
XWindowEvent(dpy, w, PropertyChangeMask, &ev);
XSelectInput(dpy, w, 0);
return ev.xproperty.time;
}
static void selectionclear(XEvent *e) {
if (e->xselectionclear.window == wmcheckwin &&
e->xselectionclear.selection == wmselatom) {
restart_dwm = 0;
running = 0;
}
}
static void acquirewm(void) {
char selname[32];
Window prev_owner;
Time ts;
XClientMessageEvent cm;
xerrorxlib = XSetErrorHandler(xerror);
screen = DefaultScreen(dpy);
root = RootWindow(dpy, screen);
snprintf(selname, sizeof(selname), "WM_S%d", screen);
wmselatom = XInternAtom(dpy, selname, False);
xatom[Manager] = XInternAtom(dpy, "MANAGER", False);
netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
utf8string = XInternAtom(dpy, "UTF8_STRING", False);
wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0);
prev_owner = XGetSelectionOwner(dpy, wmselatom);
if (!replace_wm) {
if (prev_owner != None)
die("dwm: another window manager is already running");
xerrorxlib = XSetErrorHandler(xerrorstart);
XSelectInput(dpy, root, SubstructureRedirectMask);
XSync(dpy, False);
XSetErrorHandler(xerror);
XSync(dpy, False);
} else {
int prev_alive = (prev_owner != None && prev_owner != wmcheckwin) ? 1 : 0;
if (prev_alive) {
XSetErrorHandler(xerrordummy);
XSelectInput(dpy, prev_owner, StructureNotifyMask);
XSync(dpy, False);
XSetErrorHandler(xerror);
}
ts = getservertime(wmcheckwin);
XSetSelectionOwner(dpy, wmselatom, wmcheckwin, ts);
if (XGetSelectionOwner(dpy, wmselatom) != wmcheckwin)
die("dwm: failed to acquire WM_S selection");
memset(&cm, 0, sizeof(cm));
cm.type = ClientMessage;
cm.window = root;
cm.message_type = xatom[Manager];
cm.format = 32;
cm.data.l[0] = (long)ts;
cm.data.l[1] = (long)wmselatom;
cm.data.l[2] = (long)wmcheckwin;
XSendEvent(dpy, root, False, StructureNotifyMask, (XEvent *)&cm);
XSync(dpy, False);
unsigned long long deadline = now_ms() + 5000ULL;
for (;;) {
while (XPending(dpy) > 0) {
XEvent ev;
XNextEvent(dpy, &ev);
if (prev_alive && ev.type == DestroyNotify &&
ev.xdestroywindow.window == prev_owner) {
prev_alive = 0;
}
}
otherwm_err = 0;
XSetErrorHandler(xerrorcheckother);
XSelectInput(dpy, root, SubstructureRedirectMask);
XSync(dpy, False);
XSetErrorHandler(xerror);
if (!otherwm_err && prev_alive) {
XWindowAttributes wa;
XSetErrorHandler(xerrordummy);
if (!XGetWindowAttributes(dpy, prev_owner, &wa))
prev_alive = 0;
XSync(dpy, False);
XSetErrorHandler(xerror);
}
if (!otherwm_err && !prev_alive)
break;
if (now_ms() >= deadline)
break;
{
struct pollfd pfd = { .fd = ConnectionNumber(dpy), .events = POLLIN };
poll(&pfd, 1, 50);
}
}
if (otherwm_err)
die("dwm: timed out waiting for previous window manager to exit");
return;
}
ts = getservertime(wmcheckwin);
XSetSelectionOwner(dpy, wmselatom, wmcheckwin, ts);
if (XGetSelectionOwner(dpy, wmselatom) == wmcheckwin) {
memset(&cm, 0, sizeof(cm));
cm.type = ClientMessage;
cm.window = root;
cm.message_type = xatom[Manager];
cm.format = 32;
cm.data.l[0] = (long)ts;
cm.data.l[1] = (long)wmselatom;
cm.data.l[2] = (long)wmcheckwin;
XSendEvent(dpy, root, False, StructureNotifyMask, (XEvent *)&cm);
XSync(dpy, False);
}
}
static void cleanup(void) {
@@ -538,6 +658,8 @@ static void cleanup(void) {
free(scheme[SchemeNorm]);
free(scheme[SchemeSel]);
free(scheme);
XSelectInput(dpy, root, 0);
XDeleteProperty(dpy, root, netatom[NetWMCheck]);
XDestroyWindow(dpy, wmcheckwin);
drw_free(drw);
XSync(dpy, False);
@@ -1864,7 +1986,6 @@ static void setmfact(const Arg *arg) {
static void setup(void) {
XSetWindowAttributes wa;
Atom utf8string;
struct sigaction sa;
sigemptyset(&sa.sa_mask);
@@ -1923,6 +2044,7 @@ static void setup(void) {
netatom[NetWMStrutPartial] = XInternAtom(dpy, "_NET_WM_STRUT_PARTIAL", False);
netatom[NetWMStrut] = XInternAtom(dpy, "_NET_WM_STRUT", False);
netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
netatom[NetWMPid] = XInternAtom(dpy, "_NET_WM_PID", False);
xatom[Manager] = XInternAtom(dpy, "MANAGER", False);
xatom[Xembed] = XInternAtom(dpy, "_XEMBED", False);
xatom[XembedInfo] = XInternAtom(dpy, "_XEMBED_INFO", False);
@@ -1940,11 +2062,16 @@ static void setup(void) {
updateworkarea();
updatestatus();
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);
PropModeReplace, (unsigned char *)"ANODE WM", 8);
XStoreName(dpy, wmcheckwin, "ANODE WM");
{
unsigned long pid = (unsigned long)getpid();
XChangeProperty(dpy, wmcheckwin, netatom[NetWMPid], XA_CARDINAL, 32,
PropModeReplace, (unsigned char *)&pid, 1);
}
XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32,
PropModeReplace, (unsigned char *)&wmcheckwin, 1);
XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
@@ -2170,7 +2297,7 @@ static void updatebars(void) {
.background_pixmap = ParentRelative,
.event_mask = ButtonPressMask | ExposureMask
};
XClassHint ch = {"dwm", "dwm"};
XClassHint ch = {"anode-wm", "ANODE"};
for (m = mons; m; m = m->next) {
if (m->barwin) continue;
w = (unsigned int)m->ww;
@@ -2722,6 +2849,12 @@ static int xerror(Display *dpy, XErrorEvent *ee) {
return xerrorxlib(dpy, ee);
}
static int xerrorcheckother(Display *dpy, XErrorEvent *ee) {
(void)dpy; (void)ee;
otherwm_err = 1;
return 0;
}
static int xerrordummy(Display *dpy, XErrorEvent *ee) {
(void)dpy; (void)ee;
return 0;
@@ -2742,16 +2875,20 @@ static void zoom(const Arg *arg) {
}
int main(int argc, char *argv[]) {
if (argc == 2 && !strcmp("-v", argv[1])) {
die("dwm-" VERSION);
} else if (argc != 1) {
die("usage: dwm [-v]");
for (int i = 1; i < argc; i++) {
if (!strcmp("-v", argv[i])) {
die("dwm-" VERSION);
} else if (!strcmp("--replace", argv[i])) {
replace_wm = 1;
} else {
die("usage: dwm [-v] [--replace]");
}
}
if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
fputs("warning: no locale support\n", stderr);
if (!(dpy = XOpenDisplay(NULL)))
die("dwm: cannot open display");
checkotherwm();
acquirewm();
setup();
scan();
{