const std = @import("std"); const xlib = @import("c"); const Self = @This(); pub const EventType = enum { mouse_motion_raw, mouse_motion, key_down, key_up, window_close, }; pub const KeyScanCode = enum(i32) { TAB = 23, Q = 24, W = 25, E = 26, R = 27, T = 28, Y = 29, U = 30, I = 31, O = 32, P = 33, A = 38, S = 39, D = 40, F = 41, G = 42, H = 43, J = 44, K = 45, L = 46, LSHIFT = 50, _, }; pub const Event = union(EventType) { mouse_motion_raw: struct { x: f32, y: f32, }, mouse_motion: struct { x: u32, y: u32, }, key_down: struct { scancode: KeyScanCode, }, key_up: struct { scancode: KeyScanCode, }, window_close: struct { dummy: u32, }, }; pub const WindowOptions = struct { width: usize, height: usize, resizable: bool = true, raw_mouse_input: bool = true, warpmouse: bool = false, }; display: ?*xlib.struct__XDisplay, window: c_ulong, screen: c_int, options: WindowOptions, image: ?*xlib.XImage = null, shm_seg_info: xlib.XShmSegmentInfo = undefined, cm_delete: xlib.Atom = undefined, fn wait_exposure(self: Self) void { var e: xlib.XEvent = undefined; while (true) { _ = xlib.XNextEvent(self.display, &e); switch (e.type) { xlib.Expose => return, else => continue, } } } fn x_error_handler(d: ?*xlib.struct__XDisplay, e: [*c]xlib.XErrorEvent) c_int { //std.debug.print("X Error \n", .{}); _ = d; _ = e; return 0; } pub fn getPixels(self: Self) []u8 { return @ptrCast(@alignCast(self.image.?.data[0..@intCast(self.image.?.bytes_per_line * self.image.?.height)])); } pub fn setTitle(self: Self, title: [:0]const u8) void { _ = xlib.XStoreName(self.display, self.window, @ptrCast(title.ptr)); } fn createCanvas(self: *Self, initshm: bool) void { var res: c_int = undefined; // clean up stuff before recreating canvas if (self.image != null) { res = xlib.XShmDetach(self.display, &self.shm_seg_info); std.debug.print("detach result: {d}\n", .{res}); res = self.image.?.XDestroyImage(); std.debug.print("destroyimage result: {d}\n", .{res}); if (initshm) { res = xlib.shmctl(self.shm_seg_info.shmid, xlib.IPC_RMID, 0); std.debug.print("shm remove result: {d}\n", .{res}); } } const visual = xlib.XDefaultVisualOfScreen(xlib.ScreenOfDisplay(self.display, self.screen)); const depth = xlib.XDefaultDepthOfScreen(xlib.ScreenOfDisplay(self.display, self.screen)); self.image = xlib.XShmCreateImage(self.display, visual, @intCast(depth), xlib.XShmPixmapFormat(self.display), 0, &self.shm_seg_info, @intCast(self.options.width), @intCast(self.options.height)); if (initshm) { const shmid = xlib.shmget(xlib.IPC_PRIVATE, @intCast(self.image.?.bytes_per_line * self.image.?.height), xlib.IPC_CREAT | 0o600); self.shm_seg_info.shmid = shmid; } std.debug.print("Image: {any}\n", .{self.image}); std.debug.print("shmid: {any}\n", .{self.shm_seg_info.shmid}); const shmaddr = xlib.shmat(self.shm_seg_info.shmid, @ptrFromInt(0), 0); std.debug.print("shmaddr: {any}\n", .{shmaddr}); self.image.?.data = @ptrCast(shmaddr); self.shm_seg_info.shmaddr = @ptrCast(shmaddr); self.shm_seg_info.readOnly = 0; res = xlib.XShmAttach(self.display, &self.shm_seg_info); std.debug.print("XShmAttach {d} {d}\n", .{ res, xlib.Success }); } pub fn init(options: WindowOptions) !Self { _ = xlib.XSetErrorHandler(@ptrCast(&x_error_handler)); const d = xlib.XOpenDisplay(null); if (d == null) { std.debug.print("Error opening display\n", .{}); } const s = xlib.DefaultScreen(d); const w = xlib.XCreateSimpleWindow(d, xlib.RootWindow(d, s), 0, 0, @intCast(options.width), @intCast(options.height), 0, xlib.BlackPixel(d, s), xlib.WhitePixel(d, s)); if (options.resizable == false) { const size_hints = xlib.XAllocSizeHints(); size_hints.*.flags = (xlib.PMinSize | xlib.PMaxSize); size_hints.?.*.min_width = @intCast(options.width); size_hints.?.*.max_width = @intCast(options.width); size_hints.?.*.min_height = @intCast(options.height); size_hints.?.*.max_height = @intCast(options.height); _ = xlib.XSetWMNormalHints(d, w, size_hints); _ = xlib.XFree(size_hints); } var res = xlib.XSelectInput(d, w, xlib.ExposureMask | xlib.KeyPressMask | xlib.KeyReleaseMask | xlib.StructureNotifyMask | xlib.ButtonPressMask | xlib.ButtonReleaseMask); res = xlib.XMapWindow(d, w); // set up to handle WM_DELETE_WINDOW ourselves var delete = xlib.XInternAtom(d, "WM_DELETE_WINDOW", 0); _ = xlib.XSetWMProtocols(d, w, &delete, 1); var window = Self{ .display = d, .window = w, .screen = s, .options = options, .cm_delete = delete, }; createCanvas(&window, true); //wait_exposure(window); _ = xlib.XkbSetDetectableAutoRepeat(d, 1, @ptrFromInt(0)); // TODO there might be a more elegant solution to prevent X11 from doing key repeats at all _ = xlib.XkbSetAutoRepeatRate(d, xlib.XkbUseCoreKbd, 1000000, 1000000); if (options.raw_mouse_input) { res = xlib.XGrabPointer(d, w, 1, xlib.PointerMotionMask, xlib.GrabModeAsync, xlib.GrabModeAsync, xlib.None, xlib.None, xlib.CurrentTime); std.debug.print("grab res {d} {d} {d} {d}\n", .{ res, xlib.BadCursor, xlib.BadWindow, xlib.BadValue }); _ = xlib.XWarpPointer(d, xlib.None, w, 0, 0, 0, 0, @intCast(options.width / 2), @intCast(options.height / 2)); xlib.XFixesHideCursor(d, w); var mask: [xlib.XIMaskLen(xlib.XI_RawMotion)]u8 = @splat(0); // XISetMask(mask, XI_RawMotion) mask[xlib.XI_RawMotion >> 3] |= (1 << (xlib.XI_RawMotion & 7)); var em: xlib.XIEventMask = undefined; em.deviceid = xlib.XIAllMasterDevices; em.mask = &mask; em.mask_len = mask.len; res = xlib.XISelectEvents(d, xlib.XDefaultRootWindow(d), &em, 1); std.debug.print("setmask {d}\n", .{res}); } std.debug.print("display: {any}, screen: {any}, w: {x}\n", .{ d, s, w }); return window; } pub fn flip(self: Self) void { _ = xlib.XShmPutImage(self.display, self.window, xlib.DefaultGC(self.display, self.screen), self.image, 0, 0, 0, 0, @intCast(self.image.?.width), @intCast(self.image.?.height), 0); _ = xlib.XSync(self.display, 0); } pub fn pollEvent(self: *Self) ?Event { var e: xlib.XEvent = undefined; var xdelta: f32 = 0; var ydelta: f32 = 0; const pending = xlib.XPending(self.display); if (pending == 0) return null; _ = xlib.XNextEvent(self.display, &e); switch (e.type) { xlib.GenericEvent => { _ = xlib.XGetEventData(self.display, &e.xcookie); defer { _ = xlib.XFreeEventData(self.display, &e.xcookie); } if (e.xcookie.evtype == xlib.XI_RawMotion) { const raw = @as(?*xlib.XIRawEvent, @ptrCast(@alignCast(e.xcookie.data))); if (xlib.XIMaskIsSet(raw.?.valuators.mask, 0) != 0) xdelta += @floatCast(raw.?.raw_values[0] * 1); if (xlib.XIMaskIsSet(raw.?.valuators.mask, 1) != 0) ydelta += @floatCast(raw.?.raw_values[1] * 1); if (self.options.warpmouse) _ = xlib.XWarpPointer(self.display, xlib.None, self.window, 0, 0, 0, 0, @intCast(self.options.width / 2), @intCast(self.options.height / 2)); return .{ .mouse_motion_raw = .{ .x = xdelta, .y = ydelta, } }; } }, xlib.MotionNotify => { return .{ .mouse_motion = .{ .x = @intCast(e.xmotion.x), .y = @intCast(e.xmotion.y), } }; //std.debug.print("Motion : {d} {d}\n", .{ e.xmotion.x, e.xmotion.y }); }, xlib.ConfigureNotify => { std.debug.print("Resize event {d} {d}\n", .{ e.xconfigure.width, e.xconfigure.height }); self.options.width = @intCast(e.xconfigure.width); self.options.height = @intCast(e.xconfigure.height); self.createCanvas(false); }, xlib.ButtonPress => { std.debug.print("ButtonDown {d}\n", .{e.xbutton.button}); }, xlib.ButtonRelease => { std.debug.print("ButtonUp {d}\n", .{e.xbutton.button}); }, xlib.KeyPress => { const k: KeyScanCode = @fromBackingInt(@intCast(e.xkey.keycode)); //std.debug.print("KeyDown {d}\n", .{e.xkey.keycode}); return .{ .key_down = .{ .scancode = k } }; }, xlib.KeyRelease => { const k: KeyScanCode = @fromBackingInt(@intCast(e.xkey.keycode)); //std.debug.print("KeyUp {d}\n", .{e.xkey.keycode}); return .{ .key_up = .{ .scancode = k } }; }, xlib.ClientMessage => { //std.debug.print("ClientMessage\n", .{}); if (e.xclient.data.l[0] == self.cm_delete) { return .{ .window_close = .{ .dummy = 1 } }; } }, else => {}, } return null; } pub fn deinit(self: Self) void { std.debug.print("deinit\n", .{}); _ = xlib.XkbSetAutoRepeatRate(self.display, xlib.XkbUseCoreKbd, 500, 50); _ = xlib.XUngrabPointer(self.display, self.window); _ = xlib.XCloseDisplay(self.display); }