/* See LICENSE file for copyright and license details. * * dynamic window manager is designed like any other X client as well. It is * driven through handling X events. In contrast to other X clients, a window * manager selects for SubstructureRedirectMask on the root window, to receive * events about window (dis-)appearance. Only one X connection at a time is * allowed to select for this event mask. * * The event handlers of dwm are organized in an array which is accessed * whenever a new event has been fetched. This allows event dispatching * in O(1) time. * * Each child of the root window is called a client, except windows which have * set the override_redirect flag. Clients are organized in a global * linked client list, the focus history is remembered through a global * stack list. Each client contains a bit array to indicate the tags of a * client. * * Keys and tagging rules are organized as arrays and defined in config.h. * * To understand everything else, start reading main(). */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef XINERAMA #include #endif /* macros */ #define ADJUSTBORDER(C, BW) if((C)->bw != (BW)) XSetWindowBorder(dpy, (C)->win, (BW)); #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask) #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask)) #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH)) #define ISVISIBLE(x) (x->tags & tagset[seltags]) #define LENGTH(x) (sizeof x / sizeof x[0]) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAXTAGLEN 16 #define MOUSEMASK (BUTTONMASK|PointerMotionMask) #define WIDTH(x) ((x)->w + 2 * (x)->bw) #define HEIGHT(x) ((x)->h + 2 * (x)->bw) #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1)) #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height) /* enums */ enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */ enum { ColBorder, ColFG, ColBG, ColLast }; /* color */ enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */ enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */ enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkClientWin, ClkRootWin, ClkLast }; /* clicks */ typedef union { int i; unsigned int ui; float f; 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 Client Client; struct Client { char name[256]; float mina, maxa; int x, y, w, h; int basew, baseh, incw, inch, maxw, maxh, minw, minh; int bw, oldbw; unsigned int tags; Bool isfixed, isfloating, isurgent; Client *next; Client *snext; Window win; }; typedef struct { int x, y, w, h; unsigned long norm[ColLast]; unsigned long sel[ColLast]; Drawable drawable; GC gc; struct { int ascent; int descent; int height; XFontSet set; XFontStruct *xfont; } font; } DC; /* draw context */ typedef struct { unsigned int mod; KeySym keysym; void (*func)(const Arg *); const Arg arg; } Key; typedef struct { const char *symbol; void (*arrange)(void); } Layout; typedef struct { const char *clas
package svc // import "github.com/getwtxt/getwtxt/svc"

import (
	"bytes"
	"html/template"
	"io/ioutil"
	"os"
	"reflect"
	"testing"

	"github.com/getwtxt/registry"
)

func Test_initTemplates(t *testing.T) {
	initTestConf()

	tmpls = initTemplates()
	manual := template.Must(template.ParseFiles("../assets/tmpl/index.html"))

	t.Run("Checking if Deeply Equal", func(t *testing.T) {
		if !reflect.DeepEqual(tmpls, manual) {
			t.Errorf("Returned template doesn't match manual parse\n")
		}
	})
}

func Test_cacheUpdate(t *testing.T) {
	initTestConf()
	mockRegistry()
	killStatuses()

	cacheUpdate()
	urls := "https://gbmor.dev/twtxt.txt"
	newStatus := twtxtCache.Users[urls].Status

	t.Run("Checking for any data", func(t *testing.T) {

		if len(newStatus) <= 1 {
			t.Errorf("Statuses weren't pulled\n")
		}
	})
	t.Run("Checking if Deeply Equal", func(t *testing.T) {
		t.Logf("This test is failing during CI because the statuses obtained from the registry seem to be in a random order.")
		t.Logf("The statuses obtained manually are in the expected order. However, strangely, on my own machine,")
		t.Logf("both are in the expected order. I need to do some more investigation before I can correct the test")
		t.Logf("or correct the library functions.")
		t.SkipNow()
		raw, _, _ := registry.GetTwtxt(urls)
		manual, _ := registry.ParseUserTwtxt(raw, "gbmor", urls)

		if !reflect.DeepEqual(newStatus, manual) {
			t.Errorf("Updated statuses don't match a manual fetch\n%#v\n%#v\n", newStatus, manual)
		}
	})
}

func Benchmark_cacheUpdate(b *testing.B) {
	initTestConf()
	mockRegistry()
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		cacheUpdate()

		// make sure it's pulling new statuses
		// half the time so we get a good idea
		// of its performance in both cases.
		if i > (b.N/2) && i%2 == 0 {
			b.StopTimer()
			killStatuses()
			b.StartTimer()
		}
	}
}

func Test_pingAssets(t *testing.T) {
	initTestConf()
	tmpls = initTemplates()

	b := []byte{}
	buf := bytes.NewBuffer(b)

	cssStat, _ := os.Stat("../assets/style.css")
	css, _ := ioutil.ReadFile("../assets/style.css")
	indStat, _ := os.Stat("../assets/tmpl/index.html")
	tmpls.ExecuteTemplate(buf, "index.html", confObj.Instance)
	ind := buf.Bytes()

	pingAssets()

	t.Run("Checking if index Deeply Equal", func(t *testing.T) {
		if !reflect.DeepEqual(staticCache.index, ind) {
			t.Errorf("Index not equivalent to manual parse\n")
		}
	})
	t.Run("Checking index Mod Times", func(t *testing.T) {
		if indStat.ModTime() != staticCache.indexMod {
			t.Errorf("Index mod time mismatch\n")
		}
	})
	t.Run("Checking if CSS Deeply Equal", func(t *testing.T) {
		if !reflect.DeepEqual(staticCache.css, css) {
			t.Errorf("CSS not equivalent to manual read\n")
		}
	})
	t.Run("Checking CSS Mod Times", func(t *testing.T) {
		if cssStat.ModTime() != staticCache.cssMod {
			t.Errorf("CSS mod time mismatch\n")
		}
	})

}

func Benchmark_pingAssets(b *testing.B) {
	initTestConf()
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		pingAssets()

		// We'll only have to reload the cache occasionally,
		// so only start with an empty staticCache 25% of
		// the time.
		if float64(i) > (float64(b.N) * .75) {
			b.StopTimer()
			staticCache = &staticAssets{}
			b.StartTimer()
		}
	}
}
} void togglebar(const Arg *arg) { showbar = !showbar; updategeom(); updatebar(); arrange(); } void togglefloating(const Arg *arg) { if(!sel) return; sel->isfloating = !sel->isfloating || sel->isfixed; if(sel->isfloating) resize(sel, sel->x, sel->y, sel->w, sel->h, True); arrange(); } void toggletag(const Arg *arg) { unsigned int mask; if (!sel) return; mask = sel->tags ^ (arg->ui & TAGMASK); if(sel && mask) { sel->tags = mask; arrange(); } } void toggleview(const Arg *arg) { unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK); if(mask) { tagset[seltags] = mask; arrange(); } } void unmanage(Client *c) { XWindowChanges wc; wc.border_width = c->oldbw; /* The server grab construct avoids race conditions. */ XGrabServer(dpy); XSetErrorHandler(xerrordummy); XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */ detach(c); detachstack(c); if(sel == c) focus(NULL); XUngrabButton(dpy, AnyButton, AnyModifier, c->win); setclientstate(c, WithdrawnState); free(c); XSync(dpy, False); XSetErrorHandler(xerror); XUngrabServer(dpy); arrange(); } void unmapnotify(XEvent *e) { Client *c; XUnmapEvent *ev = &e->xunmap; if((c = getclient(ev->window))) unmanage(c); } void updatebar(void) { if(dc.drawable != 0) XFreePixmap(dpy, dc.drawable); dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen)); XMoveResizeWindow(dpy, barwin, wx, by, ww, bh); } void updategeom(void) { #ifdef XINERAMA int n, i = 0; XineramaScreenInfo *info = NULL; /* window area geometry */ if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) { if(n > 1) { int di, x, y; unsigned int dui; Window dummy; if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui)) for(i = 0; i < n; i++) if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height)) break; } wx = info[i].x_org; wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org; ww = info[i].width; wh = showbar ? info[i].height - bh : info[i].height; XFree(info); } else #endif { wx = sx; wy = showbar && topbar ? sy + bh : sy; ww = sw; wh = showbar ? sh - bh : sh; } /* bar position */ by = showbar ? (topbar ? wy - bh : wy + wh) : -bh; } 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 / (float)size.min_aspect.x; c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y; } else c->maxa = c->mina = 0.0; c->isfixed = (c->maxw && c->minw && c->maxh && c->minh && c->maxw == c->minw && c->maxh == c->minh); } void updatetitle(Client *c) { if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name)) gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name); } void updatestatus() { if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext))) strcpy(stext, "dwm-"VERSION); drawbar(); } void updatewmhints(Client *c) { XWMHints *wmh; if((wmh = XGetWMHints(dpy, c->win))) { if(c == sel && wmh->flags & XUrgencyHint) { wmh->flags &= ~XUrgencyHint; XSetWMHints(dpy, c->win, wmh); } else c->isurgent = (wmh->flags & XUrgencyHint) ? True : False; XFree(wmh); } } void view(const Arg *arg) { if((arg->ui & TAGMASK) == tagset[seltags]) return; seltags ^= 1; /* toggle sel tagset */ if(arg->ui & TAGMASK) tagset[seltags] = arg->ui & TAGMASK; arrange(); } /* There's no way to check accesses to destroyed windows, thus those cases are * ignored (especially on UnmapNotify's). Other types of errors call Xlibs * default error handler, which may call exit. */ int xerror(Display *dpy, XErrorEvent *ee) { if(ee->error_code == BadWindow || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch) || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable) || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable) || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable) || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch) || (ee->request_code == X_GrabButton && ee->error_code == BadAccess) || (ee->request_code == X_GrabKey && ee->error_code == BadAccess) || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable)) return 0; fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n", ee->request_code, ee->error_code); return xerrorxlib(dpy, ee); /* may call exit */ } int xerrordummy(Display *dpy, XErrorEvent *ee) { return 0; } /* Startup Error handler to check if another window manager * is already running. */ int xerrorstart(Display *dpy, XErrorEvent *ee) { otherwm = True; return -1; } void zoom(const Arg *arg) { Client *c = sel; if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating)) return; if(c == nexttiled(clients)) if(!c || !(c = nexttiled(c->next))) return; detach(c); attach(c); focus(c); arrange(); } int main(int argc, char *argv[]) { if(argc == 2 && !strcmp("-v", argv[1])) die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n"); else if(argc != 1) die("usage: dwm [-v]\n"); if(!setlocale(LC_CTYPE, "") || !XSupportsLocale()) fprintf(stderr, "warning: no locale support\n"); if(!(dpy = XOpenDisplay(0))) die("dwm: cannot open display\n"); checkotherwm(); setup(); scan(); run(); cleanup(); XCloseDisplay(dpy); return 0; }