/*
The GPLv3 License (GPLv3)
Copyright (c) 2022 Akos Horvath
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
*/
#include "wm.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "config.h"
#include "handler.h"
#include "client.h"
#include "util.h"
Monitor wm_monitor_open(Display *d, XineramaScreenInfo info)
{
Monitor m = {
.display = d,
.info = info
};
return m;
}
void wm_monitors_open_all(Wm *wm, Display *d)
{
DEBUG_PRINT("wm_monitors_open_all\n");
int count;
XineramaScreenInfo *xsi = XineramaQueryScreens(d, &count);
if (!xsi) {
printf("wm: Could not open display. Exiting.\n");
exit(1);
}
wm->monitors = malloc(count * sizeof(Monitor));
for (int i = 0; i < count; i++) {
wm->monitors[i] = wm_monitor_open(d, xsi[i]);
//TODO: cfg
wm->monitors[i].wscount = 9;
wm->monitors[i].workspaces = calloc(wm->monitors[i].wscount, sizeof(Workspace));
wm->monitors[i].selws = 0;
for (size_t j = 0; j < wm->monitors[i].wscount; j++) {
Workspace *ws = &wm->monitors[i].workspaces[j];
ws->index = j;
ws->monitor = &wm->monitors[i];
// TODO config
snprintf(ws->name, WM_WS_NAME_LEN, "%ld", j);
ws->tree = wm_treenode_new(NODE_CLIENT, NULL);
}
//wm->monitors[i].clients = &wm->root;
wm->monitors[i].clients = NULL;
}
wm->smon = &wm->monitors[0];
// wm->smon->clients = &wm->root;
DEBUG_PRINT("smon width: %d\n", wm->smon->info.width);
}
Display* wm_connect_display()
{
Display *d;
if (!(d = XOpenDisplay(NULL)))
{
printf("wm: Could not open display. Exiting.\n");
exit(1);
}
return d;
}
void wm_set_supported_atoms(Wm *wm)
{
XChangeProperty(wm->display, wm->root.window,
XInternAtom(wm->display, "_NET_NUMBER_OF_DESKTOPS", False), XA_CARDINAL,
32, PropModeReplace, (unsigned char *) &wm->smon->wscount, 1);
char *desktop_names[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9"};
wm_client_set_atom(wm, &wm->root, "_NET_DESKTOP_NAMES",
(unsigned char*) desktop_names, XA_STRING, 9);
Atom wm_supp[] = {
XInternAtom(wm->display, "_NET_NUMBER_OF_DESKTOPS", False),
XInternAtom(wm->display, "_NET_DESKTOP_GEOMETRY", False),
XInternAtom(wm->display, "_NET_DESKTOP_VIEWPORT", False),
XInternAtom(wm->display, "_NET_CURRENT_DESKTOP", False),
XInternAtom(wm->display, "_NET_ACTIVE_WINDOW", False),
XInternAtom(wm->display, "_NET_DESKTOP_NAMES", False),
};
XChangeProperty(wm->display, wm->root.window,
XInternAtom(wm->display, "_NET_SUPPORTED", False), XA_ATOM, 32,
PropModeReplace, (unsigned char *) &wm_supp, sizeof(wm_supp)/sizeof(long));
}
bool wm_window_is_dock(Wm *wm, Window w)
{
// TODO: get atom new function
unsigned char *prop_ret;
Atom atom_ret;
int format_ret;
unsigned long nitems_ret;
unsigned long bytes_remain_ret;
int ret;
ret = XGetWindowProperty(wm->display, w,
XInternAtom(wm->display, "_NET_WM_WINDOW_TYPE", False), 0, (~0L), False,
AnyPropertyType, &atom_ret,
&format_ret, &nitems_ret, &bytes_remain_ret, &prop_ret);
if (ret != Success || nitems_ret == 0) {
fprintf(stderr, "wm: XGetWindowProperty failed\n");
return false;
}
DEBUG_PRINT("XGetWindowProperty return values, window %d:\n", (int)w);
// DEBUG_PRINT("actual atom return: %s\n", XGetAtomName(wm->display, atom_ret));
DEBUG_PRINT("actual format return: %d\n", format_ret)
DEBUG_PRINT("actual number of items return: %ld\n", nitems_ret)
DEBUG_PRINT("bytes remaining: %ld\n", nitems_ret)
//DEBUG_PRINT("property return dec: %d\n", prop_ret)
for (size_t i = 0; i < nitems_ret; i++) {
printf("property return str: %s\n",
XGetAtomName(wm->display, ((Atom*)prop_ret)[i]));
if (strcmp(XGetAtomName(wm->display, ((Atom*)prop_ret)[i]),
"_NET_WM_WINDOW_TYPE_DOCK") == 0) {
DEBUG_PRINT("%s", __func__)
DEBUG_PRINT("returning true\n")
return true;
}
}
return false;
}
NodeType wm_split_to_nodetype(SplitMode mode)
{
switch (mode) {
case SPLIT_VERTICAL:
return NODE_VERTICAL;
case SPLIT_HORIZ:
return NODE_HORIZONTAL;
case SPLIT_TAB:
return NODE_TAB;
default:
fprintf(stderr, "wm: unhandled split mode %d in %s, exiting.\n",
mode, __func__);
abort();
}
}
void wm_ws_tree_insert_client(Wm *wm, Workspace *ws, Client *client)
{
DEBUG_PRINT("%s\n", __func__);
int dock_y = 0;
if (wm->dock != ULONG_MAX) {
XWindowAttributes x;
XGetWindowAttributes(wm->display, wm->dock, &x);
dock_y = x.height;
}
if (wm_treenode_is_empty(&ws->tree) && ws->tree.client == NULL) {
ws->tree.type = NODE_CLIENT;
ws->tree.client = client;
ws->tree.pos = (Rect) {
.x = wm->config.border_width, .y = wm->config.border_width + dock_y ,
.w = ws->monitor->info.width - wm->config.border_width*2,
.h = ws->monitor->info.height - wm->config.border_width*2 - dock_y,
};
return;
}
TreeNode *focused_node = wm_treenode_ptr_find_focused_client_node(&ws->tree);
assert(focused_node);
Client *old_client = focused_node->client;
focused_node->type = wm_split_to_nodetype(ws->split);
TreeNode child1 = wm_treenode_new(NODE_CLIENT, focused_node);
TreeNode child2 = wm_treenode_new(NODE_CLIENT, focused_node);
wm_treenode_split_space(focused_node, &child1.pos, &child2.pos);
child1.client = old_client;
child2.client = client;
wm_nodearray_push(&focused_node->children, child1);
wm_nodearray_push(&focused_node->children, child2);
}
void wm_switch_ws(Wm *wm, size_t ws)
{
if (ws > wm->smon->wscount)
return;
int wscc = 0;
Client *c;
PtrArray current_ws_clients = wm_treenode_find_client_nodes_ptr(
&wm->smon->workspaces[wm->smon->selws].tree);
for (size_t i = 0; i < current_ws_clients.size; i++) {
c = ((TreeNode**)current_ws_clients.ptrs)[i]->client;
assert(c);
if (c->ws->index == wm->smon->selws) {
DEBUG_PRINT("wm_switch_ws hide client selws: %ld\n", c->ws->index)
wm_client_hide(wm, c);
}
}
wm->smon->selws = ws;
wm_client_set_atom(wm, &wm-> root, "_NET_CURRENT_DESKTOP",
(unsigned char*) &(ws), XA_CARDINAL, 1);
PtrArray switch_ws_clients = wm_treenode_find_client_nodes_ptr(
&wm->smon->workspaces[wm->smon->selws].tree);
for (size_t i = 0; i < switch_ws_clients.size; i++) {
c = ((TreeNode**)switch_ws_clients.ptrs)[i]->client;
if (c->ws->index == wm->smon->selws) {
wscc++;
wm_client_show(wm, c);
}
}
DEBUG_PRINT("wm_switch_ws focused ws client count: %d\n", wscc);
wm_ptrarray_free(¤t_ws_clients);
wm_ptrarray_free(&switch_ws_clients);
}
// TODO maybe x,y is not 0, because of bar
void wm_mstack(Wm *wm, Monitor *m)
{
DEBUG_PRINT("%s\n", __func__)
RETURN_IF_NULL(m);
Client *c;
XWindowChanges ch;
int cc_sws = 0;
int n = 0;
int sx = 0;
int sy = 0;
XEvent e;
unsigned int value_mask = CWX | CWY | CWWidth | CWHeight;
// TODO: function
// FIXME: &root probably wrong
if (wm->dock != ULONG_MAX) {
XWindowAttributes x;
XGetWindowAttributes(wm->display, wm->dock, &x);
sx = x.x;
sy = x.y+x.height;
DEBUG_PRINT("%s dock sx x: %d y: %d\n", __func__, sx, sy)
}
for (c = m->clients; c; c = c->next) {
if (c->ws->index == m->selws && c != &wm->root && !c->is_floating) {
cc_sws++;
}
}
DEBUG_PRINT("mstack cc_sws: %d\n", cc_sws)
if (cc_sws <= 0) {
DEBUG_PRINT("mstack cc_sws <= 0, returning\n")
return;
}
// dynamic
if (cc_sws == 1) {
for (c = m->clients; c; c = c->next) {
if (c->ws->index == m->selws && c != &wm->root)
break;
}
c->x = 0;
c->y = sy;
c->w = wm->smon->info.width-wm->config.border_width*2;
c->h = (wm->smon->info.height-wm->config.border_width*2)-sy;
ch = wm_client_to_xwchanges(c);
DEBUG_PRINT("mstack client: %p\n", c);
// XGetWMName(wm->display, c->window, &xt);
DEBUG_PRINT("mstack window id: %ld\n", c->window);
// DEBUG_PRINT("mstack wm_name: %s\n", xt.value)
// DEBUG_PRINT("mstack client width: %d\n", ch.width)
// DEBUG_PRINT("mstack client height: %d\n", ch.height)
XConfigureWindow(wm->display, c->window, value_mask, &ch);
wm_client_show(wm, c);
wm_client_focus(wm, c);
}
else {
// FIXME not working with dock
for (c = m->clients; c; c = c->next) {
if (c->ws->index == m->selws && c->window != wm->root.window && !c->is_floating) {
if (n == 0) {
c->x = 0;
c->y = sy;
c->w = m->info.width*wm->config.ms_p-wm->config.border_width*2;
c->h = (m->info.height-wm->config.border_width*2)-sy;
} else {
c->x = (m->info.width*wm->config.ms_p);
c->y = ((n-1)*m->info.height/(cc_sws-1))+sy;
c->w = (m->info.width - m->info.width*wm->config.ms_p) -
wm->config.border_width*2;
c->h = ((m->info.height)/(cc_sws-1)-wm->config.border_width*2);
}
n++;
ch = wm_client_to_xwchanges(c);
// TODO store wm name when client is created
// FIXME vv RUNTIME MALLOC ABORT vv
//XGetWMName(wm->display, c->window, &xt);
DEBUG_PRINT("mstack client: %p\n", c);
DEBUG_PRINT("mstack window id: %ld\n", c->window);
// DEBUG_PRINT("mstack wm_name: %s\n", xt.value)
// DEBUG_PRINT("mstack client x: %d ", ch.x)
// DEBUG_PRINT("y: %d\n", ch.y)
// DEBUG_PRINT("mstack client width: %d ", ch.width)
// DEBUG_PRINT("height: %d\n", ch.height)
XConfigureWindow(wm->display, c->window, value_mask, &ch);
wm_client_show(wm, c);
DEBUG_PRINT("%s %d. client next: %p\n", __func__, n, c->next)
if (c->next == NULL)
{
wm_client_focus(wm, c);
}
}
}
}
DEBUG_PRINT("%s end\n", __func__)
XSync(wm->display, False);
while(XCheckMaskEvent(wm->display, EnterWindowMask, &e));
wm_monitor_clients_border(wm, m);
}
void wm_layout(Wm *wm, Monitor *m)
{
RETURN_IF_NULL(m);
size_t i;
DEBUG_PRINT("%s\n", __func__);
Workspace *ws = &m->workspaces[m->selws];
PtrArray clients = wm_treenode_find_client_nodes_ptr(&ws->tree);
if (clients.size == 0)
goto ret;
for (i = 0; i < clients.size; i++) {
TreeNode *node = clients.ptrs[i];
Client *client = node->client;
assert(client);
client->x = node->pos.x;
client->y = node->pos.y;
client->w = node->pos.w;
client->h = node->pos.h;
unsigned int value_mask = CWX | CWY | CWWidth | CWHeight;
XWindowChanges xwc = wm_client_to_xwchanges((client));
XConfigureWindow(wm->display, client->window, value_mask, &xwc);
wm_client_show(wm, client);
}
wm_client_focus(wm, ((TreeNode*)clients.ptrs[0])->client);
XEvent e;
XSync(wm->display, False);
while(XCheckMaskEvent(wm->display, EnterWindowMask, &e));
wm_monitor_clients_border(wm, m);
ret:
wm_ptrarray_free(&clients);
}
Client *wm_get_last_client(Wm *wm, Monitor m)
{
Client *c = m.clients;
if (c == NULL)
return NULL;
while (c->next != NULL)
c = c->next;
return c;
}
void wm_mainloop(Wm *wm)
{
// int s = DefaultScreen(wm->display);
// Window w = XCreateSimpleWindow(wm->display, root.window, 10, 10, 300, 300,
// 2, WhitePixel(wm->display, s), BlackPixel(wm->display, s));
// XSelectInput(wm->display, w, KeyPressMask | KeyReleaseMask);
// XMapWindow(wm->display, w);
struct sockaddr s;
socklen_t t = 108;
getsockname(wm->socket_fd, &s, &t);
// int accepted_socket;
// char *buffer;
// accepted_socket = accept(wm->socket_fd, &s, &t);
// if (accepted_socket == -1) {
// if (errno == EAGAIN || errno == EWOULDBLOCK) {
// // fprintf(stderr,
// // "wm: accept failed, no waiting connections are present\n");
// } else {
// fprintf(stderr, "wm: accept failed\n");
// }
// }
// else {
// DEBUG_PRINT("accept success\n")
// len = recv(accepted_socket, buffer, 100, 0);
// if (len != -1) {
// DEBUG_PRINT("got %d bytes:", len)
// for (int i = 0; i < len; i++)
// DEBUG_PRINT("%c", buffer[i])
// DEBUG_PRINT("\n")
// } else {
// fprintf(stderr, "wm: recv failed\n");
// fprintf(stderr, "errno: %d\n", errno);
// }
// }
while (wm->running) {
XEvent e;
XNextEvent(wm->display, &e);
switch (e.type) {
case CreateNotify:
wm_create_handler(wm, e.xcreatewindow);
break;
case DestroyNotify:
wm_destroy_handler(wm, e.xdestroywindow);
break;
case ReparentNotify:
wm_reparent_handler(e.xreparent);
break;
case ConfigureRequest:
wm_configure_handler(wm, e.xconfigurerequest);
break;
case KeyRelease:
wm_keyrelease_handler(e.xkey);
break;
case KeyPress:
wm_keypress_handler(wm, e.xkey);
break;
case MotionNotify:
wm_motion_handler(wm, e.xmotion);
break;
case FocusIn:
break;
case FocusOut:
break;
case EnterNotify:
DEBUG_PRINT("pointer entered window: %d\n",
(int)e.xcrossing.window);
if (wm->config.focus_on_motion)
wm_client_focus(wm, wm_client_find(wm, e.xcrossing.window));
break;
case LeaveNotify:
DEBUG_PRINT("pointer left window: %d\n",
(int)e.xcrossing.window);
break;
case ConfigureNotify:
DEBUG_PRINT("ConfigureNotify: %d\n", (int)e.xconfigure.window)
break;
case MapRequest:
DEBUG_PRINT("MapRequest: %d\n", (int)e.xmaprequest.window)
wm_maprequest_handler(wm, e.xmaprequest);
break;
default:
DEBUG_PRINT("default: %d\n", e.type);
}
}
}
void wm_init(Wm *wm)
{
XSetWindowAttributes xa;
Display *d;
signal(SIGINT, wm_sigint_handler);
wm->config = (Config) {0};
wm_cfg_init_def(&wm->config);
char path[PATH_MAX] = {0};
const char* file = "/.config/wm.conf";
strncat(path, getenv("HOME"), PATH_MAX - 1);
strncat(path, file, (PATH_MAX - strlen(file)) - 1);
ConfigFile configfile = {0};
wm_configfile_init(&configfile, path);
wm_configfile_read(&configfile, &wm->config);
DEBUG_PRINT("wm_init\n")
DEBUG_PRINT("pid: %ld\n", ((long)getpid()))
d = wm_connect_display();
wm->display = d;
wm_monitors_open_all(wm, d);
char *display_string = DisplayString(wm->display);
setenv("DISPLAY", display_string, 1);
// TODO: only testing
// wm_socket_init();
wm->root.window = XRootWindow(wm->display, DefaultScreen(wm->display));
DEBUG_PRINT("root window: %ld\n", wm->root.window);
XSync(d, false);
xa.event_mask = StructureNotifyMask | StructureNotifyMask |
SubstructureNotifyMask | SubstructureRedirectMask |
ButtonPressMask | PropertyChangeMask;
XChangeWindowAttributes(wm->display, wm->root.window, CWEventMask, &xa);
XSelectInput(wm->display, wm->root.window, xa.event_mask);
// DEBUG_PRINT("root window id: %d\n", (root.window))
// XUngrabKey(wm->display, AnyKey, AnyModifier, root.window);
wm_grab_keys(wm);
//XSetErrorHandler(&wm_other_wm_handler);
// if (wm->other_wm) {
// printf("wm: Detected other window manager. Exiting.\n");
// exit(1);
// }
wm_set_supported_atoms(wm);
//XSetErrorHandler(&wm_xerror_handler);
wm->dock = ULONG_MAX;
wm->running = true;
wm_mainloop(wm);
wm_configfile_free(&configfile);
wm_exit(wm);
}
void wm_exit(Wm *wm)
{
DEBUG_PRINT("%s\n", __func__);
Client *c;
XUngrabKey(wm->display, AnyKey, AnyModifier, wm->root.window);
// todo add clients to root client linked list
for (c = wm->smon->clients; c; c = c->next) {
XKillClient(wm->display, c->window);
}
for (c = wm->smon->clients; c; c = c->next) {
wm_client_free(wm, c);
}
DEBUG_PRINT("%s1\n", __func__);
XCloseDisplay(wm->display);
exit(EXIT_SUCCESS);
}
void wm_grab_keys(Wm *wm)
{
RETURN_IF_NULL(wm->config.keybinds)
Keybind k;
// from dwm
{
int i, j;
XModifierKeymap *modmap;
unsigned int numlockmask = 0;
modmap = XGetModifierMapping(wm->display);
for (i = 0; i < 8; i++)
for (j = 0; j < modmap->max_keypermod; j++)
if (modmap->modifiermap[i * modmap->max_keypermod + j]
== XKeysymToKeycode(wm->display, XK_Num_Lock))
numlockmask = (1 << i);
XFreeModifiermap(modmap);
}
// from dwm
unsigned int modifiers[] = { 0, LockMask, 0|LockMask };
XUngrabKey(wm->display, AnyKey, AnyModifier, wm->root.window);
for (int i = 0; i < wm->config.kb_count; i++) {
k = wm->config.keybinds[i];
for (int j = 0; j < 3; j++)
XGrabKey(wm->display, XKeysymToKeycode(wm->display, k.keysym),
k.mask | modifiers[j], wm->root.window, True, GrabModeAsync,
GrabModeAsync);
}
}
void wm_kb_spawn(Wm *wm, Arg *args)
{
RETURN_IF_NULL(args)
RETURN_IF_NULL(args->sl)
DEBUG_PRINT("args sl 1: %s\n", args->sl[args->count-1])
DEBUG_PRINT("args sl 0: %s\n", args->sl[0])
DEBUG_PRINT("args count: %d\n", args->count)
if (args->sl[args->count-1] != NULL) {
fprintf(stderr, "%s recieved non null-terminated args. Returning\n",
__func__);
}
if (fork() == 0) {
if (wm->display)
close(ConnectionNumber(wm->display));
setsid();
execvp(args->sl[0], &(args->sl[1]));
exit(0);
}
}
void wm_kb_exit(Wm* wm, Arg *args)
{
wm->running = false;
}
void wm_kb_kill(Wm *wm, Arg *args)
{
Client *c;
c = wm_client_get_focused(wm);
RETURN_IF_NULL(c)
wm_client_kill(wm, c);
}
void wm_kb_switch_ws(Wm *wm, Arg *args)
{
RETURN_IF_NULL(args)
wm_switch_ws(wm, args->i);
}
void wm_kb_focus_dir(Wm *wm, Arg *args)
{
Client *c;
RETURN_IF_NULL(args)
c = wm_client_get_focused(wm);
wm_client_focus_dir(wm, c, args->i);
}
void wm_kb_switch_split_mode(Wm *wm, Arg *args)
{
RETURN_IF_NULL(args)
wm->smon->workspaces[wm->smon->selws].split = args->i;
}
struct sockaddr wm_socket_init(Wm *wm)
{
struct sockaddr_un sock_addr;
int ret;
ret = wm->socket_fd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0);
if (ret == -1) {
fprintf(stderr, "wm: could not create socket. Exiting.\n");
exit(EXIT_FAILURE);
}
sock_addr.sun_family = AF_UNIX;
snprintf(sock_addr.sun_path, sizeof(sock_addr.sun_path),
"/tmp/wm_socket_%c", DisplayString(wm->display)[1]);
ret = bind(wm->socket_fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr));
if (ret == -1) {
fprintf(stderr, "wm: could not bind to socket. Exiting.\n");
exit(EXIT_FAILURE);
}
ret = listen(wm->socket_fd, 512);
if (ret == -1) {
fprintf(stderr, "wm: could not listen to socket. Exiting.\n");
exit(EXIT_FAILURE);
}
}
void wm_socket_cleanup(Wm *wm)
{
struct sockaddr s;
socklen_t t = 108;
getsockname(wm->socket_fd, &s, &t);
DEBUG_PRINT("socket cleanup path: %s\n", s.sa_data)
remove(s.sa_data);
}
void wm_sigint_handler(Wm *wm, int signum)
{
wm_socket_cleanup(wm);
exit(1);
}
// TODO: maybe move some parts to wmc
void wm_settings_message_parse(Wm *wm, char *c, int len)
{
if (len <= 0)
return;
int op; /* 0 = set, 1 = get */
size_t i = 0;
char ret[50];
char *token;
char tokens[20][50];
char *settings[] = {"border-width", "border-color", "focused-border-color",
"msfact", "focus-on-motion"};
while((token = strtok(c, " ")) != NULL) {
DEBUG_PRINT("message_parse token: %s\n", token)
strncpy(tokens[i], token, 50);
}
if (strcmp(tokens[1], "set") == 0) {
op = 0;
} else if (strcmp(c, "get") == 0) {
op = 1;
} else {
return;
}
for (i = 0; i < sizeof(settings)/sizeof(char*); i++) {
if (strcmp(tokens[1], settings[i])) {
if (op == 1) {
// wm_settings_get(settings[i], &ret);
} else {
// wm_settings_set(settings[i]);
}
}
}
}