Commit 9f4ab07
2025-12-27 10:36:49
Changed files (38)
swaylock-mod
include
pam
swaylock-mod/include/background-image.h
@@ -0,0 +1,26 @@
+#ifndef _SWAY_BACKGROUND_IMAGE_H
+#define _SWAY_BACKGROUND_IMAGE_H
+#include <wayland-client.h>
+#include "cairo.h"
+
+enum background_mode {
+ BACKGROUND_MODE_STRETCH,
+ BACKGROUND_MODE_FILL,
+ BACKGROUND_MODE_FIT,
+ BACKGROUND_MODE_CENTER,
+ BACKGROUND_MODE_TILE,
+ BACKGROUND_MODE_SOLID_COLOR,
+ BACKGROUND_MODE_INVALID,
+};
+
+struct swaylock_surface;
+
+enum background_mode parse_background_mode(const char *mode);
+cairo_surface_t *load_background_image(const char *path);
+cairo_surface_t *load_background_from_buffer(void *buf, uint32_t format,
+ uint32_t width, uint32_t height, uint32_t stride, enum wl_output_transform transform);
+cairo_surface_t *scale_background_image(cairo_surface_t *image,
+ enum background_mode mode, int buffer_width, int buffer_height);
+void render_background_image(cairo_t *cairo, cairo_surface_t *image, double alpha);
+
+#endif
swaylock-mod/include/cairo.h
@@ -0,0 +1,24 @@
+#ifndef _SWAY_CAIRO_H
+#define _SWAY_CAIRO_H
+
+#include "config.h"
+#include <stdint.h>
+#include <cairo/cairo.h>
+#include <wayland-client.h>
+#if HAVE_GDK_PIXBUF
+#include <gdk-pixbuf/gdk-pixbuf.h>
+#endif
+
+void cairo_set_source_u32(cairo_t *cairo, uint32_t color);
+cairo_subpixel_order_t to_cairo_subpixel_order(enum wl_output_subpixel subpixel);
+
+cairo_surface_t *cairo_surface_duplicate(cairo_surface_t *src);
+
+#if HAVE_GDK_PIXBUF
+
+cairo_surface_t* gdk_cairo_image_surface_create_from_pixbuf(
+ const GdkPixbuf *gdkbuf);
+
+#endif // HAVE_GDK_PIXBUF
+
+#endif
swaylock-mod/include/comm.h
@@ -0,0 +1,18 @@
+#ifndef _SWAYLOCK_COMM_H
+#define _SWAYLOCK_COMM_H
+
+#include <stdbool.h>
+
+struct swaylock_password;
+
+bool spawn_comm_child(void);
+ssize_t read_comm_request(char **buf_ptr);
+bool write_comm_reply(bool success);
+// Requests the provided password to be checked. The password is always cleared
+// when the function returns.
+bool write_comm_request(struct swaylock_password *pw);
+bool read_comm_reply(void);
+// FD to poll for password authentication replies.
+int get_comm_reply_fd(void);
+
+#endif
swaylock-mod/include/effects.h
@@ -0,0 +1,64 @@
+#ifndef _SWAYLOCK_EFFECTS_H
+#define _SWAYLOCK_EFFECTS_H
+
+#include <stdbool.h>
+
+#include "cairo.h"
+
+struct swaylock_effect_screen_pos {
+ float pos;
+ bool is_percent;
+};
+
+struct swaylock_effect {
+ union {
+ struct {
+ int radius, times;
+ } blur;
+ struct {
+ int factor;
+ } pixelate;
+ double scale;
+ struct {
+ double base;
+ double factor;
+ } vignette;
+ struct {
+ struct swaylock_effect_screen_pos x;
+ struct swaylock_effect_screen_pos y;
+ struct swaylock_effect_screen_pos w;
+ struct swaylock_effect_screen_pos h;
+ enum {
+ EFFECT_COMPOSE_GRAV_CENTER,
+ EFFECT_COMPOSE_GRAV_NW,
+ EFFECT_COMPOSE_GRAV_NE,
+ EFFECT_COMPOSE_GRAV_SW,
+ EFFECT_COMPOSE_GRAV_SE,
+ EFFECT_COMPOSE_GRAV_N,
+ EFFECT_COMPOSE_GRAV_S,
+ EFFECT_COMPOSE_GRAV_E,
+ EFFECT_COMPOSE_GRAV_W,
+ } gravity;
+ char *imgpath;
+ } compose;
+ char *custom;
+ } e;
+
+ enum {
+ EFFECT_BLUR,
+ EFFECT_PIXELATE,
+ EFFECT_SCALE,
+ EFFECT_GREYSCALE,
+ EFFECT_VIGNETTE,
+ EFFECT_COMPOSE,
+ EFFECT_CUSTOM,
+ } tag;
+};
+
+cairo_surface_t *swaylock_effects_run(cairo_surface_t *surface, int scale,
+ struct swaylock_effect *effects, int count);
+
+cairo_surface_t *swaylock_effects_run_timed(cairo_surface_t *surface, int scale,
+ struct swaylock_effect *effects, int count);
+
+#endif
swaylock-mod/include/fade.h
@@ -0,0 +1,17 @@
+#ifndef _SWAYLOCK_FADE_H
+#define _SWAYLOCK_FADE_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+struct swaylock_fade {
+ float current_time;
+ float target_time;
+ uint32_t old_time;
+ double alpha;
+};
+
+void fade_update(struct swaylock_fade *fade, uint32_t time);
+bool fade_is_complete(struct swaylock_fade *fade);
+
+#endif
swaylock-mod/include/log.h
@@ -0,0 +1,42 @@
+#ifndef _SWAYLOCK_LOG_H
+#define _SWAYLOCK_LOG_H
+
+#include <stdarg.h>
+#include <string.h>
+#include <errno.h>
+
+enum log_importance {
+ LOG_SILENT = 0,
+ LOG_ERROR = 1,
+ LOG_INFO = 2,
+ LOG_DEBUG = 3,
+ LOG_TRACE = 4,
+ LOG_IMPORTANCE_LAST,
+};
+
+void swaylock_log_init(enum log_importance verbosity);
+
+#ifdef __GNUC__
+#define _ATTRIB_PRINTF(start, end) __attribute__((format(printf, start, end)))
+#else
+#define _ATTRIB_PRINTF(start, end)
+#endif
+
+void _swaylock_log(enum log_importance verbosity, const char *format, ...)
+ _ATTRIB_PRINTF(2, 3);
+
+void _swaylock_trace(const char *file, int line, const char *func);
+
+const char *_swaylock_strip_path(const char *filepath);
+
+#define swaylock_log(verb, fmt, ...) \
+ _swaylock_log(verb, "[%s:%d] " fmt, _swaylock_strip_path(__FILE__), \
+ __LINE__, ##__VA_ARGS__)
+
+#define swaylock_log_errno(verb, fmt, ...) \
+ swaylock_log(verb, fmt ": %s", ##__VA_ARGS__, strerror(errno))
+
+#define swaylock_trace() \
+ _swaylock_trace(__FILE__, __LINE__, __func__)
+
+#endif
swaylock-mod/include/loop.h
@@ -0,0 +1,54 @@
+#ifndef _SWAY_LOOP_H
+#define _SWAY_LOOP_H
+#include <stdbool.h>
+
+/**
+ * This is an event loop system designed for sway clients, not sway itself.
+ *
+ * The loop consists of file descriptors and timers. Typically the Wayland
+ * display's file descriptor will be one of the fds in the loop.
+ */
+
+struct loop;
+struct loop_timer;
+
+/**
+ * Create an event loop.
+ */
+struct loop *loop_create(void);
+
+/**
+ * Destroy the event loop (eg. on program termination).
+ */
+void loop_destroy(struct loop *loop);
+
+/**
+ * Poll the event loop. This will block until one of the fds has data.
+ */
+void loop_poll(struct loop *loop);
+
+/**
+ * Add a file descriptor to the loop.
+ */
+void loop_add_fd(struct loop *loop, int fd, short mask,
+ void (*func)(int fd, short mask, void *data), void *data);
+
+/**
+ * Add a timer to the loop.
+ *
+ * When the timer expires, the timer will be removed from the loop and freed.
+ */
+struct loop_timer *loop_add_timer(struct loop *loop, int ms,
+ void (*callback)(void *data), void *data);
+
+/**
+ * Remove a file descriptor from the loop.
+ */
+bool loop_remove_fd(struct loop *loop, int fd);
+
+/**
+ * Remove a timer from the loop.
+ */
+bool loop_remove_timer(struct loop *loop, struct loop_timer *timer);
+
+#endif
swaylock-mod/include/meson.build
@@ -0,0 +1,1 @@
+configure_file(output: 'config.h', configuration: conf_data)
swaylock-mod/include/password-buffer.h
@@ -0,0 +1,9 @@
+#ifndef _SWAY_PASSWORD_BUFFER_H
+#define _SWAY_PASSWORD_BUFFER_H
+
+#include <stddef.h>
+
+char *password_buffer_create(size_t size);
+void password_buffer_destroy(char *buffer, size_t size);
+
+#endif
swaylock-mod/include/pool-buffer.h
@@ -0,0 +1,22 @@
+#ifndef _SWAY_BUFFERS_H
+#define _SWAY_BUFFERS_H
+#include <cairo/cairo.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <wayland-client.h>
+
+struct pool_buffer {
+ struct wl_buffer *buffer;
+ cairo_surface_t *surface;
+ cairo_t *cairo;
+ uint32_t width, height;
+ void *data;
+ size_t size;
+ bool busy;
+};
+
+struct pool_buffer *get_next_buffer(struct wl_shm *shm,
+ struct pool_buffer pool[static 2], uint32_t width, uint32_t height);
+void destroy_buffer(struct pool_buffer *buffer);
+
+#endif
swaylock-mod/include/seat.h
@@ -0,0 +1,32 @@
+#ifndef _SWAYLOCK_SEAT_H
+#define _SWAYLOCK_SEAT_H
+#include <xkbcommon/xkbcommon.h>
+#include <stdint.h>
+#include <stdbool.h>
+
+struct loop;
+struct loop_timer;
+
+struct swaylock_xkb {
+ bool caps_lock;
+ bool control;
+ struct xkb_state *state;
+ struct xkb_context *context;
+ struct xkb_keymap *keymap;
+};
+
+struct swaylock_seat {
+ struct swaylock_state *state;
+ struct wl_pointer *pointer;
+ struct wl_keyboard *keyboard;
+ struct wl_touch *touch;
+ int32_t repeat_period_ms;
+ int32_t repeat_delay_ms;
+ uint32_t repeat_sym;
+ uint32_t repeat_codepoint;
+ struct loop_timer *repeat_timer;
+};
+
+extern const struct wl_seat_listener seat_listener;
+
+#endif
swaylock-mod/include/swaylock.h
@@ -0,0 +1,183 @@
+#ifndef _SWAYLOCK_H
+#define _SWAYLOCK_H
+#include <stdbool.h>
+#include <stdint.h>
+#include <wayland-client.h>
+#include "background-image.h"
+#include "cairo.h"
+#include "pool-buffer.h"
+#include "seat.h"
+#include "effects.h"
+#include "fade.h"
+#include "wlr-layer-shell-unstable-v1-client-protocol.h"
+
+enum auth_state {
+ AUTH_STATE_IDLE,
+ AUTH_STATE_CLEAR,
+ AUTH_STATE_INPUT,
+ AUTH_STATE_INPUT_NOP,
+ AUTH_STATE_BACKSPACE,
+ AUTH_STATE_VALIDATING,
+ AUTH_STATE_INVALID,
+ AUTH_STATE_GRACE,
+};
+
+struct swaylock_colorset {
+ uint32_t input;
+ uint32_t cleared;
+ uint32_t caps_lock;
+ uint32_t verifying;
+ uint32_t wrong;
+};
+
+struct swaylock_colors {
+ uint32_t background;
+ uint32_t bs_highlight;
+ uint32_t key_highlight;
+ uint32_t caps_lock_bs_highlight;
+ uint32_t caps_lock_key_highlight;
+ uint32_t separator;
+ uint32_t layout_background;
+ uint32_t layout_border;
+ uint32_t layout_text;
+ struct swaylock_colorset inside;
+ struct swaylock_colorset line;
+ struct swaylock_colorset ring;
+ struct swaylock_colorset text;
+};
+
+struct swaylock_args {
+ struct swaylock_colors colors;
+ enum background_mode mode;
+ char *font;
+ uint32_t font_size;
+ uint32_t radius;
+ uint32_t thickness;
+ uint32_t indicator_x_position;
+ uint32_t indicator_y_position;
+ bool override_indicator_x_position;
+ bool override_indicator_y_position;
+ bool ignore_empty;
+ bool show_indicator;
+ bool show_caps_lock_text;
+ bool show_caps_lock_indicator;
+ bool show_keyboard_layout;
+ bool hide_keyboard_layout;
+ bool show_failed_attempts;
+ bool daemonize;
+ bool indicator_idle_visible;
+
+ bool screenshots;
+ struct swaylock_effect *effects;
+ int effects_count;
+ bool time_effects;
+ bool indicator;
+ bool clock;
+ char *timestr;
+ char *datestr;
+ uint32_t fade_in;
+ bool allow_fade;
+ bool password_submit_on_touch;
+ uint32_t password_grace_period;
+ bool password_grace_no_mouse;
+ bool password_grace_no_touch;
+
+ char *text_cleared;
+ char *text_caps_lock;
+ char *text_verifying;
+ char *text_wrong;
+};
+
+struct swaylock_password {
+ size_t len;
+ size_t buffer_len;
+ char *buffer;
+};
+
+struct swaylock_state {
+ struct loop *eventloop;
+ struct loop_timer *clear_indicator_timer; // clears the indicator
+ struct loop_timer *clear_password_timer; // clears the password buffer
+ struct wl_display *display;
+ struct wl_compositor *compositor;
+ struct wl_subcompositor *subcompositor;
+ struct zwlr_layer_shell_v1 *layer_shell;
+ struct zwlr_input_inhibit_manager_v1 *input_inhibit_manager;
+ struct zwlr_screencopy_manager_v1 *screencopy_manager;
+ struct wl_shm *shm;
+ struct wl_list surfaces;
+ struct wl_list images;
+ cairo_surface_t *indicator_image;
+ struct swaylock_args args;
+ struct swaylock_password password;
+ struct swaylock_xkb xkb;
+ enum auth_state auth_state;
+ bool indicator_dirty;
+ int render_randnum;
+ int failed_attempts;
+ size_t n_screenshots_done;
+ bool run_display;
+ struct ext_session_lock_manager_v1 *ext_session_lock_manager_v1;
+ struct ext_session_lock_v1 *ext_session_lock_v1;
+};
+
+struct swaylock_surface {
+ cairo_surface_t *image;
+ cairo_surface_t *scaled_image;
+ struct {
+ uint32_t format, width, height, stride;
+ enum wl_output_transform transform;
+ void *data;
+ cairo_surface_t *original_image;
+ cairo_surface_t *scaled_image;
+ struct swaylock_image *image;
+ } screencopy;
+ struct swaylock_state *state;
+ struct wl_output *output;
+ uint32_t output_global_name;
+ struct wl_surface *surface;
+ struct wl_surface *child; // surface made into subsurface
+ struct wl_subsurface *subsurface;
+ struct zwlr_layer_surface_v1 *layer_surface;
+ struct zwlr_screencopy_frame_v1 *screencopy_frame;
+ struct ext_session_lock_surface_v1 *ext_session_lock_surface_v1;
+ struct pool_buffer buffers[2];
+ struct pool_buffer indicator_buffers[2];
+ struct swaylock_fade fade;
+ int events_pending;
+ bool configured;
+ bool frame_pending, dirty;
+ uint32_t width, height;
+ uint32_t indicator_width, indicator_height;
+ int32_t scale;
+ enum wl_output_subpixel subpixel;
+ enum wl_output_transform transform;
+ char *output_name;
+ struct wl_list link;
+};
+
+// There is exactly one swaylock_image for each -i argument
+struct swaylock_image {
+ char *path;
+ char *output_name;
+ cairo_surface_t *cairo_surface;
+ struct wl_list link;
+};
+
+void swaylock_handle_key(struct swaylock_state *state,
+ xkb_keysym_t keysym, uint32_t codepoint);
+void swaylock_handle_mouse(struct swaylock_state *state);
+void swaylock_handle_touch(struct swaylock_state *state);
+void render_frame_background(struct swaylock_surface *surface, bool commit);
+void render_background_fade(struct swaylock_surface *surface, uint32_t time);
+void render_frame(struct swaylock_surface *surface);
+void damage_surface(struct swaylock_surface *surface);
+void damage_state(struct swaylock_state *state);
+void clear_password_buffer(struct swaylock_password *pw);
+void schedule_indicator_clear(struct swaylock_state *state);
+
+void initialize_pw_backend(int argc, char **argv);
+void run_pw_backend_child(void);
+void clear_buffer(char *buf, size_t size);
+
+#endif
swaylock-mod/include/unicode.h
@@ -0,0 +1,41 @@
+#ifndef _SWAY_UNICODE_H
+#define _SWAY_UNICODE_H
+#include <stddef.h>
+#include <stdint.h>
+
+// Technically UTF-8 supports up to 6 byte codepoints, but Unicode itself
+// doesn't really bother with more than 4.
+#define UTF8_MAX_SIZE 4
+
+#define UTF8_INVALID 0x80
+
+/**
+ * Gets the size in bytes of the last utf8 character in a NULL terminated string
+ * This function does not validate that the buffer contains correct utf8 data;
+ * it merely looks for the first byte that correctly denotes the beginning of a
+ * utf8 character.
+ */
+int utf8_last_size(const char *str);
+
+/**
+ * Grabs the next UTF-8 character and advances the string pointer
+ */
+uint32_t utf8_decode(const char **str);
+
+/**
+ * Encodes a character as UTF-8 and returns the length of that character.
+ */
+size_t utf8_encode(char *str, uint32_t ch);
+
+/**
+ * Returns the size of the next UTF-8 character
+ */
+int utf8_size(const char *str);
+
+/**
+ * Returns the size of a UTF-8 character
+ */
+size_t utf8_chsize(uint32_t ch);
+
+#endif
+
swaylock-mod/pam/swaylock
@@ -0,0 +1,1 @@
+auth include login
swaylock-mod/.build.yml
@@ -0,0 +1,23 @@
+image: alpine/edge
+packages:
+ - meson
+ - cairo-dev
+ - wayland-dev
+ - wayland-protocols
+ - libxkbcommon-dev
+ - gdk-pixbuf-dev
+ - linux-pam-dev
+ - scdoc
+sources:
+ - https://github.com/swaywm/swaylock
+tasks:
+ - setup: |
+ cd swaylock
+ meson build
+ - build: |
+ cd swaylock
+ ninja -C build
+ - build-no-pam: |
+ cd swaylock
+ meson configure build -Dpam=disabled
+ ninja -C build
swaylock-mod/.editorconfig
@@ -0,0 +1,22 @@
+# For the full list of code style requirements, see sway's CONTRIBUTING.md
+
+root = true
+
+[*]
+charset = utf-8
+end_of_line = lf
+
+[*.{c,h,cmake,txt}]
+indent_style = tab
+indent_size = 4
+
+[*.{xml,yml}]
+indent_style = space
+indent_size = 2
+
+[config]
+indent_style = space
+indent_size = 4
+
+[*.md]
+trim_trailing_whitespace = false
swaylock-mod/.gitignore
@@ -0,0 +1,1 @@
+build
swaylock-mod/background-image.c
@@ -0,0 +1,451 @@
+#define _DEFAULT_SOURCE
+#include <assert.h>
+#include "background-image.h"
+#include "cairo.h"
+#include "log.h"
+#include "swaylock.h"
+
+#ifdef __FreeBSD__
+# include <sys/endian.h>
+#else
+# include <endian.h>
+#endif
+
+// Cairo RGB24 uses 32 bits per pixel, as XRGB, in native endianness.
+// xrgb32_le uses 32 bits per pixel, as XRGB, little endian (BGRX big endian).
+void cairo_rgb24_from_xrgb32_le(unsigned char *buf, int width, int height, int stride) {
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+ unsigned char *pix = buf + y * stride + x * 4;
+ *(uint32_t *)pix = 0 |
+ (uint32_t)pix[2] << 16 |
+ (uint32_t)pix[1] << 8 |
+ (uint32_t)pix[0];
+ }
+ }
+}
+
+// Cairo RGB24 uses 32 bits per pixel, as XRGB, in native endianness.
+// xbgr32_le uses 32 bits per pixel, as XBGR, little endian (RGBX big endian).
+void cairo_rgb24_from_xbgr32_le(unsigned char *buf, int width, int height, int stride) {
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+ unsigned char *pix = buf + y * stride + x * 4;
+ *(uint32_t *)pix = 0 |
+ (uint32_t)pix[0] << 16 |
+ (uint32_t)pix[1] << 8 |
+ (uint32_t)pix[2];
+ }
+ }
+}
+
+void cairo_rgb24_from_xrgb2101010_le(unsigned char *buf, int width, int height, int stride) {
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+ uint32_t *pix = (uint32_t *) (buf + y * stride + x * 4);
+ uint32_t color = le32toh(*pix);
+ *pix = 0 |
+ ((color >> 22) & 0xFF) << 16 |
+ ((color >> 12) & 0xFF) << 8 |
+ ((color >> 2) & 0xFF);
+ }
+ }
+}
+
+void cairo_rgb24_from_xbgr2101010_le(unsigned char *buf, int width, int height, int stride) {
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+ uint32_t *pix = (uint32_t *) (buf + y * stride + x * 4);
+ uint32_t color = le32toh(*pix);
+ *pix = 0 |
+ ((color >> 2) & 0xFF) << 16 |
+ ((color >> 12) & 0xFF) << 8 |
+ ((color >> 22) & 0xFF);
+ }
+ }
+}
+
+void cairo_rgb24_from_rgbx1010102_le(unsigned char *buf, int width, int height, int stride) {
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+ uint32_t *pix = (uint32_t *) (buf + y * stride + x * 4);
+ uint32_t color = le32toh(*pix);
+ *pix = 0 |
+ ((color >> 24) & 0xFF) << 16 |
+ ((color >> 14) & 0xFF) << 8 |
+ ((color >> 4) & 0xFF);
+ }
+ }
+}
+
+void cairo_rgb24_from_bgrx1010102_le(unsigned char *buf, int width, int height, int stride) {
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+ uint32_t *pix = (uint32_t *) (buf + y * stride + x * 4);
+ uint32_t color = le32toh(*pix);
+ *pix = 0 |
+ ((color >> 4) & 0xFF) << 16 |
+ ((color >> 14) & 0xFF) << 8 |
+ ((color >> 24) & 0xFF);
+ }
+ }
+}
+
+// Cairo RGB24 uses 32 bits per pixel, as XRGB, in native endianness.
+// BGR888 uses 24 bits per pixel, as BGR, little endian.
+// 24-bit BGR format, [23:0] B:G:R little endian (From wayland-client-protocol.h)
+void cairo_rgb24_from_bgr888_le(unsigned char *buf, int width, int height, int stride) {
+ for (int y = 0; y < height; ++y) {
+ // Row from back to front to avoid overwriting data.
+ for (int x = width-1; x >= 0; --x) {
+ // 24 bits = 3 bytes, 32 bits = 4 bytes
+ unsigned char *srcpix = buf + y * stride + x * 3;
+ unsigned char *dstpix = buf + y * stride + x * 4;
+
+ *(uint32_t *)dstpix = 0 |
+ (uint32_t)srcpix[0] << 16 |
+ (uint32_t)srcpix[1] << 8 |
+ (uint32_t)srcpix[2];
+ }
+ }
+}
+
+// Swap red and blue values in Cairo RGB24
+void cairo_rgb24_swap_rb(unsigned char *buf, int width, int height, int stride) {
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+ unsigned char *pix = buf + y * stride + x * 4;
+
+ *(uint32_t *)pix = 0 |
+ (uint32_t)pix[0] << 16 |
+ (uint32_t)pix[1] << 8 |
+ (uint32_t)pix[2];
+ }
+ }
+}
+
+enum background_mode parse_background_mode(const char *mode) {
+ if (strcmp(mode, "stretch") == 0) {
+ return BACKGROUND_MODE_STRETCH;
+ } else if (strcmp(mode, "fill") == 0) {
+ return BACKGROUND_MODE_FILL;
+ } else if (strcmp(mode, "fit") == 0) {
+ return BACKGROUND_MODE_FIT;
+ } else if (strcmp(mode, "center") == 0) {
+ return BACKGROUND_MODE_CENTER;
+ } else if (strcmp(mode, "tile") == 0) {
+ return BACKGROUND_MODE_TILE;
+ } else if (strcmp(mode, "solid_color") == 0) {
+ return BACKGROUND_MODE_SOLID_COLOR;
+ }
+ swaylock_log(LOG_ERROR, "Unsupported background mode: %s", mode);
+ return BACKGROUND_MODE_INVALID;
+}
+
+cairo_surface_t *load_background_from_buffer(void *buf, uint32_t format,
+ uint32_t width, uint32_t height, uint32_t stride, enum wl_output_transform transform) {
+ bool rotated =
+ transform == WL_OUTPUT_TRANSFORM_90 ||
+ transform == WL_OUTPUT_TRANSFORM_270 ||
+ transform == WL_OUTPUT_TRANSFORM_FLIPPED_90 ||
+ transform == WL_OUTPUT_TRANSFORM_FLIPPED_270;
+
+ cairo_surface_t *image;
+ if (rotated) {
+ image = cairo_image_surface_create(CAIRO_FORMAT_RGB24, height, width);
+ } else {
+ image = cairo_image_surface_create(CAIRO_FORMAT_RGB24, width, height);
+ }
+ if (image == NULL) {
+ swaylock_log(LOG_ERROR, "Failed to create image..");
+ return NULL;
+ }
+
+ unsigned char *destbuf = cairo_image_surface_get_data(image);
+ size_t destwidth = cairo_image_surface_get_width(image);
+ size_t destheight = cairo_image_surface_get_height(image);
+ size_t deststride = cairo_image_surface_get_stride(image);
+ unsigned char *srcbuf = buf;
+ size_t srcstride = stride;
+ size_t minstride = srcstride < deststride ? srcstride : deststride;
+
+ // Lots of these are mostly-copy-and-pasted, with a lot of boilerplate
+ // for each case.
+ // The only interesting differencess between a lot of these cases are
+ // the definitions of srcx and srcy.
+ // I don't think it's worth adding a macro to make this "cleaner" though,
+ // as that would obfuscate what's actually going on.
+ switch (transform) {
+ case WL_OUTPUT_TRANSFORM_NORMAL:
+ // In most cases, the transform is probably normal. Luckily, it can be
+ // done with just one big memcpy.
+ if (srcstride == deststride) {
+ memcpy(destbuf, srcbuf, destheight * deststride);
+ } else {
+ for (size_t y = 0; y < destheight; ++y) {
+ memcpy(destbuf + y * deststride, srcbuf + y * srcstride, minstride);
+ }
+ }
+ break;
+ case WL_OUTPUT_TRANSFORM_90:
+ for (size_t desty = 0; desty < destheight; ++desty) {
+ size_t srcx = desty;
+ for (size_t destx = 0; destx < destwidth; ++destx) {
+ size_t srcy = destwidth - destx - 1;
+ *((uint32_t *)(destbuf + desty * deststride) + destx) =
+ *((uint32_t *)(srcbuf + srcy * srcstride) + srcx);
+ }
+ }
+ break;
+ case WL_OUTPUT_TRANSFORM_180:
+ for (size_t desty = 0; desty < destheight; ++desty) {
+ size_t srcy = destheight - desty - 1;
+ for (size_t destx = 0; destx < destwidth; ++destx) {
+ size_t srcx = destwidth - destx - 1;
+ *((uint32_t *)(destbuf + desty * deststride) + destx) =
+ *((uint32_t *)(srcbuf + srcy * srcstride) + srcx);
+ }
+ }
+ break;
+ case WL_OUTPUT_TRANSFORM_270:
+ for (size_t desty = 0; desty < destheight; ++desty) {
+ size_t srcx = destheight - desty - 1;
+ for (size_t destx = 0; destx < destwidth; ++destx) {
+ size_t srcy = destx;
+ *((uint32_t *)(destbuf + desty * deststride) + destx) =
+ *((uint32_t *)(srcbuf + srcy * srcstride) + srcx);
+ }
+ }
+ break;
+ case WL_OUTPUT_TRANSFORM_FLIPPED:
+ for (size_t desty = 0; desty < destheight; ++desty) {
+ size_t srcy = desty;
+ for (size_t destx = 0; destx < destwidth; ++destx) {
+ size_t srcx = destwidth - destx - 1;
+ *((uint32_t *)(destbuf + desty * deststride) + destx) =
+ *((uint32_t *)(srcbuf + srcy * srcstride) + srcx);
+ }
+ }
+ break;
+ case WL_OUTPUT_TRANSFORM_FLIPPED_90:
+ for (size_t desty = 0; desty < destheight; ++desty) {
+ size_t srcx = desty;
+ for (size_t destx = 0; destx < destwidth; ++destx) {
+ size_t srcy = destx;
+ *((uint32_t *)(destbuf + desty * deststride) + destx) =
+ *((uint32_t *)(srcbuf + srcy * srcstride) + srcx);
+ }
+ }
+ break;
+ case WL_OUTPUT_TRANSFORM_FLIPPED_180:
+ for (size_t desty = 0; desty < destheight; ++desty) {
+ size_t srcy = destheight - desty - 1;
+ memcpy(destbuf + desty * deststride, srcbuf + srcy * srcstride, minstride);
+ }
+ break;
+ case WL_OUTPUT_TRANSFORM_FLIPPED_270:
+ for (size_t desty = 0; desty < destheight; ++desty) {
+ size_t srcx = destheight - desty - 1;
+ for (size_t destx = 0; destx < destwidth; ++destx) {
+ size_t srcy = destwidth - destx - 1;
+ *((uint32_t *)(destbuf + desty * deststride) + destx) =
+ *((uint32_t *)(srcbuf + srcy * srcstride) + srcx);
+ }
+ }
+ break;
+ }
+
+ switch (format) {
+ case WL_SHM_FORMAT_XBGR8888:
+ case WL_SHM_FORMAT_ABGR8888:
+ cairo_rgb24_from_xbgr32_le(
+ cairo_image_surface_get_data(image),
+ cairo_image_surface_get_width(image),
+ cairo_image_surface_get_height(image),
+ cairo_image_surface_get_stride(image));
+ break;
+ case WL_SHM_FORMAT_XRGB2101010:
+ case WL_SHM_FORMAT_ARGB2101010:
+ cairo_rgb24_from_xrgb2101010_le(
+ cairo_image_surface_get_data(image),
+ cairo_image_surface_get_width(image),
+ cairo_image_surface_get_height(image),
+ cairo_image_surface_get_stride(image));
+ break;
+ case WL_SHM_FORMAT_XBGR2101010:
+ case WL_SHM_FORMAT_ABGR2101010:
+ cairo_rgb24_from_xbgr2101010_le(
+ cairo_image_surface_get_data(image),
+ cairo_image_surface_get_width(image),
+ cairo_image_surface_get_height(image),
+ cairo_image_surface_get_stride(image));
+ break;
+ case WL_SHM_FORMAT_RGBX1010102:
+ case WL_SHM_FORMAT_RGBA1010102:
+ cairo_rgb24_from_rgbx1010102_le(
+ cairo_image_surface_get_data(image),
+ cairo_image_surface_get_width(image),
+ cairo_image_surface_get_height(image),
+ cairo_image_surface_get_stride(image));
+ break;
+ case WL_SHM_FORMAT_BGRX1010102:
+ case WL_SHM_FORMAT_BGRA1010102:
+ cairo_rgb24_from_bgrx1010102_le(
+ cairo_image_surface_get_data(image),
+ cairo_image_surface_get_width(image),
+ cairo_image_surface_get_height(image),
+ cairo_image_surface_get_stride(image));
+ break;
+ case WL_SHM_FORMAT_BGR888:
+ case WL_SHM_FORMAT_RGB888:
+ cairo_rgb24_from_bgr888_le(
+ cairo_image_surface_get_data(image),
+ cairo_image_surface_get_width(image),
+ cairo_image_surface_get_height(image),
+ cairo_image_surface_get_stride(image)
+ );
+ if (format == WL_SHM_FORMAT_RGB888) {
+ cairo_rgb24_swap_rb(
+ cairo_image_surface_get_data(image),
+ cairo_image_surface_get_width(image),
+ cairo_image_surface_get_height(image),
+ cairo_image_surface_get_stride(image)
+ );
+ }
+ break;
+ default:
+ swaylock_log(LOG_ERROR,
+ "Unknown pixel format: %u. Assuming XRGB32. Colors may look wrong.",
+ format);
+ // fallthrough
+ case WL_SHM_FORMAT_XRGB8888:
+ case WL_SHM_FORMAT_ARGB8888: {
+ // If we're little endian, we don't have to do anything
+ int test = 1;
+ bool is_little_endian = *(char *)&test == 1;
+ if (!is_little_endian) {
+ cairo_rgb24_from_xrgb32_le(
+ cairo_image_surface_get_data(image),
+ cairo_image_surface_get_width(image),
+ cairo_image_surface_get_height(image),
+ cairo_image_surface_get_stride(image));
+ }
+ }
+ }
+
+ return image;
+}
+
+cairo_surface_t *load_background_image(const char *path) {
+ cairo_surface_t *image;
+#if HAVE_GDK_PIXBUF
+ GError *err = NULL;
+ GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(path, &err);
+ if (!pixbuf) {
+ swaylock_log(LOG_ERROR, "Failed to load background image (%s).",
+ err->message);
+ return NULL;
+ }
+ image = gdk_cairo_image_surface_create_from_pixbuf(pixbuf);
+ g_object_unref(pixbuf);
+#else
+ image = cairo_image_surface_create_from_png(path);
+#endif // HAVE_GDK_PIXBUF
+ if (!image) {
+ swaylock_log(LOG_ERROR, "Failed to read background image.");
+ return NULL;
+ }
+ if (cairo_surface_status(image) != CAIRO_STATUS_SUCCESS) {
+ swaylock_log(LOG_ERROR, "Failed to read background image: %s."
+#if !HAVE_GDK_PIXBUF
+ "\nSway was compiled without gdk_pixbuf support, so only"
+ "\nPNG images can be loaded. This is the likely cause."
+#endif // !HAVE_GDK_PIXBUF
+ , cairo_status_to_string(cairo_surface_status(image)));
+ return NULL;
+ }
+ return image;
+}
+
+cairo_surface_t *scale_background_image(cairo_surface_t *image,
+ enum background_mode mode, int buffer_width, int buffer_height) {
+ cairo_surface_t *target = cairo_image_surface_create(CAIRO_FORMAT_RGB24, buffer_width, buffer_height);
+ cairo_t *cairo = cairo_create(target);
+ double width = cairo_image_surface_get_width(image);
+ double height = cairo_image_surface_get_height(image);
+
+ switch (mode) {
+ case BACKGROUND_MODE_STRETCH:
+ cairo_scale(cairo,
+ (double)buffer_width / width,
+ (double)buffer_height / height);
+ cairo_set_source_surface(cairo, image, 0, 0);
+ break;
+ case BACKGROUND_MODE_FILL: {
+ double window_ratio = (double)buffer_width / buffer_height;
+ double bg_ratio = width / height;
+
+ if (window_ratio > bg_ratio) {
+ double scale = (double)buffer_width / width;
+ cairo_scale(cairo, scale, scale);
+ cairo_set_source_surface(cairo, image,
+ 0, (double)buffer_height / 2 / scale - height / 2);
+ } else {
+ double scale = (double)buffer_height / height;
+ cairo_scale(cairo, scale, scale);
+ cairo_set_source_surface(cairo, image,
+ (double)buffer_width / 2 / scale - width / 2, 0);
+ }
+ break;
+ }
+ case BACKGROUND_MODE_FIT: {
+ double window_ratio = (double)buffer_width / buffer_height;
+ double bg_ratio = width / height;
+
+ if (window_ratio > bg_ratio) {
+ double scale = (double)buffer_height / height;
+ cairo_scale(cairo, scale, scale);
+ cairo_set_source_surface(cairo, image,
+ (double)buffer_width / 2 / scale - width / 2, 0);
+ } else {
+ double scale = (double)buffer_width / width;
+ cairo_scale(cairo, scale, scale);
+ cairo_set_source_surface(cairo, image,
+ 0, (double)buffer_height / 2 / scale - height / 2);
+ }
+ break;
+ }
+ case BACKGROUND_MODE_CENTER:
+ /*
+ * Align the unscaled image to integer pixel boundaries
+ * in order to prevent loss of clarity (this only matters
+ * for odd-sized images).
+ */
+ cairo_set_source_surface(cairo, image,
+ (int)((double)buffer_width / 2 - width / 2),
+ (int)((double)buffer_height / 2 - height / 2));
+ break;
+ case BACKGROUND_MODE_TILE: {
+ cairo_pattern_t *pattern = cairo_pattern_create_for_surface(image);
+ cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
+ cairo_set_source(cairo, pattern);
+ break;
+ }
+ case BACKGROUND_MODE_SOLID_COLOR:
+ case BACKGROUND_MODE_INVALID:
+ assert(0);
+ break;
+ }
+
+ cairo_pattern_set_filter(cairo_get_source(cairo), CAIRO_FILTER_BILINEAR);
+ cairo_paint(cairo);
+ cairo_destroy(cairo);
+ return target;
+}
+
+void render_background_image(cairo_t *cairo, cairo_surface_t *image, double alpha) {
+ cairo_save(cairo);
+ cairo_set_source_surface(cairo, image, 0, 0);
+ cairo_paint_with_alpha(cairo, alpha);
+ cairo_restore(cairo);
+}
swaylock-mod/cairo.c
@@ -0,0 +1,140 @@
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <cairo/cairo.h>
+#include "cairo.h"
+#if HAVE_GDK_PIXBUF
+#include <gdk-pixbuf/gdk-pixbuf.h>
+#endif
+
+void cairo_set_source_u32(cairo_t *cairo, uint32_t color) {
+ cairo_set_source_rgba(cairo,
+ (color >> (3*8) & 0xFF) / 255.0,
+ (color >> (2*8) & 0xFF) / 255.0,
+ (color >> (1*8) & 0xFF) / 255.0,
+ (color >> (0*8) & 0xFF) / 255.0);
+}
+
+cairo_subpixel_order_t to_cairo_subpixel_order(enum wl_output_subpixel subpixel) {
+ switch (subpixel) {
+ case WL_OUTPUT_SUBPIXEL_HORIZONTAL_RGB:
+ return CAIRO_SUBPIXEL_ORDER_RGB;
+ case WL_OUTPUT_SUBPIXEL_HORIZONTAL_BGR:
+ return CAIRO_SUBPIXEL_ORDER_BGR;
+ case WL_OUTPUT_SUBPIXEL_VERTICAL_RGB:
+ return CAIRO_SUBPIXEL_ORDER_VRGB;
+ case WL_OUTPUT_SUBPIXEL_VERTICAL_BGR:
+ return CAIRO_SUBPIXEL_ORDER_VBGR;
+ default:
+ return CAIRO_SUBPIXEL_ORDER_DEFAULT;
+ }
+ return CAIRO_SUBPIXEL_ORDER_DEFAULT;
+}
+
+cairo_surface_t *cairo_surface_duplicate(cairo_surface_t *src) {
+ uint32_t stride = cairo_image_surface_get_stride(src);
+ uint32_t height = cairo_image_surface_get_height(src);
+ uint32_t width = cairo_image_surface_get_width(src);
+ cairo_format_t format = cairo_image_surface_get_format(src);
+
+ void *new_data = malloc(stride * height);
+ memcpy(new_data, cairo_image_surface_get_data(src), stride * height);
+
+ return cairo_image_surface_create_for_data(new_data, format, width, height, stride);
+}
+
+#if HAVE_GDK_PIXBUF
+cairo_surface_t* gdk_cairo_image_surface_create_from_pixbuf(const GdkPixbuf *gdkbuf) {
+ int chan = gdk_pixbuf_get_n_channels(gdkbuf);
+ if (chan < 3) {
+ return NULL;
+ }
+
+ const guint8* gdkpix = gdk_pixbuf_read_pixels(gdkbuf);
+ if (!gdkpix) {
+ return NULL;
+ }
+ gint w = gdk_pixbuf_get_width(gdkbuf);
+ gint h = gdk_pixbuf_get_height(gdkbuf);
+ int stride = gdk_pixbuf_get_rowstride(gdkbuf);
+
+ cairo_format_t fmt = (chan == 3) ? CAIRO_FORMAT_RGB24 : CAIRO_FORMAT_ARGB32;
+ cairo_surface_t * cs = cairo_image_surface_create (fmt, w, h);
+ cairo_surface_flush (cs);
+ if ( !cs || cairo_surface_status(cs) != CAIRO_STATUS_SUCCESS) {
+ return NULL;
+ }
+
+ int cstride = cairo_image_surface_get_stride(cs);
+ unsigned char * cpix = cairo_image_surface_get_data(cs);
+
+ if (chan == 3) {
+ int i;
+ for (i = h; i; --i) {
+ const guint8 *gp = gdkpix;
+ unsigned char *cp = cpix;
+ const guint8* end = gp + 3*w;
+ while (gp < end) {
+#if G_BYTE_ORDER == G_LITTLE_ENDIAN
+ cp[0] = gp[2];
+ cp[1] = gp[1];
+ cp[2] = gp[0];
+#else
+ cp[1] = gp[0];
+ cp[2] = gp[1];
+ cp[3] = gp[2];
+#endif
+ gp += 3;
+ cp += 4;
+ }
+ gdkpix += stride;
+ cpix += cstride;
+ }
+ } else {
+ /* premul-color = alpha/255 * color/255 * 255 = (alpha*color)/255
+ * (z/255) = z/256 * 256/255 = z/256 (1 + 1/255)
+ * = z/256 + (z/256)/255 = (z + z/255)/256
+ * # recurse once
+ * = (z + (z + z/255)/256)/256
+ * = (z + z/256 + z/256/255) / 256
+ * # only use 16bit uint operations, loose some precision,
+ * # result is floored.
+ * -> (z + z>>8)>>8
+ * # add 0x80/255 = 0.5 to convert floor to round
+ * => (z+0x80 + (z+0x80)>>8 ) >> 8
+ * ------
+ * tested as equal to lround(z/255.0) for uint z in [0..0xfe02]
+ */
+#define PREMUL_ALPHA(x,a,b,z) \
+ G_STMT_START { z = a * b + 0x80; x = (z + (z >> 8)) >> 8; } \
+ G_STMT_END
+ int i;
+ for (i = h; i; --i) {
+ const guint8 *gp = gdkpix;
+ unsigned char *cp = cpix;
+ const guint8* end = gp + 4*w;
+ guint z1, z2, z3;
+ while (gp < end) {
+#if G_BYTE_ORDER == G_LITTLE_ENDIAN
+ PREMUL_ALPHA(cp[0], gp[2], gp[3], z1);
+ PREMUL_ALPHA(cp[1], gp[1], gp[3], z2);
+ PREMUL_ALPHA(cp[2], gp[0], gp[3], z3);
+ cp[3] = gp[3];
+#else
+ PREMUL_ALPHA(cp[1], gp[0], gp[3], z1);
+ PREMUL_ALPHA(cp[2], gp[1], gp[3], z2);
+ PREMUL_ALPHA(cp[3], gp[2], gp[3], z3);
+ cp[0] = gp[3];
+#endif
+ gp += 4;
+ cp += 4;
+ }
+ gdkpix += stride;
+ cpix += cstride;
+ }
+#undef PREMUL_ALPHA
+ }
+ cairo_surface_mark_dirty(cs);
+ return cs;
+}
+#endif // HAVE_GDK_PIXBUF
swaylock-mod/comm.c
@@ -0,0 +1,109 @@
+#include <stdbool.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include "comm.h"
+#include "log.h"
+#include "swaylock.h"
+#include "password-buffer.h"
+
+static int comm[2][2] = {{-1, -1}, {-1, -1}};
+
+ssize_t read_comm_request(char **buf_ptr) {
+ size_t size;
+ ssize_t amt;
+ amt = read(comm[0][0], &size, sizeof(size));
+ if (amt == 0) {
+ return 0;
+ } else if (amt < 0) {
+ swaylock_log_errno(LOG_ERROR, "read pw request");
+ return -1;
+ }
+ swaylock_log(LOG_DEBUG, "received pw check request");
+ char *buf = password_buffer_create(size);
+ if (!buf) {
+ return -1;
+ }
+ size_t offs = 0;
+ do {
+ amt = read(comm[0][0], &buf[offs], size - offs);
+ if (amt <= 0) {
+ swaylock_log_errno(LOG_ERROR, "failed to read pw");
+ return -1;
+ }
+ offs += (size_t)amt;
+ } while (offs < size);
+
+ *buf_ptr = buf;
+ return size;
+}
+
+bool write_comm_reply(bool success) {
+ if (write(comm[1][1], &success, sizeof(success)) != sizeof(success)) {
+ swaylock_log_errno(LOG_ERROR, "failed to write pw check result");
+ return false;
+ }
+ return true;
+}
+
+bool spawn_comm_child(void) {
+ if (pipe(comm[0]) != 0) {
+ swaylock_log_errno(LOG_ERROR, "failed to create pipe");
+ return false;
+ }
+ if (pipe(comm[1]) != 0) {
+ swaylock_log_errno(LOG_ERROR, "failed to create pipe");
+ return false;
+ }
+ pid_t child = fork();
+ if (child < 0) {
+ swaylock_log_errno(LOG_ERROR, "failed to fork");
+ return false;
+ } else if (child == 0) {
+ close(comm[0][1]);
+ close(comm[1][0]);
+ run_pw_backend_child();
+ }
+ close(comm[0][0]);
+ close(comm[1][1]);
+ return true;
+}
+
+bool write_comm_request(struct swaylock_password *pw) {
+ bool result = false;
+
+ size_t len = pw->len + 1;
+ size_t offs = 0;
+ if (write(comm[0][1], &len, sizeof(len)) < 0) {
+ swaylock_log_errno(LOG_ERROR, "Failed to request pw check");
+ goto out;
+ }
+
+ do {
+ ssize_t amt = write(comm[0][1], &pw->buffer[offs], len - offs);
+ if (amt < 0) {
+ swaylock_log_errno(LOG_ERROR, "Failed to write pw buffer");
+ goto out;
+ }
+ offs += amt;
+ } while (offs < len);
+
+ result = true;
+
+out:
+ clear_password_buffer(pw);
+ return result;
+}
+
+bool read_comm_reply(void) {
+ bool result = false;
+ if (read(comm[1][0], &result, sizeof(result)) != sizeof(result)) {
+ swaylock_log_errno(LOG_ERROR, "Failed to read pw result");
+ result = false;
+ }
+ return result;
+}
+
+int get_comm_reply_fd(void) {
+ return comm[1][0];
+}
swaylock-mod/effects.c
@@ -0,0 +1,757 @@
+#define _POSIX_C_SOURCE 200809
+#define _XOPEN_SOURCE 700
+#include <omp.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <dlfcn.h>
+#include <string.h>
+#include <errno.h>
+#include <sys/wait.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <spawn.h>
+#include <time.h>
+#include <stdio.h>
+#include "effects.h"
+#include "log.h"
+
+// glib might or might not have already defined MIN,
+// depending on whether we have pixbuf or not...
+#ifndef MIN
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
+#endif
+
+extern char **environ;
+
+static int screen_size_to_pix(struct swaylock_effect_screen_pos size, int screensize, int scale) {
+ if (size.is_percent) {
+ return (size.pos / 100.0) * screensize;
+ } else if (size.pos > 0) {
+ return size.pos * scale;
+ } else {
+ return size.pos;
+ }
+}
+
+static int screen_pos_to_pix(struct swaylock_effect_screen_pos pos, int screensize, int scale) {
+ int actual;
+ if (pos.is_percent) {
+ actual = (pos.pos / 100.0) * screensize;
+ } else {
+ actual = pos.pos * scale;
+ }
+
+ if (actual < 0) {
+ actual = screensize + actual;
+ }
+
+ return actual;
+}
+
+static const char *effect_name(struct swaylock_effect *effect) {
+ switch (effect->tag) {
+ case EFFECT_BLUR: return "blur";
+ case EFFECT_PIXELATE: return "pixelate";
+ case EFFECT_SCALE: return "scale";
+ case EFFECT_GREYSCALE: return "greyscale";
+ case EFFECT_VIGNETTE: return "vignette";
+ case EFFECT_COMPOSE: return "compose";
+ case EFFECT_CUSTOM: return effect->e.custom;
+ }
+
+ abort();
+}
+
+static void screen_pos_pair_to_pix(
+ struct swaylock_effect_screen_pos posx,
+ struct swaylock_effect_screen_pos posy,
+ int objwidth, int objheight,
+ int screenwidth, int screenheight, int scale, int gravity,
+ int *outx, int *outy) {
+ int x = screen_pos_to_pix(posx, screenwidth, scale);
+ int y = screen_pos_to_pix(posy, screenheight, scale);
+
+ // Adjust X
+ switch (gravity) {
+ case EFFECT_COMPOSE_GRAV_CENTER:
+ case EFFECT_COMPOSE_GRAV_N:
+ case EFFECT_COMPOSE_GRAV_S:
+ x -= objwidth / 2;
+ break;
+ case EFFECT_COMPOSE_GRAV_NW:
+ case EFFECT_COMPOSE_GRAV_SW:
+ case EFFECT_COMPOSE_GRAV_W:
+ break;
+ case EFFECT_COMPOSE_GRAV_NE:
+ case EFFECT_COMPOSE_GRAV_SE:
+ case EFFECT_COMPOSE_GRAV_E:
+ x -= objwidth;
+ break;
+ }
+
+ // Adjust Y
+ switch (gravity) {
+ case EFFECT_COMPOSE_GRAV_CENTER:
+ case EFFECT_COMPOSE_GRAV_W:
+ case EFFECT_COMPOSE_GRAV_E:
+ y -= objheight / 2;
+ break;
+ case EFFECT_COMPOSE_GRAV_NW:
+ case EFFECT_COMPOSE_GRAV_NE:
+ case EFFECT_COMPOSE_GRAV_N:
+ break;
+ case EFFECT_COMPOSE_GRAV_SW:
+ case EFFECT_COMPOSE_GRAV_SE:
+ case EFFECT_COMPOSE_GRAV_S:
+ y -= objheight;
+ break;
+ }
+
+ *outx = x;
+ *outy = y;
+}
+
+static uint32_t blend_pixels(float alpha, uint32_t srcpix, uint32_t destpix) {
+ uint8_t srcr = (srcpix & 0x00ff0000) >> 16;
+ uint8_t destr = (destpix & 0x00ff0000) >> 16;
+ uint8_t srcg = (srcpix & 0x0000ff00) >> 8;
+ uint8_t destg = (destpix & 0x0000ff00) >> 8;
+ uint8_t srcb = (srcpix & 0x000000ff) >> 0;
+ uint8_t destb = (destpix & 0x000000ff) >> 0;
+
+ return (uint32_t)0 |
+ (uint32_t)255 << 24 |
+ (uint32_t)(srcr + destr * (1 - alpha)) << 16 |
+ (uint32_t)(srcg + destg * (1 - alpha)) << 8 |
+ (uint32_t)(srcb + destb * (1 - alpha)) << 0;
+}
+
+static void blur_h(uint32_t *dest, uint32_t *src, int width, int height,
+ int radius) {
+ const int minradius = radius < width ? radius : width;
+
+#pragma omp parallel for
+ for (int y = 0; y < height; ++y) {
+ uint32_t *srow = src + y * width;
+ uint32_t *drow = dest + y * width;
+
+ // 'range' is float, because floating point division is usually faster
+ // than integer division.
+ int r_acc = 0;
+ int g_acc = 0;
+ int b_acc = 0;
+ float range = minradius;
+
+ // Accumulate the range (0..radius)
+ for (int x = 0; x < minradius; ++x) {
+ r_acc += (srow[x] & 0xff0000) >> 16;
+ g_acc += (srow[x] & 0x00ff00) >> 8;
+ b_acc += (srow[x] & 0x0000ff);
+ }
+
+ // Deal with the main body
+ for (int x = 0; x < width; ++x) {
+ if (x >= minradius) {
+ r_acc -= (srow[x - radius] & 0xff0000) >> 16;
+ g_acc -= (srow[x - radius] & 0x00ff00) >> 8;
+ b_acc -= (srow[x - radius] & 0x0000ff);
+ range -= 1;
+ }
+
+ if (x < width - minradius) {
+ r_acc += (srow[x + radius] & 0xff0000) >> 16;
+ g_acc += (srow[x + radius] & 0x00ff00) >> 8;
+ b_acc += (srow[x + radius] & 0x0000ff);
+ range += 1;
+ }
+
+ drow[x] = 0 |
+ (int)(r_acc / range) << 16 |
+ (int)(g_acc / range) << 8 |
+ (int)(b_acc / range);
+ }
+ }
+}
+
+static void blur_v(uint32_t *dest, uint32_t *src, int width, int height,
+ int radius) {
+ const int minradius = radius < height ? radius : height;
+
+#pragma omp parallel for
+ for (int x = 0; x < width; ++x) {
+ uint32_t *scol = src + x;
+ uint32_t *dcol = dest + x;
+
+ // 'range' is float, because floating point division is usually faster
+ // than integer division.
+ int r_acc = 0;
+ int g_acc = 0;
+ int b_acc = 0;
+ float range = minradius;
+
+ // Accumulate the range (0..radius)
+ for (int y = 0; y < minradius; ++y) {
+ r_acc += (scol[y * width] & 0xff0000) >> 16;
+ g_acc += (scol[y * width] & 0x00ff00) >> 8;
+ b_acc += (scol[y * width] & 0x0000ff);
+ }
+
+ // Deal with the main body
+ for (int y = 0; y < height; ++y) {
+ if (y >= minradius) {
+ r_acc -= (scol[(y - radius) * width] & 0xff0000) >> 16;
+ g_acc -= (scol[(y - radius) * width] & 0x00ff00) >> 8;
+ b_acc -= (scol[(y - radius) * width] & 0x0000ff);
+ range -= 1;
+ }
+
+ if (y < height - minradius) {
+ r_acc += (scol[(y + radius) * width] & 0xff0000) >> 16;
+ g_acc += (scol[(y + radius) * width] & 0x00ff00) >> 8;
+ b_acc += (scol[(y + radius) * width] & 0x0000ff);
+ range += 1;
+ }
+
+ dcol[y * width] = 0 |
+ (int)(r_acc / range) << 16 |
+ (int)(g_acc / range) << 8 |
+ (int)(b_acc / range);
+ }
+ }
+}
+
+static void blur_once(uint32_t *dest, uint32_t *src, uint32_t *scratch,
+ int width, int height, int radius) {
+ blur_h(scratch, src, width, height, radius);
+ blur_v(dest, scratch, width, height, radius);
+}
+
+// This effect_blur function, and the associated blur_* functions,
+// are my own adaptations of code in yvbbrjdr's i3lock-fancy-rapid:
+// https://github.com/yvbbrjdr/i3lock-fancy-rapid
+static void effect_blur(uint32_t *dest, uint32_t *src, int width, int height, int scale,
+ int radius, int times) {
+ uint32_t *origdest = dest;
+
+ uint32_t *scratch = malloc(width * height * sizeof(*scratch));
+ blur_once(dest, src, scratch, width, height, radius * scale);
+ for (int i = 0; i < times - 1; ++i) {
+ uint32_t *tmp = src;
+ src = dest;
+ dest = tmp;
+ blur_once(dest, src, scratch, width, height, radius * scale);
+ }
+ free(scratch);
+
+ // We're flipping between using dest and src;
+ // if the last buffer we used was src, copy that over to dest.
+ if (dest != origdest)
+ memcpy(origdest, dest, width * height * sizeof(*dest));
+}
+
+static void effect_pixelate(uint32_t *data, int width, int height, int scale, int factor) {
+ factor *= scale;
+#pragma omp parallel for
+ for (int y = 0; y < height / factor + 1; ++y) {
+ for (int x = 0; x < width / factor + 1; ++x) {
+ int total_r = 0, total_g = 0, total_b = 0;
+
+ int xstart = x * factor;
+ int ystart = y * factor;
+ int xlim = MIN(xstart + factor, width);
+ int ylim = MIN(ystart + factor, height);
+
+ // Average
+ for (int ry = ystart; ry < ylim; ++ry) {
+ for (int rx = xstart; rx < xlim; ++rx) {
+ int index = ry * width + rx;
+ total_r += (data[index] & 0xff0000) >> 16;
+ total_g += (data[index] & 0x00ff00) >> 8;
+ total_b += (data[index] & 0x0000ff);
+ }
+ }
+
+ int r = total_r / (factor * factor);
+ int g = total_g / (factor * factor);
+ int b = total_b / (factor * factor);
+
+ // Fill pixels
+ for (int ry = ystart; ry < ylim; ++ry) {
+ for (int rx = xstart; rx < xlim; ++rx) {
+ int index = ry * width + rx;
+ data[index] = r << 16 | g << 8 | b;
+ }
+ }
+ }
+ }
+}
+
+static void effect_scale(uint32_t *dest, uint32_t *src, int swidth, int sheight,
+ double scale) {
+ int dwidth = swidth * scale;
+ int dheight = sheight * scale;
+ double fact = 1.0 / scale;
+
+#pragma omp parallel for
+ for (int dy = 0; dy < dheight; ++dy) {
+ int sy = dy * fact;
+ if (sy >= sheight) continue;
+ for (int dx = 0; dx < dwidth; ++dx) {
+ int sx = dx * fact;
+ if (sx >= swidth) continue;
+ dest[dy * dwidth + dx] = src[sy * swidth + sx];
+ }
+ }
+}
+
+static void effect_greyscale(uint32_t *data, int width, int height) {
+#pragma omp parallel for
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+ int index = y * width + x;
+ int r = (data[index] & 0xff0000) >> 16;
+ int g = (data[index] & 0x00ff00) >> 8;
+ int b = (data[index] & 0x0000ff);
+ int luma = 0.2989 * r + 0.5870 * g + 0.1140 * b;
+ if (luma < 0) luma = 0;
+ if (luma > 255) luma = 255;
+ luma &= 0xFF;
+ data[index] = luma << 16 | luma << 8 | luma;
+ }
+ }
+}
+
+static void effect_vignette(uint32_t *data, int width, int height,
+ double base, double factor) {
+ base = fmin(1, fmax(0, base));
+ factor = fmin(1 - base, fmax(0, factor));
+#pragma omp parallel for
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+
+ double xf = (x * 1.0) / width;
+ double yf = (y * 1.0) / height;
+ double vignette_factor = base + factor
+ * 16 * xf * yf * (1.0 - xf) * (1.0 - yf);
+
+ int index = y * width + x;
+ int r = (data[index] & 0xff0000) >> 16;
+ int g = (data[index] & 0x00ff00) >> 8;
+ int b = (data[index] & 0x0000ff);
+
+ r = (int)(r * vignette_factor) & 0xFF;
+ g = (int)(g * vignette_factor) & 0xFF;
+ b = (int)(b * vignette_factor) & 0xFF;
+
+ data[index] = r << 16 | g << 8 | b;
+ }
+ }
+}
+
+static void effect_compose(uint32_t *data, int width, int height, int scale,
+ struct swaylock_effect_screen_pos posx,
+ struct swaylock_effect_screen_pos posy,
+ struct swaylock_effect_screen_pos posw,
+ struct swaylock_effect_screen_pos posh,
+ int gravity, char *imgpath) {
+#if !HAVE_GDK_PIXBUF
+ (void)&blend_pixels;
+ (void)&screen_size_to_pix;
+ (void)&screen_pos_pair_to_pix;
+ swaylock_log(LOG_ERROR, "Compose effect: Compiled without gdk_pixbuf support.\n");
+ return;
+#else
+ int imgw = screen_size_to_pix(posw, width, scale);
+ int imgh = screen_size_to_pix(posh, height, scale);
+ bool preserve_aspect = imgw < 0 || imgh < 0;
+
+ GError *err = NULL;
+ GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file_at_scale(
+ imgpath, imgw, imgh, preserve_aspect, &err);
+ if (!pixbuf) {
+ swaylock_log(LOG_ERROR, "Compose effect: Failed to load image file '%s' (%s).",
+ imgpath, err->message);
+ g_error_free(err);
+ return;
+ }
+
+ cairo_surface_t *image = gdk_cairo_image_surface_create_from_pixbuf(pixbuf);
+ g_object_unref(pixbuf);
+
+ int bufw = cairo_image_surface_get_width(image);
+ int bufh = cairo_image_surface_get_height(image);
+ uint32_t *bufdata = (uint32_t *)cairo_image_surface_get_data(image);
+ int bufstride = cairo_image_surface_get_stride(image) / 4;
+ bool bufalpha = cairo_image_surface_get_format(image) == CAIRO_FORMAT_ARGB32;
+
+ int imgx, imgy;
+ screen_pos_pair_to_pix(
+ posx, posy, bufw, bufh,
+ width, height, scale, gravity,
+ &imgx, &imgy);
+
+#pragma omp parallel for
+ for (int offy = 0; offy < bufh; ++offy) {
+ if (offy + imgy < 0 || offy + imgy > height)
+ continue;
+
+ for (int offx = 0; offx < bufw; ++offx) {
+ if (offx + imgx < 0 || offx + imgx > width)
+ continue;
+
+ size_t idx = (size_t)(offy + imgy) * width + (offx + imgx);
+ size_t bufidx = (size_t)offy * bufstride + (offx);
+
+ if (!bufalpha) {
+ data[idx] = bufdata[bufidx];
+ } else {
+ uint8_t alpha = (bufdata[bufidx] & 0xff000000) >> 24;
+ if (alpha == 255) {
+ data[idx] = bufdata[bufidx];
+ } else if (alpha != 0) {
+ data[idx] = blend_pixels(alpha / 255.0, bufdata[bufidx], data[idx]);
+ }
+ }
+ }
+ }
+
+ cairo_surface_destroy(image);
+#endif
+}
+
+static void effect_custom_run(uint32_t *data, int width, int height, int scale,
+ char *path) {
+ void *dl = dlopen(path, RTLD_LAZY);
+ if (dl == NULL) {
+ swaylock_log(LOG_ERROR, "Custom effect: %s", dlerror());
+ return;
+ }
+
+ void (*effect_func)(uint32_t *data, int width, int height, int scale) =
+ dlsym(dl, "swaylock_effect");
+ if (effect_func != NULL) {
+ effect_func(data, width, height, scale);
+ dlclose(dl);
+ return;
+ }
+
+ uint32_t (*pixel_func)(uint32_t pix, int x, int y, int width, int height) =
+ dlsym(dl, "swaylock_pixel");
+ if (pixel_func != NULL) {
+#pragma omp parallel for
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+ data[y * width + x] =
+ pixel_func(data[y * width + x], x, y, width, height);
+ }
+ }
+
+ dlclose(dl);
+ return;
+ }
+
+ (void)dlsym(dl, "swaylock_effect"); // Change the result of dlerror()
+ swaylock_log(LOG_ERROR, "Custom effect: %s", dlerror());
+}
+
+static bool file_is_outdated(const char *input, const char *output) {
+ struct stat instat, outstat;
+ if (stat(input, &instat) < 0) {
+ return true;
+ }
+
+ if (stat(output, &outstat) < 0) {
+ return true;
+ }
+
+ if (instat.st_mtim.tv_sec > outstat.st_mtim.tv_sec) {
+ return true;
+ }
+
+ if (
+ instat.st_mtim.tv_sec == outstat.st_mtim.tv_sec &&
+ instat.st_mtim.tv_nsec >= outstat.st_mtim.tv_nsec) {
+ return true;
+ }
+
+ return false;
+}
+
+static char *effect_custom_compile(const char *path) {
+ static char *cachepath = NULL;
+ static size_t cachelen;
+ if (!cachepath) {
+ char *xdgdir = getenv("XDG_DATA_HOME");
+ if (xdgdir) {
+ cachepath = malloc(strlen(xdgdir) + strlen("/swaylock") + 1);
+ cachelen = sprintf(cachepath, "%s/swaylock", xdgdir);
+ } else {
+ char *homedir = getenv("HOME");
+ if (homedir == NULL) {
+ swaylock_log(LOG_ERROR,
+ "Can't compile custom effect; neither $HOME nor $XDG_CONFIG_HOME "
+ "is defined.");
+ return NULL;
+ }
+
+ cachepath = malloc(strlen(homedir) + strlen("/.cache/swaylock") + 1);
+ cachelen = sprintf(cachepath, "%s/.cache/swaylock", homedir);
+ }
+
+ if (mkdir(cachepath, 0777) < 0 && errno != EEXIST) {
+ swaylock_log(LOG_ERROR,
+ "Can't compile custom effect; mkdir %s failed: %s\n",
+ cachepath, strerror(errno));
+ free(cachepath);
+ cachepath = NULL;
+ return NULL;
+ }
+ }
+
+ // Find the true, absolute path of the input file
+ char *abspath = realpath(path, NULL);
+ size_t abspathlen = strlen(abspath);
+
+ char *outpath = malloc(cachelen + 1 + abspathlen + 3 + 1);
+ size_t outlen = sprintf(outpath, "%s/%s.so", cachepath, abspath);
+
+ // Sanitize
+ for (char *ch = outpath + cachelen + 1; ch < outpath + cachelen + 1 + abspathlen; ++ch) {
+ if (!(
+ (*ch >= 'a' && *ch <= 'z') ||
+ (*ch >= 'A' && *ch <= 'Z') ||
+ (*ch >= '0' && *ch <= '9') ||
+ (*ch == '.'))) {
+ *ch = '_';
+ }
+ }
+
+ if (!file_is_outdated(path, outpath)) {
+ free(abspath);
+ return outpath;
+ }
+
+ static const char *fmt = "cc -shared -g -O2 -march=native -fopenmp -o '%s' '%s' -lm";
+ char *cmd = malloc(strlen(fmt) + outlen - 2 + abspathlen - 2 + 1);
+ sprintf(cmd, fmt, outpath, abspath);
+ free(abspath);
+ fprintf(stderr, "Compiling custom effect: %s\n", cmd);
+
+ // Finally, compile.
+ int ret = system(cmd);
+ free(cmd);
+ if (ret != 0) {
+ if (ret == -1) {
+ swaylock_log(LOG_ERROR, "Custom effect: system(): %s", strerror(errno));
+ free(outpath);
+ return NULL;
+ } else {
+ swaylock_log(LOG_ERROR, "Custom effect compilation failed\n");
+ free(outpath);
+ return NULL;
+ }
+ }
+
+ return outpath;
+}
+
+static void effect_custom(uint32_t *data, int width, int height, int scale,
+ char *path) {
+ size_t pathlen = strlen(path);
+ if (pathlen > 3 && strcmp(path + pathlen - 3, ".so") == 0) {
+ effect_custom_run(data, width, height, scale, path);
+ } else if (pathlen > 2 && strcmp(path + pathlen - 2, ".c") == 0) {
+ char *compiled = effect_custom_compile(path);
+ if (compiled != NULL) {
+ effect_custom_run(data, width, height, scale, compiled);
+ free(compiled);
+ }
+ } else {
+ swaylock_log(
+ LOG_ERROR, "%s: Unknown file type for custom effect (expected .c or .so)",
+ path);
+ }
+}
+
+static cairo_surface_t *run_effect(cairo_surface_t *surface, int scale,
+ struct swaylock_effect *effect) {
+ switch (effect->tag) {
+ case EFFECT_BLUR: {
+ cairo_surface_t *surf = cairo_image_surface_create(
+ CAIRO_FORMAT_RGB24,
+ cairo_image_surface_get_width(surface),
+ cairo_image_surface_get_height(surface));
+
+ if (cairo_surface_status(surf) != CAIRO_STATUS_SUCCESS) {
+ swaylock_log(LOG_ERROR, "Failed to create surface for blur effect");
+ cairo_surface_destroy(surf);
+ break;
+ }
+
+ effect_blur(
+ (uint32_t *)cairo_image_surface_get_data(surf),
+ (uint32_t *)cairo_image_surface_get_data(surface),
+ cairo_image_surface_get_width(surface),
+ cairo_image_surface_get_height(surface),
+ scale,
+ effect->e.blur.radius, effect->e.blur.times);
+ cairo_surface_flush(surf);
+ cairo_surface_destroy(surface);
+ surface = surf;
+ break;
+ }
+
+ case EFFECT_PIXELATE: {
+ effect_pixelate(
+ (uint32_t *)cairo_image_surface_get_data(surface),
+ cairo_image_surface_get_width(surface),
+ cairo_image_surface_get_height(surface),
+ scale,
+ effect->e.pixelate.factor);
+ cairo_surface_flush(surface);
+ break;
+ }
+
+ case EFFECT_SCALE: {
+ cairo_surface_t *surf = cairo_image_surface_create(
+ CAIRO_FORMAT_RGB24,
+ cairo_image_surface_get_width(surface) * effect->e.scale,
+ cairo_image_surface_get_height(surface) * effect->e.scale);
+
+ if (cairo_surface_status(surf) != CAIRO_STATUS_SUCCESS) {
+ swaylock_log(LOG_ERROR, "Failed to create surface for scale effect");
+ cairo_surface_destroy(surf);
+ break;
+ }
+
+ effect_scale(
+ (uint32_t *)cairo_image_surface_get_data(surf),
+ (uint32_t *)cairo_image_surface_get_data(surface),
+ cairo_image_surface_get_width(surface),
+ cairo_image_surface_get_height(surface),
+ effect->e.scale);
+ cairo_surface_flush(surf);
+ cairo_surface_destroy(surface);
+ surface = surf;
+ break;
+ }
+
+ case EFFECT_GREYSCALE: {
+ effect_greyscale(
+ (uint32_t *)cairo_image_surface_get_data(surface),
+ cairo_image_surface_get_width(surface),
+ cairo_image_surface_get_height(surface));
+ cairo_surface_flush(surface);
+ break;
+ }
+
+ case EFFECT_VIGNETTE: {
+ effect_vignette(
+ (uint32_t *)cairo_image_surface_get_data(surface),
+ cairo_image_surface_get_width(surface),
+ cairo_image_surface_get_height(surface),
+ effect->e.vignette.base,
+ effect->e.vignette.factor);
+ cairo_surface_flush(surface);
+ break;
+ }
+
+ case EFFECT_COMPOSE: {
+ effect_compose(
+ (uint32_t *)cairo_image_surface_get_data(surface),
+ cairo_image_surface_get_width(surface),
+ cairo_image_surface_get_height(surface),
+ scale,
+ effect->e.compose.x, effect->e.compose.y,
+ effect->e.compose.w, effect->e.compose.h,
+ effect->e.compose.gravity, effect->e.compose.imgpath);
+ cairo_surface_flush(surface);
+ break;
+ }
+
+ case EFFECT_CUSTOM: {
+ effect_custom(
+ (uint32_t *)cairo_image_surface_get_data(surface),
+ cairo_image_surface_get_width(surface),
+ cairo_image_surface_get_height(surface),
+ scale,
+ effect->e.custom);
+ cairo_surface_flush(surface);
+ break;
+ } }
+
+ return surface;
+}
+
+static cairo_surface_t *ensure_format(cairo_surface_t *surface) {
+ if (cairo_image_surface_get_format(surface) == CAIRO_FORMAT_RGB24) {
+ return surface;
+ }
+
+ swaylock_log(LOG_DEBUG, "Have to convert surface to CAIRO_FORMAT_RGB24 from %i.",
+ (int)cairo_image_surface_get_format(surface));
+
+ cairo_surface_t *surf = cairo_image_surface_create(
+ CAIRO_FORMAT_RGB24,
+ cairo_image_surface_get_width(surface),
+ cairo_image_surface_get_height(surface));
+ if (cairo_surface_status(surf) != CAIRO_STATUS_SUCCESS) {
+ swaylock_log(LOG_ERROR, "Failed to create surface for scale effect");
+ cairo_surface_destroy(surf);
+ return NULL;
+ }
+
+ memcpy(
+ cairo_image_surface_get_data(surf),
+ cairo_image_surface_get_data(surface),
+ cairo_image_surface_get_stride(surface) * cairo_image_surface_get_height(surface));
+ cairo_surface_destroy(surface);
+ return surf;
+}
+
+cairo_surface_t *swaylock_effects_run(cairo_surface_t *surface, int scale,
+ struct swaylock_effect *effects, int count) {
+ surface = ensure_format(surface);
+ if (surface == NULL) return NULL;
+
+ for (int i = 0; i < count; ++i) {
+ struct swaylock_effect *effect = &effects[i];
+ surface = run_effect(surface, scale, effect);
+ }
+
+ return surface;
+}
+
+#define TIME_MSEC(tv) ((tv).tv_sec * 1000.0 + (tv).tv_nsec / 1000000.0)
+#define TIME_DELTA(first, last) (TIME_MSEC(last) - TIME_MSEC(first))
+
+cairo_surface_t *swaylock_effects_run_timed(cairo_surface_t *surface, int scale,
+ struct swaylock_effect *effects, int count) {
+ struct timespec start_tv;
+ clock_gettime(CLOCK_MONOTONIC, &start_tv);
+
+ surface = ensure_format(surface);
+ if (surface == NULL) return NULL;
+
+ fprintf(stderr, "Running %i effects:\n", count);
+ for (int i = 0; i < count; ++i) {
+ struct timespec effect_start_tv;
+ clock_gettime(CLOCK_MONOTONIC, &effect_start_tv);
+
+ struct swaylock_effect *effect = &effects[i];
+ surface = run_effect(surface, scale, effect);
+
+ struct timespec effect_end_tv;
+ clock_gettime(CLOCK_MONOTONIC, &effect_end_tv);
+ fprintf(stderr, " %s: %fms\n", effect_name(effect),
+ TIME_DELTA(effect_start_tv, effect_end_tv));
+ }
+
+ struct timespec end_tv;
+ clock_gettime(CLOCK_MONOTONIC, &end_tv);
+ fprintf(stderr, "Effects took %fms.\n", TIME_DELTA(start_tv, end_tv));
+
+ return surface;
+}
swaylock-mod/fade.c
@@ -0,0 +1,26 @@
+#include "fade.h"
+#include "swaylock.h"
+#include <stdlib.h>
+
+void fade_update(struct swaylock_fade *fade, uint32_t time) {
+ if (fade->current_time >= fade->target_time) {
+ return;
+ }
+
+ double delta = 0;
+ if (fade->old_time != 0) {
+ delta = time - fade->old_time;
+ }
+ fade->old_time = time;
+
+ fade->current_time += delta;
+ if (fade->current_time > fade->target_time) {
+ fade->current_time = fade->target_time;
+ }
+
+ fade->alpha = (double)fade->current_time / (double)fade->target_time;
+}
+
+bool fade_is_complete(struct swaylock_fade *fade) {
+ return fade->target_time == 0 || fade->current_time >= fade->target_time;
+}
swaylock-mod/log.c
@@ -0,0 +1,80 @@
+#define _POSIX_C_SOURCE 199506L
+#include <errno.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+#include "log.h"
+
+static enum log_importance log_importance = LOG_ERROR;
+
+static const char *verbosity_colors[] = {
+ [LOG_SILENT] = "",
+ [LOG_ERROR ] = "\x1B[1;31m",
+ [LOG_INFO ] = "\x1B[1;34m",
+ [LOG_DEBUG ] = "\x1B[1;30m",
+ [LOG_TRACE ] = "\x1B[1;32m",
+};
+
+void swaylock_log_init(enum log_importance verbosity) {
+ if (verbosity < LOG_IMPORTANCE_LAST) {
+ log_importance = verbosity;
+ }
+}
+
+void _swaylock_log(enum log_importance verbosity, const char *fmt, ...) {
+ if (verbosity > log_importance) {
+ return;
+ }
+
+ va_list args;
+ va_start(args, fmt);
+
+ // prefix the time to the log message
+ struct tm result;
+ time_t t = time(NULL);
+ struct tm *tm_info = localtime_r(&t, &result);
+ char buffer[26];
+
+ // generate time prefix
+ strftime(buffer, sizeof(buffer), "%F %T - ", tm_info);
+ fprintf(stderr, "%s", buffer);
+
+ unsigned c = (verbosity < LOG_IMPORTANCE_LAST)
+ ? verbosity : LOG_IMPORTANCE_LAST - 1;
+
+ if (isatty(STDERR_FILENO)) {
+ fprintf(stderr, "%s", verbosity_colors[c]);
+ }
+
+ vfprintf(stderr, fmt, args);
+
+ if (isatty(STDERR_FILENO)) {
+ fprintf(stderr, "\x1B[0m");
+ }
+ fprintf(stderr, "\n");
+
+ va_end(args);
+}
+
+// This is mainly here for performance.
+// Don't want to do _swaylock_strip_path every event if we're not tracing.
+void _swaylock_trace(const char *file, int line, const char *func) {
+ if (LOG_TRACE > log_importance) {
+ return;
+ }
+
+ _swaylock_log(LOG_TRACE, "[%s:%d]: trace: %s",
+ _swaylock_strip_path(file), line, func);
+}
+
+const char *_swaylock_strip_path(const char *filepath) {
+ if (*filepath == '.') {
+ while (*filepath == '.' || *filepath == '/') {
+ ++filepath;
+ }
+ }
+ return filepath;
+ }
swaylock-mod/loop.c
@@ -0,0 +1,204 @@
+#define _POSIX_C_SOURCE 200809L
+#include <limits.h>
+#include <string.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <poll.h>
+#include <time.h>
+#include <unistd.h>
+#include <wayland-client.h>
+#include "log.h"
+#include "loop.h"
+
+struct loop_fd_event {
+ void (*callback)(int fd, short mask, void *data);
+ void *data;
+ struct wl_list link; // struct loop_fd_event::link
+};
+
+struct loop_timer {
+ void (*callback)(void *data);
+ void *data;
+ struct timespec expiry;
+ bool removed;
+ struct wl_list link; // struct loop_timer::link
+};
+
+struct loop {
+ struct pollfd *fds;
+ int fd_length;
+ int fd_capacity;
+
+ struct wl_list fd_events; // struct loop_fd_event::link
+ struct wl_list timers; // struct loop_timer::link
+};
+
+struct loop *loop_create(void) {
+ struct loop *loop = calloc(1, sizeof(struct loop));
+ if (!loop) {
+ swaylock_log(LOG_ERROR, "Unable to allocate memory for loop");
+ return NULL;
+ }
+ loop->fd_capacity = 10;
+ loop->fds = malloc(sizeof(struct pollfd) * loop->fd_capacity);
+ wl_list_init(&loop->fd_events);
+ wl_list_init(&loop->timers);
+ return loop;
+}
+
+void loop_destroy(struct loop *loop) {
+ struct loop_fd_event *event = NULL, *tmp_event = NULL;
+ wl_list_for_each_safe(event, tmp_event, &loop->fd_events, link) {
+ wl_list_remove(&event->link);
+ free(event);
+ }
+ struct loop_timer *timer = NULL, *tmp_timer = NULL;
+ wl_list_for_each_safe(timer, tmp_timer, &loop->timers, link) {
+ wl_list_remove(&timer->link);
+ free(timer);
+ }
+ free(loop->fds);
+ free(loop);
+}
+
+void loop_poll(struct loop *loop) {
+ // Calculate next timer in ms
+ int ms = INT_MAX;
+ if (!wl_list_empty(&loop->timers)) {
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ struct loop_timer *timer = NULL;
+ wl_list_for_each(timer, &loop->timers, link) {
+ int timer_ms = (timer->expiry.tv_sec - now.tv_sec) * 1000;
+ timer_ms += (timer->expiry.tv_nsec - now.tv_nsec) / 1000000;
+ if (timer_ms < ms) {
+ ms = timer_ms;
+ }
+ }
+ }
+ if (ms < 0) {
+ ms = 0;
+ }
+
+ int ret = poll(loop->fds, loop->fd_length, ms);
+ if (ret < 0 && errno != EINTR) {
+ swaylock_log_errno(LOG_ERROR, "poll failed");
+ exit(1);
+ }
+
+ // Dispatch fds
+ size_t fd_index = 0;
+ struct loop_fd_event *event = NULL;
+ wl_list_for_each(event, &loop->fd_events, link) {
+ struct pollfd pfd = loop->fds[fd_index];
+
+ // Always send these events
+ unsigned events = pfd.events | POLLHUP | POLLERR;
+
+ if (pfd.revents & events) {
+ event->callback(pfd.fd, pfd.revents, event->data);
+ }
+
+ ++fd_index;
+ }
+
+ // Dispatch timers
+ if (!wl_list_empty(&loop->timers)) {
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ struct loop_timer *timer = NULL, *tmp_timer = NULL;
+ wl_list_for_each_safe(timer, tmp_timer, &loop->timers, link) {
+ if (timer->removed) {
+ wl_list_remove(&timer->link);
+ free(timer);
+ continue;
+ }
+
+ bool expired = timer->expiry.tv_sec < now.tv_sec ||
+ (timer->expiry.tv_sec == now.tv_sec &&
+ timer->expiry.tv_nsec < now.tv_nsec);
+ if (expired) {
+ timer->callback(timer->data);
+ wl_list_remove(&timer->link);
+ free(timer);
+ }
+ }
+ }
+}
+
+void loop_add_fd(struct loop *loop, int fd, short mask,
+ void (*callback)(int fd, short mask, void *data), void *data) {
+ struct loop_fd_event *event = calloc(1, sizeof(struct loop_fd_event));
+ if (!event) {
+ swaylock_log(LOG_ERROR, "Unable to allocate memory for event");
+ return;
+ }
+ event->callback = callback;
+ event->data = data;
+ wl_list_insert(loop->fd_events.prev, &event->link);
+
+ struct pollfd pfd = {fd, mask, 0};
+
+ if (loop->fd_length == loop->fd_capacity) {
+ loop->fd_capacity += 10;
+ loop->fds = realloc(loop->fds,
+ sizeof(struct pollfd) * loop->fd_capacity);
+ }
+
+ loop->fds[loop->fd_length++] = pfd;
+}
+
+struct loop_timer *loop_add_timer(struct loop *loop, int ms,
+ void (*callback)(void *data), void *data) {
+ struct loop_timer *timer = calloc(1, sizeof(struct loop_timer));
+ if (!timer) {
+ swaylock_log(LOG_ERROR, "Unable to allocate memory for timer");
+ return NULL;
+ }
+ timer->callback = callback;
+ timer->data = data;
+
+ clock_gettime(CLOCK_MONOTONIC, &timer->expiry);
+ timer->expiry.tv_sec += ms / 1000;
+
+ long int nsec = (ms % 1000) * 1000000;
+ if (timer->expiry.tv_nsec + nsec >= 1000000000) {
+ timer->expiry.tv_sec++;
+ nsec -= 1000000000;
+ }
+ timer->expiry.tv_nsec += nsec;
+
+ wl_list_insert(&loop->timers, &timer->link);
+
+ return timer;
+}
+
+bool loop_remove_fd(struct loop *loop, int fd) {
+ size_t fd_index = 0;
+ struct loop_fd_event *event = NULL, *tmp_event = NULL;
+ wl_list_for_each_safe(event, tmp_event, &loop->fd_events, link) {
+ if (loop->fds[fd_index].fd == fd) {
+ wl_list_remove(&event->link);
+ free(event);
+
+ loop->fd_length--;
+ memmove(&loop->fds[fd_index], &loop->fds[fd_index + 1],
+ sizeof(struct pollfd) * (loop->fd_length - fd_index));
+ return true;
+ }
+ ++fd_index;
+ }
+ return false;
+}
+
+bool loop_remove_timer(struct loop *loop, struct loop_timer *remove) {
+ struct loop_timer *timer = NULL, *tmp_timer = NULL;
+ wl_list_for_each_safe(timer, tmp_timer, &loop->timers, link) {
+ if (timer == remove) {
+ timer->removed = true;
+ return true;
+ }
+ }
+ return false;
+}
swaylock-mod/main.c
@@ -0,0 +1,2050 @@
+#define _POSIX_C_SOURCE 200809L
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <poll.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+#include <wayland-client.h>
+#include <wordexp.h>
+#include "background-image.h"
+#include "cairo.h"
+#include "comm.h"
+#include "log.h"
+#include "loop.h"
+#include "password-buffer.h"
+#include "pool-buffer.h"
+#include "seat.h"
+#include "swaylock.h"
+#include "wlr-input-inhibitor-unstable-v1-client-protocol.h"
+#include "wlr-layer-shell-unstable-v1-client-protocol.h"
+#include "wlr-screencopy-unstable-v1-client-protocol.h"
+#include "ext-session-lock-v1-client-protocol.h"
+
+// returns a positive integer in milliseconds
+static uint32_t parse_seconds(const char *seconds) {
+ char *endptr;
+ errno = 0;
+ float val = strtof(seconds, &endptr);
+ if (errno != 0) {
+ swaylock_log(LOG_DEBUG, "Invalid number for seconds %s, defaulting to 0", seconds);
+ return 0;
+ }
+ if (endptr == seconds) {
+ swaylock_log(LOG_DEBUG, "No digits were found in %s, defaulting to 0", seconds);
+ return 0;
+ }
+ if (val < 0) {
+ swaylock_log(LOG_DEBUG, "Negative seconds not allowed for %s, defaulting to 0", seconds);
+ return 0;
+ }
+
+ return (uint32_t)floor(val * 1000);
+}
+
+static uint32_t parse_color(const char *color) {
+ if (color[0] == '#') {
+ ++color;
+ }
+
+ int len = strlen(color);
+ if (len != 6 && len != 8) {
+ swaylock_log(LOG_DEBUG, "Invalid color %s, defaulting to 0xFFFFFFFF",
+ color);
+ return 0xFFFFFFFF;
+ }
+ uint32_t res = (uint32_t)strtoul(color, NULL, 16);
+ if (strlen(color) == 6) {
+ res = (res << 8) | 0xFF;
+ }
+ return res;
+}
+
+static const char *parse_screen_pos(const char *str, struct swaylock_effect_screen_pos *pos) {
+ char *eptr;
+ float res = strtof(str, &eptr);
+ if (eptr == str)
+ return NULL;
+
+ pos->pos = res;
+ if (eptr[0] == '%') {
+ pos->is_percent = true;
+ return eptr + 1;
+ } else {
+ pos->is_percent = false;
+ return eptr;
+ }
+}
+
+static const char *parse_screen_pos_pair(const char *str, char delim,
+ struct swaylock_effect_screen_pos *pos1,
+ struct swaylock_effect_screen_pos *pos2) {
+ struct swaylock_effect_screen_pos tpos1, tpos2;
+ str = parse_screen_pos(str, &tpos1);
+ if (str == NULL || str[0] != delim)
+ return NULL;
+
+ str = parse_screen_pos(str + 1, &tpos2);
+ if (str == NULL)
+ return NULL;
+
+ pos1->pos = tpos1.pos;
+ pos1->is_percent = tpos1.is_percent;
+ pos2->pos = tpos2.pos;
+ pos2->is_percent = tpos2.is_percent;
+ return str;
+}
+
+static const char *parse_constant(const char *str1, const char *str2) {
+ size_t len = strlen(str2);
+ if (strncmp(str1, str2, len) == 0) {
+ return str1 + len;
+ } else {
+ return NULL;
+ }
+}
+
+static int parse_gravity_from_xy(float x, float y) {
+ if (x >= 0 && y >= 0)
+ return EFFECT_COMPOSE_GRAV_NW;
+ else if (x >= 0 && y < 0)
+ return EFFECT_COMPOSE_GRAV_SW;
+ else if (x < 0 && y >= 0)
+ return EFFECT_COMPOSE_GRAV_NE;
+ else
+ return EFFECT_COMPOSE_GRAV_SE;
+}
+
+static void parse_effect_compose(const char *str, struct swaylock_effect *effect) {
+ effect->e.compose.x = effect->e.compose.y = (struct swaylock_effect_screen_pos) { 50, 1 }; // 50%
+ effect->e.compose.w = effect->e.compose.h = (struct swaylock_effect_screen_pos) { -1, 0 }; // -1
+ effect->e.compose.gravity = EFFECT_COMPOSE_GRAV_CENTER;
+ effect->e.compose.imgpath = NULL;
+
+ // Parse position if they exist
+ const char *s = parse_screen_pos_pair(str, ',', &effect->e.compose.x, &effect->e.compose.y);
+ if (s == NULL) {
+ s = str;
+ } else {
+ // If we're given an x/y position, determine gravity automatically
+ // from whether x and y is positive or not
+ effect->e.compose.gravity = parse_gravity_from_xy(
+ effect->e.compose.x.pos, effect->e.compose.y.pos);
+ s += 1;
+ str = s;
+ }
+
+ // Parse dimensions if they exist
+ s = parse_screen_pos_pair(str, 'x', &effect->e.compose.w, &effect->e.compose.h);
+ if (s == NULL) {
+ s = str;
+ } else {
+ s += 1;
+ str = s;
+ }
+
+ // Parse gravity if it exists
+ if ((s = parse_constant(str, "center;")) != NULL)
+ effect->e.compose.gravity = EFFECT_COMPOSE_GRAV_CENTER;
+ else if ((s = parse_constant(str, "northwest;")) != NULL)
+ effect->e.compose.gravity = EFFECT_COMPOSE_GRAV_NW;
+ else if ((s = parse_constant(str, "northeast;")) != NULL)
+ effect->e.compose.gravity = EFFECT_COMPOSE_GRAV_NE;
+ else if ((s = parse_constant(str, "southwest;")) != NULL)
+ effect->e.compose.gravity = EFFECT_COMPOSE_GRAV_SW;
+ else if ((s = parse_constant(str, "southeast;")) != NULL)
+ effect->e.compose.gravity = EFFECT_COMPOSE_GRAV_SE;
+ else if ((s = parse_constant(str, "north;")) != NULL)
+ effect->e.compose.gravity = EFFECT_COMPOSE_GRAV_N;
+ else if ((s = parse_constant(str, "south;")) != NULL)
+ effect->e.compose.gravity = EFFECT_COMPOSE_GRAV_S;
+ else if ((s = parse_constant(str, "east;")) != NULL)
+ effect->e.compose.gravity = EFFECT_COMPOSE_GRAV_E;
+ else if ((s = parse_constant(str, "west;")) != NULL)
+ effect->e.compose.gravity = EFFECT_COMPOSE_GRAV_W;
+ if (s == NULL) {
+ s = str;
+ } else {
+ str = s;
+ }
+
+ // The rest is the file name
+ effect->e.compose.imgpath = strdup(str);
+}
+
+int lenient_strcmp(char *a, char *b) {
+ if (a == b) {
+ return 0;
+ } else if (!a) {
+ return -1;
+ } else if (!b) {
+ return 1;
+ } else {
+ return strcmp(a, b);
+ }
+}
+
+static int daemonize_start() {
+ swaylock_trace();
+ int fds[2];
+ if (pipe(fds) != 0) {
+ swaylock_log(LOG_ERROR, "Failed to pipe");
+ exit(1);
+ }
+ if (fork() == 0) {
+ setsid();
+ close(fds[0]);
+ int devnull = open("/dev/null", O_RDWR);
+ dup2(STDOUT_FILENO, devnull);
+ dup2(STDERR_FILENO, devnull);
+ close(devnull);
+ uint8_t success = 0;
+ if (chdir("/") != 0) {
+ write(fds[1], &success, 1);
+ exit(1);
+ }
+ return fds[1];
+ } else {
+ close(fds[1]);
+ uint8_t success;
+ if (read(fds[0], &success, 1) != 1 || !success) {
+ swaylock_log(LOG_ERROR, "Failed to daemonize");
+ exit(1);
+ }
+ close(fds[0]);
+ exit(0);
+ }
+}
+
+static void daemonize_done(void *fdptr) {
+ swaylock_trace();
+ int *fd = (int *)fdptr;
+ if (*fd < 0) {
+ return;
+ }
+
+ uint8_t success = 1;
+ if (write(*fd, &success, 1) != 1) {
+ swaylock_log(LOG_ERROR, "Failed to tell parent process that daemonization is done");
+ exit(1);
+ }
+ close(*fd);
+ *fd = -1;
+}
+
+static void destroy_surface(struct swaylock_surface *surface) {
+ swaylock_log(LOG_DEBUG, "Destroy surface for output %s", surface->output_name);
+
+ wl_list_remove(&surface->link);
+ if (surface->layer_surface != NULL) {
+ zwlr_layer_surface_v1_destroy(surface->layer_surface);
+ }
+ if (surface->ext_session_lock_surface_v1 != NULL) {
+ ext_session_lock_surface_v1_destroy(surface->ext_session_lock_surface_v1);
+ }
+ if (surface->surface != NULL) {
+ wl_surface_destroy(surface->surface);
+ }
+ destroy_buffer(&surface->buffers[0]);
+ destroy_buffer(&surface->buffers[1]);
+ destroy_buffer(&surface->indicator_buffers[0]);
+ destroy_buffer(&surface->indicator_buffers[1]);
+ wl_output_destroy(surface->output);
+ free(surface);
+}
+
+static const struct zwlr_layer_surface_v1_listener layer_surface_listener;
+static const struct ext_session_lock_surface_v1_listener ext_session_lock_surface_v1_listener;
+
+static cairo_surface_t *select_image(struct swaylock_state *state,
+ struct swaylock_surface *surface);
+
+static bool surface_is_opaque(struct swaylock_surface *surface) {
+ if (!fade_is_complete(&surface->fade)) {
+ return false;
+ }
+ if (surface->image) {
+ return cairo_surface_get_content(surface->image) == CAIRO_CONTENT_COLOR;
+ }
+ return (surface->state->args.colors.background & 0xff) == 0xff;
+}
+
+static void create_surface(struct swaylock_surface *surface) {
+ struct swaylock_state *state = surface->state;
+
+ if (state->args.allow_fade && state->args.fade_in) {
+ surface->fade.target_time = state->args.fade_in;
+ }
+
+ surface->image = select_image(state, surface);
+
+ surface->surface = wl_compositor_create_surface(state->compositor);
+ assert(surface->surface);
+
+ surface->child = wl_compositor_create_surface(state->compositor);
+ assert(surface->child);
+ surface->subsurface = wl_subcompositor_get_subsurface(state->subcompositor, surface->child, surface->surface);
+ assert(surface->subsurface);
+ wl_subsurface_set_sync(surface->subsurface);
+
+ if (state->ext_session_lock_v1) {
+ surface->ext_session_lock_surface_v1 = ext_session_lock_v1_get_lock_surface(
+ state->ext_session_lock_v1, surface->surface, surface->output);
+ ext_session_lock_surface_v1_add_listener(surface->ext_session_lock_surface_v1,
+ &ext_session_lock_surface_v1_listener, surface);
+ } else {
+ surface->layer_surface = zwlr_layer_shell_v1_get_layer_surface(
+ state->layer_shell, surface->surface, surface->output,
+ ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY, "lockscreen");
+
+ zwlr_layer_surface_v1_set_size(surface->layer_surface, 0, 0);
+ zwlr_layer_surface_v1_set_anchor(surface->layer_surface,
+ ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP |
+ ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT |
+ ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM |
+ ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT);
+ zwlr_layer_surface_v1_set_exclusive_zone(surface->layer_surface, -1);
+ zwlr_layer_surface_v1_set_keyboard_interactivity(
+ surface->layer_surface, true);
+ zwlr_layer_surface_v1_add_listener(surface->layer_surface,
+ &layer_surface_listener, surface);
+ surface->events_pending += 1;
+ }
+
+ if (!state->ext_session_lock_v1) {
+ wl_surface_commit(surface->surface);
+ }
+}
+
+static void initially_render_surface(struct swaylock_surface *surface) {
+ swaylock_log(LOG_DEBUG, "Surface for output %s ready", surface->output_name);
+ if (surface_is_opaque(surface) &&
+ surface->state->args.mode != BACKGROUND_MODE_CENTER &&
+ surface->state->args.mode != BACKGROUND_MODE_FIT) {
+ struct wl_region *region =
+ wl_compositor_create_region(surface->state->compositor);
+ wl_region_add(region, 0, 0, INT32_MAX, INT32_MAX);
+ wl_surface_set_opaque_region(surface->surface, region);
+ wl_region_destroy(region);
+ }
+
+ if (!surface->state->ext_session_lock_v1) {
+ render_frame_background(surface, true);
+ render_frame(surface);
+ }
+}
+
+static void layer_surface_configure(void *data,
+ struct zwlr_layer_surface_v1 *layer_surface,
+ uint32_t serial, uint32_t width, uint32_t height) {
+ swaylock_trace();
+ struct swaylock_surface *surface = data;
+ surface->width = width;
+ surface->height = height;
+ surface->indicator_width = 0;
+ surface->indicator_height = 0;
+ zwlr_layer_surface_v1_ack_configure(layer_surface, serial);
+
+ if (!surface->configured && --surface->events_pending == 0) {
+ initially_render_surface(surface);
+ }
+ surface->configured = true;
+}
+
+static void layer_surface_closed(void *data,
+ struct zwlr_layer_surface_v1 *layer_surface) {
+ swaylock_trace();
+ struct swaylock_surface *surface = data;
+ destroy_surface(surface);
+}
+
+static const struct zwlr_layer_surface_v1_listener layer_surface_listener = {
+ .configure = layer_surface_configure,
+ .closed = layer_surface_closed,
+};
+
+static void ext_session_lock_surface_v1_handle_configure(void *data,
+ struct ext_session_lock_surface_v1 *lock_surface, uint32_t serial,
+ uint32_t width, uint32_t height) {
+ struct swaylock_surface *surface = data;
+ surface->width = width;
+ surface->height = height;
+ surface->indicator_width = 0;
+ surface->indicator_height = 0;
+ // Render before we send the ACK event, so that we minimize flickering
+ // This means we cannot commit immediately after rendering -- we will have
+ // to send the ACK first and then commit.
+ render_frame_background(surface, false);
+ ext_session_lock_surface_v1_ack_configure(lock_surface, serial);
+ wl_surface_commit(surface->surface);
+ // render_frame(surface);
+}
+
+static const struct ext_session_lock_surface_v1_listener ext_session_lock_surface_v1_listener = {
+ .configure = ext_session_lock_surface_v1_handle_configure,
+};
+
+static const struct wl_callback_listener surface_frame_listener;
+
+static void surface_frame_handle_done(void *data, struct wl_callback *callback,
+ uint32_t time) {
+ struct swaylock_surface *surface = data;
+
+ wl_callback_destroy(callback);
+ surface->frame_pending = false;
+
+ if (surface->dirty) {
+ // Schedule a frame in case the surface is damaged again
+ struct wl_callback *callback = wl_surface_frame(surface->surface);
+ wl_callback_add_listener(callback, &surface_frame_listener, surface);
+ surface->frame_pending = true;
+ surface->dirty = false;
+
+ if (!fade_is_complete(&surface->fade)) {
+ render_background_fade(surface, time);
+ surface->dirty = true;
+ }
+
+ render_frame(surface);
+ }
+}
+
+static const struct wl_callback_listener surface_frame_listener = {
+ .done = surface_frame_handle_done,
+};
+
+void damage_surface(struct swaylock_surface *surface) {
+ if (surface->width == 0 || surface->height == 0) {
+ // Not yet configured
+ return;
+ }
+
+ surface->dirty = true;
+ if (surface->frame_pending) {
+ return;
+ }
+
+ struct wl_callback *callback = wl_surface_frame(surface->surface);
+ wl_callback_add_listener(callback, &surface_frame_listener, surface);
+ surface->frame_pending = true;
+ wl_surface_commit(surface->surface);
+}
+
+void damage_state(struct swaylock_state *state) {
+ struct swaylock_surface *surface;
+ wl_list_for_each(surface, &state->surfaces, link) {
+ damage_surface(surface);
+ }
+}
+
+static void handle_wl_output_geometry(void *data, struct wl_output *wl_output,
+ int32_t x, int32_t y, int32_t width_mm, int32_t height_mm,
+ int32_t subpixel, const char *make, const char *model,
+ int32_t transform) {
+ swaylock_trace();
+ struct swaylock_surface *surface = data;
+ surface->subpixel = subpixel;
+ surface->transform = transform;
+ if (surface->state->run_display) {
+ damage_surface(surface);
+ }
+}
+
+static void handle_wl_output_mode(void *data, struct wl_output *output,
+ uint32_t flags, int32_t width, int32_t height, int32_t refresh) {
+ // Who cares
+}
+
+static void handle_wl_output_scale(void *data, struct wl_output *output,
+ int32_t factor) {
+ swaylock_trace();
+ struct swaylock_surface *surface = data;
+ surface->scale = factor;
+ if (surface->state->run_display) {
+ damage_surface(surface);
+ }
+}
+
+static struct wl_buffer *create_shm_buffer(struct wl_shm *shm, enum wl_shm_format fmt,
+ int width, int height, int stride, void **data_out) {
+ int size = stride * height;
+
+ const char shm_name[] = "/swaylock-shm";
+ int fd = shm_open(shm_name, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
+ if (fd < 0) {
+ fprintf(stderr, "shm_open failed\n");
+ return NULL;
+ }
+ shm_unlink(shm_name);
+
+ int ret;
+ while ((ret = ftruncate(fd, size)) == EINTR) {
+ // No-op
+ }
+ if (ret < 0) {
+ close(fd);
+ fprintf(stderr, "ftruncate failed\n");
+ return NULL;
+ }
+
+ void *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+ if (data == MAP_FAILED) {
+ fprintf(stderr, "mmap failed: %m\n");
+ close(fd);
+ return NULL;
+ }
+
+ struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, size);
+ close(fd);
+ struct wl_buffer *buffer = wl_shm_pool_create_buffer(pool, 0, width, height,
+ stride, fmt);
+ wl_shm_pool_destroy(pool);
+
+ *data_out = data;
+ return buffer;
+}
+
+static cairo_surface_t *apply_effects(cairo_surface_t *image, struct swaylock_state *state, int scale) {
+ if (state->args.effects_count == 0) {
+ return image;
+ }
+
+ if (state->args.time_effects) {
+ return swaylock_effects_run_timed(
+ image, scale,
+ state->args.effects, state->args.effects_count);
+ } else {
+ return swaylock_effects_run(
+ image, scale,
+ state->args.effects, state->args.effects_count);
+ }
+}
+
+static void handle_screencopy_frame_buffer(void *data,
+ struct zwlr_screencopy_frame_v1 *frame, uint32_t format, uint32_t width,
+ uint32_t height, uint32_t stride) {
+ swaylock_trace();
+ struct swaylock_surface *surface = data;
+
+ struct swaylock_image *image = calloc(1, sizeof(struct swaylock_image));
+ image->path = NULL;
+ image->output_name = surface->output_name;
+
+ void *bufdata;
+ struct wl_buffer *buf = create_shm_buffer(surface->state->shm, format, width, height, stride, &bufdata);
+ if (buf == NULL) {
+ free(image);
+ return;
+ }
+
+ surface->screencopy.format = format;
+ surface->screencopy.width = width;
+ surface->screencopy.height = height;
+ surface->screencopy.stride = stride;
+
+ surface->screencopy.image = image;
+ surface->screencopy.data = bufdata;
+
+ zwlr_screencopy_frame_v1_copy(frame, buf);
+}
+
+static void handle_screencopy_frame_flags(void *data,
+ struct zwlr_screencopy_frame_v1 *frame, uint32_t flags) {
+ swaylock_trace();
+ struct swaylock_surface *surface = data;
+
+ // The transform affecting a screenshot consists of three parts:
+ // Whether it's flipped vertically, whether it's flipped horizontally,
+ // and the four rotation options (0, 90, 180, 270).
+ // Any of the combinations of vertical flips, horizontal flips and rotation,
+ // can be expressed in terms of only horizontal flips and rotation
+ // (which is what the enum wl_output_transform encodes).
+ // Therefore, instead of inverting the Y axis or keeping around the
+ // "was it vertically flipped?" bit, we just map our state space onto the
+ // state space encoded by wl_output_transform and let load_background_from_buffer
+ // handle the rest.
+ if (flags & ZWLR_SCREENCOPY_FRAME_V1_FLAGS_Y_INVERT) {
+ switch (surface->transform) {
+ case WL_OUTPUT_TRANSFORM_NORMAL:
+ surface->screencopy.transform = WL_OUTPUT_TRANSFORM_FLIPPED_180;
+ break;
+ case WL_OUTPUT_TRANSFORM_90:
+ surface->screencopy.transform = WL_OUTPUT_TRANSFORM_FLIPPED_90;
+ break;
+ case WL_OUTPUT_TRANSFORM_180:
+ surface->screencopy.transform = WL_OUTPUT_TRANSFORM_FLIPPED;
+ break;
+ case WL_OUTPUT_TRANSFORM_270:
+ surface->screencopy.transform = WL_OUTPUT_TRANSFORM_FLIPPED_270;
+ break;
+ case WL_OUTPUT_TRANSFORM_FLIPPED:
+ surface->screencopy.transform = WL_OUTPUT_TRANSFORM_180;
+ break;
+ case WL_OUTPUT_TRANSFORM_FLIPPED_90:
+ surface->screencopy.transform = WL_OUTPUT_TRANSFORM_90;
+ break;
+ case WL_OUTPUT_TRANSFORM_FLIPPED_180:
+ surface->screencopy.transform = WL_OUTPUT_TRANSFORM_NORMAL;
+ break;
+ case WL_OUTPUT_TRANSFORM_FLIPPED_270:
+ surface->screencopy.transform = WL_OUTPUT_TRANSFORM_270;
+ break;
+ }
+ } else {
+ surface->screencopy.transform = surface->transform;
+ }
+}
+
+static void handle_screencopy_frame_ready(void *data,
+ struct zwlr_screencopy_frame_v1 *frame, uint32_t tv_sec_hi,
+ uint32_t tv_sec_lo, uint32_t tv_nsec) {
+ swaylock_trace();
+ struct swaylock_surface *surface = data;
+ struct swaylock_state *state = surface->state;
+
+ cairo_surface_t *image = load_background_from_buffer(
+ surface->screencopy.data,
+ surface->screencopy.format,
+ surface->screencopy.width,
+ surface->screencopy.height,
+ surface->screencopy.stride,
+ surface->screencopy.transform);
+ if (image == NULL) {
+ swaylock_log(LOG_ERROR, "Failed to create image from screenshot");
+ state->args.screenshots = false;
+ state->args.fade_in = 0; // Fade in is not possible without screenshot
+ } else {
+ surface->screencopy.original_image = cairo_surface_duplicate(image);
+ surface->screencopy.image->cairo_surface = image;
+ if (state->args.screenshots) {
+ swaylock_log(LOG_DEBUG, "Loaded screenshot for output %s", surface->output_name);
+ wl_list_insert(&state->images, &surface->screencopy.image->link);
+ }
+ }
+
+ --surface->events_pending;
+}
+
+static void handle_screencopy_frame_failed(void *data,
+ struct zwlr_screencopy_frame_v1 *frame) {
+ swaylock_trace();
+ struct swaylock_surface *surface = data;
+ swaylock_log(LOG_ERROR, "Screencopy failed");
+ surface->state->args.screenshots = false;
+ surface->state->args.fade_in = 0; // Fade in is not possible without screenshot
+
+ --surface->events_pending;
+}
+
+static const struct zwlr_screencopy_frame_v1_listener screencopy_frame_listener = {
+ .buffer = handle_screencopy_frame_buffer,
+ .flags = handle_screencopy_frame_flags,
+ .ready = handle_screencopy_frame_ready,
+ .failed = handle_screencopy_frame_failed,
+};
+
+static void handle_wl_output_name(void *data, struct wl_output *output,
+ const char *name) {
+ swaylock_trace();
+ swaylock_log(LOG_DEBUG, "output name is %s", name);
+ struct swaylock_surface *surface = data;
+ surface->output_name = strdup(name);
+}
+
+static void handle_wl_output_description(void *data, struct wl_output *output,
+ const char *description) {
+ // Who cares
+}
+
+static void handle_wl_output_done(void *data, struct wl_output *output) {
+ swaylock_trace();
+ struct swaylock_surface *surface = data;
+ struct swaylock_state *state = surface->state;
+
+ static bool has_printed_screencopy_error = false;
+ if (state->screencopy_manager) {
+ surface->screencopy_frame = zwlr_screencopy_manager_v1_capture_output(
+ state->screencopy_manager, false, surface->output);
+ zwlr_screencopy_frame_v1_add_listener(surface->screencopy_frame,
+ &screencopy_frame_listener, surface);
+ surface->events_pending += 1;
+ } else if (!has_printed_screencopy_error) {
+ swaylock_log(LOG_INFO, "Compositor does not support screencopy manager, "
+ "screenshots / fade-in will not work");
+ state->args.screenshots = false;
+ state->args.fade_in = 0; // Fade in is not possible without screenshot
+ has_printed_screencopy_error = true;
+ }
+
+ --surface->events_pending;
+}
+
+struct wl_output_listener _wl_output_listener = {
+ .geometry = handle_wl_output_geometry,
+ .mode = handle_wl_output_mode,
+ .done = handle_wl_output_done,
+ .scale = handle_wl_output_scale,
+ .name = handle_wl_output_name,
+ .description = handle_wl_output_description,
+};
+
+static void ext_session_lock_v1_handle_locked(void *data, struct ext_session_lock_v1 *lock) {
+ // Who cares
+}
+
+static void ext_session_lock_v1_handle_finished(void *data, struct ext_session_lock_v1 *lock) {
+ swaylock_log(LOG_ERROR, "Failed to lock session -- "
+ "is another lockscreen running?");
+ exit(2);
+}
+
+static const struct ext_session_lock_v1_listener ext_session_lock_v1_listener = {
+ .locked = ext_session_lock_v1_handle_locked,
+ .finished = ext_session_lock_v1_handle_finished,
+};
+
+static void handle_global(void *data, struct wl_registry *registry,
+ uint32_t name, const char *interface, uint32_t version) {
+
+ struct swaylock_state *state = data;
+ if (strcmp(interface, wl_compositor_interface.name) == 0) {
+ state->compositor = wl_registry_bind(registry, name,
+ &wl_compositor_interface, 4);
+ } else if (strcmp(interface, wl_subcompositor_interface.name) == 0) {
+ state->subcompositor = wl_registry_bind(registry, name,
+ &wl_subcompositor_interface, 1);
+ } else if (strcmp(interface, wl_shm_interface.name) == 0) {
+ state->shm = wl_registry_bind(registry, name,
+ &wl_shm_interface, 1);
+ } else if (strcmp(interface, wl_seat_interface.name) == 0) {
+ struct wl_seat *seat = wl_registry_bind(
+ registry, name, &wl_seat_interface, 4);
+ struct swaylock_seat *swaylock_seat =
+ calloc(1, sizeof(struct swaylock_seat));
+ swaylock_seat->state = state;
+ wl_seat_add_listener(seat, &seat_listener, swaylock_seat);
+ } else if (strcmp(interface, zwlr_layer_shell_v1_interface.name) == 0) {
+ state->layer_shell = wl_registry_bind(
+ registry, name, &zwlr_layer_shell_v1_interface, 1);
+ } else if (strcmp(interface, zwlr_input_inhibit_manager_v1_interface.name) == 0) {
+ state->input_inhibit_manager = wl_registry_bind(
+ registry, name, &zwlr_input_inhibit_manager_v1_interface, 1);
+ } else if (strcmp(interface, wl_output_interface.name) == 0) {
+ struct swaylock_surface *surface =
+ calloc(1, sizeof(struct swaylock_surface));
+ surface->state = state;
+ surface->output = wl_registry_bind(registry, name,
+ &wl_output_interface, 4);
+ surface->output_global_name = name;
+ wl_output_add_listener(surface->output, &_wl_output_listener, surface);
+ wl_list_insert(&state->surfaces, &surface->link);
+
+ if (state->run_display) {
+ create_surface(surface);
+ wl_display_roundtrip(state->display);
+ }
+ } else if (strcmp(interface, zwlr_screencopy_manager_v1_interface.name) == 0) {
+ state->screencopy_manager = wl_registry_bind(registry, name,
+ &zwlr_screencopy_manager_v1_interface, 1);
+ } else if (strcmp(interface, ext_session_lock_manager_v1_interface.name) == 0) {
+ state->ext_session_lock_manager_v1 = wl_registry_bind(registry, name,
+ &ext_session_lock_manager_v1_interface, 1);
+ }
+}
+
+static void handle_global_remove(void *data, struct wl_registry *registry,
+ uint32_t name) {
+ struct swaylock_state *state = data;
+ struct swaylock_surface *surface;
+ wl_list_for_each(surface, &state->surfaces, link) {
+ if (surface->output_global_name == name) {
+ destroy_surface(surface);
+ break;
+ }
+ }
+}
+
+static const struct wl_registry_listener registry_listener = {
+ .global = handle_global,
+ .global_remove = handle_global_remove,
+};
+
+static int sigusr_fds[2] = {-1, -1};
+
+void do_sigusr(int sig) {
+ (void)write(sigusr_fds[1], "1", 1);
+}
+
+static cairo_surface_t *select_image(struct swaylock_state *state,
+ struct swaylock_surface *surface) {
+ struct swaylock_image *image;
+ cairo_surface_t *default_image = NULL;
+ wl_list_for_each(image, &state->images, link) {
+ if (lenient_strcmp(image->output_name, surface->output_name) == 0) {
+ return image->cairo_surface;
+ } else if (!image->output_name) {
+ default_image = image->cairo_surface;
+ }
+ }
+ return default_image;
+}
+
+static char *join_args(char **argv, int argc) {
+ assert(argc > 0);
+ int len = 0, i;
+ for (i = 0; i < argc; ++i) {
+ len += strlen(argv[i]) + 1;
+ }
+ char *res = malloc(len);
+ len = 0;
+ for (i = 0; i < argc; ++i) {
+ strcpy(res + len, argv[i]);
+ len += strlen(argv[i]);
+ res[len++] = ' ';
+ }
+ res[len - 1] = '\0';
+ return res;
+}
+
+static void load_image(char *arg, struct swaylock_state *state) {
+ // [[<output>]:]<path>
+ struct swaylock_image *image = calloc(1, sizeof(struct swaylock_image));
+ char *separator = strchr(arg, ':');
+ if (separator) {
+ *separator = '\0';
+ image->output_name = separator == arg ? NULL : strdup(arg);
+ image->path = strdup(separator + 1);
+ } else {
+ image->output_name = NULL;
+ image->path = strdup(arg);
+ }
+
+ struct swaylock_image *iter_image, *temp;
+ wl_list_for_each_safe(iter_image, temp, &state->images, link) {
+ if (lenient_strcmp(iter_image->output_name, image->output_name) == 0) {
+ if (image->output_name) {
+ swaylock_log(LOG_DEBUG,
+ "Replacing image defined for output %s with %s",
+ image->output_name, image->path);
+ } else {
+ swaylock_log(LOG_DEBUG, "Replacing default image with %s",
+ image->path);
+ }
+ wl_list_remove(&iter_image->link);
+ free(iter_image->cairo_surface);
+ free(iter_image->output_name);
+ free(iter_image->path);
+ free(iter_image);
+ break;
+ }
+ }
+
+ // The shell will not expand ~ to the value of $HOME when an output name is
+ // given. Also, any image paths given in the config file need to have shell
+ // expansions performed
+ wordexp_t p;
+ while (strstr(image->path, " ")) {
+ image->path = realloc(image->path, strlen(image->path) + 2);
+ char *ptr = strstr(image->path, " ") + 1;
+ memmove(ptr + 1, ptr, strlen(ptr) + 1);
+ *ptr = '\\';
+ }
+ if (wordexp(image->path, &p, 0) == 0) {
+ free(image->path);
+ image->path = join_args(p.we_wordv, p.we_wordc);
+ wordfree(&p);
+ }
+
+ // Load the actual image
+ image->cairo_surface = load_background_image(image->path);
+ if (!image->cairo_surface) {
+ free(image);
+ return;
+ }
+
+ wl_list_insert(&state->images, &image->link);
+ swaylock_log(LOG_DEBUG, "Loaded image %s for output %s", image->path,
+ image->output_name ? image->output_name : "*");
+}
+
+static void set_default_colors(struct swaylock_colors *colors) {
+ colors->background = 0xFFFFFFFF;
+ colors->bs_highlight = 0xDB3300FF;
+ colors->key_highlight = 0x33DB00FF;
+ colors->caps_lock_bs_highlight = 0xDB3300FF;
+ colors->caps_lock_key_highlight = 0x33DB00FF;
+ colors->separator = 0x000000FF;
+ colors->layout_background = 0x000000C0;
+ colors->layout_border = 0x00000000;
+ colors->layout_text = 0xFFFFFFFF;
+ colors->inside = (struct swaylock_colorset){
+ .input = 0x000000C0,
+ .cleared = 0xE5A445C0,
+ .caps_lock = 0x000000C0,
+ .verifying = 0x0072FFC0,
+ .wrong = 0xFA0000C0,
+ };
+ colors->line = (struct swaylock_colorset){
+ .input = 0x000000FF,
+ .cleared = 0x000000FF,
+ .caps_lock = 0x000000FF,
+ .verifying = 0x000000FF,
+ .wrong = 0x000000FF,
+ };
+ colors->ring = (struct swaylock_colorset){
+ .input = 0x337D00FF,
+ .cleared = 0xE5A445FF,
+ .caps_lock = 0xE5A445FF,
+ .verifying = 0x3300FFFF,
+ .wrong = 0x7D3300FF,
+ };
+ colors->text = (struct swaylock_colorset){
+ .input = 0xE5A445FF,
+ .cleared = 0x000000FF,
+ .caps_lock = 0xE5A445FF,
+ .verifying = 0x000000FF,
+ .wrong = 0x000000FF,
+ };
+}
+
+enum line_mode {
+ LM_LINE,
+ LM_INSIDE,
+ LM_RING,
+};
+
+static int parse_options(int argc, char **argv, struct swaylock_state *state,
+ enum line_mode *line_mode, char **config_path) {
+ enum long_option_codes {
+ LO_BS_HL_COLOR = 256,
+ LO_CAPS_LOCK_BS_HL_COLOR,
+ LO_CAPS_LOCK_KEY_HL_COLOR,
+ LO_FONT,
+ LO_FONT_SIZE,
+ LO_IND_IDLE_VISIBLE,
+ LO_IND_RADIUS,
+ LO_IND_X_POSITION,
+ LO_IND_Y_POSITION,
+ LO_IND_THICKNESS,
+ LO_IND_IMAGE,
+ LO_INSIDE_COLOR,
+ LO_INSIDE_CLEAR_COLOR,
+ LO_INSIDE_CAPS_LOCK_COLOR,
+ LO_INSIDE_VER_COLOR,
+ LO_INSIDE_WRONG_COLOR,
+ LO_KEY_HL_COLOR,
+ LO_LAYOUT_TXT_COLOR,
+ LO_LAYOUT_BG_COLOR,
+ LO_LAYOUT_BORDER_COLOR,
+ LO_LINE_COLOR,
+ LO_LINE_CLEAR_COLOR,
+ LO_LINE_CAPS_LOCK_COLOR,
+ LO_LINE_VER_COLOR,
+ LO_LINE_WRONG_COLOR,
+ LO_RING_COLOR,
+ LO_RING_CLEAR_COLOR,
+ LO_RING_CAPS_LOCK_COLOR,
+ LO_RING_VER_COLOR,
+ LO_RING_WRONG_COLOR,
+ LO_SEP_COLOR,
+ LO_TEXT_COLOR,
+ LO_TEXT_CLEAR,
+ LO_TEXT_CLEAR_COLOR,
+ LO_TEXT_CAPS_LOCK,
+ LO_TEXT_CAPS_LOCK_COLOR,
+ LO_TEXT_VER,
+ LO_TEXT_VER_COLOR,
+ LO_TEXT_WRONG,
+ LO_TEXT_WRONG_COLOR,
+ LO_EFFECT_BLUR,
+ LO_EFFECT_PIXELATE,
+ LO_EFFECT_SCALE,
+ LO_EFFECT_GREYSCALE,
+ LO_EFFECT_VIGNETTE,
+ LO_EFFECT_COMPOSE,
+ LO_EFFECT_CUSTOM,
+ LO_TIME_EFFECTS,
+ LO_INDICATOR,
+ LO_CLOCK,
+ LO_TIMESTR,
+ LO_DATESTR,
+ LO_FADE_IN,
+ LO_SUBMIT_ON_TOUCH,
+ LO_GRACE,
+ LO_GRACE_NO_MOUSE,
+ LO_GRACE_NO_TOUCH,
+ };
+
+ static struct option long_options[] = {
+ {"config", required_argument, NULL, 'C'},
+ {"color", required_argument, NULL, 'c'},
+ {"debug", no_argument, NULL, 'd'},
+ {"trace", no_argument, NULL, 't'},
+ {"ignore-empty-password", no_argument, NULL, 'e'},
+ {"daemonize", no_argument, NULL, 'f'},
+ {"help", no_argument, NULL, 'h'},
+ {"image", required_argument, NULL, 'i'},
+ {"screenshots", no_argument, NULL, 'S'},
+ {"disable-caps-lock-text", no_argument, NULL, 'L'},
+ {"indicator-caps-lock", no_argument, NULL, 'l'},
+ {"line-uses-inside", no_argument, NULL, 'n'},
+ {"line-uses-ring", no_argument, NULL, 'r'},
+ {"scaling", required_argument, NULL, 's'},
+ {"tiling", no_argument, NULL, 'T'},
+ {"no-unlock-indicator", no_argument, NULL, 'u'},
+ {"show-keyboard-layout", no_argument, NULL, 'k'},
+ {"hide-keyboard-layout", no_argument, NULL, 'K'},
+ {"show-failed-attempts", no_argument, NULL, 'F'},
+ {"version", no_argument, NULL, 'v'},
+ {"bs-hl-color", required_argument, NULL, LO_BS_HL_COLOR},
+ {"caps-lock-bs-hl-color", required_argument, NULL, LO_CAPS_LOCK_BS_HL_COLOR},
+ {"caps-lock-key-hl-color", required_argument, NULL, LO_CAPS_LOCK_KEY_HL_COLOR},
+ {"font", required_argument, NULL, LO_FONT},
+ {"font-size", required_argument, NULL, LO_FONT_SIZE},
+ {"indicator-idle-visible", no_argument, NULL, LO_IND_IDLE_VISIBLE},
+ {"indicator-radius", required_argument, NULL, LO_IND_RADIUS},
+ {"indicator-thickness", required_argument, NULL, LO_IND_THICKNESS},
+ {"indicator-x-position", required_argument, NULL, LO_IND_X_POSITION},
+ {"indicator-y-position", required_argument, NULL, LO_IND_Y_POSITION},
+ {"indicator-image", required_argument, NULL, LO_IND_IMAGE},
+ {"inside-color", required_argument, NULL, LO_INSIDE_COLOR},
+ {"inside-clear-color", required_argument, NULL, LO_INSIDE_CLEAR_COLOR},
+ {"inside-caps-lock-color", required_argument, NULL, LO_INSIDE_CAPS_LOCK_COLOR},
+ {"inside-ver-color", required_argument, NULL, LO_INSIDE_VER_COLOR},
+ {"inside-wrong-color", required_argument, NULL, LO_INSIDE_WRONG_COLOR},
+ {"key-hl-color", required_argument, NULL, LO_KEY_HL_COLOR},
+ {"layout-bg-color", required_argument, NULL, LO_LAYOUT_BG_COLOR},
+ {"layout-border-color", required_argument, NULL, LO_LAYOUT_BORDER_COLOR},
+ {"layout-text-color", required_argument, NULL, LO_LAYOUT_TXT_COLOR},
+ {"line-color", required_argument, NULL, LO_LINE_COLOR},
+ {"line-clear-color", required_argument, NULL, LO_LINE_CLEAR_COLOR},
+ {"line-caps-lock-color", required_argument, NULL, LO_LINE_CAPS_LOCK_COLOR},
+ {"line-ver-color", required_argument, NULL, LO_LINE_VER_COLOR},
+ {"line-wrong-color", required_argument, NULL, LO_LINE_WRONG_COLOR},
+ {"ring-color", required_argument, NULL, LO_RING_COLOR},
+ {"ring-clear-color", required_argument, NULL, LO_RING_CLEAR_COLOR},
+ {"ring-caps-lock-color", required_argument, NULL, LO_RING_CAPS_LOCK_COLOR},
+ {"ring-ver-color", required_argument, NULL, LO_RING_VER_COLOR},
+ {"ring-wrong-color", required_argument, NULL, LO_RING_WRONG_COLOR},
+ {"separator-color", required_argument, NULL, LO_SEP_COLOR},
+ {"text-color", required_argument, NULL, LO_TEXT_COLOR},
+ {"text-clear", required_argument, NULL, LO_TEXT_CLEAR},
+ {"text-clear-color", required_argument, NULL, LO_TEXT_CLEAR_COLOR},
+ {"text-caps-lock", required_argument, NULL, LO_TEXT_CAPS_LOCK},
+ {"text-caps-lock-color", required_argument, NULL, LO_TEXT_CAPS_LOCK_COLOR},
+ {"text-ver", required_argument, NULL, LO_TEXT_VER},
+ {"text-ver-color", required_argument, NULL, LO_TEXT_VER_COLOR},
+ {"text-wrong", required_argument, NULL, LO_TEXT_WRONG},
+ {"text-wrong-color", required_argument, NULL, LO_TEXT_WRONG_COLOR},
+ {"effect-blur", required_argument, NULL, LO_EFFECT_BLUR},
+ {"effect-pixelate", required_argument, NULL, LO_EFFECT_PIXELATE},
+ {"effect-scale", required_argument, NULL, LO_EFFECT_SCALE},
+ {"effect-greyscale", no_argument, NULL, LO_EFFECT_GREYSCALE},
+ {"effect-vignette", required_argument, NULL, LO_EFFECT_VIGNETTE},
+ {"effect-compose", required_argument, NULL, LO_EFFECT_COMPOSE},
+ {"effect-custom", required_argument, NULL, LO_EFFECT_CUSTOM},
+ {"time-effects", no_argument, NULL, LO_TIME_EFFECTS},
+ {"indicator", no_argument, NULL, LO_INDICATOR},
+ {"clock", no_argument, NULL, LO_CLOCK},
+ {"timestr", required_argument, NULL, LO_TIMESTR},
+ {"datestr", required_argument, NULL, LO_DATESTR},
+ {"fade-in", required_argument, NULL, LO_FADE_IN},
+ {"submit-on-touch", no_argument, NULL, LO_SUBMIT_ON_TOUCH},
+ {"grace", required_argument, NULL, LO_GRACE},
+ {"grace-no-mouse", no_argument, NULL, LO_GRACE_NO_MOUSE},
+ {"grace-no-touch", no_argument, NULL, LO_GRACE_NO_TOUCH},
+ {0, 0, 0, 0}
+ };
+
+ const char usage[] =
+ "Usage: swaylock [options...]\n"
+ "\n"
+ " -C, --config <config_file> "
+ "Path to the config file.\n"
+ " -c, --color <color> "
+ "Turn the screen into the given color instead of white.\n"
+ " -d, --debug "
+ "Enable debugging output.\n"
+ " -t, --trace "
+ "Enable tracing output.\n"
+ " -e, --ignore-empty-password "
+ "When an empty password is provided, do not validate it.\n"
+ " -F, --show-failed-attempts "
+ "Show current count of failed authentication attempts.\n"
+ " -f, --daemonize "
+ "Detach from the controlling terminal after locking.\n"
+ " --fade-in <seconds> "
+ "Make the lock screen fade in instead of just popping in.\n"
+ " --submit-on-touch "
+ "Submit password in response to a touch event.\n"
+ " --grace <seconds> "
+ "Password grace period. Don't require the password for the first N seconds.\n"
+ " --grace-no-mouse "
+ "During the grace period, don't unlock on a mouse event.\n"
+ " --grace-no-touch "
+ "During the grace period, don't unlock on a touch event.\n"
+ " -h, --help "
+ "Show help message and quit.\n"
+ " -i, --image [[<output>]:]<path> "
+ "Display the given image, optionally only on the given output.\n"
+ " -S, --screenshots "
+ "Use a screenshots as the background image.\n"
+ " -k, --show-keyboard-layout "
+ "Display the current xkb layout while typing.\n"
+ " -K, --hide-keyboard-layout "
+ "Hide the current xkb layout while typing.\n"
+ " -L, --disable-caps-lock-text "
+ "Disable the Caps Lock text.\n"
+ " -l, --indicator-caps-lock "
+ "Show the current Caps Lock state also on the indicator.\n"
+ " -s, --scaling <mode> "
+ "Image scaling mode: stretch, fill, fit, center, tile, solid_color.\n"
+ " -T, --tiling "
+ "Same as --scaling=tile.\n"
+ " -u, --no-unlock-indicator "
+ "Disable the unlock indicator.\n"
+ " --indicator "
+ "Always show the indicator.\n"
+ " --clock "
+ "Show time and date.\n"
+ " --timestr <format> "
+ "The format string for the time. Defaults to '%T'.\n"
+ " --datestr <format> "
+ "The format string for the date. Defaults to '%a, %x'.\n"
+ " -v, --version "
+ "Show the version number and quit.\n"
+ " --bs-hl-color <color> "
+ "Sets the color of backspace highlight segments.\n"
+ " --caps-lock-bs-hl-color <color> "
+ "Sets the color of backspace highlight segments when Caps Lock "
+ "is active.\n"
+ " --caps-lock-key-hl-color <color> "
+ "Sets the color of the key press highlight segments when "
+ "Caps Lock is active.\n"
+ " --font <font> "
+ "Sets the font of the text.\n"
+ " --font-size <size> "
+ "Sets a fixed font size for the indicator text.\n"
+ " --indicator-idle-visible "
+ "Sets the indicator to show even if idle.\n"
+ " --indicator-radius <radius> "
+ "Sets the indicator radius.\n"
+ " --indicator-thickness <thick> "
+ "Sets the indicator thickness.\n"
+ " --indicator-x-position <x> "
+ "Sets the horizontal position of the indicator.\n"
+ " --indicator-y-position <y> "
+ "Sets the vertical position of the indicator.\n"
+ " --indicator-image <path> "
+ "Display the given image inside of the indicator.\n"
+ " --inside-color <color> "
+ "Sets the color of the inside of the indicator.\n"
+ " --inside-clear-color <color> "
+ "Sets the color of the inside of the indicator when cleared.\n"
+ " --inside-caps-lock-color <color> "
+ "Sets the color of the inside of the indicator when Caps Lock "
+ "is active.\n"
+ " --inside-ver-color <color> "
+ "Sets the color of the inside of the indicator when verifying.\n"
+ " --inside-wrong-color <color> "
+ "Sets the color of the inside of the indicator when invalid.\n"
+ " --key-hl-color <color> "
+ "Sets the color of the key press highlight segments.\n"
+ " --layout-bg-color <color> "
+ "Sets the background color of the box containing the layout text.\n"
+ " --layout-border-color <color> "
+ "Sets the color of the border of the box containing the layout text.\n"
+ " --layout-text-color <color> "
+ "Sets the color of the layout text.\n"
+ " --line-color <color> "
+ "Sets the color of the line between the inside and ring.\n"
+ " --line-clear-color <color> "
+ "Sets the color of the line between the inside and ring when "
+ "cleared.\n"
+ " --line-caps-lock-color <color> "
+ "Sets the color of the line between the inside and ring when "
+ "Caps Lock is active.\n"
+ " --line-ver-color <color> "
+ "Sets the color of the line between the inside and ring when "
+ "verifying.\n"
+ " --line-wrong-color <color> "
+ "Sets the color of the line between the inside and ring when "
+ "invalid.\n"
+ " -n, --line-uses-inside "
+ "Use the inside color for the line between the inside and ring.\n"
+ " -r, --line-uses-ring "
+ "Use the ring color for the line between the inside and ring.\n"
+ " --ring-color <color> "
+ "Sets the color of the ring of the indicator.\n"
+ " --ring-clear-color <color> "
+ "Sets the color of the ring of the indicator when cleared.\n"
+ " --ring-caps-lock-color <color> "
+ "Sets the color of the ring of the indicator when Caps Lock "
+ "is active.\n"
+ " --ring-ver-color <color> "
+ "Sets the color of the ring of the indicator when verifying.\n"
+ " --ring-wrong-color <color> "
+ "Sets the color of the ring of the indicator when invalid.\n"
+ " --separator-color <color> "
+ "Sets the color of the lines that separate highlight segments.\n"
+ " --text-color <color> "
+ "Sets the color of the text.\n"
+ " --text-clear-color <color> "
+ "Sets the color of the text when cleared.\n"
+ " --text-caps-lock-color <color> "
+ "Sets the color of the text when Caps Lock is active.\n"
+ " --text-ver-color <color> "
+ "Sets the color of the text when verifying.\n"
+ " --text-wrong-color <color> "
+ "Sets the color of the text when invalid.\n"
+ " --effect-blur <radius>x<times> "
+ "Blur images.\n"
+ " --effect-pixelate <factor> "
+ "Pixelate images.\n"
+ " --effect-scale <scale> "
+ "Scale images.\n"
+ " --effect-greyscale "
+ "Make images greyscale.\n"
+ " --effect-vignette <base>:<factor>"
+ "Apply a vignette effect to images. Base and factor should be numbers between 0 and 1.\n"
+ " --effect-custom <path> "
+ "Apply a custom effect from a shared object or C source file.\n"
+ " --time-effects "
+ "Measure the time it takes to run each effect.\n"
+ "\n"
+ "All <color> options are of the form <rrggbb[aa]>.\n";
+
+ int c;
+ optind = 1;
+ while (1) {
+ int opt_idx = 0;
+ c = getopt_long(argc, argv, "c:deFfhi:SkKLlnrs:tuvC:", long_options,
+ &opt_idx);
+ if (c == -1) {
+ break;
+ }
+ switch (c) {
+ case 'C':
+ if (config_path) {
+ *config_path = strdup(optarg);
+ }
+ break;
+ case 'c':
+ if (state) {
+ state->args.colors.background = parse_color(optarg);
+ }
+ break;
+ case 'd':
+ swaylock_log_init(LOG_DEBUG);
+ break;
+ case 't':
+ swaylock_log_init(LOG_TRACE);
+ break;
+ case 'e':
+ if (state) {
+ state->args.ignore_empty = true;
+ }
+ break;
+ case 'F':
+ if (state) {
+ state->args.show_failed_attempts = true;
+ }
+ break;
+ case 'f':
+ if (state) {
+ state->args.daemonize = true;
+ }
+ break;
+ case 'i':
+ if (state) {
+ load_image(optarg, state);
+ }
+ break;
+ case 'S':
+ if (state) {
+ state->args.screenshots = true;
+ }
+ break;
+ case 'k':
+ if (state) {
+ state->args.show_keyboard_layout = true;
+ }
+ break;
+ case 'K':
+ if (state) {
+ state->args.hide_keyboard_layout = true;
+ }
+ break;
+ case 'L':
+ if (state) {
+ state->args.show_caps_lock_text = false;
+ }
+ break;
+ case 'l':
+ if (state) {
+ state->args.show_caps_lock_indicator = true;
+ }
+ break;
+ case 'n':
+ if (line_mode) {
+ *line_mode = LM_INSIDE;
+ }
+ break;
+ case 'r':
+ if (line_mode) {
+ *line_mode = LM_RING;
+ }
+ break;
+ case 's':
+ if (state) {
+ state->args.mode = parse_background_mode(optarg);
+ if (state->args.mode == BACKGROUND_MODE_INVALID) {
+ return 1;
+ }
+ }
+ break;
+ case 'T':
+ if (state) {
+ state->args.mode = BACKGROUND_MODE_TILE;
+ }
+ break;
+ case 'u':
+ if (state) {
+ state->args.show_indicator = false;
+ }
+ break;
+ case 'v':
+ fprintf(stdout, "swaylock version " SWAYLOCK_VERSION "\n");
+ exit(EXIT_SUCCESS);
+ break;
+ case LO_BS_HL_COLOR:
+ if (state) {
+ state->args.colors.bs_highlight = parse_color(optarg);
+ }
+ break;
+ case LO_CAPS_LOCK_BS_HL_COLOR:
+ if (state) {
+ state->args.colors.caps_lock_bs_highlight = parse_color(optarg);
+ }
+ break;
+ case LO_CAPS_LOCK_KEY_HL_COLOR:
+ if (state) {
+ state->args.colors.caps_lock_key_highlight = parse_color(optarg);
+ }
+ break;
+ case LO_FONT:
+ if (state) {
+ free(state->args.font);
+ state->args.font = strdup(optarg);
+ }
+ break;
+ case LO_FONT_SIZE:
+ if (state) {
+ state->args.font_size = atoi(optarg);
+ }
+ break;
+ case LO_IND_IDLE_VISIBLE:
+ if (state) {
+ state->args.indicator_idle_visible = true;
+ }
+ break;
+ case LO_IND_RADIUS:
+ if (state) {
+ state->args.radius = strtol(optarg, NULL, 0);
+ }
+ break;
+ case LO_IND_THICKNESS:
+ if (state) {
+ state->args.thickness = strtol(optarg, NULL, 0);
+ }
+ break;
+ case LO_IND_X_POSITION:
+ if (state) {
+ state->args.override_indicator_x_position = true;
+ state->args.indicator_x_position = atoi(optarg);
+ }
+ break;
+ case LO_IND_Y_POSITION:
+ if (state) {
+ state->args.override_indicator_y_position = true;
+ state->args.indicator_y_position = atoi(optarg);
+ }
+ break;
+ case LO_IND_IMAGE:
+ if (state) {
+ state->indicator_image = load_background_image(optarg);
+ }
+ break;
+ case LO_INSIDE_COLOR:
+ if (state) {
+ state->args.colors.inside.input = parse_color(optarg);
+ }
+ break;
+ case LO_INSIDE_CLEAR_COLOR:
+ if (state) {
+ state->args.colors.inside.cleared = parse_color(optarg);
+ }
+ break;
+ case LO_INSIDE_CAPS_LOCK_COLOR:
+ if (state) {
+ state->args.colors.inside.caps_lock = parse_color(optarg);
+ }
+ break;
+ case LO_INSIDE_VER_COLOR:
+ if (state) {
+ state->args.colors.inside.verifying = parse_color(optarg);
+ }
+ break;
+ case LO_INSIDE_WRONG_COLOR:
+ if (state) {
+ state->args.colors.inside.wrong = parse_color(optarg);
+ }
+ break;
+ case LO_KEY_HL_COLOR:
+ if (state) {
+ state->args.colors.key_highlight = parse_color(optarg);
+ }
+ break;
+ case LO_LAYOUT_BG_COLOR:
+ if (state) {
+ state->args.colors.layout_background = parse_color(optarg);
+ }
+ break;
+ case LO_LAYOUT_BORDER_COLOR:
+ if (state) {
+ state->args.colors.layout_border = parse_color(optarg);
+ }
+ break;
+ case LO_LAYOUT_TXT_COLOR:
+ if (state) {
+ state->args.colors.layout_text = parse_color(optarg);
+ }
+ break;
+ case LO_LINE_COLOR:
+ if (state) {
+ state->args.colors.line.input = parse_color(optarg);
+ }
+ break;
+ case LO_LINE_CLEAR_COLOR:
+ if (state) {
+ state->args.colors.line.cleared = parse_color(optarg);
+ }
+ break;
+ case LO_LINE_CAPS_LOCK_COLOR:
+ if (state) {
+ state->args.colors.line.caps_lock = parse_color(optarg);
+ }
+ break;
+ case LO_LINE_VER_COLOR:
+ if (state) {
+ state->args.colors.line.verifying = parse_color(optarg);
+ }
+ break;
+ case LO_LINE_WRONG_COLOR:
+ if (state) {
+ state->args.colors.line.wrong = parse_color(optarg);
+ }
+ break;
+ case LO_RING_COLOR:
+ if (state) {
+ state->args.colors.ring.input = parse_color(optarg);
+ }
+ break;
+ case LO_RING_CLEAR_COLOR:
+ if (state) {
+ state->args.colors.ring.cleared = parse_color(optarg);
+ }
+ break;
+ case LO_RING_CAPS_LOCK_COLOR:
+ if (state) {
+ state->args.colors.ring.caps_lock = parse_color(optarg);
+ }
+ break;
+ case LO_RING_VER_COLOR:
+ if (state) {
+ state->args.colors.ring.verifying = parse_color(optarg);
+ }
+ break;
+ case LO_RING_WRONG_COLOR:
+ if (state) {
+ state->args.colors.ring.wrong = parse_color(optarg);
+ }
+ break;
+ case LO_SEP_COLOR:
+ if (state) {
+ state->args.colors.separator = parse_color(optarg);
+ }
+ break;
+ case LO_TEXT_COLOR:
+ if (state) {
+ state->args.colors.text.input = parse_color(optarg);
+ }
+ break;
+ case LO_TEXT_CLEAR:
+ if (state) {
+ free(state->args.text_cleared);
+ state->args.text_cleared = strdup(optarg);
+ }
+ break;
+ case LO_TEXT_CLEAR_COLOR:
+ if (state) {
+ state->args.colors.text.cleared = parse_color(optarg);
+ }
+ break;
+ case LO_TEXT_CAPS_LOCK:
+ if (state) {
+ free(state->args.text_caps_lock);
+ state->args.text_caps_lock = strdup(optarg);
+ }
+ break;
+ case LO_TEXT_CAPS_LOCK_COLOR:
+ if (state) {
+ state->args.colors.text.caps_lock = parse_color(optarg);
+ }
+ break;
+ case LO_TEXT_VER:
+ if (state) {
+ free(state->args.text_verifying);
+ state->args.text_verifying = strdup(optarg);
+ }
+ break;
+ case LO_TEXT_VER_COLOR:
+ if (state) {
+ state->args.colors.text.verifying = parse_color(optarg);
+ }
+ break;
+ case LO_TEXT_WRONG:
+ if (state) {
+ free(state->args.text_wrong);
+ state->args.text_wrong = strdup(optarg);
+ }
+ break;
+ case LO_TEXT_WRONG_COLOR:
+ if (state) {
+ state->args.colors.text.wrong = parse_color(optarg);
+ }
+ break;
+ case LO_EFFECT_BLUR:
+ if (state) {
+ state->args.effects = realloc(state->args.effects,
+ sizeof(*state->args.effects) * ++state->args.effects_count);
+ struct swaylock_effect *effect = &state->args.effects[state->args.effects_count - 1];
+ effect->tag = EFFECT_BLUR;
+ if (sscanf(optarg, "%dx%d", &effect->e.blur.radius, &effect->e.blur.times) != 2) {
+ swaylock_log(LOG_ERROR, "Invalid blur effect argument %s, ignoring", optarg);
+ state->args.effects_count -= 1;
+ }
+ }
+ break;
+ case LO_EFFECT_PIXELATE:
+ if (state) {
+ state->args.effects = realloc(state->args.effects,
+ sizeof(*state->args.effects) * ++state->args.effects_count);
+ struct swaylock_effect *effect = &state->args.effects[state->args.effects_count - 1];
+ effect->tag = EFFECT_PIXELATE;
+ effect->e.pixelate.factor = atoi(optarg);
+ }
+ break;
+ case LO_EFFECT_SCALE:
+ if (state) {
+ state->args.effects = realloc(state->args.effects,
+ sizeof(*state->args.effects) * ++state->args.effects_count);
+ struct swaylock_effect *effect = &state->args.effects[state->args.effects_count - 1];
+ effect->tag = EFFECT_SCALE;
+ if (sscanf(optarg, "%lf", &effect->e.scale) != 1) {
+ swaylock_log(LOG_ERROR, "Invalid scale effect argument %s, ignoring", optarg);
+ state->args.effects_count -= 1;
+ }
+ }
+ break;
+ case LO_EFFECT_GREYSCALE:
+ if (state) {
+ state->args.effects = realloc(state->args.effects,
+ sizeof(*state->args.effects) * ++state->args.effects_count);
+ struct swaylock_effect *effect = &state->args.effects[state->args.effects_count - 1];
+ effect->tag = EFFECT_GREYSCALE;
+ }
+ break;
+ case LO_EFFECT_VIGNETTE:
+ if (state) {
+ state->args.effects = realloc(state->args.effects,
+ sizeof(*state->args.effects) * ++state->args.effects_count);
+ struct swaylock_effect *effect = &state->args.effects[state->args.effects_count - 1];
+ effect->tag = EFFECT_VIGNETTE;
+ if (sscanf(optarg, "%lf:%lf", &effect->e.vignette.base, &effect->e.vignette.factor) != 2) {
+ swaylock_log(LOG_ERROR, "Invalid factor effect argument %s, ignoring", optarg);
+ state->args.effects_count -= 1;
+ }
+ }
+ break;
+ case LO_EFFECT_COMPOSE:
+ if (state) {
+ state->args.effects = realloc(state->args.effects,
+ sizeof(*state->args.effects) * ++state->args.effects_count);
+ struct swaylock_effect *effect = &state->args.effects[state->args.effects_count - 1];
+ effect->tag = EFFECT_COMPOSE;
+ parse_effect_compose(optarg, effect);
+ }
+ break;
+ case LO_EFFECT_CUSTOM:
+ if (state) {
+ state->args.effects = realloc(state->args.effects,
+ sizeof(*state->args.effects) * ++state->args.effects_count);
+ struct swaylock_effect *effect = &state->args.effects[state->args.effects_count - 1];
+ effect->tag = EFFECT_CUSTOM;
+ effect->e.custom = strdup(optarg);
+ }
+ break;
+ case LO_TIME_EFFECTS:
+ if (state) {
+ state->args.time_effects = true;
+ }
+ break;
+ case LO_INDICATOR:
+ if (state) {
+ state->args.indicator = true;
+ }
+ break;
+ case LO_CLOCK:
+ if (state) {
+ state->args.clock = true;
+ }
+ break;
+ case LO_TIMESTR:
+ if (state) {
+ free(state->args.timestr);
+ state->args.timestr = strdup(optarg);
+ }
+ break;
+ case LO_DATESTR:
+ if (state) {
+ free(state->args.datestr);
+ state->args.datestr = strdup(optarg);
+ }
+ break;
+ case LO_FADE_IN:
+ if (state) {
+ state->args.fade_in = parse_seconds(optarg);
+ }
+ break;
+ case LO_SUBMIT_ON_TOUCH:
+ if (state) {
+ state->args.password_submit_on_touch = true;
+ }
+ break;
+ case LO_GRACE:
+ if (state) {
+ state->args.password_grace_period = parse_seconds(optarg);
+ }
+ break;
+ case LO_GRACE_NO_MOUSE:
+ if (state) {
+ state->args.password_grace_no_mouse = true;
+ }
+ break;
+ case LO_GRACE_NO_TOUCH:
+ if (state) {
+ state->args.password_grace_no_touch = true;
+ }
+ break;
+ default:
+ fprintf(stderr, "%s", usage);
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+static bool file_exists(const char *path) {
+ return path && access(path, R_OK) != -1;
+}
+
+static char *get_config_path(void) {
+ static const char *config_paths[] = {
+ "$HOME/.swaylock/config",
+ "$XDG_CONFIG_HOME/swaylock/config",
+ SYSCONFDIR "/swaylock/config",
+ };
+
+ char *config_home = getenv("XDG_CONFIG_HOME");
+ if (!config_home || config_home[0] == '\0') {
+ config_paths[1] = "$HOME/.config/swaylock/config";
+ }
+
+ wordexp_t p;
+ char *path;
+ for (size_t i = 0; i < sizeof(config_paths) / sizeof(char *); ++i) {
+ if (wordexp(config_paths[i], &p, 0) == 0) {
+ path = strdup(p.we_wordv[0]);
+ wordfree(&p);
+ if (file_exists(path)) {
+ return path;
+ }
+ free(path);
+ }
+ }
+
+ return NULL;
+}
+
+static int load_config(char *path, struct swaylock_state *state,
+ enum line_mode *line_mode) {
+ FILE *config = fopen(path, "r");
+ if (!config) {
+ swaylock_log(LOG_ERROR, "Failed to read config. Running without it.");
+ return 0;
+ }
+ char *line = NULL;
+ size_t line_size = 0;
+ ssize_t nread;
+ int line_number = 0;
+ int result = 0;
+ while ((nread = getline(&line, &line_size, config)) != -1) {
+ line_number++;
+
+ if (line[nread - 1] == '\n') {
+ line[--nread] = '\0';
+ }
+
+ if (!*line || line[0] == '#') {
+ continue;
+ }
+
+ swaylock_log(LOG_DEBUG, "Config Line #%d: %s", line_number, line);
+ char *flag = malloc(nread + 3);
+ if (flag == NULL) {
+ free(line);
+ fclose(config);
+ swaylock_log(LOG_ERROR, "Failed to allocate memory");
+ return 0;
+ }
+ sprintf(flag, "--%s", line);
+ char *argv[] = {"swaylock", flag};
+ result = parse_options(2, argv, state, line_mode, NULL);
+ free(flag);
+ if (result != 0) {
+ break;
+ }
+ }
+ free(line);
+ fclose(config);
+ return 0;
+}
+
+static struct swaylock_state state;
+
+static void display_in(int fd, short mask, void *data) {
+ if (wl_display_dispatch(state.display) == -1) {
+ state.run_display = false;
+ }
+}
+
+static void end_allow_fade_period(void *data) {
+ struct swaylock_state *state = data;
+ if (state->args.allow_fade) {
+ state->args.allow_fade = false;
+ }
+}
+
+static void end_grace_period(void *data) {
+ struct swaylock_state *state = data;
+ if (state->auth_state == AUTH_STATE_GRACE) {
+ state->auth_state = AUTH_STATE_IDLE;
+ }
+}
+
+static void comm_in(int fd, short mask, void *data) {
+ if (read_comm_reply()) {
+ // Authentication succeeded
+ state.run_display = false;
+ } else {
+ state.auth_state = AUTH_STATE_INVALID;
+ schedule_indicator_clear(&state);
+ ++state.failed_attempts;
+ damage_state(&state);
+ }
+}
+
+static void timer_render(void *data) {
+ struct swaylock_state *state = (struct swaylock_state *)data;
+ damage_state(state);
+ loop_add_timer(state->eventloop, 1000, timer_render, state);
+}
+
+static void term_in(int fd, short mask, void *data) {
+ state.run_display = false;
+}
+
+// Check for --debug 'early' we also apply the correct loglevel
+// to the forked child, without having to first proces all of the
+// configuration (including from file) before forking and (in the
+// case of the shadow backend) dropping privileges
+void log_init(int argc, char **argv) {
+ static struct option long_options[] = {
+ {"debug", no_argument, NULL, 'd'},
+ {0, 0, 0, 0}
+ };
+ int c;
+ optind = 1;
+ while (1) {
+ int opt_idx = 0;
+ c = getopt_long(argc, argv, "-:d", long_options, &opt_idx);
+ if (c == -1) {
+ break;
+ }
+ switch (c) {
+ case 'd':
+ swaylock_log_init(LOG_DEBUG);
+ return;
+ }
+ }
+ swaylock_log_init(LOG_ERROR);
+}
+
+int main(int argc, char **argv) {
+ log_init(argc, argv);
+ initialize_pw_backend(argc, argv);
+ srand(time(NULL));
+
+ enum line_mode line_mode = LM_LINE;
+ state.failed_attempts = 0;
+ state.indicator_dirty = false;
+ state.args = (struct swaylock_args){
+ .mode = BACKGROUND_MODE_FILL,
+ .font = strdup("sans-serif"),
+ .font_size = 0,
+ .radius = 75,
+ .thickness = 10,
+ .indicator_x_position = 0,
+ .indicator_y_position = 0,
+ .override_indicator_x_position = false,
+ .override_indicator_y_position = false,
+ .ignore_empty = false,
+ .show_indicator = true,
+ .show_caps_lock_indicator = false,
+ .show_caps_lock_text = true,
+ .show_keyboard_layout = false,
+ .hide_keyboard_layout = false,
+ .show_failed_attempts = false,
+ .indicator_idle_visible = false,
+
+ .screenshots = false,
+ .effects = NULL,
+ .effects_count = 0,
+ .indicator = false,
+ .clock = false,
+ .timestr = strdup("%T"),
+ .datestr = strdup("%a, %x"),
+ .allow_fade = true,
+ .password_grace_period = 0,
+
+ .text_cleared = strdup("Cleared"),
+ .text_caps_lock = strdup("Caps Lock"),
+ .text_verifying = strdup("Verifying"),
+ .text_wrong = strdup("Wrong"),
+ };
+ wl_list_init(&state.images);
+ set_default_colors(&state.args.colors);
+
+ char *config_path = NULL;
+ int result = parse_options(argc, argv, NULL, NULL, &config_path);
+ if (result != 0) {
+ free(config_path);
+ return result;
+ }
+ if (!config_path) {
+ config_path = get_config_path();
+ }
+
+ if (config_path) {
+ swaylock_log(LOG_DEBUG, "Found config at %s", config_path);
+ int config_status = load_config(config_path, &state, &line_mode);
+ free(config_path);
+ if (config_status != 0) {
+ free(state.args.font);
+ return config_status;
+ }
+ }
+
+ if (argc > 1) {
+ swaylock_log(LOG_DEBUG, "Parsing CLI Args");
+ int result = parse_options(argc, argv, &state, &line_mode, NULL);
+ if (result != 0) {
+ free(state.args.font);
+ return result;
+ }
+ }
+
+ if (line_mode == LM_INSIDE) {
+ state.args.colors.line = state.args.colors.inside;
+ } else if (line_mode == LM_RING) {
+ state.args.colors.line = state.args.colors.ring;
+ }
+
+ if (state.args.password_grace_period > 0) {
+ state.auth_state = AUTH_STATE_GRACE;
+ }
+
+ state.password.len = 0;
+ state.password.buffer_len = 1024;
+ state.password.buffer = password_buffer_create(state.password.buffer_len);
+ if (!state.password.buffer) {
+ return EXIT_FAILURE;
+ }
+
+ if (pipe(sigusr_fds) != 0) {
+ swaylock_log(LOG_ERROR, "Failed to pipe");
+ return 1;
+ }
+
+ wl_list_init(&state.surfaces);
+ state.xkb.context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
+ state.display = wl_display_connect(NULL);
+ if (!state.display) {
+ free(state.args.font);
+ swaylock_log(LOG_ERROR, "Unable to connect to the compositor. "
+ "If your compositor is running, check or set the "
+ "WAYLAND_DISPLAY environment variable.");
+ return EXIT_FAILURE;
+ }
+
+ struct wl_registry *registry = wl_display_get_registry(state.display);
+ wl_registry_add_listener(registry, ®istry_listener, &state);
+ wl_display_roundtrip(state.display);
+
+ if (!state.compositor) {
+ swaylock_log(LOG_ERROR, "Missing wl_compositor");
+ return 1;
+ }
+
+ if (!state.subcompositor) {
+ swaylock_log(LOG_ERROR, "Missing wl_subcompositor");
+ return 1;
+ }
+
+ if (!state.shm) {
+ swaylock_log(LOG_ERROR, "Missing wl_shm");
+ return 1;
+ }
+
+ struct swaylock_surface *surface;
+ // Enumerate all outputs first so that screenshots can be obtained
+ // before ext_session_lock_manager_v1_lock(). After the screen is locked,
+ // no screenshot can be retrieved because normal rendering is blocked.
+ wl_list_for_each(surface, &state.surfaces, link) {
+ surface->events_pending += 1;
+ };
+
+ wl_list_for_each(surface, &state.surfaces, link) {
+ while (surface->events_pending > 0) {
+ wl_display_roundtrip(state.display);
+ }
+ }
+
+ // Must daemonize before we run any effects, since effects use openmp
+ int daemonfd;
+ if (state.args.daemonize) {
+ wl_display_roundtrip(state.display);
+ daemonfd = daemonize_start();
+ }
+
+ // Need to apply effects to all images *before* requesting ext_session_lock_v1
+ // Otherwise, the screen would be blank while the effects are being applied.
+ struct swaylock_image *iter_image, *temp;
+ wl_list_for_each_safe(iter_image, temp, &state.images, link) {
+ iter_image->cairo_surface = apply_effects(
+ iter_image->cairo_surface, &state, 1);
+ }
+
+ if (state.ext_session_lock_manager_v1) {
+ swaylock_log(LOG_DEBUG, "Using ext-session-lock-v1");
+ state.ext_session_lock_v1 = ext_session_lock_manager_v1_lock(state.ext_session_lock_manager_v1);
+ ext_session_lock_v1_add_listener(state.ext_session_lock_v1,
+ &ext_session_lock_v1_listener, &state);
+ } else if (state.layer_shell && state.input_inhibit_manager) {
+ swaylock_log(LOG_DEBUG, "Using wlr-layer-shell + wlr-input-inhibitor");
+ zwlr_input_inhibit_manager_v1_get_inhibitor(state.input_inhibit_manager);
+ } else {
+ swaylock_log(LOG_ERROR, "Missing ext-session-lock-v1, wlr-layer-shell "
+ "and wlr-input-inhibitor");
+ return 1;
+ }
+
+ if (wl_display_roundtrip(state.display) == -1) {
+ free(state.args.font);
+ if (state.input_inhibit_manager) {
+ swaylock_log(LOG_ERROR, "Exiting - failed to inhibit input:"
+ " is another lockscreen already running?");
+ return 2;
+ }
+ return 1;
+ }
+
+ wl_list_for_each(surface, &state.surfaces, link) {
+ create_surface(surface);
+ }
+
+ wl_list_for_each(surface, &state.surfaces, link) {
+ while (surface->events_pending > 0) {
+ wl_display_roundtrip(state.display);
+ }
+ }
+
+ state.eventloop = loop_create();
+ loop_add_fd(state.eventloop, wl_display_get_fd(state.display), POLLIN,
+ display_in, NULL);
+
+ loop_add_fd(state.eventloop, get_comm_reply_fd(), POLLIN, comm_in, NULL);
+
+ loop_add_fd(state.eventloop, sigusr_fds[0], POLLIN, term_in, NULL);
+ signal(SIGUSR1, do_sigusr);
+
+ loop_add_timer(state.eventloop, 1000, timer_render, &state);
+
+ if (state.args.fade_in) {
+ loop_add_timer(state.eventloop, state.args.fade_in, end_allow_fade_period, &state);
+ }
+
+ if (state.args.daemonize && state.args.fade_in) {
+ loop_add_timer(state.eventloop, state.args.fade_in + 500, daemonize_done, &daemonfd);
+ } else if (state.args.daemonize) {
+ daemonize_done(&daemonfd);
+ }
+
+ if (state.args.password_grace_period > 0) {
+ loop_add_timer(state.eventloop, state.args.password_grace_period, end_grace_period, &state);
+ }
+
+ // Re-draw once to start the draw loop
+ damage_state(&state);
+
+ state.run_display = true;
+ while (state.run_display) {
+ errno = 0;
+ if (wl_display_flush(state.display) == -1 && errno != EAGAIN) {
+ break;
+ }
+ loop_poll(state.eventloop);
+ }
+
+ if (state.args.daemonize && state.args.fade_in) {
+ daemonize_done(&daemonfd); // In case we exit before --fade-in timeout
+ }
+ if (state.ext_session_lock_v1) {
+ ext_session_lock_v1_unlock_and_destroy(state.ext_session_lock_v1);
+ wl_display_roundtrip(state.display);
+ }
+
+ free(state.args.font);
+ return 0;
+}
swaylock-mod/meson.build
@@ -0,0 +1,131 @@
+project(
+ 'swaylock',
+ 'c',
+ version: '1.7.0.0',
+ license: 'MIT',
+ meson_version: '>=0.59.0',
+ default_options: [
+ 'c_std=c11',
+ 'warning_level=2',
+ 'werror=true',
+ ],
+)
+
+add_project_arguments(
+ [
+ '-Wno-unused-parameter',
+ '-Wno-unused-result',
+ '-Wundef',
+ '-Wvla',
+ ],
+ language: 'c',
+)
+
+cc = meson.get_compiler('c')
+
+if get_option('sse')
+ add_project_arguments('-DUSE_SSE', language: 'c')
+endif
+
+wayland_client = dependency('wayland-client', version: '>=1.20.0')
+wayland_protos = dependency('wayland-protocols', version: '>=1.25', fallback: 'wayland-protocols')
+wayland_scanner = dependency('wayland-scanner', version: '>=1.15.0', native: true)
+xkbcommon = dependency('xkbcommon')
+cairo = dependency('cairo')
+omp = dependency('openmp')
+gdk_pixbuf = dependency('gdk-pixbuf-2.0', required: get_option('gdk-pixbuf'))
+libpam = cc.find_library('pam', required: get_option('pam'))
+crypt = cc.find_library('crypt', required: not libpam.found())
+math = cc.find_library('m')
+rt = cc.find_library('rt')
+dl = cc.find_library('dl')
+
+wayland_scanner_prog = find_program(wayland_scanner.get_variable('wayland_scanner'), native: true)
+
+version = meson.project_version()
+wl_protocol_dir = wayland_protos.get_variable('pkgdatadir')
+
+wayland_scanner_code = generator(
+ wayland_scanner_prog,
+ output: '@BASENAME@-protocol.c',
+ arguments: ['private-code', '@INPUT@', '@OUTPUT@'],
+)
+
+wayland_scanner_client = generator(
+ wayland_scanner_prog,
+ output: '@BASENAME@-client-protocol.h',
+ arguments: ['client-header', '@INPUT@', '@OUTPUT@'],
+)
+
+client_protocols = [
+ wl_protocol_dir / 'stable/xdg-shell/xdg-shell.xml',
+ wl_protocol_dir / 'staging/ext-session-lock/ext-session-lock-v1.xml',
+ 'wlr-layer-shell-unstable-v1.xml',
+ 'wlr-input-inhibitor-unstable-v1.xml',
+ 'wlr-screencopy-unstable-v1.xml',
+]
+
+protos_src = []
+foreach xml : client_protocols
+ protos_src += wayland_scanner_code.process(xml)
+ protos_src += wayland_scanner_client.process(xml)
+endforeach
+
+conf_data = configuration_data()
+conf_data.set_quoted('SYSCONFDIR', get_option('prefix') / get_option('sysconfdir'))
+conf_data.set_quoted('SWAYLOCK_VERSION', version)
+conf_data.set10('HAVE_GDK_PIXBUF', gdk_pixbuf.found())
+
+subdir('include')
+
+dependencies = [
+ cairo,
+ gdk_pixbuf,
+ math,
+ rt,
+ dl,
+ xkbcommon,
+ wayland_client,
+ omp
+]
+
+sources = [
+ 'background-image.c',
+ 'cairo.c',
+ 'comm.c',
+ 'log.c',
+ 'loop.c',
+ 'main.c',
+ 'password.c',
+ 'password-buffer.c',
+ 'pool-buffer.c',
+ 'render.c',
+ 'seat.c',
+ 'unicode.c',
+ 'effects.c',
+ 'fade.c',
+]
+
+if libpam.found()
+ sources += ['pam.c']
+ dependencies += [libpam]
+else
+ warning('The swaylock binary must be setuid when compiled without libpam')
+ warning('You must do this manually post-install: chmod a+s /path/to/swaylock')
+ sources += ['shadow.c']
+ dependencies += [crypt]
+endif
+
+swaylock_inc = include_directories('include')
+
+executable('swaylock',
+ sources + protos_src,
+ include_directories: [swaylock_inc],
+ dependencies: dependencies,
+ install: true
+)
+
+install_data(
+ 'pam/swaylock',
+ install_dir: get_option('sysconfdir') / 'pam.d'
+)
swaylock-mod/meson_options.txt
@@ -0,0 +1,3 @@
+option('pam', type: 'feature', value: 'auto', description: 'Use PAM instead of shadow')
+option('gdk-pixbuf', type: 'feature', value: 'auto', description: 'Enable support for more image formats')
+option('sse', type: 'boolean', value: true, description: 'Use SSE instructions where possible')
swaylock-mod/pam.c
@@ -0,0 +1,122 @@
+#define _POSIX_C_SOURCE 200809L
+#include <pwd.h>
+#include <security/pam_appl.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include "comm.h"
+#include "log.h"
+#include "password-buffer.h"
+#include "swaylock.h"
+
+static char *pw_buf = NULL;
+
+void initialize_pw_backend(int argc, char **argv) {
+ if (getuid() != geteuid() || getgid() != getegid()) {
+ swaylock_log(LOG_ERROR,
+ "swaylock is setuid, but was compiled with the PAM"
+ " backend. Run 'chmod a-s %s' to fix. Aborting.", argv[0]);
+ exit(EXIT_FAILURE);
+ }
+ if (!spawn_comm_child()) {
+ exit(EXIT_FAILURE);
+ }
+}
+
+static int handle_conversation(int num_msg, const struct pam_message **msg,
+ struct pam_response **resp, void *data) {
+ /* PAM expects an array of responses, one for each message */
+ struct pam_response *pam_reply =
+ calloc(num_msg, sizeof(struct pam_response));
+ if (pam_reply == NULL) {
+ swaylock_log(LOG_ERROR, "Allocation failed");
+ return PAM_ABORT;
+ }
+ *resp = pam_reply;
+ for (int i = 0; i < num_msg; ++i) {
+ switch (msg[i]->msg_style) {
+ case PAM_PROMPT_ECHO_OFF:
+ case PAM_PROMPT_ECHO_ON:
+ pam_reply[i].resp = strdup(pw_buf); // PAM clears and frees this
+ if (pam_reply[i].resp == NULL) {
+ swaylock_log(LOG_ERROR, "Allocation failed");
+ return PAM_ABORT;
+ }
+ break;
+ case PAM_ERROR_MSG:
+ case PAM_TEXT_INFO:
+ break;
+ }
+ }
+ return PAM_SUCCESS;
+}
+
+static const char *get_pam_auth_error(int pam_status) {
+ switch (pam_status) {
+ case PAM_AUTH_ERR:
+ return "invalid credentials";
+ case PAM_CRED_INSUFFICIENT:
+ return "swaylock cannot authenticate users; check /etc/pam.d/swaylock "
+ "has been installed properly";
+ case PAM_AUTHINFO_UNAVAIL:
+ return "authentication information unavailable";
+ case PAM_MAXTRIES:
+ return "maximum number of authentication tries exceeded";
+ default:;
+ static char msg[64];
+ snprintf(msg, sizeof(msg), "unknown error (%d)", pam_status);
+ return msg;
+ }
+}
+
+void run_pw_backend_child(void) {
+ struct passwd *passwd = getpwuid(getuid());
+ char *username = passwd->pw_name;
+
+ const struct pam_conv conv = {
+ .conv = handle_conversation,
+ .appdata_ptr = NULL,
+ };
+ pam_handle_t *auth_handle = NULL;
+ if (pam_start("swaylock", username, &conv, &auth_handle) != PAM_SUCCESS) {
+ swaylock_log(LOG_ERROR, "pam_start failed");
+ exit(EXIT_FAILURE);
+ }
+
+ /* This code does not run as root */
+ swaylock_log(LOG_DEBUG, "Prepared to authorize user %s", username);
+
+ int pam_status = PAM_SUCCESS;
+ while (1) {
+ ssize_t size = read_comm_request(&pw_buf);
+ if (size < 0) {
+ exit(EXIT_FAILURE);
+ } else if (size == 0) {
+ break;
+ }
+
+ int pam_status = pam_authenticate(auth_handle, 0);
+ password_buffer_destroy(pw_buf, size);
+ pw_buf = NULL;
+
+ bool success = pam_status == PAM_SUCCESS;
+ if (!success) {
+ swaylock_log(LOG_ERROR, "pam_authenticate failed: %s",
+ get_pam_auth_error(pam_status));
+ }
+
+ if (!write_comm_reply(success)) {
+ exit(EXIT_FAILURE);
+ }
+ }
+
+ pam_setcred(auth_handle, PAM_REFRESH_CRED);
+
+ if (pam_end(auth_handle, pam_status) != PAM_SUCCESS) {
+ swaylock_log(LOG_ERROR, "pam_end failed");
+ exit(EXIT_FAILURE);
+ }
+
+ exit((pam_status == PAM_SUCCESS) ? EXIT_SUCCESS : EXIT_FAILURE);
+}
swaylock-mod/password-buffer.c
@@ -0,0 +1,81 @@
+#define _POSIX_C_SOURCE 200809L
+#include "password-buffer.h"
+#include "log.h"
+#include "swaylock.h"
+#include <stdlib.h>
+#include <errno.h>
+#include <unistd.h>
+#include <limits.h>
+#include <sys/mman.h>
+
+static bool mlock_supported = true;
+static long int page_size = 0;
+
+static long int get_page_size() {
+ if (!page_size) {
+ page_size = sysconf(_SC_PAGESIZE);
+ }
+ return page_size;
+}
+
+// password_buffer_lock expects addr to be page alligned
+static bool password_buffer_lock(char *addr, size_t size) {
+ int retries = 5;
+ while (mlock(addr, size) != 0 && retries > 0) {
+ switch (errno) {
+ case EAGAIN:
+ retries--;
+ if (retries == 0) {
+ swaylock_log(LOG_ERROR, "mlock() supported but failed too often.");
+ return false;
+ }
+ break;
+ case EPERM:
+ swaylock_log_errno(LOG_ERROR, "Unable to mlock() password memory: Unsupported!");
+ mlock_supported = false;
+ return true;
+ default:
+ swaylock_log_errno(LOG_ERROR, "Unable to mlock() password memory.");
+ return false;
+ }
+ return false;
+ }
+
+ return true;
+}
+
+// password_buffer_unlock expects addr to be page alligned
+static bool password_buffer_unlock(char *addr, size_t size) {
+ if (mlock_supported) {
+ if (munlock(addr, size) != 0) {
+ swaylock_log_errno(LOG_ERROR, "Unable to munlock() password memory.");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+char *password_buffer_create(size_t size) {
+ void *buffer;
+ int result = posix_memalign(&buffer, get_page_size(), size);
+ if (result) {
+ //posix_memalign doesn't set errno according to the man page
+ errno = result;
+ swaylock_log_errno(LOG_ERROR, "failed to alloc password buffer");
+ return NULL;
+ }
+
+ if (!password_buffer_lock(buffer, size)) {
+ free(buffer);
+ return NULL;
+ }
+
+ return buffer;
+}
+
+void password_buffer_destroy(char *buffer, size_t size) {
+ clear_buffer(buffer, size);
+ password_buffer_unlock(buffer, size);
+ free(buffer);
+}
swaylock-mod/password.c
@@ -0,0 +1,190 @@
+#include <assert.h>
+#include <errno.h>
+#include <pwd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <xkbcommon/xkbcommon.h>
+#include "comm.h"
+#include "log.h"
+#include "loop.h"
+#include "seat.h"
+#include "swaylock.h"
+#include "unicode.h"
+
+void clear_buffer(char *buf, size_t size) {
+ // Use volatile keyword so so compiler can't optimize this out.
+ volatile char *buffer = buf;
+ volatile char zero = '\0';
+ for (size_t i = 0; i < size; ++i) {
+ buffer[i] = zero;
+ }
+}
+
+void clear_password_buffer(struct swaylock_password *pw) {
+ clear_buffer(pw->buffer, pw->buffer_len);
+ pw->len = 0;
+}
+
+static bool backspace(struct swaylock_password *pw) {
+ if (pw->len != 0) {
+ pw->len -= utf8_last_size(pw->buffer);
+ pw->buffer[pw->len] = 0;
+ return true;
+ }
+ return false;
+}
+
+static void append_ch(struct swaylock_password *pw, uint32_t codepoint) {
+ size_t utf8_size = utf8_chsize(codepoint);
+ if (pw->len + utf8_size + 1 >= pw->buffer_len) {
+ // TODO: Display error
+ return;
+ }
+ utf8_encode(&pw->buffer[pw->len], codepoint);
+ pw->buffer[pw->len + utf8_size] = 0;
+ pw->len += utf8_size;
+}
+
+static void clear_indicator(void *data) {
+ struct swaylock_state *state = data;
+ state->clear_indicator_timer = NULL;
+ state->auth_state = AUTH_STATE_IDLE;
+ damage_state(state);
+}
+
+void schedule_indicator_clear(struct swaylock_state *state) {
+ if (state->clear_indicator_timer) {
+ loop_remove_timer(state->eventloop, state->clear_indicator_timer);
+ }
+ state->clear_indicator_timer = loop_add_timer(
+ state->eventloop, 3000, clear_indicator, state);
+}
+
+static void clear_password(void *data) {
+ struct swaylock_state *state = data;
+ state->clear_password_timer = NULL;
+ state->auth_state = AUTH_STATE_CLEAR;
+ clear_password_buffer(&state->password);
+ damage_state(state);
+ schedule_indicator_clear(state);
+}
+
+static void schedule_password_clear(struct swaylock_state *state) {
+ if (state->clear_password_timer) {
+ loop_remove_timer(state->eventloop, state->clear_password_timer);
+ }
+ state->clear_password_timer = loop_add_timer(
+ state->eventloop, 10000, clear_password, state);
+}
+
+static void submit_password(struct swaylock_state *state) {
+ if (state->args.ignore_empty && state->password.len == 0) {
+ return;
+ }
+
+ state->auth_state = AUTH_STATE_VALIDATING;
+
+ if (!write_comm_request(&state->password)) {
+ state->auth_state = AUTH_STATE_INVALID;
+ schedule_indicator_clear(state);
+ }
+
+ damage_state(state);
+}
+
+void swaylock_handle_mouse(struct swaylock_state *state) {
+ if (state->auth_state == AUTH_STATE_GRACE && !state->args.password_grace_no_mouse) {
+ state->run_display = false;
+ }
+}
+
+void swaylock_handle_touch(struct swaylock_state *state) {
+ if (state->auth_state == AUTH_STATE_GRACE && !state->args.password_grace_no_touch) {
+ state->run_display = false;
+ } else if (state->auth_state != AUTH_STATE_VALIDATING && state->args.password_submit_on_touch) {
+ submit_password(state);
+ }
+}
+
+void swaylock_handle_key(struct swaylock_state *state,
+ xkb_keysym_t keysym, uint32_t codepoint) {
+ // Authentication not needed
+ if (state->auth_state == AUTH_STATE_GRACE) {
+ state->run_display = false;
+ return;
+ }
+ // Ignore input events if validating
+ if (state->auth_state == AUTH_STATE_VALIDATING) {
+ return;
+ }
+
+ switch (keysym) {
+ case XKB_KEY_KP_Enter: /* fallthrough */
+ case XKB_KEY_Return:
+ submit_password(state);
+ break;
+ case XKB_KEY_Delete:
+ case XKB_KEY_BackSpace:
+ if (backspace(&state->password)) {
+ state->auth_state = AUTH_STATE_BACKSPACE;
+ } else {
+ state->auth_state = AUTH_STATE_CLEAR;
+ }
+ state->indicator_dirty = true;
+ damage_state(state);
+ schedule_indicator_clear(state);
+ schedule_password_clear(state);
+ break;
+ case XKB_KEY_Escape:
+ clear_password_buffer(&state->password);
+ state->auth_state = AUTH_STATE_CLEAR;
+ state->indicator_dirty = true;
+ schedule_indicator_clear(state);
+ break;
+ case XKB_KEY_Caps_Lock:
+ case XKB_KEY_Shift_L:
+ case XKB_KEY_Shift_R:
+ case XKB_KEY_Control_L:
+ case XKB_KEY_Control_R:
+ case XKB_KEY_Meta_L:
+ case XKB_KEY_Meta_R:
+ case XKB_KEY_Alt_L:
+ case XKB_KEY_Alt_R:
+ case XKB_KEY_Super_L:
+ case XKB_KEY_Super_R:
+ state->auth_state = AUTH_STATE_INPUT_NOP;
+ damage_state(state);
+ schedule_indicator_clear(state);
+ schedule_password_clear(state);
+ break;
+ case XKB_KEY_m: /* fallthrough */
+ case XKB_KEY_d:
+ case XKB_KEY_j:
+ if (state->xkb.control) {
+ submit_password(state);
+ break;
+ }
+ // fallthrough
+ case XKB_KEY_c: /* fallthrough */
+ case XKB_KEY_u:
+ if (state->xkb.control) {
+ clear_password_buffer(&state->password);
+ state->auth_state = AUTH_STATE_CLEAR;
+ damage_state(state);
+ schedule_indicator_clear(state);
+ break;
+ }
+ // fallthrough
+ default:
+ if (codepoint) {
+ append_ch(&state->password, codepoint);
+ state->auth_state = AUTH_STATE_INPUT;
+ state->indicator_dirty = true;
+ damage_state(state);
+ schedule_indicator_clear(state);
+ schedule_password_clear(state);
+ }
+ break;
+ }
+}
swaylock-mod/pool-buffer.c
@@ -0,0 +1,127 @@
+#define _POSIX_C_SOURCE 200809L
+#include <assert.h>
+#include <cairo/cairo.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <time.h>
+#include <unistd.h>
+#include <wayland-client.h>
+#include "pool-buffer.h"
+
+static int anonymous_shm_open(void) {
+ int retries = 100;
+
+ do {
+ // try a probably-unique name
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ pid_t pid = getpid();
+ char name[50];
+ snprintf(name, sizeof(name), "/swaylock-%x-%x",
+ (unsigned int)pid, (unsigned int)ts.tv_nsec);
+
+ // shm_open guarantees that O_CLOEXEC is set
+ int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (fd >= 0) {
+ shm_unlink(name);
+ return fd;
+ }
+
+ --retries;
+ } while (retries > 0 && errno == EEXIST);
+
+ return -1;
+}
+
+static void buffer_release(void *data, struct wl_buffer *wl_buffer) {
+ struct pool_buffer *buffer = data;
+ buffer->busy = false;
+}
+
+static const struct wl_buffer_listener buffer_listener = {
+ .release = buffer_release
+};
+
+static struct pool_buffer *create_buffer(struct wl_shm *shm,
+ struct pool_buffer *buf, int32_t width, int32_t height,
+ uint32_t format) {
+ uint32_t stride = width * 4;
+ size_t size = stride * height;
+
+ void *data = NULL;
+ if (size > 0) {
+ int fd = anonymous_shm_open();
+ if (fd == -1) {
+ return NULL;
+ }
+ if (ftruncate(fd, size) < 0) {
+ close(fd);
+ return NULL;
+ }
+ data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+ struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, size);
+ buf->buffer = wl_shm_pool_create_buffer(pool, 0,
+ width, height, stride, format);
+ wl_buffer_add_listener(buf->buffer, &buffer_listener, buf);
+ wl_shm_pool_destroy(pool);
+ close(fd);
+ }
+
+ buf->size = size;
+ buf->width = width;
+ buf->height = height;
+ buf->data = data;
+ buf->surface = cairo_image_surface_create_for_data(data,
+ CAIRO_FORMAT_ARGB32, width, height, stride);
+ buf->cairo = cairo_create(buf->surface);
+ return buf;
+}
+
+void destroy_buffer(struct pool_buffer *buffer) {
+ if (buffer->buffer) {
+ wl_buffer_destroy(buffer->buffer);
+ }
+ if (buffer->cairo) {
+ cairo_destroy(buffer->cairo);
+ }
+ if (buffer->surface) {
+ cairo_surface_destroy(buffer->surface);
+ }
+ if (buffer->data) {
+ munmap(buffer->data, buffer->size);
+ }
+ memset(buffer, 0, sizeof(struct pool_buffer));
+}
+
+struct pool_buffer *get_next_buffer(struct wl_shm *shm,
+ struct pool_buffer pool[static 2], uint32_t width, uint32_t height) {
+ struct pool_buffer *buffer = NULL;
+
+ for (size_t i = 0; i < 2; ++i) {
+ if (pool[i].busy) {
+ continue;
+ }
+ buffer = &pool[i];
+ }
+
+ if (!buffer) {
+ return NULL;
+ }
+
+ if (buffer->width != width || buffer->height != height) {
+ destroy_buffer(buffer);
+ }
+
+ if (!buffer->buffer) {
+ if (!create_buffer(shm, buffer, width, height,
+ WL_SHM_FORMAT_ARGB8888)) {
+ return NULL;
+ }
+ }
+ buffer->busy = true;
+ return buffer;
+}
swaylock-mod/render.c
@@ -0,0 +1,512 @@
+#include <math.h>
+#include <stdlib.h>
+#include <time.h>
+#include <locale.h>
+#include <wayland-client.h>
+#include "cairo.h"
+#include "background-image.h"
+#include "swaylock.h"
+
+// glib might or might not have already defined MIN,
+// depending on whether we have pixbuf or not...
+#ifndef MIN
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
+#endif
+
+#define M_PI 3.14159265358979323846
+const float TYPE_INDICATOR_RANGE = M_PI / 3.0f;
+const float TYPE_INDICATOR_BORDER_THICKNESS = M_PI / 128.0f;
+
+static void set_color_for_state(cairo_t *cairo, struct swaylock_state *state,
+ struct swaylock_colorset *colorset) {
+ if (state->auth_state == AUTH_STATE_VALIDATING) {
+ cairo_set_source_u32(cairo, colorset->verifying);
+ } else if (state->auth_state == AUTH_STATE_INVALID) {
+ cairo_set_source_u32(cairo, colorset->wrong);
+ } else if (state->auth_state == AUTH_STATE_CLEAR) {
+ cairo_set_source_u32(cairo, colorset->cleared);
+ } else {
+ if (state->xkb.caps_lock && state->args.show_caps_lock_indicator) {
+ cairo_set_source_u32(cairo, colorset->caps_lock);
+ } else if (state->xkb.caps_lock && !state->args.show_caps_lock_indicator &&
+ state->args.show_caps_lock_text) {
+ uint32_t inputtextcolor = state->args.colors.text.input;
+ state->args.colors.text.input = state->args.colors.text.caps_lock;
+ cairo_set_source_u32(cairo, colorset->input);
+ state->args.colors.text.input = inputtextcolor;
+ } else {
+ cairo_set_source_u32(cairo, colorset->input);
+ }
+ }
+}
+
+static void timetext(struct swaylock_surface *surface, char **tstr, char **dstr) {
+ static char dbuf[256];
+ static char tbuf[256];
+
+ // Use user's locale for strftime calls
+ char *prevloc = setlocale(LC_TIME, NULL);
+ setlocale(LC_TIME, "");
+
+ time_t t = time(NULL);
+ struct tm *tm = localtime(&t);
+
+ if (surface->state->args.timestr[0]) {
+ strftime(tbuf, sizeof(tbuf), surface->state->args.timestr, tm);
+ *tstr = tbuf;
+ } else {
+ *tstr = NULL;
+ }
+
+ if (surface->state->args.datestr[0]) {
+ strftime(dbuf, sizeof(dbuf), surface->state->args.datestr, tm);
+ *dstr = dbuf;
+ } else {
+ *dstr = NULL;
+ }
+
+ // Set it back, so we don't break stuff
+ setlocale(LC_TIME, prevloc);
+}
+
+void render_frame_background(struct swaylock_surface *surface, bool commit) {
+ struct swaylock_state *state = surface->state;
+
+ int buffer_width = surface->width * surface->scale;
+ int buffer_height = surface->height * surface->scale;
+ if (buffer_width == 0 || buffer_height == 0) {
+ return; // not yet configured
+ }
+
+ struct pool_buffer *buffer = get_next_buffer(state->shm,
+ surface->buffers, buffer_width, buffer_height);
+ if (buffer == NULL) {
+ return;
+ }
+
+ cairo_t *cairo = buffer->cairo;
+ cairo_set_antialias(cairo, CAIRO_ANTIALIAS_BEST);
+
+ cairo_save(cairo);
+ cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);
+ cairo_set_source_u32(cairo, state->args.colors.background);
+ cairo_pattern_set_filter(cairo_get_source(cairo), CAIRO_FILTER_BILINEAR);
+ cairo_paint(cairo);
+ if (surface->image && state->args.mode != BACKGROUND_MODE_SOLID_COLOR) {
+ cairo_set_operator(cairo, CAIRO_OPERATOR_OVER);
+ if (fade_is_complete(&surface->fade)) {
+ if (!surface->scaled_image) {
+ surface->scaled_image =
+ scale_background_image(surface->image, state->args.mode,
+ buffer_width, buffer_height);
+ }
+ render_background_image(cairo, surface->scaled_image, 1);
+ } else {
+ if (!surface->screencopy.scaled_image) {
+ surface->screencopy.scaled_image =
+ scale_background_image(surface->screencopy.original_image,
+ state->args.mode, buffer_width, buffer_height);
+ }
+ render_background_image(cairo, surface->screencopy.scaled_image, 1);
+ if (!surface->scaled_image) {
+ surface->scaled_image =
+ scale_background_image(surface->image, state->args.mode,
+ buffer_width, buffer_height);
+ }
+ render_background_image(cairo, surface->scaled_image, surface->fade.alpha);
+ }
+ }
+ cairo_restore(cairo);
+ cairo_identity_matrix(cairo);
+
+ wl_surface_set_buffer_scale(surface->surface, surface->scale);
+ wl_surface_attach(surface->surface, buffer->buffer, 0, 0);
+ wl_surface_damage_buffer(surface->surface, 0, 0, INT32_MAX, INT32_MAX);
+ if (commit) {
+ wl_surface_commit(surface->surface);
+ }
+}
+
+void render_background_fade(struct swaylock_surface *surface, uint32_t time) {
+ if (fade_is_complete(&surface->fade)) {
+ return;
+ }
+
+ fade_update(&surface->fade, time);
+
+ render_frame_background(surface, true);
+ render_frame(surface);
+}
+
+void render_frame(struct swaylock_surface *surface) {
+ struct swaylock_state *state = surface->state;
+
+ int arc_radius = state->args.radius * surface->scale;
+ int arc_thickness = state->args.thickness * surface->scale;
+ int buffer_diameter = (arc_radius + arc_thickness) * 2;
+
+ int buffer_width = surface->indicator_width;
+ int buffer_height = surface->indicator_height;
+ int new_width = buffer_diameter;
+ int new_height = buffer_diameter;
+
+ int subsurf_xpos;
+ int subsurf_ypos;
+
+ // Center the indicator unless overridden by the user
+ if (state->args.override_indicator_x_position) {
+ subsurf_xpos = state->args.indicator_x_position -
+ buffer_width / (2 * surface->scale) + 2 / surface->scale;
+ } else {
+ subsurf_xpos = surface->width / 2 -
+ buffer_width / (2 * surface->scale) + 2 / surface->scale;
+ }
+
+ if (state->args.override_indicator_y_position) {
+ subsurf_ypos = state->args.indicator_y_position -
+ (state->args.radius + state->args.thickness);
+ } else {
+ subsurf_ypos = surface->height / 2 -
+ (state->args.radius + state->args.thickness);
+ }
+
+ wl_subsurface_set_position(surface->subsurface, subsurf_xpos, subsurf_ypos);
+
+ struct pool_buffer *buffer = get_next_buffer(state->shm,
+ surface->indicator_buffers, buffer_width, buffer_height);
+ if (buffer == NULL) {
+ return;
+ }
+
+ cairo_t *cairo = buffer->cairo;
+ cairo_set_antialias(cairo, CAIRO_ANTIALIAS_BEST);
+ cairo_font_options_t *fo = cairo_font_options_create();
+ cairo_font_options_set_hint_style(fo, CAIRO_HINT_STYLE_FULL);
+ cairo_font_options_set_antialias(fo, CAIRO_ANTIALIAS_SUBPIXEL);
+ cairo_font_options_set_subpixel_order(fo, to_cairo_subpixel_order(surface->subpixel));
+ cairo_set_font_options(cairo, fo);
+ cairo_font_options_destroy(fo);
+ cairo_identity_matrix(cairo);
+
+ // Clear
+ cairo_save(cairo);
+ cairo_set_source_rgba(cairo, 0, 0, 0, 0);
+ cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);
+ cairo_paint(cairo);
+ cairo_restore(cairo);
+
+ float type_indicator_border_thickness =
+ TYPE_INDICATOR_BORDER_THICKNESS * surface->scale;
+
+ // This is a bit messy.
+ // After the fork, upstream added their own --indicator-idle-visible option,
+ // but it works slightly differently from swaylock-effects' --indicator
+ // option. To maintain compatibility with upstream swaylock scripts as well
+ // as with old swaylock-effects scripts, I will keep both flags.
+ bool upstream_show_indicator =
+ state->args.show_indicator && (state->auth_state != AUTH_STATE_IDLE ||
+ state->args.indicator_idle_visible);
+
+ if (state->args.indicator ||
+ (upstream_show_indicator && state->auth_state != AUTH_STATE_GRACE)) {
+ // Draw indicator image
+ cairo_surface_t *image = state->indicator_image;
+ if (image) {
+ int height = cairo_image_surface_get_height(image);
+ int width = cairo_image_surface_get_width(image);
+ int smallest = MIN(height, width);
+ double radius = arc_radius - arc_thickness * 0.5;
+ double scale = radius * 2 / smallest;
+ double offset = buffer_diameter * 0.5 / scale - smallest * 0.5;
+
+ // Create the arc that clips the image
+ cairo_arc(cairo,
+ buffer_diameter * 0.5,
+ buffer_diameter * 0.5,
+ radius,
+ 0, 2 * M_PI);
+ // Scale cairo to make image fit the indicator
+ cairo_scale(cairo, scale, scale);
+ cairo_set_source_surface(cairo, image, offset, offset);
+ // Scale cairo back
+ cairo_scale(cairo, 1 / scale, 1 / scale);
+ cairo_fill(cairo);
+ }
+
+ // Fill inner circle
+ cairo_set_line_width(cairo, 0);
+ cairo_arc(cairo, buffer_width / 2, buffer_diameter / 2,
+ arc_radius - arc_thickness / 2, 0, 2 * M_PI);
+ set_color_for_state(cairo, state, &state->args.colors.inside);
+ cairo_fill_preserve(cairo);
+ cairo_stroke(cairo);
+
+ // Draw ring
+ cairo_set_line_width(cairo, arc_thickness);
+ cairo_arc(cairo, buffer_width / 2, buffer_diameter / 2, arc_radius,
+ 0, 2 * M_PI);
+ set_color_for_state(cairo, state, &state->args.colors.ring);
+ cairo_stroke(cairo);
+
+ // Draw a message
+ char *text = NULL;
+ char *text_l1 = NULL;
+ char *text_l2 = NULL;
+ const char *layout_text = NULL;
+ double font_size;
+ char attempts[4]; // like i3lock: count no more than 999
+ set_color_for_state(cairo, state, &state->args.colors.text);
+ cairo_select_font_face(cairo, state->args.font,
+ CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
+ if (state->args.font_size > 0) {
+ font_size = state->args.font_size;
+ } else {
+ font_size = arc_radius / 3.0f;
+ }
+ cairo_set_font_size(cairo, font_size);
+ switch (state->auth_state) {
+ case AUTH_STATE_VALIDATING:
+ text = state->args.text_verifying;
+ break;
+ case AUTH_STATE_INVALID:
+ text = state->args.text_wrong;
+ break;
+ case AUTH_STATE_CLEAR:
+ text = state->args.text_cleared;
+ break;
+ case AUTH_STATE_INPUT:
+ case AUTH_STATE_INPUT_NOP:
+ case AUTH_STATE_BACKSPACE:
+ // Password text visible basic feat
+
+ char *hashText = "*";
+ if (state->password.len == 0 && state->args.ignore_empty) {
+ text = "";
+ } else {
+ size_t pass_len = state->password.len;
+ size_t max_stars = 10;
+ size_t stars_to_show = pass_len < max_stars ? pass_len : max_stars;
+ size_t hash_len = stars_to_show * strlen(hashText) + 1;
+ char *hash_buffer = malloc(hash_len);
+ if (!hash_buffer) {
+ return;
+ }
+ hash_buffer[0] = '\0';
+ for (size_t i = 0; i < stars_to_show; ++i) {
+ strcat(hash_buffer, hashText);
+ }
+ text = hash_buffer;
+ }
+
+ // Caps Lock has higher priority
+ if (state->xkb.caps_lock && state->args.show_caps_lock_text) {
+ text = state->args.text_caps_lock;
+ } else if (state->args.show_failed_attempts &&
+ state->failed_attempts > 0) {
+ if (state->failed_attempts > 999) {
+ text = "999+";
+ } else {
+ snprintf(attempts, sizeof(attempts), "%d", state->failed_attempts);
+ text = attempts;
+ }
+ } else if (state->args.clock) {
+ timetext(surface, &text_l1, &text_l2);
+ }
+
+ xkb_layout_index_t num_layout = xkb_keymap_num_layouts(state->xkb.keymap);
+ if (!state->args.hide_keyboard_layout &&
+ (state->args.show_keyboard_layout || num_layout > 1)) {
+ xkb_layout_index_t curr_layout = 0;
+
+ // advance to the first active layout (if any)
+ while (curr_layout < num_layout &&
+ xkb_state_layout_index_is_active(state->xkb.state,
+ curr_layout, XKB_STATE_LAYOUT_EFFECTIVE) != 1) {
+ ++curr_layout;
+ }
+ // will handle invalid index if none are active
+ layout_text = xkb_keymap_layout_get_name(state->xkb.keymap, curr_layout);
+ }
+ break;
+ default:
+ if (state->args.clock)
+ timetext(surface, &text_l1, &text_l2);
+ break;
+ }
+
+ if (text_l1 && !text_l2)
+ text = text_l1;
+ if (text_l2 && !text_l1)
+ text = text_l2;
+
+ if (text) {
+ cairo_text_extents_t extents;
+ cairo_font_extents_t fe;
+ double x, y;
+ cairo_text_extents(cairo, text, &extents);
+ cairo_font_extents(cairo, &fe);
+ x = (buffer_width / 2) -
+ (extents.width / 2 + extents.x_bearing);
+ y = (buffer_diameter / 2) +
+ (fe.height / 2 - fe.descent);
+
+ cairo_move_to(cairo, x, y);
+ cairo_show_text(cairo, text);
+ cairo_close_path(cairo);
+ cairo_new_sub_path(cairo);
+
+ if (new_width < extents.width) {
+ new_width = extents.width;
+ }
+ } else if (text_l1 && text_l2) {
+ cairo_text_extents_t extents_l1, extents_l2;
+ cairo_font_extents_t fe_l1, fe_l2;
+ double x_l1, y_l1, x_l2, y_l2;
+
+ /* Top */
+
+ cairo_text_extents(cairo, text_l1, &extents_l1);
+ cairo_font_extents(cairo, &fe_l1);
+ x_l1 = (buffer_width / 2) -
+ (extents_l1.width / 2 + extents_l1.x_bearing);
+ y_l1 = (buffer_diameter / 2) +
+ (fe_l1.height / 2 - fe_l1.descent) - arc_radius / 10.0f;
+
+ cairo_move_to(cairo, x_l1, y_l1);
+ cairo_show_text(cairo, text_l1);
+ cairo_close_path(cairo);
+ cairo_new_sub_path(cairo);
+
+ /* Bottom */
+
+ cairo_set_font_size(cairo, arc_radius / 6.0f);
+ cairo_text_extents(cairo, text_l2, &extents_l2);
+ cairo_font_extents(cairo, &fe_l2);
+ x_l2 = (buffer_width / 2) -
+ (extents_l2.width / 2 + extents_l2.x_bearing);
+ y_l2 = (buffer_diameter / 2) +
+ (fe_l2.height / 2 - fe_l2.descent) + arc_radius / 3.5f;
+
+ cairo_move_to(cairo, x_l2, y_l2);
+ cairo_show_text(cairo, text_l2);
+ cairo_close_path(cairo);
+ cairo_new_sub_path(cairo);
+
+ if (new_width < extents_l1.width)
+ new_width = extents_l1.width;
+ if (new_width < extents_l2.width)
+ new_width = extents_l2.width;
+
+
+ cairo_set_font_size(cairo, font_size);
+ }
+
+ // Typing indicator: Highlight random part on keypress
+ if (state->auth_state == AUTH_STATE_INPUT
+ || state->auth_state == AUTH_STATE_BACKSPACE) {
+
+ static double highlight_start = 0;
+ if (state->indicator_dirty) {
+ highlight_start +=
+ (rand() % (int)(M_PI * 100)) / 100.0 + M_PI * 0.5;
+ state->indicator_dirty = false;
+ }
+
+ cairo_arc(cairo, buffer_width / 2, buffer_diameter / 2,
+ arc_radius, highlight_start,
+ highlight_start + TYPE_INDICATOR_RANGE);
+ if (state->auth_state == AUTH_STATE_INPUT) {
+ if (state->xkb.caps_lock && state->args.show_caps_lock_indicator) {
+ cairo_set_source_u32(cairo, state->args.colors.caps_lock_key_highlight);
+ } else {
+ cairo_set_source_u32(cairo, state->args.colors.key_highlight);
+ }
+ } else {
+ if (state->xkb.caps_lock && state->args.show_caps_lock_indicator) {
+ cairo_set_source_u32(cairo, state->args.colors.caps_lock_bs_highlight);
+ } else {
+ cairo_set_source_u32(cairo, state->args.colors.bs_highlight);
+ }
+ }
+ cairo_stroke(cairo);
+
+ // Draw borders
+ cairo_set_source_u32(cairo, state->args.colors.separator);
+ cairo_arc(cairo, buffer_width / 2, buffer_diameter / 2,
+ arc_radius, highlight_start,
+ highlight_start + type_indicator_border_thickness);
+ cairo_stroke(cairo);
+
+ cairo_arc(cairo, buffer_width / 2, buffer_diameter / 2,
+ arc_radius, highlight_start + TYPE_INDICATOR_RANGE,
+ highlight_start + TYPE_INDICATOR_RANGE +
+ type_indicator_border_thickness);
+ cairo_stroke(cairo);
+ }
+
+ // Draw inner + outer border of the circle
+ set_color_for_state(cairo, state, &state->args.colors.line);
+ cairo_set_line_width(cairo, 2.0 * surface->scale);
+ cairo_arc(cairo, buffer_width / 2, buffer_diameter / 2,
+ arc_radius - arc_thickness / 2, 0, 2 * M_PI);
+ cairo_stroke(cairo);
+ cairo_arc(cairo, buffer_width / 2, buffer_diameter / 2,
+ arc_radius + arc_thickness / 2, 0, 2 * M_PI);
+ cairo_stroke(cairo);
+
+ // display layout text separately
+ if (layout_text) {
+ cairo_text_extents_t extents;
+ cairo_font_extents_t fe;
+ double x, y;
+ double box_padding = 4.0 * surface->scale;
+ cairo_text_extents(cairo, layout_text, &extents);
+ cairo_font_extents(cairo, &fe);
+ // upper left coordinates for box
+ x = (buffer_width / 2) - (extents.width / 2) - box_padding;
+ y = buffer_diameter;
+
+ // background box
+ cairo_rectangle(cairo, x, y,
+ extents.width + 2.0 * box_padding,
+ fe.height + 2.0 * box_padding);
+ cairo_set_source_u32(cairo, state->args.colors.layout_background);
+ cairo_fill_preserve(cairo);
+ // border
+ cairo_set_source_u32(cairo, state->args.colors.layout_border);
+ cairo_stroke(cairo);
+
+ // take font extents and padding into account
+ cairo_move_to(cairo,
+ x - extents.x_bearing + box_padding,
+ y + (fe.height - fe.descent) + box_padding);
+ cairo_set_source_u32(cairo, state->args.colors.layout_text);
+ cairo_show_text(cairo, layout_text);
+ cairo_new_sub_path(cairo);
+
+ new_height += fe.height + 2 * box_padding;
+ if (new_width < extents.width + 2 * box_padding) {
+ new_width = extents.width + 2 * box_padding;
+ }
+ }
+ }
+
+ // Ensure buffer size is multiple of buffer scale - required by protocol
+ new_height += surface->scale - (new_height % surface->scale);
+ new_width += surface->scale - (new_width % surface->scale);
+
+ if (buffer_width != new_width || buffer_height != new_height) {
+ destroy_buffer(buffer);
+ surface->indicator_width = new_width;
+ surface->indicator_height = new_height;
+ render_frame(surface);
+ return;
+ }
+
+ wl_surface_set_buffer_scale(surface->child, surface->scale);
+ wl_surface_attach(surface->child, buffer->buffer, 0, 0);
+ wl_surface_damage_buffer(surface->child, 0, 0, INT32_MAX, INT32_MAX);
+ wl_surface_commit(surface->child);
+
+ wl_surface_commit(surface->surface);
+}
swaylock-mod/seat.c
@@ -0,0 +1,253 @@
+#include <assert.h>
+#include <stdlib.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#include <xkbcommon/xkbcommon.h>
+#include "log.h"
+#include "swaylock.h"
+#include "seat.h"
+#include "loop.h"
+
+static void keyboard_keymap(void *data, struct wl_keyboard *wl_keyboard,
+ uint32_t format, int32_t fd, uint32_t size) {
+ struct swaylock_seat *seat = data;
+ struct swaylock_state *state = seat->state;
+ if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) {
+ close(fd);
+ swaylock_log(LOG_ERROR, "Unknown keymap format %d, aborting", format);
+ exit(1);
+ }
+ char *map_shm = mmap(NULL, size - 1, PROT_READ, MAP_PRIVATE, fd, 0);
+ if (map_shm == MAP_FAILED) {
+ close(fd);
+ swaylock_log(LOG_ERROR, "Unable to initialize keymap shm, aborting");
+ exit(1);
+ }
+ struct xkb_keymap *keymap = xkb_keymap_new_from_buffer(
+ state->xkb.context, map_shm, size - 1, XKB_KEYMAP_FORMAT_TEXT_V1,
+ XKB_KEYMAP_COMPILE_NO_FLAGS);
+ munmap(map_shm, size - 1);
+ close(fd);
+ assert(keymap);
+ struct xkb_state *xkb_state = xkb_state_new(keymap);
+ assert(xkb_state);
+ xkb_keymap_unref(state->xkb.keymap);
+ xkb_state_unref(state->xkb.state);
+ state->xkb.keymap = keymap;
+ state->xkb.state = xkb_state;
+}
+
+static void keyboard_enter(void *data, struct wl_keyboard *wl_keyboard,
+ uint32_t serial, struct wl_surface *surface, struct wl_array *keys) {
+ // Who cares
+}
+
+static void keyboard_leave(void *data, struct wl_keyboard *wl_keyboard,
+ uint32_t serial, struct wl_surface *surface) {
+ // Who cares
+}
+
+static void keyboard_repeat(void *data) {
+ struct swaylock_seat *seat = data;
+ struct swaylock_state *state = seat->state;
+ seat->repeat_timer = loop_add_timer(
+ state->eventloop, seat->repeat_period_ms, keyboard_repeat, seat);
+ swaylock_handle_key(state, seat->repeat_sym, seat->repeat_codepoint);
+}
+
+static void keyboard_key(void *data, struct wl_keyboard *wl_keyboard,
+ uint32_t serial, uint32_t time, uint32_t key, uint32_t _key_state) {
+ struct swaylock_seat *seat = data;
+ struct swaylock_state *state = seat->state;
+ enum wl_keyboard_key_state key_state = _key_state;
+ xkb_keysym_t sym = xkb_state_key_get_one_sym(state->xkb.state, key + 8);
+ uint32_t keycode = key_state == WL_KEYBOARD_KEY_STATE_PRESSED ?
+ key + 8 : 0;
+ uint32_t codepoint = xkb_state_key_get_utf32(state->xkb.state, keycode);
+ if (key_state == WL_KEYBOARD_KEY_STATE_PRESSED) {
+ swaylock_handle_key(state, sym, codepoint);
+ }
+
+ if (seat->repeat_timer) {
+ loop_remove_timer(seat->state->eventloop, seat->repeat_timer);
+ seat->repeat_timer = NULL;
+ }
+
+ if (key_state == WL_KEYBOARD_KEY_STATE_PRESSED && seat->repeat_period_ms > 0) {
+ seat->repeat_sym = sym;
+ seat->repeat_codepoint = codepoint;
+ seat->repeat_timer = loop_add_timer(
+ seat->state->eventloop, seat->repeat_delay_ms, keyboard_repeat, seat);
+ }
+}
+
+static void keyboard_modifiers(void *data, struct wl_keyboard *wl_keyboard,
+ uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched,
+ uint32_t mods_locked, uint32_t group) {
+ struct swaylock_seat *seat = data;
+ struct swaylock_state *state = seat->state;
+ if (state->xkb.state == NULL) {
+ return;
+ }
+
+ int layout_same = xkb_state_layout_index_is_active(state->xkb.state,
+ group, XKB_STATE_LAYOUT_EFFECTIVE);
+ if (!layout_same) {
+ damage_state(state);
+ }
+ xkb_state_update_mask(state->xkb.state,
+ mods_depressed, mods_latched, mods_locked, 0, 0, group);
+ int caps_lock = xkb_state_mod_name_is_active(state->xkb.state,
+ XKB_MOD_NAME_CAPS, XKB_STATE_MODS_LOCKED);
+ if (caps_lock != state->xkb.caps_lock) {
+ state->xkb.caps_lock = caps_lock;
+ damage_state(state);
+ }
+ state->xkb.control = xkb_state_mod_name_is_active(state->xkb.state,
+ XKB_MOD_NAME_CTRL,
+ XKB_STATE_MODS_DEPRESSED | XKB_STATE_MODS_LATCHED);
+}
+
+static void keyboard_repeat_info(void *data, struct wl_keyboard *wl_keyboard,
+ int32_t rate, int32_t delay) {
+ struct swaylock_seat *seat = data;
+ if (rate <= 0) {
+ seat->repeat_period_ms = -1;
+ } else {
+ // Keys per second -> milliseconds between keys
+ seat->repeat_period_ms = 1000 / rate;
+ }
+ seat->repeat_delay_ms = delay;
+}
+
+static const struct wl_keyboard_listener keyboard_listener = {
+ .keymap = keyboard_keymap,
+ .enter = keyboard_enter,
+ .leave = keyboard_leave,
+ .key = keyboard_key,
+ .modifiers = keyboard_modifiers,
+ .repeat_info = keyboard_repeat_info,
+};
+
+static void wl_pointer_enter(void *data, struct wl_pointer *wl_pointer,
+ uint32_t serial, struct wl_surface *surface,
+ wl_fixed_t surface_x, wl_fixed_t surface_y) {
+ wl_pointer_set_cursor(wl_pointer, serial, NULL, 0, 0);
+}
+
+static void wl_pointer_leave(void *data, struct wl_pointer *wl_pointer,
+ uint32_t serial, struct wl_surface *surface) {
+ // Who cares
+}
+
+static void wl_pointer_motion(void *data, struct wl_pointer *wl_pointer,
+ uint32_t time, wl_fixed_t surface_x, wl_fixed_t surface_y) {
+ swaylock_handle_mouse((struct swaylock_state *)data);
+}
+
+static void wl_pointer_button(void *data, struct wl_pointer *wl_pointer,
+ uint32_t serial, uint32_t time, uint32_t button, uint32_t state) {
+ swaylock_handle_mouse((struct swaylock_state *)data);
+}
+
+static void wl_pointer_axis(void *data, struct wl_pointer *wl_pointer,
+ uint32_t time, uint32_t axis, wl_fixed_t value) {
+ swaylock_handle_mouse((struct swaylock_state *)data);
+}
+
+static void wl_pointer_frame(void *data, struct wl_pointer *wl_pointer) {
+ // Who cares
+}
+
+static void wl_pointer_axis_source(void *data, struct wl_pointer *wl_pointer,
+ uint32_t axis_source) {
+ // Who cares
+}
+
+static void wl_pointer_axis_stop(void *data, struct wl_pointer *wl_pointer,
+ uint32_t time, uint32_t axis) {
+ // Who cares
+}
+
+static void wl_pointer_axis_discrete(void *data, struct wl_pointer *wl_pointer,
+ uint32_t axis, int32_t discrete) {
+ // Who cares
+}
+
+static const struct wl_pointer_listener pointer_listener = {
+ .enter = wl_pointer_enter,
+ .leave = wl_pointer_leave,
+ .motion = wl_pointer_motion,
+ .button = wl_pointer_button,
+ .axis = wl_pointer_axis,
+ .frame = wl_pointer_frame,
+ .axis_source = wl_pointer_axis_source,
+ .axis_stop = wl_pointer_axis_stop,
+ .axis_discrete = wl_pointer_axis_discrete,
+};
+
+static void wl_touch_down(void *data, struct wl_touch *touch, uint32_t serial,
+ uint32_t time, struct wl_surface *surface, int32_t id, wl_fixed_t x, wl_fixed_t y) {
+ swaylock_handle_touch((struct swaylock_state *)data);
+}
+
+static void wl_touch_up(void *data, struct wl_touch *touch, uint32_t serial,
+ uint32_t time, int32_t id) {
+ // Who cares
+}
+
+static void wl_touch_motion(void *data, struct wl_touch *touch, uint32_t time,
+ int32_t id, wl_fixed_t x, wl_fixed_t y) {
+ swaylock_handle_touch((struct swaylock_state *)data);
+}
+
+static void wl_touch_frame(void *data, struct wl_touch *touch) {
+ // Who cares
+}
+
+static void wl_touch_cancel(void *data, struct wl_touch *touch) {
+ // Who cares
+}
+
+static const struct wl_touch_listener touch_listener = {
+ .down = wl_touch_down,
+ .up = wl_touch_up,
+ .motion = wl_touch_motion,
+ .frame = wl_touch_frame,
+ .cancel = wl_touch_cancel,
+};
+
+static void seat_handle_capabilities(void *data, struct wl_seat *wl_seat,
+ enum wl_seat_capability caps) {
+ struct swaylock_seat *seat = data;
+ if (seat->pointer) {
+ wl_pointer_release(seat->pointer);
+ seat->pointer = NULL;
+ }
+ if (seat->keyboard) {
+ wl_keyboard_release(seat->keyboard);
+ seat->keyboard = NULL;
+ }
+ if ((caps & WL_SEAT_CAPABILITY_POINTER)) {
+ seat->pointer = wl_seat_get_pointer(wl_seat);
+ wl_pointer_add_listener(seat->pointer, &pointer_listener, seat->state);
+ }
+ if ((caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
+ seat->keyboard = wl_seat_get_keyboard(wl_seat);
+ wl_keyboard_add_listener(seat->keyboard, &keyboard_listener, seat);
+ }
+ if ((caps & WL_SEAT_CAPABILITY_TOUCH)) {
+ seat->touch = wl_seat_get_touch(wl_seat);
+ wl_touch_add_listener(seat->touch, &touch_listener, seat->state);
+ }
+}
+
+static void seat_handle_name(void *data, struct wl_seat *wl_seat,
+ const char *name) {
+ // Who cares
+}
+
+const struct wl_seat_listener seat_listener = {
+ .capabilities = seat_handle_capabilities,
+ .name = seat_handle_name,
+};
swaylock-mod/shadow.c
@@ -0,0 +1,103 @@
+#define _XOPEN_SOURCE // for crypt
+#include <pwd.h>
+#include <shadow.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <sys/types.h>
+#include <unistd.h>
+#ifdef __GLIBC__
+// GNU, you damn slimy bastard
+#include <crypt.h>
+#endif
+#include "comm.h"
+#include "log.h"
+#include "password-buffer.h"
+#include "swaylock.h"
+
+void initialize_pw_backend(int argc, char **argv) {
+ if (geteuid() != 0) {
+ swaylock_log(LOG_ERROR,
+ "swaylock needs to be setuid to read /etc/shadow");
+ exit(EXIT_FAILURE);
+ }
+
+ if (!spawn_comm_child()) {
+ exit(EXIT_FAILURE);
+ }
+
+ if (setgid(getgid()) != 0) {
+ swaylock_log_errno(LOG_ERROR, "Unable to drop root");
+ exit(EXIT_FAILURE);
+ }
+ if (setuid(getuid()) != 0) {
+ swaylock_log_errno(LOG_ERROR, "Unable to drop root");
+ exit(EXIT_FAILURE);
+ }
+ if (setuid(0) != -1) {
+ swaylock_log_errno(LOG_ERROR, "Unable to drop root (we shouldn't be "
+ "able to restore it after setuid)");
+ exit(EXIT_FAILURE);
+ }
+}
+
+void run_pw_backend_child(void) {
+ /* This code runs as root */
+ struct passwd *pwent = getpwuid(getuid());
+ if (!pwent) {
+ swaylock_log_errno(LOG_ERROR, "failed to getpwuid");
+ exit(EXIT_FAILURE);
+ }
+ char *encpw = pwent->pw_passwd;
+ if (strcmp(encpw, "x") == 0) {
+ struct spwd *swent = getspnam(pwent->pw_name);
+ if (!swent) {
+ swaylock_log_errno(LOG_ERROR, "failed to getspnam");
+ exit(EXIT_FAILURE);
+ }
+ encpw = swent->sp_pwdp;
+ }
+
+ /* We don't need any additional logging here because the parent process will
+ * also fail here and will handle logging for us. */
+ if (setgid(getgid()) != 0) {
+ exit(EXIT_FAILURE);
+ }
+ if (setuid(getuid()) != 0) {
+ exit(EXIT_FAILURE);
+ }
+ if (setuid(0) != -1) {
+ exit(EXIT_FAILURE);
+ }
+
+ /* This code does not run as root */
+ swaylock_log(LOG_DEBUG, "Prepared to authorize user %s", pwent->pw_name);
+
+ while (1) {
+ char *buf;
+ ssize_t size = read_comm_request(&buf);
+ if (size < 0) {
+ exit(EXIT_FAILURE);
+ } else if (size == 0) {
+ break;
+ }
+
+ const char *c = crypt(buf, encpw);
+ password_buffer_destroy(buf, size);
+ buf = NULL;
+
+ if (c == NULL) {
+ swaylock_log_errno(LOG_ERROR, "crypt failed");
+ exit(EXIT_FAILURE);
+ }
+ bool success = strcmp(c, encpw) == 0;
+
+ if (!write_comm_reply(success)) {
+ exit(EXIT_FAILURE);
+ }
+
+ sleep(2);
+ }
+
+ clear_buffer(encpw, strlen(encpw));
+ exit(EXIT_SUCCESS);
+}
swaylock-mod/unicode.c
@@ -0,0 +1,79 @@
+#include <stdint.h>
+#include <stddef.h>
+#include <string.h>
+#include "unicode.h"
+
+int utf8_last_size(const char *str) {
+ int len = 0;
+ char *pos = strchr(str, '\0');
+ while (pos > str) {
+ --pos; ++len;
+ if ((*pos & 0xc0) != 0x80) {
+ return len;
+ }
+ }
+ return 0;
+}
+
+size_t utf8_chsize(uint32_t ch) {
+ if (ch < 0x80) {
+ return 1;
+ } else if (ch < 0x800) {
+ return 2;
+ } else if (ch < 0x10000) {
+ return 3;
+ }
+ return 4;
+}
+
+size_t utf8_encode(char *str, uint32_t ch) {
+ size_t len = 0;
+ uint8_t first;
+
+ if (ch < 0x80) {
+ first = 0;
+ len = 1;
+ } else if (ch < 0x800) {
+ first = 0xc0;
+ len = 2;
+ } else if (ch < 0x10000) {
+ first = 0xe0;
+ len = 3;
+ } else {
+ first = 0xf0;
+ len = 4;
+ }
+
+ for (size_t i = len - 1; i > 0; --i) {
+ str[i] = (ch & 0x3f) | 0x80;
+ ch >>= 6;
+ }
+
+ str[0] = ch | first;
+ return len;
+}
+
+
+static const struct {
+ uint8_t mask;
+ uint8_t result;
+ int octets;
+} sizes[] = {
+ { 0x80, 0x00, 1 },
+ { 0xE0, 0xC0, 2 },
+ { 0xF0, 0xE0, 3 },
+ { 0xF8, 0xF0, 4 },
+ { 0xFC, 0xF8, 5 },
+ { 0xFE, 0xF8, 6 },
+ { 0x80, 0x80, -1 },
+};
+
+int utf8_size(const char *s) {
+ uint8_t c = (uint8_t)*s;
+ for (size_t i = 0; i < sizeof(sizes) / sizeof(*sizes); ++i) {
+ if ((c & sizes[i].mask) == sizes[i].result) {
+ return sizes[i].octets;
+ }
+ }
+ return -1;
+}
swaylock-mod/wlr-input-inhibitor-unstable-v1.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="wlr_input_inhibit_unstable_v1">
+ <interface name="zwlr_input_inhibit_manager_v1" version="1">
+ <description summary="inhibits input events to other clients">
+ Clients can use this interface to prevent input events from being sent to
+ any surfaces but its own, which is useful for example in lock screen
+ software. It is assumed that access to this interface will be locked down
+ to whitelisted clients by the compositor.
+ </description>
+
+ <request name="get_inhibitor">
+ <description summary="inhibit input to other clients">
+ Activates the input inhibitor. As long as the inhibitor is active, the
+ compositor will not send input events to other clients.
+ </description>
+ <arg name="id" type="new_id" interface="zwlr_input_inhibitor_v1"/>
+ </request>
+
+ <enum name="error">
+ <entry name="already_inhibited" value="0" summary="an input inhibitor is already in use on the compositor"/>
+ </enum>
+ </interface>
+
+ <interface name="zwlr_input_inhibitor_v1" version="1">
+ <description summary="inhibits input to other clients">
+ While this resource exists, input to clients other than the owner of the
+ inhibitor resource will not receive input events. The client that owns
+ this resource will receive all input events normally. The compositor will
+ also disable all of its own input processing (such as keyboard shortcuts)
+ while the inhibitor is active.
+
+ The compositor may continue to send input events to selected clients,
+ such as an on-screen keyboard (via the input-method protocol).
+ </description>
+
+ <request name="destroy" type="destructor">
+ <description summary="destroy the input inhibitor object">
+ Destroy the inhibitor and allow other clients to receive input.
+ </description>
+ </request>
+ </interface>
+</protocol>
swaylock-mod/wlr-layer-shell-unstable-v1.xml
@@ -0,0 +1,261 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="wlr_layer_shell_v1_unstable_v1">
+
+ <interface name="zwlr_layer_shell_v1" version="1">
+ <description summary="create surfaces that are layers of the desktop">
+ Clients can use this interface to assign the surface_layer role to
+ wl_surfaces. Such surfaces are assigned to a "layer" of the output and
+ rendered with a defined z-depth respective to each other. They may also be
+ anchored to the edges and corners of a screen and specify input handling
+ semantics. This interface should be suitable for the implementation of
+ many desktop shell components, and a broad number of other applications
+ that interact with the desktop.
+ </description>
+
+ <request name="get_layer_surface">
+ <description summary="create a layer_surface from a surface">
+ Create a layer surface for an existing surface. This assigns the role of
+ layer_surface, or raises a protocol error if another role is already
+ assigned.
+
+ Creating a layer surface from a wl_surface which has a buffer attached
+ or committed is a client error, and any attempts by a client to attach
+ or manipulate a buffer prior to the first layer_surface.configure call
+ must also be treated as errors.
+
+ You may pass NULL for output to allow the compositor to decide which
+ output to use. Generally this will be the one that the user most
+ recently interacted with.
+
+ Clients can specify a namespace that defines the purpose of the layer
+ surface.
+ </description>
+ <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" summary="layer to add this surface to"/>
+ <arg name="namespace" type="string" summary="namespace for the layer surface"/>
+ </request>
+
+ <enum name="error">
+ <entry name="role" value="0" summary="wl_surface has another role"/>
+ <entry name="invalid_layer" value="1" summary="layer value is invalid"/>
+ <entry name="already_constructed" value="2" summary="wl_surface has a buffer attached or committed"/>
+ </enum>
+
+ <enum name="layer">
+ <description summary="available layers for surfaces">
+ These values indicate which layers a surface can be rendered in. They
+ are ordered by z depth, bottom-most first. Traditional shell surfaces
+ will typically be rendered between the bottom and top layers.
+ Fullscreen shell surfaces are typically rendered at the top layer.
+ Multiple surfaces can share a single layer, and ordering within a
+ single layer is undefined.
+ </description>
+
+ <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">
+ <description summary="layer metadata interface">
+ An interface that may be implemented by a wl_surface, for surfaces that
+ are designed to be rendered as a layer of a stacked desktop-like
+ environment.
+
+ Layer surface state (size, anchor, exclusive zone, margin, interactivity)
+ is double-buffered, and will be applied at the time wl_surface.commit of
+ the corresponding wl_surface is called.
+ </description>
+
+ <request name="set_size">
+ <description summary="sets the size of the surface">
+ Sets the size of the surface in surface-local coordinates. The
+ compositor will display the surface centered with respect to its
+ anchors.
+
+ If you pass 0 for either value, the compositor will assign it and
+ inform you of the assignment in the configure event. You must set your
+ anchor to opposite edges in the dimensions you omit; not doing so is a
+ protocol error. Both values are 0 by default.
+
+ Size is double-buffered, see wl_surface.commit.
+ </description>
+ <arg name="width" type="uint"/>
+ <arg name="height" type="uint"/>
+ </request>
+
+ <request name="set_anchor">
+ <description summary="configures the anchor point of the surface">
+ Requests that the compositor anchor the surface to the specified edges
+ and corners. If two orthoginal edges are specified (e.g. 'top' and
+ 'left'), then the anchor point will be the intersection of the edges
+ (e.g. the top left corner of the output); otherwise the anchor point
+ will be centered on that edge, or in the center if none is specified.
+
+ Anchor is double-buffered, see wl_surface.commit.
+ </description>
+ <arg name="anchor" type="uint" enum="anchor"/>
+ </request>
+
+ <request name="set_exclusive_zone">
+ <description summary="configures the exclusive geometry of this surface">
+ Requests that the compositor avoids occluding an area of the surface
+ with other surfaces. The compositor's use of this information is
+ implementation-dependent - do not assume that this region will not
+ actually be occluded.
+
+ A positive value is only meaningful if the surface is anchored to an
+ edge, rather than a corner. The zone is the number of surface-local
+ coordinates from the edge that are considered exclusive.
+
+ Surfaces that do not wish to have an exclusive zone may instead specify
+ how they should interact with surfaces that do. If set to zero, the
+ surface indicates that it would like to be moved to avoid occluding
+ surfaces with a positive excluzive zone. If set to -1, the surface
+ indicates that it would not like to be moved to accommodate for other
+ surfaces, and the compositor should extend it all the way to the edges
+ it is anchored to.
+
+ For example, a panel might set its exclusive zone to 10, so that
+ maximized shell surfaces are not shown on top of it. A notification
+ might set its exclusive zone to 0, so that it is moved to avoid
+ occluding the panel, but shell surfaces are shown underneath it. A
+ wallpaper or lock screen might set their exclusive zone to -1, so that
+ they stretch below or over the panel.
+
+ The default value is 0.
+
+ Exclusive zone is double-buffered, see wl_surface.commit.
+ </description>
+ <arg name="zone" type="int"/>
+ </request>
+
+ <request name="set_margin">
+ <description summary="sets a margin from the anchor point">
+ Requests that the surface be placed some distance away from the anchor
+ point on the output, in surface-local coordinates. Setting this value
+ for edges you are not anchored to has no effect.
+
+ The exclusive zone includes the margin.
+
+ Margin is double-buffered, see wl_surface.commit.
+ </description>
+ <arg name="top" type="int"/>
+ <arg name="right" type="int"/>
+ <arg name="bottom" type="int"/>
+ <arg name="left" type="int"/>
+ </request>
+
+ <request name="set_keyboard_interactivity">
+ <description summary="requests keyboard events">
+ Set to 1 to request that the seat send keyboard events to this layer
+ surface. For layers below the shell surface layer, the seat will use
+ normal focus semantics. For layers above the shell surface layers, the
+ seat will always give exclusive keyboard focus to the top-most layer
+ which has keyboard interactivity set to true.
+
+ Layer surfaces receive pointer, touch, and tablet events normally. If
+ you do not want to receive them, set the input region on your surface
+ to an empty region.
+
+ Events is double-buffered, see wl_surface.commit.
+ </description>
+ <arg name="keyboard_interactivity" type="uint"/>
+ </request>
+
+ <request name="get_popup">
+ <description summary="assign this layer_surface as an xdg_popup parent">
+ This assigns an xdg_popup's parent to this layer_surface. This popup
+ should have been created via xdg_surface::get_popup with the parent set
+ to NULL, and this request must be invoked before committing the popup's
+ initial state.
+
+ See the documentation of xdg_popup for more details about what an
+ xdg_popup is and how it is used.
+ </description>
+ <arg name="popup" type="object" interface="xdg_popup"/>
+ </request>
+
+ <request name="ack_configure">
+ <description summary="ack a configure event">
+ When a configure event is received, if a client commits the
+ surface in response to the configure event, then the client
+ must make an ack_configure request sometime before the commit
+ request, passing along the serial of the configure event.
+
+ If the client receives multiple configure events before it
+ can respond to one, it only has to ack the last configure event.
+
+ A client is not required to commit immediately after sending
+ an ack_configure request - it may even ack_configure several times
+ before its next surface commit.
+
+ A client may send multiple ack_configure requests before committing, but
+ only the last request sent before a commit indicates which configure
+ event the client really is responding to.
+ </description>
+ <arg name="serial" type="uint" summary="the serial from the configure event"/>
+ </request>
+
+ <request name="destroy" type="destructor">
+ <description summary="destroy the layer_surface">
+ This request destroys the layer surface.
+ </description>
+ </request>
+
+ <event name="configure">
+ <description summary="suggest a surface change">
+ The configure event asks the client to resize its surface.
+
+ Clients should arrange their surface for the new states, and then send
+ an ack_configure request with the serial sent in this configure event at
+ some point before committing the new surface.
+
+ The client is free to dismiss all but the last configure event it
+ received.
+
+ The width and height arguments specify the size of the window in
+ surface-local coordinates.
+
+ The size is a hint, in the sense that the client is free to ignore it if
+ it doesn't resize, pick a smaller size (to satisfy aspect ratio or
+ resize in steps of NxM pixels). If the client picks a smaller size and
+ is anchored to two opposite anchors (e.g. 'top' and 'bottom'), the
+ surface will be centered on this axis.
+
+ If the width or height arguments are zero, it means the client should
+ decide its own window dimension.
+ </description>
+ <arg name="serial" type="uint"/>
+ <arg name="width" type="uint"/>
+ <arg name="height" type="uint"/>
+ </event>
+
+ <event name="closed">
+ <description summary="surface should be closed">
+ The closed event is sent by the compositor when the surface will no
+ longer be shown. The output may have been destroyed or the user may
+ have asked for it to be removed. Further changes to the surface will be
+ ignored. The client should destroy the resource after receiving this
+ event, and create a new surface if they so choose.
+ </description>
+ </event>
+
+ <enum name="error">
+ <entry name="invalid_surface_state" value="0" summary="provided surface state is invalid"/>
+ <entry name="invalid_size" value="1" summary="size is invalid"/>
+ <entry name="invalid_anchor" value="2" summary="anchor bitfield is invalid"/>
+ </enum>
+
+ <enum name="anchor" bitfield="true">
+ <entry name="top" value="1" summary="the top edge of the anchor rectangle"/>
+ <entry name="bottom" value="2" summary="the bottom edge of the anchor rectangle"/>
+ <entry name="left" value="4" summary="the left edge of the anchor rectangle"/>
+ <entry name="right" value="8" summary="the right edge of the anchor rectangle"/>
+ </enum>
+ </interface>
+</protocol>
swaylock-mod/wlr-screencopy-unstable-v1.xml
@@ -0,0 +1,157 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="wlr_screencopy_unstable_v1">
+
+ <description summary="screen content capturing on client buffers">
+ This protocol allows clients to ask the compositor to copy part of the
+ screen content to a client buffer.
+
+ Warning! The protocol described in this file is experimental and
+ backward incompatible changes may be made. Backward compatible changes
+ may be added together with the corresponding interface version bump.
+ Backward incompatible changes are done by bumping the version number in
+ the protocol and interface names and resetting the interface version.
+ Once the protocol is to be declared stable, the 'z' prefix and the
+ version number in the protocol and interface names are removed and the
+ interface version number is reset.
+ </description>
+
+ <interface name="zwlr_screencopy_manager_v1" version="1">
+ <description summary="manager to inform clients and begin capturing">
+ This object is a manager which offers requests to start capturing from a
+ source.
+ </description>
+
+ <request name="capture_output">
+ <description summary="capture an output">
+ Capture the next frame of an entire output.
+ </description>
+ <arg name="frame" type="new_id" interface="zwlr_screencopy_frame_v1"/>
+ <arg name="overlay_cursor" type="int"
+ summary="composite cursor onto the frame"/>
+ <arg name="output" type="object" interface="wl_output"/>
+ </request>
+
+ <request name="capture_output_region">
+ <description summary="capture an output's region">
+ Capture the next frame of an output's region.
+
+ The region is given in output logical coordinates, see
+ xdg_output.logical_size. The region will be clipped to the output's
+ extents.
+ </description>
+ <arg name="frame" type="new_id" interface="zwlr_screencopy_frame_v1"/>
+ <arg name="overlay_cursor" type="int"
+ summary="composite cursor onto the frame"/>
+ <arg name="output" type="object" interface="wl_output"/>
+ <arg name="x" type="int"/>
+ <arg name="y" type="int"/>
+ <arg name="width" type="int"/>
+ <arg name="height" type="int"/>
+ </request>
+
+ <request name="destroy" type="destructor">
+ <description summary="destroy the manager">
+ All objects created by the manager will still remain valid, until their
+ appropriate destroy request has been called.
+ </description>
+ </request>
+ </interface>
+
+ <interface name="zwlr_screencopy_frame_v1" version="1">
+ <description summary="a frame ready for copy">
+ This object represents a single frame.
+
+ When created, a "buffer" event will be sent. The client will then be able
+ to send a "copy" request. If the capture is successful, the compositor
+ will send a "flags" followed by a "ready" event.
+
+ If the capture failed, the "failed" event is sent. This can happen anytime
+ before the "ready" event.
+
+ Once either a "ready" or a "failed" event is received, the client should
+ destroy the frame.
+ </description>
+
+ <event name="buffer">
+ <description summary="buffer information">
+ Provides information about the frame's buffer. This event is sent once
+ as soon as the frame is created.
+
+ The client should then create a buffer with the provided attributes, and
+ send a "copy" request.
+ </description>
+ <arg name="format" type="uint" summary="buffer format"/>
+ <arg name="width" type="uint" summary="buffer width"/>
+ <arg name="height" type="uint" summary="buffer height"/>
+ <arg name="stride" type="uint" summary="buffer stride"/>
+ </event>
+
+ <request name="copy">
+ <description summary="copy the frame">
+ Copy the frame to the supplied buffer. The buffer must have a the
+ correct size, see zwlr_screencopy_frame_v1.buffer. The buffer needs to
+ have a supported format.
+
+ If the frame is successfully copied, a "flags" and a "ready" events are
+ sent. Otherwise, a "failed" event is sent.
+ </description>
+ <arg name="buffer" type="object" interface="wl_buffer"/>
+ </request>
+
+ <enum name="error">
+ <entry name="already_used" value="0"
+ summary="the object has already been used to copy a wl_buffer"/>
+ <entry name="invalid_buffer" value="1"
+ summary="buffer attributes are invalid"/>
+ </enum>
+
+ <enum name="flags" bitfield="true">
+ <entry name="y_invert" value="1" summary="contents are y-inverted"/>
+ </enum>
+
+ <event name="flags">
+ <description summary="frame flags">
+ Provides flags about the frame. This event is sent once before the
+ "ready" event.
+ </description>
+ <arg name="flags" type="uint" enum="flags" summary="frame flags"/>
+ </event>
+
+ <event name="ready">
+ <description summary="indicates frame is available for reading">
+ Called as soon as the frame is copied, indicating it is available
+ for reading. This event includes the time at which presentation happened
+ at.
+
+ The timestamp is expressed as tv_sec_hi, tv_sec_lo, tv_nsec triples,
+ each component being an unsigned 32-bit value. Whole seconds are in
+ tv_sec which is a 64-bit value combined from tv_sec_hi and tv_sec_lo,
+ and the additional fractional part in tv_nsec as nanoseconds. Hence,
+ for valid timestamps tv_nsec must be in [0, 999999999]. The seconds part
+ may have an arbitrary offset at start.
+
+ After receiving this event, the client should destroy the object.
+ </description>
+ <arg name="tv_sec_hi" type="uint"
+ summary="high 32 bits of the seconds part of the timestamp"/>
+ <arg name="tv_sec_lo" type="uint"
+ summary="low 32 bits of the seconds part of the timestamp"/>
+ <arg name="tv_nsec" type="uint"
+ summary="nanoseconds part of the timestamp"/>
+ </event>
+
+ <event name="failed">
+ <description summary="frame copy failed">
+ This event indicates that the attempted frame copy has failed.
+
+ After receiving this event, the client should destroy the object.
+ </description>
+ </event>
+
+ <request name="destroy" type="destructor">
+ <description summary="delete this object, used or not">
+ Destroys the frame. This request can be sent at any time by the client.
+ </description>
+ </request>
+ </interface>
+</protocol>