### Compile and Install swaylock from Source Source: https://github.com/swaywm/swaylock/blob/master/README.md Commands to build the project using meson and ninja, followed by system-wide installation. ```bash meson build ninja -C build sudo ninja -C build install ``` -------------------------------- ### spawn_comm_child usage in initialize_pw_backend Source: https://github.com/swaywm/swaylock Example call to spawn_comm_child in pam.c's initialize_pw_backend, exiting on failure. ```c /* pam.c: initialize_pw_backend — runs before any config parsing */ if (!spawn_comm_child()) { exit(EXIT_FAILURE); } ``` -------------------------------- ### load_background_image usage example Source: https://github.com/swaywm/swaylock Example call to load_background_image with a wall.png path. On failure, the function already logs an error; fall back to a solid color. ```c cairo_surface_t *img = load_background_image("/usr/share/backgrounds/wall.png"); if (!img) { /* log already emitted; fall back to solid color */ } ``` -------------------------------- ### write_comm_reply usage in pam.c Source: https://github.com/swaywm/swaylock Example from pam.c that calls write_comm_reply and exits on failure. ```c /* pam.c */ if (!write_comm_reply(success)) { exit(EXIT_FAILURE); } ``` -------------------------------- ### Usage example of swaylock_log and swaylock_log_errno Source: https://github.com/swaywm/swaylock Shows how to use the logging macros in practice. Includes a debug log for image loading and an error log with errno for a failed write. ```c #include "log.h" swaylock_log(LOG_DEBUG, "Loaded image %s for output %s", path, output); if (write(fd, buf, n) != n) { swaylock_log_errno(LOG_ERROR, "write() failed"); return false; } ``` -------------------------------- ### password_buffer_create usage example Source: https://github.com/swaywm/swaylock Shows how to allocate the password buffer with a 1024-byte capacity and handle allocation failure. The buffer is zero-initialized after creation. ```c 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; } state.password.buffer[0] = 0; /* main.c:1161-1168 */ ``` -------------------------------- ### PAM service file for swaylock Source: https://github.com/swaywm/swaylock Installed to /etc/pam.d/swaylock by install_data('pam/swaylock', install_dir: sysconfdir/'pam.d'). Includes the 'login' configuration file. The service name is hard-coded as "swaylock" in pam_start (pam.c:100). ```plaintext # # PAM configuration file for the swaylock screen locker. By default, it includes # the 'login' configuration file (see /etc/pam.d/login) # auth include login ``` -------------------------------- ### read_comm_request usage in shadow.c loop Source: https://github.com/swaywm/swaylock Example loop from shadow.c's run_pw_backend_child that calls read_comm_request, exits on failure, breaks on EOF, and processes the password. ```c /* shadow.c: run_pw_backend_child loop */ 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); ... } ``` -------------------------------- ### Typical sway binding: bindsym exec swaylock Source: https://github.com/swaywm/swaylock Binds the $mod+Shift+l key combination in the sway config to execute swaylock with a fullscreen lock and an image. This is a typical sway keybinding example. ```sh bindsym $mod+Shift+l exec swaylock -f -i ~/wallpaper.png ``` -------------------------------- ### Example swaylock_handle_key call Source: https://github.com/swaywm/swaylock Conceptual example of a seat event feeding the password state. This call is made on key press with repeat=false; the repeat=true flag suppresses repeat activation of Enter. ```c /* example: concept of use — a seat event feeding the password state */ swaylock_handle_key(state, sym, codepoint, false); /* seat.c:108 */ ``` -------------------------------- ### submit_password usage of write_comm_request Source: https://github.com/swaywm/swaylock Example of submit_password calling write_comm_request and handling failure by setting auth state to invalid. ```c void submit_password(struct swaylock_state *state) { if (state->args.ignore_empty && state->password.len == 0) { return; } if (state->auth_state == AUTH_STATE_VALIDATING) { return; } state->input_state = INPUT_STATE_IDLE; state->auth_state = AUTH_STATE_VALIDATING; cancel_password_clear(state); cancel_input_idle(state); if (!write_comm_request(&state->password)) { state->auth_state = AUTH_STATE_INVALID; schedule_auth_idle(state); } damage_state(state); } /* password.c:110 — note auth_state is never re-validated here on write failure */ ``` -------------------------------- ### Example swaylock config file Source: https://github.com/swaywm/swaylock Shows the config file format: one option per line, long-option=value for valued options, bare long-option for flags, leading dashes omitted, '#' comments and blank lines skipped. The 'image=' path undergoes shell expansion; a bad line aborts config loading and exits 1. ```sh # /etc/swaylock/config image=/usr/share/backgrounds/wall.png scaling=center font=DejaVu Sans ring-color=ff00ff show-failed-attempts ``` -------------------------------- ### cairo_set_source_u32 usage example Source: https://github.com/swaywm/swaylock Shows how to apply a background color from swaylock state to a Cairo context. The default background color is 0xA3A3A3FF (light gray). ```c cairo_set_source_u32(cairo, state->args.colors.background); // 0xA3A3A3FF default cairo_paint(cairo); ``` -------------------------------- ### set_input_idle callback resets timer pointer Source: https://github.com/swaywm/swaylock Example callback in password.c that resets the stored timer pointer to NULL after the loop frees the timer, preventing use of an invalid handle. ```c static void set_input_idle(void *data) { struct swaylock_state *state = data; state->input_idle_timer = NULL; /* timer was freed by the loop */ state->input_state = INPUT_STATE_IDLE; damage_state(state); } ``` -------------------------------- ### utf8_last_size function declaration Source: https://github.com/swaywm/swaylock Declares a function that returns the byte size of the last UTF-8 character in a NUL-terminated string. It does not validate the buffer; it only finds the first byte that denotes the start of a UTF-8 character. ```c /** * 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); ``` -------------------------------- ### Minimal lock: swaylock Source: https://github.com/swaywm/swaylock Runs swaylock with default settings to lock the screen. No arguments are required. ```sh swaylock ``` -------------------------------- ### swaylock usage synopsis Source: https://github.com/swaywm/swaylock Program synopsis from swaylock.1.scd and in-binary usage text at main.c:472. Shows the command-line invocation format. ```bash swaylock [options...] ``` -------------------------------- ### Configure suid Permissions for swaylock Source: https://github.com/swaywm/swaylock/blob/master/README.md Set the suid bit on the swaylock binary for systems where passwords are stored in /etc/shadow and PAM is not used. ```bash sudo chmod a+s /usr/local/bin/swaylock ``` -------------------------------- ### Black background with per-output images: swaylock -c -i Source: https://github.com/swaywm/swaylock Sets a black background color and assigns images per output. The second -i uses an empty output name (::) to apply to all outputs, and the path contains colons. ```sh swaylock -c 000000 -i eDP-1:~/wallpaper.png -i '::/path/with:colons.png' ``` -------------------------------- ### Typical consumer pattern using utf8_chsize and utf8_encode Source: https://github.com/swaywm/swaylock Shows a typical usage pattern from password.c: checks buffer space with utf8_chsize, then encodes the codepoint and advances the length. ```c /* Typical consumer pattern (as in password.c) */ size_t need = utf8_chsize(codepoint); if (pw->len + need + 1 < pw->buffer_len) { utf8_encode(&pw->buffer[pw->len], codepoint); pw->len += need; } ``` -------------------------------- ### gdk_cairo_image_surface_create_from_pixbuf Source: https://github.com/swaywm/swaylock Creates a Cairo surface from a GdkPixbuf, converting to CAIRO_FORMAT_RGB24 or CAIRO_FORMAT_ARGB32 with alpha premultiplication. Returns NULL on error. Only available when built with gdk-pixbuf support. ```APIDOC ## gdk_cairo_image_surface_create_from_pixbuf ### Description Creates a Cairo surface from a GdkPixbuf, converting to CAIRO_FORMAT_RGB24 or CAIRO_FORMAT_ARGB32 with alpha premultiplication. Returns NULL on error. Only available when built with gdk-pixbuf support. ### Parameters - `gdkbuf` (const GdkPixbuf *) - Required - Source pixbuf (not consumed; caller retains ownership) ### Returns A new cairo_surface_t * (caller destroys) with the pixbuf converted to CAIRO_FORMAT_RGB24 (3 channels) or CAIRO_FORMAT_ARGB32 (4 channels, alpha-premultiplied). Returns NULL when the pixbuf has fewer than 3 channels, when pixel data is unavailable, or when surface creation failed. ``` -------------------------------- ### Configure sgid Permissions for swaylock Source: https://github.com/swaywm/swaylock/blob/master/README.md Set the sgid bit on the swaylock binary for systems where /etc/shadow is owned by the shadow group. ```bash sudo chgrp shadow /usr/local/bin/swaylock sudo chmod g+s /usr/local/bin/swaylock ``` -------------------------------- ### swaylock_log_init function declaration Source: https://github.com/swaywm/swaylock Initializes the logging system with a verbosity threshold. If verbosity is less than LOG_IMPORTANCE_LAST, it becomes the active threshold. ```c void swaylock_log_init(enum log_importance verbosity); ``` -------------------------------- ### parse_options usage of parse_background_mode Source: https://github.com/swaywm/swaylock Shows how parse_options in main.c handles the -s/--scaling option. Returns 1 (usage error) when the mode is BACKGROUND_MODE_INVALID. ```c // main.c: parse_options handles -s/--scaling enum background_mode mode = parse_background_mode(optarg); if (mode == BACKGROUND_MODE_INVALID) { return 1; // usage error } ``` -------------------------------- ### render.c background painting with render_background_image Source: https://github.com/swaywm/swaylock Shows how render.c paints the background color and then the image unless mode is BACKGROUND_MODE_SOLID_COLOR. Uses CAIRO_OPERATOR_SOURCE for the color and CAIRO_OPERATOR_OVER for the image. ```c /* render.c: paint background color, then the image (unless solid_color) */ cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE); cairo_set_source_u32(cairo, state->args.colors.background); cairo_paint(cairo); if (surface->image && state->args.mode != BACKGROUND_MODE_SOLID_COLOR) { cairo_set_operator(cairo, CAIRO_OPERATOR_OVER); render_background_image(cairo, surface->image, state->args.mode, buffer_width, buffer_height); } ``` -------------------------------- ### gdk_cairo_image_surface_create_from_pixbuf function declaration Source: https://github.com/swaywm/swaylock Declares a helper that converts a GdkPixbuf to a Cairo surface. Only available when built with gdk-pixbuf support (HAVE_GDK_PIXBUF). Returns a new surface in CAIRO_FORMAT_RGB24 or CAIRO_FORMAT_ARGB32, or NULL on failure. The caller retains ownership of the pixbuf and must destroy the returned surface. ```c cairo_surface_t* gdk_cairo_image_surface_create_from_pixbuf( const GdkPixbuf *gdkbuf); ``` -------------------------------- ### password_buffer_create Source: https://github.com/swaywm/swaylock Creates a page-aligned, mlock-ed memory buffer for storing secrets. Returns NULL on failure with errno preserved. ```APIDOC ## password_buffer_create ### Description Creates a page-aligned, mlock-ed memory buffer for storing secrets. Returns NULL on failure with errno preserved. ### Function Signature ```c char *password_buffer_create(size_t size); ``` ### Parameters - `size` (size_t) - Required - Requested capacity in bytes ### Returns - A page-aligned, locked buffer of `size` bytes, or `NULL` on failure (errno preserved). ### Example ```c 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; } state.password.buffer[0] = 0; ``` ``` -------------------------------- ### create_buffer function declaration Source: https://github.com/swaywm/swaylock Creates a pool buffer with given dimensions and format. Returns buf on success, NULL on failure. Internally uses anonymous shm_open with 100 retries and wraps mmap in a Cairo surface. ```c struct pool_buffer *create_buffer(struct wl_shm *shm, struct pool_buffer *buf, int32_t width, int32_t height, uint32_t format); ``` -------------------------------- ### Daemonized lock with readiness notification: swaylock -f -R Source: https://github.com/swaywm/swaylock Daemonizes swaylock and provides a writable file descriptor (fd 9) backed by a FIFO. After the session is locked, swaylock writes a newline readiness byte to the fd; the display can then be blanked. ```sh mkfifo /tmp/lock-ready ``` ```sh swaylock -f -R 9 9<>/tmp/lock-ready ``` -------------------------------- ### render_background_image function signature Source: https://github.com/swaywm/swaylock Paints the image scaled per mode using cairo_paint inside cairo_save/cairo_restore. Modes: STRETCH, FILL, FIT, CENTER, TILE; SOLID_COLOR and INVALID trigger assert(0) and must be guarded by the caller. ```c void render_background_image(cairo_t *cairo, cairo_surface_t *image, enum background_mode mode, int buffer_width, int buffer_height); ``` -------------------------------- ### Wrapper script handling swaylock exit codes and signals Source: https://github.com/swaywm/swaylock Use this shell snippet in wrapper scripts or session managers to handle swaylock exit codes: 0 for normal unlock, 2 for lock failure (another locker running), and other codes for unexpected exits. It also shows how to unlock programmatically with pkill -USR1 swaylock and how to detect a crashed auth subprocess via the log message 'Password checking subprocess crashed; exiting.' ```sh swaylock -f -R 9 9<>/tmp/lock-ready status=$? case $status in 0) : ;; # unlocked normally 2) notify-send "lock failed (another locker running?)";; *) notify-send "swaylock exited with $status";; esac # Unlock programmatically (compositor permitting): pkill -USR1 swaylock # runs the SIGUSR1 unlock-and-exit path # Detect a crashed auth subprocess in logs: # "Password checking subprocess crashed; exiting." ``` -------------------------------- ### destroy_buffer usage and get_next_buffer usage Source: https://github.com/swaywm/swaylock Shows teardown of the two indicator buffers in main.c and acquisition of an indicator buffer in render.c, including error handling when no buffer is available. ```c /* main.c: destroy_surface — teardown of the two indicator buffers */ destroy_buffer(&surface->indicator_buffers[0]); destroy_buffer(&surface->indicator_buffers[1]); ``` ```c /* render.c: render_frame — acquire an indicator buffer */ struct pool_buffer *buffer = get_next_buffer(state->shm, surface->indicator_buffers, buffer_width, buffer_height); if (buffer == NULL) { swaylock_log(LOG_ERROR, "No buffer"); return false; } ``` -------------------------------- ### load_background_image function signature Source: https://github.com/swaywm/swaylock Loads an image file into a cairo surface. Returns a new surface on success or NULL on failure; caller owns the surface and must call cairo_surface_destroy. With HAVE_GDK_PIXBUF, decodes via gdk_pixbuf_new_from_file and applies embedded orientation; without it, only PNG is supported via cairo_image_surface_create_from_png. ```c cairo_surface_t *load_background_image(const char *path); ``` -------------------------------- ### Logging macros swaylock_log and swaylock_log_errno Source: https://github.com/swaywm/swaylock Macros that wrap _swaylock_log. swaylock_log prepends [file:line]; swaylock_log_errno appends strerror(errno). ```c #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)) ``` -------------------------------- ### spawn_comm_child function declaration Source: https://github.com/swaywm/swaylock Declares the function that creates pipes and forks the communication child process. Returns true on success, false on failure with error logging. ```c bool spawn_comm_child(void); ``` -------------------------------- ### Config-driven invocation with CLI override: swaylock --config --ring-color Source: https://github.com/swaywm/swaylock Loads a configuration file and overrides the ring color via the command line. The CLI option takes precedence over the config file value. ```sh swaylock --config /etc/swaylock/config --ring-color ff0000 ``` -------------------------------- ### clear_buffer implementation (password.c) Source: https://github.com/swaywm/swaylock Volatile-zeroes the buffer so the compiler cannot elide it. Used for secrets. ```c 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; } } ``` -------------------------------- ### Enums auth_state and input_state in swaylock.h Source: https://github.com/swaywm/swaylock Defines the state machine enums for authentication and input status. auth_state tracks authentication attempts (IDLE, VALIDATING, INVALID), while input_state tracks password buffer/typing status (IDLE, CLEAR, LETTER, BACKSPACE, NEUTRAL). These are stored in state->auth_state and state->input_state, and the renderer maps them to color sets and indicator text. ```c // Indicator state: status of authentication attempt enum auth_state { AUTH_STATE_IDLE, // nothing happening AUTH_STATE_VALIDATING, // currently validating password AUTH_STATE_INVALID, // displaying message: password was wrong }; // Indicator state: status of password buffer / typing letters enum input_state { INPUT_STATE_IDLE, // nothing happening; other states decay to this after time INPUT_STATE_CLEAR, // displaying message: password buffer was cleared INPUT_STATE_LETTER, // pressed a key that input a letter INPUT_STATE_BACKSPACE, // pressed backspace and removed a letter INPUT_STATE_NEUTRAL, // pressed a key (like Ctrl) that did nothing }; ``` -------------------------------- ### loop_add_fd usage in main.c Source: https://github.com/swaywm/swaylock Registers the Wayland display and the auth-reply fd with the event loop. Each call adds a file descriptor with POLLIN mask and a corresponding callback. ```c /* main.c: register the Wayland display and the auth-reply fd */ 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); ``` -------------------------------- ### loop_create Source: https://github.com/swaywm/swaylock Creates a new event loop. Returns a pointer to the new loop or NULL on allocation failure. ```APIDOC ## loop_create ### Description Creates a new event loop. ### Method C function ### Signature ```c struct loop *loop_create(void); ``` ### Parameters None. ### Returns - `struct loop *` - A new event loop, or `NULL` on allocation failure (logs `Unable to allocate memory for loop`). Initial fd capacity is 10. ``` -------------------------------- ### _swaylock_strip_path function declaration Source: https://github.com/swaywm/swaylock Strips a leading './' or '/' from a file path, used to shorten [file:line] prefixes in log messages. ```c const char *_swaylock_strip_path(const char *filepath); ``` -------------------------------- ### to_cairo_subpixel_order usage in configure_font_drawing Source: https://github.com/swaywm/swaylock Shows how to set the subpixel order on a Cairo font options object using the converted value from the Wayland surface's subpixel property. ```c /* render.c: configure_font_drawing */ cairo_font_options_set_subpixel_order(fo, to_cairo_subpixel_order(subpixel)); ``` -------------------------------- ### struct swaylock_xkb definition Source: https://github.com/swaywm/swaylock Holds xkbcommon state for a seat. Lives inside struct swaylock_state. context is created once in main; keymap/state are populated by the wl_keyboard.keymap event. ```c struct swaylock_xkb { bool caps_lock; bool control; struct xkb_state *state; struct xkb_context *context; struct xkb_keymap *keymap; }; ``` -------------------------------- ### enum background_mode definition Source: https://github.com/swaywm/swaylock Defines the background scaling modes used by the --scaling CLI argument and scaling= config key. BACKGROUND_MODE_INVALID is a sentinel returned by parse_background_mode for unknown names. ```c 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, }; ``` -------------------------------- ### to_cairo_subpixel_order Source: https://github.com/swaywm/swaylock Converts a Wayland output subpixel order to the corresponding Cairo subpixel order for font rendering. Unknown or unsupported subpixel values map to CAIRO_SUBPIXEL_ORDER_DEFAULT. ```APIDOC ## to_cairo_subpixel_order ### Description Converts a Wayland output subpixel order to the corresponding Cairo subpixel order for font rendering. Unknown or unsupported subpixel values map to CAIRO_SUBPIXEL_ORDER_DEFAULT. ### Parameters - `subpixel` (enum wl_output_subpixel) - Required - Subpixel geometry reported by wl_output (surface->subpixel) ### Returns The corresponding cairo_subpixel_order_t: WL_OUTPUT_SUBPIXEL_HORIZONTAL_RGB → CAIRO_SUBPIXEL_ORDER_RGB, HORIZONTAL_BGR → BGR, VERTICAL_RGB → VRGB, VERTICAL_BGR → VBGR, any other value → CAIRO_SUBPIXEL_ORDER_DEFAULT. ### Request Example ```c /* render.c: configure_font_drawing */ cairo_font_options_set_subpixel_order(fo, to_cairo_subpixel_order(subpixel)); ``` ``` -------------------------------- ### to_cairo_subpixel_order function declaration Source: https://github.com/swaywm/swaylock Declares a helper that converts a Wayland output subpixel enum to a Cairo subpixel order for font rendering. Maps HORIZONTAL_RGB to RGB, HORIZONTAL_BGR to BGR, VERTICAL_RGB to VRGB, VERTICAL_BGR to VBGR, and any other value to CAIRO_SUBPIXEL_ORDER_DEFAULT. ```c cairo_subpixel_order_t to_cairo_subpixel_order(enum wl_output_subpixel subpixel); ``` -------------------------------- ### append_ch function using utf8_encode Source: https://github.com/swaywm/swaylock Shows how password.c appends a codepoint to the password buffer using utf8_chsize and utf8_encode. It returns early if the buffer is too small, leaving a TODO for error display. ```c 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) { return; /* TODO: Display error */ } utf8_encode(&pw->buffer[pw->len], codepoint); pw->buffer[pw->len + utf8_size] = 0; pw->len += utf8_size; } /* password.c:38-47 */ ``` -------------------------------- ### write_comm_request function declaration Source: https://github.com/swaywm/swaylock Declares the function that serializes and writes the password to the child process. Always clears the password buffer on return. ```c // Requests the provided password to be checked. The password is always cleared // when the function returns. bool write_comm_request(struct swaylock_password *pw); ``` -------------------------------- ### password_buffer_create declaration Source: https://github.com/swaywm/swaylock Declares a function that allocates a page-aligned, mlock-ed buffer for secrets. Returns NULL on failure, preserving errno. Callers must later call password_buffer_destroy, not free. ```c char *password_buffer_create(size_t size); ``` -------------------------------- ### write_comm_reply function signature Source: https://github.com/swaywm/swaylock Child-side only. Writes a 1-byte authentication reply. Returns true on full write, false on short write or error. ```c bool write_comm_reply(bool success); ``` -------------------------------- ### struct swaylock_seat definition Source: https://github.com/swaywm/swaylock Per-seat runtime bookkeeping. repeat_* fields mirror wl_keyboard.repeat_info settings; rate is converted from keys/sec to milliseconds (repeat_period_ms = 1000 / rate); rate <= 0 stores -1, disabling repeat. ```c struct swaylock_seat { struct swaylock_state *state; struct wl_pointer *pointer; struct wl_keyboard *keyboard; int32_t repeat_period_ms; int32_t repeat_delay_ms; uint32_t repeat_sym; uint32_t repeat_codepoint; struct loop_timer *repeat_timer; }; ``` -------------------------------- ### seat_listener extern declaration Source: https://github.com/swaywm/swaylock Declares the wl_seat_listener used to bind seat events. Defined at seat.c:279-282 with handlers for capabilities and name. Attached in main.c:272 via wl_seat_add_listener. ```c extern const struct wl_seat_listener seat_listener; ``` -------------------------------- ### parse_background_mode function declaration Source: https://github.com/swaywm/swaylock Declares the function that parses a case-sensitive mode name into an enum background_mode value. Returns BACKGROUND_MODE_INVALID for unknown strings, logging 'Unsupported background mode: %s' at LOG_ERROR. ```c enum background_mode parse_background_mode(const char *mode); ``` -------------------------------- ### get_next_buffer function declaration Source: https://github.com/swaywm/swaylock Returns the first non-busy slot from a double-buffer pool, re-creating it if dimensions differ. Returns NULL when both slots are busy or creation fails. ```c struct pool_buffer *get_next_buffer(struct wl_shm *shm, struct pool_buffer pool[static 2], uint32_t width, uint32_t height); ``` -------------------------------- ### clear_buffer declaration (swaylock.h) Source: https://github.com/swaywm/swaylock Declares the clear_buffer function that zeroizes a memory buffer. Used for secrets to prevent compiler optimization. ```c void clear_buffer(char *buf, size_t size); ``` -------------------------------- ### _swaylock_log function declaration Source: https://github.com/swaywm/swaylock Logs a message at the given verbosity level. Messages with verbosity greater than the active threshold are dropped. Output goes to stderr with a timestamp and optional color when stderr is a TTY. ```c void _swaylock_log(enum log_importance verbosity, const char *format, ...) _ATTRIB_PRINTF(2, 3); ``` -------------------------------- ### utf8_size function declaration Source: https://github.com/swaywm/swaylock Declares a function that returns the size of the next UTF-8 character. It returns 1-6 for valid lead bytes or -1 for an invalid lead byte. Not currently used by swaylock's input path. ```c /** * Returns the size of the next UTF-8 character */ int utf8_size(const char *str); ``` -------------------------------- ### loop_add_fd Source: https://github.com/swaywm/swaylock Adds a file descriptor to the event loop to be monitored for events. The callback is invoked with the file descriptor, the revents mask, and the provided data pointer. ```APIDOC ## loop_add_fd ### Description Adds a file descriptor to the event loop to be monitored for events. The callback is invoked with the file descriptor, the revents mask, and the provided data pointer. ### Function Signature ```c void loop_add_fd(struct loop *loop, int fd, short mask, void (*func)(int fd, short mask, void *data), void *data); ``` ### Parameters - `loop` (struct loop *) - Required - Target loop - `fd` (int) - Required - File descriptor to watch - `mask` (short) - Required - `poll(2)` event mask (`POLLIN`, `POLLOUT`, …) - `func` (void (*)(int, short, void *)) - Required - Callback; receives fd, `revents`, `data` - `data` (void *) - Required - Opaque callback argument ### Returns Nothing. The pollfd array grows by 10 when full; a failed allocation logs `Unable to allocate memory for event` and the fd is not registered. ### Notes Callbacks always receive `POLLHUP`/`POLLERR` appended to `revents` (see `loop_poll`). ### Example ```c /* main.c: register the Wayland display and the auth-reply fd */ 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); ``` ``` -------------------------------- ### read_comm_reply function signature Source: https://github.com/swaywm/swaylock Parent-side only. Reads the reply byte from the child. Returns true on full read, false on EOF or failure. ```c bool read_comm_reply(bool *auth_success); ``` -------------------------------- ### destroy_buffer function declaration Source: https://github.com/swaywm/swaylock Tears down a pool buffer slot, destroying wl_buffer, Cairo context/surface, munmaps data, and zeroes the struct. Safe to call on a zero-initialized slot. ```c void destroy_buffer(struct pool_buffer *buffer); ``` -------------------------------- ### utf8_chsize function declaration Source: https://github.com/swaywm/swaylock Declares a function that returns the size of a UTF-8 character given a codepoint. Returns 1 for <0x80, 2 for <0x800, 3 for <0x10000, else 4. ```c /** * Returns the size of a UTF-8 character */ size_t utf8_chsize(uint32_t ch); ``` -------------------------------- ### cairo_set_source_u32 function declaration Source: https://github.com/swaywm/swaylock Declares a helper that sets a Cairo source color from a packed uint32_t value. The color is interpreted as 0xRRGGBBAA with high byte red and low byte alpha; each byte is divided by 255.0 to produce rgba. Used for every color read from struct swaylock_colors. ```c void cairo_set_source_u32(cairo_t *cairo, uint32_t color); ``` -------------------------------- ### password_buffer_destroy declaration Source: https://github.com/swaywm/swaylock Declares a function that zeroizes, unlocks, and frees a buffer created by password_buffer_create. Takes the buffer and its original size. ```c void password_buffer_destroy(char *buffer, size_t size); ``` -------------------------------- ### UTF8_MAX_SIZE and UTF8_INVALID macros Source: https://github.com/swaywm/swaylock Defines the maximum encoded length of a valid UTF-8 codepoint (4) and a sentinel value (0x80) for an invalid decodable byte. ```c // 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 ``` -------------------------------- ### enum input_state Source: https://github.com/swaywm/swaylock Defines the typing-state machine for the indicator/highlight. States: INPUT_STATE_IDLE (decayed after 1500 ms of no input), INPUT_STATE_CLEAR (buffer cleared, text 'Cleared'), INPUT_STATE_LETTER (text key pressed, draws highlight arc), INPUT_STATE_BACKSPACE (backspace removed a character, draws highlight arc), INPUT_STATE_NEUTRAL (modifier-only key pressed). Used by struct swaylock_state::input_state, password.c, and render.c. ```c enum input_state { INPUT_STATE_IDLE, // nothing happening; other states decay to this after time INPUT_STATE_CLEAR, // displaying message: password buffer was cleared INPUT_STATE_LETTER, // pressed a key that input a letter INPUT_STATE_BACKSPACE, // pressed backspace and removed a letter INPUT_STATE_NEUTRAL, // pressed a key (like Ctrl) that did nothing }; ``` -------------------------------- ### struct swaylock_image definition Source: https://github.com/swaywm/swaylock Defines the image structure used for each -i/--image argument and config image= line. output_name == NULL marks the default image for all outputs except those with their own image. select_image (main.c:311) prefers an exact output-name match, then the default. ```c struct swaylock_image { char *path; char *output_name; cairo_surface_t *cairo_surface; struct wl_list link; }; ``` -------------------------------- ### struct swaylock_state definition Source: https://github.com/swaywm/swaylock Process-global state for swaylock; a single static instance lives at main.c:1037. Includes event loop, timers, Wayland display and globals, surfaces, images, arguments, password, keyboard state, auth/input state machines, and session-lock objects. ```c struct swaylock_state { struct loop *eventloop; struct loop_timer *input_idle_timer; // timer to reset input state to IDLE struct loop_timer *auth_idle_timer; // timer to stop displaying AUTH_STATE_INVALID struct loop_timer *clear_password_timer; // clears the password buffer struct wl_display *display; struct wl_compositor *compositor; struct wl_subcompositor *subcompositor; struct wl_shm *shm; struct wl_list surfaces; struct wl_list images; struct swaylock_args args; struct swaylock_password password; struct swaylock_xkb xkb; cairo_surface_t *test_surface; cairo_t *test_cairo; // used to estimate font/text sizes enum auth_state auth_state; // state of the authentication attempt enum input_state input_state; // state of the password buffer and key inputs uint32_t highlight_start; // position of highlight; 2048 = 1 full turn int failed_attempts; bool run_display, locked; struct ext_session_lock_manager_v1 *ext_session_lock_manager_v1; struct ext_session_lock_v1 *ext_session_lock_v1; }; ``` -------------------------------- ### utf8_decode function declaration (declared only) Source: https://github.com/swaywm/swaylock Declares a function that grabs the next UTF-8 character and advances the string pointer. This prototype is dead API; no definition exists in the source tree and no code calls it. ```c /** * Grabs the next UTF-8 character and advances the string pointer */ uint32_t utf8_decode(const char **str); ``` -------------------------------- ### struct pool_buffer definition Source: https://github.com/swaywm/swaylock Defines the ARGB8888 wl_shm buffer with companion Cairo surface/context. Fields include width, height, data pointer, size, and a busy flag. ```c 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; }; ``` -------------------------------- ### read_comm_request function signature Source: https://github.com/swaywm/swaylock Child-side only. Reads a password buffer from the parent. Returns bytes read (>0), 0 on EOF, or -1 on failure. The buffer must be destroyed with password_buffer_destroy(buf, size). ```c ssize_t read_comm_request(char **buf_ptr); ``` -------------------------------- ### password_buffer_destroy Source: https://github.com/swaywm/swaylock Frees a password buffer created by password_buffer_create, zeroizing and unlocking the memory first. ```APIDOC ## password_buffer_destroy ### Description Frees a password buffer created by password_buffer_create, zeroizing and unlocking the memory first. ### Function Signature ```c void password_buffer_destroy(char *buffer, size_t size); ``` ### Parameters - `buffer` (char*) - Required - Buffer from `password_buffer_create` - `size` (size_t) - Required - The size passed at creation ### Returns - Nothing ``` -------------------------------- ### struct swaylock_surface definition Source: https://github.com/swaywm/swaylock Per-output lock surface. Contains background and indicator surfaces, session-lock surface, double-buffered indicator buffers, and output configuration details. Used for rendering the lock screen on each output. ```c struct swaylock_surface { cairo_surface_t *image; struct swaylock_state *state; struct wl_output *output; uint32_t output_global_name; struct wl_surface *surface; // surface for background struct wl_surface *child; // indicator surface made into subsurface struct wl_subsurface *subsurface; struct ext_session_lock_surface_v1 *ext_session_lock_surface_v1; struct pool_buffer indicator_buffers[2]; bool created; bool dirty; uint32_t width, height; int32_t scale; enum wl_output_subpixel subpixel; char *output_name; struct wl_list link; struct wl_callback *frame; // Dimensions of last wl_buffer committed to background surface int last_buffer_width, last_buffer_height; }; ``` -------------------------------- ### UTF-8 macros UTF8_MAX_SIZE and UTF8_INVALID Source: https://github.com/swaywm/swaylock Defines UTF8_MAX_SIZE as the maximum encoded length of a valid codepoint and UTF8_INVALID as a sentinel for invalid bytes, used by the unimplemented utf8_decode function. ```c #define UTF8_MAX_SIZE 4 #define UTF8_INVALID 0x80 ``` -------------------------------- ### cairo_set_source_u32 Source: https://github.com/swaywm/swaylock Sets the Cairo source color from a packed uint32_t value. The color is interpreted as 0xRRGGBBAA and converted to an RGBA color with each byte divided by 255.0. ```APIDOC ## cairo_set_source_u32 ### Description Sets the source color on a Cairo context from a packed uint32_t value. The color is interpreted as 0xRRGGBBAA and converted to an RGBA color with each byte divided by 255.0. ### Parameters - `cairo` (cairo_t *) - Required - Target Cairo context - `color` (uint32_t) - Required - 0xRRGGBBAA packed color (0xA3A3A3FF = light gray) ### Returns Nothing. Sets the source to rgba with (r,g,b,a) = color/255.0 per byte; high byte is red, low byte is alpha. ### Request Example ```c cairo_set_source_u32(cairo, state->args.colors.background); // 0xA3A3A3FF default cairo_paint(cairo); ``` ``` -------------------------------- ### schedule_input_idle using loop_add_timer Source: https://github.com/swaywm/swaylock Resets the input-idle timer to 1500 ms. If a timer already exists, it is removed first; the new timer calls set_input_idle on expiry. ```c void schedule_input_idle(struct swaylock_state *state) { if (state->input_idle_timer) { loop_remove_timer(state->eventloop, state->input_idle_timer); } state->input_idle_timer = loop_add_timer( state->eventloop, 1500, set_input_idle, state); } ``` -------------------------------- ### struct swaylock_colors Source: https://github.com/swaywm/swaylock Defines the complete color palette for swaylock. Defaults are set by set_default_colors (main.c:408); each field maps 1:1 to a CLI/config option. Includes background, highlight arcs, separator, layout colors, and four swaylock_colorset fields (inside, line, ring, text). ```c 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; }; ``` -------------------------------- ### enum auth_state Source: https://github.com/swaywm/swaylock Defines the authentication-attempt state machine used by swaylock. States: AUTH_STATE_IDLE (no attempt), AUTH_STATE_VALIDATING (password submitted, child verifying), AUTH_STATE_INVALID (authentication failed, shows 'Wrong' until the 3000 ms auth-idle timer fires). Used by struct swaylock_state::auth_state and consumed by render.c. ```c enum auth_state { AUTH_STATE_IDLE, // nothing happening AUTH_STATE_VALIDATING, // currently validating password AUTH_STATE_INVALID, // displaying message: password was wrong }; ``` -------------------------------- ### loop_add_timer declaration Source: https://github.com/swaywm/swaylock Declares the loop_add_timer function that adds a single-shot timer to the loop. When the timer expires, it is removed and freed; the stored data is not freed by the loop. Returns NULL on allocation failure, logging 'Unable to allocate memory for timer'. ```c /** * 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); ``` -------------------------------- ### utf8_encode function declaration Source: https://github.com/swaywm/swaylock Declares a function that encodes a Unicode codepoint as UTF-8 and returns the length of the encoded character. The destination buffer must have at least utf8_chsize(ch) bytes available. ```c /** * Encodes a character as UTF-8 and returns the length of that character. */ size_t utf8_encode(char *str, uint32_t ch); ``` -------------------------------- ### loop_add_fd declaration Source: https://github.com/swaywm/swaylock Declares the loop_add_fd function that adds a file descriptor to the event loop. The callback receives the fd, revents, and data; callbacks always receive POLLHUP/POLLERR appended to revents. The pollfd array grows by 10 when full, and a failed allocation logs 'Unable to allocate memory for event' and the fd is not registered. ```c /** * 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); ``` -------------------------------- ### struct swaylock_colorset Source: https://github.com/swaywm/swaylock Defines a group of state-dependent colors (0xRRGGBBAA). Fields: input (idle/typing), cleared (when input_state == INPUT_STATE_CLEAR), caps_lock (when Caps Lock active), verifying (when auth_state == AUTH_STATE_VALIDATING), wrong (when auth_state == AUTH_STATE_INVALID). Used by struct swaylock_colors (×4: inside, line, ring, text) and consumed by render.c:set_color_for_state. ```c struct swaylock_colorset { uint32_t input; uint32_t cleared; uint32_t caps_lock; uint32_t verifying; uint32_t wrong; }; ``` -------------------------------- ### enum log_importance definition Source: https://github.com/swaywm/swaylock Defines message importance levels. A message prints when verbosity <= log_importance (current threshold, default LOG_ERROR). LOG_IMPORTANCE_LAST is a sentinel; values >= it are clamped or rejected. ```c enum log_importance { LOG_SILENT = 0, LOG_ERROR = 1, LOG_INFO = 2, LOG_DEBUG = 3, LOG_IMPORTANCE_LAST, }; ``` -------------------------------- ### loop_add_timer Source: https://github.com/swaywm/swaylock Adds a single-shot timer to the event loop that fires after a specified delay. The timer is automatically removed and freed after it expires. ```APIDOC ## loop_add_timer ### Description Adds a single-shot timer to the event loop that fires after a specified delay. The timer is automatically removed and freed after it expires. ### Function Signature ```c struct loop_timer *loop_add_timer(struct loop *loop, int ms, void (*callback)(void *data), void *data); ``` ### Parameters - `loop` (struct loop *) - Required - Target loop - `ms` (int) - Required - Delay in milliseconds (monotonic) - `callback` (void (*)(void *)) - Required - Invoked once on expiry - `data` (void *) - Required - Opaque argument passed to `callback` ### Returns The new `struct loop_timer *` handle, or `NULL` on allocation failure (logs `Unable to allocate memory for timer`). The timer is single-shot: after firing it is removed and freed; the stored `data` is **not** freed by the loop. ### Usage in swaylock (`password.c`) Input-idle reset after **1500 ms**, auth-invalid display reset after **3000 ms**, automatic password clear after **10000 ms**, and key-repeat timers in `seat.c`. ### Example ```c void schedule_input_idle(struct swaylock_state *state) { if (state->input_idle_timer) { loop_remove_timer(state->eventloop, state->input_idle_timer); } state->input_idle_timer = loop_add_timer( state->eventloop, 1500, set_input_idle, state); } ``` ``` -------------------------------- ### loop_poll Source: https://github.com/swaywm/swaylock Polls the event loop, blocking until one of the file descriptors has data. Dispatches fd callbacks and runs expired timers. ```APIDOC ## loop_poll ### Description Polls the event loop. This will block until one of the fds has data. ### Method C function ### Signature ```c void loop_poll(struct loop *loop); ``` ### Parameters - `loop` (struct loop *) - Required - The loop to poll. ### Returns Nothing. Behavior: 1. Computes the timeout as the smallest remaining timer delta (`CLOCK_MONOTONIC`), clamped to `>= 0`. With no fds and no timers it blocks indefinitely (`poll` timeout `INT_MAX`). 2. Calls `poll(loop->fds, loop->fd_length, ms)`. A negative return other than `EINTR` logs `poll failed` and `exit(1)`. 3. Dispatches fd callbacks, always passing `pfd.revents | POLLHUP | POLLERR` so hangup/error are never missed. 4. Runs expired timers; each expired timer's callback is invoked, the timer is unlinked and freed. Timers marked `removed` (see `loop_remove_timer`) are freed without firing. ``` -------------------------------- ### loop_remove_fd function declaration Source: https://github.com/swaywm/swaylock Declares the function to remove a file descriptor from the loop. Returns true if an event for fd was found and removed, freeing the event and compacting the pollfd array; false otherwise. ```c /** * Remove a file descriptor from the loop. */ bool loop_remove_fd(struct loop *loop, int fd); ```