swot

neuSWc screenshOT tool
git clone https://git.daat.foo/swot.git
Log | Files | Refs | README | LICENSE

commit c5e40c12b5a3cda69b9f60f162b5038fb4ab14b7
Author: cowmonk <cowmonk@based.pt>
Date:   Wed, 25 Nov 2026 18:57:27 -0700

swot: screenshot init commit

Diffstat:
ALICENSE | 45+++++++++++++++++++++++++++++++++++++++++++++
AMakefile | 36++++++++++++++++++++++++++++++++++++
AREADME | 42++++++++++++++++++++++++++++++++++++++++++
Aprotocol/LICENSE | 19+++++++++++++++++++
Aprotocol/layer.xml | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aprotocol/swc_select.xml | 26++++++++++++++++++++++++++
Aprotocol/swc_snap.xml | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aswot.c | 430+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Autil.c | 27+++++++++++++++++++++++++++
Autil.h | 5+++++
10 files changed, 811 insertions(+), 0 deletions(-)

diff --git a/LICENSE b/LICENSE @@ -0,0 +1,45 @@ +MIT/X Consortium License + +© 2026 cowmonk <cowmonk@based.pt> + +util.c and util.h are from suckless dwm. Its copyright notices follow. + +© 2010-2026 Hiltjo Posthuma <hiltjo@codemadness.org> +© 2006-2019 Anselm R Garbe <anselm@garbe.ca> +© 2006-2009 Jukka Salmi <jukka at salmi dot ch> +© 2006-2007 Sander van Dijk <a dot h dot vandijk at gmail dot com> +© 2007-2011 Peter Hartlich <sgkkr at hartlich dot com> +© 2007-2009 Szabolcs Nagy <nszabolcs at gmail dot com> +© 2007-2009 Christof Musik <christof at sendfax dot de> +© 2007-2009 Premysl Hruby <dfenze at gmail dot com> +© 2007-2008 Enno Gottox Boland <gottox at s01 dot de> +© 2008 Martin Hurton <martin dot hurton at gmail dot com> +© 2008 Neale Pickett <neale dot woozle dot org> +© 2009 Mate Nagy <mnagy at port70 dot net> +© 2010-2012 Connor Lane Smith <cls@lubutu.com> +© 2011 Christoph Lohmann <20h@r-36.net> +© 2015-2016 Quentin Rameau <quinq@fifth.space> +© 2015-2016 Eric Pruitt <eric.pruitt@gmail.com> +© 2016-2017 Markus Teich <markus.teich@stusta.mhn.de> +© 2020-2022 Chris Down <chris@chrisdown.name> + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +The swc protocol definitions are covered by protocol/LICENSE. The layer-shell +protocol carries its own copyright and permission notice in protocol/layer.xml. diff --git a/Makefile b/Makefile @@ -0,0 +1,36 @@ +.POSIX: + +CC = cc +PREFIX = /usr/local +PKG_CONFIG = pkg-config +WAYLAND_SCANNER = wayland-scanner +PACKAGES = wayland-client xkbcommon spng libjpeg + +HEADERS = swc_snap.h layer.h +SOURCES = swc_snap.c layer.c + +swot: swot.c util.c util.h $(HEADERS) $(SOURCES) + $(CC) -std=c99 $(CPPFLAGS) $(CFLAGS) -o $@ swot.c util.c $(SOURCES) \ + $(LDFLAGS) `$(PKG_CONFIG) --cflags --libs $(PACKAGES)` $(LDLIBS) + +swc_snap.h swc_snap.c: protocol/swc_snap.xml +layer.h layer.c: protocol/layer.xml + +$(HEADERS): + $(WAYLAND_SCANNER) client-header protocol/$(@:.h=.xml) $@ + +$(SOURCES): + $(WAYLAND_SCANNER) private-code protocol/$(@:.c=.xml) $@ + +install: swot + mkdir -p "$(DESTDIR)$(PREFIX)/bin" + cp swot "$(DESTDIR)$(PREFIX)/bin/swot" + chmod 755 "$(DESTDIR)$(PREFIX)/bin/swot" + mkdir -p "$(DESTDIR)$(PREFIX)/share/licenses/swot/protocol" + cp LICENSE "$(DESTDIR)$(PREFIX)/share/licenses/swot/" + cp protocol/LICENSE protocol/layer.xml "$(DESTDIR)$(PREFIX)/share/licenses/swot/protocol/" + +clean: + rm -f swot $(HEADERS) $(SOURCES) + +.PHONY: install clean diff --git a/README b/README @@ -0,0 +1,42 @@ +swot - neuSWc screenshOT +======================== + +swot is like scrot but for minimal neuswc compositors. This is more of a personal project +for my own usage because I felt that swcsnap was "lacking" in my use case. However, the only +issues I had with swcsnap was that it only output to ppm and didn't have regional selection. + +Building +-------- + +Building swot doesn't require a vast amount of dependencies: a competent c99 c compiler, +wayland-client, wayland-scanner, pkg-config, libxkbcommon, libspng, and libjpeg-turbo. + + make + make install + +Usage +----- + +Using swot is quite trivial, it's a very simple program. For fullscreen screenshots invoking +it by itself is like so: + + swot > image.png # output using redirect + swot -o screenie.jpg # output using -o (output) + +Output defaults to png. + +Drag to select an area on the primary screen, or press Esc to cancel. Regional +selection uses the layer-shell protocol provided by neuswc. + + swot -s > image.png + +To output to clipboard (my main usage really) using wl-clipboard: + + swot -s | wl-copy -t image/png + +Credits +------- + +- neuswc - swcsnap was a very good reference for where to start +- suckless - thanks for util.* + diff --git a/protocol/LICENSE b/protocol/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013-2019 Michael Forney + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/protocol/layer.xml b/protocol/layer.xml @@ -0,0 +1,106 @@ +<?xml version="1.0" encoding="UTF-8"?> +<protocol name="wlr_layer_shell_unstable_v1"> + <copyright> + Copyright © 2017 Drew DeVault + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + the copyright holders not be used in advertising or publicity + pertaining to distribution of the software without specific, + written prior permission. The copyright holders make no + representations about the suitability of this software for any + purpose. It is provided "as is" without express or implied + warranty. + + THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY + SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN + AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + THIS SOFTWARE. + </copyright> + <interface name="zwlr_layer_shell_v1" version="1"> + <request name="get_layer_surface"> + <arg name="id" type="new_id" interface="zwlr_layer_surface_v1" /> + <arg name="surface" type="object" interface="wl_surface" /> + <arg name="output" type="object" interface="wl_output" allow-null="true" /> + <arg name="layer" type="uint" enum="layer" /> + <arg name="namespace" type="string" /> + </request> + <enum name="error"> + <entry name="role" value="0" /> + <entry name="invalid_layer" value="1" /> + <entry name="already_constructed" value="2" /> + </enum> + <enum name="layer"> + <entry name="background" value="0" /> + <entry name="bottom" value="1" /> + <entry name="top" value="2" /> + <entry name="overlay" value="3" /> + </enum> + </interface> + <interface name="zwlr_layer_surface_v1" version="1"> + <request name="set_size"> + <arg name="width" type="uint" /> + <arg name="height" type="uint" /> + </request> + <request name="set_anchor"> + <arg name="anchor" type="uint" enum="anchor" /> + </request> + <request name="set_exclusive_zone"> + <arg name="zone" type="int" /> + </request> + <request name="set_margin"> + <arg name="top" type="int" /> + <arg name="right" type="int" /> + <arg name="bottom" type="int" /> + <arg name="left" type="int" /> + </request> + <enum name="keyboard_interactivity"> + <entry name="none" value="0"> + </entry> + <entry name="exclusive" value="1"> + </entry> + </enum> + <request name="set_keyboard_interactivity"> + <arg name="keyboard_interactivity" type="uint" enum="keyboard_interactivity" /> + </request> + <request name="get_popup"> + <arg name="popup" type="object" interface="xdg_popup" /> + </request> + <request name="ack_configure"> + <arg name="serial" type="uint" /> + </request> + <request name="destroy" type="destructor"> + </request> + <event name="configure"> + <arg name="serial" type="uint" /> + <arg name="width" type="uint" /> + <arg name="height" type="uint" /> + </event> + <event name="closed"> + </event> + <enum name="error"> + <entry name="invalid_surface_state" value="0" /> + <entry name="invalid_size" value="1" /> + <entry name="invalid_anchor" value="2" /> + <entry name="invalid_keyboard_interactivity" value="3" /> + <entry name="invalid_exclusive_edge" value="4" /> + </enum> + <enum name="anchor" bitfield="true"> + <entry name="top" value="1" /> + <entry name="bottom" value="2" /> + <entry name="left" value="4" /> + <entry name="right" value="8" /> + </enum> + </interface> + <!-- Type reference for get_popup, which swot never calls. --> + <interface name="xdg_popup" version="1"> + <request name="destroy" type="destructor" /> + </interface> +</protocol> diff --git a/protocol/swc_select.xml b/protocol/swc_select.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<protocol name="swc_select"> + <interface name="swc_select" version="1"> + <description summary="Get a selection box"> + Allows clients to get an interactive selction box. + </description> + + <request name="grab" /> + <event name="update" > + <arg name="x1" type="int" /> + <arg name="y1" type="int" /> + <arg name="x2" type="int" /> + <arg name="y2" type="int" /> + </event> + + <event name="done" > + <arg name="x1" type="int" /> + <arg name="y1" type="int" /> + <arg name="x2" type="int" /> + <arg name="y2" type="int" /> + </event> + + <event name="cancelled" /> + <request name="destroy" type="destructor" /> + </interface> +</protocol> diff --git a/protocol/swc_snap.xml b/protocol/swc_snap.xml @@ -0,0 +1,75 @@ +<?xml version="1.0" encoding="UTF-8"?> +<protocol name="swc_snap"> + <interface name="swc_snap" version="2"> + <description summary="raw screen capture into client buffers"> + gives a screen capture capability where the client supplies a + wl_shm buffer and the compositor fills it with a raw frame. + </description> + + <enum name="flags" bitfield="true"> + <entry name="overlay_cursor" value="1" + summary="composite the current cursor into the frame"/> + </enum> + + <enum name="pixel_format"> + <entry name="xrgb8888" value="0" + summary="WL_SHM_FORMAT_XRGB8888"/> + <entry name="argb8888" value="1" + summary="WL_SHM_FORMAT_ARGB8888"/> + </enum> + + <enum name="failure_reason"> + <entry name="no_screen" value="0" + summary="no captureable screen is available"/> + <entry name="unsupported_buffer" value="1" + summary="buffer is not a wl_shm xrgb/argb8888 buffer"/> + <entry name="size_mismatch" value="2" + summary="buffer dimensions are too small for the screen"/> + <entry name="internal" value="3" + summary="compositor capture failed"/> + </enum> + + <request name="destroy" type="destructor"> + <description summary="destroy the capture object"/> + </request> + + <request name="capture"> + <description summary="capture a frame into a client buffer"> + captures the current primary screen into the supplied wl_shm + buffer. The compositor writes raw pixels and reports ready or + failed state + </description> + <arg name="buffer" type="object" interface="wl_buffer" + summary="client-provided wl_shm buffer to fill"/> + <arg name="flags" type="uint" summary="bitmask of swc_snap.flags"/> + </request> + + <event name="buffer"> + <description summary="current capture frame metadata"> + describes the current frame geometry and pixel format expected + by the capture stream + </description> + <arg name="width" type="uint"/> + <arg name="height" type="uint"/> + <arg name="format" type="uint" + summary="swc_snap.pixel_format value"/> + </event> + + <event name="ready"> + <description summary="capture complete"> + the requested buffer has been filled and is ready for client + </description> + <arg name="tv_sec" type="uint" summary="CLOCK_MONOTONIC seconds"/> + <arg name="tv_nsec" type="uint" summary="CLOCK_MONOTONIC nanoseconds"/> + </event> + + <event name="failed"> + <description summary="capture failed"> + the capture request failed, the object still usable and the + client may retry with another buffer or after a mode change + </description> + <arg name="reason" type="uint" + summary="swc_snap.failure_reason value"/> + </event> + </interface> +</protocol> diff --git a/swot.c b/swot.c @@ -0,0 +1,430 @@ +#define _POSIX_C_SOURCE 200809L + +#include "layer.h" +#include "swc_snap.h" +#include "util.h" + +#include <stdint.h> +#include <stdio.h> +#include <jpeglib.h> +#include <spng.h> +#include <string.h> +#include <strings.h> +#include <sys/mman.h> +#include <unistd.h> +#include <xkbcommon/xkbcommon.h> + +struct Rect { + int left, top, right, bottom; +}; + +struct Canvas { + struct wl_buffer *buffer; + uint32_t *pixels; + struct Rect box; + int busy; +}; + +static struct Canvas canvases[2]; +static struct Rect shown; +static int redraw; + +static struct wl_shm *shm; +static struct swc_snap *snap; +static struct wl_buffer *frame; +static struct wl_compositor *compositor; +static struct zwlr_layer_shell_v1 *shell; +static struct wl_seat *seat; +static struct wl_surface *overlay; +static struct xkb_state *keys; +static int width, height, ready, selected; +static uint32_t drag_button, capabilities; +static struct Rect region; + +static void +buffer_info(void *data, struct swc_snap *s, uint32_t w, uint32_t h, uint32_t fmt) +{ + if (!w || !h || w > INT32_MAX / 4 / h) + die("swot: invalid capture dimensions"); + if ((frame || overlay) && (w != (uint32_t)width || h != (uint32_t)height)) + die("swot: screen resized during capture"); + width = w; + height = h; +} + +static void +capture_ready(void *data, struct swc_snap *s, uint32_t sec, uint32_t nsec) +{ + ready = 1; +} + +static void +capture_failed(void *data, struct swc_snap *s, uint32_t reason) +{ + die("swot: capture failed (%u)", reason); +} + +static const struct swc_snap_listener snap_listener = {buffer_info, capture_ready, capture_failed}; + +static void +seat_caps(void *data, struct wl_seat *s, uint32_t caps) +{ + capabilities = caps; + if (overlay && !(caps & WL_SEAT_CAPABILITY_POINTER)) + die("swot: pointer disconnected"); +} + +static const struct wl_seat_listener seat_listener = {.capabilities = seat_caps}; + +static void +global(void *data, struct wl_registry *reg, uint32_t id, const char *name, uint32_t version) +{ + if (!strcmp(name, "wl_shm")) + shm = wl_registry_bind(reg, id, &wl_shm_interface, 1); + else if (!strcmp(name, "swc_snap")) { + snap = wl_registry_bind(reg, id, &swc_snap_interface, 1); + swc_snap_add_listener(snap, &snap_listener, NULL); + } else if (*(int *)data) { + if (!strcmp(name, "wl_compositor")) + compositor = wl_registry_bind(reg, id, &wl_compositor_interface, 1); + else if (!strcmp(name, "zwlr_layer_shell_v1")) + shell = wl_registry_bind(reg, id, &zwlr_layer_shell_v1_interface, 1); + else if (!seat && !strcmp(name, "wl_seat")) { + seat = wl_registry_bind(reg, id, &wl_seat_interface, 1); + wl_seat_add_listener(seat, &seat_listener, NULL); + } + } +} + +static void +removed(void *data, struct wl_registry *reg, uint32_t id) +{ +} + +static const struct wl_registry_listener registry_listener = {global, removed}; + +static struct wl_buffer * +make_buffer(uint32_t **pixels) +{ + FILE *file = tmpfile(); + int stride = width * 4, size = stride * height; + struct wl_shm_pool *pool; + struct wl_buffer *buffer; + + if (!file || ftruncate(fileno(file), size) < 0) + die("swot: creating shared buffer:"); + *pixels = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0); + if (*pixels == MAP_FAILED) + die("swot: mmap:"); + pool = wl_shm_create_pool(shm, fileno(file), size); + fclose(file); + if (!pool) + die("swot: creating Wayland buffer pool:"); + buffer = wl_shm_pool_create_buffer(pool, 0, width, height, stride, WL_SHM_FORMAT_ARGB8888); + wl_shm_pool_destroy(pool); + if (!buffer) + die("swot: creating Wayland buffer:"); + return buffer; +} + +static void +write_png(FILE *out, unsigned char *rgb, int w, int h) +{ + struct spng_ihdr header = {.width = w, .height = h, .bit_depth = 8, + .color_type = SPNG_COLOR_TYPE_TRUECOLOR}; + spng_ctx *ctx = spng_ctx_new(SPNG_CTX_ENCODER); + int err; + + if (!ctx) + die("swot: allocating PNG encoder"); + if ((err = spng_set_png_file(ctx, out)) || + (err = spng_set_ihdr(ctx, &header)) || + (err = spng_encode_image(ctx, rgb, (size_t)w * h * 3, SPNG_FMT_PNG, SPNG_ENCODE_FINALIZE))) + die("swot: PNG: %s", spng_strerror(err)); + spng_ctx_free(ctx); +} + +static void +write_jpeg(FILE *out, unsigned char *rgb, int w, int h) +{ + struct jpeg_compress_struct jpg; + struct jpeg_error_mgr err; + JSAMPROW row; + + jpg.err = jpeg_std_error(&err); + jpeg_create_compress(&jpg); + jpeg_stdio_dest(&jpg, out); + jpg.image_width = w; + jpg.image_height = h; + jpg.input_components = 3; + jpg.in_color_space = JCS_RGB; + jpeg_set_defaults(&jpg); + jpeg_start_compress(&jpg, TRUE); + while (jpg.next_scanline < jpg.image_height) { + row = rgb + (size_t)jpg.next_scanline * w * 3; + jpeg_write_scanlines(&jpg, &row, 1); + } + jpeg_finish_compress(&jpg); + jpeg_destroy_compress(&jpg); +} + +static void +paint_border(uint32_t *pixels, struct Rect r, uint32_t outer, uint32_t inner) +{ + int x, y, edge; + + for (edge = 0; edge < 2 && r.left < r.right && r.top < r.bottom; edge++) { + for (x = r.left; x < r.right; x++) { + pixels[r.top * width + x] = outer; + pixels[(r.bottom - 1) * width + x] = outer; + } + for (y = r.top; y < r.bottom; y++) { + pixels[y * width + r.left] = outer; + pixels[y * width + r.right - 1] = outer; + } + r = (struct Rect){r.left + 1, r.top + 1, r.right - 1, r.bottom - 1}; + outer = inner; + } +} + +static void +damage_border(struct Rect r) +{ + int w = r.right - r.left, h = r.bottom - r.top; + int dx = MIN(2, w), dy = MIN(2, h); + + if (w <= 0 || h <= 0) + return; + wl_surface_damage(overlay, r.left, r.top, w, dy); + wl_surface_damage(overlay, r.left, r.bottom - dy, w, dy); + wl_surface_damage(overlay, r.left, r.top, dx, h); + wl_surface_damage(overlay, r.right - dx, r.top, dx, h); +} + +static void +released(void *data, struct wl_buffer *buffer) +{ + struct Canvas *canvas = data; + canvas->busy = 0; +} + +static const struct wl_buffer_listener buffer_listener = {released}; + +static void +draw_box(void) +{ + struct Canvas *canvas = canvases[0].busy ? &canvases[1] : &canvases[0]; + + if (canvas->busy) + return; + paint_border(canvas->pixels, canvas->box, 0, 0); + paint_border(canvas->pixels, region, 0xffffffff, 0xff000000); + wl_surface_attach(overlay, canvas->buffer, 0, 0); + damage_border(shown); + damage_border(region); + wl_surface_commit(overlay); + canvas->box = shown = region; + canvas->busy = 1; + redraw = 0; +} + +static int +pointer_event(const void *data, void *target, uint32_t opcode, + const struct wl_message *event, union wl_argument *args) +{ + static int x, y, start_x, start_y; + + if (!strcmp(event->name, "enter") || !strcmp(event->name, "motion")) { + unsigned xy = !strcmp(event->name, "enter") ? 2 : 1; + x = MIN(width, MAX(0, wl_fixed_to_int(args[xy].f))); + y = MIN(height, MAX(0, wl_fixed_to_int(args[xy + 1].f))); + if (drag_button && !selected) { + region = (struct Rect){MIN(start_x, x), MIN(start_y, y), + MAX(start_x, x), MAX(start_y, y)}; + redraw = 1; + } + } else if (!strcmp(event->name, "button")) { + uint32_t btn = args[2].u, state = args[3].u; + if (!drag_button && state == WL_POINTER_BUTTON_STATE_PRESSED) { + drag_button = btn; + start_x = x; + start_y = y; + } else if (btn == drag_button && state == WL_POINTER_BUTTON_STATE_RELEASED) { + selected = 1; + } + } + return 0; +} + +static void +load_keymap(uint32_t format, int fd, uint32_t size) +{ + struct xkb_context *ctx; + struct xkb_keymap *map; + char *text; + + xkb_state_unref(keys); + keys = NULL; + if (format == WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) { + text = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0); + ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + if (text == MAP_FAILED || !ctx) + die("swot: loading keyboard map"); + map = xkb_keymap_new_from_buffer(ctx, text, size - 1, XKB_KEYMAP_FORMAT_TEXT_V1, 0); + munmap(text, size); + if (!map || !(keys = xkb_state_new(map))) + die("swot: invalid keyboard map"); + xkb_keymap_unref(map); + xkb_context_unref(ctx); + } + close(fd); +} + +/* probably overkill just to get the keyboard input instead of using evdev */ +static int +keyboard_event(const void *data, void *target, uint32_t opcode, + const struct wl_message *event, union wl_argument *args) +{ + if (!strcmp(event->name, "keymap")) + load_keymap(args[0].u, args[1].h, args[2].u); + else if (keys && !strcmp(event->name, "modifiers")) + xkb_state_update_mask(keys, args[1].u, args[2].u, args[3].u, 0, 0, args[4].u); + else if (keys && !selected && !strcmp(event->name, "key") && + args[3].u == WL_KEYBOARD_KEY_STATE_PRESSED && + xkb_state_key_get_one_sym(keys, args[2].u + 8) == XKB_KEY_Escape) + die("swot: selection cancelled"); + return 0; +} + +static void +configure(void *data, struct zwlr_layer_surface_v1 *layer, uint32_t serial, uint32_t w, uint32_t h) +{ + if (w != (uint32_t)width || h != (uint32_t)height) + die("swot: selection surface does not match capture size"); + zwlr_layer_surface_v1_ack_configure(layer, serial); + redraw = 1; +} + +static void +closed(void *data, struct zwlr_layer_surface_v1 *layer) +{ + die("swot: selection closed"); +} + +static const struct zwlr_layer_surface_v1_listener layer_listener = {configure, closed}; + +static void +select_region(struct wl_display *display) +{ + struct zwlr_layer_surface_v1 *layer; + struct Canvas *canvas; + + if (!shell || !compositor || !(capabilities & WL_SEAT_CAPABILITY_POINTER)) + die("swot: selection requires layer-shell and a pointer"); + wl_proxy_add_dispatcher((struct wl_proxy *)wl_seat_get_pointer(seat), pointer_event, NULL, NULL); + if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) + wl_proxy_add_dispatcher((struct wl_proxy *)wl_seat_get_keyboard(seat), keyboard_event, NULL, NULL); + overlay = wl_compositor_create_surface(compositor); + layer = zwlr_layer_shell_v1_get_layer_surface(shell, overlay, NULL, + ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY, "swot"); + zwlr_layer_surface_v1_add_listener(layer, &layer_listener, NULL); + zwlr_layer_surface_v1_set_size(layer, width, height); + zwlr_layer_surface_v1_set_exclusive_zone(layer, -1); + zwlr_layer_surface_v1_set_keyboard_interactivity(layer, + ZWLR_LAYER_SURFACE_V1_KEYBOARD_INTERACTIVITY_EXCLUSIVE); + for (canvas = canvases; canvas < canvases + 2; canvas++) { + canvas->buffer = make_buffer(&canvas->pixels); + wl_buffer_add_listener(canvas->buffer, &buffer_listener, canvas); + } + wl_surface_commit(overlay); + while (!selected) { + if (wl_display_dispatch(display) < 0) + die("swot: waiting for selection:"); + if (redraw && !selected) + draw_box(); + } + zwlr_layer_surface_v1_destroy(layer); + wl_surface_destroy(overlay); + overlay = NULL; + for (canvas = canvases; canvas < canvases + 2; canvas++) { + wl_buffer_destroy(canvas->buffer); + munmap(canvas->pixels, (size_t)width * height * 4); + } +} + +static uint32_t * +screenshot(int select) +{ + struct wl_display *display; + struct wl_registry *registry; + uint32_t *pixels; + + if (!(display = wl_display_connect(NULL))) + die("swot: connecting to Wayland:"); + registry = wl_display_get_registry(display); + if (!registry || wl_registry_add_listener(registry, &registry_listener, &select) < 0) + die("swot: binding Wayland registry:"); + if (wl_display_roundtrip(display) < 0 || wl_display_roundtrip(display) < 0) + die("swot: reading Wayland globals:"); + if (!snap || !shm || !width) + die("swot: capture requires swc_snap, wl_shm and an active screen"); + if (select) + select_region(display); + else + region = (struct Rect){0, 0, width, height}; + frame = make_buffer(&pixels); + swc_snap_capture(snap, frame, SWC_SNAP_FLAGS_OVERLAY_CURSOR); + while (!ready) + if (wl_display_dispatch(display) < 0) + die("swot: waiting for capture:"); + wl_buffer_destroy(frame); + wl_display_disconnect(display); + xkb_state_unref(keys); + return pixels; +} + +int +main(int argc, char **argv) +{ + const char *path = NULL, *ext; + FILE *out = stdout; + uint32_t *pixels, pixel; + unsigned char *rgb, *p; + int opt, select_region = 0, w, h, x, y; + + while ((opt = getopt(argc, argv, "so:")) != -1) { + switch (opt) { + case 's': select_region = 1; break; + case 'o': path = optarg; break; + default: die("usage: swot [-s] [-o file]"); + } + } + if (optind != argc) + die("usage: swot [-s] [-o file]"); + pixels = screenshot(select_region); + w = region.right - region.left; + h = region.bottom - region.top; + if (w <= 0 || h <= 0) + die("swot: empty selection on captured screen"); + /* Forward packing is safe because each source pixel is larger than its RGB triple */ + p = rgb = (unsigned char *)pixels; + for (y = 0; y < h; y++) { + for (x = 0; x < w; x++) { + pixel = pixels[(region.top + y) * width + region.left + x]; + *p++ = pixel >> 16; + *p++ = pixel >> 8; + *p++ = pixel; + } + } + if (path && !(out = fopen(path, "wb"))) + die("swot: %s:", path); + ext = path ? strrchr(path, '.') : NULL; + if (ext && (!strcasecmp(ext, ".jpg") || !strcasecmp(ext, ".jpeg"))) + write_jpeg(out, rgb, w, h); + else + write_png(out, rgb, w, h); + munmap(pixels, (size_t)width * height * 4); + if (fclose(out)) + die("swot: writing image:"); + return 0; +} diff --git a/util.c b/util.c @@ -0,0 +1,27 @@ +// See LICENSE file for copyright and license details. +#include <errno.h> +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "util.h" + +void +die(const char *fmt, ...) +{ + va_list ap; + int saved_errno; + + saved_errno = errno; + + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + + if (fmt[0] && fmt[strlen(fmt)-1] == ':') + fprintf(stderr, " %s", strerror(saved_errno)); + fputc('\n', stderr); + + exit(1); +} diff --git a/util.h b/util.h @@ -0,0 +1,5 @@ +// See LICENSE file for copyright and license details. +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#define MIN(a, b) ((a) < (b) ? (a) : (b)) + +void die(const char *fmt, ...);