feat: introduce v2.0 abstraction layer with core types, backend interface, and plugin system

feat: add fade effects with API control and real-time event subscription
test: add API integration tests with isolated test environment and coverage reporting
build: update Makefile for recursive source finding, dynamic linking, and test targets
docs: document abstraction layer, fade effects, and API enhancements in README
This commit is contained in:
2026-02-07 13:04:52 +01:00
parent 877d3f302c
commit 6b143990bb
181 changed files with 20646 additions and 7198 deletions
+704 -344
View File
File diff suppressed because it is too large Load Diff
+1266 -3
View File
File diff suppressed because it is too large Load Diff
+5 -4
View File
@@ -16,10 +16,11 @@
#include <unistd.h>
#include <ctype.h>
#include <pwd.h>
#include <limits.h>
static AppLauncherState launcher_state = {0};
static char recent_file_path[512] = {0};
static char recent_file_path[PATH_MAX] = {0};
static void scan_desktop_dir(const char *dir);
static int parse_desktop_file(const char *path, AppEntry *entry);
@@ -42,7 +43,7 @@ void applauncher_init(void)
snprintf(recent_file_path, sizeof(recent_file_path),
"%s/.local/share/dwn/recent_apps", home);
char dir_path[512];
char dir_path[PATH_MAX];
snprintf(dir_path, sizeof(dir_path), "%s/.local/share/dwn", home);
mkdir(dir_path, 0755);
@@ -66,7 +67,7 @@ void applauncher_refresh(void)
const char *home = getenv("HOME");
if (home) {
char user_apps[512];
char user_apps[PATH_MAX];
snprintf(user_apps, sizeof(user_apps), "%s/.local/share/applications", home);
scan_desktop_dir(user_apps);
}
@@ -271,7 +272,7 @@ static void add_to_recent(const char *desktop_id)
static char *strip_field_codes(const char *exec)
{
static char result[512];
static char result[PATH_MAX];
size_t j = 0;
for (size_t i = 0; exec[i] && j < sizeof(result) - 1; i++) {
+206
View File
@@ -0,0 +1,206 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* Async Context Implementation - Per-Module Async State
*/
#include "threading.h"
#include "util.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/eventfd.h>
/* Full definition of AsyncContext implementation */
struct AsyncContextImpl {
char name[32];
ThreadPool *pool;
EventBus *event_bus;
Channel *completion_channel;
_Atomic int operation_count;
_Atomic int shutdown_requested;
pthread_mutex_t mutex;
int event_fd;
};
typedef struct {
struct AsyncContextImpl *ctx;
TaskFunc user_func;
void *user_data;
Future *future;
} AsyncWrapperData;
static void async_wrapper_func(void *data, atomic_int *cancelled)
{
AsyncWrapperData *wrap = data;
/* Execute user's function */
if (wrap->user_func) {
wrap->user_func(wrap->user_data, cancelled);
}
/* Signal completion via channel */
TaskHandle *task_ptr = dwn_malloc(sizeof(TaskHandle));
if (task_ptr) {
*task_ptr = (TaskHandle)wrap; /* Just use wrapper as identifier */
channel_try_send(wrap->ctx->completion_channel, task_ptr);
}
atomic_fetch_sub_explicit(&wrap->ctx->operation_count, 1, ATOMIC_RELAXED);
}
AsyncContext* async_context_create(const char *name)
{
struct AsyncContextImpl *ctx = dwn_malloc(sizeof(struct AsyncContextImpl));
if (!ctx) return NULL;
strncpy(ctx->name, name ? name : "unnamed", sizeof(ctx->name) - 1);
ctx->name[sizeof(ctx->name) - 1] = '\0';
ctx->pool = thread_pool_default();
ctx->event_bus = event_bus_default();
ctx->completion_channel = channel_create(64);
if (!ctx->completion_channel) {
dwn_free(ctx);
return NULL;
}
atomic_store_explicit(&ctx->operation_count, 0, ATOMIC_RELEASE);
atomic_store_explicit(&ctx->shutdown_requested, 0, ATOMIC_RELEASE);
if (pthread_mutex_init(&ctx->mutex, NULL) != 0) {
channel_destroy(ctx->completion_channel);
dwn_free(ctx);
return NULL;
}
/* We use the channel's eventfd for polling */
ctx->event_fd = -1; /* Will use channel's fd via async_get_poll_fd */
return (AsyncContext*)ctx;
}
void async_context_destroy(AsyncContext *ctx)
{
if (!ctx) return;
struct AsyncContextImpl *impl = (struct AsyncContextImpl*)ctx;
atomic_store_explicit(&impl->shutdown_requested, 1, ATOMIC_RELEASE);
/* Wait for operations to complete */
int timeout = 100; /* 10 seconds max wait */
while (atomic_load_explicit(&impl->operation_count, ATOMIC_ACQUIRE) > 0 && timeout > 0) {
usleep(100000); /* 100ms */
timeout--;
}
channel_close(impl->completion_channel);
channel_destroy(impl->completion_channel);
pthread_mutex_destroy(&impl->mutex);
dwn_free(impl);
}
TaskHandle async_submit(AsyncContext *ctx, TaskFunc func, void *user_data,
TaskPriority priority)
{
if (!ctx || !func) return NULL;
struct AsyncContextImpl *impl = (struct AsyncContextImpl*)ctx;
if (atomic_load_explicit(&impl->shutdown_requested, ATOMIC_ACQUIRE)) {
return NULL;
}
AsyncWrapperData *wrap = dwn_malloc(sizeof(AsyncWrapperData));
if (!wrap) return NULL;
wrap->ctx = impl;
wrap->user_func = func;
wrap->user_data = user_data;
wrap->future = NULL;
atomic_fetch_add_explicit(&impl->operation_count, 1, ATOMIC_RELAXED);
TaskHandle task = task_create_with_callback(
async_wrapper_func, wrap, priority,
NULL, NULL
);
if (!task || thread_pool_submit(thread_pool_default(), task) != THREAD_OK) {
atomic_fetch_sub_explicit(&impl->operation_count, 1, ATOMIC_RELAXED);
dwn_free(wrap);
return NULL;
}
return task;
}
Future* async_submit_future(AsyncContext *ctx, TaskFunc func, void *user_data,
TaskPriority priority)
{
if (!ctx || !func) return NULL;
struct AsyncContextImpl *impl = (struct AsyncContextImpl*)ctx;
Future *f = future_create();
if (!f) return NULL;
AsyncWrapperData *wrap = dwn_malloc(sizeof(AsyncWrapperData));
if (!wrap) {
future_destroy(f);
return NULL;
}
wrap->ctx = impl;
wrap->user_func = func;
wrap->user_data = user_data;
wrap->future = f;
atomic_fetch_add_explicit(&impl->operation_count, 1, ATOMIC_RELAXED);
TaskHandle task = task_create(async_wrapper_func, wrap, priority);
if (!task) {
atomic_fetch_sub_explicit(&impl->operation_count, 1, ATOMIC_RELAXED);
dwn_free(wrap);
future_destroy(f);
return NULL;
}
ThreadStatus status = thread_pool_submit(thread_pool_default(), task);
if (status != THREAD_OK) {
task_destroy(task);
atomic_fetch_sub_explicit(&impl->operation_count, 1, ATOMIC_RELAXED);
dwn_free(wrap);
future_destroy(f);
return NULL;
}
return f;
}
uint32_t async_poll(AsyncContext *ctx)
{
if (!ctx) return 0;
struct AsyncContextImpl *impl = (struct AsyncContextImpl*)ctx;
uint32_t processed = 0;
void *data;
while (channel_try_recv(impl->completion_channel, &data) == THREAD_OK) {
dwn_free(data);
processed++;
}
return processed;
}
int async_get_poll_fd(AsyncContext *ctx)
{
if (!ctx) return -1;
struct AsyncContextImpl *impl = (struct AsyncContextImpl*)ctx;
return impl->event_fd;
}
+27 -6
View File
@@ -202,22 +202,43 @@ void atoms_update_desktop_names(void)
return;
}
char names[MAX_WORKSPACES * 32];
int offset = 0;
/* Buffer needs to account for:
- MAX_WORKSPACES names
- Each name up to sizeof(Workspace.name) - 1 = 31 chars
- Plus null terminator for each name
- Plus 8 characters for numeric fallback (e.g., "9\0")
*/
char names[MAX_WORKSPACES * (32 + 1)];
size_t offset = 0;
size_t max_offset = sizeof(names);
for (int i = 0; i < MAX_WORKSPACES; i++) {
const char *name = dwn->workspaces[i].name;
size_t remaining = max_offset - offset;
if (remaining < 2) { /* Need at least room for one char + null */
break;
}
int written;
if (name[0] == '\0') {
offset += snprintf(names + offset, sizeof(names) - offset, "%d", i + 1);
written = snprintf(names + offset, remaining, "%d", i + 1);
} else {
offset += snprintf(names + offset, sizeof(names) - offset, "%s", name);
written = snprintf(names + offset, remaining, "%s", name);
}
if (written < 0 || (size_t)written >= remaining) {
/* Truncation or error - ensure null termination */
names[offset] = '\0';
offset++;
} else {
offset += (size_t)written + 1; /* Include null terminator */
}
names[offset++] = '\0';
}
XChangeProperty(dwn->display, dwn->root, ewmh.NET_DESKTOP_NAMES,
misc_atoms.UTF8_STRING, 8, PropModeReplace,
(unsigned char *)names, offset);
(unsigned char *)names, (int)offset);
}
void atoms_set_current_desktop(int desktop)
+3 -3
View File
@@ -110,7 +110,7 @@ static void scan_xdg_directory(const char *dir_path)
continue;
}
char exec_cmd[512];
char exec_cmd[PATH_MAX];
if (parse_desktop_file(full_path, exec_cmd, sizeof(exec_cmd)) == 0) {
LOG_INFO("Autostart: %s -> %s", entry->d_name, exec_cmd);
spawn_async(exec_cmd);
@@ -236,7 +236,7 @@ static int parse_desktop_file(const char *path, char *exec_cmd, size_t exec_size
}
if (access(try_exec, X_OK) != 0) {
char which_cmd[512];
char which_cmd[PATH_MAX];
snprintf(which_cmd, sizeof(which_cmd), "which %s >/dev/null 2>&1", try_exec);
if (system(which_cmd) != 0) {
exec_cmd[0] = '\0';
@@ -256,7 +256,7 @@ static void strip_exec_field_codes(char *exec)
return;
}
char result[512];
char result[PATH_MAX];
size_t j = 0;
for (size_t i = 0; exec[i] != '\0' && j < sizeof(result) - 1; i++) {
+806
View File
@@ -0,0 +1,806 @@
/*
* DWN - Desktop Window Manager
* X11 Backend Implementation
*/
#define _GNU_SOURCE
#include "backends/x11/x11_backend.h"
#include "core/wm_types.h"
#include "core/wm_string.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/cursorfont.h>
#include <X11/keysym.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/*==============================================================================
* X11 Backend State
*============================================================================*/
static struct {
Display *display;
int screen;
Window root;
bool initialized;
int fd;
/* Error handling */
int last_error;
XErrorHandler error_handler;
XIOErrorHandler io_error_handler;
/* Cursor cache */
Cursor cursor_cache[XC_num_glyphs];
bool cursor_loaded[XC_num_glyphs];
/* Atoms cache */
Atom atom_wm_protocols;
Atom atom_wm_delete_window;
Atom atom_wm_state;
Atom atom_wm_fullscreen;
Atom atom_wm_maximized_horz;
Atom atom_wm_maximized_vert;
Atom atom_net_wm_name;
Atom atom_utf8_string;
} x11_state = {0};
/*==============================================================================
* Error Handlers
*============================================================================*/
static int x11_error_handler(Display *dpy, XErrorEvent *ev) {
x11_state.last_error = ev->error_code;
char msg[256];
XGetErrorText(dpy, ev->error_code, msg, sizeof(msg));
fprintf(stderr, "X11 Error: %s (request %d, minor %d)\n",
msg, ev->request_code, ev->minor_code);
return 0;
}
static int x11_io_error_handler(Display *dpy) {
(void)dpy;
fprintf(stderr, "X11 IO Error: Connection to display lost\n");
x11_state.initialized = false;
return 0;
}
/*==============================================================================
* Backend Information
*============================================================================*/
static WmBackendInfo x11_get_info(void) {
return (WmBackendInfo){
.name = "x11",
.version = "1.0",
.description = "X11 Window System Backend",
.capabilities =
WM_BACKEND_CAP_WINDOWS |
WM_BACKEND_CAP_INPUT_EVENTS |
WM_BACKEND_CAP_MULTI_MONITOR |
WM_BACKEND_CAP_CLIPBOARD,
.supports_multiple_instances = false,
.requires_compositor = false
};
}
/*==============================================================================
* Lifecycle
*============================================================================*/
static bool x11_init(void *config) {
(void)config;
if (x11_state.initialized) return true;
XSetErrorHandler(x11_error_handler);
XSetIOErrorHandler(x11_io_error_handler);
return true;
}
static void x11_shutdown(void) {
if (!x11_state.initialized) return;
/* Free cached cursors */
for (int i = 0; i < XC_num_glyphs; i++) {
if (x11_state.cursor_loaded[i]) {
XFreeCursor(x11_state.display, x11_state.cursor_cache[i]);
}
}
x11_state.initialized = false;
}
static bool x11_is_initialized(void) {
return x11_state.initialized;
}
/*==============================================================================
* Connection
*============================================================================*/
static bool x11_connect(void) {
if (x11_state.display) return true;
x11_state.display = XOpenDisplay(NULL);
if (!x11_state.display) {
fprintf(stderr, "Failed to open X11 display\n");
return false;
}
x11_state.screen = DefaultScreen(x11_state.display);
x11_state.root = RootWindow(x11_state.display, x11_state.screen);
x11_state.fd = ConnectionNumber(x11_state.display);
x11_state.initialized = true;
/* Cache atoms */
x11_state.atom_wm_protocols = XInternAtom(x11_state.display, "WM_PROTOCOLS", False);
x11_state.atom_wm_delete_window = XInternAtom(x11_state.display, "WM_DELETE_WINDOW", False);
x11_state.atom_wm_state = XInternAtom(x11_state.display, "_NET_WM_STATE", False);
x11_state.atom_wm_fullscreen = XInternAtom(x11_state.display, "_NET_WM_STATE_FULLSCREEN", False);
x11_state.atom_wm_maximized_horz = XInternAtom(x11_state.display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
x11_state.atom_wm_maximized_vert = XInternAtom(x11_state.display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
x11_state.atom_net_wm_name = XInternAtom(x11_state.display, "_NET_WM_NAME", False);
x11_state.atom_utf8_string = XInternAtom(x11_state.display, "UTF8_STRING", False);
return true;
}
static void x11_disconnect(void) {
if (x11_state.display) {
XCloseDisplay(x11_state.display);
x11_state.display = NULL;
x11_state.initialized = false;
}
}
static bool x11_is_connected(void) {
return x11_state.display != NULL && x11_state.initialized;
}
static int x11_get_file_descriptor(void) {
return x11_state.fd;
}
static void x11_flush(void) {
if (x11_state.display) XFlush(x11_state.display);
}
static void x11_sync(void) {
if (x11_state.display) XSync(x11_state.display, False);
}
/*==============================================================================
* Screen/Display
*============================================================================*/
static void x11_get_screen_dimensions(int *width, int *height) {
if (!x11_state.display) {
if (width) *width = 0;
if (height) *height = 0;
return;
}
if (width) *width = DisplayWidth(x11_state.display, x11_state.screen);
if (height) *height = DisplayHeight(x11_state.display, x11_state.screen);
}
static int x11_get_screen_count(void) {
return x11_state.display ? ScreenCount(x11_state.display) : 0;
}
static void x11_get_screen_geometry(int screen, WmRect *geometry) {
if (!x11_state.display || !geometry) return;
geometry->x = 0;
geometry->y = 0;
geometry->width = DisplayWidth(x11_state.display, screen);
geometry->height = DisplayHeight(x11_state.display, screen);
}
/*==============================================================================
* Window Management - Geometry
*============================================================================*/
static void x11_window_get_geometry(WmWindowHandle window, WmRect *geometry) {
if (!x11_state.display || !geometry) return;
Window root;
int x, y;
unsigned int width, height, border, depth;
if (XGetGeometry(x11_state.display, (Window)window, &root,
&x, &y, &width, &height, &border, &depth)) {
geometry->x = x;
geometry->y = y;
geometry->width = (int)width;
geometry->height = (int)height;
}
}
static void x11_window_set_geometry(WmWindowHandle window, const WmRect *geometry) {
if (!x11_state.display || !geometry) return;
XMoveResizeWindow(x11_state.display, (Window)window,
geometry->x, geometry->y,
(unsigned int)geometry->width,
(unsigned int)geometry->height);
}
static void x11_window_move(WmWindowHandle window, int x, int y) {
if (!x11_state.display) return;
XMoveWindow(x11_state.display, (Window)window, x, y);
}
static void x11_window_resize(WmWindowHandle window, int width, int height) {
if (!x11_state.display) return;
XResizeWindow(x11_state.display, (Window)window,
(unsigned int)width, (unsigned int)height);
}
static void x11_window_move_resize(WmWindowHandle window, const WmRect *geometry) {
x11_window_set_geometry(window, geometry);
}
/*==============================================================================
* Window Management - Visibility
*============================================================================*/
static void x11_window_show(WmWindowHandle window) {
if (!x11_state.display) return;
XMapWindow(x11_state.display, (Window)window);
}
static void x11_window_hide(WmWindowHandle window) {
if (!x11_state.display) return;
XUnmapWindow(x11_state.display, (Window)window);
}
static bool x11_window_is_visible(WmWindowHandle window) {
if (!x11_state.display) return false;
XWindowAttributes attrs;
if (XGetWindowAttributes(x11_state.display, (Window)window, &attrs)) {
return attrs.map_state == IsViewable;
}
return false;
}
static void x11_window_map(WmWindowHandle window) {
x11_window_show(window);
}
static void x11_window_unmap(WmWindowHandle window) {
x11_window_hide(window);
}
static bool x11_window_is_mapped(WmWindowHandle window) {
return x11_window_is_visible(window);
}
/*==============================================================================
* Window Management - Stacking
*============================================================================*/
static void x11_window_raise(WmWindowHandle window) {
if (!x11_state.display) return;
XRaiseWindow(x11_state.display, (Window)window);
}
static void x11_window_lower(WmWindowHandle window) {
if (!x11_state.display) return;
XLowerWindow(x11_state.display, (Window)window);
}
static void x11_window_reparent(WmWindowHandle window, WmWindowHandle parent, int x, int y) {
if (!x11_state.display) return;
XReparentWindow(x11_state.display, (Window)window, (Window)parent, x, y);
}
/*==============================================================================
* Window Management - Focus
*============================================================================*/
static void x11_window_focus(WmWindowHandle window) {
if (!x11_state.display) return;
XSetInputFocus(x11_state.display, (Window)window, RevertToPointerRoot, CurrentTime);
}
static void x11_window_unfocus(WmWindowHandle window) {
(void)window;
if (!x11_state.display) return;
XSetInputFocus(x11_state.display, PointerRoot, RevertToPointerRoot, CurrentTime);
}
static bool x11_window_is_focused(WmWindowHandle window) {
if (!x11_state.display) return false;
Window focused;
int revert_to;
XGetInputFocus(x11_state.display, &focused, &revert_to);
return (Window)window == focused;
}
static WmWindowHandle x11_window_get_focused(void) {
if (!x11_state.display) return NULL;
Window focused;
int revert_to;
XGetInputFocus(x11_state.display, &focused, &revert_to);
return (WmWindowHandle)focused;
}
/*==============================================================================
* Window Management - Border
*============================================================================*/
static void x11_window_set_border_width(WmWindowHandle window, int width) {
if (!x11_state.display) return;
XSetWindowBorderWidth(x11_state.display, (Window)window, (unsigned int)width);
}
static int x11_window_get_border_width(WmWindowHandle window) {
if (!x11_state.display) return 0;
XWindowAttributes attrs;
if (XGetWindowAttributes(x11_state.display, (Window)window, &attrs)) {
return (int)attrs.border_width;
}
return 0;
}
/*==============================================================================
* Window Management - Properties
*============================================================================*/
static void x11_window_set_title(WmWindowHandle window, const char *title) {
if (!x11_state.display || !title) return;
XStoreName(x11_state.display, (Window)window, title);
if (x11_state.atom_net_wm_name != None && x11_state.atom_utf8_string != None) {
XChangeProperty(x11_state.display, (Window)window,
x11_state.atom_net_wm_name, x11_state.atom_utf8_string,
8, PropModeReplace,
(const unsigned char*)title, (int)strlen(title));
}
}
static char* x11_window_get_title(WmWindowHandle window) {
if (!x11_state.display) return NULL;
char *title = NULL;
/* Try _NET_WM_NAME first (UTF-8) */
if (x11_state.atom_net_wm_name != None) {
Atom actual_type;
int actual_format;
unsigned long nitems, bytes_after;
unsigned char *data = NULL;
if (XGetWindowProperty(x11_state.display, (Window)window,
x11_state.atom_net_wm_name, 0, ~0L, False,
x11_state.atom_utf8_string, &actual_type,
&actual_format, &nitems, &bytes_after, &data) == Success) {
if (data && actual_type == x11_state.atom_utf8_string) {
title = strdup((char*)data);
XFree(data);
if (title) return title;
}
if (data) XFree(data);
}
}
/* Fall back to WM_NAME */
char *name = NULL;
if (XFetchName(x11_state.display, (Window)window, &name)) {
title = strdup(name);
XFree(name);
}
return title;
}
/*==============================================================================
* Window Management - Protocols
*============================================================================*/
static bool x11_window_supports_protocol(WmWindowHandle window, const char *protocol) {
if (!x11_state.display || !protocol) return false;
Atom proto = XInternAtom(x11_state.display, protocol, True);
if (proto == None) return false;
Atom *protocols = NULL;
int count = 0;
if (XGetWMProtocols(x11_state.display, (Window)window, &protocols, &count)) {
for (int i = 0; i < count; i++) {
if (protocols[i] == proto) {
XFree(protocols);
return true;
}
}
XFree(protocols);
}
return false;
}
static void x11_window_close(WmWindowHandle window) {
if (!x11_state.display) return;
if (x11_window_supports_protocol(window, "WM_DELETE_WINDOW")) {
XEvent ev;
ev.type = ClientMessage;
ev.xclient.window = (Window)window;
ev.xclient.message_type = x11_state.atom_wm_protocols;
ev.xclient.format = 32;
ev.xclient.data.l[0] = (long)x11_state.atom_wm_delete_window;
ev.xclient.data.l[1] = CurrentTime;
XSendEvent(x11_state.display, (Window)window, False, NoEventMask, &ev);
} else {
XKillClient(x11_state.display, (Window)window);
}
}
static void x11_window_kill(WmWindowHandle window) {
if (!x11_state.display) return;
XKillClient(x11_state.display, (Window)window);
}
/*==============================================================================
* Window Management - State
*============================================================================*/
static void x11_window_set_fullscreen(WmWindowHandle window, bool fullscreen) {
if (!x11_state.display) return;
XEvent ev;
ev.type = ClientMessage;
ev.xclient.window = (Window)window;
ev.xclient.message_type = x11_state.atom_wm_state;
ev.xclient.format = 32;
ev.xclient.data.l[0] = fullscreen ? 1 : 0; /* _NET_WM_STATE_ADD or _NET_WM_STATE_REMOVE */
ev.xclient.data.l[1] = (long)x11_state.atom_wm_fullscreen;
ev.xclient.data.l[2] = 0;
ev.xclient.data.l[3] = 1; /* Source indication: normal application */
ev.xclient.data.l[4] = 0;
XSendEvent(x11_state.display, x11_state.root, False,
SubstructureRedirectMask | SubstructureNotifyMask, &ev);
}
static void x11_window_set_urgent(WmWindowHandle window, bool urgent) {
if (!x11_state.display) return;
XWMHints *hints = XGetWMHints(x11_state.display, (Window)window);
if (!hints) {
hints = XAllocWMHints();
if (!hints) return;
}
if (urgent) {
hints->flags |= XUrgencyHint;
} else {
hints->flags &= ~XUrgencyHint;
}
XSetWMHints(x11_state.display, (Window)window, hints);
XFree(hints);
}
static bool x11_window_is_urgent(WmWindowHandle window) {
if (!x11_state.display) return false;
XWMHints *hints = XGetWMHints(x11_state.display, (Window)window);
if (!hints) return false;
bool urgent = (hints->flags & XUrgencyHint) != 0;
XFree(hints);
return urgent;
}
/*==============================================================================
* Input - Events
*============================================================================*/
static bool x11_poll_event(WmBackendEvent *event) {
if (!x11_state.display || !event) return false;
if (!XPending(x11_state.display)) return false;
XEvent xev;
XNextEvent(x11_state.display, &xev);
/* Translate X11 event to backend event */
memset(event, 0, sizeof(*event));
event->window = (WmWindowHandle)xev.xany.window;
event->timestamp = (uint64_t)xev.xany.serial;
switch (xev.type) {
case Expose:
event->type = WM_BACKEND_EVENT_EXPOSE;
event->data.configure.x = xev.xexpose.x;
event->data.configure.y = xev.xexpose.y;
event->data.configure.width = xev.xexpose.width;
event->data.configure.height = xev.xexpose.height;
break;
case ConfigureNotify:
event->type = WM_BACKEND_EVENT_CONFIGURE;
event->data.configure.x = xev.xconfigure.x;
event->data.configure.y = xev.xconfigure.y;
event->data.configure.width = xev.xconfigure.width;
event->data.configure.height = xev.xconfigure.height;
break;
case MapNotify:
event->type = WM_BACKEND_EVENT_MAP;
break;
case UnmapNotify:
event->type = WM_BACKEND_EVENT_UNMAP;
break;
case DestroyNotify:
event->type = WM_BACKEND_EVENT_DESTROY;
break;
case FocusIn:
event->type = WM_BACKEND_EVENT_FOCUS_IN;
break;
case FocusOut:
event->type = WM_BACKEND_EVENT_FOCUS_OUT;
break;
case KeyPress:
event->type = WM_BACKEND_EVENT_KEY_PRESS;
event->data.key.keycode = xev.xkey.keycode;
event->data.key.state = xev.xkey.state;
break;
case KeyRelease:
event->type = WM_BACKEND_EVENT_KEY_RELEASE;
event->data.key.keycode = xev.xkey.keycode;
event->data.key.state = xev.xkey.state;
break;
case ButtonPress:
event->type = WM_BACKEND_EVENT_BUTTON_PRESS;
event->data.button.button = xev.xbutton.button;
event->data.button.x = xev.xbutton.x;
event->data.button.y = xev.xbutton.y;
event->data.button.state = xev.xbutton.state;
break;
case ButtonRelease:
event->type = WM_BACKEND_EVENT_BUTTON_RELEASE;
event->data.button.button = xev.xbutton.button;
event->data.button.x = xev.xbutton.x;
event->data.button.y = xev.xbutton.y;
event->data.button.state = xev.xbutton.state;
break;
case MotionNotify:
event->type = WM_BACKEND_EVENT_MOTION;
event->data.button.x = xev.xmotion.x;
event->data.button.y = xev.xmotion.y;
event->data.button.state = xev.xmotion.state;
break;
case EnterNotify:
event->type = WM_BACKEND_EVENT_ENTER;
break;
case LeaveNotify:
event->type = WM_BACKEND_EVENT_LEAVE;
break;
case PropertyNotify:
event->type = WM_BACKEND_EVENT_PROPERTY;
event->data.property.name = XGetAtomName(x11_state.display, xev.xproperty.atom);
break;
case ClientMessage:
event->type = WM_BACKEND_EVENT_CLIENT_MESSAGE;
break;
default:
event->type = WM_BACKEND_EVENT_NONE;
break;
}
return true;
}
static void x11_wait_event(WmBackendEvent *event) {
if (!x11_state.display || !event) return;
while (!x11_poll_event(event)) {
/* Wait for event */
}
}
/*==============================================================================
* Input - Grabbing
*============================================================================*/
static void x11_grab_key(int keycode, uint32_t modifiers, WmWindowHandle window,
bool owner_events, uint32_t pointer_mode, uint32_t keyboard_mode) {
if (!x11_state.display) return;
XGrabKey(x11_state.display, keycode, modifiers, (Window)window,
owner_events, pointer_mode, keyboard_mode);
}
static void x11_ungrab_key(int keycode, uint32_t modifiers, WmWindowHandle window) {
if (!x11_state.display) return;
XUngrabKey(x11_state.display, keycode, modifiers, (Window)window);
}
static void x11_grab_button(int button, uint32_t modifiers, WmWindowHandle window,
bool owner_events, uint32_t event_mask,
uint32_t pointer_mode, uint32_t keyboard_mode,
WmWindowHandle confine_to, uint32_t cursor) {
if (!x11_state.display) return;
XGrabButton(x11_state.display, button, modifiers, (Window)window,
owner_events, event_mask, pointer_mode, keyboard_mode,
(Window)confine_to, cursor);
}
static void x11_ungrab_button(int button, uint32_t modifiers, WmWindowHandle window) {
if (!x11_state.display) return;
XUngrabButton(x11_state.display, button, modifiers, (Window)window);
}
static void x11_grab_pointer(WmWindowHandle window, bool owner_events, uint32_t event_mask,
uint32_t pointer_mode, uint32_t keyboard_mode,
WmWindowHandle confine_to, uint32_t cursor, WmTime time) {
if (!x11_state.display) return;
XGrabPointer(x11_state.display, (Window)window, owner_events, event_mask,
pointer_mode, keyboard_mode, (Window)confine_to,
(Cursor)cursor, (Time)time);
}
static void x11_ungrab_pointer(WmTime time) {
if (!x11_state.display) return;
XUngrabPointer(x11_state.display, (Time)time);
}
/*==============================================================================
* Input - Pointer
*============================================================================*/
static void x11_query_pointer(WmWindowHandle window, int *root_x, int *root_y,
int *win_x, int *win_y, uint32_t *mask) {
if (!x11_state.display) return;
Window root, child;
int rx, ry, wx, wy;
unsigned int m;
XQueryPointer(x11_state.display, (Window)window, &root, &child,
&rx, &ry, &wx, &wy, &m);
if (root_x) *root_x = rx;
if (root_y) *root_y = ry;
if (win_x) *win_x = wx;
if (win_y) *win_y = wy;
if (mask) *mask = m;
}
static void x11_warp_pointer(WmWindowHandle dest_w, int dest_x, int dest_y) {
if (!x11_state.display) return;
XWarpPointer(x11_state.display, None, (Window)dest_w, 0, 0, 0, 0, dest_x, dest_y);
}
/*==============================================================================
* Atoms/Properties
*============================================================================*/
static uint32_t x11_atom_get(const char *name) {
if (!x11_state.display || !name) return 0;
return (uint32_t)XInternAtom(x11_state.display, name, False);
}
static const char* x11_atom_get_name(uint32_t atom) {
if (!x11_state.display || atom == 0) return NULL;
return XGetAtomName(x11_state.display, (Atom)atom);
}
/*==============================================================================
* Backend Interface
*============================================================================*/
static const BackendInterface x11_backend_interface = {
.name = "x11",
.get_info = x11_get_info,
.init = x11_init,
.shutdown = x11_shutdown,
.is_initialized = x11_is_initialized,
.connect = x11_connect,
.disconnect = x11_disconnect,
.is_connected = x11_is_connected,
.get_file_descriptor = x11_get_file_descriptor,
.flush = x11_flush,
.sync = x11_sync,
.get_screen_dimensions = x11_get_screen_dimensions,
.get_screen_count = x11_get_screen_count,
.get_screen_geometry = x11_get_screen_geometry,
.window_get_geometry = x11_window_get_geometry,
.window_set_geometry = x11_window_set_geometry,
.window_move = x11_window_move,
.window_resize = x11_window_resize,
.window_move_resize = x11_window_move_resize,
.window_show = x11_window_show,
.window_hide = x11_window_hide,
.window_is_visible = x11_window_is_visible,
.window_map = x11_window_map,
.window_unmap = x11_window_unmap,
.window_is_mapped = x11_window_is_mapped,
.window_raise = x11_window_raise,
.window_lower = x11_window_lower,
.window_reparent = x11_window_reparent,
.window_focus = x11_window_focus,
.window_unfocus = x11_window_unfocus,
.window_is_focused = x11_window_is_focused,
.window_get_focused = x11_window_get_focused,
.window_set_border_width = x11_window_set_border_width,
.window_get_border_width = x11_window_get_border_width,
.window_set_title = x11_window_set_title,
.window_get_title = x11_window_get_title,
.window_supports_protocol = x11_window_supports_protocol,
.window_close = x11_window_close,
.window_kill = x11_window_kill,
.window_set_fullscreen = x11_window_set_fullscreen,
.window_set_urgent = x11_window_set_urgent,
.window_is_urgent = x11_window_is_urgent,
.poll_event = x11_poll_event,
.wait_event = x11_wait_event,
.grab_key = x11_grab_key,
.ungrab_key = x11_ungrab_key,
.grab_button = x11_grab_button,
.ungrab_button = x11_ungrab_button,
.grab_pointer = x11_grab_pointer,
.ungrab_pointer = x11_ungrab_pointer,
.query_pointer = x11_query_pointer,
.warp_pointer = x11_warp_pointer,
.atom_get = x11_atom_get,
.atom_get_name = x11_atom_get_name,
};
const BackendInterface* x11_backend_get_interface(void) {
return &x11_backend_interface;
}
Display* x11_backend_get_display(void) {
return x11_state.display;
}
Window x11_backend_get_root(void) {
return x11_state.root;
}
int x11_backend_get_screen(void) {
return x11_state.screen;
}
+366
View File
@@ -0,0 +1,366 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* Channel Implementation - Thread-Safe Communication
*/
#include "threading.h"
#include "util.h"
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/eventfd.h>
#include <unistd.h>
/* ============================================================================
* Channel Implementation
* ============================================================================ */
struct Channel {
uint32_t capacity;
uint32_t head;
uint32_t tail;
uint32_t count;
ChannelType type;
void **buffer;
pthread_mutex_t mutex;
pthread_cond_t not_full;
pthread_cond_t not_empty;
int event_fd; /* For select() integration */
_Atomic int closed;
_Atomic int waiters; /* Number of threads waiting */
};
Channel* channel_create(uint32_t capacity)
{
Channel *ch = dwn_malloc(sizeof(Channel));
if (!ch) return NULL;
ch->capacity = capacity;
ch->head = 0;
ch->tail = 0;
ch->count = 0;
ch->type = (capacity == 0) ? CHANNEL_UNBUFFERED : CHANNEL_BUFFERED;
ch->event_fd = -1;
atomic_store_explicit(&ch->closed, 0, ATOMIC_RELEASE);
atomic_store_explicit(&ch->waiters, 0, ATOMIC_RELEASE);
if (capacity > 0) {
ch->buffer = dwn_malloc(sizeof(void*) * capacity);
if (!ch->buffer) {
dwn_free(ch);
return NULL;
}
} else {
ch->buffer = NULL;
}
if (pthread_mutex_init(&ch->mutex, NULL) != 0) {
dwn_free(ch->buffer);
dwn_free(ch);
return NULL;
}
if (pthread_cond_init(&ch->not_full, NULL) != 0) {
pthread_mutex_destroy(&ch->mutex);
dwn_free(ch->buffer);
dwn_free(ch);
return NULL;
}
if (pthread_cond_init(&ch->not_empty, NULL) != 0) {
pthread_cond_destroy(&ch->not_full);
pthread_mutex_destroy(&ch->mutex);
dwn_free(ch->buffer);
dwn_free(ch);
return NULL;
}
/* Create eventfd for async notification */
ch->event_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (ch->event_fd < 0) {
pthread_cond_destroy(&ch->not_empty);
pthread_cond_destroy(&ch->not_full);
pthread_mutex_destroy(&ch->mutex);
dwn_free(ch->buffer);
dwn_free(ch);
return NULL;
}
return ch;
}
void channel_destroy(Channel *ch)
{
if (!ch) return;
channel_close(ch);
pthread_cond_destroy(&ch->not_empty);
pthread_cond_destroy(&ch->not_full);
pthread_mutex_destroy(&ch->mutex);
if (ch->event_fd >= 0) {
close(ch->event_fd);
}
dwn_free(ch->buffer);
dwn_free(ch);
}
static void channel_notify(Channel *ch)
{
/* Signal eventfd */
uint64_t one = 1;
ssize_t w __attribute__((unused)) = write(ch->event_fd, &one, sizeof(one));
}
static bool channel_is_full(Channel *ch)
{
return ch->count >= ch->capacity;
}
static bool channel_is_empty(Channel *ch)
{
return ch->count == 0;
}
static void channel_push_internal(Channel *ch, void *data)
{
if (ch->capacity > 0) {
ch->buffer[ch->head] = data;
ch->head = (ch->head + 1) % ch->capacity;
ch->count++;
}
}
static void* channel_pop_internal(Channel *ch)
{
if (ch->capacity > 0 && ch->count > 0) {
void *data = ch->buffer[ch->tail];
ch->tail = (ch->tail + 1) % ch->capacity;
ch->count--;
return data;
}
return NULL;
}
ThreadStatus channel_send(Channel *ch, void *data)
{
return channel_send_timeout(ch, data, 0);
}
ThreadStatus channel_send_timeout(Channel *ch, void *data, uint64_t timeout_ms)
{
if (!ch || !data) return THREAD_ERROR_INVALID;
pthread_mutex_lock(&ch->mutex);
if (atomic_load_explicit(&ch->closed, ATOMIC_ACQUIRE)) {
pthread_mutex_unlock(&ch->mutex);
return THREAD_ERROR_CLOSED;
}
/* Wait for space */
if (ch->capacity > 0) {
while (channel_is_full(ch) && !atomic_load_explicit(&ch->closed, ATOMIC_ACQUIRE)) {
atomic_fetch_add_explicit(&ch->waiters, 1, ATOMIC_RELAXED);
if (timeout_ms == 0) {
pthread_cond_wait(&ch->not_full, &ch->mutex);
} else {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += timeout_ms / 1000;
ts.tv_nsec += (timeout_ms % 1000) * 1000000;
if (ts.tv_nsec >= 1000000000) {
ts.tv_sec++;
ts.tv_nsec -= 1000000000;
}
int ret = pthread_cond_timedwait(&ch->not_full, &ch->mutex, &ts);
if (ret == ETIMEDOUT) {
atomic_fetch_sub_explicit(&ch->waiters, 1, ATOMIC_RELAXED);
pthread_mutex_unlock(&ch->mutex);
return THREAD_ERROR_TIMEOUT;
}
}
atomic_fetch_sub_explicit(&ch->waiters, 1, ATOMIC_RELAXED);
}
}
if (atomic_load_explicit(&ch->closed, ATOMIC_ACQUIRE)) {
pthread_mutex_unlock(&ch->mutex);
return THREAD_ERROR_CLOSED;
}
channel_push_internal(ch, data);
pthread_cond_signal(&ch->not_empty);
pthread_mutex_unlock(&ch->mutex);
channel_notify(ch);
return THREAD_OK;
}
ThreadStatus channel_try_send(Channel *ch, void *data)
{
if (!ch || !data) return THREAD_ERROR_INVALID;
if (pthread_mutex_trylock(&ch->mutex) != 0) {
return THREAD_ERROR_BUSY;
}
if (atomic_load_explicit(&ch->closed, ATOMIC_ACQUIRE)) {
pthread_mutex_unlock(&ch->mutex);
return THREAD_ERROR_CLOSED;
}
if (ch->capacity > 0 && channel_is_full(ch)) {
pthread_mutex_unlock(&ch->mutex);
return THREAD_ERROR_BUSY;
}
channel_push_internal(ch, data);
pthread_cond_signal(&ch->not_empty);
pthread_mutex_unlock(&ch->mutex);
channel_notify(ch);
return THREAD_OK;
}
ThreadStatus channel_recv(Channel *ch, void **data)
{
return channel_recv_timeout(ch, data, 0);
}
ThreadStatus channel_recv_timeout(Channel *ch, void **data, uint64_t timeout_ms)
{
if (!ch || !data) return THREAD_ERROR_INVALID;
pthread_mutex_lock(&ch->mutex);
/* Wait for data */
while (channel_is_empty(ch) && !atomic_load_explicit(&ch->closed, ATOMIC_ACQUIRE)) {
atomic_fetch_add_explicit(&ch->waiters, 1, ATOMIC_RELAXED);
if (timeout_ms == 0) {
pthread_cond_wait(&ch->not_empty, &ch->mutex);
} else {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += timeout_ms / 1000;
ts.tv_nsec += (timeout_ms % 1000) * 1000000;
if (ts.tv_nsec >= 1000000000) {
ts.tv_sec++;
ts.tv_nsec -= 1000000000;
}
int ret = pthread_cond_timedwait(&ch->not_empty, &ch->mutex, &ts);
if (ret == ETIMEDOUT) {
atomic_fetch_sub_explicit(&ch->waiters, 1, ATOMIC_RELAXED);
pthread_mutex_unlock(&ch->mutex);
return THREAD_ERROR_TIMEOUT;
}
}
atomic_fetch_sub_explicit(&ch->waiters, 1, ATOMIC_RELAXED);
}
if (channel_is_empty(ch)) {
pthread_mutex_unlock(&ch->mutex);
return THREAD_ERROR_CLOSED;
}
*data = channel_pop_internal(ch);
pthread_cond_signal(&ch->not_full);
pthread_mutex_unlock(&ch->mutex);
return THREAD_OK;
}
ThreadStatus channel_try_recv(Channel *ch, void **data)
{
if (!ch || !data) return THREAD_ERROR_INVALID;
if (pthread_mutex_trylock(&ch->mutex) != 0) {
return THREAD_ERROR_BUSY;
}
if (channel_is_empty(ch)) {
pthread_mutex_unlock(&ch->mutex);
return atomic_load_explicit(&ch->closed, ATOMIC_ACQUIRE) ?
THREAD_ERROR_CLOSED : THREAD_ERROR_BUSY;
}
*data = channel_pop_internal(ch);
pthread_cond_signal(&ch->not_full);
pthread_mutex_unlock(&ch->mutex);
return THREAD_OK;
}
void channel_close(Channel *ch)
{
if (!ch) return;
pthread_mutex_lock(&ch->mutex);
atomic_store_explicit(&ch->closed, 1, ATOMIC_RELEASE);
pthread_cond_broadcast(&ch->not_full);
pthread_cond_broadcast(&ch->not_empty);
pthread_mutex_unlock(&ch->mutex);
channel_notify(ch);
}
bool channel_is_closed(Channel *ch)
{
if (!ch) return true;
return atomic_load_explicit(&ch->closed, ATOMIC_ACQUIRE) != 0;
}
/* ============================================================================
* Select Implementation
* ============================================================================ */
int channel_select(Channel **channels, uint32_t count, uint64_t timeout_ms,
void **out_data)
{
if (!channels || count == 0) return -1;
uint64_t start_time = 0;
if (timeout_ms > 0) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
start_time = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
for (;;) {
/* Try non-blocking receive on all channels */
for (uint32_t i = 0; i < count; i++) {
if (channel_try_recv(channels[i], out_data) == THREAD_OK) {
return (int)i;
}
}
/* Check timeout */
if (timeout_ms > 0) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
uint64_t now = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
if (now - start_time >= timeout_ms) {
return -1;
}
}
/* Short sleep to avoid busy-wait */
struct timespec sleep_ts = {0, 1000000}; /* 1ms */
nanosleep(&sleep_ts, NULL);
}
}
+24 -4
View File
@@ -14,6 +14,8 @@
#include "layout.h"
#include "panel.h"
#include "api.h"
#include "rules.h"
#include "marks.h"
#include <string.h>
#include <stdlib.h>
@@ -235,11 +237,25 @@ Client *client_manage(Window window)
client_sync_log("client_manage: syncing X");
XSync(dwn->display, False);
client_sync_log("client_manage: applying rules");
bool rules_applied = rules_apply_to_client(client);
if (rules_applied) {
client_configure(client);
if (client->workspace != (unsigned int)dwn->current_workspace) {
client_hide(client);
}
}
client_sync_log("client_manage: showing");
client_show(client);
if (client->workspace == (unsigned int)dwn->current_workspace) {
client_show(client);
}
client_sync_log("client_manage: focusing");
client_focus(client, true);
if (client->workspace == (unsigned int)dwn->current_workspace) {
client_focus(client, true);
}
api_emit_window_created(client->window, client->title, client->class, client->workspace);
@@ -258,6 +274,8 @@ void client_unmanage(Client *client)
api_emit_window_destroyed(client->window, client->title, client->workspace);
marks_remove_client(client);
LOG_DEBUG("Unmanaging window: %lu", client->window);
if (dwn->alt_tab_client == client) {
@@ -725,8 +743,10 @@ void client_update_title(Client *client)
}
char old_title[256];
strncpy(old_title, client->title, sizeof(old_title) - 1);
old_title[sizeof(old_title) - 1] = '\0';
size_t title_len = strlen(client->title);
if (title_len >= sizeof(old_title)) title_len = sizeof(old_title) - 1;
memcpy(old_title, client->title, title_len);
old_title[title_len] = '\0';
char *name = atoms_get_window_name(client->window);
if (name != NULL) {
+89
View File
@@ -97,6 +97,9 @@ void config_set_defaults(Config *cfg)
cfg->demo_ai_timeout_ms = 15000;
cfg->demo_window_timeout_ms = 5000;
cfg->fade_speed = 0.5f; /* Default moderate speed */
cfg->fade_intensity = 1.0f; /* Default full intensity */
strncpy(cfg->color_panel_bg, DEFAULT_PANEL_BG, sizeof(cfg->color_panel_bg) - 1);
strncpy(cfg->color_panel_fg, DEFAULT_PANEL_FG, sizeof(cfg->color_panel_fg) - 1);
strncpy(cfg->color_workspace_active, DEFAULT_WS_ACTIVE, sizeof(cfg->color_workspace_active) - 1);
@@ -227,6 +230,14 @@ static void handle_config_entry(const char *section, const char *key,
int val = atoi(value);
cfg->demo_window_timeout_ms = (val >= 1000 && val <= 30000) ? val : 5000;
}
} else if (strcmp(section, "effects") == 0) {
if (strcmp(key, "fade_speed") == 0) {
float val = atof(value);
cfg->fade_speed = (val >= 0.1f && val <= 3.0f) ? val : 0.5f;
} else if (strcmp(key, "fade_intensity") == 0) {
float val = atof(value);
cfg->fade_intensity = (val >= 0.0f && val <= 1.0f) ? val : 1.0f;
}
} else if (strcmp(section, "colors") == 0) {
if (strcmp(key, "panel_bg") == 0) {
strncpy(cfg->color_panel_bg, value, sizeof(cfg->color_panel_bg) - 1);
@@ -350,9 +361,53 @@ bool config_load(Config *cfg, const char *path)
LOG_INFO("AI features enabled");
}
/* Validate and clamp all config values to safe ranges */
config_validate(cfg);
return true;
}
void config_validate(Config *cfg)
{
if (cfg == NULL) return;
/* Panel height: 10-100 pixels */
if (cfg->panel_height < 10) cfg->panel_height = 10;
if (cfg->panel_height > 100) cfg->panel_height = 100;
/* Border width: 0-20 pixels */
if (cfg->border_width < 0) cfg->border_width = 0;
if (cfg->border_width > 20) cfg->border_width = 20;
/* Title height: 0-50 pixels */
if (cfg->title_height < 0) cfg->title_height = 0;
if (cfg->title_height > 50) cfg->title_height = 50;
/* Default master ratio: 0.1-0.9 */
if (cfg->default_master_ratio < 0.1f) cfg->default_master_ratio = 0.1f;
if (cfg->default_master_ratio > 0.9f) cfg->default_master_ratio = 0.9f;
/* Default master count: 1-8 */
if (cfg->default_master_count < 1) cfg->default_master_count = 1;
if (cfg->default_master_count > 8) cfg->default_master_count = 8;
/* Gap: 0-50 pixels */
if (cfg->gap < 0) cfg->gap = 0;
if (cfg->gap > 50) cfg->gap = 50;
/* Fade speed: 0.1-3.0 */
if (cfg->fade_speed < 0.1f) cfg->fade_speed = 0.1f;
if (cfg->fade_speed > 3.0f) cfg->fade_speed = 3.0f;
/* Fade intensity: 0.0-1.0 */
if (cfg->fade_intensity < 0.0f) cfg->fade_intensity = 0.0f;
if (cfg->fade_intensity > 1.0f) cfg->fade_intensity = 1.0f;
/* API port: 1024-65535 (avoid well-known ports) */
if (cfg->api_port < 1024) cfg->api_port = 8777;
if (cfg->api_port > 65535) cfg->api_port = 8777;
}
bool config_reload(Config *cfg)
{
if (cfg == NULL) {
@@ -440,3 +495,37 @@ void config_init_colors(Config *cfg)
cfg->colors.notification_bg = parse_color(cfg->color_notification_bg);
cfg->colors.notification_fg = parse_color(cfg->color_notification_fg);
}
float config_get_fade_speed(void)
{
if (dwn != NULL && dwn->config != NULL) {
return dwn->config->fade_speed;
}
return 0.5f;
}
float config_get_fade_intensity(void)
{
if (dwn != NULL && dwn->config != NULL) {
return dwn->config->fade_intensity;
}
return 1.0f;
}
void config_set_fade_speed(float speed)
{
if (dwn != NULL && dwn->config != NULL) {
if (speed < 0.1f) speed = 0.1f;
if (speed > 3.0f) speed = 3.0f;
dwn->config->fade_speed = speed;
}
}
void config_set_fade_intensity(float intensity)
{
if (dwn != NULL && dwn->config != NULL) {
if (intensity < 0.0f) intensity = 0.0f;
if (intensity > 1.0f) intensity = 1.0f;
dwn->config->fade_intensity = intensity;
}
}
+909
View File
@@ -0,0 +1,909 @@
/*
* DWN - Desktop Window Manager
* Abstract Client Implementation
*/
#include "core/wm_client.h"
#include "core/wm_hashmap.h"
#include "core/wm_list.h"
#include "client.h"
#include "dwn.h"
#include "util.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
/*==============================================================================
* Internal Structures
*============================================================================*/
struct AbstractClient {
/* Core identification */
WmClientId id;
WmWindowHandle window;
WmWindowHandle frame;
WmClientType type;
/* Legacy client pointer (for compatibility during migration) */
Client *legacy;
bool owns_legacy;
/* State */
WmClientState state;
WmWorkspaceId workspace;
/* Geometry */
WmRect geometry;
WmRect saved_geometry;
int border_width;
/* Properties */
char title[256];
char class_name[64];
char instance_name[64];
WmColor color;
/* List links */
AbstractClient *next;
AbstractClient *prev;
AbstractClient *mru_next;
AbstractClient *mru_prev;
};
struct WmClientManager {
AbstractClient *clients; /* Global client list */
AbstractClient *clients_tail; /* Tail of global list */
AbstractClient *mru_head; /* Most recently used */
AbstractClient *mru_tail; /* Least recently used */
WmHashMap *by_window; /* Map: window handle -> client */
WmHashMap *by_frame; /* Map: frame handle -> client */
WmHashMap *by_id; /* Map: client ID -> client */
AbstractClient *focused;
WmClientId next_id;
int count;
};
/*==============================================================================
* Global State
*============================================================================*/
static WmClientManager *g_client_manager = NULL;
/*==============================================================================
* Internal Helpers
*============================================================================*/
static WmClientId generate_client_id(void) {
if (!g_client_manager) return 0;
return g_client_manager->next_id++;
}
static void link_client(AbstractClient *client) {
if (!g_client_manager || !client) return;
/* Add to global list */
if (g_client_manager->clients_tail) {
g_client_manager->clients_tail->next = client;
client->prev = g_client_manager->clients_tail;
g_client_manager->clients_tail = client;
} else {
g_client_manager->clients = client;
g_client_manager->clients_tail = client;
}
/* Add to MRU list (at head = most recent) */
if (g_client_manager->mru_head) {
client->mru_next = g_client_manager->mru_head;
g_client_manager->mru_head->mru_prev = client;
g_client_manager->mru_head = client;
} else {
g_client_manager->mru_head = client;
g_client_manager->mru_tail = client;
}
g_client_manager->count++;
}
static void unlink_client(AbstractClient *client) {
if (!g_client_manager || !client) return;
/* Remove from global list */
if (client->prev) {
client->prev->next = client->next;
} else {
g_client_manager->clients = client->next;
}
if (client->next) {
client->next->prev = client->prev;
} else {
g_client_manager->clients_tail = client->prev;
}
/* Remove from MRU list */
if (client->mru_prev) {
client->mru_prev->mru_next = client->mru_next;
} else {
g_client_manager->mru_head = client->mru_next;
}
if (client->mru_next) {
client->mru_next->mru_prev = client->mru_prev;
} else {
g_client_manager->mru_tail = client->mru_prev;
}
g_client_manager->count--;
}
/*==============================================================================
* Client Lifecycle
*============================================================================*/
AbstractClient* wm_client_create(WmWindowHandle window, WmClientType type) {
if (!window) return NULL;
AbstractClient *client = calloc(1, sizeof(AbstractClient));
if (!client) return NULL;
client->id = generate_client_id();
client->window = window;
client->type = type;
client->state = WM_CLIENT_STATE_NORMAL | WM_CLIENT_STATE_MAPPED;
client->workspace = 0;
client->border_width = 0;
client->color = 0;
/* Register with manager */
if (g_client_manager) {
link_client(client);
wm_hashmap_insert(g_client_manager->by_window, window, client);
int id_key = (int)client->id;
wm_hashmap_insert(g_client_manager->by_id, (void*)(intptr_t)id_key, client);
}
LOG_DEBUG("Created abstract client %u for window %p", client->id, window);
return client;
}
void wm_client_destroy(AbstractClient *client) {
if (!client) return;
LOG_DEBUG("Destroying abstract client %u", client->id);
/* Remove from manager */
if (g_client_manager) {
wm_hashmap_remove(g_client_manager->by_window, client->window);
if (client->frame) {
wm_hashmap_remove(g_client_manager->by_frame, client->frame);
}
int id_key = (int)client->id;
wm_hashmap_remove(g_client_manager->by_id, (void*)(intptr_t)id_key);
unlink_client(client);
/* Clear focus if this was focused */
if (g_client_manager->focused == client) {
g_client_manager->focused = NULL;
}
}
/* Destroy legacy client if we own it */
if (client->legacy && client->owns_legacy) {
client_destroy(client->legacy);
}
free(client);
}
bool wm_client_is_valid(const AbstractClient *client) {
return client != NULL &&
!(client->state & WM_CLIENT_STATE_DESTROYING);
}
/*==============================================================================
* Native Access
*============================================================================*/
WmWindowHandle wm_client_get_window(const AbstractClient *client) {
return client ? client->window : NULL;
}
WmWindowHandle wm_client_get_frame(const AbstractClient *client) {
return client ? client->frame : NULL;
}
Client* wm_client_get_legacy(const AbstractClient *client) {
return client ? client->legacy : NULL;
}
AbstractClient* wm_client_from_legacy(Client *legacy_client) {
if (!legacy_client) return NULL;
/* Check if we already have a wrapper for this client */
AbstractClient *existing = wm_client_find_by_window((WmWindowHandle)legacy_client->window);
if (existing) return existing;
/* Create wrapper */
AbstractClient *client = calloc(1, sizeof(AbstractClient));
if (!client) return NULL;
client->id = generate_client_id();
client->window = (WmWindowHandle)legacy_client->window;
client->frame = (WmWindowHandle)legacy_client->frame;
client->legacy = legacy_client;
client->owns_legacy = false;
/* Sync state from legacy */
client->workspace = legacy_client->workspace;
client->border_width = legacy_client->border_width;
client->geometry.x = legacy_client->x;
client->geometry.y = legacy_client->y;
client->geometry.width = legacy_client->width;
client->geometry.height = legacy_client->height;
size_t title_len = strlen(legacy_client->title);
if (title_len >= sizeof(client->title)) title_len = sizeof(client->title) - 1;
memcpy(client->title, legacy_client->title, title_len);
client->title[title_len] = '\0';
size_t class_len = strlen(legacy_client->class);
if (class_len >= sizeof(client->class_name)) class_len = sizeof(client->class_name) - 1;
memcpy(client->class_name, legacy_client->class, class_len);
client->class_name[class_len] = '\0';
client->color = legacy_client->taskbar_color;
/* Convert flags */
if (legacy_client->flags & CLIENT_FLOATING) {
client->state |= WM_CLIENT_STATE_FLOATING;
}
if (legacy_client->flags & CLIENT_FULLSCREEN) {
client->state |= WM_CLIENT_STATE_FULLSCREEN;
}
if (legacy_client->flags & CLIENT_URGENT) {
client->state |= WM_CLIENT_STATE_URGENT;
}
if (legacy_client->flags & CLIENT_MINIMIZED) {
client->state |= WM_CLIENT_STATE_MINIMIZED;
}
if (legacy_client->flags & CLIENT_STICKY) {
client->state |= WM_CLIENT_STATE_STICKY;
}
if (legacy_client->flags & CLIENT_MAXIMIZED) {
client->state |= WM_CLIENT_STATE_MAXIMIZED;
}
/* Register */
if (g_client_manager) {
link_client(client);
wm_hashmap_insert(g_client_manager->by_window, client->window, client);
if (client->frame) {
wm_hashmap_insert(g_client_manager->by_frame, client->frame, client);
}
int id_key = (int)client->id;
wm_hashmap_insert(g_client_manager->by_id, (void*)(intptr_t)id_key, client);
}
return client;
}
/*==============================================================================
* Client Identification
*============================================================================*/
WmClientId wm_client_get_id(const AbstractClient *client) {
return client ? client->id : 0;
}
WmClientType wm_client_get_type(const AbstractClient *client) {
return client ? client->type : WM_CLIENT_TYPE_UNKNOWN;
}
void wm_client_set_type(AbstractClient *client, WmClientType type) {
if (client) client->type = type;
}
/*==============================================================================
* Client State
*============================================================================*/
WmClientState wm_client_get_state(const AbstractClient *client) {
return client ? client->state : 0;
}
void wm_client_set_state(AbstractClient *client, WmClientState state) {
if (client) client->state = state;
}
void wm_client_add_state(AbstractClient *client, WmClientState state) {
if (client) client->state |= state;
}
void wm_client_remove_state(AbstractClient *client, WmClientState state) {
if (client) client->state &= ~state;
}
void wm_client_toggle_state(AbstractClient *client, WmClientState state) {
if (client) client->state ^= state;
}
bool wm_client_has_state(const AbstractClient *client, WmClientState state) {
return client && (client->state & state) != 0;
}
/*==============================================================================
* Client Geometry
*============================================================================*/
WmRect wm_client_get_geometry(const AbstractClient *client) {
if (!client) return (WmRect){0, 0, 0, 0};
/* Sync from legacy if available */
if (client->legacy) {
return (WmRect){
client->legacy->x,
client->legacy->y,
client->legacy->width,
client->legacy->height
};
}
return client->geometry;
}
void wm_client_set_geometry(AbstractClient *client, const WmRect *geometry) {
if (!client || !geometry) return;
client->geometry = *geometry;
/* Sync to legacy if available */
if (client->legacy) {
client->legacy->x = geometry->x;
client->legacy->y = geometry->y;
client->legacy->width = geometry->width;
client->legacy->height = geometry->height;
}
}
WmPoint wm_client_get_position(const AbstractClient *client) {
WmRect geom = wm_client_get_geometry(client);
return (WmPoint){geom.x, geom.y};
}
void wm_client_set_position(AbstractClient *client, int x, int y) {
if (!client) return;
client->geometry.x = x;
client->geometry.y = y;
if (client->legacy) {
client->legacy->x = x;
client->legacy->y = y;
}
}
WmSize wm_client_get_size(const AbstractClient *client) {
WmRect geom = wm_client_get_geometry(client);
return (WmSize){geom.width, geom.height};
}
void wm_client_set_size(AbstractClient *client, int width, int height) {
if (!client) return;
client->geometry.width = width;
client->geometry.height = height;
if (client->legacy) {
client->legacy->width = width;
client->legacy->height = height;
}
}
int wm_client_get_border_width(const AbstractClient *client) {
if (!client) return 0;
if (client->legacy) return client->legacy->border_width;
return client->border_width;
}
void wm_client_set_border_width(AbstractClient *client, int width) {
if (!client) return;
client->border_width = width;
if (client->legacy) {
client->legacy->border_width = width;
}
}
void wm_client_save_geometry(AbstractClient *client) {
if (!client) return;
client->saved_geometry = wm_client_get_geometry(client);
if (client->legacy) {
client->legacy->old_x = client->saved_geometry.x;
client->legacy->old_y = client->saved_geometry.y;
client->legacy->old_width = client->saved_geometry.width;
client->legacy->old_height = client->saved_geometry.height;
}
}
void wm_client_restore_geometry(AbstractClient *client) {
if (!client) return;
wm_client_set_geometry(client, &client->saved_geometry);
}
/*==============================================================================
* Client Workspace
*============================================================================*/
WmWorkspaceId wm_client_get_workspace(const AbstractClient *client) {
return client ? client->workspace : 0;
}
void wm_client_set_workspace(AbstractClient *client, WmWorkspaceId workspace) {
if (!client) return;
client->workspace = workspace;
if (client->legacy) {
client->legacy->workspace = workspace;
}
}
bool wm_client_is_on_workspace(const AbstractClient *client, WmWorkspaceId workspace) {
if (!client) return false;
if (client->state & WM_CLIENT_STATE_STICKY) return true;
return client->workspace == workspace;
}
bool wm_client_is_visible_on_current(const AbstractClient *client) {
if (!client || !dwn) return false;
return wm_client_is_on_workspace(client, dwn->current_workspace);
}
/*==============================================================================
* Client Properties
*============================================================================*/
const char* wm_client_get_title(const AbstractClient *client) {
if (!client) return "";
if (client->legacy) return client->legacy->title;
return client->title;
}
void wm_client_set_title(AbstractClient *client, const char *title) {
if (!client || !title) return;
strncpy(client->title, title, sizeof(client->title) - 1);
client->title[sizeof(client->title) - 1] = '\0';
if (client->legacy) {
strncpy(client->legacy->title, title, sizeof(client->legacy->title) - 1);
client->legacy->title[sizeof(client->legacy->title) - 1] = '\0';
}
}
const char* wm_client_get_class(const AbstractClient *client) {
if (!client) return "";
if (client->legacy) return client->legacy->class;
return client->class_name;
}
void wm_client_set_class(AbstractClient *client, const char *class_name) {
if (!client || !class_name) return;
strncpy(client->class_name, class_name, sizeof(client->class_name) - 1);
client->class_name[sizeof(client->class_name) - 1] = '\0';
if (client->legacy) {
strncpy(client->legacy->class, class_name, sizeof(client->legacy->class) - 1);
client->legacy->class[sizeof(client->legacy->class) - 1] = '\0';
}
}
const char* wm_client_get_instance(const AbstractClient *client) {
if (!client) return "";
return client->instance_name;
}
void wm_client_set_instance(AbstractClient *client, const char *instance) {
if (!client || !instance) return;
strncpy(client->instance_name, instance, sizeof(client->instance_name) - 1);
client->instance_name[sizeof(client->instance_name) - 1] = '\0';
}
WmColor wm_client_get_color(const AbstractClient *client) {
if (!client) return 0;
if (client->legacy) return client->legacy->taskbar_color;
return client->color;
}
void wm_client_set_color(AbstractClient *client, WmColor color) {
if (!client) return;
client->color = color;
if (client->legacy) {
client->legacy->taskbar_color = color;
}
}
/*==============================================================================
* Client Actions (delegate to legacy for now)
*============================================================================*/
void wm_client_focus(AbstractClient *client) {
if (!client) return;
if (client->legacy) {
client_focus(client->legacy, true);
}
client->state |= WM_CLIENT_STATE_FOCUS;
if (g_client_manager) {
wm_client_manager_touch(g_client_manager, client);
g_client_manager->focused = client;
}
}
void wm_client_unfocus(AbstractClient *client) {
if (!client) return;
if (client->legacy) {
client_unfocus(client->legacy);
}
client->state &= ~WM_CLIENT_STATE_FOCUS;
if (g_client_manager && g_client_manager->focused == client) {
g_client_manager->focused = NULL;
}
}
void wm_client_raise(AbstractClient *client) {
if (!client) return;
if (client->legacy) {
client_raise(client->legacy);
}
}
void wm_client_lower(AbstractClient *client) {
if (!client) return;
if (client->legacy) {
client_lower(client->legacy);
}
}
void wm_client_show(AbstractClient *client) {
if (!client) return;
if (client->legacy) {
client_show(client->legacy);
}
client->state |= WM_CLIENT_STATE_MAPPED;
}
void wm_client_hide(AbstractClient *client) {
if (!client) return;
if (client->legacy) {
client_hide(client->legacy);
}
client->state &= ~WM_CLIENT_STATE_MAPPED;
}
void wm_client_minimize(AbstractClient *client) {
if (!client) return;
if (client->legacy) {
client_minimize(client->legacy);
}
client->state |= WM_CLIENT_STATE_MINIMIZED;
}
void wm_client_restore(AbstractClient *client) {
if (!client) return;
if (client->legacy) {
client_restore(client->legacy);
}
client->state &= ~WM_CLIENT_STATE_MINIMIZED;
}
void wm_client_close(AbstractClient *client) {
if (!client) return;
if (client->legacy) {
client_close(client->legacy);
}
}
void wm_client_kill(AbstractClient *client) {
if (!client) return;
if (client->legacy) {
client_kill(client->legacy);
}
}
/*==============================================================================
* Client Management
*============================================================================*/
void wm_client_reparent(AbstractClient *client, WmWindowHandle frame) {
if (!client) return;
client->frame = frame;
/* Update frame lookup */
if (g_client_manager) {
if (client->frame) {
wm_hashmap_remove(g_client_manager->by_frame, client->frame);
}
wm_hashmap_insert(g_client_manager->by_frame, frame, client);
}
if (client->legacy) {
/* Legacy doesn't have a direct reparent function for frames */
}
}
void wm_client_unreparent(AbstractClient *client) {
if (!client) return;
if (g_client_manager && client->frame) {
wm_hashmap_remove(g_client_manager->by_frame, client->frame);
}
client->frame = NULL;
}
void wm_client_configure(AbstractClient *client) {
if (!client) return;
if (client->legacy) {
client_configure(client->legacy);
}
}
void wm_client_apply_size_hints(AbstractClient *client, int *width, int *height) {
if (!client || !width || !height) return;
if (client->legacy) {
client_apply_size_hints(client->legacy, width, height);
}
}
void wm_client_move_resize(AbstractClient *client, int x, int y, int width, int height) {
if (!client) return;
client->geometry.x = x;
client->geometry.y = y;
client->geometry.width = width;
client->geometry.height = height;
if (client->legacy) {
client_move_resize(client->legacy, x, y, width, height);
}
}
/*==============================================================================
* Client List Management
*============================================================================*/
AbstractClient* wm_client_get_next(const AbstractClient *client) {
return client ? client->next : NULL;
}
AbstractClient* wm_client_get_prev(const AbstractClient *client) {
return client ? client->prev : NULL;
}
AbstractClient* wm_client_get_first(void) {
return g_client_manager ? g_client_manager->clients : NULL;
}
AbstractClient* wm_client_get_last(void) {
return g_client_manager ? g_client_manager->clients_tail : NULL;
}
AbstractClient* wm_client_get_next_mru(const AbstractClient *client) {
return client ? client->mru_next : NULL;
}
AbstractClient* wm_client_get_prev_mru(const AbstractClient *client) {
return client ? client->mru_prev : NULL;
}
/*==============================================================================
* Client Lookup
*============================================================================*/
AbstractClient* wm_client_find_by_window(WmWindowHandle window) {
if (!g_client_manager || !window) return NULL;
return wm_hashmap_get(g_client_manager->by_window, window);
}
AbstractClient* wm_client_find_by_frame(WmWindowHandle frame) {
if (!g_client_manager || !frame) return NULL;
return wm_hashmap_get(g_client_manager->by_frame, frame);
}
AbstractClient* wm_client_find_by_id(WmClientId id) {
if (!g_client_manager) return NULL;
return wm_hashmap_get(g_client_manager->by_id, (void*)(intptr_t)id);
}
/*==============================================================================
* Client Iteration
*============================================================================*/
void wm_client_foreach(WmClientForeachFunc func, void *user_data) {
if (!func) return;
AbstractClient *client = wm_client_get_first();
while (client) {
AbstractClient *next = client->next;
if (!func(client, user_data)) break;
client = next;
}
}
typedef struct {
WmWorkspaceId workspace;
WmClientForeachFunc func;
void *user_data;
} ForeachWorkspaceData;
static bool foreach_workspace_wrapper(AbstractClient *client, void *data) {
ForeachWorkspaceData *fwd = data;
if (wm_client_is_on_workspace(client, fwd->workspace)) {
return fwd->func(client, fwd->user_data);
}
return true;
}
void wm_client_foreach_on_workspace(WmWorkspaceId workspace,
WmClientForeachFunc func, void *user_data) {
ForeachWorkspaceData data = { workspace, func, user_data };
wm_client_foreach(foreach_workspace_wrapper, &data);
}
int wm_client_count(void) {
return g_client_manager ? g_client_manager->count : 0;
}
typedef struct {
int count;
WmWorkspaceId workspace;
} CountWorkspaceData;
static bool count_workspace(AbstractClient *client, void *data) {
CountWorkspaceData *cwd = data;
if (wm_client_is_on_workspace(client, cwd->workspace)) {
cwd->count++;
}
return true;
}
int wm_client_count_on_workspace(WmWorkspaceId workspace) {
CountWorkspaceData data = { 0, workspace };
wm_client_foreach(count_workspace, &data);
return data.count;
}
/*==============================================================================
* Client Manager
*============================================================================*/
WmClientManager* wm_client_manager_get(void) {
return g_client_manager;
}
bool wm_client_manager_init(void) {
if (g_client_manager) return true;
g_client_manager = calloc(1, sizeof(WmClientManager));
if (!g_client_manager) return false;
g_client_manager->by_window = wm_hashmap_new();
g_client_manager->by_frame = wm_hashmap_new();
g_client_manager->by_id = wm_hashmap_new();
if (!g_client_manager->by_window ||
!g_client_manager->by_frame ||
!g_client_manager->by_id) {
wm_client_manager_shutdown();
return false;
}
g_client_manager->next_id = 1;
LOG_INFO("Client manager initialized");
return true;
}
void wm_client_manager_shutdown(void) {
if (!g_client_manager) return;
/* Destroy all abstract clients (but not legacy ones - we don't own them) */
AbstractClient *client = g_client_manager->clients;
while (client) {
AbstractClient *next = client->next;
if (client->owns_legacy) {
client_destroy(client->legacy);
}
free(client);
client = next;
}
wm_hashmap_destroy(g_client_manager->by_window);
wm_hashmap_destroy(g_client_manager->by_frame);
wm_hashmap_destroy(g_client_manager->by_id);
free(g_client_manager);
g_client_manager = NULL;
LOG_INFO("Client manager shutdown");
}
void wm_client_manager_add(WmClientManager *mgr, AbstractClient *client) {
if (!mgr || !client) return;
/* Client is already linked when created */
}
void wm_client_manager_remove(WmClientManager *mgr, AbstractClient *client) {
if (!mgr || !client) return;
/* Client is already unlinked when destroyed */
}
void wm_client_manager_touch(WmClientManager *mgr, AbstractClient *client) {
if (!mgr || !client) return;
/* Already at head - nothing to do */
if (mgr->mru_head == client) return;
/* Remove from current position */
if (client->mru_prev) {
client->mru_prev->mru_next = client->mru_next;
}
if (client->mru_next) {
client->mru_next->mru_prev = client->mru_prev;
}
if (mgr->mru_tail == client) {
mgr->mru_tail = client->mru_prev;
}
/* Insert at head */
client->mru_prev = NULL;
client->mru_next = mgr->mru_head;
if (mgr->mru_head) {
mgr->mru_head->mru_prev = client;
}
mgr->mru_head = client;
}
AbstractClient* wm_client_manager_get_focused(const WmClientManager *mgr) {
return mgr ? mgr->focused : NULL;
}
void wm_client_manager_set_focused(WmClientManager *mgr, AbstractClient *client) {
if (!mgr) return;
mgr->focused = client;
}
+416
View File
@@ -0,0 +1,416 @@
/*
* DWN - Desktop Window Manager
* Abstract Hash Map Implementation
*/
#include "core/wm_hashmap.h"
#include "core/wm_string.h"
#include <stdlib.h>
#include <string.h>
/*==============================================================================
* Constants
*============================================================================*/
#define WM_HASHMAP_INITIAL_CAPACITY 16
#define WM_HASHMAP_LOAD_FACTOR 0.75
/*==============================================================================
* Entry Structure
*============================================================================*/
typedef struct WmHashMapEntry {
uint32_t hash;
void *key;
void *value;
struct WmHashMapEntry *next;
} WmHashMapEntry;
/*==============================================================================
* Hash Map Structure
*============================================================================*/
struct WmHashMap {
WmHashMapEntry **buckets;
size_t bucket_count;
size_t size;
WmHashFunc hash_func;
WmKeyEqualFunc key_equal;
WmFreeFunc key_free;
WmFreeFunc value_free;
};
/*==============================================================================
* Internal Helpers
*============================================================================*/
static void hashmap_clone_insert(void *key, void *value, void *user_data) {
wm_hashmap_insert((WmHashMap *)user_data, key, value);
}
/*==============================================================================
* Default Hash Functions
*============================================================================*/
static uint32_t wm_hash_pointer(const void *key) {
/* FNV-1a hash for pointer */
uintptr_t ptr = (uintptr_t)key;
uint32_t hash = 2166136261u;
for (size_t i = 0; i < sizeof(ptr); i++) {
hash ^= (ptr >> (i * 8)) & 0xFF;
hash *= 16777619u;
}
return hash;
}
static uint32_t wm_hash_string(const void *key) {
const char *str = key;
uint32_t hash = 2166136261u;
while (*str) {
hash ^= (uint8_t)*str++;
hash *= 16777619u;
}
return hash;
}
static bool wm_equal_pointer(const void *a, const void *b) {
return a == b;
}
static bool wm_equal_string(const void *a, const void *b) {
return strcmp((const char*)a, (const char*)b) == 0;
}
/*==============================================================================
* Internal Helpers
*============================================================================*/
static bool wm_hashmap_resize(WmHashMap *map) {
size_t old_count = map->bucket_count;
WmHashMapEntry **old_buckets = map->buckets;
size_t new_count = old_count * 2;
WmHashMapEntry **new_buckets = calloc(new_count, sizeof(WmHashMapEntry*));
if (!new_buckets) return false;
map->buckets = new_buckets;
map->bucket_count = new_count;
/* Rehash all entries */
for (size_t i = 0; i < old_count; i++) {
WmHashMapEntry *entry = old_buckets[i];
while (entry) {
WmHashMapEntry *next = entry->next;
size_t new_index = entry->hash % new_count;
entry->next = new_buckets[new_index];
new_buckets[new_index] = entry;
entry = next;
}
}
free(old_buckets);
return true;
}
/*==============================================================================
* Lifecycle
*============================================================================*/
WmHashMap* wm_hashmap_new(void) {
return wm_hashmap_new_full(NULL, NULL, NULL, NULL);
}
WmHashMap* wm_hashmap_new_full(WmHashFunc hash_func, WmKeyEqualFunc key_equal,
WmFreeFunc key_free, WmFreeFunc value_free) {
WmHashMap *map = calloc(1, sizeof(WmHashMap));
if (!map) return NULL;
map->bucket_count = WM_HASHMAP_INITIAL_CAPACITY;
map->buckets = calloc(map->bucket_count, sizeof(WmHashMapEntry*));
if (!map->buckets) {
free(map);
return NULL;
}
map->hash_func = hash_func ? hash_func : wm_hash_pointer;
map->key_equal = key_equal ? key_equal : wm_equal_pointer;
map->key_free = key_free;
map->value_free = value_free;
return map;
}
WmHashMap* wm_hashmap_new_string_key(void) {
return wm_hashmap_new_full(wm_hash_string, wm_equal_string, free, NULL);
}
void wm_hashmap_destroy(WmHashMap *map) {
if (!map) return;
wm_hashmap_clear(map);
free(map->buckets);
free(map);
}
WmHashMap* wm_hashmap_clone(const WmHashMap *map) {
if (!map) return NULL;
WmHashMap *clone = wm_hashmap_new_full(map->hash_func, map->key_equal,
NULL, NULL);
if (!clone) return NULL;
/* Note: This creates a shallow copy */
wm_hashmap_foreach(map, hashmap_clone_insert, clone);
clone->key_free = map->key_free;
clone->value_free = map->value_free;
return clone;
}
/*==============================================================================
* Capacity
*============================================================================*/
size_t wm_hashmap_size(const WmHashMap *map) {
return map ? map->size : 0;
}
bool wm_hashmap_is_empty(const WmHashMap *map) {
return !map || map->size == 0;
}
void wm_hashmap_clear(WmHashMap *map) {
if (!map) return;
for (size_t i = 0; i < map->bucket_count; i++) {
WmHashMapEntry *entry = map->buckets[i];
while (entry) {
WmHashMapEntry *next = entry->next;
if (map->key_free && entry->key) map->key_free(entry->key);
if (map->value_free && entry->value) map->value_free(entry->value);
free(entry);
entry = next;
}
map->buckets[i] = NULL;
}
map->size = 0;
}
/*==============================================================================
* Element Access
*============================================================================*/
void* wm_hashmap_get(const WmHashMap *map, const void *key) {
if (!map || !key) return NULL;
uint32_t hash = map->hash_func(key);
size_t index = hash % map->bucket_count;
WmHashMapEntry *entry = map->buckets[index];
while (entry) {
if (entry->hash == hash && map->key_equal(entry->key, key)) {
return entry->value;
}
entry = entry->next;
}
return NULL;
}
void* wm_hashmap_get_or_default(const WmHashMap *map, const void *key, void *default_val) {
void *val = wm_hashmap_get(map, key);
return val ? val : default_val;
}
bool wm_hashmap_contains(const WmHashMap *map, const void *key) {
return wm_hashmap_get(map, key) != NULL;
}
/*==============================================================================
* Modifiers
*============================================================================*/
bool wm_hashmap_insert(WmHashMap *map, void *key, void *value) {
if (!map || !key) return false;
/* Check if resize needed */
if ((double)map->size / map->bucket_count > WM_HASHMAP_LOAD_FACTOR) {
if (!wm_hashmap_resize(map)) return false;
}
uint32_t hash = map->hash_func(key);
size_t index = hash % map->bucket_count;
/* Check if key exists */
WmHashMapEntry *entry = map->buckets[index];
while (entry) {
if (entry->hash == hash && map->key_equal(entry->key, key)) {
/* Update existing entry */
if (map->value_free) map->value_free(entry->value);
entry->value = value;
return true;
}
entry = entry->next;
}
/* Insert new entry */
entry = malloc(sizeof(WmHashMapEntry));
if (!entry) return false;
entry->hash = hash;
entry->key = key;
entry->value = value;
entry->next = map->buckets[index];
map->buckets[index] = entry;
map->size++;
return true;
}
bool wm_hashmap_insert_no_replace(WmHashMap *map, void *key, void *value) {
if (!map || !key) return false;
if (wm_hashmap_contains(map, key)) return false;
return wm_hashmap_insert(map, key, value);
}
void* wm_hashmap_set(WmHashMap *map, void *key, void *value) {
if (!map || !key) return NULL;
void *old_value = wm_hashmap_get(map, key);
wm_hashmap_insert(map, key, value);
return old_value;
}
void* wm_hashmap_remove(WmHashMap *map, const void *key) {
if (!map || !key) return NULL;
uint32_t hash = map->hash_func(key);
size_t index = hash % map->bucket_count;
WmHashMapEntry *entry = map->buckets[index];
WmHashMapEntry *prev = NULL;
while (entry) {
if (entry->hash == hash && map->key_equal(entry->key, key)) {
void *value = entry->value;
if (prev) {
prev->next = entry->next;
} else {
map->buckets[index] = entry->next;
}
if (map->key_free) map->key_free(entry->key);
free(entry);
map->size--;
return value;
}
prev = entry;
entry = entry->next;
}
return NULL;
}
bool wm_hashmap_steal(WmHashMap *map, const void *key) {
return wm_hashmap_remove(map, key) != NULL;
}
/*==============================================================================
* Iteration
*============================================================================*/
typedef struct WmHashMapIterInternal {
WmHashMap *map;
size_t bucket;
WmHashMapEntry *entry;
WmHashMapEntry *next_entry;
} WmHashMapIterInternal;
void wm_hashmap_iter_init(WmHashMapIter *iter, WmHashMap *map) {
if (!iter) return;
iter->map = map;
iter->bucket = 0;
iter->entry = NULL;
iter->next_entry = NULL;
if (!map) return;
/* Find first bucket with entry */
for (size_t i = 0; i < map->bucket_count; i++) {
if (map->buckets[i]) {
iter->bucket = i;
iter->entry = map->buckets[i];
iter->next_entry = ((WmHashMapEntry*)iter->entry)->next;
break;
}
}
}
bool wm_hashmap_iter_next(WmHashMapIter *iter, void **key, void **value) {
if (!iter || !iter->entry) return false;
WmHashMapEntry *entry = (WmHashMapEntry*)iter->entry;
*key = entry->key;
*value = entry->value;
/* Move to next entry */
entry = entry->next;
if (!entry) {
/* Find next bucket with entries */
WmHashMap *map = (WmHashMap*)iter->map;
for (size_t i = iter->bucket + 1; i < map->bucket_count; i++) {
if (map->buckets[i]) {
iter->bucket = i;
entry = map->buckets[i];
break;
}
}
}
iter->entry = entry;
return true;
}
void wm_hashmap_foreach(const WmHashMap *map, WmHashForeachFunc func, void *user_data) {
if (!map || !func) return;
for (size_t i = 0; i < map->bucket_count; i++) {
WmHashMapEntry *entry = map->buckets[i];
while (entry) {
func(entry->key, entry->value, user_data);
entry = entry->next;
}
}
}
/*==============================================================================
* String Helpers
*============================================================================*/
bool wm_hashmap_insert_string(WmHashMap *map, const char *key, void *value) {
if (!map || !key) return false;
char *key_copy = strdup(key);
if (!key_copy) return false;
if (!wm_hashmap_insert(map, key_copy, value)) {
free(key_copy);
return false;
}
return true;
}
void* wm_hashmap_get_string(const WmHashMap *map, const char *key) {
return wm_hashmap_get(map, key);
}
bool wm_hashmap_contains_string(const WmHashMap *map, const char *key) {
return wm_hashmap_contains(map, key);
}
void* wm_hashmap_remove_string(WmHashMap *map, const char *key) {
return wm_hashmap_remove(map, key);
}
+432
View File
@@ -0,0 +1,432 @@
/*
* DWN - Desktop Window Manager
* Abstract List Implementation (Dynamic Array)
*/
#include "core/wm_list.h"
#include "core/wm_types.h"
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
/*==============================================================================
* List Structure
*============================================================================*/
struct WmList {
void **data;
size_t size;
size_t capacity;
WmFreeFunc free_func;
};
/*==============================================================================
* Lifecycle
*============================================================================*/
WmList* wm_list_new(void) {
WmList *list = calloc(1, sizeof(WmList));
if (!list) return NULL;
list->capacity = 8;
list->data = malloc(list->capacity * sizeof(void*));
if (!list->data) {
free(list);
return NULL;
}
return list;
}
WmList* wm_list_new_sized(size_t initial_capacity) {
WmList *list = calloc(1, sizeof(WmList));
if (!list) return NULL;
list->capacity = initial_capacity > 0 ? initial_capacity : 8;
list->data = malloc(list->capacity * sizeof(void*));
if (!list->data) {
free(list);
return NULL;
}
return list;
}
void wm_list_destroy(WmList *list) {
if (!list) return;
if (list->free_func) {
for (size_t i = 0; i < list->size; i++) {
list->free_func(list->data[i]);
}
}
free(list->data);
free(list);
}
void wm_list_destroy_no_free(WmList *list) {
if (!list) return;
free(list->data);
free(list);
}
WmList* wm_list_clone(const WmList *list) {
if (!list) return NULL;
WmList *clone = wm_list_new_sized(list->capacity);
if (!clone) return NULL;
memcpy(clone->data, list->data, list->size * sizeof(void*));
clone->size = list->size;
clone->free_func = list->free_func;
return clone;
}
void wm_list_set_free_func(WmList *list, WmFreeFunc func) {
if (list) list->free_func = func;
}
/*==============================================================================
* Capacity
*============================================================================*/
static bool wm_list_grow(WmList *list, size_t min_capacity) {
if (list->capacity >= min_capacity) return true;
size_t new_capacity = list->capacity * 2;
if (new_capacity < min_capacity) new_capacity = min_capacity;
void **new_data = realloc(list->data, new_capacity * sizeof(void*));
if (!new_data) return false;
list->data = new_data;
list->capacity = new_capacity;
return true;
}
size_t wm_list_size(const WmList *list) {
return list ? list->size : 0;
}
size_t wm_list_capacity(const WmList *list) {
return list ? list->capacity : 0;
}
bool wm_list_is_empty(const WmList *list) {
return !list || list->size == 0;
}
void wm_list_reserve(WmList *list, size_t capacity) {
if (!list) return;
wm_list_grow(list, capacity);
}
void wm_list_compact(WmList *list) {
if (!list || list->capacity <= list->size) return;
size_t new_capacity = list->size > 0 ? list->size : 1;
void **new_data = realloc(list->data, new_capacity * sizeof(void*));
if (new_data) {
list->data = new_data;
list->capacity = new_capacity;
}
}
void wm_list_clear(WmList *list) {
if (!list) return;
if (list->free_func) {
for (size_t i = 0; i < list->size; i++) {
list->free_func(list->data[i]);
}
}
list->size = 0;
}
/*==============================================================================
* Modifiers
*============================================================================*/
void wm_list_append(WmList *list, void *item) {
if (!list) return;
if (!wm_list_grow(list, list->size + 1)) return;
list->data[list->size++] = item;
}
void wm_list_prepend(WmList *list, void *item) {
wm_list_insert(list, 0, item);
}
void wm_list_insert(WmList *list, size_t index, void *item) {
if (!list || index > list->size) return;
if (!wm_list_grow(list, list->size + 1)) return;
memmove(&list->data[index + 1], &list->data[index],
(list->size - index) * sizeof(void*));
list->data[index] = item;
list->size++;
}
void wm_list_insert_sorted(WmList *list, void *item, WmCompareFunc compare) {
if (!list) return;
size_t i = 0;
while (i < list->size && compare(list->data[i], item) < 0) {
i++;
}
wm_list_insert(list, i, item);
}
void wm_list_remove(WmList *list, void *item) {
if (!list) return;
for (size_t i = 0; i < list->size; i++) {
if (list->data[i] == item) {
wm_list_remove_at(list, i);
return;
}
}
}
void wm_list_remove_at(WmList *list, size_t index) {
if (!list || index >= list->size) return;
if (list->free_func) {
list->free_func(list->data[index]);
}
memmove(&list->data[index], &list->data[index + 1],
(list->size - index - 1) * sizeof(void*));
list->size--;
}
void* wm_list_take_at(WmList *list, size_t index) {
if (!list || index >= list->size) return NULL;
void *item = list->data[index];
memmove(&list->data[index], &list->data[index + 1],
(list->size - index - 1) * sizeof(void*));
list->size--;
return item;
}
bool wm_list_remove_one(WmList *list, void *item) {
if (!list) return false;
for (size_t i = 0; i < list->size; i++) {
if (list->data[i] == item) {
wm_list_remove_at(list, i);
return true;
}
}
return false;
}
bool wm_list_remove_all(WmList *list, void *item) {
if (!list) return false;
bool removed = false;
for (size_t i = list->size; i-- > 0; ) {
if (list->data[i] == item) {
wm_list_remove_at(list, i);
removed = true;
}
}
return removed;
}
void* wm_list_pop_back(WmList *list) {
if (!list || list->size == 0) return NULL;
return list->data[--list->size];
}
void* wm_list_pop_front(WmList *list) {
return wm_list_take_at(list, 0);
}
/*==============================================================================
* Accessors
*============================================================================*/
void* wm_list_get(const WmList *list, size_t index) {
if (!list || index >= list->size) return NULL;
return list->data[index];
}
void* wm_list_first(const WmList *list) {
if (!list || list->size == 0) return NULL;
return list->data[0];
}
void* wm_list_last(const WmList *list) {
if (!list || list->size == 0) return NULL;
return list->data[list->size - 1];
}
void* wm_list_front(const WmList *list) {
return wm_list_first(list);
}
void* wm_list_back(const WmList *list) {
return wm_list_last(list);
}
void wm_list_set(WmList *list, size_t index, void *item) {
if (!list || index >= list->size) return;
if (list->free_func) {
list->free_func(list->data[index]);
}
list->data[index] = item;
}
/*==============================================================================
* Iteration
*============================================================================*/
void wm_list_foreach(const WmList *list, WmForeachFunc func, void *user_data) {
if (!list || !func) return;
for (size_t i = 0; i < list->size; i++) {
if (!func(list->data[i], i, user_data)) break;
}
}
void wm_list_foreach_reverse(const WmList *list, WmForeachFunc func, void *user_data) {
if (!list || !func) return;
for (size_t i = list->size; i-- > 0; ) {
if (!func(list->data[i], i, user_data)) break;
}
}
/*==============================================================================
* Search
*============================================================================*/
ssize_t wm_list_index_of(const WmList *list, void *item) {
if (!list) return -1;
for (size_t i = 0; i < list->size; i++) {
if (list->data[i] == item) return (ssize_t)i;
}
return -1;
}
bool wm_list_contains(const WmList *list, void *item) {
return wm_list_index_of(list, item) >= 0;
}
void* wm_list_find(const WmList *list, WmCompareFunc compare, const void *key) {
if (!list || !compare) return NULL;
for (size_t i = 0; i < list->size; i++) {
if (compare(list->data[i], key) == 0) return list->data[i];
}
return NULL;
}
ssize_t wm_list_find_index(const WmList *list, WmCompareFunc compare, const void *key) {
if (!list || !compare) return -1;
for (size_t i = 0; i < list->size; i++) {
if (compare(list->data[i], key) == 0) return (ssize_t)i;
}
return -1;
}
/*==============================================================================
* Sorting
*============================================================================*/
static void wm_list_qsort_helper(void **data, size_t left, size_t right,
WmCompareFunc compare) {
if (left >= right) return;
void *pivot = data[(left + right) / 2];
size_t i = left, j = right;
while (i <= j) {
while (compare(data[i], pivot) < 0) i++;
while (compare(data[j], pivot) > 0) j--;
if (i <= j) {
void *tmp = data[i];
data[i] = data[j];
data[j] = tmp;
i++;
if (j > 0) j--;
}
}
if (j > left) wm_list_qsort_helper(data, left, j, compare);
if (i < right) wm_list_qsort_helper(data, i, right, compare);
}
void wm_list_sort(WmList *list, WmCompareFunc compare) {
if (!list || list->size < 2) return;
wm_list_qsort_helper(list->data, 0, list->size - 1, compare);
}
/*==============================================================================
* Data Operations
*============================================================================*/
void** wm_list_data(WmList *list) {
return list ? list->data : NULL;
}
void* wm_list_steal(WmList *list, size_t index) {
return wm_list_take_at(list, index);
}
WmList* wm_list_slice(const WmList *list, size_t start, size_t end) {
if (!list || start >= list->size || start >= end) return wm_list_new();
if (end > list->size) end = list->size;
size_t count = end - start;
WmList *slice = wm_list_new_sized(count);
if (!slice) return NULL;
memcpy(slice->data, &list->data[start], count * sizeof(void*));
slice->size = count;
return slice;
}
void wm_list_move(WmList *list, size_t from, size_t to) {
if (!list || from >= list->size || to >= list->size || from == to) return;
void *item = list->data[from];
if (from < to) {
memmove(&list->data[from], &list->data[from + 1],
(to - from) * sizeof(void*));
} else {
memmove(&list->data[to + 1], &list->data[to],
(from - to) * sizeof(void*));
}
list->data[to] = item;
}
void wm_list_swap(WmList *list, size_t i, size_t j) {
if (!list || i >= list->size || j >= list->size) return;
void *tmp = list->data[i];
list->data[i] = list->data[j];
list->data[j] = tmp;
}
/*==============================================================================
* Comparison
*============================================================================*/
bool wm_list_equals(const WmList *list1, const WmList *list2) {
if (list1 == list2) return true;
if (!list1 || !list2) return false;
if (list1->size != list2->size) return false;
for (size_t i = 0; i < list1->size; i++) {
if (list1->data[i] != list2->data[i]) return false;
}
return true;
}
+650
View File
@@ -0,0 +1,650 @@
/*
* DWN - Desktop Window Manager
* Abstract String Implementation
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
#include <assert.h>
#include "core/wm_string.h"
#include "core/wm_types.h"
/*==============================================================================
* String Structure
*============================================================================*/
struct WmString {
char *data;
size_t length;
size_t capacity;
};
/*==============================================================================
* Internal Helpers
*============================================================================*/
static bool wm_string_grow(WmString *str, size_t min_capacity) {
if (str->capacity >= min_capacity) return true;
size_t new_capacity = str->capacity * 2;
if (new_capacity < 16) new_capacity = 16;
if (new_capacity < min_capacity) new_capacity = min_capacity;
char *new_data = realloc(str->data, new_capacity);
if (!new_data) return false;
str->data = new_data;
str->capacity = new_capacity;
return true;
}
/*==============================================================================
* Lifecycle
*============================================================================*/
WmString* wm_string_new(const char *str) {
if (!str) return wm_string_new_empty();
return wm_string_new_n(str, strlen(str));
}
WmString* wm_string_new_empty(void) {
WmString *s = calloc(1, sizeof(WmString));
if (!s) return NULL;
s->data = malloc(1);
if (!s->data) {
free(s);
return NULL;
}
s->data[0] = '\0';
s->length = 0;
s->capacity = 1;
return s;
}
WmString* wm_string_new_sized(size_t capacity) {
WmString *s = calloc(1, sizeof(WmString));
if (!s) return NULL;
s->data = malloc(capacity + 1);
if (!s->data) {
free(s);
return NULL;
}
s->data[0] = '\0';
s->length = 0;
s->capacity = capacity + 1;
return s;
}
WmString* wm_string_new_printf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
WmString *s = wm_string_new_vprintf(fmt, args);
va_end(args);
return s;
}
WmString* wm_string_new_vprintf(const char *fmt, va_list args) {
va_list args_copy;
va_copy(args_copy, args);
int len = vsnprintf(NULL, 0, fmt, args_copy);
va_end(args_copy);
if (len < 0) return NULL;
WmString *s = wm_string_new_sized(len + 1);
if (!s) return NULL;
vsnprintf(s->data, s->capacity, fmt, args);
s->length = len;
return s;
}
WmString* wm_string_new_n(const char *str, size_t n) {
if (!str) return wm_string_new_empty();
WmString *s = calloc(1, sizeof(WmString));
if (!s) return NULL;
s->data = malloc(n + 1);
if (!s->data) {
free(s);
return NULL;
}
memcpy(s->data, str, n);
s->data[n] = '\0';
s->length = n;
s->capacity = n + 1;
return s;
}
void wm_string_destroy(WmString *str) {
if (!str) return;
free(str->data);
free(str);
}
WmString* wm_string_clone(const WmString *str) {
if (!str) return NULL;
return wm_string_new_n(str->data, str->length);
}
/*==============================================================================
* Operations
*============================================================================*/
void wm_string_append(WmString *str, const char *suffix) {
if (!str || !suffix) return;
wm_string_append_n(str, suffix, strlen(suffix));
}
void wm_string_append_char(WmString *str, char c) {
if (!str) return;
if (!wm_string_grow(str, str->length + 2)) return;
str->data[str->length++] = c;
str->data[str->length] = '\0';
}
void wm_string_append_n(WmString *str, const char *suffix, size_t n) {
if (!str || !suffix || n == 0) return;
if (!wm_string_grow(str, str->length + n + 1)) return;
memcpy(str->data + str->length, suffix, n);
str->length += n;
str->data[str->length] = '\0';
}
void wm_string_append_printf(WmString *str, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
wm_string_append_vprintf(str, fmt, args);
va_end(args);
}
void wm_string_append_vprintf(WmString *str, const char *fmt, va_list args) {
if (!str || !fmt) return;
va_list args_copy;
va_copy(args_copy, args);
int len = vsnprintf(NULL, 0, fmt, args_copy);
va_end(args_copy);
if (len < 0) return;
if (!wm_string_grow(str, str->length + len + 1)) return;
vsnprintf(str->data + str->length, str->capacity - str->length, fmt, args);
str->length += len;
}
void wm_string_append_string(WmString *str, const WmString *suffix) {
if (!suffix) return;
wm_string_append_n(str, suffix->data, suffix->length);
}
void wm_string_prepend(WmString *str, const char *prefix) {
if (!str || !prefix) return;
size_t prefix_len = strlen(prefix);
if (prefix_len == 0) return;
if (!wm_string_grow(str, str->length + prefix_len + 1)) return;
memmove(str->data + prefix_len, str->data, str->length + 1);
memcpy(str->data, prefix, prefix_len);
str->length += prefix_len;
}
void wm_string_prepend_char(WmString *str, char c) {
if (!str) return;
if (!wm_string_grow(str, str->length + 2)) return;
memmove(str->data + 1, str->data, str->length + 1);
str->data[0] = c;
str->length++;
}
void wm_string_insert(WmString *str, size_t pos, const char *insert) {
if (!str || !insert || pos > str->length) return;
size_t insert_len = strlen(insert);
if (insert_len == 0) return;
if (!wm_string_grow(str, str->length + insert_len + 1)) return;
memmove(str->data + pos + insert_len, str->data + pos, str->length - pos + 1);
memcpy(str->data + pos, insert, insert_len);
str->length += insert_len;
}
void wm_string_insert_char(WmString *str, size_t pos, char c) {
if (!str || pos > str->length) return;
if (!wm_string_grow(str, str->length + 2)) return;
memmove(str->data + pos + 1, str->data + pos, str->length - pos + 1);
str->data[pos] = c;
str->length++;
}
void wm_string_insert_string(WmString *str, size_t pos, const WmString *insert) {
if (!insert) return;
wm_string_insert(str, pos, insert->data);
}
void wm_string_erase(WmString *str, size_t pos, size_t len) {
if (!str || pos >= str->length) return;
if (len > str->length - pos) len = str->length - pos;
memmove(str->data + pos, str->data + pos + len, str->length - pos - len + 1);
str->length -= len;
}
void wm_string_clear(WmString *str) {
if (!str) return;
str->length = 0;
str->data[0] = '\0';
}
/*==============================================================================
* Queries
*============================================================================*/
const char* wm_string_cstr(const WmString *str) {
return str ? str->data : "";
}
char* wm_string_detach(WmString *str) {
if (!str) return NULL;
char *data = str->data;
free(str);
return data;
}
size_t wm_string_length(const WmString *str) {
return str ? str->length : 0;
}
size_t wm_string_capacity(const WmString *str) {
return str ? str->capacity : 0;
}
size_t wm_string_bytes(const WmString *str) {
return str ? str->length + 1 : 0;
}
bool wm_string_is_empty(const WmString *str) {
return !str || str->length == 0;
}
bool wm_string_is_null(const WmString *str) {
return str == NULL;
}
char wm_string_char_at(const WmString *str, size_t pos) {
if (!str || pos >= str->length) return '\0';
return str->data[pos];
}
/*==============================================================================
* Comparison
*============================================================================*/
bool wm_string_equals(const WmString *str1, const WmString *str2) {
if (str1 == str2) return true;
if (!str1 || !str2) return false;
if (str1->length != str2->length) return false;
return memcmp(str1->data, str2->data, str1->length) == 0;
}
bool wm_string_equals_cstr(const WmString *str, const char *cstr) {
if (!str) return !cstr || cstr[0] == '\0';
if (!cstr) return str->length == 0;
return strcmp(str->data, cstr) == 0;
}
int wm_string_compare(const WmString *str1, const WmString *str2) {
if (str1 == str2) return 0;
if (!str1) return -1;
if (!str2) return 1;
return strcmp(str1->data, str2->data);
}
int wm_string_compare_cstr(const WmString *str, const char *cstr) {
if (!str) return cstr ? -1 : 0;
if (!cstr) return 1;
return strcmp(str->data, cstr);
}
int wm_string_case_compare(const WmString *str1, const WmString *str2) {
if (str1 == str2) return 0;
if (!str1) return -1;
if (!str2) return 1;
return strcasecmp(str1->data, str2->data);
}
int wm_string_case_compare_cstr(const WmString *str, const char *cstr) {
if (!str) return cstr ? -1 : 0;
if (!cstr) return 1;
return strcasecmp(str->data, cstr);
}
/*==============================================================================
* Searching
*============================================================================*/
bool wm_string_contains(const WmString *str, const char *needle) {
if (!str || !needle) return false;
return strstr(str->data, needle) != NULL;
}
bool wm_string_contains_char(const WmString *str, char c) {
if (!str) return false;
return strchr(str->data, c) != NULL;
}
size_t wm_string_find(const WmString *str, const char *needle, size_t start) {
if (!str || !needle || start > str->length) return (size_t)-1;
const char *found = strstr(str->data + start, needle);
return found ? (size_t)(found - str->data) : (size_t)-1;
}
size_t wm_string_find_char(const WmString *str, char c, size_t start) {
if (!str || start > str->length) return (size_t)-1;
const char *found = strchr(str->data + start, c);
return found ? (size_t)(found - str->data) : (size_t)-1;
}
size_t wm_string_find_last(const WmString *str, const char *needle) {
if (!str || !needle) return (size_t)-1;
/* Simple implementation since strrstr is not standard */
size_t needle_len = strlen(needle);
if (needle_len == 0) return str->length;
for (size_t i = str->length - needle_len + 1; i-- > 0; ) {
if (memcmp(str->data + i, needle, needle_len) == 0) {
return i;
}
}
return (size_t)-1;
}
size_t wm_string_find_last_char(const WmString *str, char c) {
if (!str) return (size_t)-1;
const char *found = strrchr(str->data, c);
return found ? (size_t)(found - str->data) : (size_t)-1;
}
bool wm_string_starts_with(const WmString *str, const char *prefix) {
if (!str || !prefix) return false;
size_t prefix_len = strlen(prefix);
if (prefix_len > str->length) return false;
return strncmp(str->data, prefix, prefix_len) == 0;
}
bool wm_string_starts_with_char(const WmString *str, char c) {
return str && str->length > 0 && str->data[0] == c;
}
bool wm_string_ends_with(const WmString *str, const char *suffix) {
if (!str || !suffix) return false;
size_t suffix_len = strlen(suffix);
if (suffix_len > str->length) return false;
return strncmp(str->data + str->length - suffix_len, suffix, suffix_len) == 0;
}
bool wm_string_ends_with_char(const WmString *str, char c) {
return str && str->length > 0 && str->data[str->length - 1] == c;
}
/*==============================================================================
* Modification
*============================================================================*/
void wm_string_trim(WmString *str) {
wm_string_trim_left(str);
wm_string_trim_right(str);
}
void wm_string_trim_left(WmString *str) {
if (!str) return;
size_t i = 0;
while (i < str->length && isspace((unsigned char)str->data[i])) i++;
if (i > 0) {
memmove(str->data, str->data + i, str->length - i + 1);
str->length -= i;
}
}
void wm_string_trim_right(WmString *str) {
if (!str) return;
while (str->length > 0 && isspace((unsigned char)str->data[str->length - 1])) {
str->data[--str->length] = '\0';
}
}
void wm_string_replace(WmString *str, const char *search, const char *replace) {
if (!str || !search || !replace) return;
size_t count = wm_string_replace_all(str, search, replace);
(void)count;
}
void wm_string_replace_char(WmString *str, char search, char replace) {
if (!str) return;
for (size_t i = 0; i < str->length; i++) {
if (str->data[i] == search) str->data[i] = replace;
}
}
size_t wm_string_replace_all(WmString *str, const char *search, const char *replace) {
if (!str || !search || !replace) return 0;
size_t search_len = strlen(search);
size_t replace_len = strlen(replace);
size_t count = 0;
char *pos = str->data;
while ((pos = strstr(pos, search)) != NULL) {
count++;
pos += search_len;
}
if (count == 0) return 0;
size_t new_length = str->length + count * (replace_len - search_len);
if (!wm_string_grow(str, new_length + 1)) return 0;
WmString *result = wm_string_new_sized(new_length);
if (!result) return 0;
char *src = str->data;
char *dst = result->data;
while ((pos = strstr(src, search)) != NULL) {
size_t prefix_len = pos - src;
memcpy(dst, src, prefix_len);
dst += prefix_len;
memcpy(dst, replace, replace_len);
dst += replace_len;
src = pos + search_len;
}
size_t remaining = new_length - (size_t)(dst - result->data);
strncpy(dst, src, remaining);
dst[remaining] = '\0';
result->length = new_length;
free(str->data);
str->data = result->data;
str->length = result->length;
str->capacity = result->capacity;
free(result);
return count;
}
void wm_string_to_lower(WmString *str) {
if (!str) return;
for (size_t i = 0; i < str->length; i++) {
str->data[i] = tolower((unsigned char)str->data[i]);
}
}
void wm_string_to_upper(WmString *str) {
if (!str) return;
for (size_t i = 0; i < str->length; i++) {
str->data[i] = toupper((unsigned char)str->data[i]);
}
}
void wm_string_reverse(WmString *str) {
if (!str) return;
for (size_t i = 0, j = str->length - 1; i < j; i++, j--) {
char tmp = str->data[i];
str->data[i] = str->data[j];
str->data[j] = tmp;
}
}
/*==============================================================================
* Substrings
*============================================================================*/
WmString* wm_string_substring(const WmString *str, size_t start, size_t len) {
if (!str || start > str->length) return wm_string_new_empty();
if (start + len > str->length) len = str->length - start;
return wm_string_new_n(str->data + start, len);
}
WmString* wm_string_left(const WmString *str, size_t n) {
if (!str) return wm_string_new_empty();
if (n > str->length) n = str->length;
return wm_string_new_n(str->data, n);
}
WmString* wm_string_right(const WmString *str, size_t n) {
if (!str) return wm_string_new_empty();
if (n > str->length) n = str->length;
return wm_string_new_n(str->data + str->length - n, n);
}
/*==============================================================================
* Formatting
*============================================================================*/
void wm_string_printf(WmString *str, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
wm_string_clear(str);
wm_string_append_vprintf(str, fmt, args);
va_end(args);
}
void wm_string_vprintf(WmString *str, const char *fmt, va_list args) {
wm_string_clear(str);
wm_string_append_vprintf(str, fmt, args);
}
/*==============================================================================
* Conversion
*============================================================================*/
int wm_string_to_int(const WmString *str, int default_val) {
if (!str || str->length == 0) return default_val;
char *end;
long val = strtol(str->data, &end, 10);
if (end == str->data) return default_val;
return (int)val;
}
long wm_string_to_long(const WmString *str, long default_val) {
if (!str || str->length == 0) return default_val;
char *end;
long val = strtol(str->data, &end, 10);
if (end == str->data) return default_val;
return val;
}
float wm_string_to_float(const WmString *str, float default_val) {
if (!str || str->length == 0) return default_val;
char *end;
float val = strtof(str->data, &end);
if (end == str->data) return default_val;
return val;
}
double wm_string_to_double(const WmString *str, double default_val) {
if (!str || str->length == 0) return default_val;
char *end;
double val = strtod(str->data, &end);
if (end == str->data) return default_val;
return val;
}
bool wm_string_to_bool(const WmString *str, bool default_val) {
if (!str || str->length == 0) return default_val;
if (strcasecmp(str->data, "true") == 0 ||
strcmp(str->data, "1") == 0 ||
strcasecmp(str->data, "yes") == 0) {
return true;
}
if (strcasecmp(str->data, "false") == 0 ||
strcmp(str->data, "0") == 0 ||
strcasecmp(str->data, "no") == 0) {
return false;
}
return default_val;
}
WmString* wm_string_from_int(int val) {
return wm_string_new_printf("%d", val);
}
WmString* wm_string_from_long(long val) {
return wm_string_new_printf("%ld", val);
}
WmString* wm_string_from_float(float val, int precision) {
return wm_string_new_printf("%.*f", precision, val);
}
WmString* wm_string_from_double(double val, int precision) {
return wm_string_new_printf("%.*lf", precision, val);
}
WmString* wm_string_from_bool(bool val) {
return wm_string_new(val ? "true" : "false");
}
/*==============================================================================
* Hash
*============================================================================*/
uint32_t wm_string_hash(const WmString *str) {
if (!str) return 0;
return wm_string_hash_cstr(str->data);
}
uint32_t wm_string_hash_cstr(const char *str) {
if (!str) return 0;
/* FNV-1a hash */
uint32_t hash = 2166136261u;
while (*str) {
hash ^= (uint8_t)*str++;
hash *= 16777619u;
}
return hash;
}
+4 -2
View File
@@ -164,8 +164,10 @@ void decorations_render_title_bar(Client *client, bool focused)
return;
}
char display_title[256];
strncpy(display_title, client->title, sizeof(display_title) - 4);
display_title[sizeof(display_title) - 4] = '\0';
size_t disp_len = strlen(client->title);
if (disp_len >= sizeof(display_title) - 3) disp_len = sizeof(display_title) - 4;
memcpy(display_title, client->title, disp_len);
display_title[disp_len] = '\0';
XGlyphInfo extents;
XftTextExtentsUtf8(dpy, title_font,
+329
View File
@@ -0,0 +1,329 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* Event Bus Implementation - Thread-Safe Pub/Sub
*/
#include "threading.h"
#include "util.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/eventfd.h>
#define MAX_SUBSCRIPTIONS_PER_TYPE 64
#define EVENT_QUEUE_SIZE 4096
/* ============================================================================
* Event Bus Types
* ============================================================================ */
typedef struct Subscription {
SubscriptionId id;
EventType type;
EventHandler handler;
void *user_data;
EventFilter filter;
void *filter_data;
bool active;
} Subscription;
typedef struct EventNode {
EventType type;
void *data;
void (*free_fn)(void*);
struct EventNode *next;
} EventNode;
struct EventBus {
Subscription subscriptions[MAX_SUBSCRIPTIONS_PER_TYPE * 32]; /* Fixed pool */
uint32_t subscription_count;
_Atomic SubscriptionId next_id;
/* Event queue (MPSC) */
pthread_mutex_t queue_mutex;
EventNode *event_head;
EventNode *event_tail;
_Atomic uint32_t event_count;
int event_fd;
_Atomic int shutdown;
uint32_t batch_size;
pthread_mutex_t sub_mutex;
};
static SubscriptionId generate_subscription_id(EventBus *bus)
{
return atomic_fetch_add_explicit(&bus->next_id, 1, ATOMIC_RELAXED) + 1;
}
/* ============================================================================
* Event Bus Implementation
* ============================================================================ */
EventBus* event_bus_create(void)
{
EventBus *bus = dwn_malloc(sizeof(EventBus));
if (!bus) return NULL;
memset(bus->subscriptions, 0, sizeof(bus->subscriptions));
bus->subscription_count = 0;
atomic_store_explicit(&bus->next_id, 0, ATOMIC_RELEASE);
bus->event_head = NULL;
bus->event_tail = NULL;
atomic_store_explicit(&bus->event_count, 0, ATOMIC_RELEASE);
atomic_store_explicit(&bus->shutdown, 0, ATOMIC_RELEASE);
bus->batch_size = 100;
if (pthread_mutex_init(&bus->queue_mutex, NULL) != 0) {
dwn_free(bus);
return NULL;
}
if (pthread_mutex_init(&bus->sub_mutex, NULL) != 0) {
pthread_mutex_destroy(&bus->queue_mutex);
dwn_free(bus);
return NULL;
}
bus->event_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (bus->event_fd < 0) {
pthread_mutex_destroy(&bus->sub_mutex);
pthread_mutex_destroy(&bus->queue_mutex);
dwn_free(bus);
return NULL;
}
return bus;
}
void event_bus_destroy(EventBus *bus)
{
if (!bus) return;
atomic_store_explicit(&bus->shutdown, 1, ATOMIC_RELEASE);
/* Drain remaining events */
event_bus_process(bus);
/* Free remaining events */
pthread_mutex_lock(&bus->queue_mutex);
EventNode *node = bus->event_head;
while (node) {
EventNode *next = node->next;
if (node->free_fn) {
node->free_fn(node->data);
}
dwn_free(node);
node = next;
}
pthread_mutex_unlock(&bus->queue_mutex);
close(bus->event_fd);
pthread_mutex_destroy(&bus->sub_mutex);
pthread_mutex_destroy(&bus->queue_mutex);
dwn_free(bus);
}
SubscriptionId event_bus_subscribe(EventBus *bus, EventType type,
EventHandler handler, void *user_data)
{
return event_bus_subscribe_filtered(bus, type, handler, user_data, NULL, NULL);
}
SubscriptionId event_bus_subscribe_filtered(EventBus *bus, EventType type,
EventHandler handler, void *user_data,
EventFilter filter, void *filter_data)
{
if (!bus || !handler || type >= 32) return 0;
pthread_mutex_lock(&bus->sub_mutex);
if (bus->subscription_count >= sizeof(bus->subscriptions) / sizeof(bus->subscriptions[0])) {
pthread_mutex_unlock(&bus->sub_mutex);
return 0;
}
/* Find slot */
for (uint32_t i = 0; i < sizeof(bus->subscriptions) / sizeof(bus->subscriptions[0]); i++) {
if (!bus->subscriptions[i].active) {
Subscription *sub = &bus->subscriptions[i];
sub->id = generate_subscription_id(bus);
sub->type = type;
sub->handler = handler;
sub->user_data = user_data;
sub->filter = filter;
sub->filter_data = filter_data;
sub->active = true;
bus->subscription_count++;
pthread_mutex_unlock(&bus->sub_mutex);
return sub->id;
}
}
pthread_mutex_unlock(&bus->sub_mutex);
return 0;
}
bool event_bus_unsubscribe(EventBus *bus, SubscriptionId id)
{
if (!bus || id == 0) return false;
pthread_mutex_lock(&bus->sub_mutex);
for (uint32_t i = 0; i < sizeof(bus->subscriptions) / sizeof(bus->subscriptions[0]); i++) {
if (bus->subscriptions[i].active && bus->subscriptions[i].id == id) {
bus->subscriptions[i].active = false;
bus->subscription_count--;
pthread_mutex_unlock(&bus->sub_mutex);
return true;
}
}
pthread_mutex_unlock(&bus->sub_mutex);
return false;
}
void event_bus_publish(EventBus *bus, EventType type, void *event_data)
{
event_bus_publish_owned(bus, type, event_data, NULL);
}
void event_bus_publish_owned(EventBus *bus, EventType type, void *event_data,
void (*free_fn)(void*))
{
if (!bus || type >= 32) {
if (free_fn && event_data) free_fn(event_data);
return;
}
if (atomic_load_explicit(&bus->shutdown, ATOMIC_ACQUIRE)) {
if (free_fn && event_data) free_fn(event_data);
return;
}
EventNode *node = dwn_malloc(sizeof(EventNode));
if (!node) {
if (free_fn && event_data) free_fn(event_data);
return;
}
node->type = type;
node->data = event_data;
node->free_fn = free_fn;
node->next = NULL;
pthread_mutex_lock(&bus->queue_mutex);
if (bus->event_tail) {
bus->event_tail->next = node;
} else {
bus->event_head = node;
}
bus->event_tail = node;
atomic_fetch_add_explicit(&bus->event_count, 1, ATOMIC_RELAXED);
pthread_mutex_unlock(&bus->queue_mutex);
/* Signal via eventfd */
uint64_t one = 1;
ssize_t w __attribute__((unused)) = write(bus->event_fd, &one, sizeof(one));
}
uint32_t event_bus_process(EventBus *bus)
{
if (!bus) return 0;
/* Acknowledge eventfd */
uint64_t val;
ssize_t r __attribute__((unused)) = read(bus->event_fd, &val, sizeof(val));
uint32_t processed = 0;
while (processed < bus->batch_size) {
/* Dequeue event */
pthread_mutex_lock(&bus->queue_mutex);
EventNode *node = bus->event_head;
if (!node) {
pthread_mutex_unlock(&bus->queue_mutex);
break;
}
bus->event_head = node->next;
if (!bus->event_head) {
bus->event_tail = NULL;
}
atomic_fetch_sub_explicit(&bus->event_count, 1, ATOMIC_RELAXED);
pthread_mutex_unlock(&bus->queue_mutex);
/* Dispatch to subscribers */
pthread_mutex_lock(&bus->sub_mutex);
for (uint32_t i = 0; i < sizeof(bus->subscriptions) / sizeof(bus->subscriptions[0]); i++) {
Subscription *sub = &bus->subscriptions[i];
if (sub->active && sub->type == node->type) {
/* Check filter if present */
bool should_handle = true;
if (sub->filter) {
should_handle = sub->filter(node->type, node->data, sub->filter_data);
}
if (should_handle) {
sub->handler(node->type, node->data, sub->user_data);
}
}
}
pthread_mutex_unlock(&bus->sub_mutex);
/* Free event data */
if (node->free_fn) {
node->free_fn(node->data);
}
dwn_free(node);
processed++;
}
return processed;
}
void event_bus_set_batch_size(EventBus *bus, uint32_t batch_size)
{
if (!bus) return;
bus->batch_size = batch_size ? batch_size : 100;
}
/* ============================================================================
* Default Event Bus
* ============================================================================ */
static EventBus *g_default_bus = NULL;
EventBus* event_bus_default(void)
{
return g_default_bus;
}
bool event_bus_init_default(void)
{
if (g_default_bus) return true;
g_default_bus = event_bus_create();
return g_default_bus != NULL;
}
void event_bus_shutdown_default(void)
{
if (g_default_bus) {
event_bus_destroy(g_default_bus);
g_default_bus = NULL;
}
}
+333
View File
@@ -0,0 +1,333 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* Future/Promise Implementation - Async Result Handling
*/
#include "threading.h"
#include "util.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
/* ============================================================================
* Future Implementation
* ============================================================================ */
typedef struct FutureCallbackNode {
FutureCallback callback;
void *user_data;
struct FutureCallbackNode *next;
} FutureCallbackNode;
struct Future {
pthread_mutex_t mutex;
pthread_cond_t ready;
FutureResult result;
int error_code;
_Atomic int ready_flag;
_Atomic int has_result;
FutureCallbackNode *callbacks;
_Atomic int callback_count;
};
Future* future_create(void)
{
Future *f = dwn_malloc(sizeof(Future));
if (!f) return NULL;
atomic_store_explicit(&f->ready_flag, 0, ATOMIC_RELEASE);
atomic_store_explicit(&f->has_result, 0, ATOMIC_RELEASE);
atomic_store_explicit(&f->callback_count, 0, ATOMIC_RELAXED);
f->result = NULL;
f->error_code = 0;
f->callbacks = NULL;
if (pthread_mutex_init(&f->mutex, NULL) != 0) {
dwn_free(f);
return NULL;
}
if (pthread_cond_init(&f->ready, NULL) != 0) {
pthread_mutex_destroy(&f->mutex);
dwn_free(f);
return NULL;
}
return f;
}
void future_destroy(Future *f)
{
if (!f) return;
/* Free callback chain */
FutureCallbackNode *node = f->callbacks;
while (node) {
FutureCallbackNode *next = node->next;
dwn_free(node);
node = next;
}
pthread_cond_destroy(&f->ready);
pthread_mutex_destroy(&f->mutex);
dwn_free(f);
}
void future_set_result(Future *f, FutureResult result)
{
if (!f) return;
pthread_mutex_lock(&f->mutex);
if (atomic_load_explicit(&f->has_result, ATOMIC_ACQUIRE)) {
pthread_mutex_unlock(&f->mutex);
return; /* Already set */
}
f->result = result;
f->error_code = 0;
atomic_store_explicit(&f->has_result, 1, ATOMIC_RELEASE);
atomic_store_explicit(&f->ready_flag, 1, ATOMIC_RELEASE);
/* Execute callbacks */
FutureCallbackNode *node = f->callbacks;
while (node) {
node->callback(f, result, node->user_data);
node = node->next;
}
pthread_cond_broadcast(&f->ready);
pthread_mutex_unlock(&f->mutex);
}
void future_set_error(Future *f, int error_code)
{
if (!f) return;
pthread_mutex_lock(&f->mutex);
if (atomic_load_explicit(&f->has_result, ATOMIC_ACQUIRE)) {
pthread_mutex_unlock(&f->mutex);
return;
}
f->result = NULL;
f->error_code = error_code;
atomic_store_explicit(&f->has_result, 1, ATOMIC_RELEASE);
atomic_store_explicit(&f->ready_flag, 1, ATOMIC_RELEASE);
/* Execute callbacks with NULL result */
FutureCallbackNode *node = f->callbacks;
while (node) {
node->callback(f, NULL, node->user_data);
node = node->next;
}
pthread_cond_broadcast(&f->ready);
pthread_mutex_unlock(&f->mutex);
}
FutureResult future_get(Future *f, ThreadStatus *status)
{
return future_get_timeout(f, 0, status);
}
FutureResult future_get_timeout(Future *f, uint64_t timeout_ms, ThreadStatus *status)
{
if (!f) {
if (status) *status = THREAD_ERROR_INVALID;
return NULL;
}
pthread_mutex_lock(&f->mutex);
if (!atomic_load_explicit(&f->ready_flag, ATOMIC_ACQUIRE)) {
if (timeout_ms == 0) {
pthread_cond_wait(&f->ready, &f->mutex);
} else {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += timeout_ms / 1000;
ts.tv_nsec += (timeout_ms % 1000) * 1000000;
if (ts.tv_nsec >= 1000000000) {
ts.tv_sec++;
ts.tv_nsec -= 1000000000;
}
int ret = pthread_cond_timedwait(&f->ready, &f->mutex, &ts);
if (ret == ETIMEDOUT) {
pthread_mutex_unlock(&f->mutex);
if (status) *status = THREAD_ERROR_TIMEOUT;
return NULL;
}
}
}
FutureResult result = f->result;
if (status) {
*status = (f->error_code != 0) ? THREAD_ERROR : THREAD_OK;
}
pthread_mutex_unlock(&f->mutex);
return result;
}
bool future_is_ready(Future *f)
{
if (!f) return false;
return atomic_load_explicit(&f->ready_flag, ATOMIC_ACQUIRE) != 0;
}
void future_then(Future *f, FutureCallback callback, void *user_data)
{
if (!f || !callback) return;
pthread_mutex_lock(&f->mutex);
/* If already ready, execute immediately */
if (atomic_load_explicit(&f->ready_flag, ATOMIC_ACQUIRE)) {
pthread_mutex_unlock(&f->mutex);
callback(f, f->result, user_data);
return;
}
/* Add to callback chain */
FutureCallbackNode *node = dwn_malloc(sizeof(FutureCallbackNode));
if (!node) {
pthread_mutex_unlock(&f->mutex);
return;
}
node->callback = callback;
node->user_data = user_data;
node->next = f->callbacks;
f->callbacks = node;
atomic_fetch_add_explicit(&f->callback_count, 1, ATOMIC_RELAXED);
pthread_mutex_unlock(&f->mutex);
}
/* ============================================================================
* Composite Futures
* ============================================================================ */
typedef struct {
Future *composite;
_Atomic int remaining;
uint32_t total;
pthread_mutex_t mutex;
} CompositeFutureData;
static void all_callback(Future *f, FutureResult result, void *user_data)
{
(void)f;
(void)result;
CompositeFutureData *data = user_data;
int rem = atomic_fetch_sub_explicit(&data->remaining, 1, ATOMIC_ACQ_REL) - 1;
if (rem == 0) {
future_set_result(data->composite, (void*)(uintptr_t)data->total);
}
}
Future* future_all(Future **futures, uint32_t count)
{
if (!futures || count == 0) return NULL;
Future *composite = future_create();
if (!composite) return NULL;
if (count == 1) {
/* Optimize single future */
FutureResult r = future_get(futures[0], NULL);
future_set_result(composite, r);
return composite;
}
CompositeFutureData *data = dwn_malloc(sizeof(CompositeFutureData));
if (!data) {
future_destroy(composite);
return NULL;
}
data->composite = composite;
atomic_store_explicit(&data->remaining, count, ATOMIC_RELEASE);
data->total = count;
pthread_mutex_init(&data->mutex, NULL);
/* Attach callback to each future */
for (uint32_t i = 0; i < count; i++) {
if (future_is_ready(futures[i])) {
/* Already done */
if (atomic_fetch_sub_explicit(&data->remaining, 1, ATOMIC_ACQ_REL) - 1 == 0) {
future_set_result(composite, (void*)(uintptr_t)count);
pthread_mutex_destroy(&data->mutex);
dwn_free(data);
return composite;
}
} else {
future_then(futures[i], all_callback, data);
}
}
return composite;
}
static void any_callback(Future *f, FutureResult result, void *user_data)
{
(void)f;
CompositeFutureData *data = user_data;
pthread_mutex_lock(&data->mutex);
if (!future_is_ready(data->composite)) {
future_set_result(data->composite, result);
}
pthread_mutex_unlock(&data->mutex);
}
Future* future_any(Future **futures, uint32_t count)
{
if (!futures || count == 0) return NULL;
Future *composite = future_create();
if (!composite) return NULL;
if (count == 1) {
FutureResult r = future_get(futures[0], NULL);
future_set_result(composite, r);
return composite;
}
CompositeFutureData *data = dwn_malloc(sizeof(CompositeFutureData));
if (!data) {
future_destroy(composite);
return NULL;
}
data->composite = composite;
pthread_mutex_init(&data->mutex, NULL);
/* Attach callback to each future */
for (uint32_t i = 0; i < count; i++) {
if (future_is_ready(futures[i])) {
future_set_result(composite, futures[i]->result);
pthread_mutex_destroy(&data->mutex);
dwn_free(data);
return composite;
} else {
future_then(futures[i], any_callback, data);
}
}
return composite;
}
+248
View File
@@ -17,6 +17,7 @@
#include "demo.h"
#include "layout.h"
#include "api.h"
#include "marks.h"
#include <stdio.h>
#include <string.h>
@@ -71,6 +72,7 @@ void key_news_open(void);
void key_show_shortcuts(void);
void key_start_tutorial(void);
void key_screenshot(void);
void key_kill_all_clients(void);
static KeyBinding bindings[MAX_KEYBINDINGS];
static int binding_count = 0;
@@ -436,6 +438,21 @@ void keys_handle_press(XKeyEvent *ev)
KeySym keysym = XLookupKeysym(ev, 0);
if (marks_is_waiting_for_mark() || marks_is_waiting_for_goto()) {
char key_buf[32] = {0};
XLookupString(ev, key_buf, sizeof(key_buf) - 1, NULL, NULL);
if (keysym == XK_Escape) {
marks_cancel_mode();
return;
}
if (key_buf[0] != '\0') {
if (marks_handle_key(key_buf[0])) {
return;
}
}
}
if (keysym == XK_Super_L || keysym == XK_Super_R) {
super_pressed = true;
@@ -578,6 +595,21 @@ void keys_setup_defaults(void)
keys_bind(MOD_SUPER, XK_Return, key_news_open, "Open news article");
keys_bind(0, XK_Print, key_screenshot, "Take screenshot");
keys_bind(MOD_SUPER, XK_k, key_kill_all_clients, "Kill all applications");
keys_bind(MOD_SUPER | MOD_ALT, XK_Left, key_move_window_left, "Move window left");
keys_bind(MOD_SUPER | MOD_ALT, XK_Right, key_move_window_right, "Move window right");
keys_bind(MOD_SUPER | MOD_ALT, XK_Up, key_move_window_up, "Move window up");
keys_bind(MOD_SUPER | MOD_ALT, XK_Down, key_move_window_down, "Move window down");
keys_bind(MOD_SUPER | MOD_CTRL, XK_Left, key_resize_window_left, "Shrink window width");
keys_bind(MOD_SUPER | MOD_CTRL, XK_Right, key_resize_window_right, "Grow window width");
keys_bind(MOD_SUPER | MOD_CTRL, XK_Up, key_resize_window_up, "Shrink window height");
keys_bind(MOD_SUPER | MOD_CTRL, XK_Down, key_resize_window_down, "Grow window height");
keys_bind(MOD_SUPER, XK_m, key_set_mark, "Set window mark");
keys_bind(MOD_SUPER, XK_apostrophe, key_goto_mark, "Go to marked window");
}
@@ -614,6 +646,22 @@ void key_close_window(void)
}
}
void key_kill_all_clients(void)
{
if (dwn == NULL || dwn->client_list == NULL) {
return;
}
Client *c = dwn->client_list;
while (c != NULL) {
Client *next = c->next;
if (c->workspace == (unsigned int)dwn->current_workspace) {
client_kill(c);
}
c = next;
}
}
void key_quit_dwn(void)
{
LOG_INFO("Quit requested via keyboard shortcut");
@@ -889,6 +937,7 @@ void key_show_shortcuts(void)
"Alt+F10 Toggle maximize\n"
"Alt+F11 Toggle fullscreen\n"
"Super+F9 Toggle floating\n"
"Super+K Kill all applications\n"
"\n"
"=== Workspaces ===\n"
"F1-F9 Switch to workspace\n"
@@ -909,6 +958,14 @@ void key_show_shortcuts(void)
"Super+Up Top 50% (2x=full height)\n"
"Super+Down Bottom 50% (2x=full height)\n"
"\n"
"=== Keyboard Window Control ===\n"
"Super+Alt+Arrow Move window by 20px\n"
"Super+Ctrl+Arrow Resize window by 20px\n"
"\n"
"=== Window Marks ===\n"
"Super+M then a-z Set mark for window\n"
"Super+' then a-z Jump to marked window\n"
"\n"
"=== AI Features ===\n"
"Super+A AI command palette\n"
"Super+Shift+A Show AI context\n"
@@ -1088,3 +1145,194 @@ void key_start_demo(void)
demo_start();
}
}
#define KEYBOARD_MOVE_STEP 20
#define KEYBOARD_RESIZE_STEP 20
void key_move_window_left(void)
{
Workspace *ws = workspace_get_current();
if (ws == NULL || ws->focused == NULL) {
return;
}
Client *c = ws->focused;
if (!client_is_floating(c)) {
client_set_floating(c, true);
workspace_arrange_current();
}
c->snap.horizontal = SNAP_H_NONE;
c->snap.vertical = SNAP_V_NONE;
client_move(c, c->x - KEYBOARD_MOVE_STEP, c->y);
decorations_render(c, true);
}
void key_move_window_right(void)
{
Workspace *ws = workspace_get_current();
if (ws == NULL || ws->focused == NULL) {
return;
}
Client *c = ws->focused;
if (!client_is_floating(c)) {
client_set_floating(c, true);
workspace_arrange_current();
}
c->snap.horizontal = SNAP_H_NONE;
c->snap.vertical = SNAP_V_NONE;
client_move(c, c->x + KEYBOARD_MOVE_STEP, c->y);
decorations_render(c, true);
}
void key_move_window_up(void)
{
Workspace *ws = workspace_get_current();
if (ws == NULL || ws->focused == NULL) {
return;
}
Client *c = ws->focused;
if (!client_is_floating(c)) {
client_set_floating(c, true);
workspace_arrange_current();
}
c->snap.horizontal = SNAP_H_NONE;
c->snap.vertical = SNAP_V_NONE;
client_move(c, c->x, c->y - KEYBOARD_MOVE_STEP);
decorations_render(c, true);
}
void key_move_window_down(void)
{
Workspace *ws = workspace_get_current();
if (ws == NULL || ws->focused == NULL) {
return;
}
Client *c = ws->focused;
if (!client_is_floating(c)) {
client_set_floating(c, true);
workspace_arrange_current();
}
c->snap.horizontal = SNAP_H_NONE;
c->snap.vertical = SNAP_V_NONE;
client_move(c, c->x, c->y + KEYBOARD_MOVE_STEP);
decorations_render(c, true);
}
void key_resize_window_left(void)
{
Workspace *ws = workspace_get_current();
if (ws == NULL || ws->focused == NULL) {
return;
}
Client *c = ws->focused;
if (!client_is_floating(c)) {
client_set_floating(c, true);
workspace_arrange_current();
}
c->snap.horizontal = SNAP_H_NONE;
c->snap.vertical = SNAP_V_NONE;
int new_width = c->width - KEYBOARD_RESIZE_STEP;
if (new_width < 50) {
new_width = 50;
}
client_resize(c, new_width, c->height);
decorations_render(c, true);
}
void key_resize_window_right(void)
{
Workspace *ws = workspace_get_current();
if (ws == NULL || ws->focused == NULL) {
return;
}
Client *c = ws->focused;
if (!client_is_floating(c)) {
client_set_floating(c, true);
workspace_arrange_current();
}
c->snap.horizontal = SNAP_H_NONE;
c->snap.vertical = SNAP_V_NONE;
client_resize(c, c->width + KEYBOARD_RESIZE_STEP, c->height);
decorations_render(c, true);
}
void key_resize_window_up(void)
{
Workspace *ws = workspace_get_current();
if (ws == NULL || ws->focused == NULL) {
return;
}
Client *c = ws->focused;
if (!client_is_floating(c)) {
client_set_floating(c, true);
workspace_arrange_current();
}
c->snap.horizontal = SNAP_H_NONE;
c->snap.vertical = SNAP_V_NONE;
int new_height = c->height - KEYBOARD_RESIZE_STEP;
if (new_height < 50) {
new_height = 50;
}
client_resize(c, c->width, new_height);
decorations_render(c, true);
}
void key_resize_window_down(void)
{
Workspace *ws = workspace_get_current();
if (ws == NULL || ws->focused == NULL) {
return;
}
Client *c = ws->focused;
if (!client_is_floating(c)) {
client_set_floating(c, true);
workspace_arrange_current();
}
c->snap.horizontal = SNAP_H_NONE;
c->snap.vertical = SNAP_V_NONE;
client_resize(c, c->width, c->height + KEYBOARD_RESIZE_STEP);
decorations_render(c, true);
}
void key_set_mark(void)
{
marks_start_set_mode();
}
void key_goto_mark(void)
{
marks_start_goto_mode();
}
+349 -9
View File
@@ -15,13 +15,19 @@
static const char *layout_names[] = {
"Tiling",
"Floating",
"Monocle"
"Monocle",
"Centered",
"Columns",
"Fibonacci"
};
static const char *layout_symbols[] = {
"[]=",
"><>",
"[M]"
"[M]",
"|M|",
"|||",
"[@]"
};
@@ -42,6 +48,15 @@ void layout_arrange(int workspace)
case LAYOUT_MONOCLE:
layout_arrange_monocle(workspace);
break;
case LAYOUT_CENTERED_MASTER:
layout_arrange_centered_master(workspace);
break;
case LAYOUT_COLUMNS:
layout_arrange_columns(workspace);
break;
case LAYOUT_FIBONACCI:
layout_arrange_fibonacci(workspace);
break;
default:
layout_arrange_tiling(workspace);
break;
@@ -90,11 +105,21 @@ void layout_arrange_tiling(int workspace)
int master_y = area_y + gap;
int stack_y = area_y + gap;
for (Client *c = dwn->client_list; c != NULL; c = c->next) {
if (c->workspace != (unsigned int)workspace) {
for (Client *c = dwn->client_list; c != NULL; ) {
Client *next = c->next;
if (c->flags & CLIENT_UNMANAGING) {
c = next;
continue;
}
if (c->workspace != (unsigned int)workspace) {
c = next;
continue;
}
if (client_is_floating(c) || client_is_fullscreen(c) || client_is_minimized(c)) {
c = next;
continue;
}
@@ -141,6 +166,8 @@ void layout_arrange_tiling(int workspace)
actual_w, actual_h);
i++;
c = next;
}
}
@@ -150,11 +177,21 @@ void layout_arrange_floating(int workspace)
int area_x, area_y, area_width, area_height;
layout_get_usable_area(&area_x, &area_y, &area_width, &area_height);
for (Client *c = dwn->client_list; c != NULL; c = c->next) {
if (c->workspace != (unsigned int)workspace) {
for (Client *c = dwn->client_list; c != NULL; ) {
Client *next = c->next;
if (c->flags & CLIENT_UNMANAGING) {
c = next;
continue;
}
if (c->workspace != (unsigned int)workspace) {
c = next;
continue;
}
if (client_is_minimized(c)) {
c = next;
continue;
}
@@ -196,6 +233,8 @@ void layout_arrange_floating(int workspace)
if (c->height < 50) c->height = 50;
client_configure(c);
c = next;
}
}
@@ -209,11 +248,21 @@ void layout_arrange_monocle(int workspace)
int title_height = config_get_title_height();
int border = config_get_border_width();
for (Client *c = dwn->client_list; c != NULL; c = c->next) {
if (c->workspace != (unsigned int)workspace) {
for (Client *c = dwn->client_list; c != NULL; ) {
Client *next = c->next;
if (c->flags & CLIENT_UNMANAGING) {
c = next;
continue;
}
if (c->workspace != (unsigned int)workspace) {
c = next;
continue;
}
if (client_is_floating(c) || client_is_fullscreen(c) || client_is_minimized(c)) {
c = next;
continue;
}
@@ -226,6 +275,8 @@ void layout_arrange_monocle(int workspace)
if (w < 50) w = 50;
client_move_resize(c, x + border, y + title_height + border, w, h);
c = next;
}
}
@@ -259,14 +310,27 @@ int layout_count_tiled_clients(int workspace)
{
int count = 0;
for (Client *c = dwn->client_list; c != NULL; c = c->next) {
for (Client *c = dwn->client_list; c != NULL; ) {
Client *next = c->next;
if (c->flags & CLIENT_UNMANAGING) {
c = next;
continue;
}
if (c->workspace != (unsigned int)workspace) {
c = next;
continue;
}
if (client_is_floating(c) || client_is_fullscreen(c) || client_is_minimized(c)) {
c = next;
continue;
}
count++;
c = next;
}
return count;
@@ -336,3 +400,279 @@ const char *layout_get_symbol(LayoutType layout)
}
return "???";
}
void layout_arrange_centered_master(int workspace)
{
Workspace *ws = workspace_get(workspace);
if (ws == NULL) {
return;
}
int area_x, area_y, area_width, area_height;
layout_get_usable_area(&area_x, &area_y, &area_width, &area_height);
int gap = config_get_gap();
int title_height = config_get_title_height();
int border = config_get_border_width();
int n = layout_count_tiled_clients(workspace);
if (n == 0) {
return;
}
int master_count = ws->master_count;
if (master_count > n) {
master_count = n;
}
if (n == 1) {
for (Client *c = dwn->client_list; c != NULL; c = c->next) {
if (c->flags & CLIENT_UNMANAGING) continue;
if (c->workspace != (unsigned int)workspace) continue;
if (client_is_floating(c) || client_is_fullscreen(c) || client_is_minimized(c)) continue;
int x = area_x + gap + border;
int y = area_y + gap + title_height + border;
int w = area_width - 2 * gap - 2 * border;
int h = area_height - 2 * gap - title_height - 2 * border;
client_move_resize(c, x, y, w, h);
break;
}
return;
}
int stack_count = n - master_count;
int left_stack = stack_count / 2;
int right_stack = stack_count - left_stack;
int master_width = (int)((area_width - 4 * gap) * ws->master_ratio);
int side_width = (area_width - master_width - 4 * gap) / 2;
int master_x = area_x + gap + side_width + gap;
int left_x = area_x + gap;
int right_x = master_x + master_width + gap;
int i = 0;
int master_y = area_y + gap;
int left_y = area_y + gap;
int right_y = area_y + gap;
int left_i = 0;
int right_i = 0;
for (Client *c = dwn->client_list; c != NULL; ) {
Client *next = c->next;
if (c->flags & CLIENT_UNMANAGING) {
c = next;
continue;
}
if (c->workspace != (unsigned int)workspace) {
c = next;
continue;
}
if (client_is_floating(c) || client_is_fullscreen(c) || client_is_minimized(c)) {
c = next;
continue;
}
int x, y, w, h;
if (i < master_count) {
int master_h = (area_height - 2 * gap - (master_count - 1) * gap) / master_count;
x = master_x;
y = master_y;
w = master_width;
h = master_h;
master_y += h + gap;
} else if (left_i < left_stack) {
int left_h = left_stack > 0 ?
(area_height - 2 * gap - (left_stack - 1) * gap) / left_stack : 0;
x = left_x;
y = left_y;
w = side_width;
h = left_h;
left_y += h + gap;
left_i++;
} else {
int right_h = right_stack > 0 ?
(area_height - 2 * gap - (right_stack - 1) * gap) / right_stack : 0;
x = right_x;
y = right_y;
w = side_width;
h = right_h;
right_y += h + gap;
right_i++;
}
int actual_h = h - title_height - 2 * border;
int actual_w = w - 2 * border;
if (actual_h < 50) actual_h = 50;
if (actual_w < 50) actual_w = 50;
client_move_resize(c, x + border, y + title_height + border,
actual_w, actual_h);
i++;
c = next;
}
}
void layout_arrange_columns(int workspace)
{
Workspace *ws = workspace_get(workspace);
if (ws == NULL) {
return;
}
int area_x, area_y, area_width, area_height;
layout_get_usable_area(&area_x, &area_y, &area_width, &area_height);
int gap = config_get_gap();
int title_height = config_get_title_height();
int border = config_get_border_width();
int n = layout_count_tiled_clients(workspace);
if (n == 0) {
return;
}
int col_width = (area_width - (n + 1) * gap) / n;
if (col_width < 50) col_width = 50;
int i = 0;
int col_x = area_x + gap;
for (Client *c = dwn->client_list; c != NULL; ) {
Client *next = c->next;
if (c->flags & CLIENT_UNMANAGING) {
c = next;
continue;
}
if (c->workspace != (unsigned int)workspace) {
c = next;
continue;
}
if (client_is_floating(c) || client_is_fullscreen(c) || client_is_minimized(c)) {
c = next;
continue;
}
int x = col_x;
int y = area_y + gap;
int w = col_width - 2 * border;
int h = area_height - 2 * gap - title_height - 2 * border;
if (w < 50) w = 50;
if (h < 50) h = 50;
client_move_resize(c, x + border, y + title_height + border, w, h);
col_x += col_width + gap;
i++;
c = next;
}
}
void layout_arrange_fibonacci(int workspace)
{
Workspace *ws = workspace_get(workspace);
if (ws == NULL) {
return;
}
int area_x, area_y, area_width, area_height;
layout_get_usable_area(&area_x, &area_y, &area_width, &area_height);
int gap = config_get_gap();
int title_height = config_get_title_height();
int border = config_get_border_width();
int n = layout_count_tiled_clients(workspace);
if (n == 0) {
return;
}
int fib_x = area_x + gap;
int fib_y = area_y + gap;
int fib_w = area_width - 2 * gap;
int fib_h = area_height - 2 * gap;
int i = 0;
for (Client *c = dwn->client_list; c != NULL; ) {
Client *next = c->next;
if (c->flags & CLIENT_UNMANAGING) {
c = next;
continue;
}
if (c->workspace != (unsigned int)workspace) {
c = next;
continue;
}
if (client_is_floating(c) || client_is_fullscreen(c) || client_is_minimized(c)) {
c = next;
continue;
}
int x = fib_x;
int y = fib_y;
int w = fib_w;
int h = fib_h;
if (i < n - 1) {
switch (i % 4) {
case 0:
w = (int)(fib_w * ws->master_ratio);
fib_x += w + gap;
fib_w -= w + gap;
break;
case 1:
h = (int)(fib_h * ws->master_ratio);
fib_y += h + gap;
fib_h -= h + gap;
break;
case 2:
w = (int)(fib_w * ws->master_ratio);
fib_w -= w + gap;
x = fib_x + fib_w + gap;
break;
case 3:
h = (int)(fib_h * ws->master_ratio);
fib_h -= h + gap;
y = fib_y + fib_h + gap;
break;
}
}
int actual_w = w - 2 * border;
int actual_h = h - title_height - 2 * border;
if (actual_w < 50) actual_w = 50;
if (actual_h < 50) actual_h = 50;
client_move_resize(c, x + border, y + title_height + border,
actual_w, actual_h);
i++;
c = next;
}
}
+120 -30
View File
@@ -25,6 +25,14 @@
#include "screenshot.h"
#include "ocr.h"
#include "util.h"
#include "slider.h"
#include "rules.h"
#include "marks.h"
/* New abstraction layer */
#include "core/wm_client.h"
#include "plugins/layout_plugin.h"
#include "plugins/builtin_layouts.h"
#include <stdio.h>
#include <stdlib.h>
@@ -40,6 +48,10 @@
#include <X11/extensions/Xinerama.h>
#include <X11/extensions/XInput2.h>
/* Forward declarations for fade controls (defined in systray.c) */
void fade_controls_init(void);
void fade_controls_cleanup(void);
DWNState *dwn = NULL;
static DWNState dwn_state;
@@ -62,35 +74,36 @@ static int last_x_error = 0;
static int x_error_handler(Display *dpy, XErrorEvent *ev)
{
char error_text[256];
XGetErrorText(dpy, ev->error_code, error_text, sizeof(error_text));
(void)dpy;
last_x_error = ev->error_code;
FILE *crash = fopen("/tmp/dwn_crash.log", "a");
if (crash) {
fprintf(crash, "[X_ERROR] code=%d request=%d resource=%lu: %s\n",
ev->error_code, ev->request_code, ev->resourceid, error_text);
fflush(crash);
fsync(fileno(crash));
fclose(crash);
}
/* Async-signal-safe error logging using write() only.
* Do NOT use stdio functions (fprintf, fflush, etc.) here as this
* handler may be called from signal context. */
char buf[512];
int len;
if (ev->error_code == BadWindow) {
LOG_DEBUG("X11 BadWindow error (request %d, resource %lu) - window was destroyed",
ev->request_code, ev->resourceid);
return 0;
len = snprintf(buf, sizeof(buf),
"[X_ERROR] BadWindow (request %d, resource %lu)\n",
ev->request_code, ev->resourceid);
} else if (ev->error_code == BadMatch || ev->error_code == BadValue ||
ev->error_code == BadDrawable || ev->error_code == BadPixmap) {
len = snprintf(buf, sizeof(buf),
"[X_ERROR] code=%d request=%d - continuing\n",
ev->error_code, ev->request_code);
} else {
len = snprintf(buf, sizeof(buf),
"[X_ERROR] code=%d request=%d resource=%lu\n",
ev->error_code, ev->request_code, ev->resourceid);
}
if (ev->error_code == BadMatch || ev->error_code == BadValue ||
ev->error_code == BadDrawable || ev->error_code == BadPixmap) {
LOG_WARN("X11 error: %s (request %d, resource %lu) - continuing",
error_text, ev->request_code, ev->resourceid);
return 0;
if (len > 0 && len < (int)sizeof(buf)) {
ssize_t _wrote = write(STDERR_FILENO, buf, (size_t)len);
(void)_wrote; /* Best effort in signal handler */
}
LOG_WARN("X11 error: %s (request %d, resource %lu)",
error_text, ev->request_code, ev->resourceid);
return 0;
}
@@ -98,13 +111,10 @@ static int x_io_error_handler(Display *dpy)
{
(void)dpy;
FILE *crash = fopen("/tmp/dwn_crash.log", "a");
if (crash) {
fprintf(crash, "[IO_ERROR] Fatal X11 I/O error - X server connection lost\n");
fflush(crash);
fsync(fileno(crash));
fclose(crash);
}
/* Async-signal-safe logging - write directly to stderr */
const char msg[] = "[IO_ERROR] Fatal X11 I/O error - X server connection lost\n";
ssize_t _wrote = write(STDERR_FILENO, msg, sizeof(msg) - 1);
(void)_wrote; /* Best effort in signal handler */
fprintf(stderr, "[IO_ERROR] Fatal X11 I/O error - X server connection lost\n");
fflush(stderr);
@@ -502,6 +512,27 @@ static void handle_button_press(XButtonEvent *ev)
}
}
/* Handle fade control sliders */
if (fade_speed_control.slider != NULL && fade_speed_control.slider->visible) {
if (ev->window == fade_speed_control.slider->window) {
LOG_DEBUG("Fade speed slider click: x=%d, y=%d", ev->x, ev->y);
slider_handle_click(fade_speed_control.slider, ev->x, ev->y);
return;
} else {
slider_hide(fade_speed_control.slider);
}
}
if (fade_intensity_control.slider != NULL && fade_intensity_control.slider->visible) {
if (ev->window == fade_intensity_control.slider->window) {
LOG_DEBUG("Fade intensity slider click: x=%d, y=%d", ev->x, ev->y);
slider_handle_click(fade_intensity_control.slider, ev->x, ev->y);
return;
} else {
slider_hide(fade_intensity_control.slider);
}
}
Notification *notif = notification_find_by_window(ev->window);
if (notif != NULL) {
notification_close(notif->id);
@@ -597,6 +628,14 @@ static void handle_button_release(XButtonEvent *ev)
volume_slider_handle_release(volume_slider);
}
if (fade_speed_control.slider != NULL && fade_speed_control.slider->visible && fade_speed_control.slider->dragging) {
slider_handle_release(fade_speed_control.slider);
}
if (fade_intensity_control.slider != NULL && fade_intensity_control.slider->visible && fade_intensity_control.slider->dragging) {
slider_handle_release(fade_intensity_control.slider);
}
if (dwn->drag_client != NULL) {
api_emit_drag_ended(dwn->drag_client->window, dwn->resizing);
XUngrabPointer(dwn->display, CurrentTime);
@@ -617,6 +656,18 @@ static void handle_motion_notify(XMotionEvent *ev)
return;
}
if (fade_speed_control.slider != NULL && fade_speed_control.slider->visible && ev->window == fade_speed_control.slider->window) {
LOG_DEBUG("Fade speed slider motion: x=%d, y=%d", ev->x, ev->y);
slider_handle_motion(fade_speed_control.slider, ev->x, ev->y);
return;
}
if (fade_intensity_control.slider != NULL && fade_intensity_control.slider->visible && ev->window == fade_intensity_control.slider->window) {
LOG_DEBUG("Fade intensity slider motion: x=%d, y=%d", ev->x, ev->y);
slider_handle_motion(fade_intensity_control.slider, ev->x, ev->y);
return;
}
if (dwn->drag_client == NULL) {
return;
}
@@ -842,6 +893,12 @@ int dwn_init(void)
extern void config_init_colors(Config *cfg);
config_init_colors(dwn->config);
extern int cli_port;
if (cli_port > 0) {
dwn->config->api_port = cli_port;
LOG_INFO("API port overridden by CLI: %d", cli_port);
}
dwn->font = XLoadQueryFont(dwn->display, dwn->config->font_name);
if (dwn->font == NULL) {
dwn->font = XLoadQueryFont(dwn->display, "fixed");
@@ -878,11 +935,18 @@ int dwn_init(void)
workspace_init();
/* Initialize new abstraction layer */
wm_client_manager_init();
wm_layout_manager_init();
wm_layouts_builtin_init();
LOG_INFO("Layout plugin system initialized");
decorations_init();
panels_init();
systray_init();
fade_controls_init();
xembed_init();
@@ -910,6 +974,11 @@ int dwn_init(void)
demo_init();
rules_init();
rules_load(NULL);
marks_init();
atoms_setup_ewmh();
XSelectInput(dwn->display, dwn->root,
@@ -941,6 +1010,12 @@ void dwn_cleanup(void)
{
LOG_INFO("DWN shutting down");
/* Cleanup new abstraction layer */
wm_layout_manager_shutdown();
wm_client_manager_shutdown();
marks_cleanup();
rules_cleanup();
demo_cleanup();
api_cleanup();
ocr_cleanup();
@@ -953,6 +1028,7 @@ void dwn_cleanup(void)
autostart_cleanup();
keys_cleanup();
xembed_cleanup();
fade_controls_cleanup();
systray_cleanup();
panels_cleanup();
decorations_cleanup();
@@ -1110,9 +1186,10 @@ static void print_usage(const char *program)
printf("Usage: %s [OPTIONS]\n", program);
printf("\n");
printf("Options:\n");
printf(" -h, --help Show this help message\n");
printf(" -v, --version Show version information\n");
printf(" -c CONFIG Use specified config file\n");
printf(" -h, --help Show this help message\n");
printf(" -v, --version Show version information\n");
printf(" -c, --config FILE Use specified config file\n");
printf(" -p, --port PORT Use specified API port (overrides config)\n");
printf("\n");
printf("Environment variables:\n");
printf(" OPENROUTER_API_KEY Enable AI features\n");
@@ -1125,6 +1202,9 @@ static void print_version(void)
printf("AI-enhanced X11 window manager\n");
}
int cli_port = -1;
static char *cli_config = NULL;
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; i++) {
@@ -1136,6 +1216,16 @@ int main(int argc, char *argv[])
print_version();
return 0;
}
if ((strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--port") == 0) && i + 1 < argc) {
cli_port = atoi(argv[++i]);
if (cli_port <= 0 || cli_port > 65535) {
fprintf(stderr, "Invalid port number: %s\n", argv[i]);
return EXIT_FAILURE;
}
}
if ((strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--config") == 0) && i + 1 < argc) {
cli_config = argv[++i];
}
}
XInitThreads();
+193
View File
@@ -0,0 +1,193 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* Window marks implementation
*/
#include "marks.h"
#include "client.h"
#include "workspace.h"
#include "notifications.h"
#include "util.h"
#include <string.h>
#include <ctype.h>
typedef enum {
MARKS_MODE_NONE,
MARKS_MODE_SET,
MARKS_MODE_GOTO
} MarksMode;
static Client *marked_clients[MAX_MARKS];
static MarksMode current_mode = MARKS_MODE_NONE;
void marks_init(void)
{
memset(marked_clients, 0, sizeof(marked_clients));
current_mode = MARKS_MODE_NONE;
LOG_INFO("Window marks system initialized");
}
void marks_cleanup(void)
{
marks_clear_all();
}
static int mark_to_index(char mark)
{
char lower = (char)tolower((unsigned char)mark);
if (lower >= 'a' && lower <= 'z') {
return lower - 'a';
}
return -1;
}
void marks_set(char mark, Client *client)
{
int idx = mark_to_index(mark);
if (idx < 0 || client == NULL) {
return;
}
for (int i = 0; i < MAX_MARKS; i++) {
if (marked_clients[i] == client) {
marked_clients[i] = NULL;
}
}
marked_clients[idx] = client;
char msg[128];
snprintf(msg, sizeof(msg), "Window marked as '%c'", mark);
notification_show("DWN Marks", "Mark Set", msg, NULL, 1500);
LOG_DEBUG("Set mark '%c' for window '%s'", mark, client->title);
}
Client *marks_get(char mark)
{
int idx = mark_to_index(mark);
if (idx < 0) {
return NULL;
}
return marked_clients[idx];
}
void marks_clear(char mark)
{
int idx = mark_to_index(mark);
if (idx >= 0) {
marked_clients[idx] = NULL;
}
}
void marks_clear_all(void)
{
memset(marked_clients, 0, sizeof(marked_clients));
}
void marks_remove_client(Client *client)
{
if (client == NULL) {
return;
}
for (int i = 0; i < MAX_MARKS; i++) {
if (marked_clients[i] == client) {
marked_clients[i] = NULL;
}
}
}
bool marks_is_waiting_for_mark(void)
{
return current_mode == MARKS_MODE_SET;
}
bool marks_is_waiting_for_goto(void)
{
return current_mode == MARKS_MODE_GOTO;
}
void marks_start_set_mode(void)
{
Workspace *ws = workspace_get_current();
if (ws == NULL || ws->focused == NULL) {
notification_show("DWN Marks", "No Window",
"Focus a window first to set a mark", NULL, 2000);
return;
}
current_mode = MARKS_MODE_SET;
notification_show("DWN Marks", "Set Mark",
"Press a-z to set mark for this window", NULL, 0);
}
void marks_start_goto_mode(void)
{
current_mode = MARKS_MODE_GOTO;
notification_show("DWN Marks", "Go to Mark",
"Press a-z to jump to marked window", NULL, 0);
}
void marks_cancel_mode(void)
{
if (current_mode != MARKS_MODE_NONE) {
current_mode = MARKS_MODE_NONE;
notification_close_all();
}
}
bool marks_handle_key(char key)
{
if (current_mode == MARKS_MODE_NONE) {
return false;
}
char lower = (char)tolower((unsigned char)key);
if (lower < 'a' || lower > 'z') {
marks_cancel_mode();
return true;
}
notification_close_all();
if (current_mode == MARKS_MODE_SET) {
Workspace *ws = workspace_get_current();
if (ws != NULL && ws->focused != NULL) {
marks_set(lower, ws->focused);
}
} else if (current_mode == MARKS_MODE_GOTO) {
Client *c = marks_get(lower);
if (c != NULL) {
if (c->workspace != (unsigned int)dwn->current_workspace) {
workspace_switch((int)c->workspace);
}
client_focus(c, true);
client_raise(c);
} else {
char msg[64];
snprintf(msg, sizeof(msg), "No window marked as '%c'", lower);
notification_show("DWN Marks", "Mark Not Found", msg, NULL, 1500);
}
}
current_mode = MARKS_MODE_NONE;
return true;
}
char marks_get_mark_for_client(Client *client)
{
if (client == NULL) {
return '\0';
}
for (int i = 0; i < MAX_MARKS; i++) {
if (marked_clients[i] == client) {
return (char)('a' + i);
}
}
return '\0';
}
+23 -6
View File
@@ -464,24 +464,40 @@ uint32_t notification_show(const char *app_name, const char *summary,
}
Notification *notif = dwn_calloc(1, sizeof(Notification));
if (notif == NULL) {
LOG_ERROR("Failed to allocate notification");
return 0;
}
notif->id = next_notification_id++;
if (app_name) strncpy(notif->app_name, app_name, sizeof(notif->app_name) - 1);
if (summary) strncpy(notif->summary, summary, sizeof(notif->summary) - 1);
if (app_name) {
strncpy(notif->app_name, app_name, sizeof(notif->app_name) - 1);
notif->app_name[sizeof(notif->app_name) - 1] = '\0';
}
if (summary) {
strncpy(notif->summary, summary, sizeof(notif->summary) - 1);
notif->summary[sizeof(notif->summary) - 1] = '\0';
}
if (body != NULL && body[0] != '\0') {
notif->body_len = strlen(body);
notif->body = dwn_malloc(notif->body_len + 1);
if (notif->body != NULL) {
memcpy(notif->body, body, notif->body_len + 1);
if (notif->body == NULL) {
LOG_ERROR("Failed to allocate notification body");
dwn_free(notif);
return 0;
}
memcpy(notif->body, body, notif->body_len + 1);
} else {
notif->body = NULL;
notif->body_len = 0;
}
if (icon) strncpy(notif->icon, icon, sizeof(notif->icon) - 1);
if (icon) {
strncpy(notif->icon, icon, sizeof(notif->icon) - 1);
notif->icon[sizeof(notif->icon) - 1] = '\0';
}
notif->timeout = (timeout < 0) ? DEFAULT_TIMEOUT : timeout;
notif->urgency = NOTIFY_URGENCY_NORMAL;
@@ -519,7 +535,8 @@ uint32_t notification_show(const char *app_name, const char *summary,
}
LOG_DEBUG("Notification %u (%dx%d): %s - %s", notif->id,
notif->width, notif->height, notif->summary, notif->body);
notif->width, notif->height, notif->summary,
notif->body ? notif->body : "(no body)");
api_emit_notification_shown(notif->id, notif->summary, notif->body);
+190 -110
View File
@@ -1,7 +1,7 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* OCR text extraction using Tesseract
* OCR text extraction using Tesseract - Production Hardened
*/
#include "ocr.h"
@@ -13,10 +13,24 @@
#include <tesseract/capi.h>
#include <leptonica/allheaders.h>
/* Thread state tracking */
typedef enum {
OCR_THREAD_RUNNING,
OCR_THREAD_COMPLETED,
OCR_THREAD_JOINED
} OcrThreadState;
typedef struct OcrRequestInternal {
OcrRequest base;
OcrThreadState thread_state;
atomic_int cancelled;
struct OcrRequestInternal *next;
} OcrRequestInternal;
static TessBaseAPI *tess_api = NULL;
static bool initialized = false;
static pthread_mutex_t ocr_mutex = PTHREAD_MUTEX_INITIALIZER;
static OcrRequest *ocr_queue = NULL;
static OcrRequestInternal *ocr_queue = NULL;
static atomic_int ocr_shutting_down = 0;
bool ocr_init(void)
@@ -24,22 +38,22 @@ bool ocr_init(void)
if (initialized) {
return true;
}
atomic_store(&ocr_shutting_down, 0);
tess_api = TessBaseAPICreate();
if (tess_api == NULL) {
LOG_ERROR("Failed to create Tesseract API");
return false;
}
if (TessBaseAPIInit3(tess_api, NULL, "eng") != 0) {
LOG_WARN("Tesseract initialization failed, OCR unavailable");
TessBaseAPIDelete(tess_api);
tess_api = NULL;
return false;
}
initialized = true;
LOG_INFO("OCR module initialized with Tesseract");
return true;
@@ -48,24 +62,42 @@ bool ocr_init(void)
void ocr_cleanup(void)
{
atomic_store(&ocr_shutting_down, 1);
pthread_mutex_lock(&ocr_mutex);
while (ocr_queue != NULL) {
OcrRequest *req = ocr_queue;
ocr_queue = req->next;
OcrRequestInternal *req = ocr_queue;
while (req != NULL) {
OcrRequestInternal *next = req->next;
/* Signal cancellation */
atomic_store(&req->cancelled, 1);
/* Remove from queue */
req->next = NULL;
pthread_mutex_unlock(&ocr_mutex);
pthread_join(req->thread, NULL);
if (req->png_data != NULL) {
dwn_free(req->png_data);
/* Join thread if not already joined */
if (req->thread_state != OCR_THREAD_JOINED) {
pthread_join(req->base.thread, NULL);
req->thread_state = OCR_THREAD_JOINED;
}
ocr_result_free(&req->result);
/* Free resources */
if (req->base.png_data != NULL) {
dwn_free(req->base.png_data);
req->base.png_data = NULL;
}
ocr_result_free(&req->base.result);
dwn_free(req);
pthread_mutex_lock(&ocr_mutex);
req = next;
}
ocr_queue = NULL;
pthread_mutex_unlock(&ocr_mutex);
if (tess_api != NULL) {
TessBaseAPIEnd(tess_api);
TessBaseAPIDelete(tess_api);
@@ -76,7 +108,7 @@ void ocr_cleanup(void)
bool ocr_is_available(void)
{
return initialized && tess_api != NULL;
return initialized && tess_api != NULL && !atomic_load(&ocr_shutting_down);
}
const char *ocr_status_string(OcrStatus status)
@@ -118,43 +150,43 @@ OcrStatus ocr_extract_from_png(const unsigned char *png_data, size_t size,
if (result == NULL) {
return OCR_ERROR_INVALID_ARG;
}
memset(result, 0, sizeof(OcrResult));
if (png_data == NULL || size == 0) {
return OCR_ERROR_INVALID_ARG;
}
if (!ocr_is_available()) {
return OCR_ERROR_NOT_AVAILABLE;
}
const char *lang = (language != NULL && language[0] != '\0') ? language : "eng";
if (TessBaseAPIInit3(tess_api, NULL, lang) != 0) {
LOG_WARN("Failed to set language '%s', falling back to 'eng'", lang);
if (TessBaseAPIInit3(tess_api, NULL, "eng") != 0) {
return OCR_ERROR_INIT;
}
}
PIX *image = pixReadMem(png_data, size);
if (image == NULL) {
LOG_ERROR("Failed to read PNG image for OCR");
return OCR_ERROR_IMAGE;
}
TessBaseAPISetImage2(tess_api, image);
char *text = TessBaseAPIGetUTF8Text(tess_api);
if (text == NULL) {
pixDestroy(&image);
return OCR_ERROR_IMAGE;
}
int conf = TessBaseAPIMeanTextConf(tess_api);
float confidence = (float)conf / 100.0f;
size_t text_len = strlen(text);
result->text = dwn_malloc(text_len + 1);
if (result->text == NULL) {
@@ -162,80 +194,101 @@ OcrStatus ocr_extract_from_png(const unsigned char *png_data, size_t size,
pixDestroy(&image);
return OCR_ERROR_NO_MEMORY;
}
memcpy(result->text, text, text_len + 1);
result->length = text_len;
result->confidence = confidence;
TessDeleteText(text);
pixDestroy(&image);
return OCR_OK;
}
static void *ocr_worker(void *arg)
{
OcrRequest *req = (OcrRequest *)arg;
if (atomic_load(&ocr_shutting_down)) {
req->state = OCR_STATE_ERROR;
req->status = OCR_ERROR_NOT_AVAILABLE;
OcrRequestInternal *req = (OcrRequestInternal *)arg;
if (atomic_load(&ocr_shutting_down) || atomic_load(&req->cancelled)) {
req->base.state = OCR_STATE_ERROR;
req->base.status = OCR_ERROR_NOT_AVAILABLE;
return NULL;
}
/* Create local Tesseract instance for thread safety */
TessBaseAPI *local_tess = TessBaseAPICreate();
if (local_tess == NULL) {
req->status = OCR_ERROR_INIT;
req->state = OCR_STATE_ERROR;
req->base.status = OCR_ERROR_INIT;
req->base.state = OCR_STATE_ERROR;
return NULL;
}
const char *lang = req->language[0] ? req->language : "eng";
const char *lang = req->base.language[0] ? req->base.language : "eng";
if (TessBaseAPIInit3(local_tess, NULL, lang) != 0) {
if (TessBaseAPIInit3(local_tess, NULL, "eng") != 0) {
TessBaseAPIDelete(local_tess);
req->status = OCR_ERROR_INIT;
req->state = OCR_STATE_ERROR;
req->base.status = OCR_ERROR_INIT;
req->base.state = OCR_STATE_ERROR;
return NULL;
}
}
PIX *image = pixReadMem(req->png_data, req->png_size);
/* Check for cancellation */
if (atomic_load(&req->cancelled)) {
TessBaseAPIEnd(local_tess);
TessBaseAPIDelete(local_tess);
req->base.status = OCR_ERROR_NOT_AVAILABLE;
req->base.state = OCR_STATE_ERROR;
return NULL;
}
PIX *image = pixReadMem(req->base.png_data, req->base.png_size);
if (image == NULL) {
TessBaseAPIEnd(local_tess);
TessBaseAPIDelete(local_tess);
req->status = OCR_ERROR_IMAGE;
req->state = OCR_STATE_ERROR;
req->base.status = OCR_ERROR_IMAGE;
req->base.state = OCR_STATE_ERROR;
return NULL;
}
TessBaseAPISetImage2(local_tess, image);
/* Check for cancellation again before expensive OCR operation */
if (atomic_load(&req->cancelled)) {
pixDestroy(&image);
TessBaseAPIEnd(local_tess);
TessBaseAPIDelete(local_tess);
req->base.status = OCR_ERROR_NOT_AVAILABLE;
req->base.state = OCR_STATE_ERROR;
return NULL;
}
char *text = TessBaseAPIGetUTF8Text(local_tess);
int conf = TessBaseAPIMeanTextConf(local_tess);
if (text != NULL) {
size_t len = strlen(text);
req->result.text = dwn_malloc(len + 1);
if (req->result.text) {
memcpy(req->result.text, text, len + 1);
req->result.length = len;
req->result.confidence = (float)conf / 100.0f;
req->status = OCR_OK;
req->state = OCR_STATE_COMPLETED;
req->base.result.text = dwn_malloc(len + 1);
if (req->base.result.text != NULL) {
memcpy(req->base.result.text, text, len + 1);
req->base.result.length = len;
req->base.result.confidence = (float)conf / 100.0f;
req->base.status = OCR_OK;
req->base.state = OCR_STATE_COMPLETED;
} else {
req->status = OCR_ERROR_NO_MEMORY;
req->state = OCR_STATE_ERROR;
req->base.status = OCR_ERROR_NO_MEMORY;
req->base.state = OCR_STATE_ERROR;
}
TessDeleteText(text);
} else {
req->status = OCR_ERROR_IMAGE;
req->state = OCR_STATE_ERROR;
req->base.status = OCR_ERROR_IMAGE;
req->base.state = OCR_STATE_ERROR;
}
pixDestroy(&image);
TessBaseAPIEnd(local_tess);
TessBaseAPIDelete(local_tess);
return NULL;
}
@@ -246,41 +299,50 @@ OcrRequest *ocr_extract_async(const unsigned char *png_data, size_t size,
if (!initialized || atomic_load(&ocr_shutting_down)) {
return NULL;
}
if (png_data == NULL || size == 0) {
return NULL;
}
OcrRequest *req = dwn_calloc(1, sizeof(OcrRequest));
/* Check for reasonable size to prevent memory exhaustion */
if (size > 100 * 1024 * 1024) { /* 100MB limit */
LOG_ERROR("OCR image too large: %zu bytes", size);
return NULL;
}
OcrRequestInternal *req = dwn_calloc(1, sizeof(OcrRequestInternal));
if (req == NULL) {
return NULL;
}
req->png_data = dwn_malloc(size);
if (req->png_data == NULL) {
req->base.png_data = dwn_malloc(size);
if (req->base.png_data == NULL) {
dwn_free(req);
return NULL;
}
memcpy(req->png_data, png_data, size);
req->png_size = size;
memcpy(req->base.png_data, png_data, size);
req->base.png_size = size;
if (language != NULL && language[0] != '\0') {
strncpy(req->language, language, sizeof(req->language) - 1);
req->language[sizeof(req->language) - 1] = '\0';
strncpy(req->base.language, language, sizeof(req->base.language) - 1);
req->base.language[sizeof(req->base.language) - 1] = '\0';
}
req->state = OCR_STATE_PENDING;
req->callback = callback;
req->base.state = OCR_STATE_PENDING;
req->base.callback = callback;
atomic_init(&req->cancelled, 0);
req->thread_state = OCR_THREAD_RUNNING;
pthread_mutex_lock(&ocr_mutex);
req->next = ocr_queue;
ocr_queue = req;
pthread_mutex_unlock(&ocr_mutex);
if (pthread_create(&req->thread, NULL, ocr_worker, req) != 0) {
if (pthread_create(&req->base.thread, NULL, ocr_worker, req) != 0) {
pthread_mutex_lock(&ocr_mutex);
OcrRequest **pp = &ocr_queue;
/* Remove from queue */
OcrRequestInternal **pp = &ocr_queue;
while (*pp != NULL) {
if (*pp == req) {
*pp = req->next;
@@ -289,13 +351,14 @@ OcrRequest *ocr_extract_async(const unsigned char *png_data, size_t size,
pp = &(*pp)->next;
}
pthread_mutex_unlock(&ocr_mutex);
dwn_free(req->png_data);
dwn_free(req->base.png_data);
dwn_free(req);
return NULL;
}
LOG_DEBUG("OCR async request started");
return req;
return (OcrRequest *)req;
}
void ocr_process_pending(void)
@@ -303,42 +366,54 @@ void ocr_process_pending(void)
if (atomic_load(&ocr_shutting_down)) {
return;
}
pthread_mutex_lock(&ocr_mutex);
OcrRequest **pp = &ocr_queue;
OcrRequestInternal **pp = &ocr_queue;
while (*pp != NULL) {
OcrRequest *req = *pp;
if (req->state == OCR_STATE_COMPLETED ||
req->state == OCR_STATE_ERROR) {
pthread_join(req->thread, NULL);
OcrRequestInternal *req = *pp;
if (req->base.state == OCR_STATE_COMPLETED ||
req->base.state == OCR_STATE_ERROR) {
/* Remove from queue */
*pp = req->next;
pthread_mutex_unlock(&ocr_mutex);
if (req->callback != NULL) {
req->callback(req);
/* Join thread if not already joined */
if (req->thread_state != OCR_THREAD_JOINED) {
pthread_join(req->base.thread, NULL);
req->thread_state = OCR_THREAD_JOINED;
}
/* Invoke callback */
if (req->base.callback != NULL) {
req->base.callback((OcrRequest *)req);
}
pthread_mutex_lock(&ocr_mutex);
} else {
pp = &(*pp)->next;
}
}
pthread_mutex_unlock(&ocr_mutex);
}
void ocr_cancel(OcrRequest *req)
void ocr_cancel(OcrRequest *base_req)
{
if (req == NULL) {
if (base_req == NULL) {
return;
}
OcrRequestInternal *req = (OcrRequestInternal *)base_req;
/* Signal cancellation */
atomic_store(&req->cancelled, 1);
/* Remove from queue */
pthread_mutex_lock(&ocr_mutex);
OcrRequest **pp = &ocr_queue;
OcrRequestInternal **pp = &ocr_queue;
while (*pp != NULL) {
if (*pp == req) {
*pp = req->next;
@@ -347,13 +422,18 @@ void ocr_cancel(OcrRequest *req)
pp = &(*pp)->next;
}
pthread_mutex_unlock(&ocr_mutex);
pthread_cancel(req->thread);
pthread_join(req->thread, NULL);
if (req->png_data != NULL) {
dwn_free(req->png_data);
/* Wait for thread to complete (it will check cancelled flag) */
if (req->thread_state != OCR_THREAD_JOINED) {
pthread_join(req->base.thread, NULL);
req->thread_state = OCR_THREAD_JOINED;
}
ocr_result_free(&req->result);
/* Free resources */
if (req->base.png_data != NULL) {
dwn_free(req->base.png_data);
req->base.png_data = NULL;
}
ocr_result_free(&req->base.result);
dwn_free(req);
}
+44 -9
View File
@@ -63,6 +63,7 @@ typedef struct {
static CachedXftColor xft_color_cache[XFT_COLOR_CACHE_SIZE];
static Visual *cached_visual = NULL;
static int xft_color_lru_counter = 0;
static bool xft_cache_initialized = false;
static XftDraw *cached_xft_draw = NULL;
static Drawable cached_drawable = None;
@@ -155,6 +156,12 @@ static XftColor *panel_get_cached_xft_color(unsigned long color)
cached_visual = DefaultVisual(dwn->display, dwn->screen);
}
/* Initialize cache on first use */
if (!xft_cache_initialized) {
memset(xft_color_cache, 0, sizeof(xft_color_cache));
xft_cache_initialized = true;
}
for (int i = 0; i < XFT_COLOR_CACHE_SIZE; i++) {
if (xft_color_cache[i].valid && xft_color_cache[i].pixel == color) {
xft_color_cache[i].lru_counter = ++xft_color_lru_counter;
@@ -164,14 +171,22 @@ static XftColor *panel_get_cached_xft_color(unsigned long color)
int oldest_idx = 0;
int oldest_lru = xft_color_cache[0].lru_counter;
for (int i = 1; i < XFT_COLOR_CACHE_SIZE; i++) {
bool found_invalid = false;
for (int i = 0; i < XFT_COLOR_CACHE_SIZE; i++) {
if (!xft_color_cache[i].valid) {
oldest_idx = i;
found_invalid = true;
break;
}
if (xft_color_cache[i].lru_counter < oldest_lru) {
oldest_lru = xft_color_cache[i].lru_counter;
oldest_idx = i;
}
if (!found_invalid) {
for (int i = 1; i < XFT_COLOR_CACHE_SIZE; i++) {
if (xft_color_cache[i].lru_counter < oldest_lru) {
oldest_lru = xft_color_cache[i].lru_counter;
oldest_idx = i;
}
}
}
@@ -396,6 +411,12 @@ void panel_render(Panel *panel)
int systray_actual_width = systray_get_width();
int systray_x = panel->width - systray_actual_width - PANEL_PADDING;
/* Render fade controls before systray */
int fade_width = fade_controls_get_width();
int fade_x = systray_x - fade_width - WIDGET_SPACING;
fade_controls_render(panel, fade_x);
systray_render(panel, systray_x, &width);
if (dwn->ai_enabled) {
@@ -683,8 +704,18 @@ void panel_handle_click(Panel *panel, int x, int y, int button)
}
if (panel->position == PANEL_TOP) {
/* Check fade controls first */
int fade_hit = fade_controls_hit_test(x);
LOG_DEBUG("Panel click: x=%d, fade_hit=%d", x, fade_hit);
if (fade_hit > 0) {
LOG_DEBUG("Fade control clicked: control_id=%d", fade_hit);
fade_controls_handle_click(fade_hit, x, y, button);
return;
}
int systray_actual_width = systray_get_width();
int systray_start = panel->width - systray_actual_width - PANEL_PADDING;
if (x >= systray_start) {
systray_handle_click(x, y, button);
return;
@@ -956,7 +987,7 @@ static ProcCpuState *add_cpu_history(int pid)
return state;
}
char path[32];
char path[64];
for (int i = 0; i < PROC_CPU_HISTORY_SIZE; i++) {
snprintf(path, sizeof(path), "/proc/%d", proc_cpu_history[i].pid);
if (access(path, F_OK) != 0) {
@@ -1477,8 +1508,10 @@ static void panel_render_top_process(Panel *panel, int x, int *width)
color = ambient_glow_bg(color, dwn->ambient_phase + PHASE_OFFSET_TOP_CPU);
proc_name = sys_stats.top_cpu_processes[0];
strncpy(name_buf, proc_name, TOP_PROCESS_NAME_MAX_LEN);
name_buf[TOP_PROCESS_NAME_MAX_LEN] = '\0';
size_t name_len = strlen(proc_name);
if (name_len > TOP_PROCESS_NAME_MAX_LEN) name_len = TOP_PROCESS_NAME_MAX_LEN;
memcpy(name_buf, proc_name, name_len);
name_buf[name_len] = '\0';
while (strlen(name_buf) > 2 && panel_text_width(name_buf, (int)strlen(name_buf)) > available_for_name) {
name_buf[strlen(name_buf) - 1] = '\0';
}
@@ -1495,8 +1528,10 @@ static void panel_render_top_process(Panel *panel, int x, int *width)
color = ambient_glow_bg(color, dwn->ambient_phase + PHASE_OFFSET_TOP_MEM);
proc_name = sys_stats.top_mem_processes[0];
strncpy(name_buf, proc_name, TOP_PROCESS_NAME_MAX_LEN);
name_buf[TOP_PROCESS_NAME_MAX_LEN] = '\0';
size_t name_len = strlen(proc_name);
if (name_len > TOP_PROCESS_NAME_MAX_LEN) name_len = TOP_PROCESS_NAME_MAX_LEN;
memcpy(name_buf, proc_name, name_len);
name_buf[name_len] = '\0';
while (strlen(name_buf) > 2 && panel_text_width(name_buf, (int)strlen(name_buf)) > available_for_name) {
name_buf[strlen(name_buf) - 1] = '\0';
}
+510
View File
@@ -0,0 +1,510 @@
/*
* DWN - Desktop Window Manager
* Layout Plugin Manager Implementation
*/
#include "plugins/layout_plugin.h"
#include "core/wm_list.h"
#include "core/wm_hashmap.h"
#include "core/wm_string.h"
#include "core/wm_client.h"
#include "dwn.h"
#include "util.h"
#include "config.h"
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
/*==============================================================================
* Helper for casting dlsym result to function pointer (avoids ISO C warning)
*============================================================================*/
union dlsym_cast {
void *obj_ptr;
LayoutPluginEntryFunc func_ptr;
};
/*==============================================================================
* Internal Structures
*============================================================================*/
struct LayoutManager {
WmList *plugins; /* List of LayoutPlugin* */
WmHashMap *by_name; /* Map: name -> LayoutPlugin* */
LayoutPlugin *default_layout;
bool initialized;
};
struct WmLayoutState {
void *plugin_data;
WmWorkspaceId workspace;
};
/*==============================================================================
* Global State
*============================================================================*/
static LayoutManager *g_layout_manager = NULL;
/*==============================================================================
* Layout Manager Lifecycle
*============================================================================*/
LayoutManager* wm_layout_manager_get(void) {
return g_layout_manager;
}
bool wm_layout_manager_init(void) {
if (g_layout_manager) return true;
g_layout_manager = calloc(1, sizeof(LayoutManager));
if (!g_layout_manager) return false;
g_layout_manager->plugins = wm_list_new();
g_layout_manager->by_name = wm_hashmap_new_string_key();
if (!g_layout_manager->plugins || !g_layout_manager->by_name) {
wm_layout_manager_shutdown();
return false;
}
/* Register built-in layouts */
/* These will be implemented as static plugins */
g_layout_manager->initialized = true;
LOG_INFO("Layout manager initialized");
return true;
}
void wm_layout_manager_shutdown(void) {
if (!g_layout_manager) return;
/* Unload all plugins */
AbstractClient *client = NULL; /* Dummy for iteration */
(void)client;
/* Destroy all loaded plugins */
while (!wm_list_is_empty(g_layout_manager->plugins)) {
LayoutPlugin *plugin = wm_list_first(g_layout_manager->plugins);
wm_layout_manager_unload(g_layout_manager, plugin);
}
wm_list_destroy(g_layout_manager->plugins);
wm_hashmap_destroy(g_layout_manager->by_name);
free(g_layout_manager);
g_layout_manager = NULL;
LOG_INFO("Layout manager shutdown");
}
/*==============================================================================
* Layout Plugin Management
*============================================================================*/
bool wm_layout_manager_register(LayoutManager *mgr, LayoutPlugin *plugin) {
if (!mgr || !plugin || !plugin->interface) return false;
/* Check API version */
if (plugin->interface->api_version != WM_LAYOUT_PLUGIN_API_VERSION) {
LOG_ERROR("Layout plugin '%s' has incompatible API version %d (expected %d)",
plugin->interface->name, plugin->interface->api_version,
WM_LAYOUT_PLUGIN_API_VERSION);
return false;
}
/* Check if already registered */
if (wm_hashmap_contains_string(mgr->by_name, plugin->interface->name)) {
LOG_WARN("Layout plugin '%s' is already registered", plugin->interface->name);
return false;
}
/* Initialize plugin */
if (plugin->interface->init) {
if (!plugin->interface->init(plugin)) {
LOG_ERROR("Failed to initialize layout plugin '%s'", plugin->interface->name);
return false;
}
}
/* Add to lists */
wm_list_append(mgr->plugins, plugin);
wm_hashmap_insert_string(mgr->by_name, plugin->interface->name, plugin);
/* Set as default if first layout */
if (!mgr->default_layout) {
mgr->default_layout = plugin;
}
LOG_INFO("Registered layout plugin: %s (%s)",
plugin->interface->name, plugin->interface->description);
return true;
}
void wm_layout_manager_unregister(LayoutManager *mgr, LayoutPlugin *plugin) {
if (!mgr || !plugin) return;
/* Shutdown plugin */
if (plugin->interface && plugin->interface->shutdown) {
plugin->interface->shutdown(plugin);
}
/* Remove from lists */
wm_list_remove(mgr->plugins, plugin);
wm_hashmap_remove_string(mgr->by_name, plugin->interface->name);
/* Clear default if this was it */
if (mgr->default_layout == plugin) {
mgr->default_layout = wm_list_first(mgr->plugins);
}
LOG_INFO("Unregistered layout plugin: %s", plugin->interface->name);
}
LayoutPlugin* wm_layout_manager_load(LayoutManager *mgr, const char *path) {
if (!mgr || !path) return NULL;
void *handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (!handle) {
LOG_ERROR("Failed to load layout plugin '%s': %s", path, dlerror());
return NULL;
}
/* Get entry point */
union dlsym_cast cast;
cast.obj_ptr = dlsym(handle, WM_LAYOUT_PLUGIN_ENTRY);
LayoutPluginEntryFunc entry = cast.func_ptr;
if (!entry) {
LOG_ERROR("Layout plugin '%s' missing entry point '%s'",
path, WM_LAYOUT_PLUGIN_ENTRY);
dlclose(handle);
return NULL;
}
/* Get interface */
const LayoutPluginInterface *iface = entry();
if (!iface) {
LOG_ERROR("Layout plugin '%s' returned NULL interface", path);
dlclose(handle);
return NULL;
}
/* Create plugin instance */
LayoutPlugin *plugin = calloc(1, sizeof(LayoutPlugin));
if (!plugin) {
dlclose(handle);
return NULL;
}
plugin->interface = iface;
plugin->handle = handle;
plugin->path = strdup(path);
plugin->enabled = true;
/* Register */
if (!wm_layout_manager_register(mgr, plugin)) {
free(plugin->path);
free(plugin);
dlclose(handle);
return NULL;
}
return plugin;
}
void wm_layout_manager_unload(LayoutManager *mgr, LayoutPlugin *plugin) {
if (!mgr || !plugin) return;
void *handle = plugin->handle;
wm_layout_manager_unregister(mgr, plugin);
free(plugin->path);
/* Free workspace states */
if (plugin->workspace_states) {
for (int i = 0; i < plugin->num_workspaces; i++) {
if (plugin->workspace_states[i] && plugin->interface->state_destroy) {
plugin->interface->state_destroy(plugin, plugin->workspace_states[i]);
}
}
free(plugin->workspace_states);
}
free(plugin);
if (handle) {
dlclose(handle);
}
}
LayoutPlugin* wm_layout_manager_get_layout(LayoutManager *mgr, const char *name) {
if (!mgr || !name) return NULL;
return wm_hashmap_get_string(mgr->by_name, name);
}
LayoutPlugin* wm_layout_manager_get_default(LayoutManager *mgr) {
return mgr ? mgr->default_layout : NULL;
}
void wm_layout_manager_set_default(LayoutManager *mgr, LayoutPlugin *plugin) {
if (mgr) mgr->default_layout = plugin;
}
const char** wm_layout_manager_list(LayoutManager *mgr, int *count) {
if (!mgr || !count) return NULL;
*count = wm_list_size(mgr->plugins);
if (*count == 0) return NULL;
const char **names = malloc(*count * sizeof(const char*));
if (!names) return NULL;
int i = 0;
size_t idx = 0;
while (idx < wm_list_size(mgr->plugins)) {
LayoutPlugin *plugin = wm_list_get(mgr->plugins, idx++);
if (plugin) names[i++] = plugin->interface->name;
}
return names;
}
/*==============================================================================
* Layout Context
*============================================================================*/
static bool get_workspace_info(WmWorkspaceId workspace, WmLayoutWorkArea *work_area,
int *client_count, int *master_count, int *stack_count,
float *master_ratio, int *master_count_target) {
if (!dwn || !work_area || workspace < 0 || workspace >= MAX_WORKSPACES) {
return false;
}
Workspace *ws = &dwn->workspaces[workspace];
/* Calculate work area */
work_area->x = 0;
work_area->y = 0;
work_area->width = dwn->screen_width;
work_area->height = dwn->screen_height;
work_area->padding_top = 0;
work_area->padding_bottom = 0;
work_area->padding_left = 0;
work_area->padding_right = 0;
work_area->gap = 0;
if (dwn->config) {
work_area->gap = config_get_gap();
if (dwn->config->top_panel_enabled) {
work_area->padding_top = config_get_panel_height();
}
if (dwn->config->bottom_panel_enabled) {
work_area->padding_bottom = config_get_panel_height();
}
}
work_area->y += work_area->padding_top;
work_area->height -= work_area->padding_top + work_area->padding_bottom;
/* Count clients */
int count = 0;
int masters = 0;
int stacks = 0;
for (Client *c = ws->clients; c; c = c->next) {
if (!(c->flags & (CLIENT_MINIMIZED | CLIENT_UNMANAGING | CLIENT_FLOATING))) {
count++;
if (masters < ws->master_count) {
masters++;
} else {
stacks++;
}
}
}
*client_count = count;
*master_count = masters;
*stack_count = stacks;
*master_ratio = ws->master_ratio;
*master_count_target = ws->master_count;
return true;
}
bool wm_layout_context_init(LayoutContext *ctx, WmWorkspaceId workspace) {
if (!ctx || !g_layout_manager) return false;
memset(ctx, 0, sizeof(*ctx));
ctx->workspace = workspace;
if (!get_workspace_info(workspace, &ctx->work_area, &ctx->client_count,
&ctx->master_count, &ctx->stack_count,
&ctx->master_ratio, &ctx->master_count_target)) {
return false;
}
ctx->gap = ctx->work_area.gap;
return true;
}
void wm_layout_context_cleanup(LayoutContext *ctx) {
if (!ctx) return;
/* Nothing to cleanup currently */
}
/*==============================================================================
* Layout Arrangement
*============================================================================*/
typedef struct {
AbstractClient **clients;
WmLayoutGeometry *geometries;
int count;
int capacity;
} ArrangeData;
static bool collect_client(AbstractClient *client, void *data) {
ArrangeData *ad = data;
if (ad->count >= ad->capacity) return false;
/* Skip floating, minimized, and unmanaged clients */
if (wm_client_is_floating(client) ||
wm_client_is_minimized(client) ||
wm_client_has_state(client, WM_CLIENT_STATE_DESTROYING)) {
return true;
}
ad->clients[ad->count] = client;
ad->geometries[ad->count] = (WmLayoutGeometry){0};
ad->count++;
return true;
}
bool wm_layout_arrange(LayoutPlugin *plugin, WmWorkspaceId workspace) {
if (!plugin || !plugin->interface || !plugin->interface->arrange) {
return false;
}
/* Initialize context */
LayoutContext ctx;
if (!wm_layout_context_init(&ctx, workspace)) {
return false;
}
ctx.config = &plugin->config;
/* Get or create workspace state */
if (workspace >= plugin->num_workspaces) {
/* Expand workspace states array */
int new_size = workspace + 1;
WmLayoutState **new_states = realloc(plugin->workspace_states,
new_size * sizeof(WmLayoutState*));
if (!new_states) {
wm_layout_context_cleanup(&ctx);
return false;
}
/* Initialize new entries */
for (int i = plugin->num_workspaces; i < new_size; i++) {
new_states[i] = NULL;
}
plugin->workspace_states = new_states;
plugin->num_workspaces = new_size;
}
if (!plugin->workspace_states[workspace] && plugin->interface->state_create) {
plugin->workspace_states[workspace] =
plugin->interface->state_create(plugin, workspace);
}
ctx.state = plugin->workspace_states[workspace];
/* Collect clients */
int max_clients = wm_client_count_on_workspace(workspace);
if (max_clients == 0) {
wm_layout_context_cleanup(&ctx);
return true;
}
AbstractClient **clients = malloc(max_clients * sizeof(AbstractClient*));
WmLayoutGeometry *geometries = malloc(max_clients * sizeof(WmLayoutGeometry));
if (!clients || !geometries) {
free(clients);
free(geometries);
wm_layout_context_cleanup(&ctx);
return false;
}
ArrangeData data = { clients, geometries, 0, max_clients };
wm_client_foreach_on_workspace(workspace, collect_client, &data);
if (data.count == 0) {
free(clients);
free(geometries);
wm_layout_context_cleanup(&ctx);
return true;
}
/* Calculate layout */
bool success = plugin->interface->arrange(plugin, &ctx, clients, data.count, geometries);
/* Apply geometries */
if (success) {
for (int i = 0; i < data.count; i++) {
AbstractClient *client = clients[i];
WmLayoutGeometry *geom = &geometries[i];
if (geom->hidden) {
wm_client_hide(client);
} else {
wm_client_show(client);
if (geom->fullscreen) {
wm_client_set_state(client, WM_CLIENT_STATE_FULLSCREEN);
} else {
wm_client_move_resize(client, geom->x, geom->y,
geom->width, geom->height);
}
}
}
}
free(clients);
free(geometries);
wm_layout_context_cleanup(&ctx);
return success;
}
bool wm_layout_arrange_clients(LayoutPlugin *plugin, LayoutContext *ctx,
AbstractClient **clients, int num_clients) {
if (!plugin || !plugin->interface || !plugin->interface->arrange) {
return false;
}
WmLayoutGeometry *geometries = calloc(num_clients, sizeof(WmLayoutGeometry));
if (!geometries) return false;
bool success = plugin->interface->arrange(plugin, ctx, clients, num_clients, geometries);
if (success) {
for (int i = 0; i < num_clients; i++) {
WmLayoutGeometry *geom = &geometries[i];
if (!geom->hidden && !geom->fullscreen) {
wm_client_move_resize(clients[i], geom->x, geom->y,
geom->width, geom->height);
}
}
}
free(geometries);
return success;
}
+180
View File
@@ -0,0 +1,180 @@
/*
* DWN - Desktop Window Manager
* Built-in Layout Registration
*/
#include "plugins/layout_plugin.h"
#include "plugins/builtin_layouts.h"
#include "core/wm_list.h"
#include "dwn.h"
#include "util.h"
#include <stdlib.h>
/* External built-in layout interfaces */
extern const LayoutPluginInterface* wm_layout_tiling_get_interface(void);
extern const LayoutPluginInterface* wm_layout_floating_get_interface(void);
extern const LayoutPluginInterface* wm_layout_monocle_get_interface(void);
extern const LayoutPluginInterface* wm_layout_grid_get_interface(void);
/*==============================================================================
* Built-in Layout Registration
*============================================================================*/
static LayoutPlugin* register_builtin_layout(LayoutManager *mgr,
const LayoutPluginInterface *iface) {
if (!mgr || !iface) return NULL;
LayoutPlugin *plugin = calloc(1, sizeof(LayoutPlugin));
if (!plugin) return NULL;
plugin->interface = iface;
plugin->handle = NULL; /* Built-in, not dynamically loaded */
plugin->path = NULL;
plugin->enabled = true;
if (!wm_layout_manager_register(mgr, plugin)) {
free(plugin);
return NULL;
}
LOG_INFO("Registered built-in layout: %s", iface->name);
return plugin;
}
/*==============================================================================
* Initialize All Built-in Layouts
*============================================================================*/
bool wm_layouts_builtin_init(void) {
LayoutManager *mgr = wm_layout_manager_get();
if (!mgr) {
LOG_ERROR("Layout manager not initialized");
return false;
}
bool success = true;
/* Register tiling layout */
if (!register_builtin_layout(mgr, wm_layout_tiling_get_interface())) {
LOG_ERROR("Failed to register tiling layout");
success = false;
}
/* Register floating layout */
if (!register_builtin_layout(mgr, wm_layout_floating_get_interface())) {
LOG_ERROR("Failed to register floating layout");
success = false;
}
/* Register monocle layout */
if (!register_builtin_layout(mgr, wm_layout_monocle_get_interface())) {
LOG_ERROR("Failed to register monocle layout");
success = false;
}
/* Register grid layout */
if (!register_builtin_layout(mgr, wm_layout_grid_get_interface())) {
LOG_ERROR("Failed to register grid layout");
success = false;
}
/* Set default layout */
LayoutPlugin *tiling = wm_layout_manager_get_layout(mgr, "tiling");
if (tiling) {
wm_layout_manager_set_default(mgr, tiling);
}
return success;
}
/*==============================================================================
* Get Layout by Type (Compatibility)
*============================================================================*/
LayoutPlugin* wm_layout_get_by_type(LayoutManager *mgr, LayoutType type) {
if (!mgr) mgr = wm_layout_manager_get();
if (!mgr) return NULL;
switch (type) {
case LAYOUT_TILING:
return wm_layout_manager_get_layout(mgr, "tiling");
case LAYOUT_FLOATING:
return wm_layout_manager_get_layout(mgr, "floating");
case LAYOUT_MONOCLE:
return wm_layout_manager_get_layout(mgr, "monocle");
default:
return wm_layout_manager_get_default(mgr);
}
}
/*==============================================================================
* Compatibility Bridge
*============================================================================*/
/**
* Bridge function to call layout arrangement through the new plugin system.
* This allows gradual migration from the old layout system.
*/
bool wm_layout_arrange_workspace(LayoutManager *mgr, int workspace, LayoutType type) {
if (!mgr) mgr = wm_layout_manager_get();
if (!mgr) return false;
LayoutPlugin *plugin = wm_layout_get_by_type(mgr, type);
if (!plugin) {
plugin = wm_layout_manager_get_default(mgr);
}
if (!plugin) {
LOG_ERROR("No layout available for workspace %d", workspace);
return false;
}
return wm_layout_arrange(plugin, workspace);
}
/**
* Get the symbol for a layout type.
*/
const char* wm_layout_get_symbol_for_type(LayoutType type) {
switch (type) {
case LAYOUT_TILING:
return "[]=";
case LAYOUT_FLOATING:
return "><>";
case LAYOUT_MONOCLE:
return "[M]";
default:
return "???";
}
}
/**
* Get the name for a layout type.
*/
const char* wm_layout_get_name_for_type(LayoutType type) {
switch (type) {
case LAYOUT_TILING:
return "tiling";
case LAYOUT_FLOATING:
return "floating";
case LAYOUT_MONOCLE:
return "monocle";
default:
return "unknown";
}
}
/**
* Get LayoutType from layout name.
*/
LayoutType wm_layout_type_from_name(const char *name) {
if (!name) return LAYOUT_TILING;
if (strcmp(name, "tiling") == 0) return LAYOUT_TILING;
if (strcmp(name, "floating") == 0) return LAYOUT_FLOATING;
if (strcmp(name, "monocle") == 0) return LAYOUT_MONOCLE;
if (strcmp(name, "grid") == 0) return LAYOUT_TILING; /* Default to tiling for unknown */
return LAYOUT_TILING;
}
+126
View File
@@ -0,0 +1,126 @@
/*
* DWN - Desktop Window Manager
* Floating Layout Plugin (Built-in)
*/
#include "plugins/layout_plugin.h"
#include "core/wm_client.h"
#include "util.h"
#include <stdlib.h>
/*==============================================================================
* Floating Layout Interface
*============================================================================*/
static bool floating_init(LayoutPlugin *plugin) {
LOG_INFO("Floating layout initialized");
(void)plugin;
return true;
}
static void floating_shutdown(LayoutPlugin *plugin) {
LOG_INFO("Floating layout shutdown");
(void)plugin;
}
static WmLayoutState* floating_state_create(LayoutPlugin *plugin, WmWorkspaceId workspace) {
(void)plugin;
(void)workspace;
/* No state needed for floating layout */
return NULL;
}
static void floating_state_destroy(LayoutPlugin *plugin, WmLayoutState *state) {
(void)plugin;
(void)state;
}
static void floating_state_reset(LayoutPlugin *plugin, WmLayoutState *state) {
(void)plugin;
(void)state;
}
/*==============================================================================
* Floating Layout Calculation
*============================================================================*/
static bool floating_arrange(LayoutPlugin *plugin, LayoutContext *ctx,
AbstractClient **clients, int num_clients,
WmLayoutGeometry *geometries) {
(void)plugin;
(void)ctx;
(void)clients;
/* Floating layout doesn't arrange windows - they stay where they are */
/* Just mark all as floating */
for (int i = 0; i < num_clients; i++) {
geometries[i].floating = true;
geometries[i].hidden = false;
geometries[i].fullscreen = false;
/* x, y, width, height are ignored since floating = true */
}
return true;
}
/*==============================================================================
* Layout Configuration Parameters
*============================================================================*/
static WmLayoutParameter floating_parameters[] = {
{
.name = "constrain_to_workarea",
.description = "Keep floating windows within work area",
.type = WM_LAYOUT_PARAM_BOOL,
.default_value.bool_value = true
}
};
/*==============================================================================
* Layout Plugin Interface
*============================================================================*/
static LayoutPluginInterface floating_interface = {
.api_version = WM_LAYOUT_PLUGIN_API_VERSION,
.name = "floating",
.description = "Floating layout - windows can be moved freely",
.author = "DWN",
.version = "1.0",
.parameters = floating_parameters,
.num_parameters = sizeof(floating_parameters) / sizeof(floating_parameters[0]),
.init = floating_init,
.shutdown = floating_shutdown,
.state_create = floating_state_create,
.state_destroy = floating_state_destroy,
.state_reset = floating_state_reset,
.config_parse = NULL,
.config_apply = NULL,
.arrange = floating_arrange,
.client_added = NULL,
.client_removed = NULL,
.client_floating_changed = NULL,
.inc_master = NULL,
.set_master_ratio = NULL,
.set_master_count = NULL,
.swap_master = NULL,
.rotate = NULL,
.resize_master = NULL
};
/*==============================================================================
* Exported Interface
*============================================================================*/
const LayoutPluginInterface* wm_layout_floating_get_interface(void) {
return &floating_interface;
}
WM_LAYOUT_REGISTER(floating, floating_interface)
+167
View File
@@ -0,0 +1,167 @@
/*
* DWN - Desktop Window Manager
* Grid Layout Plugin (Built-in)
*/
#include "plugins/layout_plugin.h"
#include "core/wm_client.h"
#include "util.h"
#include <stdlib.h>
#include <math.h>
/*==============================================================================
* Grid Layout Interface
*============================================================================*/
static bool grid_init(LayoutPlugin *plugin) {
LOG_INFO("Grid layout initialized");
(void)plugin;
return true;
}
static void grid_shutdown(LayoutPlugin *plugin) {
LOG_INFO("Grid layout shutdown");
(void)plugin;
}
static WmLayoutState* grid_state_create(LayoutPlugin *plugin, WmWorkspaceId workspace) {
(void)plugin;
(void)workspace;
return NULL;
}
static void grid_state_destroy(LayoutPlugin *plugin, WmLayoutState *state) {
(void)plugin;
(void)state;
}
static void grid_state_reset(LayoutPlugin *plugin, WmLayoutState *state) {
(void)plugin;
(void)state;
}
/*==============================================================================
* Grid Layout Calculation
*============================================================================*/
static bool grid_arrange(LayoutPlugin *plugin, LayoutContext *ctx,
AbstractClient **clients, int num_clients,
WmLayoutGeometry *geometries) {
(void)plugin;
(void)clients;
if (num_clients == 0) return true;
WmLayoutWorkArea *wa = &ctx->work_area;
int gap = ctx->gap;
/* Calculate effective work area with padding */
int wx = wa->x + wa->padding_left + gap;
int wy = wa->y + wa->padding_top + gap;
int ww = wa->width - wa->padding_left - wa->padding_right - gap * 2;
int wh = wa->height - wa->padding_top - wa->padding_bottom - gap * 2;
if (num_clients == 1) {
geometries[0].x = wx;
geometries[0].y = wy;
geometries[0].width = ww;
geometries[0].height = wh;
geometries[0].floating = false;
return true;
}
/* Calculate grid dimensions */
int cols = (int)ceil(sqrt(num_clients));
int rows = (num_clients + cols - 1) / cols;
/* Adjust for gap */
int cell_w = (ww - gap * (cols - 1)) / cols;
int cell_h = (wh - gap * (rows - 1)) / rows;
int extra_w = (ww - gap * (cols - 1)) % cols;
int extra_h = (wh - gap * (rows - 1)) % rows;
for (int i = 0; i < num_clients; i++) {
int col = i % cols;
int row = i / cols;
geometries[i].x = wx + col * (cell_w + gap);
geometries[i].y = wy + row * (cell_h + gap);
geometries[i].width = cell_w + (col < extra_w ? 1 : 0);
geometries[i].height = cell_h + (row < extra_h ? 1 : 0);
geometries[i].floating = false;
/* Last row might have fewer cells */
if (row == rows - 1) {
int remaining = num_clients - row * cols;
if (cols > remaining) {
/* Center the remaining cells */
int offset = (ww - (remaining * cell_w + (remaining - 1) * gap)) / 2;
geometries[i].x = wx + offset + col * (cell_w + gap);
}
}
}
return true;
}
/*==============================================================================
* Layout Configuration Parameters
*============================================================================*/
static WmLayoutParameter grid_parameters[] = {
{
.name = "gap",
.description = "Gap between windows in pixels",
.type = WM_LAYOUT_PARAM_INT,
.default_value.int_value = 0
}
};
/*==============================================================================
* Layout Plugin Interface
*============================================================================*/
static LayoutPluginInterface grid_interface = {
.api_version = WM_LAYOUT_PLUGIN_API_VERSION,
.name = "grid",
.description = "Grid layout - windows arranged in a grid pattern",
.author = "DWN",
.version = "1.0",
.parameters = grid_parameters,
.num_parameters = sizeof(grid_parameters) / sizeof(grid_parameters[0]),
.init = grid_init,
.shutdown = grid_shutdown,
.state_create = grid_state_create,
.state_destroy = grid_state_destroy,
.state_reset = grid_state_reset,
.config_parse = NULL,
.config_apply = NULL,
.arrange = grid_arrange,
.client_added = NULL,
.client_removed = NULL,
.client_floating_changed = NULL,
.inc_master = NULL,
.set_master_ratio = NULL,
.set_master_count = NULL,
.swap_master = NULL,
.rotate = NULL,
.resize_master = NULL
};
/*==============================================================================
* Exported Interface
*============================================================================*/
const LayoutPluginInterface* wm_layout_grid_get_interface(void) {
return &grid_interface;
}
WM_LAYOUT_REGISTER(grid, grid_interface)
+182
View File
@@ -0,0 +1,182 @@
/*
* DWN - Desktop Window Manager
* Monocle Layout Plugin (Built-in)
*/
#include "plugins/layout_plugin.h"
#include "core/wm_client.h"
#include "util.h"
#include <stdlib.h>
/*==============================================================================
* Monocle Layout State
*============================================================================*/
typedef struct {
int focused_index; /* Which client is currently visible */
} MonocleState;
/*==============================================================================
* Monocle Layout Interface
*============================================================================*/
static bool monocle_init(LayoutPlugin *plugin) {
LOG_INFO("Monocle layout initialized");
(void)plugin;
return true;
}
static void monocle_shutdown(LayoutPlugin *plugin) {
LOG_INFO("Monocle layout shutdown");
(void)plugin;
}
static WmLayoutState* monocle_state_create(LayoutPlugin *plugin, WmWorkspaceId workspace) {
(void)plugin;
(void)workspace;
MonocleState *ms = calloc(1, sizeof(MonocleState));
ms->focused_index = 0;
return (WmLayoutState*)ms;
}
static void monocle_state_destroy(LayoutPlugin *plugin, WmLayoutState *state) {
(void)plugin;
free(state);
}
static void monocle_state_reset(LayoutPlugin *plugin, WmLayoutState *state) {
(void)plugin;
if (state) {
MonocleState *ms = (MonocleState*)state;
ms->focused_index = 0;
}
}
/*==============================================================================
* Monocle Layout Calculation
*============================================================================*/
static bool monocle_arrange(LayoutPlugin *plugin, LayoutContext *ctx,
AbstractClient **clients, int num_clients,
WmLayoutGeometry *geometries) {
(void)plugin;
(void)clients;
if (num_clients == 0) return true;
WmLayoutWorkArea *wa = &ctx->work_area;
int gap = ctx->gap;
/* Calculate effective work area with padding */
int wx = wa->x + wa->padding_left + gap;
int wy = wa->y + wa->padding_top + gap;
int ww = wa->width - wa->padding_left - wa->padding_right - gap * 2;
int wh = wa->height - wa->padding_top - wa->padding_bottom - gap * 2;
/* All clients take full area - they will be stacked */
for (int i = 0; i < num_clients; i++) {
geometries[i].x = wx;
geometries[i].y = wy;
geometries[i].width = ww;
geometries[i].height = wh;
geometries[i].floating = false;
geometries[i].hidden = false;
geometries[i].fullscreen = false;
}
return true;
}
/*==============================================================================
* Layout Manipulation
*============================================================================*/
static void monocle_rotate(LayoutPlugin *plugin, LayoutContext *ctx, bool clockwise) {
(void)plugin;
(void)ctx;
if (!ctx->state) return;
MonocleState *ms = (MonocleState*)ctx->state;
if (clockwise) {
ms->focused_index++;
if (ms->focused_index >= ctx->client_count) {
ms->focused_index = 0;
}
} else {
ms->focused_index--;
if (ms->focused_index < 0) {
ms->focused_index = ctx->client_count - 1;
}
}
}
/*==============================================================================
* Layout Configuration Parameters
*============================================================================*/
static WmLayoutParameter monocle_parameters[] = {
{
.name = "gaps",
.description = "Show gaps around the monocle window",
.type = WM_LAYOUT_PARAM_BOOL,
.default_value.bool_value = false
},
{
.name = "bar_height",
.description = "Height of client indicator bar",
.type = WM_LAYOUT_PARAM_INT,
.default_value.int_value = 4
}
};
/*==============================================================================
* Layout Plugin Interface
*============================================================================*/
static LayoutPluginInterface monocle_interface = {
.api_version = WM_LAYOUT_PLUGIN_API_VERSION,
.name = "monocle",
.description = "Monocle layout - one maximized window at a time",
.author = "DWN",
.version = "1.0",
.parameters = monocle_parameters,
.num_parameters = sizeof(monocle_parameters) / sizeof(monocle_parameters[0]),
.init = monocle_init,
.shutdown = monocle_shutdown,
.state_create = monocle_state_create,
.state_destroy = monocle_state_destroy,
.state_reset = monocle_state_reset,
.config_parse = NULL,
.config_apply = NULL,
.arrange = monocle_arrange,
.client_added = NULL,
.client_removed = NULL,
.client_floating_changed = NULL,
.inc_master = NULL,
.set_master_ratio = NULL,
.set_master_count = NULL,
.swap_master = NULL,
.rotate = monocle_rotate,
.resize_master = NULL
};
/*==============================================================================
* Exported Interface
*============================================================================*/
const LayoutPluginInterface* wm_layout_monocle_get_interface(void) {
return &monocle_interface;
}
WM_LAYOUT_REGISTER(monocle, monocle_interface)
+286
View File
@@ -0,0 +1,286 @@
/*
* DWN - Desktop Window Manager
* Tiling Layout Plugin (Built-in)
*/
#include "plugins/layout_plugin.h"
#include "core/wm_client.h"
#include "util.h"
#include <stdlib.h>
#include <string.h>
/*==============================================================================
* Tiling Layout State
*============================================================================*/
typedef struct {
int dummy; /* Placeholder for future state */
} TilingState;
/*==============================================================================
* Tiling Layout Interface
*============================================================================*/
static bool tiling_init(LayoutPlugin *plugin) {
LOG_INFO("Tiling layout initialized");
(void)plugin;
return true;
}
static void tiling_shutdown(LayoutPlugin *plugin) {
LOG_INFO("Tiling layout shutdown");
(void)plugin;
}
static WmLayoutState* tiling_state_create(LayoutPlugin *plugin, WmWorkspaceId workspace) {
(void)plugin;
(void)workspace;
/* Layout manager allocates WmLayoutState, we just return our plugin data */
TilingState *ts = calloc(1, sizeof(TilingState));
return (WmLayoutState*)ts; /* Cast to opaque type */
}
static void tiling_state_destroy(LayoutPlugin *plugin, WmLayoutState *state) {
(void)plugin;
free(state); /* state is actually TilingState* */
}
static void tiling_state_reset(LayoutPlugin *plugin, WmLayoutState *state) {
(void)plugin;
if (state) {
memset(state, 0, sizeof(TilingState));
}
}
/*==============================================================================
* Tiling Layout Calculation
*============================================================================*/
static bool tiling_arrange(LayoutPlugin *plugin, LayoutContext *ctx,
AbstractClient **clients, int num_clients,
WmLayoutGeometry *geometries) {
(void)plugin;
(void)clients;
if (num_clients == 0) return true;
WmLayoutWorkArea *wa = &ctx->work_area;
int gap = ctx->gap;
/* Calculate effective work area with padding */
int wx = wa->x + wa->padding_left;
int wy = wa->y + wa->padding_top;
int ww = wa->width - wa->padding_left - wa->padding_right;
int wh = wa->height - wa->padding_top - wa->padding_bottom;
/* Apply gap to work area */
wx += gap;
wy += gap;
ww -= gap * 2;
wh -= gap * 2;
if (num_clients == 1) {
/* Single client takes full area */
geometries[0].x = wx;
geometries[0].y = wy;
geometries[0].width = ww;
geometries[0].height = wh;
geometries[0].floating = false;
return true;
}
/* Calculate master area */
int master_count = ctx->master_count_target;
if (master_count < 1) master_count = 1;
if (master_count > num_clients) master_count = num_clients;
int stack_count = num_clients - master_count;
/* Calculate master width based on ratio */
int master_w = (stack_count > 0) ? (int)(ww * ctx->master_ratio) : ww;
int stack_w = ww - master_w;
/* Adjust for gap */
if (stack_count > 0) {
master_w -= gap / 2;
stack_w -= gap / 2;
}
/* Arrange master clients vertically */
int master_h = wh / master_count;
int master_h_remainder = wh % master_count;
for (int i = 0; i < master_count; i++) {
geometries[i].x = wx;
geometries[i].y = wy + i * master_h + (i < master_h_remainder ? i : master_h_remainder);
geometries[i].width = master_w;
geometries[i].height = master_h + (i < master_h_remainder ? 1 : 0);
geometries[i].floating = false;
/* Apply gap */
if (i > 0) {
geometries[i].y += gap;
geometries[i].height -= gap;
}
if (i < master_count - 1) {
geometries[i].height -= gap;
}
}
/* Arrange stack clients vertically */
if (stack_count > 0) {
int stack_x = wx + master_w + gap;
int stack_h = wh / stack_count;
int stack_h_remainder = wh % stack_count;
for (int i = 0; i < stack_count; i++) {
int idx = master_count + i;
geometries[idx].x = stack_x;
geometries[idx].y = wy + i * stack_h + (i < stack_h_remainder ? i : stack_h_remainder);
geometries[idx].width = stack_w;
geometries[idx].height = stack_h + (i < stack_h_remainder ? 1 : 0);
geometries[idx].floating = false;
/* Apply gap */
if (i > 0) {
geometries[idx].y += gap;
geometries[idx].height -= gap;
}
if (i < stack_count - 1) {
geometries[idx].height -= gap;
}
}
}
return true;
}
/*==============================================================================
* Layout Manipulation
*============================================================================*/
static void tiling_inc_master(LayoutPlugin *plugin, LayoutContext *ctx, int delta) {
(void)plugin;
int new_count = ctx->master_count_target + delta;
if (new_count < 1) new_count = 1;
if (new_count > ctx->client_count) new_count = ctx->client_count;
ctx->master_count_target = new_count;
}
static void tiling_set_master_ratio(LayoutPlugin *plugin, LayoutContext *ctx, float ratio) {
(void)plugin;
if (ratio < 0.1f) ratio = 0.1f;
if (ratio > 0.9f) ratio = 0.9f;
ctx->master_ratio = ratio;
}
static void tiling_set_master_count(LayoutPlugin *plugin, LayoutContext *ctx, int count) {
(void)plugin;
if (count < 1) count = 1;
if (count > ctx->client_count) count = ctx->client_count;
ctx->master_count_target = count;
}
static void tiling_swap_master(LayoutPlugin *plugin, LayoutContext *ctx) {
(void)plugin;
(void)ctx;
}
static void tiling_rotate(LayoutPlugin *plugin, LayoutContext *ctx, bool clockwise) {
(void)plugin;
(void)ctx;
(void)clockwise;
}
static void tiling_resize_master(LayoutPlugin *plugin, LayoutContext *ctx,
int x, int y, int *new_master_count, float *new_ratio) {
(void)plugin;
(void)x;
(void)y;
*new_master_count = ctx->master_count_target;
*new_ratio = ctx->master_ratio;
}
/*==============================================================================
* Layout Configuration Parameters
*============================================================================*/
static WmLayoutParameter tiling_parameters[] = {
{
.name = "master_ratio",
.description = "Ratio of screen width for master area",
.type = WM_LAYOUT_PARAM_FLOAT,
.default_value.float_value = 0.5f
},
{
.name = "master_count",
.description = "Number of clients in master area",
.type = WM_LAYOUT_PARAM_INT,
.default_value.int_value = 1
},
{
.name = "gap",
.description = "Gap between windows in pixels",
.type = WM_LAYOUT_PARAM_INT,
.default_value.int_value = 0
}
};
/*==============================================================================
* Layout Plugin Interface
*============================================================================*/
static LayoutPluginInterface tiling_interface = {
.api_version = WM_LAYOUT_PLUGIN_API_VERSION,
.name = "tiling",
.description = "Classic tiling layout with master and stack areas",
.author = "DWN",
.version = "1.0",
.parameters = tiling_parameters,
.num_parameters = sizeof(tiling_parameters) / sizeof(tiling_parameters[0]),
.init = tiling_init,
.shutdown = tiling_shutdown,
.state_create = tiling_state_create,
.state_destroy = tiling_state_destroy,
.state_reset = tiling_state_reset,
.config_parse = NULL,
.config_apply = NULL,
.arrange = tiling_arrange,
.client_added = NULL,
.client_removed = NULL,
.client_floating_changed = NULL,
.inc_master = tiling_inc_master,
.set_master_ratio = tiling_set_master_ratio,
.set_master_count = tiling_set_master_count,
.swap_master = tiling_swap_master,
.rotate = tiling_rotate,
.resize_master = tiling_resize_master
};
/*==============================================================================
* Exported Interface
*============================================================================*/
const LayoutPluginInterface* wm_layout_tiling_get_interface(void) {
return &tiling_interface;
}
/* Register as a built-in layout */
WM_LAYOUT_REGISTER(tiling, tiling_interface)
+580
View File
@@ -0,0 +1,580 @@
/*
* DWN - Desktop Window Manager
* Widget Plugin Manager Implementation
*/
#include "plugins/widget_plugin.h"
#include "core/wm_list.h"
#include "core/wm_hashmap.h"
#include "util.h"
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
/*==============================================================================
* Helper for casting dlsym result to function pointer (avoids ISO C warning)
*============================================================================*/
union dlsym_cast {
void *obj_ptr;
WidgetPluginEntryFunc func_ptr;
};
/*==============================================================================
* Internal Structures
*============================================================================*/
struct WidgetManager {
WmList *plugins; /* List of WidgetPlugin* */
WmHashMap *by_id; /* Map: widget ID -> WidgetPlugin* */
bool initialized;
};
struct WidgetPanel {
WmList *left_widgets;
WmList *center_widgets;
WmList *right_widgets;
WmRect geometry;
bool needs_redraw;
};
/*==============================================================================
* Global State
*============================================================================*/
static WidgetManager *g_widget_manager = NULL;
/*==============================================================================
* Widget Manager Lifecycle
*============================================================================*/
WidgetManager* wm_widget_manager_get(void) {
return g_widget_manager;
}
bool wm_widget_manager_init(void) {
if (g_widget_manager) return true;
g_widget_manager = calloc(1, sizeof(WidgetManager));
if (!g_widget_manager) return false;
g_widget_manager->plugins = wm_list_new();
g_widget_manager->by_id = wm_hashmap_new_string_key();
if (!g_widget_manager->plugins || !g_widget_manager->by_id) {
wm_widget_manager_shutdown();
return false;
}
LOG_INFO("Widget manager initialized");
return true;
}
void wm_widget_manager_shutdown(void) {
if (!g_widget_manager) return;
/* Destroy all instances and plugins */
while (!wm_list_is_empty(g_widget_manager->plugins)) {
WidgetPlugin *plugin = wm_list_first(g_widget_manager->plugins);
wm_widget_manager_unload(g_widget_manager, plugin);
}
wm_list_destroy(g_widget_manager->plugins);
wm_hashmap_destroy(g_widget_manager->by_id);
free(g_widget_manager);
g_widget_manager = NULL;
LOG_INFO("Widget manager shutdown");
}
/*==============================================================================
* Widget Plugin Management
*============================================================================*/
bool wm_widget_manager_register(WidgetManager *mgr, WidgetPlugin *plugin) {
if (!mgr || !plugin || !plugin->interface) return false;
/* Check API version */
if (plugin->interface->api_version != WM_WIDGET_PLUGIN_API_VERSION) {
LOG_ERROR("Widget plugin '%s' has incompatible API version %d (expected %d)",
plugin->interface->info.id, plugin->interface->api_version,
WM_WIDGET_PLUGIN_API_VERSION);
return false;
}
/* Check if already registered */
if (wm_hashmap_contains_string(mgr->by_id, plugin->interface->info.id)) {
LOG_WARN("Widget plugin '%s' is already registered",
plugin->interface->info.id);
return false;
}
/* Initialize plugin */
if (plugin->interface->init) {
if (!plugin->interface->init(plugin)) {
LOG_ERROR("Failed to initialize widget plugin '%s'",
plugin->interface->info.id);
return false;
}
}
/* Add to lists */
wm_list_append(mgr->plugins, plugin);
wm_hashmap_insert_string(mgr->by_id, plugin->interface->info.id, plugin);
LOG_INFO("Registered widget plugin: %s (%s)",
plugin->interface->info.id, plugin->interface->info.name);
return true;
}
void wm_widget_manager_unregister(WidgetManager *mgr, WidgetPlugin *plugin) {
if (!mgr || !plugin) return;
/* Destroy all instances */
WidgetInstance *instance = plugin->instances;
while (instance) {
WidgetInstance *next = instance->next;
wm_widget_destroy_instance(instance);
instance = next;
}
/* Shutdown plugin */
if (plugin->interface && plugin->interface->shutdown) {
plugin->interface->shutdown(plugin);
}
/* Remove from lists */
wm_list_remove(mgr->plugins, plugin);
wm_hashmap_remove_string(mgr->by_id, plugin->interface->info.id);
LOG_INFO("Unregistered widget plugin: %s", plugin->interface->info.id);
}
WidgetPlugin* wm_widget_manager_load(WidgetManager *mgr, const char *path) {
if (!mgr || !path) return NULL;
void *handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (!handle) {
LOG_ERROR("Failed to load widget plugin '%s': %s", path, dlerror());
return NULL;
}
/* Get entry point */
union dlsym_cast cast;
cast.obj_ptr = dlsym(handle, WM_WIDGET_PLUGIN_ENTRY);
WidgetPluginEntryFunc entry = cast.func_ptr;
if (!entry) {
LOG_ERROR("Widget plugin '%s' missing entry point '%s'",
path, WM_WIDGET_PLUGIN_ENTRY);
dlclose(handle);
return NULL;
}
/* Get interface */
const WidgetPluginInterface *iface = entry();
if (!iface) {
LOG_ERROR("Widget plugin '%s' returned NULL interface", path);
dlclose(handle);
return NULL;
}
/* Create plugin instance */
WidgetPlugin *plugin = calloc(1, sizeof(WidgetPlugin));
if (!plugin) {
dlclose(handle);
return NULL;
}
plugin->interface = iface;
plugin->handle = handle;
plugin->path = strdup(path);
plugin->enabled = true;
/* Register */
if (!wm_widget_manager_register(mgr, plugin)) {
free(plugin->path);
free(plugin);
dlclose(handle);
return NULL;
}
return plugin;
}
void wm_widget_manager_unload(WidgetManager *mgr, WidgetPlugin *plugin) {
if (!mgr || !plugin) return;
void *handle = plugin->handle;
wm_widget_manager_unregister(mgr, plugin);
free(plugin->path);
free(plugin);
if (handle) {
dlclose(handle);
}
}
WidgetPlugin* wm_widget_manager_get_widget(WidgetManager *mgr, const char *id) {
if (!mgr || !id) return NULL;
return wm_hashmap_get_string(mgr->by_id, id);
}
const char** wm_widget_manager_list(WidgetManager *mgr, int *count) {
if (!mgr || !count) return NULL;
*count = wm_list_size(mgr->plugins);
if (*count == 0) return NULL;
const char **ids = malloc(*count * sizeof(const char*));
if (!ids) return NULL;
size_t idx = 0;
int i = 0;
while (idx < wm_list_size(mgr->plugins)) {
WidgetPlugin *plugin = wm_list_get(mgr->plugins, idx++);
if (plugin) ids[i++] = plugin->interface->info.id;
}
return ids;
}
/*==============================================================================
* Widget Instance Operations
*============================================================================*/
WidgetInstance* wm_widget_create_instance(WidgetPlugin *plugin,
const WmWidgetConfig *config) {
if (!plugin || !plugin->interface) return NULL;
WidgetInstance *instance = NULL;
if (plugin->interface->instance_create) {
instance = plugin->interface->instance_create(plugin, config);
} else {
/* Create basic instance */
instance = calloc(1, sizeof(WidgetInstance));
}
if (!instance) return NULL;
instance->plugin = plugin;
instance->state = WM_WIDGET_STATE_NORMAL;
instance->constraints = plugin->interface->info.default_constraints;
/* Add to plugin's instance list */
instance->next = plugin->instances;
if (plugin->instances) {
plugin->instances->prev = instance;
}
plugin->instances = instance;
plugin->instance_count++;
LOG_DEBUG("Created widget instance of '%s'", plugin->interface->info.id);
return instance;
}
void wm_widget_destroy_instance(WidgetInstance *instance) {
if (!instance || !instance->plugin) return;
WidgetPlugin *plugin = instance->plugin;
/* Remove from plugin's instance list */
if (instance->prev) {
instance->prev->next = instance->next;
} else {
plugin->instances = instance->next;
}
if (instance->next) {
instance->next->prev = instance->prev;
}
plugin->instance_count--;
/* Destroy */
if (plugin->interface->instance_destroy) {
plugin->interface->instance_destroy(plugin, instance);
} else {
free(instance);
}
LOG_DEBUG("Destroyed widget instance of '%s'", plugin->interface->info.id);
}
void wm_widget_render(WidgetInstance *instance, WidgetContext *ctx) {
if (!instance || !instance->plugin || !ctx) return;
const WidgetPluginInterface *iface = instance->plugin->interface;
if (iface->render && !(instance->state & WM_WIDGET_STATE_HIDDEN)) {
instance->context = ctx;
iface->render(instance->plugin, instance, ctx);
}
}
bool wm_widget_send_event(WidgetInstance *instance, const WmWidgetEvent *event) {
if (!instance || !instance->plugin || !event) return false;
const WidgetPluginInterface *iface = instance->plugin->interface;
if (iface->handle_event) {
return iface->handle_event(instance->plugin, instance, event);
}
return false;
}
void wm_widget_update(WidgetInstance *instance) {
if (!instance || !instance->plugin) return;
const WidgetPluginInterface *iface = instance->plugin->interface;
if (iface->update) {
iface->update(instance->plugin, instance);
}
}
void wm_widget_get_preferred_size(WidgetInstance *instance,
int *width, int *height) {
if (!instance || !instance->plugin || !width || !height) return;
const WidgetPluginInterface *iface = instance->plugin->interface;
*width = instance->constraints.min_width;
*height = instance->constraints.min_height;
if (iface->get_preferred_size) {
iface->get_preferred_size(instance->plugin, instance, width, height);
}
}
/*==============================================================================
* Widget Panel Operations
*============================================================================*/
WidgetPanel* wm_widget_panel_create(void) {
WidgetPanel *panel = calloc(1, sizeof(WidgetPanel));
if (!panel) return NULL;
panel->left_widgets = wm_list_new();
panel->center_widgets = wm_list_new();
panel->right_widgets = wm_list_new();
panel->needs_redraw = true;
if (!panel->left_widgets || !panel->center_widgets || !panel->right_widgets) {
wm_widget_panel_destroy(panel);
return NULL;
}
return panel;
}
void wm_widget_panel_destroy(WidgetPanel *panel) {
if (!panel) return;
/* Destroy all widget instances */
WidgetInstance *instance;
while ((instance = wm_list_first(panel->left_widgets)) != NULL) {
wm_widget_destroy_instance(instance);
}
while ((instance = wm_list_first(panel->center_widgets)) != NULL) {
wm_widget_destroy_instance(instance);
}
while ((instance = wm_list_first(panel->right_widgets)) != NULL) {
wm_widget_destroy_instance(instance);
}
wm_list_destroy(panel->left_widgets);
wm_list_destroy(panel->center_widgets);
wm_list_destroy(panel->right_widgets);
free(panel);
}
void wm_widget_panel_add(WidgetPanel *panel, WidgetInstance *instance,
WmWidgetPosition position) {
if (!panel || !instance) return;
WmList *list;
switch (position) {
case WM_WIDGET_POSITION_LEFT:
list = panel->left_widgets;
break;
case WM_WIDGET_POSITION_CENTER:
list = panel->center_widgets;
break;
case WM_WIDGET_POSITION_RIGHT:
list = panel->right_widgets;
break;
default:
list = panel->left_widgets;
}
wm_list_append(list, instance);
panel->needs_redraw = true;
}
void wm_widget_panel_remove(WidgetPanel *panel, WidgetInstance *instance) {
if (!panel || !instance) return;
wm_list_remove(panel->left_widgets, instance);
wm_list_remove(panel->center_widgets, instance);
wm_list_remove(panel->right_widgets, instance);
panel->needs_redraw = true;
}
void wm_widget_panel_arrange(WidgetPanel *panel, const WmRect *panel_geometry) {
if (!panel || !panel_geometry) return;
panel->geometry = *panel_geometry;
int x = panel_geometry->x;
int y = panel_geometry->y;
int height = panel_geometry->height;
int center_x = panel_geometry->x + panel_geometry->width / 2;
int right_x = panel_geometry->x + panel_geometry->width;
/* Arrange left widgets */
size_t idx = 0;
while (idx < wm_list_size(panel->left_widgets)) {
WidgetInstance *instance = wm_list_get(panel->left_widgets, idx++);
if (!instance) continue;
int w, h;
wm_widget_get_preferred_size(instance, &w, &h);
instance->geometry.x = x;
instance->geometry.y = y + (height - h) / 2;
instance->geometry.width = w;
instance->geometry.height = h;
x += w;
}
/* Arrange right widgets (in reverse order) */
idx = wm_list_size(panel->right_widgets);
while (idx-- > 0) {
WidgetInstance *instance = wm_list_get(panel->right_widgets, idx);
if (!instance) continue;
int w, h;
wm_widget_get_preferred_size(instance, &w, &h);
right_x -= w;
instance->geometry.x = right_x;
instance->geometry.y = y + (height - h) / 2;
instance->geometry.width = w;
instance->geometry.height = h;
}
/* Arrange center widgets */
int total_center_width = 0;
idx = 0;
while (idx < wm_list_size(panel->center_widgets)) {
WidgetInstance *instance = wm_list_get(panel->center_widgets, idx++);
if (!instance) continue;
int w, h;
wm_widget_get_preferred_size(instance, &w, &h);
total_center_width += w;
}
x = center_x - total_center_width / 2;
idx = 0;
while (idx < wm_list_size(panel->center_widgets)) {
WidgetInstance *instance = wm_list_get(panel->center_widgets, idx++);
if (!instance) continue;
int w, h;
wm_widget_get_preferred_size(instance, &w, &h);
instance->geometry.x = x;
instance->geometry.y = y + (height - h) / 2;
instance->geometry.width = w;
instance->geometry.height = h;
x += w;
}
panel->needs_redraw = true;
}
void wm_widget_panel_render(WidgetPanel *panel) {
if (!panel) return;
/* Render left widgets */
size_t idx = 0;
while (idx < wm_list_size(panel->left_widgets)) {
WidgetInstance *instance = wm_list_get(panel->left_widgets, idx++);
if (instance) {
WidgetContext ctx = {0};
ctx.geometry = instance->geometry;
wm_widget_render(instance, &ctx);
}
}
/* Render center widgets */
idx = 0;
while (idx < wm_list_size(panel->center_widgets)) {
WidgetInstance *instance = wm_list_get(panel->center_widgets, idx++);
if (instance) {
WidgetContext ctx = {0};
ctx.geometry = instance->geometry;
wm_widget_render(instance, &ctx);
}
}
/* Render right widgets */
idx = 0;
while (idx < wm_list_size(panel->right_widgets)) {
WidgetInstance *instance = wm_list_get(panel->right_widgets, idx++);
if (instance) {
WidgetContext ctx = {0};
ctx.geometry = instance->geometry;
wm_widget_render(instance, &ctx);
}
}
panel->needs_redraw = false;
}
bool wm_widget_panel_handle_event(WidgetPanel *panel,
const WmWidgetEvent *event) {
if (!panel || !event) return false;
/* Check all widgets for hit testing */
WmList *lists[] = {
panel->left_widgets,
panel->center_widgets,
panel->right_widgets
};
for (int i = 0; i < 3; i++) {
size_t idx = 0;
while (idx < wm_list_size(lists[i])) {
WidgetInstance *instance = wm_list_get(lists[i], idx++);
if (!instance) continue;
WmWidgetGeometry *geom = &instance->geometry;
/* Simple hit testing */
if (event->data.point.x >= geom->x &&
event->data.point.x < geom->x + geom->width &&
event->data.point.y >= geom->y &&
event->data.point.y < geom->y + geom->height) {
if (wm_widget_send_event(instance, event)) {
return true;
}
}
}
}
return false;
}
+328
View File
@@ -0,0 +1,328 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* Window rules engine implementation
*/
#include "rules.h"
#include "config.h"
#include "client.h"
#include "workspace.h"
#include "util.h"
#include "layout.h"
#define _GNU_SOURCE
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <fnmatch.h>
static WindowRule rules[MAX_RULES];
static int rule_count = 0;
void rules_init(void)
{
rule_count = 0;
memset(rules, 0, sizeof(rules));
LOG_INFO("Window rules engine initialized");
}
void rules_cleanup(void)
{
rules_clear();
}
void rules_add(const WindowRule *rule)
{
if (rule == NULL) {
return;
}
if (rule_count >= MAX_RULES) {
LOG_WARN("Maximum number of window rules reached (%d)", MAX_RULES);
return;
}
memcpy(&rules[rule_count], rule, sizeof(WindowRule));
rule_count++;
LOG_DEBUG("Added window rule: class='%s' title='%s'",
rule->class_pattern, rule->title_pattern);
}
void rules_clear(void)
{
rule_count = 0;
memset(rules, 0, sizeof(rules));
}
int rules_count(void)
{
return rule_count;
}
bool rules_match_pattern(const char *str, const char *pattern)
{
if (str == NULL || pattern == NULL) {
return false;
}
if (pattern[0] == '\0') {
return true;
}
return fnmatch(pattern, str, FNM_CASEFOLD) == 0;
}
static bool rule_matches(const WindowRule *rule, const Client *client)
{
if (rule == NULL || client == NULL) {
return false;
}
switch (rule->match_type) {
case RULE_MATCH_CLASS:
return rules_match_pattern(client->class, rule->class_pattern);
case RULE_MATCH_TITLE:
return rules_match_pattern(client->title, rule->title_pattern);
case RULE_MATCH_CLASS_AND_TITLE:
return rules_match_pattern(client->class, rule->class_pattern) &&
rules_match_pattern(client->title, rule->title_pattern);
}
return false;
}
static void apply_rule(const WindowRule *rule, Client *client)
{
if (rule == NULL || client == NULL) {
return;
}
LOG_DEBUG("Applying rule to window '%s' (class: %s)",
client->title, client->class);
if (rule->has_workspace && rule->workspace >= 0 && rule->workspace < MAX_WORKSPACES) {
if (client->workspace != (unsigned int)rule->workspace) {
workspace_remove_client((int)client->workspace, client);
client->workspace = (unsigned int)rule->workspace;
workspace_add_client(rule->workspace, client);
LOG_DEBUG(" Moved to workspace %d", rule->workspace + 1);
}
}
if (rule->has_floating) {
if (rule->floating) {
client->flags |= CLIENT_FLOATING;
} else {
client->flags &= ~CLIENT_FLOATING;
}
LOG_DEBUG(" Set floating: %s", rule->floating ? "true" : "false");
}
if (rule->has_sticky) {
if (rule->sticky) {
client->flags |= CLIENT_STICKY;
} else {
client->flags &= ~CLIENT_STICKY;
}
LOG_DEBUG(" Set sticky: %s", rule->sticky ? "true" : "false");
}
if (rule->has_fullscreen) {
if (rule->fullscreen) {
client->flags |= CLIENT_FULLSCREEN;
} else {
client->flags &= ~CLIENT_FULLSCREEN;
}
LOG_DEBUG(" Set fullscreen: %s", rule->fullscreen ? "true" : "false");
}
if (rule->has_size) {
if (rule->width > 0) {
client->width = rule->width;
}
if (rule->height > 0) {
client->height = rule->height;
}
LOG_DEBUG(" Set size: %dx%d", client->width, client->height);
}
if (rule->has_position) {
int area_x, area_y, area_w, area_h;
layout_get_usable_area(&area_x, &area_y, &area_w, &area_h);
int title_h = config_get_title_height();
int border = client->border_width;
client->x = area_x + rule->x + border;
client->y = area_y + rule->y + title_h + border;
LOG_DEBUG(" Set position: %d,%d", client->x, client->y);
}
}
bool rules_apply_to_client(Client *client)
{
if (client == NULL) {
return false;
}
bool applied = false;
for (int i = 0; i < rule_count; i++) {
if (rule_matches(&rules[i], client)) {
apply_rule(&rules[i], client);
applied = true;
}
}
return applied;
}
static char *str_trim_whitespace(char *str)
{
if (str == NULL) {
return NULL;
}
while (isspace((unsigned char)*str)) {
str++;
}
if (*str == '\0') {
return str;
}
char *end = str + strlen(str) - 1;
while (end > str && isspace((unsigned char)*end)) {
end--;
}
*(end + 1) = '\0';
return str;
}
static bool parse_bool(const char *value)
{
if (value == NULL) {
return false;
}
return strcmp(value, "true") == 0 ||
strcmp(value, "1") == 0 ||
strcmp(value, "yes") == 0;
}
static void parse_rule_value(WindowRule *rule, const char *key, const char *value)
{
if (rule == NULL || key == NULL || value == NULL) {
return;
}
if (strcmp(key, "workspace") == 0) {
rule->has_workspace = true;
rule->workspace = atoi(value) - 1;
if (rule->workspace < 0) rule->workspace = 0;
if (rule->workspace >= MAX_WORKSPACES) rule->workspace = MAX_WORKSPACES - 1;
} else if (strcmp(key, "floating") == 0) {
rule->has_floating = true;
rule->floating = parse_bool(value);
} else if (strcmp(key, "sticky") == 0) {
rule->has_sticky = true;
rule->sticky = parse_bool(value);
} else if (strcmp(key, "fullscreen") == 0) {
rule->has_fullscreen = true;
rule->fullscreen = parse_bool(value);
} else if (strcmp(key, "width") == 0) {
rule->has_size = true;
rule->width = atoi(value);
} else if (strcmp(key, "height") == 0) {
rule->has_size = true;
rule->height = atoi(value);
} else if (strcmp(key, "x") == 0) {
rule->has_position = true;
rule->x = atoi(value);
} else if (strcmp(key, "y") == 0) {
rule->has_position = true;
rule->y = atoi(value);
} else if (strcmp(key, "opacity") == 0) {
rule->has_opacity = true;
rule->opacity = (float)atof(value);
if (rule->opacity < 0.0f) rule->opacity = 0.0f;
if (rule->opacity > 1.0f) rule->opacity = 1.0f;
}
}
static void parse_rule_line(const char *key, const char *value)
{
WindowRule rule;
memset(&rule, 0, sizeof(rule));
char key_copy[RULE_PATTERN_SIZE];
safe_strncpy(key_copy, key, sizeof(key_copy));
if (strncmp(key_copy, "class:", 6) == 0) {
rule.match_type = RULE_MATCH_CLASS;
safe_strncpy(rule.class_pattern, key_copy + 6, sizeof(rule.class_pattern));
} else if (strncmp(key_copy, "title:", 6) == 0) {
rule.match_type = RULE_MATCH_TITLE;
safe_strncpy(rule.title_pattern, key_copy + 6, sizeof(rule.title_pattern));
} else {
rule.match_type = RULE_MATCH_CLASS;
safe_strncpy(rule.class_pattern, key_copy, sizeof(rule.class_pattern));
}
char value_copy[512];
safe_strncpy(value_copy, value, sizeof(value_copy));
char *token = strtok(value_copy, ",");
while (token != NULL) {
char *trimmed = str_trim_whitespace(token);
char *eq = strchr(trimmed, ':');
if (eq != NULL) {
*eq = '\0';
char *prop_key = str_trim_whitespace(trimmed);
char *prop_val = str_trim_whitespace(eq + 1);
parse_rule_value(&rule, prop_key, prop_val);
}
token = strtok(NULL, ",");
}
rules_add(&rule);
}
static void rules_config_callback(const char *section, const char *key,
const char *value, void *user_data)
{
(void)user_data;
if (strcmp(section, "rules") != 0) {
return;
}
parse_rule_line(key, value);
}
bool rules_load(const char *path)
{
if (path == NULL) {
if (dwn == NULL || dwn->config == NULL) {
return false;
}
path = dwn->config->config_path;
}
int prev_count = rule_count;
config_parse_ini(path, rules_config_callback, NULL);
int loaded = rule_count - prev_count;
if (loaded > 0) {
LOG_INFO("Loaded %d window rules from config", loaded);
}
return loaded > 0;
}
+334 -228
View File
@@ -1,7 +1,7 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* Screenshot capture implementation using X11 and libpng
* Screenshot capture implementation - Production Hardened
*/
#include "screenshot.h"
@@ -13,6 +13,7 @@
#include <stdlib.h>
#include <string.h>
#include <stdatomic.h>
#include <setjmp.h>
#include <png.h>
static bool initialized = false;
@@ -23,6 +24,19 @@ static atomic_int screenshot_shutting_down = 0;
static const char base64_chars[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/* Thread state tracking to prevent double-join */
typedef enum {
THREAD_STATE_RUNNING,
THREAD_STATE_COMPLETED,
THREAD_STATE_JOINED
} ThreadState;
typedef struct ScreenshotRequestInternal {
ScreenshotRequest base;
ThreadState thread_state;
struct ScreenshotRequestInternal *next;
} ScreenshotRequestInternal;
bool screenshot_init(void)
{
atomic_store(&screenshot_shutting_down, 0);
@@ -34,45 +48,65 @@ bool screenshot_init(void)
void screenshot_cleanup(void)
{
atomic_store(&screenshot_shutting_down, 1);
pthread_mutex_lock(&screenshot_mutex);
while (screenshot_queue != NULL) {
ScreenshotRequest *req = screenshot_queue;
screenshot_queue = req->next;
pthread_mutex_unlock(&screenshot_mutex);
pthread_join(req->thread, NULL);
screenshot_result_free(&req->result);
ScreenshotRequestInternal *req = (ScreenshotRequestInternal *)screenshot_queue;
while (req != NULL) {
ScreenshotRequestInternal *next = req->next;
/* Only join if not already joined */
if (req->thread_state != THREAD_STATE_JOINED) {
pthread_mutex_unlock(&screenshot_mutex);
pthread_join(req->base.thread, NULL);
pthread_mutex_lock(&screenshot_mutex);
}
/* Free resources */
screenshot_result_free(&req->base.result);
dwn_free(req);
pthread_mutex_lock(&screenshot_mutex);
req = next;
}
screenshot_queue = NULL;
pthread_mutex_unlock(&screenshot_mutex);
initialized = false;
}
static size_t base64_encoded_size(size_t input_size)
{
/* Check for overflow */
if (input_size > ((size_t)-1 - 2) / 4 * 3) {
return 0;
}
return 4 * ((input_size + 2) / 3);
}
char *screenshot_to_base64(const ScreenshotResult *result, size_t *out_len)
{
if (result == NULL || result->data == NULL || result->size == 0) {
if (out_len) *out_len = 0;
return NULL;
}
size_t encoded_size = base64_encoded_size(result->size);
if (encoded_size == 0) {
if (out_len) *out_len = 0;
return NULL;
}
char *encoded = dwn_malloc(encoded_size + 1);
if (encoded == NULL) {
if (out_len) *out_len = 0;
return NULL;
}
const unsigned char *input = result->data;
size_t input_len = result->size;
char *output = encoded;
for (size_t i = 0; i < input_len; i += 3) {
unsigned int n = ((unsigned int)input[i]) << 16;
if (i + 1 < input_len) {
@@ -81,18 +115,18 @@ char *screenshot_to_base64(const ScreenshotResult *result, size_t *out_len)
if (i + 2 < input_len) {
n |= (unsigned int)input[i + 2];
}
*output++ = base64_chars[(n >> 18) & 0x3F];
*output++ = base64_chars[(n >> 12) & 0x3F];
*output++ = (i + 1 < input_len) ? base64_chars[(n >> 6) & 0x3F] : '=';
*output++ = (i + 2 < input_len) ? base64_chars[n & 0x3F] : '=';
}
*output = '\0';
if (out_len != NULL) {
*out_len = output - encoded;
*out_len = (size_t)(output - encoded);
}
return encoded;
}
@@ -136,19 +170,39 @@ typedef struct {
size_t capacity;
} PngBuffer;
typedef struct {
PngBuffer *buf;
unsigned char *row;
jmp_buf jmpbuf;
const char *error_msg;
} PngWriteContext;
static void png_write_callback(png_structp png, png_bytep data, png_size_t length)
{
PngBuffer *buf = (PngBuffer *)png_get_io_ptr(png);
if (buf == NULL) {
png_error(png, "Invalid buffer pointer");
return;
}
/* Check for addition overflow */
if (length > (size_t)-1 - buf->size) {
png_error(png, "Buffer size overflow");
return;
}
size_t new_size = buf->size + length;
if (new_size > buf->capacity) {
/* Grow capacity with overflow check */
size_t new_capacity = buf->capacity * 2;
if (new_capacity < new_size) {
new_capacity = new_size + 1024;
}
if (new_capacity < new_size || new_capacity > (size_t)-1 / 2) {
png_error(png, "Buffer capacity overflow");
return;
}
unsigned char *new_data = dwn_realloc(buf->data, new_capacity);
if (new_data == NULL) {
png_error(png, "Memory allocation failed");
@@ -157,9 +211,9 @@ static void png_write_callback(png_structp png, png_bytep data, png_size_t lengt
buf->data = new_data;
buf->capacity = new_capacity;
}
memcpy(buf->data + buf->size, data, length);
buf->size = new_size;
buf->size += length;
}
static void png_flush_callback(png_structp png)
@@ -167,59 +221,107 @@ static void png_flush_callback(png_structp png)
(void)png;
}
static void png_error_handler(png_structp png, png_const_charp msg)
{
PngWriteContext *ctx = (PngWriteContext *)png_get_error_ptr(png);
if (ctx != NULL) {
ctx->error_msg = msg;
longjmp(ctx->jmpbuf, 1);
}
}
static ScreenshotStatus ximage_to_png(XImage *img, ScreenshotResult *result)
{
if (img == NULL || result == NULL) {
return SCREENSHOT_ERROR_INVALID_ARG;
}
png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
/* Check for overflow in image dimensions */
if (img->width <= 0 || img->height <= 0) {
return SCREENSHOT_ERROR_INVALID_ARG;
}
if ((size_t)img->width > (size_t)-1 / (size_t)img->height / 3) {
return SCREENSHOT_ERROR_INVALID_ARG;
}
/* Initialize result */
memset(result, 0, sizeof(ScreenshotResult));
/* Calculate initial buffer capacity with overflow check */
size_t initial_capacity = (size_t)(img->width * img->height * 3 / 2 + 1024);
if (initial_capacity < 1024) {
return SCREENSHOT_ERROR_INVALID_ARG;
}
PngBuffer buf = {0};
buf.capacity = initial_capacity;
buf.data = dwn_malloc(buf.capacity);
if (buf.data == NULL) {
return SCREENSHOT_ERROR_NO_MEMORY;
}
/* Allocate row buffer */
size_t row_size = (size_t)img->width * 3;
if (row_size < (size_t)img->width) { /* Overflow check */
dwn_free(buf.data);
return SCREENSHOT_ERROR_NO_MEMORY;
}
unsigned char *row = dwn_malloc(row_size);
if (row == NULL) {
dwn_free(buf.data);
return SCREENSHOT_ERROR_NO_MEMORY;
}
/* Set up context for error handling */
PngWriteContext ctx;
ctx.buf = &buf;
ctx.row = row;
ctx.error_msg = NULL;
png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, &ctx, png_error_handler, NULL);
if (png == NULL) {
dwn_free(buf.data);
dwn_free(row);
return SCREENSHOT_ERROR_PNG;
}
png_infop info = png_create_info_struct(png);
if (info == NULL) {
png_destroy_write_struct(&png, NULL);
dwn_free(buf.data);
dwn_free(row);
return SCREENSHOT_ERROR_PNG;
}
if (setjmp(png_jmpbuf(png))) {
/* Set up error handling */
if (setjmp(ctx.jmpbuf)) {
/* Error occurred - cleanup all resources */
png_destroy_write_struct(&png, &info);
dwn_free(buf.data);
dwn_free(row);
LOG_ERROR("PNG encoding error: %s", ctx.error_msg ? ctx.error_msg : "unknown");
return SCREENSHOT_ERROR_PNG;
}
PngBuffer buf = {0};
buf.capacity = (size_t)(img->width * img->height * 3 / 2 + 1024);
buf.data = dwn_malloc(buf.capacity);
if (buf.data == NULL) {
png_destroy_write_struct(&png, &info);
return SCREENSHOT_ERROR_NO_MEMORY;
}
png_set_write_fn(png, &buf, png_write_callback, png_flush_callback);
png_set_IHDR(png, info, img->width, img->height, 8,
png_set_IHDR(png, info, (png_uint_32)img->width, (png_uint_32)img->height, 8,
PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_write_info(png, info);
unsigned char *row = dwn_malloc(img->width * 3);
if (row == NULL) {
dwn_free(buf.data);
png_destroy_write_struct(&png, &info);
return SCREENSHOT_ERROR_NO_MEMORY;
}
/* Calculate bit shifts for color extraction */
unsigned long red_mask = img->red_mask;
unsigned long green_mask = img->green_mask;
unsigned long blue_mask = img->blue_mask;
int red_shift = 0;
int green_shift = 0;
int blue_shift = 0;
while ((red_mask & 1) == 0 && red_shift < 32) {
red_shift++;
red_mask >>= 1;
@@ -232,7 +334,8 @@ static ScreenshotStatus ximage_to_png(XImage *img, ScreenshotResult *result)
blue_shift++;
blue_mask >>= 1;
}
/* Write image data */
for (int y = 0; y < img->height; y++) {
for (int x = 0; x < img->width; x++) {
unsigned long pixel = XGetPixel(img, x, y);
@@ -242,17 +345,17 @@ static ScreenshotStatus ximage_to_png(XImage *img, ScreenshotResult *result)
}
png_write_row(png, row);
}
png_write_end(png, info);
dwn_free(row);
png_destroy_write_struct(&png, &info);
dwn_free(row);
result->data = buf.data;
result->size = buf.size;
result->width = img->width;
result->height = img->height;
return SCREENSHOT_OK;
}
@@ -261,13 +364,11 @@ ScreenshotStatus screenshot_capture_fullscreen(ScreenshotResult *result)
if (result == NULL) {
return SCREENSHOT_ERROR_INVALID_ARG;
}
if (dwn == NULL || dwn->display == NULL) {
return SCREENSHOT_ERROR_X11;
}
memset(result, 0, sizeof(ScreenshotResult));
XImage *img = XGetImage(dwn->display, dwn->root,
0, 0, dwn->screen_width, dwn->screen_height,
AllPlanes, ZPixmap);
@@ -275,10 +376,10 @@ ScreenshotStatus screenshot_capture_fullscreen(ScreenshotResult *result)
LOG_ERROR("XGetImage failed for fullscreen capture");
return SCREENSHOT_ERROR_X11;
}
ScreenshotStatus status = ximage_to_png(img, result);
XDestroyImage(img);
return status;
}
@@ -287,29 +388,28 @@ ScreenshotStatus screenshot_capture_window(Window window, ScreenshotResult *resu
if (result == NULL) {
return SCREENSHOT_ERROR_INVALID_ARG;
}
if (dwn == NULL || dwn->display == NULL) {
return SCREENSHOT_ERROR_X11;
}
if (window == None) {
return SCREENSHOT_ERROR_WINDOW_NOT_FOUND;
}
memset(result, 0, sizeof(ScreenshotResult));
XWindowAttributes wa;
if (!XGetWindowAttributes(dwn->display, window, &wa)) {
return SCREENSHOT_ERROR_WINDOW_NOT_FOUND;
}
int x, y;
Window child;
XTranslateCoordinates(dwn->display, window, dwn->root, 0, 0, &x, &y, &child);
int width = wa.width;
int height = wa.height;
/* Clamp to screen bounds */
if (x < 0) {
width += x;
x = 0;
@@ -324,21 +424,21 @@ ScreenshotStatus screenshot_capture_window(Window window, ScreenshotResult *resu
if (y + height > dwn->screen_height) {
height = dwn->screen_height - y;
}
if (width <= 0 || height <= 0) {
return SCREENSHOT_ERROR_X11;
}
XImage *img = XGetImage(dwn->display, dwn->root, x, y, width, height,
AllPlanes, ZPixmap);
if (img == NULL) {
LOG_ERROR("XGetImage failed for window capture");
return SCREENSHOT_ERROR_X11;
}
ScreenshotStatus status = ximage_to_png(img, result);
XDestroyImage(img);
return status;
}
@@ -347,19 +447,19 @@ ScreenshotStatus screenshot_capture_active(ScreenshotResult *result)
if (result == NULL) {
return SCREENSHOT_ERROR_INVALID_ARG;
}
if (dwn == NULL) {
return SCREENSHOT_ERROR_X11;
}
Workspace *ws = workspace_get_current();
if (ws == NULL || ws->focused == NULL) {
return SCREENSHOT_ERROR_WINDOW_NOT_FOUND;
}
Client *c = ws->focused;
Window target = (c->frame != None) ? c->frame : c->window;
return screenshot_capture_window(target, result);
}
@@ -368,17 +468,16 @@ ScreenshotStatus screenshot_capture_area(int x, int y, int width, int height, Sc
if (result == NULL) {
return SCREENSHOT_ERROR_INVALID_ARG;
}
if (width <= 0 || height <= 0) {
return SCREENSHOT_ERROR_INVALID_ARG;
}
if (dwn == NULL || dwn->display == NULL) {
return SCREENSHOT_ERROR_X11;
}
memset(result, 0, sizeof(ScreenshotResult));
/* Clamp to screen bounds */
if (x < 0) {
width += x;
x = 0;
@@ -393,181 +492,179 @@ ScreenshotStatus screenshot_capture_area(int x, int y, int width, int height, Sc
if (y + height > dwn->screen_height) {
height = dwn->screen_height - y;
}
if (width <= 0 || height <= 0) {
return SCREENSHOT_ERROR_INVALID_ARG;
}
XImage *img = XGetImage(dwn->display, dwn->root, x, y, width, height,
AllPlanes, ZPixmap);
if (img == NULL) {
LOG_ERROR("XGetImage failed for area capture");
return SCREENSHOT_ERROR_X11;
}
ScreenshotStatus status = ximage_to_png(img, result);
XDestroyImage(img);
return status;
}
static void *screenshot_worker(void *arg)
{
ScreenshotRequest *req = (ScreenshotRequest *)arg;
ScreenshotRequestInternal *req = (ScreenshotRequestInternal *)arg;
if (atomic_load(&screenshot_shutting_down)) {
req->state = SCREENSHOT_STATE_ERROR;
req->status = SCREENSHOT_ERROR_X11;
req->base.status = SCREENSHOT_ERROR_X11;
req->base.state = SCREENSHOT_STATE_ERROR;
return NULL;
}
switch (req->mode) {
switch (req->base.mode) {
case SCREENSHOT_MODE_FULLSCREEN:
req->status = screenshot_capture_fullscreen(&req->result);
req->base.status = screenshot_capture_fullscreen(&req->base.result);
break;
case SCREENSHOT_MODE_WINDOW:
req->status = screenshot_capture_window(req->window, &req->result);
req->base.status = screenshot_capture_window(req->base.window, &req->base.result);
break;
case SCREENSHOT_MODE_ACTIVE:
req->status = screenshot_capture_active(&req->result);
req->base.status = screenshot_capture_active(&req->base.result);
break;
case SCREENSHOT_MODE_AREA:
req->status = screenshot_capture_area(req->x, req->y,
req->width, req->height,
&req->result);
req->base.status = screenshot_capture_area(req->base.x, req->base.y,
req->base.width, req->base.height,
&req->base.result);
break;
default:
req->base.status = SCREENSHOT_ERROR_INVALID_ARG;
break;
}
req->state = (req->status == SCREENSHOT_OK)
? SCREENSHOT_STATE_COMPLETED
: SCREENSHOT_STATE_ERROR;
req->base.state = (req->base.status == SCREENSHOT_OK)
? SCREENSHOT_STATE_COMPLETED
: SCREENSHOT_STATE_ERROR;
return NULL;
}
static ScreenshotRequest *screenshot_create_request(void)
{
if (!initialized || atomic_load(&screenshot_shutting_down)) {
return NULL;
}
ScreenshotRequestInternal *req = dwn_calloc(1, sizeof(ScreenshotRequestInternal));
if (req == NULL) {
return NULL;
}
req->base.state = SCREENSHOT_STATE_PENDING;
req->thread_state = THREAD_STATE_RUNNING;
return (ScreenshotRequest *)req;
}
static void screenshot_queue_add(ScreenshotRequestInternal *req)
{
pthread_mutex_lock(&screenshot_mutex);
req->next = (ScreenshotRequestInternal *)screenshot_queue;
screenshot_queue = (ScreenshotRequest *)req;
pthread_mutex_unlock(&screenshot_mutex);
}
static void screenshot_queue_remove(ScreenshotRequestInternal *req)
{
pthread_mutex_lock(&screenshot_mutex);
ScreenshotRequestInternal **pp = (ScreenshotRequestInternal **)&screenshot_queue;
while (*pp != NULL) {
if (*pp == req) {
*pp = req->next;
break;
}
pp = (ScreenshotRequestInternal **)&(*pp)->next;
}
pthread_mutex_unlock(&screenshot_mutex);
}
ScreenshotRequest *screenshot_capture_async(ScreenshotMode mode,
void (*callback)(ScreenshotRequest *))
{
if (!initialized || atomic_load(&screenshot_shutting_down)) {
ScreenshotRequest *base_req = screenshot_create_request();
if (base_req == NULL) {
return NULL;
}
ScreenshotRequest *req = dwn_calloc(1, sizeof(ScreenshotRequest));
if (req == NULL) {
return NULL;
}
req->mode = mode;
req->state = SCREENSHOT_STATE_PENDING;
req->callback = callback;
pthread_mutex_lock(&screenshot_mutex);
req->next = screenshot_queue;
screenshot_queue = req;
pthread_mutex_unlock(&screenshot_mutex);
if (pthread_create(&req->thread, NULL, screenshot_worker, req) != 0) {
pthread_mutex_lock(&screenshot_mutex);
ScreenshotRequest **pp = &screenshot_queue;
while (*pp != NULL) {
if (*pp == req) {
*pp = req->next;
break;
}
pp = &(*pp)->next;
}
pthread_mutex_unlock(&screenshot_mutex);
ScreenshotRequestInternal *req = (ScreenshotRequestInternal *)base_req;
req->base.mode = mode;
req->base.callback = callback;
screenshot_queue_add(req);
if (pthread_create(&req->base.thread, NULL, screenshot_worker, req) != 0) {
screenshot_queue_remove(req);
dwn_free(req);
return NULL;
}
LOG_DEBUG("Screenshot async request started (mode=%d)", mode);
return req;
return (ScreenshotRequest *)req;
}
ScreenshotRequest *screenshot_capture_window_async(Window window,
void (*callback)(ScreenshotRequest *))
{
if (!initialized || atomic_load(&screenshot_shutting_down)) {
ScreenshotRequest *base_req = screenshot_create_request();
if (base_req == NULL) {
return NULL;
}
ScreenshotRequest *req = dwn_calloc(1, sizeof(ScreenshotRequest));
if (req == NULL) {
return NULL;
}
req->mode = SCREENSHOT_MODE_WINDOW;
req->window = window;
req->state = SCREENSHOT_STATE_PENDING;
req->callback = callback;
pthread_mutex_lock(&screenshot_mutex);
req->next = screenshot_queue;
screenshot_queue = req;
pthread_mutex_unlock(&screenshot_mutex);
if (pthread_create(&req->thread, NULL, screenshot_worker, req) != 0) {
pthread_mutex_lock(&screenshot_mutex);
ScreenshotRequest **pp = &screenshot_queue;
while (*pp != NULL) {
if (*pp == req) {
*pp = req->next;
break;
}
pp = &(*pp)->next;
}
pthread_mutex_unlock(&screenshot_mutex);
ScreenshotRequestInternal *req = (ScreenshotRequestInternal *)base_req;
req->base.mode = SCREENSHOT_MODE_WINDOW;
req->base.window = window;
req->base.callback = callback;
screenshot_queue_add(req);
if (pthread_create(&req->base.thread, NULL, screenshot_worker, req) != 0) {
screenshot_queue_remove(req);
dwn_free(req);
return NULL;
}
LOG_DEBUG("Screenshot async window request started");
return req;
return (ScreenshotRequest *)req;
}
ScreenshotRequest *screenshot_capture_area_async(int x, int y, int w, int h,
void (*callback)(ScreenshotRequest *))
{
if (!initialized || atomic_load(&screenshot_shutting_down)) {
ScreenshotRequest *base_req = screenshot_create_request();
if (base_req == NULL) {
return NULL;
}
ScreenshotRequest *req = dwn_calloc(1, sizeof(ScreenshotRequest));
if (req == NULL) {
return NULL;
}
req->mode = SCREENSHOT_MODE_AREA;
req->x = x;
req->y = y;
req->width = w;
req->height = h;
req->state = SCREENSHOT_STATE_PENDING;
req->callback = callback;
pthread_mutex_lock(&screenshot_mutex);
req->next = screenshot_queue;
screenshot_queue = req;
pthread_mutex_unlock(&screenshot_mutex);
if (pthread_create(&req->thread, NULL, screenshot_worker, req) != 0) {
pthread_mutex_lock(&screenshot_mutex);
ScreenshotRequest **pp = &screenshot_queue;
while (*pp != NULL) {
if (*pp == req) {
*pp = req->next;
break;
}
pp = &(*pp)->next;
}
pthread_mutex_unlock(&screenshot_mutex);
ScreenshotRequestInternal *req = (ScreenshotRequestInternal *)base_req;
req->base.mode = SCREENSHOT_MODE_AREA;
req->base.x = x;
req->base.y = y;
req->base.width = w;
req->base.height = h;
req->base.callback = callback;
screenshot_queue_add(req);
if (pthread_create(&req->base.thread, NULL, screenshot_worker, req) != 0) {
screenshot_queue_remove(req);
dwn_free(req);
return NULL;
}
LOG_DEBUG("Screenshot async area request started");
return req;
return (ScreenshotRequest *)req;
}
void screenshot_process_pending(void)
@@ -575,54 +672,63 @@ void screenshot_process_pending(void)
if (atomic_load(&screenshot_shutting_down)) {
return;
}
pthread_mutex_lock(&screenshot_mutex);
ScreenshotRequest **pp = &screenshot_queue;
ScreenshotRequestInternal **pp = (ScreenshotRequestInternal **)&screenshot_queue;
while (*pp != NULL) {
ScreenshotRequest *req = *pp;
if (req->state == SCREENSHOT_STATE_COMPLETED ||
req->state == SCREENSHOT_STATE_ERROR) {
pthread_join(req->thread, NULL);
ScreenshotRequestInternal *req = *pp;
if (req->base.state == SCREENSHOT_STATE_COMPLETED ||
req->base.state == SCREENSHOT_STATE_ERROR) {
/* Remove from queue first */
*pp = req->next;
pthread_mutex_unlock(&screenshot_mutex);
if (req->callback != NULL) {
req->callback(req);
/* Join thread if not already joined */
if (req->thread_state != THREAD_STATE_JOINED) {
pthread_join(req->base.thread, NULL);
req->thread_state = THREAD_STATE_JOINED;
}
/* Invoke callback */
if (req->base.callback != NULL) {
req->base.callback((ScreenshotRequest *)req);
}
pthread_mutex_lock(&screenshot_mutex);
} else {
pp = &(*pp)->next;
pp = (ScreenshotRequestInternal **)&(*pp)->next;
}
}
pthread_mutex_unlock(&screenshot_mutex);
}
void screenshot_cancel(ScreenshotRequest *req)
void screenshot_cancel(ScreenshotRequest *base_req)
{
if (req == NULL) {
if (base_req == NULL) {
return;
}
pthread_mutex_lock(&screenshot_mutex);
ScreenshotRequest **pp = &screenshot_queue;
while (*pp != NULL) {
if (*pp == req) {
*pp = req->next;
break;
}
pp = &(*pp)->next;
ScreenshotRequestInternal *req = (ScreenshotRequestInternal *)base_req;
/* Remove from queue */
screenshot_queue_remove(req);
/* Note: We don't cancel the thread here as it could be in the middle of X11 operations.
* Instead, we let it complete and ignore the result. This is safer than pthread_cancel
* which could leave resources in an inconsistent state. */
/* Wait for completion */
if (req->thread_state != THREAD_STATE_JOINED) {
pthread_join(req->base.thread, NULL);
req->thread_state = THREAD_STATE_JOINED;
}
pthread_mutex_unlock(&screenshot_mutex);
pthread_cancel(req->thread);
pthread_join(req->thread, NULL);
screenshot_result_free(&req->result);
/* Free resources */
screenshot_result_free(&req->base.result);
dwn_free(req);
}
+326
View File
@@ -0,0 +1,326 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* Generic slider widget implementation
*/
#include "slider.h"
#include "config.h"
#include "util.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <X11/Xft/Xft.h>
/* XFT support for slider */
static XftDraw *slider_xft_draw = NULL;
static Drawable slider_xft_drawable = None;
static Visual *slider_cached_visual = NULL;
static XftDraw *slider_get_xft_draw(Drawable d)
{
if (slider_xft_drawable == d && slider_xft_draw != NULL) {
return slider_xft_draw;
}
if (slider_xft_draw != NULL) {
XftDrawDestroy(slider_xft_draw);
}
if (slider_cached_visual == NULL) {
slider_cached_visual = DefaultVisual(dwn->display, dwn->screen);
}
slider_xft_draw = XftDrawCreate(dwn->display, d, slider_cached_visual, dwn->colormap);
slider_xft_drawable = d;
return slider_xft_draw;
}
static int slider_get_text_width(const char *text)
{
if (dwn == NULL || text == NULL) {
return 0;
}
if (dwn->xft_font != NULL) {
XGlyphInfo extents;
XftTextExtentsUtf8(dwn->display, dwn->xft_font,
(const FcChar8 *)text, strlen(text), &extents);
return extents.xOff;
}
if (dwn->font != NULL) {
return XTextWidth(dwn->font, text, strlen(text));
}
return strlen(text) * 8;
}
static void slider_draw_text(Drawable d, int x, int y, const char *text, unsigned long color)
{
if (dwn == NULL || dwn->display == NULL || text == NULL) {
return;
}
if (dwn->xft_font != NULL) {
XftDraw *xft_draw = slider_get_xft_draw(d);
if (xft_draw != NULL) {
XRenderColor render_color;
render_color.red = ((color >> 16) & 0xFF) * 257;
render_color.green = ((color >> 8) & 0xFF) * 257;
render_color.blue = (color & 0xFF) * 257;
render_color.alpha = 0xFFFF;
XftColor xft_color;
XftColorAllocValue(dwn->display, slider_cached_visual, dwn->colormap,
&render_color, &xft_color);
XftDrawStringUtf8(xft_draw, &xft_color, dwn->xft_font,
x, y, (const FcChar8 *)text, strlen(text));
XftColorFree(dwn->display, slider_cached_visual, dwn->colormap, &xft_color);
return;
}
}
XSetForeground(dwn->display, dwn->gc, color);
XDrawString(dwn->display, d, dwn->gc, x, y, text, strlen(text));
}
/*============================================================================*/
GenericSlider *slider_create(int x, int y,
const char *label_prefix,
bool show_percentage,
SliderValueChangedCallback callback,
void *user_data)
{
if (dwn == NULL || dwn->display == NULL) {
return NULL;
}
GenericSlider *slider = dwn_calloc(1, sizeof(GenericSlider));
if (slider == NULL) {
return NULL;
}
slider->x = x;
slider->y = y;
slider->width = SLIDER_WIDTH;
slider->height = SLIDER_HEIGHT;
slider->value = 50;
slider->label_prefix = label_prefix;
slider->show_percentage = show_percentage;
slider->on_value_changed = callback;
slider->user_data = user_data;
slider->visible = false;
slider->dragging = false;
/* Create window */
XSetWindowAttributes attrs;
attrs.override_redirect = True;
attrs.background_pixel = config_get_colors()->panel_bg;
attrs.border_pixel = config_get_colors()->border_focused;
attrs.event_mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask | ExposureMask;
slider->window = XCreateWindow(
dwn->display,
dwn->root,
x, y, slider->width, slider->height,
1,
CopyFromParent,
CopyFromParent,
CopyFromParent,
CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWEventMask,
&attrs
);
return slider;
}
void slider_destroy(GenericSlider *slider)
{
if (slider == NULL) {
return;
}
if (slider->window != None) {
XDestroyWindow(dwn->display, slider->window);
}
dwn_free(slider);
}
void slider_show(GenericSlider *slider, int x, int y)
{
if (slider == NULL || dwn == NULL || dwn->display == NULL) {
return;
}
slider->x = x;
slider->y = y;
/* Reposition window */
XMoveWindow(dwn->display, slider->window, x, y);
/* Ensure it's above the panel */
XWindowChanges changes;
changes.stack_mode = Above;
XConfigureWindow(dwn->display, slider->window, CWStackMode, &changes);
slider->visible = true;
XMapRaised(dwn->display, slider->window);
slider_render(slider);
}
void slider_hide(GenericSlider *slider)
{
if (slider == NULL || slider->window == None) {
return;
}
slider->visible = false;
slider->dragging = false;
XUnmapWindow(dwn->display, slider->window);
}
bool slider_is_visible(const GenericSlider *slider)
{
return slider != NULL && slider->visible;
}
void slider_render(GenericSlider *slider)
{
if (slider == NULL || slider->window == None || !slider->visible) {
return;
}
Display *dpy = dwn->display;
const ColorScheme *colors = config_get_colors();
/* Clear background */
XSetForeground(dpy, dwn->gc, colors->panel_bg);
XFillRectangle(dpy, slider->window, dwn->gc, 0, 0, slider->width, slider->height);
/* Draw track */
int track_x = (slider->width - 4) / 2;
int track_y = SLIDER_PADDING + 20; /* Leave room for label at top */
int track_height = slider->height - track_y - SLIDER_PADDING - 15; /* Room for value at bottom */
/* Background track */
XSetForeground(dpy, dwn->gc, colors->workspace_inactive);
XFillRectangle(dpy, slider->window, dwn->gc, track_x, track_y, 4, track_height);
/* Filled portion */
int fill_height = (slider->value * track_height) / 100;
int fill_y = track_y + track_height - fill_height;
XSetForeground(dpy, dwn->gc, colors->workspace_active);
XFillRectangle(dpy, slider->window, dwn->gc, track_x, fill_y, 4, fill_height);
/* Draw knob */
int knob_y = fill_y - (SLIDER_KNOB_HEIGHT / 2);
if (knob_y < track_y - 4) knob_y = track_y - 4;
if (knob_y > track_y + track_height - 4) knob_y = track_y + track_height - 4;
XSetForeground(dpy, dwn->gc, colors->panel_fg);
XFillRectangle(dpy, slider->window, dwn->gc,
track_x - 4, knob_y, 12, SLIDER_KNOB_HEIGHT);
/* Draw label at top */
char label_text[32];
snprintf(label_text, sizeof(label_text), "%s", slider->label_prefix);
int label_width = slider_get_text_width(label_text);
int label_x = (slider->width - label_width) / 2;
slider_draw_text(slider->window, label_x, 15, label_text, colors->panel_fg);
/* Draw value at bottom */
char value_text[16];
if (slider->show_percentage) {
snprintf(value_text, sizeof(value_text), "%d%%", slider->value);
} else {
snprintf(value_text, sizeof(value_text), "%d", slider->value);
}
int value_width = slider_get_text_width(value_text);
int value_x = (slider->width - value_width) / 2;
slider_draw_text(slider->window, value_x, slider->height - 4, value_text, colors->panel_fg);
XFlush(dpy);
}
void slider_handle_click(GenericSlider *slider, int x, int y)
{
(void)x;
if (slider == NULL) {
return;
}
slider->dragging = true;
/* Calculate new value from y position */
int track_y = SLIDER_PADDING + 20;
int track_height = slider->height - track_y - SLIDER_PADDING - 15;
int relative_y = y - track_y;
if (relative_y < 0) relative_y = 0;
if (relative_y > track_height) relative_y = track_height;
int new_value = 100 - (relative_y * 100 / track_height);
if (new_value < 0) new_value = 0;
if (new_value > 100) new_value = 100;
if (new_value != slider->value) {
slider->value = new_value;
slider_render(slider);
if (slider->on_value_changed) {
slider->on_value_changed(slider, slider->value);
}
}
}
void slider_handle_motion(GenericSlider *slider, int x, int y)
{
if (slider == NULL || !slider->visible || !slider->dragging) {
return;
}
slider_handle_click(slider, x, y);
}
void slider_handle_release(GenericSlider *slider)
{
if (slider == NULL) {
return;
}
slider->dragging = false;
}
void slider_set_value(GenericSlider *slider, int value)
{
if (slider == NULL) {
return;
}
if (value < 0) value = 0;
if (value > 100) value = 100;
slider->value = value;
if (slider->visible) {
slider_render(slider);
}
}
int slider_get_value(const GenericSlider *slider)
{
return slider != NULL ? slider->value : 0;
}
bool slider_hit_test(const GenericSlider *slider, int x, int y)
{
if (slider == NULL || !slider->visible) {
return false;
}
return (x >= slider->x && x < slider->x + slider->width &&
y >= slider->y && y < slider->y + slider->height);
}
+292
View File
@@ -10,6 +10,7 @@
#include "util.h"
#include "notifications.h"
#include "atoms.h"
#include "api.h"
#include <stdio.h>
#include <stdlib.h>
@@ -46,6 +47,12 @@ BatteryState battery_state = {0};
MultiBatteryState multi_battery_state = {0};
VolumeSlider *volume_slider = NULL;
/* Fade controls */
FadeControl fade_speed_control = {0};
FadeControl fade_intensity_control = {0};
static int fade_speed_icon_x = 0;
static int fade_intensity_icon_x = 0;
TrayIcon tray_icons[MAX_TRAY_ICONS];
int tray_icon_count = 0;
Window tray_selection_owner = None;
@@ -1223,3 +1230,288 @@ void xembed_update_icon_state(Window icon_win)
panel_render_all();
}
}
/*============================================================================*/
/* Fade Control Implementation */
/*============================================================================*/
/* Callback for speed slider value changes */
static void fade_speed_changed_callback(GenericSlider *slider, int value)
{
(void)slider;
/* Get old value before changing */
float old_speed = config_get_fade_speed();
/* Map 0-100 to 0.1-3.0 */
float speed = 0.1f + (value / 100.0f) * 2.9f;
LOG_DEBUG("Fade speed changed: slider_value=%d -> speed=%.2f", value, speed);
config_set_fade_speed(speed);
/* Update ambient speed in real-time */
if (dwn != NULL) {
dwn->ambient_speed = speed;
}
/* Emit WebSocket event */
api_emit_fade_speed_changed(old_speed, speed);
panel_render_all();
}
/* Callback for intensity slider value changes */
static void fade_intensity_changed_callback(GenericSlider *slider, int value)
{
(void)slider;
/* Get old value before changing */
float old_intensity = config_get_fade_intensity();
/* Map 0-100 to 0.0-1.0 */
float intensity = value / 100.0f;
LOG_DEBUG("Fade intensity changed: slider_value=%d -> intensity=%.2f", value, intensity);
config_set_fade_intensity(intensity);
/* Emit WebSocket event */
api_emit_fade_intensity_changed(old_intensity, intensity);
panel_render_all();
}
void fade_controls_init(void)
{
if (dwn == NULL || dwn->display == NULL) {
return;
}
/* Create speed slider */
fade_speed_control.slider = slider_create(0, 0, "Spd:", true,
fade_speed_changed_callback, NULL);
if (fade_speed_control.slider != NULL) {
/* Set initial value from config (map 0.1-3.0 to 0-100) */
float speed = config_get_fade_speed();
int slider_value = (int)((speed - 0.1f) / 2.9f * 100);
LOG_DEBUG("Fade controls init: speed=%.2f -> slider_value=%d", speed, slider_value);
slider_set_value(fade_speed_control.slider, slider_value);
}
/* Create intensity slider */
fade_intensity_control.slider = slider_create(0, 0, "Int:", true,
fade_intensity_changed_callback, NULL);
if (fade_intensity_control.slider != NULL) {
/* Set initial value from config (map 0.0-1.0 to 0-100) */
float intensity = config_get_fade_intensity();
LOG_DEBUG("Fade controls init: intensity=%.2f -> slider_value=%d", intensity, (int)(intensity * 100));
slider_set_value(fade_intensity_control.slider, (int)(intensity * 100));
}
}
void fade_controls_cleanup(void)
{
if (fade_speed_control.slider != NULL) {
slider_destroy(fade_speed_control.slider);
fade_speed_control.slider = NULL;
}
if (fade_intensity_control.slider != NULL) {
slider_destroy(fade_intensity_control.slider);
fade_intensity_control.slider = NULL;
}
}
void fade_controls_hide_all(void)
{
if (fade_speed_control.slider != NULL && slider_is_visible(fade_speed_control.slider)) {
slider_hide(fade_speed_control.slider);
}
if (fade_intensity_control.slider != NULL && slider_is_visible(fade_intensity_control.slider)) {
slider_hide(fade_intensity_control.slider);
}
}
void fade_controls_render(Panel *panel, int x)
{
if (panel == NULL || dwn == NULL) {
return;
}
const ColorScheme *colors = config_get_colors();
/* Calculate text_y same as systray_render_widgets */
int font_height = 12;
if (dwn->xft_font != NULL) {
font_height = dwn->xft_font->ascent;
} else if (dwn->font != NULL) {
font_height = dwn->font->ascent;
}
int text_y = (panel->height + font_height) / 2;
int current_x = x;
/* Render fade speed icon/button */
fade_speed_icon_x = current_x;
float speed = config_get_fade_speed();
char speed_label[16];
snprintf(speed_label, sizeof(speed_label), "S:%.1f", speed);
unsigned long speed_color = ambient_glow_bg(colors->panel_fg,
dwn->ambient_phase + PHASE_OFFSET_SYSTRAY);
draw_utf8_text(panel->buffer, current_x, text_y, speed_label, speed_color);
current_x += get_text_width(speed_label) + SYSTRAY_SPACING;
/* Render fade intensity icon/button */
fade_intensity_icon_x = current_x;
float intensity = config_get_fade_intensity();
char intensity_label[16];
snprintf(intensity_label, sizeof(intensity_label), "I:%d%%", (int)(intensity * 100));
unsigned long intensity_color = ambient_glow_bg(colors->panel_fg,
dwn->ambient_phase + PHASE_OFFSET_SYSTRAY);
draw_utf8_text(panel->buffer, current_x, text_y, intensity_label, intensity_color);
}
int fade_controls_get_width(void)
{
/* Calculate approximate width for both controls */
return 80; /* Approximate width for "S:0.5 I:100%" + spacing */
}
int fade_controls_hit_test(int x)
{
/* Check if x position hits any fade control icon */
/* Return 1 for speed, 2 for intensity, 0 for none */
if (x >= fade_speed_icon_x && x < fade_speed_icon_x + 40) {
return 1; /* Speed control */
}
if (x >= fade_intensity_icon_x && x < fade_intensity_icon_x + 50) {
return 2; /* Intensity control */
}
return 0;
}
void fade_controls_handle_click(int control_id, int x, int y, int button)
{
(void)x;
(void)y;
if (control_id == 1) {
/* Speed control clicked */
if (button == 1) {
/* Toggle speed slider */
if (fade_speed_control.slider == NULL) {
int panel_height = config_get_panel_height();
fade_speed_control.slider = slider_create(fade_speed_icon_x, panel_height,
"Spd:", true,
fade_speed_changed_callback, NULL);
if (fade_speed_control.slider != NULL) {
float speed = config_get_fade_speed();
int slider_value = (int)((speed - 0.1f) / 2.9f * 100);
slider_set_value(fade_speed_control.slider, slider_value);
}
}
if (fade_speed_control.slider != NULL) {
if (slider_is_visible(fade_speed_control.slider)) {
slider_hide(fade_speed_control.slider);
} else {
/* Hide other sliders */
if (volume_slider != NULL && volume_slider->visible) {
volume_slider_hide(volume_slider);
}
if (fade_intensity_control.slider != NULL &&
slider_is_visible(fade_intensity_control.slider)) {
slider_hide(fade_intensity_control.slider);
}
slider_show(fade_speed_control.slider, fade_speed_icon_x,
config_get_panel_height());
}
}
} else if (button == 4) {
/* Scroll up - increase speed */
float old_speed = config_get_fade_speed();
float speed = old_speed + 0.1f;
if (speed > 3.0f) speed = 3.0f;
config_set_fade_speed(speed);
if (dwn != NULL) {
dwn->ambient_speed = speed;
}
if (fade_speed_control.slider != NULL) {
int slider_value = (int)((speed - 0.1f) / 2.9f * 100);
slider_set_value(fade_speed_control.slider, slider_value);
}
api_emit_fade_speed_changed(old_speed, speed);
panel_render_all();
} else if (button == 5) {
/* Scroll down - decrease speed */
float old_speed = config_get_fade_speed();
float speed = old_speed - 0.1f;
if (speed < 0.1f) speed = 0.1f;
config_set_fade_speed(speed);
if (dwn != NULL) {
dwn->ambient_speed = speed;
}
if (fade_speed_control.slider != NULL) {
int slider_value = (int)((speed - 0.1f) / 2.9f * 100);
slider_set_value(fade_speed_control.slider, slider_value);
}
api_emit_fade_speed_changed(old_speed, speed);
panel_render_all();
}
} else if (control_id == 2) {
/* Intensity control clicked */
if (button == 1) {
/* Toggle intensity slider */
if (fade_intensity_control.slider == NULL) {
int panel_height = config_get_panel_height();
fade_intensity_control.slider = slider_create(fade_intensity_icon_x, panel_height,
"Int:", true,
fade_intensity_changed_callback, NULL);
if (fade_intensity_control.slider != NULL) {
float intensity = config_get_fade_intensity();
slider_set_value(fade_intensity_control.slider, (int)(intensity * 100));
}
}
if (fade_intensity_control.slider != NULL) {
if (slider_is_visible(fade_intensity_control.slider)) {
slider_hide(fade_intensity_control.slider);
} else {
/* Hide other sliders */
if (volume_slider != NULL && volume_slider->visible) {
volume_slider_hide(volume_slider);
}
if (fade_speed_control.slider != NULL &&
slider_is_visible(fade_speed_control.slider)) {
slider_hide(fade_speed_control.slider);
}
slider_show(fade_intensity_control.slider, fade_intensity_icon_x,
config_get_panel_height());
}
}
} else if (button == 4) {
/* Scroll up - increase intensity */
float old_intensity = config_get_fade_intensity();
float intensity = old_intensity + 0.05f;
if (intensity > 1.0f) intensity = 1.0f;
config_set_fade_intensity(intensity);
if (fade_intensity_control.slider != NULL) {
slider_set_value(fade_intensity_control.slider, (int)(intensity * 100));
}
api_emit_fade_intensity_changed(old_intensity, intensity);
panel_render_all();
} else if (button == 5) {
/* Scroll down - decrease intensity */
float old_intensity = config_get_fade_intensity();
float intensity = old_intensity - 0.05f;
if (intensity < 0.0f) intensity = 0.0f;
config_set_fade_intensity(intensity);
if (fade_intensity_control.slider != NULL) {
slider_set_value(fade_intensity_control.slider, (int)(intensity * 100));
}
api_emit_fade_intensity_changed(old_intensity, intensity);
panel_render_all();
}
}
}
+581
View File
@@ -0,0 +1,581 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* Specialized Worker Threads - Implementation
*/
#include "thread_workers.h"
#include "util.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <dirent.h>
#include <curl/curl.h>
#include <errno.h>
/* ============================================================================
* I/O Worker Implementation
* ============================================================================ */
typedef struct {
char path[512];
IoCallback callback;
void *user_data;
void *data;
size_t size;
int error;
} IoOperation;
static AsyncContext *g_io_context = NULL;
static size_t dwn_curl_write_cb(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t total = size * nmemb;
IoOperation *op = userp;
void *new_data = realloc(op->data, op->size + total + 1);
if (!new_data) return 0;
op->data = new_data;
memcpy((char*)op->data + op->size, contents, total);
op->size += total;
((char*)op->data)[op->size] = '\0';
return total;
}
static void io_read_file_worker(void *user_data, atomic_int *cancelled)
{
(void)cancelled;
IoOperation *op = user_data;
int fd = open(op->path, O_RDONLY);
if (fd < 0) {
op->error = errno;
return;
}
struct stat st;
if (fstat(fd, &st) < 0) {
op->error = errno;
close(fd);
return;
}
op->size = st.st_size;
op->data = malloc(op->size + 1);
if (!op->data) {
op->error = ENOMEM;
close(fd);
return;
}
ssize_t n = read(fd, op->data, op->size);
close(fd);
if (n < 0) {
op->error = errno;
free(op->data);
op->data = NULL;
return;
}
((char*)op->data)[n] = '\0';
}
static void io_write_file_worker(void *user_data, atomic_int *cancelled)
{
(void)cancelled;
IoOperation *op = user_data;
int fd = open(op->path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) {
op->error = errno;
return;
}
ssize_t n = write(fd, op->data, op->size);
close(fd);
if (n < 0 || (size_t)n != op->size) {
op->error = errno;
return;
}
op->error = 0;
}
static void io_read_dir_worker(void *user_data, atomic_int *cancelled)
{
(void)cancelled;
IoOperation *op = user_data;
DIR *dir = opendir(op->path);
if (!dir) {
op->error = errno;
return;
}
size_t total_size = 0;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
total_size += strlen(entry->d_name) + 1;
}
rewinddir(dir);
op->data = malloc(total_size + 1);
if (!op->data) {
op->error = ENOMEM;
closedir(dir);
return;
}
char *p = op->data;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
size_t name_len = strlen(entry->d_name);
size_t remaining = total_size - (size_t)(p - (char*)op->data);
if (name_len + 1 > remaining) break;
memcpy(p, entry->d_name, name_len);
p[name_len] = '\0';
p += name_len + 1;
}
*p = '\0';
op->size = p - (char*)op->data;
closedir(dir);
}
static void io_http_get_worker(void *user_data, atomic_int *cancelled)
{
(void)cancelled;
IoOperation *op = user_data;
CURL *curl = curl_easy_init();
if (!curl) {
op->error = -1;
return;
}
curl_easy_setopt(curl, CURLOPT_URL, op->path);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, dwn_curl_write_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, op);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
/* Check for cancellation periodically */
/* Note: curl doesn't easily support cancellation mid-transfer */
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
op->error = res;
if (op->data) {
free(op->data);
op->data = NULL;
op->size = 0;
}
}
curl_easy_cleanup(curl);
}
static void io_operation_cleanup(Task *task, void *user_data, ThreadStatus status)
{
(void)task;
(void)status;
IoOperation *op = user_data;
if (op->callback) {
op->callback(op->data, op->size, op->error, op->user_data);
}
if (op->data && op->error != 0) {
free(op->data);
}
free(op);
}
bool io_worker_init(void)
{
if (g_io_context) return true;
g_io_context = async_context_create("io");
return g_io_context != NULL;
}
void io_worker_shutdown(void)
{
if (g_io_context) {
async_context_destroy(g_io_context);
g_io_context = NULL;
}
}
TaskHandle io_read_file_async(const char *path, IoCallback callback, void *user_data)
{
if (!g_io_context || !path) return NULL;
IoOperation *op = calloc(1, sizeof(IoOperation));
if (!op) return NULL;
strncpy(op->path, path, sizeof(op->path) - 1);
op->callback = callback;
op->user_data = user_data;
TaskHandle task = task_create_with_callback(
io_read_file_worker, op, TASK_PRIORITY_NORMAL,
io_operation_cleanup, op
);
if (!task || thread_pool_submit(thread_pool_default(), task) != THREAD_OK) {
free(op);
return NULL;
}
return task;
}
TaskHandle io_write_file_async(const char *path, const void *data, size_t size,
IoCallback callback, void *user_data)
{
if (!g_io_context || !path || !data) return NULL;
IoOperation *op = calloc(1, sizeof(IoOperation));
if (!op) return NULL;
strncpy(op->path, path, sizeof(op->path) - 1);
op->data = malloc(size);
if (!op->data) {
free(op);
return NULL;
}
memcpy(op->data, data, size);
op->size = size;
op->callback = callback;
op->user_data = user_data;
TaskHandle task = task_create_with_callback(
io_write_file_worker, op, TASK_PRIORITY_NORMAL,
io_operation_cleanup, op
);
if (!task || thread_pool_submit(thread_pool_default(), task) != THREAD_OK) {
free(op->data);
free(op);
return NULL;
}
return task;
}
TaskHandle io_read_dir_async(const char *path, IoCallback callback, void *user_data)
{
if (!g_io_context || !path) return NULL;
IoOperation *op = calloc(1, sizeof(IoOperation));
if (!op) return NULL;
strncpy(op->path, path, sizeof(op->path) - 1);
op->callback = callback;
op->user_data = user_data;
TaskHandle task = task_create_with_callback(
io_read_dir_worker, op, TASK_PRIORITY_NORMAL,
io_operation_cleanup, op
);
if (!task || thread_pool_submit(thread_pool_default(), task) != THREAD_OK) {
free(op);
return NULL;
}
return task;
}
TaskHandle io_http_get_async(const char *url, IoCallback callback, void *user_data)
{
if (!g_io_context || !url) return NULL;
IoOperation *op = calloc(1, sizeof(IoOperation));
if (!op) return NULL;
strncpy(op->path, url, sizeof(op->path) - 1);
op->callback = callback;
op->user_data = user_data;
TaskHandle task = task_create_with_callback(
io_http_get_worker, op, TASK_PRIORITY_NORMAL,
io_operation_cleanup, op
);
if (!task || thread_pool_submit(thread_pool_default(), task) != THREAD_OK) {
free(op);
return NULL;
}
return task;
}
/* ============================================================================
* System Worker Implementation
* ============================================================================ */
static AsyncContext *g_system_context = NULL;
static SystemStats g_cached_stats;
static pthread_mutex_t g_stats_mutex = PTHREAD_MUTEX_INITIALIZER;
static uint32_t g_stats_timer_id = 0;
static void parse_meminfo(uint64_t *total, uint64_t *available)
{
*total = 0;
*available = 0;
FILE *f = fopen("/proc/meminfo", "r");
if (!f) return;
char line[256];
while (fgets(line, sizeof(line), f)) {
if (strncmp(line, "MemTotal:", 9) == 0) {
sscanf(line, "MemTotal: %lu", total);
*total *= 1024;
} else if (strncmp(line, "MemAvailable:", 13) == 0) {
sscanf(line, "MemAvailable: %lu", available);
*available *= 1024;
break;
} else if (strncmp(line, "MemFree:", 8) == 0 && *available == 0) {
/* Fallback if MemAvailable not present */
sscanf(line, "MemFree: %lu", available);
*available *= 1024;
}
}
fclose(f);
}
static void parse_loadavg(float load[3])
{
FILE *f = fopen("/proc/loadavg", "r");
if (!f) return;
if (fscanf(f, "%f %f %f", &load[0], &load[1], &load[2]) != 3) {
load[0] = load[1] = load[2] = 0.0f;
}
fclose(f);
}
static void parse_stat(float *cpu_percent)
{
static uint64_t prev_idle = 0, prev_total = 0;
FILE *f = fopen("/proc/stat", "r");
if (!f) return;
char line[256];
if (fgets(line, sizeof(line), f)) {
unsigned long user, nice, system, idle, iowait, irq, softirq, steal;
sscanf(line, "cpu %lu %lu %lu %lu %lu %lu %lu %lu",
&user, &nice, &system, &idle, &iowait, &irq, &softirq, &steal);
uint64_t idle_time = idle + iowait;
uint64_t total_time = user + nice + system + idle + iowait + irq + softirq + steal;
uint64_t diff_idle = idle_time - prev_idle;
uint64_t diff_total = total_time - prev_total;
if (diff_total > 0) {
*cpu_percent = 100.0f * (1.0f - ((float)diff_idle / diff_total));
}
prev_idle = idle_time;
prev_total = total_time;
}
fclose(f);
}
static void system_stats_worker(void *user_data, atomic_int *cancelled)
{
(void)user_data;
(void)cancelled;
SystemStats stats;
memset(&stats, 0, sizeof(stats));
parse_stat(&stats.cpu_percent);
uint64_t mem_available = 0;
parse_meminfo(&stats.memory_total, &mem_available);
stats.memory_used = stats.memory_total - mem_available;
if (stats.memory_total > 0) {
stats.memory_percent = 100.0f * (float)stats.memory_used / stats.memory_total;
}
parse_loadavg(stats.load_avg);
FILE *f = fopen("/proc/uptime", "r");
if (f) {
double uptime = 0.0;
if (fscanf(f, "%lf", &uptime) == 1) {
stats.uptime_seconds = (uint64_t)uptime;
}
fclose(f);
}
pthread_mutex_lock(&g_stats_mutex);
g_cached_stats = stats;
pthread_mutex_unlock(&g_stats_mutex);
}
static void stats_timer_callback(TimerId id, void *user_data)
{
(void)id;
(void)user_data;
ASYNC(system_stats_worker, NULL);
}
bool system_worker_init(void)
{
if (g_system_context) return true;
g_system_context = async_context_create("system");
if (!g_system_context) return false;
/* Initial stats read */
system_stats_worker(NULL, NULL);
/* Start periodic updates */
g_stats_timer_id = timer_schedule_repeating(1000, stats_timer_callback, NULL);
return true;
}
void system_worker_shutdown(void)
{
if (g_stats_timer_id) {
timer_cancel(g_stats_timer_id);
g_stats_timer_id = 0;
}
if (g_system_context) {
async_context_destroy(g_system_context);
g_system_context = NULL;
}
}
bool system_worker_get_cached_stats(SystemStats *stats)
{
if (!stats) return false;
pthread_mutex_lock(&g_stats_mutex);
*stats = g_cached_stats;
pthread_mutex_unlock(&g_stats_mutex);
return true;
}
/* ============================================================================
* Deferred Worker Implementation
* ============================================================================ */
static bool g_deferred_initialized = false;
bool deferred_worker_init(void)
{
g_deferred_initialized = true;
return true;
}
void deferred_worker_shutdown(void)
{
g_deferred_initialized = false;
}
DeferredId deferred_after(uint64_t delay_ms, DeferredCallback callback, void *user_data)
{
if (!g_deferred_initialized) return 0;
return timer_schedule(delay_ms, (TimerCallback)callback, user_data);
}
DeferredId deferred_every(uint64_t interval_ms, DeferredCallback callback, void *user_data)
{
if (!g_deferred_initialized) return 0;
return timer_schedule_repeating(interval_ms, (TimerCallback)callback, user_data);
}
bool deferred_cancel(DeferredId id)
{
return timer_cancel(id);
}
uint32_t deferred_process(void)
{
return timer_process();
}
int deferred_get_poll_fd(void)
{
return timer_get_poll_fd();
}
/* ============================================================================
* Integration
* ============================================================================ */
bool thread_workers_init(void)
{
if (!io_worker_init()) return false;
if (!system_worker_init()) {
io_worker_shutdown();
return false;
}
if (!deferred_worker_init()) {
system_worker_shutdown();
io_worker_shutdown();
return false;
}
return true;
}
void thread_workers_shutdown(void)
{
deferred_worker_shutdown();
system_worker_shutdown();
io_worker_shutdown();
}
bool thread_workers_process_all(void)
{
bool work_done = false;
/* Process timers */
if (deferred_process() > 0) work_done = true;
/* Process event bus */
if (event_bus_process(event_bus_default()) > 0) work_done = true;
return work_done;
}
int thread_workers_get_poll_fds(int *fds)
{
int count = 0;
int fd = deferred_get_poll_fd();
if (fd >= 0) fds[count++] = fd;
/* Note: event bus fd would be added here if exposed */
return count;
}
+884
View File
@@ -0,0 +1,884 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* Extensive Abstract Threading Framework - Implementation
*/
#define _GNU_SOURCE
#include "threading.h"
#include "util.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/syscall.h>
#include <sys/eventfd.h>
#include <sys/timerfd.h>
#include <time.h>
#include <poll.h>
/* Use C11 atomic operations from stdatomic.h - no custom defines needed */
/* Linux-specific for gettid */
#ifndef SYS_gettid
#define SYS_gettid __NR_gettid
#endif
/* ============================================================================
* Task Implementation
* ============================================================================ */
struct Task {
TaskFunc func;
void *user_data;
TaskCallback on_complete;
void *callback_data;
TaskPriority priority;
_Atomic TaskState state;
_Atomic int cancelled;
Future *future; /* Optional associated future */
ThreadStatus result_status;
pthread_mutex_t mutex;
pthread_cond_t completed;
};
TaskHandle task_create(TaskFunc func, void *user_data, TaskPriority priority)
{
if (!func) return NULL;
Task *task = dwn_malloc(sizeof(Task));
if (!task) return NULL;
task->func = func;
task->user_data = user_data;
task->on_complete = NULL;
task->callback_data = NULL;
task->priority = priority;
atomic_store_explicit(&task->state, TASK_STATE_PENDING, ATOMIC_RELEASE);
atomic_store_explicit(&task->cancelled, 0, ATOMIC_RELEASE);
task->future = NULL;
task->result_status = THREAD_OK;
if (pthread_mutex_init(&task->mutex, NULL) != 0) {
dwn_free(task);
return NULL;
}
if (pthread_cond_init(&task->completed, NULL) != 0) {
pthread_mutex_destroy(&task->mutex);
dwn_free(task);
return NULL;
}
return task;
}
TaskHandle task_create_with_callback(TaskFunc func, void *user_data,
TaskPriority priority,
TaskCallback on_complete,
void *callback_data)
{
Task *task = task_create(func, user_data, priority);
if (!task) return NULL;
task->on_complete = on_complete;
task->callback_data = callback_data;
return task;
}
void task_destroy(TaskHandle task)
{
if (!task) return;
TaskState state = atomic_load_explicit(&task->state, ATOMIC_ACQUIRE);
if (state == TASK_STATE_RUNNING) {
/* Can't destroy running task */
return;
}
pthread_cond_destroy(&task->completed);
pthread_mutex_destroy(&task->mutex);
dwn_free(task);
}
bool task_cancel(TaskHandle task)
{
if (!task) return false;
atomic_store_explicit(&task->cancelled, 1, ATOMIC_RELEASE);
TaskState state = atomic_load_explicit(&task->state, ATOMIC_ACQUIRE);
return (state != TASK_STATE_COMPLETED && state != TASK_STATE_ERROR);
}
TaskState task_get_state(TaskHandle task)
{
if (!task) return TASK_STATE_ERROR;
return atomic_load_explicit(&task->state, ATOMIC_ACQUIRE);
}
ThreadStatus task_wait(TaskHandle task, uint64_t timeout_ms)
{
if (!task) return THREAD_ERROR_INVALID;
pthread_mutex_lock(&task->mutex);
TaskState state = atomic_load_explicit(&task->state, ATOMIC_ACQUIRE);
if (state != TASK_STATE_COMPLETED && state != TASK_STATE_ERROR &&
state != TASK_STATE_CANCELLED) {
if (timeout_ms == 0) {
/* Infinite wait */
pthread_cond_wait(&task->completed, &task->mutex);
} else {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += timeout_ms / 1000;
ts.tv_nsec += (timeout_ms % 1000) * 1000000;
if (ts.tv_nsec >= 1000000000) {
ts.tv_sec++;
ts.tv_nsec -= 1000000000;
}
int ret = pthread_cond_timedwait(&task->completed, &task->mutex, &ts);
if (ret == ETIMEDOUT) {
pthread_mutex_unlock(&task->mutex);
return THREAD_ERROR_TIMEOUT;
}
}
}
pthread_mutex_unlock(&task->mutex);
return task->result_status;
}
bool task_is_cancelled(TaskHandle task)
{
if (!task) return false;
return atomic_load_explicit(&task->cancelled, ATOMIC_ACQUIRE) != 0;
}
/* Internal: Execute task in worker thread */
static void task_execute(Task *task)
{
atomic_store_explicit(&task->state, TASK_STATE_RUNNING, ATOMIC_RELEASE);
/* Execute the actual work */
task->func(task->user_data, &task->cancelled);
/* Determine final state */
if (atomic_load_explicit(&task->cancelled, ATOMIC_ACQUIRE)) {
task->result_status = THREAD_ERROR;
atomic_store_explicit(&task->state, TASK_STATE_CANCELLED, ATOMIC_RELEASE);
} else {
atomic_store_explicit(&task->state, TASK_STATE_COMPLETED, ATOMIC_RELEASE);
}
/* Signal completion */
pthread_mutex_lock(&task->mutex);
pthread_cond_broadcast(&task->completed);
pthread_mutex_unlock(&task->mutex);
/* Call completion callback if set */
if (task->on_complete) {
task->on_complete(task, task->callback_data, task->result_status);
}
/* Set future result if associated */
if (task->future) {
future_set_result(task->future, (void*)(uintptr_t)task->result_status);
}
}
/* ============================================================================
* Lock-Free SPSC Queue Implementation
* ============================================================================ */
void spsc_queue_init(SpscQueue *q)
{
if (!q) return;
atomic_store_explicit(&q->head, 0, ATOMIC_RELEASE);
atomic_store_explicit(&q->tail, 0, ATOMIC_RELEASE);
}
bool spsc_queue_push(SpscQueue *q, void *item)
{
if (!q || !item) return false;
const uint64_t mask = SPSC_QUEUE_SIZE - 1;
uint64_t head = atomic_load_explicit(&q->head, ATOMIC_RELAXED);
uint64_t next = (head + 1) & mask;
/* Check if full */
if (next == atomic_load_explicit(&q->tail, ATOMIC_ACQUIRE)) {
return false;
}
q->buffer[head] = item;
atomic_store_explicit(&q->head, next, ATOMIC_RELEASE);
atomic_thread_fence(ATOMIC_RELEASE);
return true;
}
bool spsc_queue_pop(SpscQueue *q, void **item)
{
if (!q || !item) return false;
uint64_t tail = atomic_load_explicit(&q->tail, ATOMIC_RELAXED);
/* Check if empty */
if (tail == atomic_load_explicit(&q->head, ATOMIC_ACQUIRE)) {
return false;
}
*item = q->buffer[tail];
atomic_store_explicit(&q->tail, (tail + 1) & (SPSC_QUEUE_SIZE - 1), ATOMIC_RELEASE);
atomic_thread_fence(ATOMIC_RELEASE);
return true;
}
bool spsc_queue_empty(SpscQueue *q)
{
if (!q) return true;
return atomic_load_explicit(&q->head, ATOMIC_ACQUIRE) ==
atomic_load_explicit(&q->tail, ATOMIC_ACQUIRE);
}
uint64_t spsc_queue_size_approx(SpscQueue *q)
{
if (!q) return 0;
uint64_t head = atomic_load_explicit(&q->head, ATOMIC_ACQUIRE);
uint64_t tail = atomic_load_explicit(&q->tail, ATOMIC_ACQUIRE);
return (head - tail) & (SPSC_QUEUE_SIZE - 1);
}
/* ============================================================================
* Lock-Free MPSC Queue Implementation
* ============================================================================ */
/* Based on Dmitry Vyukov's MPMC queue */
struct MpscQueue {
struct Cell {
_Atomic(uintptr_t) sequence;
void *data;
} *buffer;
uint32_t capacity;
uint32_t mask;
CACHE_ALIGN _Atomic(uint64_t) head; /* Consumer position */
CACHE_ALIGN _Atomic(uint64_t) tail; /* Producer position */
};
MpscQueue* mpsc_queue_create(uint32_t capacity)
{
/* Round up to power of 2 */
uint32_t cap = 1;
while (cap < capacity) cap <<= 1;
MpscQueue *q = dwn_malloc(sizeof(MpscQueue));
if (!q) return NULL;
q->buffer = dwn_malloc(sizeof(struct Cell) * cap);
if (!q->buffer) {
dwn_free(q);
return NULL;
}
q->capacity = cap;
q->mask = cap - 1;
for (uint32_t i = 0; i < cap; i++) {
atomic_store_explicit(&q->buffer[i].sequence, i, ATOMIC_RELEASE);
}
atomic_store_explicit(&q->head, 0, ATOMIC_RELEASE);
atomic_store_explicit(&q->tail, 0, ATOMIC_RELEASE);
return q;
}
void mpsc_queue_destroy(MpscQueue *q)
{
if (!q) return;
dwn_free(q->buffer);
dwn_free(q);
}
bool mpsc_queue_push(MpscQueue *q, void *item)
{
if (!q || !item) return false;
struct Cell *cell;
uint64_t pos = atomic_load_explicit(&q->tail, ATOMIC_RELAXED);
for (;;) {
cell = &q->buffer[pos & q->mask];
uint64_t seq = atomic_load_explicit(&cell->sequence, ATOMIC_ACQUIRE);
if (seq < pos) {
/* Queue full */
return false;
}
if (seq == pos) {
/* Try to claim this slot */
if (atomic_compare_exchange_strong_explicit(
&q->tail, &pos, pos + 1,
ATOMIC_RELAXED, ATOMIC_RELAXED)) {
break;
}
/* Failed, retry */
} else {
/* Another thread moved tail, retry */
pos = atomic_load_explicit(&q->tail, ATOMIC_RELAXED);
}
}
cell->data = item;
atomic_store_explicit(&cell->sequence, pos + 1, ATOMIC_RELEASE);
return true;
}
bool mpsc_queue_pop(MpscQueue *q, void **item)
{
if (!q || !item) return false;
uint64_t pos = atomic_load_explicit(&q->head, ATOMIC_RELAXED);
struct Cell *cell = &q->buffer[pos & q->mask];
uint64_t seq = atomic_load_explicit(&cell->sequence, ATOMIC_ACQUIRE);
if (seq < pos + 1) {
/* Empty */
return false;
}
/* Only one consumer, no CAS needed */
atomic_store_explicit(&q->head, pos + 1, ATOMIC_RELAXED);
*item = cell->data;
atomic_store_explicit(&cell->sequence, pos + q->mask + 1, ATOMIC_RELEASE);
return true;
}
bool mpsc_queue_empty(MpscQueue *q)
{
if (!q) return true;
uint64_t head = atomic_load_explicit(&q->head, ATOMIC_ACQUIRE);
uint64_t tail = atomic_load_explicit(&q->tail, ATOMIC_ACQUIRE);
return head >= tail;
}
/* ============================================================================
* Thread Pool Implementation
* ============================================================================ */
/* Per-worker state for work stealing */
typedef struct {
pthread_t thread;
SpscQueue local_queue;
_Atomic int active;
_Atomic uint64_t tasks_processed;
uint32_t id;
ThreadPool *pool;
} PoolWorker;
struct ThreadPool {
ThreadPoolConfig config;
/* Priority queues (MPSC) */
MpscQueue *queues[TASK_PRIORITY_COUNT];
/* Worker threads */
PoolWorker *workers;
uint32_t worker_count;
_Atomic uint32_t active_workers;
/* Synchronization */
pthread_mutex_t mutex;
pthread_cond_t work_available;
_Atomic int shutdown;
_Atomic uint64_t total_tasks;
_Atomic uint64_t completed_tasks;
/* Event fd for signaling main thread */
int event_fd;
};
static void* worker_thread_func(void *arg);
ThreadPool* thread_pool_create(const ThreadPoolConfig *config)
{
ThreadPool *pool = dwn_malloc(sizeof(ThreadPool));
if (!pool) return NULL;
pool->config = config ? *config : THREAD_POOL_DEFAULT_CONFIG;
/* Create priority queues */
for (int i = 0; i < TASK_PRIORITY_COUNT; i++) {
pool->queues[i] = mpsc_queue_create(pool->config.queue_capacity);
if (!pool->queues[i]) {
for (int j = 0; j < i; j++) {
mpsc_queue_destroy(pool->queues[j]);
}
dwn_free(pool);
return NULL;
}
}
/* Allocate workers */
pool->workers = dwn_malloc(sizeof(PoolWorker) * pool->config.max_threads);
if (!pool->workers) {
for (int i = 0; i < TASK_PRIORITY_COUNT; i++) {
mpsc_queue_destroy(pool->queues[i]);
}
dwn_free(pool);
return NULL;
}
pool->worker_count = 0;
atomic_store_explicit(&pool->active_workers, 0, ATOMIC_RELEASE);
atomic_store_explicit(&pool->shutdown, 0, ATOMIC_RELEASE);
atomic_store_explicit(&pool->total_tasks, 0, ATOMIC_RELEASE);
atomic_store_explicit(&pool->completed_tasks, 0, ATOMIC_RELEASE);
pthread_mutex_init(&pool->mutex, NULL);
pthread_cond_init(&pool->work_available, NULL);
/* Event fd for notification */
pool->event_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
/* Start minimum threads */
for (uint32_t i = 0; i < pool->config.min_threads; i++) {
PoolWorker *w = &pool->workers[pool->worker_count];
spsc_queue_init(&w->local_queue);
w->id = pool->worker_count;
w->pool = pool;
atomic_store_explicit(&w->active, 1, ATOMIC_RELEASE);
atomic_store_explicit(&w->tasks_processed, 0, ATOMIC_RELEASE);
if (pthread_create(&w->thread, NULL, worker_thread_func, w) == 0) {
pool->worker_count++;
atomic_fetch_add_explicit(&pool->active_workers, 1, ATOMIC_RELAXED);
}
}
return pool;
}
static Task* steal_task(ThreadPool *pool, PoolWorker *thief)
{
/* Try to steal from other workers' local queues */
for (uint32_t i = 0; i < pool->config.steal_attempts; i++) {
uint32_t victim_idx = (thief->id + i + 1) % pool->worker_count;
PoolWorker *victim = &pool->workers[victim_idx];
if (victim == thief) continue;
void *task;
if (spsc_queue_pop(&victim->local_queue, &task)) {
return (Task*)task;
}
}
/* Try global priority queues */
for (int prio = TASK_PRIORITY_CRITICAL; prio < TASK_PRIORITY_COUNT; prio++) {
void *task;
if (mpsc_queue_pop(pool->queues[prio], &task)) {
return (Task*)task;
}
}
return NULL;
}
static void* worker_thread_func(void *arg)
{
PoolWorker *worker = arg;
ThreadPool *pool = worker->pool;
char name[16];
snprintf(name, sizeof(name), "dwn-worker-%u", worker->id);
threading_set_name(name);
while (!atomic_load_explicit(&pool->shutdown, ATOMIC_ACQUIRE)) {
Task *task = NULL;
/* Try local queue first */
if (!spsc_queue_pop(&worker->local_queue, (void**)&task)) {
/* Try to steal */
task = steal_task(pool, worker);
}
if (task) {
atomic_fetch_add_explicit(&worker->tasks_processed, 1, ATOMIC_RELAXED);
task_execute(task);
atomic_fetch_add_explicit(&pool->completed_tasks, 1, ATOMIC_RELEASE);
/* Signal completion via eventfd */
uint64_t one = 1;
ssize_t w __attribute__((unused)) = write(pool->event_fd, &one, sizeof(one));
} else {
/* No work - wait */
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_nsec += 1000000; /* 1ms */
if (ts.tv_nsec >= 1000000000) {
ts.tv_sec++;
ts.tv_nsec -= 1000000000;
}
pthread_mutex_lock(&pool->mutex);
pthread_cond_timedwait(&pool->work_available, &pool->mutex, &ts);
pthread_mutex_unlock(&pool->mutex);
}
}
atomic_fetch_sub_explicit(&pool->active_workers, 1, ATOMIC_RELAXED);
return NULL;
}
void thread_pool_destroy(ThreadPool *pool)
{
if (!pool) return;
thread_pool_shutdown(pool, 5000);
for (uint32_t i = 0; i < pool->worker_count; i++) {
pthread_join(pool->workers[i].thread, NULL);
}
for (int i = 0; i < TASK_PRIORITY_COUNT; i++) {
mpsc_queue_destroy(pool->queues[i]);
}
close(pool->event_fd);
pthread_cond_destroy(&pool->work_available);
pthread_mutex_destroy(&pool->mutex);
dwn_free(pool->workers);
dwn_free(pool);
}
ThreadStatus thread_pool_submit(ThreadPool *pool, TaskHandle task)
{
if (!pool || !task) return THREAD_ERROR_INVALID;
if (atomic_load_explicit(&pool->shutdown, ATOMIC_ACQUIRE)) {
return THREAD_ERROR_CLOSED;
}
Task *t = (Task*)task;
TaskPriority prio = t->priority;
/* Try to push to priority queue */
if (!mpsc_queue_push(pool->queues[prio], t)) {
return THREAD_ERROR_BUSY;
}
atomic_fetch_add_explicit(&pool->total_tasks, 1, ATOMIC_RELAXED);
/* Signal workers */
pthread_cond_broadcast(&pool->work_available);
/* Dynamically scale up if needed */
uint32_t active = atomic_load_explicit(&pool->active_workers, ATOMIC_ACQUIRE);
if (active < pool->config.max_threads && active < pool->worker_count + 2) {
/* Spawn additional thread */
pthread_mutex_lock(&pool->mutex);
if (pool->worker_count < pool->config.max_threads) {
PoolWorker *w = &pool->workers[pool->worker_count];
spsc_queue_init(&w->local_queue);
w->id = pool->worker_count;
w->pool = pool;
atomic_store_explicit(&w->active, 1, ATOMIC_RELEASE);
if (pthread_create(&w->thread, NULL, worker_thread_func, w) == 0) {
pool->worker_count++;
atomic_fetch_add_explicit(&pool->active_workers, 1, ATOMIC_RELAXED);
}
}
pthread_mutex_unlock(&pool->mutex);
}
return THREAD_OK;
}
ThreadStatus thread_pool_submit_func(ThreadPool *pool, TaskFunc func,
void *user_data, TaskPriority priority)
{
TaskHandle task = task_create(func, user_data, priority);
if (!task) return THREAD_ERROR_NOMEM;
ThreadStatus status = thread_pool_submit(pool, task);
if (status != THREAD_OK) {
task_destroy(task);
}
return status;
}
uint32_t thread_pool_active_count(ThreadPool *pool)
{
if (!pool) return 0;
return atomic_load_explicit(&pool->active_workers, ATOMIC_ACQUIRE);
}
uint32_t thread_pool_pending_count(ThreadPool *pool)
{
if (!pool) return 0;
uint64_t total = atomic_load_explicit(&pool->total_tasks, ATOMIC_ACQUIRE);
uint64_t completed = atomic_load_explicit(&pool->completed_tasks, ATOMIC_ACQUIRE);
return (uint32_t)(total - completed);
}
ThreadStatus thread_pool_shutdown(ThreadPool *pool, uint64_t timeout_ms)
{
(void)timeout_ms;
if (!pool) return THREAD_ERROR_INVALID;
atomic_store_explicit(&pool->shutdown, 1, ATOMIC_RELEASE);
pthread_cond_broadcast(&pool->work_available);
/* Cancel pending tasks */
for (int prio = 0; prio < TASK_PRIORITY_COUNT; prio++) {
void *task_ptr;
while (mpsc_queue_pop(pool->queues[prio], &task_ptr)) {
Task *t = (Task*)task_ptr;
atomic_store_explicit(&t->state, TASK_STATE_CANCELLED, ATOMIC_RELEASE);
}
}
return THREAD_OK;
}
/* ============================================================================
* Default Thread Pool
* ============================================================================ */
static ThreadPool *g_default_pool = NULL;
ThreadPool* thread_pool_default(void)
{
return g_default_pool;
}
ThreadStatus thread_pool_init_default(const ThreadPoolConfig *config)
{
if (g_default_pool) return THREAD_OK;
g_default_pool = thread_pool_create(config);
return g_default_pool ? THREAD_OK : THREAD_ERROR;
}
void thread_pool_shutdown_default(void)
{
if (g_default_pool) {
thread_pool_destroy(g_default_pool);
g_default_pool = NULL;
}
}
/* ============================================================================
* Thread-Local Storage
* ============================================================================ */
struct TlsKey {
pthread_key_t key;
};
TlsKey* tls_create(void (*destructor)(void*))
{
TlsKey *k = dwn_malloc(sizeof(TlsKey));
if (!k) return NULL;
if (pthread_key_create(&k->key, destructor) != 0) {
dwn_free(k);
return NULL;
}
return k;
}
void tls_destroy(TlsKey *key)
{
if (!key) return;
pthread_key_delete(key->key);
dwn_free(key);
}
void tls_set(TlsKey *key, void *value)
{
if (!key) return;
pthread_setspecific(key->key, value);
}
void* tls_get(TlsKey *key)
{
if (!key) return NULL;
return pthread_getspecific(key->key);
}
/* ============================================================================
* Read-Write Lock
* ============================================================================ */
struct RwLock {
pthread_rwlock_t lock;
};
RwLock* rwlock_create(void)
{
RwLock *l = dwn_malloc(sizeof(RwLock));
if (!l) return NULL;
if (pthread_rwlock_init(&l->lock, NULL) != 0) {
dwn_free(l);
return NULL;
}
return l;
}
void rwlock_destroy(RwLock *lock)
{
if (!lock) return;
pthread_rwlock_destroy(&lock->lock);
dwn_free(lock);
}
void rwlock_read_lock(RwLock *lock)
{
if (!lock) return;
pthread_rwlock_rdlock(&lock->lock);
}
bool rwlock_read_trylock(RwLock *lock)
{
if (!lock) return false;
return pthread_rwlock_tryrdlock(&lock->lock) == 0;
}
void rwlock_read_unlock(RwLock *lock)
{
if (!lock) return;
pthread_rwlock_unlock(&lock->lock);
}
void rwlock_write_lock(RwLock *lock)
{
if (!lock) return;
pthread_rwlock_wrlock(&lock->lock);
}
bool rwlock_write_trylock(RwLock *lock)
{
if (!lock) return false;
return pthread_rwlock_trywrlock(&lock->lock) == 0;
}
void rwlock_write_unlock(RwLock *lock)
{
if (!lock) return;
pthread_rwlock_unlock(&lock->lock);
}
/* ============================================================================
* Barrier
* ============================================================================ */
struct Barrier {
pthread_barrier_t barrier;
};
Barrier* barrier_create(uint32_t count)
{
Barrier *b = dwn_malloc(sizeof(Barrier));
if (!b) return NULL;
if (pthread_barrier_init(&b->barrier, NULL, count) != 0) {
dwn_free(b);
return NULL;
}
return b;
}
void barrier_destroy(Barrier *b)
{
if (!b) return;
pthread_barrier_destroy(&b->barrier);
dwn_free(b);
}
bool barrier_wait(Barrier *b, uint64_t timeout_ms)
{
(void)timeout_ms;
if (!b) return false;
int ret = pthread_barrier_wait(&b->barrier);
return (ret == 0 || ret == PTHREAD_BARRIER_SERIAL_THREAD);
}
/* ============================================================================
* Utility Functions
* ============================================================================ */
uint32_t threading_hw_concurrency(void)
{
long nprocs = sysconf(_SC_NPROCESSORS_ONLN);
return (nprocs > 0) ? (uint32_t)nprocs : 1;
}
uint64_t threading_current_thread_id(void)
{
return (uint64_t)syscall(SYS_gettid);
}
void threading_set_name(const char *name)
{
if (!name) return;
pthread_setname_np(pthread_self(), name);
}
void threading_yield(void)
{
sched_yield();
}
/* ============================================================================
* Global Initialization
* ============================================================================ */
bool threading_init(void)
{
if (!thread_pool_init_default(NULL)) {
return false;
}
if (!timer_init()) {
thread_pool_shutdown_default();
return false;
}
if (!event_bus_init_default()) {
timer_shutdown();
thread_pool_shutdown_default();
return false;
}
return true;
}
void threading_shutdown(void)
{
event_bus_shutdown_default();
timer_shutdown();
thread_pool_shutdown_default();
}
+321
View File
@@ -0,0 +1,321 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* Threading Integration with Main Event Loop
*
* Integrates the threading framework with DWN's main X11 event loop
* using select() for multiplexing.
*/
#include "threading.h"
#include "thread_workers.h"
#include "dwn.h"
#include "util.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/select.h>
/* ============================================================================
* Integration State
* ============================================================================ */
typedef struct {
int original_xfd;
int timer_fd;
int event_bus_fd;
ThreadPool *pool;
bool initialized;
} ThreadingIntegration;
static ThreadingIntegration g_integration = {0};
/* ============================================================================
* Initialization
* ============================================================================ */
bool threading_integration_init(void)
{
if (g_integration.initialized) return true;
/* Initialize core threading */
if (!threading_init()) {
LOG_ERROR("Failed to initialize threading subsystem");
return false;
}
/* Initialize workers */
if (!thread_workers_init()) {
LOG_ERROR("Failed to initialize worker threads");
threading_shutdown();
return false;
}
g_integration.pool = thread_pool_default();
g_integration.timer_fd = deferred_get_poll_fd();
g_integration.event_bus_fd = -1; /* Would come from event bus */
g_integration.initialized = true;
LOG_INFO("Threading integration initialized");
return true;
}
void threading_integration_shutdown(void)
{
if (!g_integration.initialized) return;
thread_workers_shutdown();
threading_shutdown();
g_integration.initialized = false;
LOG_INFO("Threading integration shutdown");
}
/* ============================================================================
* Select Integration
* ============================================================================ */
/**
* Prepare fd_set for select() call
* Call this before select() to include threading fds
*/
void threading_integration_prepare_select(int xfd, fd_set *fds, int *max_fd)
{
if (!g_integration.initialized) return;
g_integration.original_xfd = xfd;
/* Add timer fd */
if (g_integration.timer_fd >= 0) {
FD_SET(g_integration.timer_fd, fds);
if (g_integration.timer_fd > *max_fd) {
*max_fd = g_integration.timer_fd;
}
}
/* Add event bus fd */
if (g_integration.event_bus_fd >= 0) {
FD_SET(g_integration.event_bus_fd, fds);
if (g_integration.event_bus_fd > *max_fd) {
*max_fd = g_integration.event_bus_fd;
}
}
}
/**
* Process threading events after select() returns
* Call this when select() indicates data available
*/
void threading_integration_process(fd_set *fds)
{
if (!g_integration.initialized) return;
/* Process timer events */
if (g_integration.timer_fd >= 0 && FD_ISSET(g_integration.timer_fd, fds)) {
deferred_process();
}
/* Process event bus */
if (g_integration.event_bus_fd >= 0 && FD_ISSET(g_integration.event_bus_fd, fds)) {
event_bus_process(event_bus_default());
}
/* Process async contexts */
thread_workers_process_all();
}
/**
* Non-blocking check for threading work
* Call this periodically from main loop
*/
void threading_integration_poll(void)
{
if (!g_integration.initialized) return;
/* Process any pending async work */
thread_workers_process_all();
}
/* ============================================================================
* Convenience API for Main Loop
* ============================================================================ */
/**
* Run main loop iteration with integrated threading
* This is an alternative to manual select() integration
*/
void threading_integration_run_iteration(int xfd, void (*handle_xevent)(void))
{
if (!g_integration.initialized) {
if (handle_xevent) handle_xevent();
return;
}
fd_set fds;
struct timeval tv;
int max_fd = xfd;
FD_ZERO(&fds);
FD_SET(xfd, &fds);
/* Add threading fds */
threading_integration_prepare_select(xfd, &fds, &max_fd);
/* Short timeout for responsive async processing */
tv.tv_sec = 0;
tv.tv_usec = 10000; /* 10ms */
int ready = select(max_fd + 1, &fds, NULL, NULL, &tv);
if (ready > 0) {
/* Process X11 events */
if (FD_ISSET(xfd, &fds)) {
if (handle_xevent) handle_xevent();
}
/* Process threading events */
threading_integration_process(&fds);
} else {
/* No events, just process pending async work */
threading_integration_poll();
}
}
/* ============================================================================
* Stats Integration
* ============================================================================ */
/**
* Get thread pool statistics for display/debugging
*/
void threading_integration_get_stats(char *buf, size_t bufsize)
{
if (!g_integration.initialized || !buf || bufsize == 0) return;
ThreadPool *pool = g_integration.pool;
uint32_t active = thread_pool_active_count(pool);
uint32_t pending = thread_pool_pending_count(pool);
snprintf(buf, bufsize, "Threads: %u active, %u pending tasks",
active, pending);
}
/* ============================================================================
* Module-Specific Async Contexts
* ============================================================================ */
/* Async contexts for different subsystems */
static AsyncContext *g_ai_context = NULL;
static AsyncContext *g_screenshot_context = NULL;
static AsyncContext *g_ocr_context = NULL;
bool threading_integration_init_module_contexts(void)
{
if (!g_integration.initialized) return false;
g_ai_context = async_context_create("ai");
g_screenshot_context = async_context_create("screenshot");
g_ocr_context = async_context_create("ocr");
return (g_ai_context && g_screenshot_context && g_ocr_context);
}
void threading_integration_cleanup_module_contexts(void)
{
if (g_ocr_context) {
async_context_destroy(g_ocr_context);
g_ocr_context = NULL;
}
if (g_screenshot_context) {
async_context_destroy(g_screenshot_context);
g_screenshot_context = NULL;
}
if (g_ai_context) {
async_context_destroy(g_ai_context);
g_ai_context = NULL;
}
}
AsyncContext* threading_integration_get_ai_context(void)
{
return g_ai_context;
}
AsyncContext* threading_integration_get_screenshot_context(void)
{
return g_screenshot_context;
}
AsyncContext* threading_integration_get_ocr_context(void)
{
return g_ocr_context;
}
/* ============================================================================
* High-Level Task Submission Helpers
* ============================================================================ */
/**
* Submit AI work
*/
TaskHandle threading_integration_submit_ai(TaskFunc func, void *user_data)
{
if (!g_ai_context) return NULL;
return async_submit(g_ai_context, func, user_data, TASK_PRIORITY_NORMAL);
}
/**
* Submit screenshot work
*/
TaskHandle threading_integration_submit_screenshot(TaskFunc func, void *user_data)
{
if (!g_screenshot_context) return NULL;
return async_submit(g_screenshot_context, func, user_data, TASK_PRIORITY_HIGH);
}
/**
* Submit OCR work
*/
TaskHandle threading_integration_submit_ocr(TaskFunc func, void *user_data)
{
if (!g_ocr_context) return NULL;
return async_submit(g_ocr_context, func, user_data, TASK_PRIORITY_NORMAL);
}
/**
* Submit UI-critical work (runs at highest priority)
*/
TaskHandle threading_integration_submit_ui(TaskFunc func, void *user_data)
{
TaskHandle task = task_create(func, user_data, TASK_PRIORITY_CRITICAL);
if (!task) return NULL;
ThreadStatus status = thread_pool_submit(thread_pool_default(), task);
if (status != THREAD_OK) {
task_destroy(task);
return NULL;
}
return task;
}
/**
* Submit background work (runs at lowest priority)
*/
TaskHandle threading_integration_submit_background(TaskFunc func, void *user_data)
{
TaskHandle task = task_create(func, user_data, TASK_PRIORITY_IDLE);
if (!task) return NULL;
ThreadStatus status = thread_pool_submit(thread_pool_default(), task);
if (status != THREAD_OK) {
task_destroy(task);
return NULL;
}
return task;
}
+292
View File
@@ -0,0 +1,292 @@
/*
* DWN - Desktop Window Manager
* retoor <retoor@molodetz.nl>
* Timer/Scheduler Implementation - Delayed Execution
*/
#include "threading.h"
#include "util.h"
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/timerfd.h>
#include <errno.h>
#include <poll.h>
#define MAX_TIMERS 256
#define TIMER_HASH_SIZE 64
/* ============================================================================
* Timer Types
* ============================================================================ */
typedef struct Timer {
TimerId id;
uint64_t fire_time;
uint64_t interval;
TimerCallback callback;
void *user_data;
bool active;
bool repeating;
struct Timer *next; /* For hash collision chain */
} Timer;
static struct {
Timer timers[MAX_TIMERS];
Timer *id_hash[TIMER_HASH_SIZE];
pthread_mutex_t mutex;
int timer_fd;
_Atomic uint64_t next_id;
bool initialized;
} g_timer_state;
/* ============================================================================
* Helper Functions
* ============================================================================ */
static uint64_t get_monotonic_ms(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
static uint32_t hash_timer_id(TimerId id)
{
return (uint32_t)(id % TIMER_HASH_SIZE);
}
static Timer* find_timer(TimerId id)
{
uint32_t hash = hash_timer_id(id);
Timer *t = g_timer_state.id_hash[hash];
while (t) {
if (t->id == id && t->active) return t;
t = t->next;
}
return NULL;
}
static void insert_timer(Timer *timer)
{
uint32_t hash = hash_timer_id(timer->id);
timer->next = g_timer_state.id_hash[hash];
g_timer_state.id_hash[hash] = timer;
}
static void remove_timer(Timer *timer)
{
uint32_t hash = hash_timer_id(timer->id);
Timer **pp = &g_timer_state.id_hash[hash];
while (*pp) {
if (*pp == timer) {
*pp = timer->next;
return;
}
pp = &(*pp)->next;
}
}
static void update_timer_fd(void)
{
/* Find next timer to fire */
uint64_t next_fire = 0;
bool has_timer = false;
for (int i = 0; i < MAX_TIMERS; i++) {
if (g_timer_state.timers[i].active) {
if (!has_timer || g_timer_state.timers[i].fire_time < next_fire) {
next_fire = g_timer_state.timers[i].fire_time;
has_timer = true;
}
}
}
if (!has_timer) return;
/* Set timerfd to fire at next_fire */
struct itimerspec its;
uint64_t now = get_monotonic_ms();
if (next_fire <= now) {
its.it_value.tv_sec = 0;
its.it_value.tv_nsec = 1; /* Fire immediately */
} else {
uint64_t diff = next_fire - now;
its.it_value.tv_sec = diff / 1000;
its.it_value.tv_nsec = (diff % 1000) * 1000000;
}
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0;
timerfd_settime(g_timer_state.timer_fd, 0, &its, NULL);
}
/* ============================================================================
* Timer API Implementation
* ============================================================================ */
bool timer_init(void)
{
if (g_timer_state.initialized) return true;
memset(&g_timer_state, 0, sizeof(g_timer_state));
if (pthread_mutex_init(&g_timer_state.mutex, NULL) != 0) {
return false;
}
g_timer_state.timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
if (g_timer_state.timer_fd < 0) {
pthread_mutex_destroy(&g_timer_state.mutex);
return false;
}
atomic_store_explicit(&g_timer_state.next_id, 1, ATOMIC_RELEASE);
g_timer_state.initialized = true;
return true;
}
void timer_shutdown(void)
{
if (!g_timer_state.initialized) return;
close(g_timer_state.timer_fd);
pthread_mutex_destroy(&g_timer_state.mutex);
g_timer_state.initialized = false;
}
static TimerId allocate_timer_id(void)
{
return atomic_fetch_add_explicit(&g_timer_state.next_id, 1, ATOMIC_RELAXED);
}
TimerId timer_schedule(uint64_t delay_ms, TimerCallback callback, void *user_data)
{
return timer_schedule_repeating(delay_ms, callback, user_data);
}
TimerId timer_schedule_repeating(uint64_t interval_ms, TimerCallback callback,
void *user_data)
{
if (!g_timer_state.initialized || !callback || interval_ms == 0) return 0;
pthread_mutex_lock(&g_timer_state.mutex);
/* Find free slot */
Timer *timer = NULL;
for (int i = 0; i < MAX_TIMERS; i++) {
if (!g_timer_state.timers[i].active) {
timer = &g_timer_state.timers[i];
break;
}
}
if (!timer) {
pthread_mutex_unlock(&g_timer_state.mutex);
LOG_ERROR("No free timer slots");
return 0;
}
timer->id = allocate_timer_id();
timer->fire_time = get_monotonic_ms() + interval_ms;
timer->interval = interval_ms;
timer->callback = callback;
timer->user_data = user_data;
timer->active = true;
timer->repeating = true;
insert_timer(timer);
update_timer_fd();
pthread_mutex_unlock(&g_timer_state.mutex);
return timer->id;
}
bool timer_cancel(TimerId id)
{
if (!g_timer_state.initialized || id == 0) return false;
pthread_mutex_lock(&g_timer_state.mutex);
Timer *timer = find_timer(id);
if (timer) {
timer->active = false;
remove_timer(timer);
pthread_mutex_unlock(&g_timer_state.mutex);
return true;
}
pthread_mutex_unlock(&g_timer_state.mutex);
return false;
}
bool timer_exists(TimerId id)
{
if (!g_timer_state.initialized || id == 0) return false;
pthread_mutex_lock(&g_timer_state.mutex);
bool exists = (find_timer(id) != NULL);
pthread_mutex_unlock(&g_timer_state.mutex);
return exists;
}
uint32_t timer_process(void)
{
if (!g_timer_state.initialized) return 0;
/* Acknowledge timerfd */
uint64_t expirations;
ssize_t n = read(g_timer_state.timer_fd, &expirations, sizeof(expirations));
if (n < 0 && errno != EAGAIN) {
return 0;
}
uint64_t now = get_monotonic_ms();
uint32_t fired = 0;
pthread_mutex_lock(&g_timer_state.mutex);
for (int i = 0; i < MAX_TIMERS; i++) {
Timer *timer = &g_timer_state.timers[i];
if (!timer->active) continue;
if (timer->fire_time <= now) {
/* Fire timer (outside lock to avoid deadlock) */
TimerCallback cb = timer->callback;
void *data = timer->user_data;
TimerId id = timer->id;
bool repeating = timer->repeating;
uint64_t interval = timer->interval;
if (!repeating) {
timer->active = false;
remove_timer(timer);
} else {
timer->fire_time = now + interval;
}
pthread_mutex_unlock(&g_timer_state.mutex);
cb(id, data);
pthread_mutex_lock(&g_timer_state.mutex);
fired++;
}
}
update_timer_fd();
pthread_mutex_unlock(&g_timer_state.mutex);
return fired;
}
int timer_get_poll_fd(void)
{
return g_timer_state.initialized ? g_timer_state.timer_fd : -1;
}
+26 -24
View File
@@ -172,6 +172,11 @@ void workspace_move_client(Client *client, int new_workspace)
return;
}
if (client->flags & CLIENT_UNMANAGING) {
LOG_DEBUG("workspace_move_client: client %lu being unmanged, skipping", client->window);
return;
}
if (client->workspace == (unsigned int)new_workspace) {
return;
}
@@ -181,8 +186,6 @@ void workspace_move_client(Client *client, int new_workspace)
LOG_DEBUG("Moving window '%s' from workspace %d to %d",
client->title, old_workspace + 1, new_workspace + 1);
XGrabServer(dwn->display);
workspace_remove_client(old_workspace, client);
workspace_add_client(new_workspace, client);
atoms_set_window_desktop(client->window, new_workspace);
@@ -194,9 +197,6 @@ void workspace_move_client(Client *client, int new_workspace)
workspace_arrange(old_workspace);
XUngrabServer(dwn->display);
XSync(dwn->display, False);
workspace_switch(new_workspace);
}
@@ -232,10 +232,7 @@ void workspace_set_layout(int workspace, LayoutType layout)
int old_layout = ws->layout;
ws->layout = layout;
XGrabServer(dwn->display);
workspace_arrange(workspace);
XUngrabServer(dwn->display);
XSync(dwn->display, False);
api_emit_workspace_layout_changed(workspace, old_layout, layout);
@@ -258,15 +255,11 @@ void workspace_cycle_layout(int workspace)
int old_layout = ws->layout;
ws->layout = (ws->layout + 1) % LAYOUT_COUNT;
XGrabServer(dwn->display);
workspace_arrange(workspace);
XUngrabServer(dwn->display);
XSync(dwn->display, False);
api_emit_workspace_layout_changed(workspace, old_layout, ws->layout);
const char *layout_names[] = { "Tiling", "Floating", "Monocle" };
LOG_INFO("Workspace %d: %s layout", workspace + 1, layout_names[ws->layout]);
LOG_INFO("Workspace %d: %s layout", workspace + 1, layout_get_name(ws->layout));
}
void workspace_set_master_ratio(int workspace, float ratio)
@@ -283,10 +276,7 @@ void workspace_set_master_ratio(int workspace, float ratio)
ws->master_ratio = ratio;
XGrabServer(dwn->display);
workspace_arrange(workspace);
XUngrabServer(dwn->display);
XSync(dwn->display, False);
if (old_ratio != ws->master_ratio) {
api_emit_workspace_master_ratio_changed(workspace, old_ratio, ws->master_ratio);
@@ -313,10 +303,7 @@ void workspace_set_master_count(int workspace, int count)
if (count < 1) count = 1;
ws->master_count = count;
XGrabServer(dwn->display);
workspace_arrange(workspace);
XUngrabServer(dwn->display);
XSync(dwn->display, False);
if (old_count != ws->master_count) {
api_emit_workspace_master_count_changed(workspace, old_count, ws->master_count);
@@ -350,11 +337,8 @@ void workspace_arrange(int workspace)
void workspace_arrange_current(void)
{
XGrabServer(dwn->display);
workspace_arrange(dwn->current_workspace);
panel_raise_all();
XUngrabServer(dwn->display);
XSync(dwn->display, False);
}
@@ -364,10 +348,19 @@ void workspace_show(int workspace)
return;
}
for (Client *c = dwn->client_list; c != NULL; c = c->next) {
for (Client *c = dwn->client_list; c != NULL; ) {
Client *next = c->next;
if (c->flags & CLIENT_UNMANAGING) {
c = next;
continue;
}
if (c->workspace == (unsigned int)workspace && !client_is_minimized(c)) {
client_show(c);
}
c = next;
}
}
@@ -377,10 +370,19 @@ void workspace_hide(int workspace)
return;
}
for (Client *c = dwn->client_list; c != NULL; c = c->next) {
for (Client *c = dwn->client_list; c != NULL; ) {
Client *next = c->next;
if (c->flags & CLIENT_UNMANAGING) {
c = next;
continue;
}
if (c->workspace == (unsigned int)workspace) {
client_hide(c);
}
c = next;
}
}