speedwm-personal/speedwm.c
2022-09-08 18:07:30 +02:00

5552 lines
128 KiB
C

/* See LICENSE file for copyright and license details.
*/
#include <assert.h>
#include <errno.h>
#include <locale.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#if USEWINICON
#include <limits.h>
#include <stdint.h>
#endif
#include <sys/types.h>
#include <sys/wait.h>
#include "toggle.h"
#if USEIPC
#include <sys/epoll.h>
#endif
#include <X11/cursorfont.h>
#include <X11/keysym.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xproto.h>
#include <X11/Xutil.h>
#include <X11/Xresource.h>
#include <X11/extensions/shape.h>
#ifdef XINERAMA
#include <X11/extensions/Xinerama.h>
#endif /* XINERAMA */
#include <X11/Xft/Xft.h>
#if USEIMLIB2
#include <Imlib2.h>
#endif
#include <X11/Xlib-xcb.h>
#include <xcb/res.h>
#ifdef __OpenBSD__
#include <sys/sysctl.h>
#include <kvm.h>
#endif /* __OpenBSD */
#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)->mw) - MAX((x),(m)->mx)) \
* MAX(0, MIN((y)+(h),(m)->wy+(m)->mh) - MAX((y),(m)->my)))
#define INTERSECTC(x,y,w,h,z) (MAX(0, MIN((x)+(w),(z)->x+(z)->w) - MAX((x),(z)->x)) \
* MAX(0, MIN((y)+(h),(z)->y+(z)->h) - MAX((y),(z)->y)))
#define HIDDEN(C) ((getstate(C->win) == IconicState))
#define ISVISIBLEONTAG(C, T) ((C->tags & T))
#define ISVISIBLE(C) ((C->tags & C->mon->tagset[C->mon->seltags]) || C->issticky)
#define LENGTH(X) (sizeof X / sizeof X[0])
#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 TAGSLENGTH (LENGTH(tags))
#define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
#define RIGHTOF(a,b) (a.y_org > b.y_org) || \
((a.y_org == b.y_org) && (a.x_org > b.x_org))
#define OPAQUE 0xffU
#define TRANSPARENT 0
#define MWM_HINTS_FLAGS_FIELD 0
#define MWM_HINTS_DECORATIONS_FIELD 2
#define MWM_HINTS_DECORATIONS (1 << 1)
#define MWM_DECOR_ALL (1 << 0)
#define MWM_DECOR_BORDER (1 << 1)
#define MWM_DECOR_TITLE (1 << 3)
/* enums */
enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
/* color schemes */
enum { SchemeNormBorder,
SchemeSelBorder,
SchemeTags,
SchemeBar,
SchemeHid,
SchemeLayout,
SchemeNormTitle,
SchemeSelTitle,
SchemeStatus,
};
enum { NetSupported, NetWMName,
#if USEWINICON
NetWMIcon,
#endif
NetWMState, NetWMCheck,
NetWMFullscreen, NetActiveWindow, NetWMWindowType, NetWMWindowTypeDesktop,
NetWMWindowTypeDialog, NetClientList, NetDesktopNames, NetDesktopViewport, NetNumberOfDesktops, NetCurrentDesktop,
#if USEFADE
NetWMWindowsOpacity,
#endif
NetClientListStacking, NetClientInfo, NetLast }; /* EWMH atoms */
enum { WMClass, WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; /* default atoms */
enum { DWMTags, DWMLast };
enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
#if USEIPC
typedef struct TagState TagState;
struct TagState {
int selected;
int occupied;
int urgent;
};
typedef struct ClientState ClientState;
struct ClientState {
int isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen;
};
#endif
typedef union {
long i;
unsigned long 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;
float cfact;
int x, y, w, h;
int sfx, sfy, sfw, sfh; /* stored float geometry, used on mode revert */
int oldx, oldy, oldw, oldh;
int basew, baseh, incw, inch, maxw, maxh, minw, minh;
int bw, oldbw;
unsigned int tags;
int isfixed, ispermanent, isfloating, isurgent, neverfocus, oldstate, isfullscreen, ignoretransient, issticky, isterminal, noswallow, needresize;
pid_t pid;
char scratchkey;
#if USEWINICON
unsigned int icw, ich; Picture icon;
#endif
int issteam;
int beingmoved;
Client *next;
Client *snext;
Client *swallowing;
Monitor *mon;
Window win;
#if USEIPC
ClientState prevstate;
#endif
};
typedef struct {
unsigned int mod;
KeySym chain;
KeySym keysym;
void (*func)(const Arg *);
const Arg arg;
} Key;
typedef struct {
unsigned int signum;
void (*func)(const Arg *);
const Arg arg;
} Signal;
typedef struct {
const char *symbol;
void (*arrange)(Monitor *);
} Layout;
typedef struct Pertag Pertag;
struct Monitor {
char ltsymbol[16];
#if USEIPC
char lastltsymbol[16];
#endif
float mfact;
float cfact;
int nmaster;
int num;
int by, bh; /* bar geometry */
int tx, tw; /* bar tray geometry */
int btw;
int bt;
int mx, my, mw, mh; /* screen size */
int wx, wy, ww, wh; /* window area */
int gappih; /* horizontal gap between windows */
int gappiv; /* vertical gap between windows */
int gappoh; /* horizontal outer gaps */
int gappov; /* vertical outer gaps */
unsigned int seltags;
unsigned int sellt;
unsigned int tagset[2];
#if USEIPC
TagState tagstate;
#endif
#if USETAGPREVIEW
int previewshow;
#endif
int showbar;
int barposition;
int hidsel;
int mouseactivated;
Client *clients;
Client *sel;
#if USEIPC
Client *lastsel;
#endif
Client *stack;
Monitor *next;
Window barwin;
Window traywin;
#if USETAGPREVIEW
Window tagwin;
Pixmap *tagmap;
#endif
const Layout *lt[2];
#if USEIPC
const Layout *lastlt;
#endif
Pertag *pertag;
};
/* Order of the rules */
typedef struct {
const char *class;
const char *instance;
const char *title;
unsigned int tags;
int isfloating;
int ispermanent;
int isterminal;
int noswallow;
int monitor;
int unmanaged;
int ignoretransient;
const char scratchkey;
} Rule;
typedef struct {
const char *cmd;
int id;
} StatusCmd;
/* Xresources preferences */
enum resource_type {
STRING = 0,
INTEGER = 1,
FLOAT = 2
};
typedef struct {
char *name;
enum resource_type type;
void *dst;
} ResourcePref;
/* function declarations */
static void applyrules(Client *c);
#if LAYOUT_CM
static void centeredmaster(Monitor *m);
#endif
#if LAYOUT_CFM
static void centeredfloatingmaster(Monitor *m);
#endif
#if LAYOUT_TW
static void tilewide(Monitor *m);
#endif
static void getgaps(Monitor *m, int *oh, int *ov, int *ih, int *iv, unsigned int *nc);
static void getfacts(Monitor *m, int msize, int ssize, float *mf, float *sf, int *mr, int *sr);
#if LAYOUT_STAIRS
static void stairs(Monitor *m);
#endif
static int applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact);
static void spawnscratch(const Arg *arg);
static void inplacerotate(const Arg *arg);
static void togglescratch(const Arg *arg);
static void settagsatom(Window w, unsigned int tags);
static void togglesticky(const Arg *arg);
static void previewtag(const Arg *arg);
static void setcurrentdesktop(void);
static void setdesktopnames(void);
static void setnumdesktops(void);
static void setviewport(void);
static void arrange(Monitor *m);
static void arrangemon(Monitor *m);
static void attach(Client *c);
static void attachabove(Client *c);
static void attachaside(Client *c);
static void attachbelow(Client *c);
static void attachbottom(Client *c);
static void attachtop(Client *c);
static void attachstack(Client *c);
#if USEMOUSE
static void buttonpress(XEvent *e);
#endif
static void checkotherwm(void);
static void cleanup(void);
static void cleanupmon(Monitor *mon);
static void clientmessage(XEvent *e);
#if LAYOUT_COL
static void col(Monitor *);
#endif
static void configure(Client *c);
static void configurenotify(XEvent *e);
static void livereloadxrdb(const Arg *arg);
static void configurerequest(XEvent *e);
static void copyvalidchars(char *text, char *rawtext);
static void autostart_exec(void);
static void moveresize(const Arg *arg);
static void moveresizeedge(const Arg *arg);
static Monitor *createmon(void);
#if LAYOUT_DECK
static void deck(Monitor *m);
#endif
static void cyclelayout(const Arg *arg);
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 drawroundedcorners(Client *c);
static int drawstatusbar(Monitor *m, int bh, char* text);
#if USEMOUSE
static void enternotify(XEvent *e);
#endif
static void expose(XEvent *e);
static void focus(Client *c);
static void focusin(XEvent *e);
static void focusmon(const Arg *arg);
static void focusstack(int inc, int vis);
static void focusstackvis(const Arg *arg);
static void focusstackhid(const Arg *arg);
static Atom getatomprop(Client *c, Atom prop);
#if USEWINICON
static Picture geticonprop(Window w, unsigned int *icw, unsigned int *ich);
#endif
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 hide(const Arg *arg);
static void hidewin(Client *c);
static void incnmaster(const Arg *arg);
#if USEIPC
static int handlexevent(struct epoll_event *ev);
#endif
static void keypress(XEvent *e);
static int fake_signal(void);
static void killclient(const Arg *arg);
static void killunsel(const Arg *arg);
#if USEMOUSE
static void layoutmenu(const Arg *arg);
#endif
static void manage(Window w, XWindowAttributes *wa);
static void managealtbar(Window win, XWindowAttributes *wa);
static void managetray(Window win, XWindowAttributes *wa);
static void mappingnotify(XEvent *e);
static void maprequest(XEvent *e);
#if LAYOUT_MONOCLE
static void monocle(Monitor *m);
#endif
static void motionnotify(XEvent *e);
#if USEMOUSE
static void movemouse(const Arg *arg);
static void moveorplace(const Arg *arg);
#endif
static Client *nexttagged(Client *c);
static Client *nexttiled(Client *c);
#if USEMOUSE
static void placemouse(const Arg *arg);
#endif
#if USEFADE
static void opacity(Client *c, double opacity);
#endif
static void pop(Client *);
static void propertynotify(XEvent *e);
static void quit(const Arg *arg);
static Client *recttoclient(int x, int y, int w, int h);
static Monitor *recttomon(int x, int y, int w, int h);
static void resetlayout(const Arg *arg);
static void reorganizetags(const Arg *arg);
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);
#if USEMOUSE
static void resizemouse(const Arg *arg);
#endif
static void restack(Monitor *m);
static void run(void);
static void scantray(void);
static void scan(void);
static void scratchpad_hide ();
static _Bool scratchpad_last_showed_is_killed (void);
static void scratchpad_remove ();
static void scratchpad_show ();
static void scratchpad_show_client (Client * c);
static void scratchpad_show_first (void);
static int sendevent(Client *c, Atom proto);
static void sendmon(Client *c, Monitor *m);
static void setclientstate(Client *c, long state);
static void setclienttagprop(Client *c);
static void setfocus(Client *c);
static void setfullscreen(Client *c, int fullscreen);
static void setgaps(int oh, int ov, int ih, int iv);
static void incrgaps(const Arg *arg);
static void incrigaps(const Arg *arg);
static void incrogaps(const Arg *arg);
static void togglegaps(const Arg *arg);
static void defaultgaps(const Arg *arg);
static void setlayout(const Arg *arg);
#if USEMOUSE
static void dragcfact(const Arg *arg);
#endif
#if USEIPC
static void setlayoutsafe(const Arg *arg);
#endif
static void setcfact(const Arg *arg);
static void setmfact(const Arg *arg);
static void setup(void);
#if USEIPC
static void setupepoll(void);
#endif
static void seturgent(Client *c, int urg);
static void show(const Arg *arg);
static void showwin(Client *c);
static void showhide(Client *c);
#if USETAGPREVIEW
static void showtagpreview(unsigned int i);
#endif
static void sigchld(int unused);
#ifdef XINERAMA
static void sortscreens(XineramaScreenInfo *screens, int n);
#endif
static void sighup(int unused);
static void sigterm(int unused);
static void spawn(const Arg *arg);
static void spawnbar();
static void unmanagealtbar(Window w);
static void unmanagetray(Window w);
#if USETAGPREVIEW
static void getpreview(void);
#endif
static void tagmon(const Arg *arg);
#if LAYOUT_TILE
static void tile(Monitor *);
#endif
#if LAYOUT_TILE54
static void tile54(Monitor *);
#endif
static void togglebar(const Arg *arg);
static void togglefloating(const Arg *arg);
static void toggleopacity(const Arg *arg);
static void togglefullscr(const Arg *arg);
#if USEWINICON
static void freeicon(Client *c);
#endif
#if USEMOUSE
static void togglewin(const Arg *arg);
#endif
static void unfocus(Client *c, int setfocus);
static void unmanage(Client *c, int destroyed);
static void unmapnotify(XEvent *e);
static void updatecurrentdesktop(void);
static void updatebarpos(Monitor *m);
static void updatebars(void);
static void updateclientlist(void);
static int updategeom(void);
static void updatemotifhints(Client *c);
static void updatenumlockmask(void);
#if USEMOUSE
static void resizemouse(const Arg *arg);
#endif
static void updatesizehints(Client *c);
static void updatestatus(void);
static void updaterules(Client *c);
static void updatetitle(Client *c);
#if USEWINICON
#if USETAGPREVIEW
static void updatepreview(void);
#endif
static void updateicon(Client *c);
#endif
static void updatewindowtype(Client *c);
static void updatewmhints(Client *c);
static void view(const Arg *arg);
static void viewtoleft(const Arg *arg);
static void viewtoright(const Arg *arg);
static void warp(const Client *c);
static Client *wintoclient(Window w);
static Monitor *wintomon(Window w);
static int wmclasscontains(Window win, const char *class, const char *name);
static int xerror(Display *dpy, XErrorEvent *ee);
static int xerrordummy(Display *dpy, XErrorEvent *ee);
static int xerrorstart(Display *dpy, XErrorEvent *ee);
static void xinitvisual();
static void zoom(const Arg *arg);
static void load_xresources(void);
static void resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst);
static pid_t getparentprocess(pid_t p);
static int isdescprocess(pid_t p, pid_t c);
static Client *swallowingclient(Window w);
static Client *termforwin(const Client *c);
static pid_t winpid(Window w);
/* variables */
static const char broken[] = "speedwm";
#if USEMOUSE
static const char *layoutmenu_cmd = "speedwm-utils -layout";
#endif
static char stext[1024];
static char rawstext[1024];
static int statusw;
#if USEMOUSE
static int statuscmdn;
static char lastbutton[] = "-";
#endif
static int screen;
static int tw, sh; /* X display screen geometry width, height */
static int bh, blw = 0; /* bar geometry */
static int unmanaged = 0; /* whether the window manager should manage the new window or not */
static int lrpad; /* sum of left and right padding for text */
static int vp; /* vertical padding for bar */
static int sp; /* side padding for bar */
static int (*xerrorxlib)(Display *, XErrorEvent *);
static unsigned int numlockmask = 0;
static void (*handler[LASTEvent]) (XEvent *) = {
#if USEMOUSE
[ButtonPress] = buttonpress,
#endif
[ClientMessage] = clientmessage,
[ConfigureRequest] = configurerequest,
[ConfigureNotify] = configurenotify,
[DestroyNotify] = destroynotify,
#if USEMOUSE
[EnterNotify] = enternotify,
#endif
[Expose] = expose,
[FocusIn] = focusin,
[KeyPress] = keypress,
[MappingNotify] = mappingnotify,
[MapRequest] = maprequest,
[MotionNotify] = motionnotify,
[PropertyNotify] = propertynotify,
[UnmapNotify] = unmapnotify
};
static Atom wmatom[WMLast], netatom[NetLast], dwmatom[DWMLast], motifatom;
#if USEIPC
static int epoll_fd;
static int dpy_fd;
#endif
static int running = 1;
static int restart = 0;
static Cur *cursor[CurLast];
static Clr **scheme;
static Clr **tagscheme;
static Display *dpy;
static Drw *drw;
static Monitor *mons, *selmon;
#if USEIPC
static Monitor *lastselmon; /* IPC */
#endif
static Window root, wmcheckwin;
static KeySym keychain = -1;
/* scratchpad */
#define SCRATCHPAD_MASK (1u << sizeof tags / sizeof * tags)
static Client * scratchpad_last_showed = NULL;
static int useargb = 0;
static Visual *visual;
static int depth;
static Colormap cmap;
static xcb_connection_t *xcon;
#define FORCE_VSPLIT forcevsplit
#if USEIPC
#include "toggle/ipc.c"
#endif
/* configuration, allows nested code to access above variables */
#include <X11/XF86keysym.h> /* Enable multimedia button support */
#include "options.h" /* Include options */
#include "layouts.c" /* Enable patched layouts */
#include "autostart.h" /* Add autostart support */
#include "colors.h" /* Include colors */
#include "rules.h" /* Include rules */
#include "layouts.h" /* Include layout list */
#include "xresources.h" /* Include .Xresources/Pywal support */
#include "keybinds.h" /* Include keybinds */
#if USEIPC
#include "ipccmd.h" /* Include IPC */
#include "toggle/ipc-cli.c"
#include "toggle/ipc-yajl.c"
#endif
#if USEMOUSE
static const char *statuscmd[] = { shell, "-c", NULL, NULL };
#include "mouse.h" /* Include mouse support */
#endif
char *get_speedwm_path(){
struct stat s;
int r, length, rate = 42;
char *path = NULL;
if(lstat("/proc/self/exe", &s) == -1){
perror("lstat:");
return NULL;
}
length = s.st_size + 1 - rate;
do{
length+=rate;
free(path);
path = malloc(sizeof(char) * length);
if(path == NULL){
perror("malloc:");
return NULL;
}
r = readlink("/proc/self/exe", path, length);
if(r == -1){
perror("readlink:");
return NULL;
}
}while(r >= length);
path[r] = '\0';
return path;
}
void self_restart(const Arg *arg) {
char *const argv[] = {get_speedwm_path(), NULL};
if(argv[0] == NULL){
return;
}
execv(argv[0], argv);
}
#include "fsignal.h" /* Include fsignal support */
unsigned int tagw[LENGTH(tags)];
struct Pertag {
unsigned int curtag, prevtag; /* current and previous tag */
int nmasters[LENGTH(tags) + 1]; /* number of windows in master area */
float mfacts[LENGTH(tags) + 1]; /* mfacts per tag */
unsigned int sellts[LENGTH(tags) + 1]; /* selected layouts */
const Layout *ltidxs[LENGTH(tags) + 1][2]; /* matrix of tags and layouts indexes */
int showbars[LENGTH(tags) + 1]; /* display bar for the current tag */
};
/* compile-time check if all tags fit into an unsigned int bit array. */
struct NumTags { char limitexceeded[LENGTH(tags) > 31 ? -1 : 1]; };
/* speedwm will keep pid's of processes from autostart array and kill them at quit */
static pid_t *autostart_pids;
static size_t autostart_len;
/* execute command from autostart array */
static void
autostart_exec() {
const char *const *p;
size_t i = 0;
/* count entries */
for (p = autostart; *p; autostart_len++, p++)
while (*++p);
autostart_pids = malloc(autostart_len * sizeof(pid_t));
for (p = autostart; *p; i++, p++) {
if ((autostart_pids[i] = fork()) == 0) {
setsid();
execvp(*p, (char *const *)p);
fprintf(stderr, "speedwm: execvp %s\n", *p);
perror(" failed");
_exit(EXIT_FAILURE);
}
/* skip arguments */
while (*++p);
}
}
/* 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;
c->scratchkey = 0;
XGetClassHint(dpy, c->win, &ch);
class = ch.res_class ? ch.res_class : broken;
instance = ch.res_name ? ch.res_name : broken;
if (strstr(class, "Steam") || strstr(class, "steam_app_"))
c->issteam = 1;
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->isterminal = r->isterminal;
c->noswallow = r->noswallow;
c->isfloating = r->isfloating;
c->ignoretransient = r->ignoretransient;
c->ispermanent = r->ispermanent;
c->tags |= r->tags;
unmanaged = r->unmanaged;
c->scratchkey = r->scratchkey;
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);
if(c->tags & TAGMASK) c->tags = c->tags & TAGMASK;
else if(c->mon->tagset[c->mon->seltags]) c->tags = c->mon->tagset[c->mon->seltags];
else c->tags = 1;
if (c->tags != SCRATCHPAD_MASK)
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 > tw)
*x = tw - 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) {
/* 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)
{
memcpy(m->ltsymbol, m->lt[m->sellt]->symbol, sizeof(m->ltsymbol));
if (m->lt[m->sellt]->arrange) {
m->lt[m->sellt]->arrange(m);
}
if (roundedcorners) {
Client *c;
for (c = nexttiled(m->clients); c; c = nexttiled(c->next))
drawroundedcorners(c);
}
}
void
attach(Client *c)
{
c->next = c->mon->clients;
c->mon->clients = c;
}
void
attachabove(Client *c)
{
if (c->mon->sel == NULL || c->mon->sel == c->mon->clients || c->mon->sel->isfloating) {
attach(c);
return;
}
Client *at;
for (at = c->mon->clients; at->next != c->mon->sel; at = at->next);
c->next = at->next;
at->next = c;
}
void
attachaside(Client *c) {
Client *at = nexttagged(c);
if(!at) {
attach(c);
return;
}
c->next = at->next;
at->next = c;
}
void
attachbelow(Client *c)
{
if(c->mon->sel == NULL || c->mon->sel == c || c->mon->sel->isfloating) {
attach(c);
return;
}
c->next = c->mon->sel->next;
c->mon->sel->next = c;
}
void
attachbottom(Client *c)
{
Client *below = c->mon->clients;
for (; below && below->next; below = below->next);
c->next = NULL;
if (below)
below->next = c;
else
c->mon->clients = c;
}
void
attachtop(Client *c)
{
int n;
Monitor *m = selmon;
Client *below;
for (n = 1, below = c->mon->clients;
below && below->next && (below->isfloating || !ISVISIBLEONTAG(below, c->tags) || n != m->nmaster);
n = below->isfloating || !ISVISIBLEONTAG(below, c->tags) ? n + 0 : n + 1, below = below->next);
c->next = NULL;
if (below) {
c->next = below->next;
below->next = c;
}
else
c->mon->clients = c;
}
void
attachstack(Client *c)
{
c->snext = c->mon->stack;
c->mon->stack = c;
}
void
swallow(Client *p, Client *c)
{
if (c->noswallow || c->isterminal)
return;
if (c->noswallow && !swallowfloating && c->isfloating)
return;
if (!swallowclients)
return;
detach(c);
detachstack(c);
setclientstate(c, WithdrawnState);
XUnmapWindow(dpy, p->win);
p->swallowing = c;
c->mon = p->mon;
Window w = p->win;
p->win = c->win;
c->win = w;
updatetitle(p);
XMoveResizeWindow(dpy, p->win, p->x, p->y, p->w, p->h);
arrange(p->mon);
configure(p);
updateclientlist();
}
void
unswallow(Client *c)
{
c->win = c->swallowing->win;
free(c->swallowing);
c->swallowing = NULL;
/* unfullscreen the client */
setfullscreen(c, 0);
updatetitle(c);
arrange(c->mon);
XMapWindow(dpy, c->win);
XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
setclientstate(c, NormalState);
focus(NULL);
arrange(c->mon);
}
#if USEMOUSE
void
buttonpress(XEvent *e)
{
unsigned int i, x, click, occ;
Arg arg = {0};
Client *c;
Monitor *m;
XButtonPressedEvent *ev = &e->xbutton;
*lastbutton = '0' + ev->button;
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 = occ = 0;
/* Bitmask of occupied tags */
for (c = m->clients; c; c = c->next)
occ |= c->tags;
if (leftlayout) {
x += blw;
} if (ev->x < x && leftlayout) {
click = ClkLtSymbol; // left layout
} else {
do {
if (!(occ & 1 << i || m->tagset[m->seltags] & 1 << i))
continue;
if (!hidetags)
x += TEXTW(occ & 1 << i ? usedtags[i] : tags[i]);
} while (ev->x >= x && ++i < LENGTH(tags));
if (i < LENGTH(tags) && !hidetags) {
selmon->mouseactivated = 1;
click = ClkTagBar;
arg.ui = 1 << i;
} else if (ev->x < x + blw && !leftlayout) // right layout
click = ClkLtSymbol; // right layout
else if (ev->x > selmon->ww - statusw + lrpad - 2 && !hidestatus) {
x = selmon->ww - statusw + lrpad - 2;
click = ClkStatusText;
char *text = rawstext;
int i = -1;
char ch;
statuscmdn = 0;
while (text[++i]) {
if ((unsigned char)text[i] < ' ') {
ch = text[i];
text[i] = '\0';
x += TEXTW(text) - lrpad - 2;
text[i] = ch;
text += i+1;
i = -1;
if (x >= ev->x)
break;
if (ch <= LENGTH(statuscmds))
statuscmdn = ch;
}
}
} else {
if (!leftlayout) {
x += blw; // Left layout does not need this
}
// Don't click if title is hidden
// This is not required, but you won't be able to see what you're clicking so we might as well disable it
if (!hidetitle) {
c = m->clients;
if (c) {
do {
if (!c || !ISVISIBLE(c))
continue;
else
x += (1.0 / (double)m->bt) * m->btw;
} while (c && ev->x > x && (c = c->next));
click = ClkWinTitle;
arg.v = c;
}
}
}
}
} 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 || click == ClkWinTitle) && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
}
#endif
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) + 1; i++)
free(scheme[i]);
free(scheme);
if (fullscreenhidebar)
XDestroyWindow(dpy, wmcheckwin);
drw_free(drw);
XSync(dpy, False);
XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
#if USEIPC
ipc_cleanup();
if (close(epoll_fd) < 0) {
fprintf(stderr, "Failed to close epoll file descriptor\n");
}
#endif
}
void
cleanupmon(Monitor *mon)
{
Monitor *m;
#if USETAGPREVIEW
size_t i;
#endif
if (mon == mons)
mons = mons->next;
else {
for (m = mons; m && m->next != mon; m = m->next);
m->next = mon->next;
}
#if USETAGPREVIEW
for (i = 0; i < LENGTH(tags); i++) {
if (mon->tagmap[i])
XFreePixmap(dpy, mon->tagmap[i]);
free(mon->tagmap);
if (!altbar) {
XUnmapWindow(dpy, mon->tagwin);
XDestroyWindow(dpy, mon->tagwin);
}
#endif
free(mon);
#if USETAGPREVIEW
}
#endif
}
void
clientmessage(XEvent *e)
{
XClientMessageEvent *cme = &e->xclient;
Client *c = wintoclient(cme->window);
unsigned int i;
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]) {
for (i = 0; i < LENGTH(tags) && !((1 << i) & c->tags); i++);
if (i < LENGTH(tags)) {
const Arg a = {.ui = 1 << i};
selmon = c->mon;
view(&a);
focus(c);
restack(selmon);
}
}
}
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) {
dirty = (tw != ev->width || sh != ev->height);
tw = ev->width;
sh = ev->height;
if (updategeom() || dirty) {
drw_resize(drw, tw, 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 + sp, m->by + vp, m->ww - 2 * sp, m->bh);
}
focus(NULL);
arrange(NULL);
}
}
}
void drawroundedcorners(Client *c)
{
if (cornerradius <= 0 || !c || c->isfullscreen) {
return;
}
if (borderpx >= 1)
return;
if (!roundedcorners)
return;
Window win;
win = c->win;
if (!win)
return;
XWindowAttributes win_attr;
if (!XGetWindowAttributes(dpy, win, &win_attr))
return;
int dia = 2 * cornerradius;
int w = c->w;
int h = c->h;
if (w < dia || h < dia)
return;
Pixmap mask;
mask = XCreatePixmap(dpy, win, w, h, 1);
if (!mask)
return;
XGCValues xgcv;
GC shape_gc;
shape_gc = XCreateGC(dpy, mask, 0, &xgcv);
if (!shape_gc) {
XFreePixmap(dpy, mask);
free(shape_gc);
return;
}
XSetForeground(dpy, shape_gc, 0);
XFillRectangle(dpy, mask, shape_gc, 0, 0, w, h);
XSetForeground(dpy, shape_gc, 1);
XFillArc(dpy, mask, shape_gc, 0, 0, dia, dia, 0, 23040);
XFillArc(dpy, mask, shape_gc, w-dia-1, 0, dia, dia, 0, 23040);
XFillArc(dpy, mask, shape_gc, 0, h-dia-1, dia, dia, 0, 23040);
XFillArc(dpy, mask, shape_gc, w-dia-1, h-dia-1, dia, dia, 0, 23040);
XFillRectangle(dpy, mask, shape_gc, cornerradius, 0, w-dia, h);
XFillRectangle(dpy, mask, shape_gc, 0, cornerradius, w, h-dia);
XShapeCombineMask(dpy, win, ShapeBounding, 0, 0, mask, ShapeSet);
XFreePixmap(dpy, mask);
XFreeGC(dpy, shape_gc);
}
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 (!c->issteam) {
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
c->needresize = 1;
} 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);
}
void
copyvalidchars(char *text, char *rawtext)
{
int i = -1, j = 0;
while(rawtext[++i]) {
if ((unsigned char)rawtext[i] >= ' ') {
text[j++] = rawtext[i];
}
}
text[j] = '\0';
}
Monitor *
createmon(void)
{
Monitor *m;
unsigned int i;
m = ecalloc(1, sizeof(Monitor));
m->tagset[0] = m->tagset[1] = startontag ? 1 : 0;
m->mfact = mfact;
m->nmaster = nmaster;
m->showbar = showbar;
m->barposition = barposition;
m->bh = bh;
m->gappih = gappih;
m->gappiv = gappiv;
m->gappoh = gappoh;
m->gappov = gappov;
m->lt[0] = &layouts[0];
m->lt[1] = &layouts[1 % LENGTH(layouts)];
strncpy(m->ltsymbol, layouts[0].symbol, sizeof m->ltsymbol);
m->pertag = ecalloc(1, sizeof(Pertag));
m->pertag->curtag = m->pertag->prevtag = 1;
for (i = 0; i <= LENGTH(tags); i++) {
m->pertag->nmasters[i] = m->nmaster;
m->pertag->mfacts[i] = m->mfact;
m->pertag->ltidxs[i][0] = m->lt[0];
m->pertag->ltidxs[i][1] = m->lt[1];
m->pertag->sellts[i] = m->sellt;
m->pertag->showbars[i] = m->showbar;
}
#if USETAGPREVIEW
m->tagmap = ecalloc(LENGTH(tags), sizeof(Pixmap));
#endif
return m;
}
void
cyclelayout(const Arg *arg) {
Layout *l;
for(l = (Layout *)layouts; l != selmon->lt[selmon->sellt]; l++);
if(arg->i > 0) {
if(l->symbol && (l + 1)->symbol)
setlayout(&((Arg) { .v = (l + 1) }));
else
setlayout(&((Arg) { .v = layouts }));
} else {
if(l != layouts && (l - 1)->symbol)
setlayout(&((Arg) { .v = (l - 1) }));
else
setlayout(&((Arg) { .v = &layouts[LENGTH(layouts) - 2] }));
}
}
void
destroynotify(XEvent *e)
{
Client *c;
Monitor *m;
XDestroyWindowEvent *ev = &e->xdestroywindow;
if ((c = wintoclient(ev->window)))
unmanage(c, 1);
else if ((c = swallowingclient(ev->window)))
unmanage(c->swallowing, 1);
if (altbar && (m = wintomon(ev->window)) && m->barwin == ev->window)
unmanagealtbar(ev->window);
else if (altbar && m->traywin == ev->window)
unmanagetray(ev->window);
}
#if USEMOUSE
void
layoutmenu(const Arg *arg) {
FILE *p;
char c[3];
int i;
if (!(p = popen(layoutmenu_cmd, "r")))
return;
pclose(p);
i = atoi(c);
setlayout(&((Arg) {.v = &layouts[i]}));
}
#endif
void
detach(Client *c)
{
Client **tc;
for (tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next);
*tc = c->next;
}
void
getfacts(Monitor *m, int msize, int ssize, float *mf, float *sf, int *mr, int *sr)
{
unsigned int n;
float mfacts, sfacts;
int mtotal = 0, stotal = 0;
Client *c;
for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
mfacts = MIN(n, m->nmaster);
sfacts = n - m->nmaster;
for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++)
if (n < m->nmaster)
mtotal += msize / mfacts;
else
stotal += ssize / sfacts;
*mf = mfacts; // total factor of master area
*sf = sfacts; // total factor of stack area
*mr = msize - mtotal; // the remainder (rest) of pixels after an even master split
*sr = ssize - stotal; // the remainder (rest) of pixels after an even stack split
}
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;
}
#if USEMOUSE
void
dragcfact(const Arg *arg)
{
int prev_x, prev_y, dist_x, dist_y;
float fact;
Client *c;
XEvent ev;
Time lasttime = 0;
if (!(c = selmon->sel))
return;
if (c->isfloating) {
resizemouse(arg);
return;
}
if (c->isfullscreen) /* no support resizing fullscreen windows by mouse */
return;
restack(selmon);
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/2, c->h/2);
prev_x = prev_y = -999999;
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 / 60))
continue;
lasttime = ev.xmotion.time;
if (prev_x == -999999) {
prev_x = ev.xmotion.x_root;
prev_y = ev.xmotion.y_root;
}
dist_x = ev.xmotion.x - prev_x;
dist_y = ev.xmotion.y - prev_y;
if (abs(dist_x) > abs(dist_y)) {
fact = (float) 4.0 * dist_x / c->mon->ww;
} else {
fact = (float) -4.0 * dist_y / c->mon->wh;
}
if (fact)
setcfact(&((Arg) { .f = fact }));
prev_x = ev.xmotion.x;
prev_y = ev.xmotion.y;
break;
}
} while (ev.type != ButtonRelease);
XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w/2, c->h/2);
XUngrabPointer(dpy, CurrentTime);
while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
}
#endif
Bool
isHexDigit(char digit) {
return (digit >= '0' && digit <= '9') || (digit >= 'A' && digit <= 'F') || (digit >= 'a' && digit <= 'f');
}
Bool
isHexColor(char* hex) {
return isHexDigit(hex[1]) && isHexDigit(hex[2]) && isHexDigit(hex[3]) &&
isHexDigit(hex[4]) && isHexDigit(hex[5]) && isHexDigit(hex[6]) &&
hex[0] == '#' && hex[7] == '\0';
}
void
readAndSetColor(int clrIdx, char* txt) {
char buf[8];
memcpy(buf, txt, 7);
buf[7] = '\0';
if(isHexColor(buf)) {
drw_clr_create(drw, &drw->scheme[clrIdx], buf, alphas[SchemeStatus][ColBg]);
}
}
int
drawstatusbar(Monitor *m, int bh, char* stext) {
int ret, i, j, w, x, len;
short isCode = 0;
char *text;
char *p;
len = strlen(stext) + 1 ;
if (!(text = (char*) malloc(sizeof(char)*len)))
die("malloc");
p = text;
i = -1, j = 0;
while (rawstext[++i])
if ((unsigned char)rawstext[i] >= ' ')
text[j++] = rawstext[i];
text[j] = '\0';
/* compute width of the status text */
w = 0;
i = -1;
while (text[++i]) {
if (text[i] == '^') {
if (!isCode) {
isCode = 1;
text[i] = '\0';
w += TEXTW(text) - lrpad;
text[i] = '^';
if (text[++i] == 'f')
w += atoi(text + ++i);
} else {
isCode = 0;
text = text + i + 1;
i = -1;
}
}
}
if (!isCode)
w += TEXTW(text) - lrpad;
else
isCode = 0;
text = p;
w += 2; /* 1px padding on both sides */
ret = x = m->ww - w - 2 * sp;
drw_setscheme(drw, scheme[LENGTH(colors)]);
drw->scheme[ColFg] = scheme[SchemeStatus][ColFg];
drw->scheme[ColBg] = scheme[SchemeStatus][ColBg];
drw_rect(drw, x, 0, w, bh, 1, 1);
x++;
/* process status text */
i = -1;
while (text[++i]) {
if (text[i] == '^' && !isCode) {
isCode = 1;
text[i] = '\0';
w = TEXTW(text) - lrpad;
drw_text(drw, x, 0, w, bh, 0, text, 0);
x += w;
/* process code */
while (text[++i] != '^') {
if (text[i] == 'c') {
readAndSetColor(ColFg, (char*)text+i+1);
i += 7;
} else if (text[i] == 'b') {
readAndSetColor(ColBg, (char*)text+i+1);
i += 7;
} else if (text[i] == 'C') {
int c = atoi(text + ++i);
drw_clr_create(drw, &drw->scheme[ColFg], colstatus[c], alphas[SchemeStatus][ColBg]);
} else if (text[i] == 'B') {
int c = atoi(text + ++i);
drw_clr_create(drw, &drw->scheme[ColBg], colstatus[c], alphas[SchemeStatus][ColBg]);
} else if (text[i] == 'd') {
drw->scheme[ColFg] = scheme[SchemeStatus][ColFg];
drw->scheme[ColBg] = scheme[SchemeStatus][ColBg];
} else if (text[i] == 'r') {
int rx = atoi(text + ++i);
while (text[++i] != ',');
int ry = atoi(text + ++i);
while (text[++i] != ',');
int rw = atoi(text + ++i);
while (text[++i] != ',');
int rh = atoi(text + ++i);
drw_rect(drw, rx + x, ry, rw, rh, 1, 0);
} else if (text[i] == 'f') {
x += atoi(text + ++i);
}
}
text = text + i + 1;
i=-1;
isCode = 0;
}
}
if (!isCode) {
w = TEXTW(text) - lrpad;
drw_text(drw, x, 0, w, bh, 0, text, 0);
w = 0;
}
drw_setscheme(drw, scheme[SchemeStatus]);
free(p);
return ret;
}
void
drawbar(Monitor *m)
{
int x = 0, w = 0, tw = 0, scm;
int boxs = drw->fonts->h / 9;
int boxw = drw->fonts->h / 6 + 2;
unsigned int i, occ = 0, urg = 0, n = 0;
#if LAYOUT_MONOCLE
unsigned int s = 0, a = 0;
#endif
const char *tagtext;
Client *c;
if (!m->showbar)
return;
if (altbar)
return;
/* draw status first so it can be overdrawn by tags later */
if (m == selmon || 1) { /* status is only drawn on selected monitor */
char *text, *s, ch;
if (!hidestatus) {
tw = statusw = m->ww - drawstatusbar(m, bh, stext);
}
// for statuscmd
for (text = s = stext; *s; s++) {
if ((unsigned char)(*s) < ' ') {
ch = *s;
*s = '\0';
tw = TEXTW(text) - lrpad;
x += tw;
*s = ch;
text = s + 1;
}
}
}
for (c = m->clients; c; c = c->next) {
if (ISVISIBLE(c))
n++;
occ |= c->tags;
if (c->isurgent && !hidetags)
urg |= c->tags;
}
/* Draw the layout bar on the left if leftlayout = 1 */
/* If colorlayoutnorm = 0, draw using SchemeLayout */
if (leftlayout && !hidelayout) {
w = blw = TEXTW(m->ltsymbol);
drw_setscheme(drw, scheme[SchemeLayout]);
x = drw_text(drw, x, 0, w, bh, lrpad / 2, m->ltsymbol, 0);
}
if (!hidetags) {
for (i = 0; i < LENGTH(tags); i++) {
if (!(occ & 1 << i || m->tagset[m->seltags] & 1 << i))
continue;
if (!hidetags) {
tagtext = occ & 1 << i ? usedtags[i] : tags[i];
w = TEXTW(tagtext);
drw_setscheme(drw, (m->tagset[m->seltags] & 1 << i ? tagscheme[i] : scheme[SchemeTags]));
drw_text(drw, x, 0, w, bh, lrpad / 2, tagtext, urg & 1 << i);
if (underlineall || m->tagset[m->seltags] & 1 << i)
if (underline)
drw_rect(drw, x + underlinepad, bh - underlinestroke - underlinevoffset, w - (underlinepad * 2), underlinestroke, 1, 0);
x += w;
}
}
}
#if LAYOUT_MONOCLE
if (monoclecount) {
if (m->lt[m->sellt]->arrange == monocle) {
for (c = nexttiled(m->clients), a = 0, s = 0; c; c = nexttiled(c->next), a++)
if (c == m->stack)
s = a + 1;
if (!s && a)
s = 1;
snprintf(m->ltsymbol, sizeof m->ltsymbol, monocleformat, s, a);
}
}
#endif
/* Draw the layout bar on the right if leftlayout is not 0 */
/* If colorlayoutnorm = 0, draw using SchemeLayout */
if (!leftlayout && !hidelayout) {
w = blw = TEXTW(m->ltsymbol);
drw_setscheme(drw, scheme[SchemeLayout]);
x = drw_text(drw, x, 0, w, bh, lrpad / 2, m->ltsymbol, 0);
}
if ((w = m->ww - tw - x) > bh) {
if (n > 0) {
int remainder = w % n;
int tabw = (1.0 / (double)n) * w + 1;
for (c = m->clients; c; c = c->next) {
if (!ISVISIBLE(c))
continue;
if (m->sel == c)
scm = SchemeSelTitle;
else if (HIDDEN(c))
scm = SchemeHid;
else
scm = SchemeNormTitle;
drw_setscheme(drw, scheme[scm]);
if (remainder >= 0) {
if (remainder == 0) {
tabw--;
}
remainder--;
}
if (!hidetitle) {
if (hideicon) {
drw_text(drw, x, 0, tabw, bh, lrpad / 2, c->name, 0);
} else {
#if USEWINICON
drw_text(drw, x, 0, tabw, bh, lrpad / 2 + (c->icon ? c->icw + ICONSPACING : 0), c->name, 0);
if (c->icon) drw_pic(drw, x + lrpad / 2, (bh - c->ich) / 2, c->icw, c->ich, c->icon);
#else
drw_text(drw, x, 0, tabw, bh, lrpad / 2, c->name, 0);
#endif
}
}
// Draw sticky window indicator
if (c->issticky && !hidesticky) {
drw_polygon(drw, x + boxs, c->isfloating ? boxs * 2 + boxw : boxs, stickyiconbb.x, stickyiconbb.y, boxw, boxw * stickyiconbb.y / stickyiconbb.x, stickyicon, LENGTH(stickyicon), Nonconvex, c->tags & c->mon->tagset[c->mon->seltags]);
}
// Draw floating window indicator
if (c->isfloating && !hidefloating) {
drw_rect(drw, x + boxs, boxs, boxw, boxw, c->isfixed, 0);
}
x += tabw;
}
} else {
drw_setscheme(drw, scheme[SchemeBar]);
drw_rect(drw, x, 0, w, bh, 1, 1);
}
}
m->bt = n;
m->btw = w;
drw_map(drw, m->barwin, 0, 0, m->ww, bh);
}
void
drawbars(void)
{
Monitor *m;
for (m = mons; m; m = m->next)
drawbar(m);
}
#if USEMOUSE
void
enternotify(XEvent *e)
{
if (!clicktofocus) {
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);
}
}
#endif
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) || HIDDEN(c)); c = c->snext);
if (selmon->sel && selmon->sel != c) {
unfocus(selmon->sel, 0);
if (selmon->hidsel) {
hidewin(selmon->sel);
if (c)
arrange(c->mon);
selmon->hidsel = 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[SchemeSelBorder][ColBorder].pixel);
setfocus(c);
#if USEFADE
opacity(c, activeopacity);
#endif
} else {
XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
}
selmon->sel = c;
#if LAYOUT_MONOCLE
if (selmon->lt[selmon->sellt]->arrange == monocle)
arrangemon(selmon);
#endif
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);
warp(selmon->sel);
}
void
focusstackvis(const Arg *arg)
{
focusstack(arg->i, 0);
}
void
focusstackhid(const Arg *arg)
{
focusstack(arg->i, 1);
}
void
focusstack(int inc, int hid)
{
Client *c = NULL, *i;
if (!selmon->sel && !hid)
return;
if (!selmon->clients)
return;
if (inc > 0) {
if (selmon->sel)
for (c = selmon->sel->next;
c && (!ISVISIBLE(c) || (!hid && HIDDEN(c)));
c = c->next);
if (!c)
for (c = selmon->clients;
c && (!ISVISIBLE(c) || (!hid && HIDDEN(c)));
c = c->next);
} else {
if (selmon->sel) {
for (i = selmon->clients; i != selmon->sel; i = i->next)
if (ISVISIBLE(i) && !(!hid && HIDDEN(i)))
c = i;
} else
c = selmon->clients;
if (!c)
for (; i; i = i->next)
if (ISVISIBLE(i) && !(!hid && HIDDEN(i)))
c = i;
}
if (c) {
focus(c);
restack(selmon);
if (HIDDEN(c)) {
showwin(c);
c->mon->hidsel = 1;
}
}
}
Atom
getatomprop(Client *c, Atom prop)
{
int di;
unsigned long dl;
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;
XFree(p);
}
return atom;
}
#if USEWINICON
static uint32_t prealpha(uint32_t p) {
uint8_t a = p >> 24u;
uint32_t rb = (a * (p & 0xFF00FFu)) >> 8u;
uint32_t g = (a * (p & 0x00FF00u)) >> 8u;
return (rb & 0xFF00FFu) | (g & 0x00FF00u) | (a << 24u);
}
Picture
geticonprop(Window win, unsigned int *picw, unsigned int *pich)
{
int format;
unsigned long n, extra, *p = NULL;
Atom real;
if (XGetWindowProperty(dpy, win, netatom[NetWMIcon], 0L, LONG_MAX, False, AnyPropertyType,
&real, &format, &n, &extra, (unsigned char **)&p) != Success)
return None;
if (n == 0 || format != 32) { XFree(p); return None; }
unsigned long *bstp = NULL;
uint32_t w, h, sz;
{
unsigned long *i; const unsigned long *end = p + n;
uint32_t bstd = UINT32_MAX, d, m;
for (i = p; i < end - 1; i += sz) {
if ((w = *i++) >= 16384 || (h = *i++) >= 16384) { XFree(p); return None; }
if ((sz = w * h) > end - i) break;
if ((m = w > h ? w : h) >= ICONSIZE && (d = m - ICONSIZE) < bstd) { bstd = d; bstp = i; }
}
if (!bstp) {
for (i = p; i < end - 1; i += sz) {
if ((w = *i++) >= 16384 || (h = *i++) >= 16384) { XFree(p); return None; }
if ((sz = w * h) > end - i) break;
if ((d = ICONSIZE - (w > h ? w : h)) < bstd) { bstd = d; bstp = i; }
}
}
if (!bstp) { XFree(p); return None; }
}
if ((w = *(bstp - 2)) == 0 || (h = *(bstp - 1)) == 0) { XFree(p); return None; }
uint32_t icw, ich;
if (w <= h) {
ich = ICONSIZE; icw = w * ICONSIZE / h;
if (icw == 0) icw = 1;
}
else {
icw = ICONSIZE; ich = h * ICONSIZE / w;
if (ich == 0) ich = 1;
}
*picw = icw; *pich = ich;
uint32_t i, *bstp32 = (uint32_t *)bstp;
for (sz = w * h, i = 0; i < sz; ++i) bstp32[i] = prealpha(bstp[i]);
Picture ret = drw_picture_create_resized(drw, (char *)bstp, w, h, icw, ich);
XFree(p);
return ret;
}
#endif
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, (unsigned char **)&p) != Success)
return -1;
if (n != 0)
result = *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)
strncpy(text, (char *)name.value, size - 1);
else {
if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
strncpy(text, *list, size - 1);
XFreeStringList(list);
}
}
text[size - 1] = '\0';
XFree(name.value);
return 1;
}
void
grabbuttons(Client *c, int focused)
{
updatenumlockmask();
{
#if USEMOUSE
unsigned int i, j;
unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
#endif
XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
if (!focused)
XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
BUTTONMASK, GrabModeSync, GrabModeSync, None, None);
#if USEMOUSE
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);
#endif
}
}
void
grabkeys(void)
{
updatenumlockmask();
{
unsigned int i, j;
unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
KeyCode code;
KeyCode chain;
XUngrabKey(dpy, AnyKey, AnyModifier, root);
for (i = 0; i < LENGTH(keys); i++)
if ((code = XKeysymToKeycode(dpy, keys[i].keysym))) {
if (keys[i].chain != -1 &&
((chain = XKeysymToKeycode(dpy, keys[i].chain))))
code = chain;
for (j = 0; j < LENGTH(modifiers); j++)
XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
True, GrabModeAsync, GrabModeAsync);
}
}
}
void
hide(const Arg *arg)
{
hidewin(selmon->sel);
focus(NULL);
arrange(selmon);
}
void
hidewin(Client *c) {
if (!c || HIDDEN(c))
return;
Window w = c->win;
static XWindowAttributes ra, ca;
// more or less taken directly from blackbox's hide() function
XGrabServer(dpy);
XGetWindowAttributes(dpy, root, &ra);
XGetWindowAttributes(dpy, w, &ca);
// prevent UnmapNotify events
XSelectInput(dpy, root, ra.your_event_mask & ~SubstructureNotifyMask);
XSelectInput(dpy, w, ca.your_event_mask & ~StructureNotifyMask);
XUnmapWindow(dpy, w);
setclientstate(c, IconicState);
XSelectInput(dpy, root, ra.your_event_mask);
XSelectInput(dpy, w, ca.your_event_mask);
XUngrabServer(dpy);
}
#if USEIPC
int
handlexevent(struct epoll_event *ev)
{
if (ev->events & EPOLLIN) {
XEvent ev;
while (running && XPending(dpy)) {
XNextEvent(dpy, &ev);
if (handler[ev.type]) {
handler[ev.type](&ev); /* call handler */
ipc_send_events(mons, &lastselmon, selmon);
}
}
} else if (ev-> events & EPOLLHUP) {
return -1;
}
return 0;
}
#endif
void
incnmaster(const Arg *arg)
{
if (i3nmaster) {
selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag] = !selmon->nmaster;
} else {
selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag] = 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, j;
KeySym keysym;
XKeyEvent *ev;
int current = 0;
unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
ev = &e->xkey;
keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
for (i = 0; i < LENGTH(keys); i++) {
if (keysym == keys[i].keysym && keys[i].chain == -1
&& CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
&& keys[i].func)
keys[i].func(&(keys[i].arg));
else if (keysym == keys[i].chain && keychain == -1
&& CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
&& keys[i].func) {
current = 1;
keychain = keysym;
for (j = 0; j < LENGTH(modifiers); j++)
XGrabKey(dpy, AnyKey, 0 | modifiers[j], root,
True, GrabModeAsync, GrabModeAsync);
} else if (!current && keysym == keys[i].keysym
&& keychain != -1
&& keys[i].chain == keychain
&& keys[i].func)
keys[i].func(&(keys[i].arg));
}
if (!current) {
keychain = -1;
grabkeys();
}
}
int
fake_signal(void)
{
char fsignal[256];
char indicator[9] = "fsignal:";
char str_signum[16];
int i, v, signum;
size_t len_fsignal, len_indicator = strlen(indicator);
// Get root name property
if (gettextprop(root, XA_WM_NAME, fsignal, sizeof(fsignal))) {
len_fsignal = strlen(fsignal);
// Check if this is indeed a fake signal
if (len_indicator > len_fsignal ? 0 : strncmp(indicator, fsignal, len_indicator) == 0) {
memcpy(str_signum, &fsignal[len_indicator], len_fsignal - len_indicator);
str_signum[len_fsignal - len_indicator] = '\0';
// Convert string value into managable integer
for (i = signum = 0; i < strlen(str_signum); i++) {
v = str_signum[i] - '0';
if (v >= 0 && v <= 9) {
signum = signum * 10 + v;
}
}
// Check if a signal was found, and if so handle it
if (signum)
for (i = 0; i < LENGTH(signals); i++)
if (signum == signals[i].signum && signals[i].func)
signals[i].func(&(signals[i].arg));
// A fake signal was sent
return 1;
}
}
// No fake signal was sent, so proceed with update
return 0;
}
void
setgaps(int oh, int ov, int ih, int iv)
{
if (oh < 0) oh = 0;
if (ov < 0) ov = 0;
if (ih < 0) ih = 0;
if (iv < 0) iv = 0;
selmon->gappoh = oh;
selmon->gappov = ov;
selmon->gappih = ih;
selmon->gappiv = iv;
arrange(selmon);
}
void
getgaps(Monitor *m, int *oh, int *ov, int *ih, int *iv, unsigned int *nc)
{
unsigned int n, oe, ie;
#if PERTAG_PATCH
oe = ie = selmon->pertag->enablegaps[selmon->pertag->curtag];
#else
oe = ie = enablegaps;
#endif // PERTAG_PATCH
Client *c;
for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
if (smartgaps && n == 1) {
oe = smartgapsize; // outer gaps disabled when only one client
}
*oh = m->gappoh*oe; // outer horizontal gap
*ov = m->gappov*oe; // outer vertical gap
*ih = m->gappih*ie; // inner horizontal gap
*iv = m->gappiv*ie; // inner vertical gap
*nc = n; // number of clients
}
void
show(const Arg *arg)
{
if (selmon->hidsel)
selmon->hidsel = 0;
showwin(selmon->sel);
}
void
showwin(Client *c)
{
if (!c || !HIDDEN(c))
return;
XMapWindow(dpy, c->win);
setclientstate(c, NormalState);
arrange(c->mon);
}
void
showhide(Client *c)
{
if (!c)
return;
if (ISVISIBLE(c)) {
/* show clients top down */
XMoveWindow(dpy, c->win, c->x, c->y);
if (c->needresize) {
c->needresize = 0;
XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
} else {
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);
}
}
#if USEMOUSE
void
togglewin(const Arg *arg)
{
Client *c = (Client*)arg->v;
if (c == selmon->sel) {
hidewin(c);
focus(NULL);
arrange(selmon);
} else {
if (HIDDEN(c))
showwin(c);
focus(c);
restack(selmon);
}
}
#endif
void
togglegaps(const Arg *arg)
{
enablegaps = !enablegaps;
arrange(selmon);
}
void
defaultgaps(const Arg *arg)
{
setgaps(gappoh, gappov, gappih, gappiv);
}
void
incrgaps(const Arg *arg)
{
setgaps(
selmon->gappoh + arg->i,
selmon->gappov + arg->i,
selmon->gappih + arg->i,
selmon->gappiv + arg->i
);
}
void
incrigaps(const Arg *arg)
{
setgaps(
selmon->gappoh,
selmon->gappov,
selmon->gappih + arg->i,
selmon->gappiv + arg->i
);
}
void
incrogaps(const Arg *arg)
{
setgaps(
selmon->gappoh + arg->i,
selmon->gappov + arg->i,
selmon->gappih,
selmon->gappiv
);
}
void
killclient(const Arg *arg)
{
if (!selmon->sel || selmon->sel->ispermanent)
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
killunsel(const Arg *arg)
{
Client *i = NULL;
if (!selmon->sel)
return;
for (i = selmon->clients; i; i = i->next) {
if (ISVISIBLE(i) && i != selmon->sel) {
if (!sendevent(i, wmatom[WMDelete])) {
XGrabServer(dpy);
XSetErrorHandler(xerrordummy);
XSetCloseDownMode(dpy, DestroyAll);
XKillClient(dpy, i->win);
XSync(dpy, False);
XSetErrorHandler(xerror);
XUngrabServer(dpy);
}
}
}
}
void
manage(Window w, XWindowAttributes *wa)
{
Client *c, *t = NULL, *term = NULL;
Window trans = None;
XWindowChanges wc;
int format;
unsigned int *ptags;
unsigned long n, extra;
Atom atom;
c = ecalloc(1, sizeof(Client));
c->win = w;
c->pid = winpid(w);
if (getatomprop(c, netatom[NetWMWindowType]) == netatom[NetWMWindowTypeDesktop]) {
XMapWindow(dpy, c->win);
XLowerWindow(dpy, c->win);
free(c);
return;
}
/* 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;
c->cfact = 1.0;
#if USEWINICON
updateicon(c);
#endif
updatetitle(c);
if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) {
c->mon = t->mon;
c->tags = t->tags;
} else {
c->mon = selmon;
applyrules(c);
term = termforwin(c);
if(XGetWindowProperty(dpy, c->win, dwmatom[DWMTags], 0L, 1L, False, XA_CARDINAL,
&atom, &format, &n, &extra, (unsigned char **)&ptags) == Success && n == 1 && *ptags != 0) {
c->tags = *ptags;
XFree(ptags);
}
}
settagsatom(c->win, c->tags);
if (unmanaged) {
XMapWindow(dpy, c->win);
if (unmanaged == 1)
XRaiseWindow(dpy, c->win);
else if (unmanaged == 2)
XLowerWindow(dpy, c->win);
free(c);
unmanaged = 0;
return;
}
if (c->x + WIDTH(c) > c->mon->mx + c->mon->mw)
c->x = c->mon->mx + c->mon->mw - WIDTH(c);
if (c->y + HEIGHT(c) > c->mon->my + c->mon->mh)
c->y = c->mon->my + c->mon->mh - HEIGHT(c);
c->x = MAX(c->x, c->mon->mx);
/* only fix client y-offset, if the client center might cover the bar */
c->y = MAX(c->y, ((c->mon->by == c->mon->my) && (c->x + (c->w / 2) >= c->mon->wx)
&& (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : c->mon->my);
c->bw = borderpx;
wc.border_width = c->bw;
XConfigureWindow(dpy, w, CWBorderWidth, &wc);
XSetWindowBorder(dpy, w, scheme[SchemeNormBorder][ColBorder].pixel);
configure(c); /* propagates border_width, if size doesn't change */
updatewindowtype(c);
updatesizehints(c);
updatewmhints(c);
{
int format;
unsigned long *data, n, extra;
Monitor *m;
Atom atom;
if (XGetWindowProperty(dpy, c->win, netatom[NetClientInfo], 0L, 2L, False, XA_CARDINAL,
&atom, &format, &n, &extra, (unsigned char **)&data) == Success && n == 2) {
c->tags = *data;
for (m = mons; m; m = m->next) {
if (m->num == *(data+1)) {
c->mon = m;
break;
}
}
}
if (n > 0)
XFree(data);
}
setclienttagprop(c);
if (savefloat)
{
c->sfx = c->x;
c->sfy = c->y;
c->sfw = c->w;
c->sfh = c->h;
}
if (centerfloating)
{
c->x = c->mon->mx + (c->mon->mw - WIDTH(c)) / 2;
c->y = c->mon->my + (c->mon->mh - HEIGHT(c)) / 2;
}
updatemotifhints(c);
XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
grabbuttons(c, 0);
if (!c->isfloating)
c->isfloating = c->oldstate = t || c->isfixed;
if (c->isfloating)
XRaiseWindow(dpy, c->win);
switch(attachdirection){
case 1:
attachabove(c);
break;
case 2:
attachaside(c);
break;
case 3:
attachbelow(c);
break;
case 4:
attachbottom(c);
break;
case 5:
attachtop(c);
break;
default:
attach(c);
}
attachstack(c);
setclienttagprop(c);
XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
(unsigned char *) &(c->win), 1);
XChangeProperty(dpy, root, netatom[NetClientListStacking], XA_WINDOW, 32, PropModePrepend,
(unsigned char *) &(c->win), 1);
XMoveResizeWindow(dpy, c->win, c->x + 2 * tw, c->y, c->w, c->h); /* some windows require this */
//setclientstate(c, NormalState);
if (!HIDDEN(c))
setclientstate(c, NormalState);
if (c->mon == selmon)
unfocus(selmon->sel, 0);
c->mon->sel = c;
arrange(c->mon);
if (!HIDDEN(c))
XMapWindow(dpy, c->win);
if (term)
swallow(term, c);
if (focusspawn && !warpcursor) {
focus(c); // Auto focus next spawned window
} else {
focus(NULL); // No need if warpcursor is enabled because warpcursor is going to warp and focus the window anyway
}
}
void
managealtbar(Window win, XWindowAttributes *wa)
{
Monitor *m;
if (!(m = recttomon(wa->x, wa->y, wa->width, wa->height)))
return;
m->barwin = win;
m->by = wa->y;
bh = m->bh = wa->height;
updatebarpos(m);
arrange(m);
XSelectInput(dpy, win, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
XMoveResizeWindow(dpy, win, wa->x, wa->y, wa->width, wa->height);
XMapWindow(dpy, win);
XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
(unsigned char *) &win, 1);
}
void
managetray(Window win, XWindowAttributes *wa)
{
Monitor *m;
if (!(m = recttomon(wa->x, wa->y, wa->width, wa->height)))
return;
m->traywin = win;
m->tx = wa->x;
m->tw = wa->width;
updatebarpos(m);
arrange(m);
XSelectInput(dpy, win, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
XMoveResizeWindow(dpy, win, wa->x, wa->y, wa->width, wa->height);
XMapWindow(dpy, win);
XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
(unsigned char *) &win, 1);
}
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))
return;
if (!wa.depth)
return;
if (wa.override_redirect)
return;
if (wmclasscontains(ev->window, altbarclass, ""))
managealtbar(ev->window, &wa);
else if (!wintoclient(ev->window))
manage(ev->window, &wa);
}
void
motionnotify(XEvent *e)
{
Monitor *m;
Client *c;
m = 0;
static Monitor *mon = NULL;
XMotionEvent *ev = &e->xmotion;
unsigned int i, x = 0, occ = 0;
if (ev->window == selmon->barwin) {
i = x = 0;
for (c = selmon->clients; c; c = c->next)
occ |= c->tags == 255 ? 0 : c->tags;
if (leftlayout)
x += blw;
do {
if (!(occ & 1 << i || selmon->tagset[selmon->seltags] & 1 << i))
continue;
x += TEXTW(occ & 1 << i ? usedtags[i] : tags[i]);
} while (ev->x >= x && ++i < (LENGTH(tags)));
#if USETAGPREVIEW
if (mousepreview && !hidetags) {
if (i < LENGTH(tags)) {
if ((i + 1) != selmon->previewshow && !(selmon->tagset[selmon->seltags] & 1 << i)) {
selmon->previewshow = i + 1;
showtagpreview(i);
} else if (selmon->tagset[selmon->seltags] & 1 << i) {
selmon->previewshow = 0;
XUnmapWindow(dpy, selmon->tagwin);
}
} else if (selmon->previewshow) {
selmon->previewshow = 0;
XUnmapWindow(dpy, selmon->tagwin);
}
} else if (selmon->previewshow) {
showtagpreview(0);
XUnmapWindow(dpy, selmon->tagwin);
}
#endif
}
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
moveresize(const Arg *arg) {
/* only floating windows can be moved */
Client *c;
c = selmon->sel;
int x, y, w, h, nx, ny, nw, nh, ox, oy, ow, oh;
char xAbs, yAbs, wAbs, hAbs;
int msx, msy, dx, dy, nmx, nmy;
unsigned int dui;
Window dummy;
if (!c || !arg)
return;
if (selmon->lt[selmon->sellt]->arrange && !c->isfloating)
return;
if (sscanf((char *)arg->v, "%d%c %d%c %d%c %d%c", &x, &xAbs, &y, &yAbs, &w, &wAbs, &h, &hAbs) != 8)
return;
/* compute new window position; prevent window from be positioned outside the current monitor */
nw = c->w + w;
if (wAbs == 'W')
nw = w < selmon->mw - 2 * c->bw ? w : selmon->mw - 2 * c->bw;
nh = c->h + h;
if (hAbs == 'H')
nh = h < selmon->mh - 2 * c->bw ? h : selmon->mh - 2 * c->bw;
nx = c->x + x;
if (xAbs == 'X') {
if (x < selmon->mx)
nx = selmon->mx;
else if (x > selmon->mx + selmon->mw)
nx = selmon->mx + selmon->mw - nw - 2 * c->bw;
else
nx = x;
}
ny = c->y + y;
if (yAbs == 'Y') {
if (y < selmon->my)
ny = selmon->my;
else if (y > selmon->my + selmon->mh)
ny = selmon->my + selmon->mh - nh - 2 * c->bw;
else
ny = y;
}
ox = c->x;
oy = c->y;
ow = c->w;
oh = c->h;
XRaiseWindow(dpy, c->win);
Bool xqp = XQueryPointer(dpy, root, &dummy, &dummy, &msx, &msy, &dx, &dy, &dui);
resize(c, nx, ny, nw, nh, True);
/* move cursor along with the window to avoid problems caused by the sloppy focus */
if (xqp && ox <= msx && (ox + ow) >= msx && oy <= msy && (oy + oh) >= msy)
{
nmx = c->x - ox + c->w - ow;
nmy = c->y - oy + c->h - oh;
/* make sure the cursor stays inside the window */
if ((msx + nmx) > c->x && (msy + nmy) > c->y)
XWarpPointer(dpy, None, None, 0, 0, 0, 0, nmx, nmy);
}
}
void
moveresizeedge(const Arg *arg) {
/* move or resize floating window to edge of screen */
Client *c;
c = selmon->sel;
char e;
int nx, ny, nw, nh, ox, oy, ow, oh, bp;
int msx, msy, dx, dy, nmx, nmy;
int starty;
unsigned int dui;
Window dummy;
nx = c->x;
ny = c->y;
nw = c->w;
nh = c->h;
starty = selmon->showbar && barposition ? bh : 0;
bp = selmon->showbar && !barposition ? bh : 0;
if (!c || !arg)
return;
if (selmon->lt[selmon->sellt]->arrange && !c->isfloating)
return;
if(sscanf((char *)arg->v, "%c", &e) != 1)
return;
if(e == 't')
ny = starty;
if(e == 'b')
ny = c->h > selmon->mh - 2 * c->bw ? c->h - bp : selmon->mh - c->h - 2 * c->bw - bp;
if(e == 'l')
nx = selmon->mx;
if(e == 'r')
nx = c->w > selmon->mw - 2 * c->bw ? selmon->mx + c->w : selmon->mx + selmon->mw - c->w - 2 * c->bw;
if(e == 'T') {
/* if you click to resize again, it will return to old size/position */
if(c->h + starty == c->oldh + c->oldy) {
nh = c->oldh;
ny = c->oldy;
} else {
nh = c->h + c->y - starty;
ny = starty;
}
}
if(e == 'B')
nh = c->h + c->y + 2 * c->bw + bp == selmon->mh ? c->oldh : selmon->mh - c->y - 2 * c->bw - bp;
if(e == 'L') {
if(selmon->mx + c->w == c->oldw + c->oldx) {
nw = c->oldw;
nx = c->oldx;
} else {
nw = c->w + c->x - selmon->mx;
nx = selmon->mx;
}
}
if(e == 'R')
nw = c->w + c->x + 2 * c->bw == selmon->mx + selmon->mw ? c->oldw : selmon->mx + selmon->mw - c->x - 2 * c->bw;
ox = c->x;
oy = c->y;
ow = c->w;
oh = c->h;
XRaiseWindow(dpy, c->win);
Bool xqp = XQueryPointer(dpy, root, &dummy, &dummy, &msx, &msy, &dx, &dy, &dui);
resize(c, nx, ny, nw, nh, True);
/* move cursor along with the window to avoid problems caused by the sloppy focus */
if (xqp && ox <= msx && (ox + ow) >= msx && oy <= msy && (oy + oh) >= msy) {
nmx = c->x - ox + c->w - ow;
nmy = c->y - oy + c->h - oh;
/* make sure the cursor stays inside the window */
if ((msx + nmx) > c->x && (msy + nmy) > c->y)
XWarpPointer(dpy, None, None, 0, 0, 0, 0, nmx, nmy);
}
}
Client *
nexttagged(Client *c) {
Client *walked = c->mon->clients;
for(;
walked && (walked->isfloating || !ISVISIBLEONTAG(walked, c->tags));
walked = walked->next
);
return walked;
}
#if USEMOUSE
void
moveorplace(const Arg *arg) {
if ((!selmon->lt[selmon->sellt]->arrange || (selmon->sel && selmon->sel->isfloating)))
movemouse(arg);
else
placemouse(arg);
}
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 / 60))
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);
}
}
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;
if (!mousemfact) {
XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
} else {
if (c->isfloating || NULL == c->mon->lt[c->mon->sellt]->arrange) {
XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
} else {
XWarpPointer(dpy, None, root, 0, 0, 0, 0,
selmon->mx + (selmon->ww * selmon->mfact),
selmon->my + (selmon->wh / 2)
);
}
}
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 / 60))
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 (!mousemfact) {
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);
if (c->isfloating || NULL == c->mon->lt[c->mon->sellt]->arrange) {
XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
} else {
if (mousemfact) {
selmon->mfact = (double) (ev.xmotion.x_root - selmon->mx) / (double) selmon->ww;
arrange(selmon);
XWarpPointer(dpy, None, root, 0, 0, 0, 0,
selmon->mx + (selmon->ww * selmon->mfact),
selmon->my + (selmon->wh / 2)
);
}
}
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);
}
}
#endif
Client *
nexttiled(Client *c)
{
for (; c && (c->isfloating || !ISVISIBLE(c) || HIDDEN(c)); c = c->next);
return c;
}
#if USEFADE
void
opacity(Client *c, double opacity)
{
if(bUseOpacity && opacity > 0 && opacity < 1 && fadeinactive) {
unsigned long real_opacity[] = { opacity * 0xffffffff };
XChangeProperty(dpy, c->win, netatom[NetWMWindowsOpacity], XA_CARDINAL,
32, PropModeReplace, (unsigned char *)real_opacity,
1);
} else
XDeleteProperty(dpy, c->win, netatom[NetWMWindowsOpacity]);
}
#endif
void
placemouse(const Arg *arg)
{
int x, y, px, py, ocx, ocy, nx = -9999, ny = -9999, freemove = 0;
Client *c, *r = NULL, *at, *prevr;
Monitor *m;
XEvent ev;
XWindowAttributes wa;
Time lasttime = 0;
int attachmode, prevattachmode;
attachmode = prevattachmode = -1;
if (!(c = selmon->sel) || !c->mon->lt[c->mon->sellt]->arrange) /* no support for placemouse when floating layout is used */
return;
if (c->isfullscreen) /* no support placing fullscreen windows by mouse */
return;
restack(selmon);
prevr = c;
if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess)
return;
c->isfloating = 0;
c->beingmoved = 1;
XGetWindowAttributes(dpy, c->win, &wa);
ocx = wa.x;
ocy = wa.y;
if (arg->i == 2) // warp cursor to client center
XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, WIDTH(c) / 2, HEIGHT(c) / 2);
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 / 60))
continue;
lasttime = ev.xmotion.time;
nx = ocx + (ev.xmotion.x - x);
ny = ocy + (ev.xmotion.y - y);
if (!freemove && (abs(nx - ocx) > snap || abs(ny - ocy) > snap))
freemove = 1;
if (freemove)
XMoveWindow(dpy, c->win, nx, ny);
if ((m = recttomon(ev.xmotion.x, ev.xmotion.y, 1, 1)) && m != selmon)
selmon = m;
if (arg->i == 1) { // tiled position is relative to the client window center point
px = nx + wa.width / 2;
py = ny + wa.height / 2;
} else { // tiled position is relative to the mouse cursor
px = ev.xmotion.x;
py = ev.xmotion.y;
}
r = recttoclient(px, py, 1, 1);
if (!r || r == c)
break;
attachmode = 0; // below
if (((float)(r->y + r->h - py) / r->h) > ((float)(r->x + r->w - px) / r->w)) {
if (abs(r->y - py) < r->h / 2)
attachmode = 1; // above
} else if (abs(r->x - px) < r->w / 2)
attachmode = 1; // above
if ((r && r != prevr) || (attachmode != prevattachmode)) {
detachstack(c);
detach(c);
if (c->mon != r->mon) {
arrangemon(c->mon);
c->tags = r->mon->tagset[r->mon->seltags];
}
c->mon = r->mon;
r->mon->sel = r;
if (attachmode) {
if (r == r->mon->clients)
attach(c);
else {
for (at = r->mon->clients; at->next != r; at = at->next);
c->next = at->next;
at->next = c;
}
} else {
c->next = r->next;
r->next = c;
}
attachstack(c);
arrangemon(r->mon);
prevr = r;
prevattachmode = attachmode;
}
break;
}
} while (ev.type != ButtonRelease);
XUngrabPointer(dpy, CurrentTime);
if ((m = recttomon(ev.xmotion.x, ev.xmotion.y, 1, 1)) && m != c->mon) {
detach(c);
detachstack(c);
arrangemon(c->mon);
c->mon = m;
c->tags = m->tagset[m->seltags];
attach(c);
attachstack(c);
selmon = m;
}
focus(c);
c->beingmoved = 0;
if (nx != -9999)
resize(c, nx, ny, c->w, c->h, 0);
arrangemon(c->mon);
}
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)) {
if (!fake_signal())
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->ignoretransient && !c->isfloating &&
(XGetTransientForHint(dpy, c->win, &trans)) &&
(c->isfloating = (wintoclient(trans)) != NULL))
arrange(c->mon);
break;
case XA_WM_NORMAL_HINTS:
updatesizehints(c);
break;
case XA_WM_HINTS:
updatewmhints(c);
drawbars();
break;
}
if (ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
updatetitle(c);
updaterules(c);
if (c == c->mon->sel)
drawbar(c->mon);
}
#if USEWINICON
else if (ev->atom == netatom[NetWMIcon]) {
updateicon(c);
if (c == c->mon->sel)
drawbar(c->mon);
}
#endif
if (ev->atom == netatom[NetWMWindowType])
updatewindowtype(c);
if (ev->atom == motifatom)
updatemotifhints(c);
if (ev->atom == wmatom[WMClass]) {
if (wmclass) {
applyrules(c);
}
}
}
}
void
saveSession(void)
{
FILE *fw = fopen(SESSION_FILE, "w");
for (Client *c = selmon->clients; c != NULL; c = c->next) { // get all the clients with their tags and write them to the file
fprintf(fw, "%lu %u\n", c->win, c->tags);
}
fclose(fw);
}
void
restoreSession(void)
{
// restore session
FILE *fr = fopen(SESSION_FILE, "r");
if (!fr)
return;
char *str = malloc(23 * sizeof(char)); // allocate enough space for excepted input from text file
while (fscanf(fr, "%[^\n] ", str) != EOF) { // read file till the end
long unsigned int winId;
unsigned int tagsForWin;
int check = sscanf(str, "%lu %u", &winId, &tagsForWin); // get data
if (check != 2) // break loop if data wasn't read correctly
break;
for (Client *c = selmon->clients; c ; c = c->next) { // add tags to every window by winId
if (c->win == winId) {
c->tags = tagsForWin;
break;
}
}
}
for (Client *c = selmon->clients; c ; c = c->next) { // refocus on windows
focus(c);
restack(c->mon);
}
for (Monitor *m = selmon; m; m = m->next) // rearrange all monitors
arrange(m);
free(str);
fclose(fr);
// delete a file
remove(SESSION_FILE);
}
void
quit(const Arg *arg)
{
Monitor *m;
Client *c;
// fix: reloading dwm keeps all the hidden clients hidden
for (m = mons; m; m = m->next) {
if (m) {
for (c = m->stack; c; c = c->next)
if (c && HIDDEN(c)) showwin(c);
}
}
if(arg->i) restart = 1;
running = 0;
if (restart == 1)
saveSession();
}
Client *
recttoclient(int x, int y, int w, int h)
{
Client *c, *r = NULL;
int a, area = 0;
for (c = nexttiled(selmon->clients); c; c = nexttiled(c->next)) {
if ((a = INTERSECTC(x, y, w, h, c)) > area) {
area = a;
r = c;
}
}
return r;
}
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
resetlayout(const Arg *arg)
{
if (defaultlayout) {
Arg default_layout = {.v = &layouts[0]};
Arg default_mfact = {.f = mfact + 1};
setlayout(&default_layout);
setmfact(&default_mfact);
}
}
void
reorganizetags(const Arg *arg) {
Client *c;
unsigned int occ, unocc, i;
unsigned int tagdest[LENGTH(tags)];
occ = 0;
for (c = selmon->clients; c; c = c->next)
occ |= (1 << (ffs(c->tags)-1));
unocc = 0;
for (i = 0; i < LENGTH(tags); ++i) {
while (unocc < i && (occ & (1 << unocc)))
unocc++;
if (occ & (1 << i)) {
tagdest[i] = unocc;
occ &= ~(1 << i);
occ |= 1 << unocc;
}
}
for (c = selmon->clients; c; c = c->next)
c->tags = 1 << tagdest[ffs(c->tags)-1];
if (selmon->sel)
selmon->tagset[selmon->seltags] = selmon->sel->tags;
arrange(selmon);
}
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;
if (c->beingmoved)
return;
wc.border_width = c->bw;
if ((nexttiled(c->mon->clients) == c) && !(nexttiled(c->next)))
resetlayout(NULL);
XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
configure(c);
XSync(dpy, False);
}
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));
if (warpcursor)
{
if (m == selmon && (m->tagset[m->seltags] & m->sel->tags) && selmon->lt[selmon->sellt] != &layouts[2])
warp(m->sel);
}
}
void
run(void)
{
#if USEIPC
int event_count = 0;
const int MAX_EVENTS = 10;
struct epoll_event events[MAX_EVENTS];
#endif
XSync(dpy, False);
#if USEIPC
/* main event loop */
while (running) {
event_count = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
for (int i = 0; i < event_count; i++) {
int event_fd = events[i].data.fd;
DEBUG("Got event from fd %d\n", event_fd);
if (event_fd == dpy_fd) {
// -1 means EPOLLHUP
if (handlexevent(events + i) == -1)
return;
} else if (event_fd == ipc_get_sock_fd()) {
ipc_handle_socket_epoll_event(events + i);
} else if (ipc_is_client_registered(event_fd)){
if (ipc_handle_client_epoll_event(events + i, mons, &lastselmon, selmon,
LENGTH(tags), layouts, LENGTH(layouts)) < 0) {
fprintf(stderr, "Error handling IPC event on fd %d\n", event_fd);
}
} else {
fprintf(stderr, "Got event from unknown fd %d, ptr %p, u32 %d, u64 %lu",
event_fd, events[i].data.ptr, events[i].data.u32,
events[i].data.u64);
fprintf(stderr, " with events %d\n", events[i].events);
return;
}
}
}
#endif
}
void spawnscratch(const Arg *arg)
{
if (fork() == 0) {
if (dpy)
close(ConnectionNumber(dpy));
setsid();
execvp(((char **)arg->v)[1], ((char **)arg->v)+1);
fprintf(stderr, "speedwm: execvp %s", ((char **)arg->v)[1]);
perror(" failed");
exit(EXIT_SUCCESS);
}
}
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 (altbar && wmclasscontains(wins[i], altbarclass, ""))
managealtbar(wins[i], &wa);
else 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);
}
}
static void scratchpad_hide ()
{
if (selmon -> sel)
{
selmon -> sel -> tags = SCRATCHPAD_MASK;
if (floatscratchpad)
selmon -> sel -> isfloating = 1;
focus(NULL);
arrange(selmon);
}
}
static _Bool scratchpad_last_showed_is_killed (void)
{
_Bool killed = 1;
for (Client * c = selmon -> clients; c != NULL; c = c -> next)
{
if (c == scratchpad_last_showed)
{
killed = 0;
break;
}
}
return killed;
}
static void scratchpad_remove ()
{
if (selmon -> sel && scratchpad_last_showed != NULL && selmon -> sel == scratchpad_last_showed)
scratchpad_last_showed = NULL;
}
static void scratchpad_show ()
{
if (scratchpad_last_showed == NULL || scratchpad_last_showed_is_killed ())
scratchpad_show_first ();
else
{
if (scratchpad_last_showed -> tags != SCRATCHPAD_MASK)
{
scratchpad_last_showed -> tags = SCRATCHPAD_MASK;
focus(NULL);
arrange(selmon);
}
else
{
_Bool found_current = 0;
_Bool found_next = 0;
for (Client * c = selmon -> clients; c != NULL; c = c -> next)
{
if (found_current == 0)
{
if (c == scratchpad_last_showed)
{
found_current = 1;
continue;
}
}
else
{
if (c -> tags == SCRATCHPAD_MASK)
{
found_next = 1;
scratchpad_show_client (c);
break;
}
}
}
if (found_next == 0) scratchpad_show_first ();
}
}
}
static void scratchpad_show_client (Client * c)
{
scratchpad_last_showed = c;
c -> tags = selmon->tagset[selmon->seltags];
focus(c);
arrange(selmon);
}
static void scratchpad_show_first (void)
{
for (Client * c = selmon -> clients; c != NULL; c = c -> next)
{
if (c -> tags == SCRATCHPAD_MASK)
{
scratchpad_show_client (c);
break;
}
}
}
void
scantray(void)
{
unsigned int num;
Window d1, d2, *wins = NULL;
XWindowAttributes wa;
if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
for (unsigned int i = 0; i < num; i++) {
if (wmclasscontains(wins[i], altbarclass, alttrayname)) {
if (!XGetWindowAttributes(dpy, wins[i], &wa))
break;
managetray(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] ? m->tagset[m->seltags] : 1);
//attach(c);
switch(attachdirection){
case 1:
attachabove(c);
break;
case 2:
attachaside(c);
break;
case 3:
attachbelow(c);
break;
case 4:
attachbottom(c);
break;
case 5:
attachtop(c);
break;
default:
attach(c);
}
attachstack(c);
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);
}
void
setcurrentdesktop(void){
long data[] = { 0 };
XChangeProperty(dpy, root, netatom[NetCurrentDesktop], XA_CARDINAL, 32, PropModeReplace, (unsigned char *)data, 1);
}
void
setdesktopnames(void)
{
XTextProperty text;
Xutf8TextListToTextProperty(dpy, tags, TAGSLENGTH, XUTF8StringStyle, &text);
XSetTextProperty(dpy, root, &text, netatom[NetDesktopNames]);
}
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
setnumdesktops(void){
long data[] = { TAGSLENGTH };
XChangeProperty(dpy, root, netatom[NetNumberOfDesktops], XA_CARDINAL, 32, PropModeReplace, (unsigned char *)data, 1);
}
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 = selmon->pertag->sellts[selmon->pertag->curtag] ^= 1;
if (arg && arg->v)
selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt] = (Layout *)arg->v;
if (selmon->sel)
arrange(selmon);
else
drawbar(selmon);
}
void
setcfact(const Arg *arg)
{
float f;
Client *c;
c = selmon->sel;
if (!arg || !c || !selmon->lt[selmon->sellt]->arrange)
return;
if (!arg->f)
f = 1.0;
else if (arg->f > 4.0) // set fact absolutely
f = arg->f - 4.0;
else
f = arg->f + c->cfact;
if (f < 0.25)
f = 0.25;
else if (f > 4.0)
f = 4.0;
c->cfact = f;
arrange(selmon);
}
#if USEIPC
void
setlayoutsafe(const Arg *arg)
{
const Layout *ltptr = (Layout *)arg->v;
if (ltptr == 0)
setlayout(arg);
for (int i = 0; i < LENGTH(layouts); i++) {
if (ltptr == &layouts[i])
setlayout(arg);
}
}
#endif
/* 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 = selmon->pertag->mfacts[selmon->pertag->curtag] = f;
arrange(selmon);
}
void
toggleopacity(const Arg *arg) {
#if USEFADE
bUseOpacity = !bUseOpacity;
for (Monitor* m = mons; m; m = m->next)
for (Client* c = m->clients; c; c = c->next)
opacity(c, (bUseOpacity && c != selmon->sel) ? inactiveopacity : activeopacity);
#endif
}
void
setup(void)
{
XSetWindowAttributes wa;
Atom utf8string;
/* clean up any zombies immediately */
sigchld(0);
signal(SIGHUP, sighup);
signal(SIGTERM, sigterm);
/* init screen */
screen = DefaultScreen(dpy);
tw = DisplayWidth(dpy, screen);
sh = DisplayHeight(dpy, screen);
root = RootWindow(dpy, screen);
xinitvisual();
drw = drw_create(dpy, screen, root, tw, sh, visual, depth, cmap);
if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
die("no fonts could be loaded.");
lrpad = drw->fonts->h;
bh = altbar ? 0 : drw->fonts->h + barheight;
sp = barpaddingh;
vp = (barposition == 1) ? barpaddingv : - barpaddingv;
updategeom();
int i = 0;
/* 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);
#if USEWINICON
netatom[NetWMIcon] = XInternAtom(dpy, "_NET_WM_ICON", False);
#endif
netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
if (fullscreenhidebar)
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[NetWMWindowTypeDesktop] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DESKTOP", False);
netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
dwmatom[DWMTags] = XInternAtom(dpy, "_DWM_TAGS", False);
netatom[NetClientInfo] = XInternAtom(dpy, "_NET_CLIENT_INFO", False);
netatom[NetClientListStacking] = XInternAtom(dpy, "_NET_CLIENT_LIST_STACKING", False);
#if USEFADE
netatom[NetWMWindowsOpacity] = XInternAtom(dpy, "_NET_WM_WINDOW_OPACITY", False);
#endif
netatom[NetDesktopViewport] = XInternAtom(dpy, "_NET_DESKTOP_VIEWPORT", False);
netatom[NetNumberOfDesktops] = XInternAtom(dpy, "_NET_NUMBER_OF_DESKTOPS", False);
netatom[NetCurrentDesktop] = XInternAtom(dpy, "_NET_CURRENT_DESKTOP", False);
netatom[NetDesktopNames] = XInternAtom(dpy, "_NET_DESKTOP_NAMES", False);
motifatom = XInternAtom(dpy, "_MOTIF_WM_HINTS", 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) + 1, sizeof(Clr *));
scheme[LENGTH(colors)] = drw_scm_create(drw, colors[0], alphas[i], 3);
if (LENGTH(tags) > LENGTH(tagsel))
die("too few color schemes for the tags");
for (i = 0; i < LENGTH(colors); i++)
scheme[i] = drw_scm_create(drw, colors[i], alphas[i], 3);
tagscheme = ecalloc(LENGTH(tagsel), sizeof(Clr *));
for (i = 0; i < LENGTH(tagsel); i++)
tagscheme[i] = drw_scm_create(drw, tagsel[i], tagalpha, 2);
/* init bars */
updatebars();
updatestatus();
#if USETAGPREVIEW
updatepreview();
#endif
/* supporting window for NetWMCheck */
if (fullscreenhidebar) {
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 *) "speedwm", 7);
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);
setnumdesktops();
setcurrentdesktop();
setdesktopnames();
setviewport();
XDeleteProperty(dpy, root, netatom[NetClientList]);
XDeleteProperty(dpy, root, netatom[NetClientInfo]);
XDeleteProperty(dpy, root, netatom[NetClientListStacking]);
/* select events */
wa.cursor = cursor[CurNormal]->cursor;
wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
|ButtonPressMask|PointerMotionMask|EnterWindowMask
|LeaveWindowMask|StructureNotifyMask|PropertyChangeMask|KeyPressMask;
XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
XSelectInput(dpy, root, wa.event_mask);
grabkeys();
focus(NULL);
#if USEIPC
setupepoll();
#endif
spawnbar();
}
void
setviewport(void){
long data[] = { 0, 0 };
XChangeProperty(dpy, root, netatom[NetDesktopViewport], XA_CARDINAL, 32, PropModeReplace, (unsigned char *)data, 2);
}
#if USEIPC
void
setupepoll(void)
{
epoll_fd = epoll_create1(0);
dpy_fd = ConnectionNumber(dpy);
struct epoll_event dpy_event;
// Initialize struct to 0
memset(&dpy_event, 0, sizeof(dpy_event));
DEBUG("Display socket is fd %d\n", dpy_fd);
if (epoll_fd == -1) {
fputs("Failed to create epoll file descriptor", stderr);
}
dpy_event.events = EPOLLIN;
dpy_event.data.fd = dpy_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, dpy_fd, &dpy_event)) {
fputs("Failed to add display file descriptor to epoll", stderr);
close(epoll_fd);
exit(1);
}
if (ipc_init(ipcsockpath, epoll_fd, ipccommands, LENGTH(ipccommands)) < 0) {
fputs("Failed to initialize IPC\n", stderr);
}
}
#endif
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);
}
#if USETAGPREVIEW
void
showtagpreview(unsigned int i)
{
if (!selmon->previewshow || !selmon->tagmap[i]) {
XUnmapWindow(dpy, selmon->tagwin);
return;
}
if (tagpreview) {
XSetWindowBackgroundPixmap(dpy, selmon->tagwin, selmon->tagmap[i]);
XCopyArea(dpy, selmon->tagmap[i], selmon->tagwin, drw->gc, 0, 0,
selmon->mw / scalepreview, selmon->mh / scalepreview,
0, 0);
XSync(dpy, False);
XMapWindow(dpy, selmon->tagwin);
}
}
#endif
void
sigchld(int unused)
{
pid_t pid;
if (signal(SIGCHLD, sigchld) == SIG_ERR)
die("can't install SIGCHLD handler:");
while (0 < (pid = waitpid(-1, NULL, WNOHANG))) {
pid_t *p, *lim;
if (!(p = autostart_pids))
continue;
lim = &p[autostart_len];
for (; p < lim; p++) {
if (*p == pid) {
*p = -1;
break;
}
}
}
}
#if USETAGPREVIEW
void
getpreview(void)
{
unsigned int occ = 0, i;
Client *c;
Imlib_Image image;
for (c = selmon->clients; c; c = c->next)
occ |= c->tags == 255 ? 0 : c->tags;
for (i = 0; i < LENGTH(tags); i++) {
/* searching for tags that are occupied && selected */
if (!(occ & 1 << i) || !(selmon->tagset[selmon->seltags] & 1 << i))
continue;
if (selmon->tagmap[i]) { /* tagmap exist, clean it */
XFreePixmap(dpy, selmon->tagmap[i]);
selmon->tagmap[i] = 0;
}
if (!(image = imlib_create_image(tw, sh))) {
fprintf(stderr, "speedwm: imlib: failed to create image, skipping.\n");
continue;
}
imlib_context_set_image(image);
imlib_context_set_display(dpy);
imlib_image_set_has_alpha(1);
imlib_context_set_blend(0);
imlib_context_set_visual(visual);
imlib_context_set_drawable(root);
if (!barpreview)
imlib_copy_drawable_to_image(0, selmon->wx, selmon->wy, selmon->ww ,selmon->wh, 0, 0, 1);
else
imlib_copy_drawable_to_image(0, selmon->mx, selmon->my, selmon->mw ,selmon->mh, 0, 0, 1);
selmon->tagmap[i] = XCreatePixmap(dpy, selmon->tagwin, selmon->mw + tagpreviewpaddingh / scalepreview, selmon->mh + 1 * sp + tagpreviewpaddingv / scalepreview, depth);
imlib_context_set_drawable(selmon->tagmap[i]);
imlib_render_image_part_on_drawable_at_size(0, 0, selmon->mw + tagpreviewpaddingh, selmon->mh + 1 * sp, 0, 0 + tagpreviewpaddingv + 1 * sp, selmon->mw / scalepreview, selmon->mh / scalepreview);
imlib_free_image();
}
}
#endif
void
sighup(int unused)
{
Arg a = {.i = 1};
quit(&a);
}
void
sigterm(int unused)
{
Arg a = {.i = 0};
quit(&a);
}
#ifdef XINERAMA
void
sortscreens(XineramaScreenInfo *screens, int n)
{
int i, j;
XineramaScreenInfo *screen = ecalloc(1, sizeof(XineramaScreenInfo));
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (RIGHTOF(screens[i], screens[j])) {
memcpy(&screen[0], &screens[i], sizeof(XineramaScreenInfo));
memcpy(&screens[i], &screens[j], sizeof(XineramaScreenInfo));
memcpy(&screens[j], &screen[0], sizeof(XineramaScreenInfo));
}
XFree(screen);
}
#endif /* XINERAMA */
void
spawn(const Arg *arg)
{
if (fork() == 0) {
if (dpy)
close(ConnectionNumber(dpy));
#if USEMOUSE
if (arg->v == statuscmd) {
for (int i = 0; i < LENGTH(statuscmds); i++) {
if (statuscmdn == statuscmds[i].id) {
statuscmd[2] = statuscmds[i].cmd;
setenv("BUTTON", lastbutton, 1);
break;
}
}
if (!statuscmd[2])
exit(EXIT_SUCCESS);
}
#endif
setsid();
execvp(((char **)arg->v)[0], (char **)arg->v);
fprintf(stderr, "speedwm: execvp %s", ((char **)arg->v)[0]);
perror(" failed");
exit(EXIT_SUCCESS);
}
}
void
spawnbar()
{
if (*altbarcmd)
if (system(altbarcmd) == 0)
return;
}
void
tagmon(const Arg *arg)
{
Client *c = selmon->sel;
if (!c || !mons->next)
return;
if (movefullscreenmon) {
if (c->isfullscreen) {
c->isfullscreen = 0;
sendmon(c, dirtomon(arg->i));
c->isfullscreen = 1;
resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh);
XRaiseWindow(dpy, c->win);
} else
sendmon(c, dirtomon(arg->i));
} else {
sendmon(selmon->sel, dirtomon(arg->i));
}
}
void
viewtoleft(const Arg *arg) {
if(__builtin_popcount(selmon->tagset[selmon->seltags] & TAGMASK) == 1
&& selmon->tagset[selmon->seltags] > 1) {
selmon->seltags ^= 1; /* toggle sel tagset */
selmon->tagset[selmon->seltags] = selmon->tagset[selmon->seltags ^ 1] >> 1;
focus(NULL);
arrange(selmon);
}
}
void
viewtoright(const Arg *arg) {
if(__builtin_popcount(selmon->tagset[selmon->seltags] & TAGMASK) == 1
&& selmon->tagset[selmon->seltags] & (TAGMASK >> 1)) {
selmon->seltags ^= 1; /* toggle sel tagset */
selmon->tagset[selmon->seltags] = selmon->tagset[selmon->seltags ^ 1] << 1;
focus(NULL);
arrange(selmon);
}
}
void
togglebar(const Arg *arg)
{
/**
* Polybar tray does not raise maprequest event. It must be manually scanned
* for. Scanning it too early while the tray is being populated would give
* wrong dimensions.
*/
if (altbar && !selmon->traywin)
scantray();
selmon->showbar = selmon->pertag->showbars[selmon->pertag->curtag] = !selmon->showbar;
updatebarpos(selmon);
XMoveResizeWindow(dpy, selmon->barwin, selmon->wx + sp, selmon->by + vp, selmon->ww - 2 * sp, selmon->bh);
XMoveResizeWindow(dpy, selmon->traywin, selmon->wx + sp, selmon->by + vp, selmon->ww - 2 * sp, selmon->bh);
if (altbar)
XMoveResizeWindow(dpy, selmon->traywin, selmon->tx, selmon->by, selmon->tw, selmon->bh);
arrange(selmon);
}
void
togglescratch(const Arg *arg)
{
Client *c;
unsigned int found = 0;
for (c = selmon->clients; c && !(found = c->scratchkey == ((char**)arg->v)[0][0]); c = c->next);
if (found) {
c->tags = ISVISIBLE(c) ? 0 : selmon->tagset[selmon->seltags];
focus(NULL);
arrange(selmon);
if (ISVISIBLE(c)) {
focus(c);
restack(selmon);
}
} else{
spawnscratch(arg);
}
}
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)
{
if (savefloat)
{
/* restore last known float dimensions */
resize(selmon->sel, selmon->sel->sfx, selmon->sel->sfy, selmon->sel->sfw, selmon->sel->sfh, False);
}
else
{
resize(selmon->sel, selmon->sel->x, selmon->sel->y, selmon->sel->w, selmon->sel->h, 0);
}
}
else
{
selmon->sel->sfx = selmon->sel->x;
selmon->sel->sfy = selmon->sel->y;
selmon->sel->sfw = selmon->sel->w;
selmon->sel->sfh = selmon->sel->h;
}
arrange(selmon);
}
void
togglesticky(const Arg *arg)
{
if (!selmon->sel)
return;
selmon->sel->issticky = !selmon->sel->issticky;
arrange(selmon);
}
void
togglefullscr(const Arg *arg)
{
if(selmon->sel)
setfullscreen(selmon->sel, !selmon->sel->isfullscreen);
}
#if USEWINICON
void
freeicon(Client *c)
{
if (c->icon) {
XRenderFreePicture(dpy, c->icon);
c->icon = None;
}
updatecurrentdesktop();
}
#endif
void
unfocus(Client *c, int setfocus)
{
if (!c)
return;
grabbuttons(c, 0);
#if USEFADE
opacity(c, inactiveopacity);
#endif
XSetWindowBorder(dpy, c->win, scheme[SchemeNormBorder][ColBorder].pixel);
if (setfocus) {
XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
}
updatecurrentdesktop();
}
void
unmanage(Client *c, int destroyed)
{
Monitor *m = c->mon;
XWindowChanges wc;
if (c->swallowing) {
unswallow(c);
return;
}
Client *s = swallowingclient(c->win);
if (s) {
free(s->swallowing);
s->swallowing = NULL;
arrange(m);
focus(NULL);
return;
}
detach(c);
detachstack(c);
#if USEWINICON
freeicon(c);
#endif
if (!destroyed) {
wc.border_width = c->oldbw;
XGrabServer(dpy); /* avoid race conditions */
XSetErrorHandler(xerrordummy);
XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
setclientstate(c, WithdrawnState);
XSync(dpy, False);
XSetErrorHandler(xerror);
XUngrabServer(dpy);
}
if (scratchpad_last_showed == c)
scratchpad_last_showed = NULL;
free(c);
if (!s) {
arrange(m);
focus(NULL);
updateclientlist();
}
}
void
unmanagealtbar(Window w)
{
Monitor *m = wintomon(w);
if (!m)
return;
m->barwin = 0;
m->by = 0;
m->bh = 0;
updatebarpos(m);
arrange(m);
}
void
unmanagetray(Window w)
{
Monitor *m = wintomon(w);
if (!m)
return;
m->traywin = 0;
m->tx = 0;
m->tw = 0;
updatebarpos(m);
arrange(m);
}
void
unmapnotify(XEvent *e)
{
Client *c;
Monitor *m;
XUnmapEvent *ev = &e->xunmap;
if ((c = wintoclient(ev->window))) {
if (ev->send_event)
setclientstate(c, WithdrawnState);
else
unmanage(c, 0);
} else if (altbar && (m = wintomon(ev->window)) && m->barwin == ev->window)
unmanagealtbar(ev->window);
else if (altbar && m->traywin == ev->window)
unmanagetray(ev->window);
}
void
updatebars(void)
{
if (altbar)
return;
Monitor *m;
XSetWindowAttributes wa = {
.override_redirect = True,
.background_pixel = 0,
.border_pixel = 0,
.colormap = cmap,
.event_mask = ButtonPressMask|ExposureMask|PointerMotionMask
};
XClassHint ch = {"speedwm", "speeddwm"};
for (m = mons; m; m = m->next) {
if (m->barwin)
continue;
m->barwin = XCreateWindow(dpy, root, m->wx + sp, m->by + vp, m->ww - 2 * sp, bh, 0, depth,
InputOutput, visual,
CWOverrideRedirect|CWBackPixel|CWBorderPixel|CWColormap|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 = m->wh - barpaddingv - m->bh;
m->by = m->barposition ? m->wy : m->wy + m->wh + barpaddingv;
m->wy = m->barposition ? m->wy + m->bh + vp : m->wy;
} else
m->by = -m->bh - vp;
}
void
updateclientlist()
{
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);
XDeleteProperty(dpy, root, netatom[NetClientListStacking]);
for (m = mons; m; m = m->next)
for (c = m->stack; c; c = c->snext)
XChangeProperty(dpy, root, netatom[NetClientListStacking],
XA_WINDOW, 32, PropModeAppend,
(unsigned char *) &(c->win), 1);
}
void updatecurrentdesktop(void){
long rawdata[] = { selmon->tagset[selmon->seltags] };
int i=0;
while(*rawdata >> (i+1)){
i++;
}
long data[] = { i };
XChangeProperty(dpy, root, netatom[NetCurrentDesktop], XA_CARDINAL, 32, PropModeReplace, (unsigned char *)data, 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;
sortscreens(unique, nn);
if (n <= nn) { /* new monitors available */
for (i = 0; i < (nn - n); 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);
}
} else { /* less monitors available nn < n */
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;
switch(attachdirection){
case 1:
attachabove(c);
break;
case 2:
attachaside(c);
break;
case 3:
attachbelow(c);
break;
case 4:
attachbottom(c);
break;
case 5:
attachtop(c);
break;
default:
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 != tw || mons->mh != sh) {
dirty = 1;
mons->mw = mons->ww = tw;
mons->mh = mons->wh = sh;
updatebarpos(mons);
}
}
if (dirty) {
selmon = mons;
selmon = wintomon(root);
}
return dirty;
}
void
updatemotifhints(Client *c)
{
Atom real;
int format;
unsigned char *p = NULL;
unsigned long n, extra;
unsigned long *motif;
int width, height;
if (!decorhints)
return;
if (XGetWindowProperty(dpy, c->win, motifatom, 0L, 5L, False, motifatom,
&real, &format, &n, &extra, &p) == Success && p != NULL) {
motif = (unsigned long*)p;
if (motif[MWM_HINTS_FLAGS_FIELD] & MWM_HINTS_DECORATIONS) {
width = WIDTH(c);
height = HEIGHT(c);
if (motif[MWM_HINTS_DECORATIONS_FIELD] & MWM_DECOR_ALL ||
motif[MWM_HINTS_DECORATIONS_FIELD] & MWM_DECOR_BORDER ||
motif[MWM_HINTS_DECORATIONS_FIELD] & MWM_DECOR_TITLE)
c->bw = c->oldbw = borderpx;
else
c->bw = c->oldbw = 0;
resize(c, c->x, c->y, width - (2*c->bw), height - (2*c->bw), 0);
}
XFree(p);
}
}
void
updatenumlockmask(void)
{
unsigned int i, j;
XModifierKeymap *modmap;
numlockmask = 0;
modmap = XGetModifierMapping(dpy);
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 = size.base_width;
c->baseh = size.base_height;
} else if (size.flags & PMinSize) {
c->basew = size.min_width;
c->baseh = size.min_height;
} else
c->basew = c->baseh = 0;
if (size.flags & PResizeInc) {
c->incw = size.width_inc;
c->inch = size.height_inc;
} else
c->incw = c->inch = 0;
if (size.flags & PMaxSize) {
c->maxw = size.max_width;
c->maxh = size.max_height;
} else
c->maxw = c->maxh = 0;
if (size.flags & PMinSize) {
c->minw = size.min_width;
c->minh = size.min_height;
} else if (size.flags & PBaseSize) {
c->minw = size.base_width;
c->minh = size.base_height;
} else
c->minw = c->minh = 0;
if (size.flags & PAspect) {
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);
}
void
updatestatus(void)
{
Monitor* m;
if (!gettextprop(root, XA_WM_NAME, rawstext, sizeof(rawstext)) && !hidestatus) {
strcpy(stext, defaultname);
statusw = TEXTW(stext) - lrpad + 2;
} else {
if (!hidestatus) {
copyvalidchars(stext, rawstext);
char *text, *s, ch;
statusw = 0;
for (text = s = stext; *s; s++) {
if ((unsigned char)(*s) < ' ') {
ch = *s;
*s = '\0';
statusw += TEXTW(text) - lrpad;
*s = ch;
text = s + 1;
}
}
statusw += TEXTW(text) - lrpad + 2;
}
}
if (statusallmons) {
for(m = mons; m; m = m->next)
drawbar(m);
} else {
drawbar(selmon);
}
}
void
updaterules(Client *c)
{
if (refreshrules)
{
const char *class, *instance;
unsigned int i;
const Rule *r;
Monitor *m;
XClassHint ch = { NULL, NULL };
/* rule matching */
XGetClassHint(dpy, c->win, &ch);
class = ch.res_class ? ch.res_class : broken;
instance = ch.res_name ? ch.res_name : broken;
char found_rule = 0;
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;
if(!found_rule)
{
c->tags=0;
found_rule=1;
}
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];
// end apply rules
if (c->isfloating)
resize(c, c->x, c->y,
c->w, c->h, 0);
arrange(c->mon);
}
}
void
updatetitle(Client *c)
{
#if USEIPC
char oldname[sizeof(c->name)];
strcpy(oldname, c->name);
#endif
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')
strcpy(c->name, broken);
#if USEIPC
for (Monitor *m = mons; m; m = m->next) {
if (m->sel == c && strcmp(oldname, c->name) != 0)
ipc_focused_title_change_event(m->num, c->win, oldname, c->name);
}
#endif
}
#if USEWINICON
void
updateicon(Client *c)
{
freeicon(c);
c->icon = geticonprop(c->win, &c->icw, &c->ich);
}
#endif
#if USETAGPREVIEW
void
updatepreview(void)
{
Monitor *m;
XSetWindowAttributes wa = {
.background_pixel = 0,
.border_pixel = 0,
.colormap = cmap,
.override_redirect = True,
//.background_pixmap = ParentRelative,
.event_mask = ButtonPressMask|ExposureMask
};
for (m = mons; m; m = m->next) {
m->tagwin = XCreateWindow(dpy, root, m->wx, m->by + bh, m->mw / scalepreview, m->mh / scalepreview, 0,
depth, CopyFromParent, visual,
CWOverrideRedirect|CWBackPixel|CWBorderPixel|CWColormap|CWEventMask, &wa);
//DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
//CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
XDefineCursor(dpy, m->tagwin, cursor[CurNormal]->cursor);
XMapRaised(dpy, m->tagwin);
XUnmapWindow(dpy, m->tagwin);
}
}
#endif
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)
{
Monitor *m;
int i;
unsigned int tmptag;
#if USEMOUSE
selmon->mouseactivated = 1;
#endif
#if USETAGPREVIEW
/* fix: tag preview gets captured in the next tag preview if the user switched tag while a preview is showing */
if (selmon->previewshow && !selmon->mouseactivated)
return;
#endif
if(arg->ui && (arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
return;
#if USETAGPREVIEW
getpreview();
#endif
for (m = mons; m; m = m->next)
m->seltags ^= 1;
if (arg->ui & TAGMASK) {
for (m = mons; m; m = m->next)
m->tagset[m->seltags] = arg->ui & TAGMASK;
if (pertag) {
selmon->pertag->prevtag = selmon->pertag->curtag;
if (arg->ui == ~0)
selmon->pertag->curtag = 0;
else {
for (i = 0; !(arg->ui & 1 << i); i++) ;
selmon->pertag->curtag = i + 1;
}
} else {
tmptag = selmon->pertag->prevtag;
selmon->pertag->prevtag = selmon->pertag->curtag;
selmon->pertag->curtag = tmptag;
}
selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag];
selmon->mfact = selmon->pertag->mfacts[selmon->pertag->curtag];
selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
selmon->lt[selmon->sellt^1] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt^1];
if (selmon->showbar != selmon->pertag->showbars[selmon->pertag->curtag])
togglebar(NULL);
}
#if USETAGPREVIEW
XUnmapWindow(dpy, selmon->tagwin);
#endif
selmon->mouseactivated = 0;
focus(NULL);
arrange(NULL);
updatecurrentdesktop();
}
void
warp(const Client *c)
{
int x, y;
if (!c) {
XWarpPointer(dpy, None, root, 0, 0, 0, 0, selmon->wx + selmon->ww / 2, selmon->wy + selmon->wh / 2);
return;
}
if (!getrootptr(&x, &y) ||
(x > c->x - c->bw &&
y > c->y - c->bw &&
x < c->x + c->w + c->bw*2 &&
y < c->y + c->h + c->bw*2) ||
(y > c->mon->by && y < c->mon->by + bh) ||
(c->mon->barposition && !y))
return;
XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w / 2, c->h / 2);
}
pid_t
winpid(Window w)
{
pid_t result = 0;
#ifdef __linux__
xcb_res_client_id_spec_t spec = {0};
spec.client = w;
spec.mask = XCB_RES_CLIENT_ID_MASK_LOCAL_CLIENT_PID;
xcb_generic_error_t *e = NULL;
xcb_res_query_client_ids_cookie_t c = xcb_res_query_client_ids(xcon, 1, &spec);
xcb_res_query_client_ids_reply_t *r = xcb_res_query_client_ids_reply(xcon, c, &e);
if (!r)
return (pid_t)0;
xcb_res_client_id_value_iterator_t i = xcb_res_query_client_ids_ids_iterator(r);
for (; i.rem; xcb_res_client_id_value_next(&i)) {
spec = i.data->spec;
if (spec.mask & XCB_RES_CLIENT_ID_MASK_LOCAL_CLIENT_PID) {
uint32_t *t = xcb_res_client_id_value_value(i.data);
result = *t;
break;
}
}
free(r);
if (result == (pid_t)-1)
result = 0;
#endif /* __linux__ */
#ifdef __OpenBSD__
Atom type;
int format;
unsigned long len, bytes;
unsigned char *prop;
pid_t ret;
if (XGetWindowProperty(dpy, w, XInternAtom(dpy, "_NET_WM_PID", 0), 0, 1, False, AnyPropertyType, &type, &format, &len, &bytes, &prop) != Success || !prop)
return 0;
ret = *(pid_t*)prop;
XFree(prop);
result = ret;
#endif /* __OpenBSD__ */
return result;
}
pid_t
getparentprocess(pid_t p)
{
unsigned int v = 0;
#ifdef __linux__
FILE *f;
char buf[256];
snprintf(buf, sizeof(buf) - 1, "/proc/%u/stat", (unsigned)p);
if (!(f = fopen(buf, "r")))
return 0;
if (fscanf(f, "%*u %*s %*c %u", (unsigned *)&v) != 1)
v = (pid_t)0;
fclose(f);
#endif /* __linux__*/
#ifdef __OpenBSD__
int n;
kvm_t *kd;
struct kinfo_proc *kp;
kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, NULL);
if (!kd)
return 0;
kp = kvm_getprocs(kd, KERN_PROC_PID, p, sizeof(*kp), &n);
v = kp->p_ppid;
#endif /* __OpenBSD__ */
return (pid_t)v;
}
int
isdescprocess(pid_t p, pid_t c)
{
while (p != c && c != 0)
c = getparentprocess(c);
return (int)c;
}
Client *
termforwin(const Client *w)
{
Client *c;
Monitor *m;
if (!w->pid || w->isterminal)
return NULL;
for (m = mons; m; m = m->next) {
for (c = m->clients; c; c = c->next) {
if (c->isterminal && !c->swallowing && c->pid && isdescprocess(c->pid, w->pid))
return c;
}
}
return NULL;
}
Client *
swallowingclient(Window w)
{
Client *c;
Monitor *m;
for (m = mons; m; m = m->next) {
for (c = m->clients; c; c = c->next) {
if (c->swallowing && c->swallowing->win == w)
return c;
}
}
return NULL;
}
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 || w == m->traywin)
return m;
if ((c = wintoclient(w)))
return c->mon;
return selmon;
}
int
wmclasscontains(Window win, const char *class, const char *name)
{
XClassHint ch = { NULL, NULL };
int res = 1;
if (XGetClassHint(dpy, win, &ch)) {
if (ch.res_name && strstr(ch.res_name, name) == NULL)
res = 0;
if (ch.res_class && strstr(ch.res_class, class) == NULL)
res = 0;
} else
res = 0;
if (ch.res_class)
XFree(ch.res_class);
if (ch.res_name)
XFree(ch.res_name);
return res;
}
/* 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, "speedwm: 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("speedwm: Do not start speedwm by running 'speedwm'. Your X session should run 'speedwm_run'. See 'speedwm-help -a' for more information.\nhttps://codeberg.org/speedie/speedwm");
return -1;
}
void
xinitvisual()
{
XVisualInfo *infos;
XRenderPictFormat *fmt;
int nitems;
int i;
XVisualInfo tpl = {
.screen = screen,
.depth = 32,
.class = TrueColor
};
long masks = VisualScreenMask | VisualDepthMask | VisualClassMask;
infos = XGetVisualInfo(dpy, masks, &tpl, &nitems);
visual = NULL;
for(i = 0; i < nitems; i ++) {
fmt = XRenderFindVisualFormat(dpy, infos[i].visual);
if (fmt->type == PictTypeDirect && fmt->direct.alphaMask) {
visual = infos[i].visual;
depth = infos[i].depth;
cmap = XCreateColormap(dpy, root, visual, AllocNone);
useargb = 1;
break;
}
}
XFree(infos);
if (! visual) {
visual = DefaultVisual(dpy, screen);
depth = DefaultDepth(dpy, screen);
cmap = DefaultColormap(dpy, screen);
}
}
void
zoom(const Arg *arg)
{
Client *c = selmon->sel;
if (!selmon->lt[selmon->sellt]->arrange
|| (selmon->sel && selmon->sel->isfloating))
return;
if (c == nexttiled(selmon->clients))
if (!c || !(c = nexttiled(c->next)))
return;
pop(c);
}
void
resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst)
{
char *sdst = NULL;
int *idst = NULL;
float *fdst = NULL;
sdst = dst;
idst = dst;
fdst = dst;
char fullname[256];
char *type;
XrmValue ret;
snprintf(fullname, sizeof(fullname), "%s.%s", "speedwm", name);
fullname[sizeof(fullname) - 1] = '\0';
XrmGetResource(db, fullname, "*", &type, &ret);
if (!(ret.addr == NULL || strncmp("String", type, 64)))
{
switch (rtype) {
case STRING:
strcpy(sdst, ret.addr);
break;
case INTEGER:
*idst = strtoul(ret.addr, NULL, 10);
break;
case FLOAT:
*fdst = strtof(ret.addr, NULL);
break;
}
}
}
void
load_xresources(void)
{
Display *display;
char *resm;
XrmDatabase db;
ResourcePref *p;
display = XOpenDisplay(NULL);
resm = XResourceManagerString(display);
if (!resm)
return;
db = XrmGetStringDatabase(resm);
for (p = resources; p < resources + LENGTH(resources); p++)
resource_load(db, p->name, p->type, p->dst);
XCloseDisplay(display);
}
/* Thanks to https://codeberg.org/explosion-mental/demwm for this! */
void
previewtag(const Arg *arg)
{
#if USETAGPREVIEW
if (selmon->previewshow != (arg->ui + 1))
selmon->previewshow = arg->ui + 1;
else
selmon->previewshow = 0;
showtagpreview(arg->ui);
#endif
}
void
setclienttagprop(Client *c)
{
long data[] = { (long) c->tags, (long) c->mon->num };
XChangeProperty(dpy, c->win, netatom[NetClientInfo], XA_CARDINAL, 32,
PropModeReplace, (unsigned char *) data, 2);
}
void
settagsatom(Window w, unsigned int tags) {
XChangeProperty(dpy, w, dwmatom[DWMTags], XA_CARDINAL, 32,
PropModeReplace, (unsigned char*)&tags, 1);
}
int
main(int argc, char *argv[])
{
if (argc == 2 && !strcmp("-v", argv[1]))
die("speedwm-"VERSION);
else if (argc != 1)
die("usage: speedwm [-v]");
if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
fputs("warning: no locale support\n", stderr);
if (!(dpy = XOpenDisplay(NULL)))
die("speedwm: cannot open display");
if (!(xcon = XGetXCBConnection(dpy)))
die("speedwm: cannot get xcb connection\n");
checkotherwm();
autostart_exec();
XrmInitialize();
load_xresources();
setup();
#ifdef __OpenBSD__
if (pledge("stdio rpath proc exec ps", NULL) == -1)
die("pledge");
#endif /* __OpenBSD__ */
scan();
restoreSession();
run();
if(restart) execvp(argv[0], argv);
cleanup();
XCloseDisplay(dpy);
return EXIT_SUCCESS;
}
void
livereloadxrdb(const Arg *arg)
{
load_xresources();
int i;
for (i = 0; i < LENGTH(colors); i++)
scheme[i] = drw_scm_create(drw, colors[i], alphas[i], 3);
focus(NULL);
arrange(NULL);
}
void
insertclient(Client *item, Client *insertItem, int after) {
Client *c;
if (item == NULL || insertItem == NULL || item == insertItem) return;
detach(insertItem);
if (!after && selmon->clients == item) {
attach(insertItem);
return;
}
if (after) {
c = item;
} else {
for (c = selmon->clients; c; c = c->next) { if (c->next == item) break; }
}
insertItem->next = c->next;
c->next = insertItem;
}
void
inplacerotate(const Arg *arg)
{
if(!selmon->sel || (selmon->sel->isfloating && !arg->f)) return;
unsigned int selidx = 0, i = 0;
Client *c = NULL, *stail = NULL, *mhead = NULL, *mtail = NULL, *shead = NULL;
// Determine positionings for insertclient
for (c = selmon->clients; c; c = c->next) {
if (ISVISIBLE(c) && !(c->isfloating)) {
if (selmon->sel == c) { selidx = i; }
if (i == selmon->nmaster - 1) { mtail = c; }
if (i == selmon->nmaster) { shead = c; }
if (mhead == NULL) { mhead = c; }
stail = c;
i++;
}
}
// All clients rotate
if (arg->i == 2) insertclient(selmon->clients, stail, 0);
if (arg->i == -2) insertclient(stail, selmon->clients, 1);
// Stack xor master rotate
if (arg->i == -1 && selidx >= selmon->nmaster) insertclient(stail, shead, 1);
if (arg->i == 1 && selidx >= selmon->nmaster) insertclient(shead, stail, 0);
if (arg->i == -1 && selidx < selmon->nmaster) insertclient(mtail, mhead, 1);
if (arg->i == 1 && selidx < selmon->nmaster) insertclient(mhead, mtail, 0);
// Restore focus position
i = 0;
for (c = selmon->clients; c; c = c->next) {
if (!ISVISIBLE(c) || (c->isfloating)) continue;
if (i == selidx) { focus(c); break; }
i++;
}
arrange(selmon);
focus(c);
}