From 56f643120f082c9fd609f25e3ad9db6eb435fb89 Mon Sep 17 00:00:00 2001 From: elbachir-one Date: Mon, 24 Jun 2024 22:15:50 +0100 Subject: [PATCH] Inspired by a Reddit post from u/PawarShubham3007 shubham-cpp on github, this patch aiming to make dwm focus on windows of the same program. --- config.def.h | 4 +++- dwm.c | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/config.def.h b/config.def.h index 9efa774..fd0dda6 100644 --- a/config.def.h +++ b/config.def.h @@ -85,6 +85,8 @@ static const Key keys[] = { { MODKEY, XK_period, focusmon, {.i = +1 } }, { MODKEY|ShiftMask, XK_comma, tagmon, {.i = -1 } }, { MODKEY|ShiftMask, XK_period, tagmon, {.i = +1 } }, + { MODKEY, XK_n, focussame, {.i = +1 } }, + { MODKEY|ShiftMask, XK_n, focussame, {.i = -1 } }, TAGKEYS( XK_1, 0) TAGKEYS( XK_2, 1) TAGKEYS( XK_3, 2) diff --git a/dwm.c b/dwm.c index 67c6b2b..c657315 100644 --- a/dwm.c +++ b/dwm.c @@ -233,6 +233,8 @@ 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); +static void focussame(const Arg *arg); +static Window lastfocusedwin = None; /* variables */ static const char broken[] = "broken"; @@ -786,6 +788,59 @@ expose(XEvent *e) drawbar(m); } +void +focussame(const Arg *arg) { + Client *c; + XClassHint ch = { NULL, NULL }; + char *class_name = NULL; + int direction = arg->i; + + if (!selmon->sel) + return; + + if (!XGetClassHint(dpy, selmon->sel->win, &ch)) + return; + class_name = ch.res_class; + + Client *clients[32]; + int num_clients = 0; + for (c = selmon->clients; c && num_clients < 32; c = c->next) { + if (c->tags & selmon->tagset[selmon->seltags] && XGetClassHint(dpy, c->win, &ch)) { + if (strcmp(class_name, ch.res_class) == 0) + clients[num_clients++] = c; + XFree(ch.res_class); + XFree(ch.res_name); + } + } + + Client *target_client = NULL; + if (direction == +1) { + for (int i = 0; i < num_clients; ++i) { + if (clients[i]->win == lastfocusedwin) { + target_client = clients[(i + 1) % num_clients]; + break; + } + } + if (!target_client) + target_client = clients[0]; + } else if (direction == -1) { + for (int i = 0; i < num_clients; ++i) { + if (clients[i]->win == lastfocusedwin) { + target_client = clients[(i - 1 + num_clients) % num_clients]; + break; + } + } + if (!target_client) + target_client = clients[num_clients - 1]; + } + + if (target_client) { + focus(target_client); + restack(selmon); + lastfocusedwin = target_client->win; + } +} + void focus(Client *c) { -- 2.45.2