diff --git a/scripts/anode-replace b/scripts/anode-replace index 61ef1e8..9c118b6 100755 --- a/scripts/anode-replace +++ b/scripts/anode-replace @@ -160,6 +160,43 @@ get_win_pid() { MY_UID="$(id -u)" SELF_PID="$$" +norm_display() { + case "${1:-}" in + *.0) printf '%s\n' "${1%.0}" ;; + *) printf '%s\n' "${1:-}" ;; + esac +} + +pid_matches_display() { + _p="$1" + [ -n "${DISPLAY:-}" ] || return 0 + if [ -d "/proc/$SELF_PID" ]; then + [ -r "/proc/$_p/environ" ] || return 1 + _pdisp="$(tr '\0' '\n' < "/proc/$_p/environ" 2>/dev/null | awk 'substr($0, 1, 8) == "DISPLAY=" { print substr($0, 9); exit }' || true)" + [ -n "${_pdisp:-}" ] || return 1 + [ "$(norm_display "$_pdisp")" = "$(norm_display "$DISPLAY")" ] && return 0 + return 1 + fi + _pe="$(ps eww -p "$_p" 2>/dev/null || true)" + if [ -n "${_pe:-}" ]; then + _pdisp="$(printf '%s\n' "$_pe" | awk ' + { + for (i = 1; i <= NF; i++) { + if (substr($i, 1, 8) == "DISPLAY=") { + print substr($i, 9) + exit + } + } + } + ' || true)" + if [ -n "${_pdisp:-}" ]; then + [ "$(norm_display "$_pdisp")" = "$(norm_display "$DISPLAY")" ] && return 0 + return 1 + fi + fi + return 0 +} + find_wm_pid_by_name() { _wmname="$1" [ -n "$_wmname" ] || return 0 @@ -177,10 +214,14 @@ find_wm_pid_by_name() { sub(/^.*\//, "", c) if (tolower(c) == t) { print $2 - exit } } - ' + ' | while read -r _wpid; do + if pid_matches_display "$_wpid"; then + printf '%s\n' "$_wpid" + break + fi + done } get_ppid() { @@ -236,7 +277,9 @@ kill_my_procs() { if (c in want) print $2 } ' | while read -r _kpid; do - kill -TERM "$_kpid" 2>/dev/null || true + if pid_matches_display "$_kpid"; then + kill -TERM "$_kpid" 2>/dev/null || true + fi done } diff --git a/src/dwm/dwm.c b/src/dwm/dwm.c index bb0cac2..a9dd926 100644 --- a/src/dwm/dwm.c +++ b/src/dwm/dwm.c @@ -60,7 +60,7 @@ enum { SchemeNorm, SchemeSel }; enum { NetSupported, NetWMName, NetWMState, NetWMCheck, NetSystemTray, NetSystemTrayOP, NetSystemTrayOrientation, NetSystemTrayOrientationHorz, NetSystemTrayVisual, - NetWMFullscreen, NetActiveWindow, NetWorkarea, + NetWMFullscreen, NetWMFocused, NetActiveWindow, NetWorkarea, NetWMWindowType, NetWMWindowTypeDialog, NetWMWindowTypeDock, NetWMStrutPartial, NetWMStrut, NetClientList, NetWMPid, NetLast }; enum { Manager, Xembed, XembedInfo, XLast }; @@ -160,6 +160,7 @@ struct DockWin { }; /* function declarations */ +static void addwmstate(Client *c, Atom state); 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); @@ -184,10 +185,12 @@ static void drawbars(void); static void enternotify(XEvent *e); static void expose(XEvent *e); static void focus(Client *c); +static void focusarranged(Monitor *m); 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 extracteventtime(const XEvent *e, Time *out); +static Time getfocustime(void); static int getrootptr(int *x, int *y); static long getstate(Window w); static unsigned int getsystraywidth(void); @@ -195,6 +198,7 @@ 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 grid(Monitor *m); +static int hasatomprop(Client *c, Atom prop, Atom target); static void incnmaster(const Arg *arg); static void keypress(XEvent *e); static void keyrelease(XEvent *e); @@ -213,7 +217,9 @@ static void propertynotify(XEvent *e); static void quit(const Arg *arg); static Monitor *recttomon(int x, int y, int w, int h); static void reloadxres(const Arg *arg); +static unsigned long readatomlist(Client *c, Atom prop, Atom *out, unsigned long max_atoms); static void removesystrayicon(Client *i); +static void removewmstate(Client *c, Atom state); static void resize(Client *c, int x, int y, int w, int h, int interact); static void resizebarwin(Monitor *m); static void resizeclient(Client *c, int x, int y, int w, int h); @@ -226,6 +232,7 @@ static int sendevent(Window w, Atom proto, int m, long d0, long d1, long d2, lon static void sendmon(Client *c, Monitor *m); static void setclientstate(Client *c, long state); static void setfocus(Client *c); +static void setnofocus(void); static void setfullscreen(Client *c, int fullscreen); static void setlayout(const Arg *arg); static void setmfact(const Arg *arg); @@ -338,7 +345,8 @@ static Display *dpy; static Drw *drw; static Fnt *dwmfont = NULL; static Monitor *mons, *selmon; -static Window root, wmcheckwin; +static Window root, wmcheckwin, nofocuswin; +static Time last_event_time = CurrentTime; #include "config.h" @@ -662,10 +670,15 @@ static void cleanup(void) { free(scheme); XSelectInput(dpy, root, 0); XDeleteProperty(dpy, root, netatom[NetWMCheck]); + XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime); + if (nofocuswin != None) { + XDestroyWindow(dpy, nofocuswin); + nofocuswin = None; + } XDestroyWindow(dpy, wmcheckwin); + wmcheckwin = None; drw_free(drw); XSync(dpy, False); - XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime); XDeleteProperty(dpy, root, netatom[NetActiveWindow]); } @@ -691,33 +704,29 @@ static void clientmessage(XEvent *e) { cme->message_type == netatom[NetSystemTrayOP]) { if (cme->data.l[1] == SYSTEM_TRAY_REQUEST_DOCK) { Window iw = (Window)cme->data.l[2]; + long flags = 0; if (!iw || wintosystrayicon(iw)) return; + if (!XGetWindowAttributes(dpy, iw, &wa)) + return; if (!(c = (Client *)calloc(1, sizeof(Client)))) die("fatal: could not malloc() %zu bytes\n", sizeof(Client)); c->win = iw; c->mon = systraytomon(NULL); c->next = systray->icons; systray->icons = c; - if (!XGetWindowAttributes(dpy, c->win, &wa)) { - wa.width = bh; - wa.height = bh; - wa.border_width = 0; - wa.depth = DefaultDepth(dpy, screen); - } c->x = c->oldx = c->y = c->oldy = 0; c->w = c->oldw = wa.width; c->h = c->oldh = wa.height; c->oldbw = wa.border_width; c->bw = 0; c->isfloating = True; - long flags = 0; + XAddToSaveSet(dpy, c->win); + XReparentWindow(dpy, c->win, systray->win, 0, 0); + XSelectInput(dpy, c->win, StructureNotifyMask | SubstructureNotifyMask | PropertyChangeMask | ResizeRedirectMask); c->tags = getxembedflags(c->win, &flags) ? ((flags & XEMBED_MAPPED) ? 1 : 0) : 1; updatesizehints(c); updatesystrayicongeom(c, wa.width, wa.height); - XAddToSaveSet(dpy, c->win); - XSelectInput(dpy, c->win, StructureNotifyMask | SubstructureNotifyMask | PropertyChangeMask | ResizeRedirectMask); - XReparentWindow(dpy, c->win, systray->win, 0, 0); if (!systray->use_argb && wa.depth == DefaultDepth(dpy, screen)) { swa.background_pixel = scheme[SchemeNorm][ColBg].pixel; XChangeWindowAttributes(dpy, c->win, CWBackPixel, &swa); @@ -730,6 +739,7 @@ static void clientmessage(XEvent *e) { sendevent(c->win, xatom[Xembed], StructureNotifyMask, CurrentTime, XEMBED_WINDOW_ACTIVATE, 0, (long)systray->win, XEMBED_EMBEDDED_VERSION_VAL); } else { + XUnmapWindow(dpy, c->win); setclientstate(c, WithdrawnState); } XSync(dpy, False); @@ -747,8 +757,15 @@ static void clientmessage(XEvent *e) { (cme->data.l[0] == 2 && !c->isfullscreen))); } } else if (cme->message_type == netatom[NetActiveWindow]) { - if (c != selmon->sel && !c->isurgent) + if (ISVISIBLE(c) && c->mon == selmon) { + if (c != selmon->sel) + focus(c); + else + setfocus(c); + restack(selmon); + } else if (c != selmon->sel && !c->isurgent) { seturgent(c, 1); + } } } @@ -801,9 +818,12 @@ static void configurerequest(XEvent *e) { XWindowChanges wc; if ((c = wintoclient(ev->window))) { - if (ev->value_mask & CWBorderWidth) + if (c->isfullscreen) { + if (ISVISIBLE(c)) + configure(c); + } else if (ev->value_mask & CWBorderWidth) { c->bw = ev->border_width; - else if (c->isfloating || !selmon->lt[selmon->sellt]->arrange) { + } 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; } @@ -1012,19 +1032,51 @@ static void focus(Client *c) { attachstack(c); grabbuttons(c, 1); XSetWindowBorder(dpy, c->win, scheme[SchemeSel][ColBorder].pixel); + addwmstate(c, netatom[NetWMFocused]); setfocus(c); } else { - XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime); - XDeleteProperty(dpy, root, netatom[NetActiveWindow]); + Window none = None; + setnofocus(); + XChangeProperty(dpy, root, netatom[NetActiveWindow], XA_WINDOW, 32, + PropModeReplace, (unsigned char *)&none, 1); } selmon->sel = c; drawbars(); } +static void focusarranged(Monitor *m) { + Client *c; + if (!m) m = selmon; + for (c = m->stack; c && !ISVISIBLE(c); c = c->snext) ; + if (m->sel && m->sel != c) + unfocus(m->sel, (m == selmon && !c) ? 1 : 0); + if (m == selmon) { + if (m->sel != c) + setnofocus(); + XUngrabKeyboard(dpy, CurrentTime); + } + m->sel = c; + if (c) { + detachstack(c); + attachstack(c); + } + arrange(m); + if (m == selmon) + focus(c); + else + drawbar(m); +} + static void focusin(XEvent *e) { + Client *c; XFocusChangeEvent *ev = &e->xfocus; if (ev->mode == NotifyGrab || ev->mode == NotifyWhileGrabbed) return; + if (ev->detail == NotifyPointer || ev->detail == NotifyInferior || + ev->detail == NotifyDetailNone || ev->window == root) + return; + if (!(c = wintoclient(ev->window)) || !ISVISIBLE(c)) + return; if (selmon->sel && ev->window != selmon->sel->win) setfocus(selmon->sel); } @@ -1035,6 +1087,8 @@ static void focusmon(const Arg *arg) { if ((m = dirtomon(arg->i)) == selmon) return; Monitor *oldm = selmon; unfocus(selmon->sel, 0); + setnofocus(); + XUngrabKeyboard(dpy, CurrentTime); selmon = m; if (showsystray && !systraypinning) { resizebarwin(oldm); @@ -1060,22 +1114,94 @@ static void focusstack(const Arg *arg) { if (ISVISIBLE(i)) c = i; } if (c) { + if (c != selmon->sel) + setnofocus(); + XUngrabKeyboard(dpy, CurrentTime); focus(c); restack(selmon); } } -static Atom getatomprop(Client *c, Atom prop) { +static int extracteventtime(const XEvent *e, Time *out) { + switch (e->type) { + case KeyPress: + case KeyRelease: *out = e->xkey.time; return 1; + case ButtonPress: + case ButtonRelease: *out = e->xbutton.time; return 1; + case MotionNotify: *out = e->xmotion.time; return 1; + case EnterNotify: + case LeaveNotify: *out = e->xcrossing.time; return 1; + case PropertyNotify: *out = e->xproperty.time; return 1; + case SelectionClear: *out = e->xselectionclear.time; return 1; + default: return 0; + } +} + +static Time getfocustime(void) { + if (wmcheckwin != None) { + Time t = getservertime(wmcheckwin); + if (t != CurrentTime) + last_event_time = t; + } + return last_event_time; +} + +static unsigned long readatomlist(Client *c, Atom prop, Atom *out, unsigned long max_atoms) { int di; - unsigned long dl; + unsigned long dl, n = 0, copied = 0; unsigned char *p = NULL; - Atom da, atom = None; - if (XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, XA_ATOM, - &da, &di, &dl, &dl, &p) == Success && p) { - atom = *(Atom *)p; + Atom da = None; + if (XGetWindowProperty(dpy, c->win, prop, 0L, (long)max_atoms, False, XA_ATOM, + &da, &di, &n, &dl, &p) == Success && p) { + if (di == 32 && da == XA_ATOM) { + Atom *atoms = (Atom *)p; + copied = MIN(n, max_atoms); + for (unsigned long i = 0; i < copied; i++) + out[i] = atoms[i]; + } XFree(p); } - return atom; + return copied; +} + +static int hasatomprop(Client *c, Atom prop, Atom target) { + Atom atoms[64]; + unsigned long n = readatomlist(c, prop, atoms, LENGTH(atoms)); + for (unsigned long i = 0; i < n; i++) + if (atoms[i] == target) + return 1; + return 0; +} + +static void addwmstate(Client *c, Atom state) { + Atom atoms[64]; + unsigned long n = readatomlist(c, netatom[NetWMState], atoms, LENGTH(atoms) - 1); + for (unsigned long i = 0; i < n; i++) + if (atoms[i] == state) + return; + atoms[n++] = state; + XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, + PropModeReplace, (unsigned char *)atoms, (int)n); +} + +static void removewmstate(Client *c, Atom state) { + Atom atoms[64], out[64]; + unsigned long n = readatomlist(c, netatom[NetWMState], atoms, LENGTH(atoms)); + unsigned long m = 0; + int removed = 0; + for (unsigned long i = 0; i < n; i++) { + if (atoms[i] == state) + removed = 1; + else + out[m++] = atoms[i]; + } + if (!removed) + return; + if (m > 0) + XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, + PropModeReplace, (unsigned char *)out, (int)m); + else + XDeleteProperty(dpy, c->win, netatom[NetWMState]); } static int getrootptr(int *x, int *y) { @@ -1158,14 +1284,14 @@ static void grabkeys(void) { XUngrabKey(dpy, AnyKey, AnyModifier, root); - /* Monitor Super_L (Fn+Alt) for comfortable one-shot tap-latch fallback */ + /* Monitor Super_L (Fn+Alt) for comfortable one-shot tap-latch fallback without freezing pointer */ KeyCode super_kc = XKeysymToKeycode(dpy, XK_Super_L); if (super_kc) { for (j = 0; j < LENGTH(modifiers); j++) { - XGrabKey(dpy, super_kc, modifiers[j], root, True, GrabModeSync, GrabModeAsync); - XGrabKey(dpy, super_kc, Mod5Mask | modifiers[j], root, True, GrabModeSync, GrabModeAsync); - XGrabKey(dpy, super_kc, Mod1Mask | modifiers[j], root, True, GrabModeSync, GrabModeAsync); - XGrabKey(dpy, super_kc, Mod1Mask | Mod5Mask | modifiers[j], root, True, GrabModeSync, GrabModeAsync); + XGrabKey(dpy, super_kc, modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + XGrabKey(dpy, super_kc, Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + XGrabKey(dpy, super_kc, Mod1Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + XGrabKey(dpy, super_kc, Mod1Mask | Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); } } @@ -1249,7 +1375,6 @@ static void keypress(XEvent *e) { super_down = 1; super_dirty = 0; super_down_ms = t; - XAllowEvents(dpy, ReplayKeyboard, ev->time); return; } @@ -1288,7 +1413,12 @@ static void keypress(XEvent *e) { matched = 1; } if (matched && keys[i].func) { + if (super_down) { + super_down = 0; + super_dirty = 1; + } keys[i].func(&(keys[i].arg)); + XUngrabKeyboard(dpy, CurrentTime); return; } } @@ -1546,10 +1676,21 @@ static void mappingnotify(XEvent *e) { } static void mapnotify(XEvent *e) { + Client *i; XMapEvent *ev = &e->xmap; if (ev->window == root || (systray && ev->window == systray->win)) return; - if (!wintoclient(ev->window) && !wintosystrayicon(ev->window) && isdockwin(ev->window)) { + if ((i = wintosystrayicon(ev->window))) { + long flags = 0; + if (!i->tags && (!getxembedflags(i->win, &flags) || (flags & XEMBED_MAPPED))) { + i->tags = 1; + setclientstate(i, NormalState); + updatesystray(1); + drawbars(); + } + return; + } + if (!wintoclient(ev->window) && isdockwin(ev->window)) { XSelectInput(dpy, ev->window, PropertyChangeMask); dockadd(ev->window); } @@ -1893,7 +2034,10 @@ static void run(void) { grabkeys(); } while (XPending(dpy) > 0) { + Time evtime = CurrentTime; XNextEvent(dpy, &ev); + if (extracteventtime(&ev, &evtime) && evtime != CurrentTime) + last_event_time = evtime; if (handler[ev.type]) handler[ev.type](&ev); } @@ -1933,7 +2077,9 @@ static void scan(void) { } static void sendmon(Client *c, Monitor *m) { + Monitor *oldm; if (c->mon == m) return; + oldm = c->mon; unfocus(c, 1); detach(c); detachstack(c); @@ -1941,8 +2087,8 @@ static void sendmon(Client *c, Monitor *m) { c->tags = m->tagset[m->seltags]; attach(c); attachstack(c); - focus(NULL); - arrange(NULL); + focusarranged(oldm); + focusarranged(m); } static void setclientstate(Client *c, long state) { @@ -1983,34 +2129,47 @@ static int sendevent(Window w, Atom proto, int mask, long d0, long d1, long d2, } static void setfocus(Client *c) { - if (!c->neverfocus) { + Time ts; + 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->win, wmatom[WMTakeFocus], NoEventMask, (long)wmatom[WMTakeFocus], CurrentTime, 0, 0, 0); + ts = getfocustime(); + sendevent(c->win, wmatom[WMTakeFocus], NoEventMask, + (long)wmatom[WMTakeFocus], (long)ts, 0, 0, 0); + XChangeProperty(dpy, root, netatom[NetActiveWindow], XA_WINDOW, 32, + PropModeReplace, (unsigned char *)&(c->win), 1); +} + +static void setnofocus(void) { + XSetInputFocus(dpy, nofocuswin != None ? nofocuswin : root, + RevertToPointerRoot, CurrentTime); } static 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); + addwmstate(c, netatom[NetWMFullscreen]); 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); + if (ISVISIBLE(c)) { + resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh); + XRaiseWindow(dpy, c->win); + } else { + c->oldx = c->x; c->oldy = c->y; + c->oldw = c->w; c->oldh = c->h; + c->x = c->mon->mx; c->y = c->mon->my; + c->w = c->mon->mw; c->h = c->mon->mh; + } } else if (!fullscreen && c->isfullscreen) { - XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, - PropModeReplace, (unsigned char *)0, 0); + removewmstate(c, netatom[NetWMFullscreen]); 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); + if (ISVISIBLE(c)) + resizeclient(c, c->x, c->y, c->w, c->h); arrange(c->mon); } } @@ -2087,6 +2246,7 @@ static void setup(void) { 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[NetWMFocused] = XInternAtom(dpy, "_NET_WM_STATE_FOCUSED", False); netatom[NetWorkarea] = XInternAtom(dpy, "_NET_WORKAREA", False); netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False); netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False); @@ -2112,6 +2272,16 @@ static void setup(void) { updateworkarea(); updatestatus(); + { + XSetWindowAttributes nwa; + nwa.override_redirect = True; + nwa.event_mask = NoEventMask; + nofocuswin = XCreateWindow(dpy, root, -10, -10, 1, 1, 0, + 0, InputOnly, CopyFromParent, + CWOverrideRedirect | CWEventMask, &nwa); + XMapWindow(dpy, nofocuswin); + } + XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmcheckwin, 1); XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8, @@ -2131,8 +2301,7 @@ static void setup(void) { wa.cursor = cursor[CurNormal]->cursor; wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask | ButtonPressMask | PointerMotionMask | EnterWindowMask | - LeaveWindowMask | StructureNotifyMask | PropertyChangeMask | - FocusChangeMask; + LeaveWindowMask | StructureNotifyMask | PropertyChangeMask; XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa); XSelectInput(dpy, root, wa.event_mask); grabkeys(); @@ -2151,9 +2320,19 @@ static void seturgent(Client *c, int urg) { static void showhide(Client *c) { if (!c) return; if (ISVISIBLE(c)) { - 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); + if (c->isfullscreen) { + c->bw = 0; + c->x = c->mon->mx; + c->y = c->mon->my; + c->w = c->mon->mw; + c->h = c->mon->mh; + XMoveResizeWindow(dpy, c->win, c->x, c->y, (unsigned int)c->w, (unsigned int)c->h); + configure(c); + } else { + XMoveWindow(dpy, c->win, c->x, c->y); + if (!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) + resize(c, c->x, c->y, c->w, c->h, 0); + } showhide(c->snext); } else { showhide(c->snext); @@ -2207,8 +2386,7 @@ static Monitor *systraytomon(Monitor *m) { static void tag(const Arg *arg) { if (selmon->sel && (arg->ui & TAGMASK)) { selmon->sel->tags = arg->ui & TAGMASK; - focus(NULL); - arrange(selmon); + focusarranged(selmon); } } @@ -2274,8 +2452,7 @@ static void toggletag(const Arg *arg) { newtags = selmon->sel->tags ^ (arg->ui & TAGMASK); if (newtags) { selmon->sel->tags = newtags; - focus(NULL); - arrange(selmon); + focusarranged(selmon); } } @@ -2283,8 +2460,7 @@ 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); + focusarranged(selmon); } } @@ -2292,9 +2468,12 @@ static void unfocus(Client *c, int setfocus) { if (!c) return; grabbuttons(c, 0); XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColBorder].pixel); + removewmstate(c, netatom[NetWMFocused]); if (setfocus) { - XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime); - XDeleteProperty(dpy, root, netatom[NetActiveWindow]); + Window none = None; + setnofocus(); + XChangeProperty(dpy, root, netatom[NetActiveWindow], XA_WINDOW, 32, + PropModeReplace, (unsigned char *)&none, 1); } } @@ -2831,10 +3010,10 @@ static void updatetitle(Client *c) { } static 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; + if (hasatomprop(c, netatom[NetWMState], netatom[NetWMFullscreen])) + setfullscreen(c, 1); + if (hasatomprop(c, netatom[NetWMWindowType], netatom[NetWMWindowTypeDialog])) + c->isfloating = 1; } static void updatewmhints(Client *c) { @@ -2858,8 +3037,7 @@ static void view(const Arg *arg) { selmon->seltags ^= 1; if (arg->ui & TAGMASK) selmon->tagset[selmon->seltags] = arg->ui & TAGMASK; - focus(NULL); - arrange(selmon); + focusarranged(selmon); } static Client *wintoclient(Window w) { diff --git a/tests/test_replace.py b/tests/test_replace.py index 0f1f871..829eb52 100755 --- a/tests/test_replace.py +++ b/tests/test_replace.py @@ -786,6 +786,118 @@ def test_switch_session_stale_i3sock_fallback(): terminate(xvfb) +def test_replace_display_scoped_daemon_cleanup(): + disp = pick_display() + other_disp = ":199" + cc = os.environ.get("CC", "cc") + with tempfile.TemporaryDirectory() as tmp: + env = make_env(tmp, disp) + daemon_dir = os.path.join(tmp, "daemons") + os.makedirs(daemon_dir, exist_ok=True) + sleeper_c = os.path.join(tmp, "sleeper.c") + sleeper_bin = os.path.join(tmp, "sleeper") + with open(sleeper_c, "w", encoding="utf-8") as f: + f.write( + "#include \n" + "#include \n" + "static void on_term(int s) { (void)s; _exit(0); }\n" + "int main(void) {\n" + " signal(SIGTERM, on_term);\n" + " while (1) pause();\n" + " return 0;\n" + "}\n" + ) + subprocess.run([cc, "-O2", sleeper_c, "-o", sleeper_bin], check=True) + statusd_bin = os.path.join(daemon_dir, "anode-statusd") + dunst_bin = os.path.join(daemon_dir, "dunst") + os.link(sleeper_bin, statusd_bin) + os.link(sleeper_bin, dunst_bin) + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + dwm1 = None + dpy = None + new_pid = None + procs = [] + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0) + assert dpy + root = X11.XDefaultRootWindow(dpy) + + dwm1 = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0) + assert wm1 + + same_statusd = subprocess.Popen( + [statusd_bin], env=dict(env, DISPLAY=f"{disp}.0"), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + other_statusd = subprocess.Popen( + [statusd_bin], env=dict(env, DISPLAY=other_disp), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + same_dunst = subprocess.Popen( + [dunst_bin], env=dict(env, DISPLAY=disp), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + other_dunst = subprocess.Popen( + [dunst_bin], env=dict(env, DISPLAY=other_disp), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + procs = [same_statusd, other_statusd, same_dunst, other_dunst] + + if os.path.isdir(f"/proc/{os.getpid()}"): + expected_comm = [ + (same_statusd, "anode-statusd"), + (other_statusd, "anode-statusd"), + (same_dunst, "dunst"), + (other_dunst, "dunst"), + ] + def comms_ready(): + for p, name in expected_comm: + try: + with open(f"/proc/{p.pid}/comm", "r", encoding="utf-8") as cf: + if cf.read().strip() != name: + return False + except OSError: + return False + return True + assert wait_until(comms_ready, timeout=3.0), "dummy daemons did not finish exec" + else: + time.sleep(0.15) + + rep = subprocess.run( + [REPLACE_BIN, "--no-autostart"], + env=env, capture_output=True, text=True, + ) + assert rep.returncode == 0, f"anode-replace failed: stdout={rep.stdout} stderr={rep.stderr}" + + wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK") + if wm2 and wm2 != wm1: + new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID") + + assert wait_until(lambda: same_statusd.poll() is not None, timeout=4.0), ( + f"anode-statusd on {disp}.0 was not stopped by anode-replace" + ) + assert wait_until(lambda: same_dunst.poll() is not None, timeout=4.0), ( + f"dunst on {disp} was not stopped by anode-replace" + ) + time.sleep(0.2) + assert other_statusd.poll() is None, f"anode-statusd on {other_disp} was killed across displays" + assert other_dunst.poll() is None, f"dunst on {other_disp} was killed across displays" + finally: + for p in procs: + terminate(p) + terminate(dwm1) + kill_pid_and_wait(new_pid) + time.sleep(0.15) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + def main(): if not shutil.which("Xvfb"): print("test_replace: Xvfb not installed (skipping)") @@ -798,6 +910,7 @@ def main(): test_dm_session_leader_guard() test_switch_session_xprofile_handoff() test_switch_session_stale_i3sock_fallback() + test_replace_display_scoped_daemon_cleanup() print("test_replace: OK") return 0 diff --git a/tests/test_x11_xvfb.py b/tests/test_x11_xvfb.py index a1de8af..77ca284 100755 --- a/tests/test_x11_xvfb.py +++ b/tests/test_x11_xvfb.py @@ -72,6 +72,26 @@ class XWMHints(ctypes.Structure): ] +class XSetWindowAttributes(ctypes.Structure): + _fields_ = [ + ("background_pixmap", ctypes.c_ulong), + ("background_pixel", ctypes.c_ulong), + ("border_pixmap", ctypes.c_ulong), + ("border_pixel", ctypes.c_ulong), + ("bit_gravity", ctypes.c_int), + ("win_gravity", ctypes.c_int), + ("backing_store", ctypes.c_int), + ("backing_planes", ctypes.c_ulong), + ("backing_pixel", ctypes.c_ulong), + ("save_under", ctypes.c_int), + ("event_mask", ctypes.c_long), + ("do_not_propagate_mask", ctypes.c_long), + ("override_redirect", ctypes.c_int), + ("colormap", ctypes.c_ulong), + ("cursor", ctypes.c_ulong), + ] + + X11.XOpenDisplay.argtypes = [ctypes.c_char_p] X11.XOpenDisplay.restype = Display_p X11.XCloseDisplay.argtypes = [Display_p] @@ -95,6 +115,8 @@ X11.XCreateSimpleWindow.argtypes = [ ] X11.XCreateSimpleWindow.restype = Window X11.XDestroyWindow.argtypes = [Display_p, Window] +X11.XMapWindow.argtypes = [Display_p, Window] +X11.XChangeWindowAttributes.argtypes = [Display_p, Window, ctypes.c_ulong, ctypes.POINTER(XSetWindowAttributes)] X11.XChangeProperty.argtypes = [ Display_p, Window, Atom, Atom, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int ] @@ -770,6 +792,564 @@ def test_gtk_xsettings_no_double_scale(): terminate(xvfb) +def test_fullscreen_workspace_switch_focus(): + if not shutil.which("xdotool"): + print("test_x11_xvfb: xdotool not installed (skipping fullscreen focus test)") + return + disp = pick_display() + with tempfile.TemporaryDirectory() as home: + env = dict(os.environ) + env["DISPLAY"] = disp + env["HOME"] = home + env["XDG_CONFIG_HOME"] = os.path.join(home, ".config") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + env["PATH"] = ( + os.path.join(BUILD, "dwm") + ":" + + os.path.join(BUILD, "st") + ":" + + os.path.join(ROOT, "scripts") + ":" + + env.get("PATH", "") + ) + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-noreset", "-screen", "0", "1280x800x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + dpy = None + dwm = None + game = None + tag2_client = None + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode())) + assert dpy, f"Failed to open Xvfb {disp}" + + dwm = subprocess.Popen([os.path.join(BUILD, "dwm", "dwm")], env=env) + tray_atom = X11.XInternAtom(dpy, b"_NET_SYSTEM_TRAY_S0", 0) + assert wait_until(lambda: X11.XGetSelectionOwner(dpy, tray_atom)), "DWM failed to start on Xvfb" + + game_code = ( + "import ctypes, ctypes.util, json, sys, time\n" + "X11 = ctypes.CDLL(ctypes.util.find_library('X11') or 'libX11.so.6')\n" + "X11.XOpenDisplay.restype = ctypes.c_void_p\n" + "X11.XDefaultRootWindow.argtypes = [ctypes.c_void_p]\n" + "X11.XDefaultRootWindow.restype = ctypes.c_ulong\n" + "X11.XCreateSimpleWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_ulong, ctypes.c_ulong]\n" + "X11.XCreateSimpleWindow.restype = ctypes.c_ulong\n" + "X11.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]\n" + "X11.XInternAtom.restype = ctypes.c_ulong\n" + "X11.XChangeProperty.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]\n" + "X11.XSelectInput.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_long]\n" + "X11.XMapWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong]\n" + "X11.XFlush.argtypes = [ctypes.c_void_p]\n" + "X11.XPending.argtypes = [ctypes.c_void_p]\n" + "X11.XNextEvent.argtypes = [ctypes.c_void_p, ctypes.c_void_p]\n" + "X11.XGrabPointer.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_uint, ctypes.c_int, ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong]\n" + "X11.XGrabPointer.restype = ctypes.c_int\n" + "X11.XUngrabPointer.argtypes = [ctypes.c_void_p, ctypes.c_ulong]\n" + "X11.XTranslateCoordinates.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_ulong)]\n" + "class XFocusChangeEvent(ctypes.Structure):\n" + " _fields_ = [('type', ctypes.c_int), ('serial', ctypes.c_ulong), ('send_event', ctypes.c_int),\n" + " ('display', ctypes.c_void_p), ('window', ctypes.c_ulong), ('mode', ctypes.c_int), ('detail', ctypes.c_int)]\n" + "class XConfigureEvent(ctypes.Structure):\n" + " _fields_ = [('type', ctypes.c_int), ('serial', ctypes.c_ulong), ('send_event', ctypes.c_int),\n" + " ('display', ctypes.c_void_p), ('event', ctypes.c_ulong), ('window', ctypes.c_ulong),\n" + " ('x', ctypes.c_int), ('y', ctypes.c_int), ('width', ctypes.c_int), ('height', ctypes.c_int),\n" + " ('border_width', ctypes.c_int), ('above', ctypes.c_ulong), ('override_redirect', ctypes.c_int)]\n" + "dpy = X11.XOpenDisplay(None)\n" + "root = X11.XDefaultRootWindow(dpy)\n" + "win = X11.XCreateSimpleWindow(dpy, root, 0, 0, 1280, 800, 0, 0, 0x222222)\n" + "wm_state = X11.XInternAtom(dpy, b'_NET_WM_STATE', 0)\n" + "wm_fs = X11.XInternAtom(dpy, b'_NET_WM_STATE_FULLSCREEN', 0)\n" + "fs_val = ctypes.c_ulong(wm_fs)\n" + "X11.XChangeProperty(dpy, win, wm_state, 4, 32, 0, ctypes.byref(fs_val), 1)\n" + "mask = (1<<0)|(1<<2)|(1<<6)|(1<<4)|(1<<5)|(1<<17)|(1<<21)\n" + "X11.XSelectInput(dpy, win, mask)\n" + "X11.XMapWindow(dpy, win)\n" + "X11.XFlush(dpy)\n" + "buf = (ctypes.c_long * 32)()\n" + "print('READY', flush=True)\n" + "t0 = time.monotonic()\n" + "while time.monotonic() - t0 < 8.0:\n" + " while X11.XPending(dpy):\n" + " X11.XNextEvent(dpy, buf)\n" + " et = ctypes.c_int.from_buffer(buf).value\n" + " if et == 9:\n" + " fe = XFocusChangeEvent.from_buffer(buf)\n" + " tx, ty, ch = ctypes.c_int(), ctypes.c_int(), ctypes.c_ulong()\n" + " X11.XTranslateCoordinates(dpy, win, root, 0, 0, ctypes.byref(tx), ctypes.byref(ty), ctypes.byref(ch))\n" + " grc = X11.XGrabPointer(dpy, win, 1, (1<<2)|(1<<3)|(1<<6), 1, 1, win, 0, 0)\n" + " print(json.dumps({'ev': 'FocusIn', 'mode': fe.mode, 'pos': [tx.value, ty.value], 'grab': grc}), flush=True)\n" + " elif et == 10:\n" + " fe = XFocusChangeEvent.from_buffer(buf)\n" + " X11.XUngrabPointer(dpy, 0)\n" + " print(json.dumps({'ev': 'FocusOut', 'mode': fe.mode}), flush=True)\n" + " elif et == 22:\n" + " ce = XConfigureEvent.from_buffer(buf)\n" + " print(json.dumps({'ev': 'ConfigureNotify', 'pos': [ce.x, ce.y], 'size': [ce.width, ce.height]}), flush=True)\n" + " elif et in (2, 4, 6, 7, 8):\n" + " names = {2: 'KeyPress', 4: 'ButtonPress', 6: 'MotionNotify', 7: 'EnterNotify', 8: 'LeaveNotify'}\n" + " print(json.dumps({'ev': names[et]}), flush=True)\n" + " time.sleep(0.005)\n" + ) + game = subprocess.Popen( + [sys.executable, "-c", game_code], + env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + assert game.stdout.readline().strip() == "READY" + time.sleep(0.35) + + subprocess.run(["xdotool", "mousemove", "640", "400", "click", "1"], env=env, check=True) + time.sleep(0.15) + + # Switch Tag 1 -> Tag 2 while holding Super_L + subprocess.run(["xdotool", "keydown", "Super_L"], env=env, check=True) + time.sleep(0.08) + subprocess.run(["xdotool", "key", "2"], env=env, check=True) + time.sleep(0.12) + subprocess.run(["xdotool", "keyup", "Super_L"], env=env, check=True) + time.sleep(0.25) + + # Open and focus a window on Tag 2 so Tag 2 takes X11 focus/pointer + tag2_client = subprocess.Popen( + [os.path.join(BUILD, "st", "st"), "-e", "sh", "-c", "sleep 4"], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + time.sleep(0.4) + subprocess.run(["xdotool", "mousemove", "400", "400", "click", "1"], env=env, check=True) + time.sleep(0.2) + + # Switch Tag 2 -> Tag 1 while holding Super_L (this previously caused GrabFrozen & offscreen FocusIn) + subprocess.run(["xdotool", "keydown", "Super_L"], env=env, check=True) + time.sleep(0.08) + subprocess.run(["xdotool", "key", "1"], env=env, check=True) + time.sleep(0.12) + subprocess.run(["xdotool", "keyup", "Super_L"], env=env, check=True) + time.sleep(0.3) + + # Interact with game after returning to Tag 1 + subprocess.run(["xdotool", "mousemove", "500", "500", "click", "1", "mousemove", "700", "300", "key", "a"], + env=env, check=True) + time.sleep(0.25) + + # Verify quick Super_L tap-latch still works under GrabModeAsync + subprocess.run(["xdotool", "key", "Super_L"], env=env, check=True) + time.sleep(0.08) + subprocess.run(["xdotool", "key", "2"], env=env, check=True) + time.sleep(0.25) + + terminate(game) + out, err = game.communicate(timeout=3) + import json + events = [json.loads(line) for line in out.splitlines() if line.strip().startswith("{")] + + offscreen_idx = next((i for i, e in enumerate(events) if e["ev"] == "ConfigureNotify" and e["pos"][0] < 0), None) + assert offscreen_idx is not None, f"Game never moved offscreen on tag switch: {events}" + + post_return = events[offscreen_idx:] + onscreen_cfg_idx = next( + (i for i, e in enumerate(post_return) + if e["ev"] == "ConfigureNotify" and e["pos"] == [0, 0] and e["size"] == [1280, 800]), + None, + ) + assert onscreen_cfg_idx is not None, f"Missing ConfigureNotify(0,0) on return to Tag 1: {post_return}" + + first_focusin_idx = next((i for i, e in enumerate(post_return) if e["ev"] == "FocusIn"), None) + assert first_focusin_idx is not None, f"Missing FocusIn on return to Tag 1: {post_return}" + assert onscreen_cfg_idx < first_focusin_idx, f"FocusIn arrived before ConfigureNotify(0,0): {post_return}" + + fi = post_return[first_focusin_idx] + assert fi["pos"] == [0, 0], f"Game was offscreen at FocusIn: {fi}" + assert fi["mode"] == 0, f"FocusIn was not NotifyNormal (Super_L grab still active?): {fi}" + assert fi["grab"] == 0, f"XGrabPointer failed on FocusIn after return (GrabFrozen/etc): {fi} ({post_return})" + + # Ensure no FocusIn while holding Super_L failed grab AND mouse/key events worked after returning + post_focus_names = [e["ev"] for e in post_return[first_focusin_idx:]] + for req in ("MotionNotify", "ButtonPress", "KeyPress"): + assert req in post_focus_names, f"Missing {req} after return to Tag 1: {post_return}" + + # Confirm tap-latch switched back away to Tag 2 at the end + last_off = next((i for i, e in enumerate(post_return[first_focusin_idx:]) if e["ev"] == "ConfigureNotify" and e["pos"][0] < 0), None) + assert last_off is not None, f"Super_L tap-latch did not switch back to Tag 2: {post_return}" + finally: + terminate(tag2_client) + terminate(game) + terminate(dwm) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + +def test_wine_take_focus_workspace_switch(): + if not shutil.which("xdotool"): + print("test_x11_xvfb: xdotool not installed (skipping Wine WM_TAKE_FOCUS test)") + return + disp = pick_display() + with tempfile.TemporaryDirectory() as home: + env = dict(os.environ) + env["DISPLAY"] = disp + env["HOME"] = home + env["XDG_CONFIG_HOME"] = os.path.join(home, ".config") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + env["PATH"] = ( + os.path.join(BUILD, "dwm") + ":" + + os.path.join(BUILD, "st") + ":" + + os.path.join(ROOT, "scripts") + ":" + + env.get("PATH", "") + ) + subprocess.run([os.path.join(ROOT, "scripts", "anode-apply-scale"), "1.00", "--touch=0"], env=env, check=True) + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-noreset", "-screen", "0", "1280x800x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + dpy = None + dwm = None + wine_sim = None + tag2_client = None + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode())) + assert dpy, f"Failed to open Xvfb {disp}" + + dwm = subprocess.Popen([os.path.join(BUILD, "dwm", "dwm")], env=env) + tray_atom = X11.XInternAtom(dpy, b"_NET_SYSTEM_TRAY_S0", 0) + assert wait_until(lambda: X11.XGetSelectionOwner(dpy, tray_atom)), "DWM failed to start on Xvfb" + + sim_code = ( + "import ctypes, ctypes.util, json, time\n" + "X11 = ctypes.CDLL(ctypes.util.find_library('X11') or 'libX11.so.6')\n" + "X11.XOpenDisplay.restype = ctypes.c_void_p\n" + "X11.XDefaultRootWindow.argtypes = [ctypes.c_void_p]\n" + "X11.XDefaultRootWindow.restype = ctypes.c_ulong\n" + "X11.XCreateSimpleWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_ulong, ctypes.c_ulong]\n" + "X11.XCreateSimpleWindow.restype = ctypes.c_ulong\n" + "X11.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]\n" + "X11.XInternAtom.restype = ctypes.c_ulong\n" + "X11.XChangeProperty.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]\n" + "X11.XSetWMProtocols.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong), ctypes.c_int]\n" + "class XWMHints(ctypes.Structure):\n" + " _fields_ = [('flags', ctypes.c_long), ('input', ctypes.c_int), ('initial_state', ctypes.c_int),\n" + " ('icon_pixmap', ctypes.c_ulong), ('icon_window', ctypes.c_ulong),\n" + " ('icon_x', ctypes.c_int), ('icon_y', ctypes.c_int),\n" + " ('icon_mask', ctypes.c_ulong), ('window_group', ctypes.c_ulong)]\n" + "class XFocusChangeEvent(ctypes.Structure):\n" + " _fields_ = [('type', ctypes.c_int), ('serial', ctypes.c_ulong), ('send_event', ctypes.c_int),\n" + " ('display', ctypes.c_void_p), ('window', ctypes.c_ulong), ('mode', ctypes.c_int), ('detail', ctypes.c_int)]\n" + "class XConfigureEvent(ctypes.Structure):\n" + " _fields_ = [('type', ctypes.c_int), ('serial', ctypes.c_ulong), ('send_event', ctypes.c_int),\n" + " ('display', ctypes.c_void_p), ('event', ctypes.c_ulong), ('window', ctypes.c_ulong),\n" + " ('x', ctypes.c_int), ('y', ctypes.c_int), ('width', ctypes.c_int), ('height', ctypes.c_int),\n" + " ('border_width', ctypes.c_int), ('above', ctypes.c_ulong), ('override_redirect', ctypes.c_int)]\n" + "class XClientMessageData(ctypes.Union):\n" + " _fields_ = [('b', ctypes.c_char * 20), ('s', ctypes.c_short * 10), ('l', ctypes.c_long * 5)]\n" + "class XClientMessageEvent(ctypes.Structure):\n" + " _fields_ = [('type', ctypes.c_int), ('serial', ctypes.c_ulong), ('send_event', ctypes.c_int),\n" + " ('display', ctypes.c_void_p), ('window', ctypes.c_ulong), ('message_type', ctypes.c_ulong),\n" + " ('format', ctypes.c_int), ('data', XClientMessageData)]\n" + "X11.XAllocWMHints.restype = ctypes.POINTER(XWMHints)\n" + "X11.XSetWMHints.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.POINTER(XWMHints)]\n" + "X11.XFree.argtypes = [ctypes.c_void_p]\n" + "X11.XSelectInput.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_long]\n" + "X11.XMapWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong]\n" + "X11.XFlush.argtypes = [ctypes.c_void_p]\n" + "X11.XPending.argtypes = [ctypes.c_void_p]\n" + "X11.XNextEvent.argtypes = [ctypes.c_void_p, ctypes.c_void_p]\n" + "X11.XSetInputFocus.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong]\n" + "X11.XGrabPointer.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_uint, ctypes.c_int, ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong]\n" + "X11.XGrabPointer.restype = ctypes.c_int\n" + "X11.XUngrabPointer.argtypes = [ctypes.c_void_p, ctypes.c_ulong]\n" + "X11.XTranslateCoordinates.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_ulong)]\n" + "dpy = X11.XOpenDisplay(None)\n" + "root = X11.XDefaultRootWindow(dpy)\n" + "win = X11.XCreateSimpleWindow(dpy, root, 0, 0, 800, 600, 0, 0, 0x222222)\n" + "wmh = X11.XAllocWMHints()\n" + "wmh.contents.flags = 1\n" # InputHint + "wmh.contents.input = 0\n" # globally-active Wine-style client + "X11.XSetWMHints(dpy, win, wmh)\n" + "X11.XFree(wmh)\n" + "wm_proto = X11.XInternAtom(dpy, b'WM_PROTOCOLS', 0)\n" + "wm_del = X11.XInternAtom(dpy, b'WM_DELETE_WINDOW', 0)\n" + "wm_take = X11.XInternAtom(dpy, b'WM_TAKE_FOCUS', 0)\n" + "protos = (ctypes.c_ulong * 2)(wm_del, wm_take)\n" + "X11.XSetWMProtocols(dpy, win, protos, 2)\n" + "wm_state = X11.XInternAtom(dpy, b'_NET_WM_STATE', 0)\n" + "wm_maxh = X11.XInternAtom(dpy, b'_NET_WM_STATE_MAXIMIZED_HORZ', 0)\n" + "wm_fs = X11.XInternAtom(dpy, b'_NET_WM_STATE_FULLSCREEN', 0)\n" + "states = (ctypes.c_ulong * 2)(wm_maxh, wm_fs)\n" # fullscreen NOT at index 0 + "X11.XChangeProperty(dpy, win, wm_state, 4, 32, 0, states, 2)\n" + "mask = (1<<0)|(1<<2)|(1<<6)|(1<<4)|(1<<5)|(1<<17)|(1<<21)\n" + "X11.XSelectInput(dpy, win, mask)\n" + "X11.XMapWindow(dpy, win)\n" + "X11.XFlush(dpy)\n" + "buf = (ctypes.c_long * 32)()\n" + "print(json.dumps({'ready': int(win)}), flush=True)\n" + "t0 = time.monotonic()\n" + "while time.monotonic() - t0 < 10.0:\n" + " while X11.XPending(dpy):\n" + " X11.XNextEvent(dpy, buf)\n" + " et = ctypes.c_int.from_buffer(buf).value\n" + " if et == 33:\n" + " cm = XClientMessageEvent.from_buffer(buf)\n" + " if cm.message_type == wm_proto and cm.data.l[0] == wm_take:\n" + " ts = int(cm.data.l[1]) & 0xffffffff\n" + " X11.XSetInputFocus(dpy, win, 1, ts)\n" + " X11.XFlush(dpy)\n" + " print(json.dumps({'ev': 'WM_TAKE_FOCUS', 'time': ts}), flush=True)\n" + " elif et == 9:\n" + " fe = XFocusChangeEvent.from_buffer(buf)\n" + " tx, ty, ch = ctypes.c_int(), ctypes.c_int(), ctypes.c_ulong()\n" + " X11.XTranslateCoordinates(dpy, win, root, 0, 0, ctypes.byref(tx), ctypes.byref(ty), ctypes.byref(ch))\n" + " grc = X11.XGrabPointer(dpy, win, 1, (1<<2)|(1<<3)|(1<<6), 1, 1, win, 0, 0)\n" + " print(json.dumps({'ev': 'FocusIn', 'mode': fe.mode, 'pos': [tx.value, ty.value], 'grab': grc}), flush=True)\n" + " elif et == 10:\n" + " fe = XFocusChangeEvent.from_buffer(buf)\n" + " X11.XUngrabPointer(dpy, 0)\n" + " print(json.dumps({'ev': 'FocusOut', 'mode': fe.mode}), flush=True)\n" + " elif et == 22:\n" + " ce = XConfigureEvent.from_buffer(buf)\n" + " print(json.dumps({'ev': 'ConfigureNotify', 'pos': [ce.x, ce.y], 'size': [ce.width, ce.height]}), flush=True)\n" + " elif et in (2, 4, 6):\n" + " names = {2: 'KeyPress', 4: 'ButtonPress', 6: 'MotionNotify'}\n" + " print(json.dumps({'ev': names[et]}), flush=True)\n" + " time.sleep(0.005)\n" + ) + wine_sim = subprocess.Popen( + [sys.executable, "-c", sim_code], + env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + import json + ready_info = json.loads(wine_sim.stdout.readline().strip()) + win_id = ready_info["ready"] + time.sleep(0.4) + + net_wm_state_atom = X11.XInternAtom(dpy, b"_NET_WM_STATE", 0) + atom_maxh = X11.XInternAtom(dpy, b"_NET_WM_STATE_MAXIMIZED_HORZ", 0) + atom_fs = X11.XInternAtom(dpy, b"_NET_WM_STATE_FULLSCREEN", 0) + atom_foc = X11.XInternAtom(dpy, b"_NET_WM_STATE_FOCUSED", 0) + + def get_win_states(): + return get_cardinal_prop(dpy, win_id, "_NET_WM_STATE") + + init_states = wait_until( + lambda: (lambda s: s if atom_fs in s and atom_foc in s else None)(get_win_states()) + ) + assert init_states is not None, f"Missing expected _NET_WM_STATE atoms: {get_win_states()}" + assert atom_maxh in init_states, f"_NET_WM_STATE_MAXIMIZED_HORZ was overwritten: {init_states}" + a_init = XWindowAttributes() + X11.XGetWindowAttributes(dpy, win_id, ctypes.byref(a_init)) + assert (a_init.x, a_init.y, a_init.width, a_init.height) == (0, 0, 1280, 800), ( + f"Multi-atom _NET_WM_STATE_FULLSCREEN not detected fullscreen: {(a_init.x, a_init.y, a_init.width, a_init.height)}" + ) + + # Switch Tag 1 -> Tag 2 via Super_L + 2, spawn and click st on Tag 2 + subprocess.run(["xdotool", "keydown", "Super_L"], env=env, check=True) + time.sleep(0.06) + subprocess.run(["xdotool", "key", "2"], env=env, check=True) + time.sleep(0.08) + subprocess.run(["xdotool", "keyup", "Super_L"], env=env, check=True) + time.sleep(0.25) + + tag2_client = subprocess.Popen( + [os.path.join(BUILD, "st", "st"), "-e", "sh", "-c", "sleep 6"], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + time.sleep(0.4) + subprocess.run(["xdotool", "mousemove", "400", "400", "click", "1"], env=env, check=True) + time.sleep(0.2) + + # Switch Tag 2 -> Tag 1 via Super_L + 1 + subprocess.run(["xdotool", "keydown", "Super_L"], env=env, check=True) + time.sleep(0.06) + subprocess.run(["xdotool", "key", "1"], env=env, check=True) + time.sleep(0.08) + subprocess.run(["xdotool", "keyup", "Super_L"], env=env, check=True) + time.sleep(0.3) + + subprocess.run(["xdotool", "mousemove", "500", "500", "click", "1", "mousemove", "700", "300", "key", "a"], + env=env, check=True) + time.sleep(0.25) + + # Phase 2: switch away to Tag 2 via Super_L + 2, wait, then return via bar Tag 1 click (x=50, y=10) + subprocess.run(["xdotool", "keydown", "Super_L"], env=env, check=True) + time.sleep(0.06) + subprocess.run(["xdotool", "key", "2"], env=env, check=True) + time.sleep(0.08) + subprocess.run(["xdotool", "keyup", "Super_L"], env=env, check=True) + time.sleep(0.25) + subprocess.run(["xdotool", "mousemove", "400", "400", "click", "1"], env=env, check=True) + time.sleep(0.2) + subprocess.run(["xdotool", "mousemove", "50", "10", "click", "1"], env=env, check=True) + time.sleep(0.3) + subprocess.run(["xdotool", "mousemove", "520", "480", "click", "1", "mousemove", "720", "320", "key", "b"], + env=env, check=True) + time.sleep(0.25) + + terminate(wine_sim) + out, _ = wine_sim.communicate(timeout=3) + events = [json.loads(line) for line in out.splitlines() if line.strip().startswith("{")] + + off_indices = [i for i, e in enumerate(events) if e["ev"] == "ConfigureNotify" and e["pos"][0] < 0] + assert len(off_indices) >= 2, f"Expected two workspace switches away from Tag 1: {events}" + + pre_switch = events[:off_indices[0]] + init_tf = [e for e in pre_switch if e["ev"] == "WM_TAKE_FOCUS"] + assert init_tf and init_tf[0]["time"] > 0, f"Initial WM_TAKE_FOCUS must have non-zero time: {pre_switch}" + + # Check Phase 1 (Super_L + 1 return) + seg1 = events[off_indices[0]:off_indices[1]] + tf1 = [e for e in seg1 if e["ev"] == "WM_TAKE_FOCUS"] + assert len(tf1) == 1, f"Expected exactly 1 WM_TAKE_FOCUS on Super_L+1 return, got {len(tf1)}: {seg1}" + assert tf1[0]["time"] > init_tf[-1]["time"], f"WM_TAKE_FOCUS timestamp did not advance: {tf1[0]} vs {init_tf[-1]}" + fi1 = [e for e in seg1 if e["ev"] == "FocusIn"] + assert fi1, f"Missing FocusIn on Super_L+1 return: {seg1}" + assert fi1[0]["mode"] == 0 and fi1[0]["pos"] == [0, 0] and fi1[0]["grab"] == 0, f"Bad FocusIn/grab on Super_L+1 return: {fi1[0]}" + seg1_names = [e["ev"] for e in seg1] + for req in ("MotionNotify", "ButtonPress", "KeyPress"): + assert req in seg1_names, f"Missing {req} after Super_L+1 return: {seg1}" + + # Check Phase 2 (bar Tag 1 click return) + seg2 = events[off_indices[1]:] + tf2 = [e for e in seg2 if e["ev"] == "WM_TAKE_FOCUS"] + assert len(tf2) == 1, f"Expected exactly 1 WM_TAKE_FOCUS on bar click return, got {len(tf2)}: {seg2}" + assert tf2[0]["time"] > tf1[0]["time"], f"WM_TAKE_FOCUS timestamp did not advance on bar click: {tf2[0]} vs {tf1[0]}" + fi2 = [e for e in seg2 if e["ev"] == "FocusIn"] + assert fi2, f"Missing FocusIn on bar click return: {seg2}" + assert fi2[0]["mode"] == 0 and fi2[0]["pos"] == [0, 0] and fi2[0]["grab"] == 0, f"Bad FocusIn/grab on bar click return: {fi2[0]}" + seg2_names = [e["ev"] for e in seg2] + for req in ("MotionNotify", "ButtonPress", "KeyPress"): + assert req in seg2_names, f"Missing {req} after bar click return: {seg2}" + finally: + terminate(tag2_client) + terminate(wine_sim) + terminate(dwm) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + +def test_systray_xembed_dock_race(): + disp = pick_display() + with tempfile.TemporaryDirectory() as home: + env = dict(os.environ) + env["DISPLAY"] = disp + env["HOME"] = home + env["XDG_CONFIG_HOME"] = os.path.join(home, ".config") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + env["PATH"] = ( + os.path.join(BUILD, "dwm") + ":" + + os.path.join(ROOT, "scripts") + ":" + + env.get("PATH", "") + ) + subprocess.run([os.path.join(ROOT, "scripts", "anode-apply-scale"), "1.00", "--touch=0"], env=env, check=True) + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-noreset", "-screen", "0", "1280x800x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + dpy = None + cdpy = None + dwm = None + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode())) + assert dpy, f"Failed to open Xvfb {disp}" + cdpy = wait_until(lambda: X11.XOpenDisplay(disp.encode())) + assert cdpy, f"Failed to open client display on Xvfb {disp}" + root = X11.XDefaultRootWindow(dpy) + + dwm = subprocess.Popen([os.path.join(BUILD, "dwm", "dwm")], env=env) + tray_atom = X11.XInternAtom(dpy, b"_NET_SYSTEM_TRAY_S0", 0) + tray_win = wait_until(lambda: X11.XGetSelectionOwner(dpy, tray_atom)) + assert tray_win, "DWM failed to acquire _NET_SYSTEM_TRAY_S0" + + xembed_info = X11.XInternAtom(cdpy, b"_XEMBED_INFO", 0) + op_atom = X11.XInternAtom(cdpy, b"_NET_SYSTEM_TRAY_OPCODE", 0) + + def set_xembed(ic, mapped): + arr = (ctypes.c_ulong * 2)(1, 1 if mapped else 0) + X11.XChangeProperty(cdpy, ic, xembed_info, xembed_info, 32, 0, arr, 2) + + def send_dock(ic): + ev = XClientMessageEvent() + ev.type = 33 + ev.display = cdpy + ev.window = tray_win + ev.message_type = op_atom + ev.format = 32 + ev.data.l[0] = 0 + ev.data.l[1] = 0 + ev.data.l[2] = ic + X11.XSendEvent(cdpy, tray_win, 0, 0, ctypes.byref(ev)) + + def assert_icon_viewable_resized(ic, desc): + def check(): + if ic not in query_children(dpy, tray_win): + return None + a = XWindowAttributes() + if not X11.XGetWindowAttributes(dpy, ic, ctypes.byref(a)): + return None + if a.map_state == 2 and 8 <= a.width <= 48 and 8 <= a.height <= 48: + return (a.width, a.height) + return None + res = wait_until(check, timeout=3.0) + if not res: + a = XWindowAttributes() + X11.XGetWindowAttributes(dpy, ic, ctypes.byref(a)) + raise AssertionError( + f"{desc}: icon {hex(ic)} failed systray check " + f"(in_tray={ic in query_children(dpy, tray_win)}, map_state={a.map_state}, size={a.width}x{a.height})" + ) + + # Subtest A: GTK2/HexChat burst race (_XEMBED_INFO=(1,0) -> REQUEST_DOCK -> _XEMBED_INFO=(1,1)) + for delay in (0.0, 0.0005, 0.002, 0.01): + ic = X11.XCreateSimpleWindow(cdpy, root, 0, 0, 200, 200, 0, 0, 0xffffff) + set_xembed(ic, False) + send_dock(ic) + X11.XFlush(cdpy) + if delay > 0.0: + time.sleep(delay) + set_xembed(ic, True) + X11.XFlush(cdpy) + assert_icon_viewable_resized(ic, f"Subtest A (delay={delay})") + + # Subtest B: Already-mapped icon docking + ic_mapped = X11.XCreateSimpleWindow(cdpy, root, 0, 0, 200, 200, 0, 0, 0xffffff) + swa = XSetWindowAttributes() + swa.override_redirect = 1 + X11.XChangeWindowAttributes(cdpy, ic_mapped, 1 << 9, ctypes.byref(swa)) + set_xembed(ic_mapped, True) + X11.XMapWindow(cdpy, ic_mapped) + X11.XSync(cdpy, 0) + send_dock(ic_mapped) + X11.XFlush(cdpy) + assert_icon_viewable_resized(ic_mapped, "Subtest B (already-mapped)") + + # Subtest C: Toggle XEMBED_MAPPED 1 -> 0 -> 1 + ic_toggle = X11.XCreateSimpleWindow(cdpy, root, 0, 0, 200, 200, 0, 0, 0xffffff) + set_xembed(ic_toggle, True) + send_dock(ic_toggle) + X11.XFlush(cdpy) + assert_icon_viewable_resized(ic_toggle, "Subtest C (initial map)") + + set_xembed(ic_toggle, False) + X11.XFlush(cdpy) + def is_unmapped(): + a = XWindowAttributes() + return X11.XGetWindowAttributes(dpy, ic_toggle, ctypes.byref(a)) and a.map_state == 0 + assert wait_until(is_unmapped, timeout=3.0), "Subtest C: icon did not unmap on XEMBED_MAPPED=0" + + set_xembed(ic_toggle, True) + X11.XFlush(cdpy) + assert_icon_viewable_resized(ic_toggle, "Subtest C (remap)") + finally: + terminate(dwm) + if cdpy: + X11.XCloseDisplay(cdpy) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + def main(): if not shutil.which("Xvfb"): print("test_x11_xvfb: Xvfb not installed (skipping)") @@ -788,6 +1368,12 @@ def main(): print("test_x11_xvfb: lockscreen overlaps systray OK") test_gtk_xsettings_no_double_scale() print("test_x11_xvfb: GTK/XSETTINGS non-double-scaling OK") + test_fullscreen_workspace_switch_focus() + print("test_x11_xvfb: fullscreen workspace switch focus OK") + test_wine_take_focus_workspace_switch() + print("test_x11_xvfb: Wine WM_TAKE_FOCUS workspace switch OK") + test_systray_xembed_dock_race() + print("test_x11_xvfb: systray XEmbed dock/map race OK") return 0