wm/src/wm.c

768 lines
22 KiB
C

/*
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 <http://www.gnu.org/licenses/>.
*/
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <X11/X.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/Xinerama.h>
#include <X11/Xft/Xft.h>
#include "wm.h"
#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_len = count;
wm->monitors = malloc(count * sizeof(Monitor));
assert(wm->monitors);
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));
assert(wm->monitors[i].workspaces);
wm->monitors[i].selected_ws = 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->selected_monitor = &wm->monitors[0];
DEBUG_PRINT("smon width: %d\n", wm->selected_monitor->info.width);
XFree(xsi);
}
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->selected_monitor->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)
for (size_t i = 0; i < nitems_ret; i++) {
char *ret_str = XGetAtomName(wm->display, ((Atom*)prop_ret)[i]);
printf("property return str: %s\n", ret_str);
if (strcmp(ret_str, "_NET_WM_WINDOW_TYPE_DOCK") == 0) {
DEBUG_PRINT("%s", __func__)
DEBUG_PRINT("returning true\n")
XFree(ret_str);
return true;
}
XFree(ret_str);
}
XFree(prop_ret);
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 = ws->focused_node ? ws->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;
focused_node->client = NULL;
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->selected_monitor->wscount)
return;
int wscc = 0;
Client *c;
DEBUG_PRINT("switching to ws %ld, clients:", ws);
wm_treenode_print(wm->selected_monitor->workspaces[ws].tree);
NodeArray *current_ws_clients = wm_treenode_find_client_nodes(CURRENT_WS(wm).tree);
for (size_t i = 0; i < current_ws_clients->size; i++) {
c = ((TreeNode**)current_ws_clients->nodes)[i]->client;
assert(c);
if (c->ws->index == wm->selected_monitor->selected_ws) {
DEBUG_PRINT("wm_switch_ws hide client selws: %ld\n", c->ws->index)
wm_client_hide(wm, c);
}
}
wm->selected_monitor->selected_ws = ws;
wm_client_set_atom(wm, &wm-> root, "_NET_CURRENT_DESKTOP",
(unsigned char*) &(ws), XA_CARDINAL, 1);
NodeArray *switch_ws_clients = wm_treenode_find_client_nodes(CURRENT_WS(wm).tree);
for (size_t i = 0; i < switch_ws_clients->size; i++) {
c = ((TreeNode**)switch_ws_clients->nodes)[i]->client;
if (c->ws->index == wm->selected_monitor->selected_ws) {
wscc++;
wm_client_show(wm, c);
}
}
DEBUG_PRINT("wm_switch_ws focused ws client count: %d\n", wscc);
if (CURRENT_WS(wm).focused_node)
wm_client_focus(wm, CURRENT_WS(wm).focused_node->client);
wm_layout(wm, wm->selected_monitor);
wm_nodearray_free(current_ws_clients);
wm_nodearray_free(switch_ws_clients);
}
void wm_move_client_ws(Wm *wm, int ws)
{
if (ws > wm->selected_monitor->wscount)
return;
TreeNode *focused_node = wm_treenode_ptr_find_focused_client_node(CURRENT_WS(wm).tree);
Client *moved_client = focused_node->client;
wm_ws_tree_insert_client(wm, &wm->selected_monitor->workspaces[ws], moved_client);
wm_client_hide(wm, moved_client);
moved_client->ws = &wm->selected_monitor->workspaces[ws];
wm_client_set_atom(wm, moved_client, "_NET_WM_DESKTOP",
(unsigned char*)&moved_client->ws->index, XA_CARDINAL,
CURRENT_WS(wm).index);
wm_treenode_remove_node(wm, CURRENT_WS(wm).tree, focused_node);
CURRENT_WS(wm).focused_node = NULL;
char *str = wm_treenode_to_str(wm->selected_monitor->workspaces[ws].tree);
DEBUG_PRINT("move target ws tree: %s\n", str);
wm_layout(wm, wm->selected_monitor);
}
void wm_layout(Wm *wm, Monitor *m)
{
RETURN_IF_NULL(m);
size_t i;
DEBUG_PRINT("%s\n", __func__);
Workspace *ws = &m->workspaces[m->selected_ws];
NodeArray *clients = wm_treenode_find_client_nodes(ws->tree);
if (clients->size == 0)
goto ret;
for (i = 0; i < clients->size; i++) {
TreeNode *node = clients->nodes[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->frame, value_mask, &xwc);
if (wm->config.show_titlebar) {
xwc.y = wm->titlebar_font->height * 2;
xwc.x = 0;
xwc.height -= wm->titlebar_font->height * 2;
} else {
xwc.y = 0;
xwc.x = 0;
}
XConfigureWindow(wm->display, client->window, value_mask, &xwc);
wm_client_draw_frame(wm, client);
}
XEvent e;
XSync(wm->display, False);
while(XCheckMaskEvent(wm->display, EnterWindowMask, &e));
wm_monitor_clients_border(wm, m);
ret:
wm_nodearray_free(clients);
}
void wm_mainloop(Wm *wm)
{
struct sockaddr s;
socklen_t t = 108;
getsockname(wm->socket_fd, &s, &t);
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)
{
DEBUG_PRINT("wm_init\n");
DEBUG_PRINT("pid: %ld\n", getpid());
XSetWindowAttributes xa;
// 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);
wm_logfile_init(wm->config.log_path);
wm->log_entries = wm_read_log(wm->config.log_path);
wm->display = wm_connect_display();
wm_monitors_open_all(wm, wm->display);
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(wm->display, 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);
wm_grab_keys(wm);
//XSetErrorHandler(&wm_other_wm_handler);
// if (wm->other_wm) {
// printf("wm: Detected other window manager. Exiting.\n");
// exit(1);
// }
// initialize titlebar font
int screen = DefaultScreen(wm->display);
wm->titlebar_font = XftFontOpenName(wm->display, screen, wm->config.titlebar_font);
if (!wm->titlebar_font) {
fprintf(stderr, "wm: could not open font \"%s\". exiting.\n",
wm->config.titlebar_font);
exit(1);
}
// initialize titlebar colors
Visual *visual = DefaultVisual(wm->display, screen);
Colormap cmap = DefaultColormap(wm->display, screen);
int ret = XftColorAllocName(wm->display, visual, cmap, wm->config.titlebar_color,
&wm->titlebar_color);
if (ret == 0) {
fprintf(stderr, "wm: could not allocate color \"%s\". exiting.\n",
wm->config.titlebar_color);
exit(1);
}
ret = XftColorAllocName(wm->display, visual, cmap, wm->config.titlebar_focused_color,
&wm->titlebar_focused_color);
if (ret == 0) {
fprintf(stderr, "wm: could not allocate color \"%s\". exiting.\n",
wm->config.titlebar_focused_color);
exit(1);
}
ret = XftColorAllocName(wm->display, visual, cmap, wm->config.titlebar_text_color,
&wm->titlebar_text_color);
if (ret == 0) {
fprintf(stderr, "wm: could not allocate color \"%s\". exiting.\n",
wm->config.titlebar_text_color);
exit(1);
}
wm_set_supported_atoms(wm);
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__);
XUngrabKey(wm->display, AnyKey, AnyModifier, wm->root.window);
// TODO: perhaps add created clients to a PtrArray field in workspace.
// would reduce number of calls to wm_treenode_find_client_nodes_ptr
for (size_t i = 0; i < wm->monitors_len; i++) {
for (size_t j = 0; j < wm->monitors[i].wscount; j++) {
NodeArray *clients = wm_treenode_find_client_nodes(
wm->monitors[i].workspaces[j].tree);
for (size_t k = 0; k < clients->size; k++) {
Client *c = ((TreeNode*)clients->nodes[k])->client;
XKillClient(wm->display, c->window);
DEBUG_PRINT("freeing client %p\n", (void*)c);
wm_client_free(wm, c);
}
wm_nodearray_free(clients);
}
}
// free titlebar font and colors
int screen = DefaultScreen(wm->display);
Visual *visual = DefaultVisual(wm->display, screen);
Colormap cmap = DefaultColormap(wm->display, screen);
XftColorFree(wm->display, visual, cmap, &wm->titlebar_color);
XftColorFree(wm->display, visual, cmap, &wm->titlebar_focused_color);
XftColorFree(wm->display, visual, cmap, &wm->titlebar_text_color);
XftFontClose(wm->display, wm->titlebar_font);
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)
WM_LOG_STATE_START(wm);
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);
}
wm->log_after_maprequest = true;
}
void wm_kb_exit(Wm* wm, Arg *args)
{
wm->running = false;
}
void wm_kb_kill(Wm *wm, Arg *args)
{
WM_LOG_STATE_START(wm);
Client *c;
c = wm_client_get_focused(wm);
RETURN_IF_NULL(c)
wm_client_kill(wm, c);
WM_LOG_STATE_END(wm);
}
void wm_kb_switch_ws(Wm *wm, Arg *args)
{
RETURN_IF_NULL(args)
WM_LOG_STATE_START(wm);
wm_switch_ws(wm, args->i);
WM_LOG_STATE_END(wm);
}
void wm_kb_move_client_ws(Wm *wm, Arg *args)
{
RETURN_IF_NULL(args)
WM_LOG_STATE_START(wm);
wm_move_client_ws(wm, args->i);
WM_LOG_STATE_END(wm);
}
void wm_kb_focus_dir(Wm *wm, Arg *args)
{
Client *c;
RETURN_IF_NULL(args)
WM_LOG_STATE_START(wm);
c = wm_client_get_focused(wm);
wm_client_focus_dir(wm, c, args->i);
WM_LOG_STATE_END(wm);
}
void wm_kb_move_dir(Wm *wm, Arg *args)
{
Client *c;
RETURN_IF_NULL(args)
WM_LOG_STATE_START(wm);
c = wm_client_get_focused(wm);
wm_client_swap_dir(wm, c, args->i);
WM_LOG_STATE_END(wm);
}
void wm_kb_switch_split_mode(Wm *wm, Arg *args)
{
RETURN_IF_NULL(args)
WM_LOG_STATE_START(wm);
wm->selected_monitor->workspaces[wm->selected_monitor->selected_ws].split = args->i;
WM_LOG_STATE_END(wm);
}
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 *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]);
}
}
}
}