From dace7dca77e9539b5cb459f79c1154d11b3030fe Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Thu, 23 Mar 2023 20:28:57 +0100 Subject: first version of wlock --- .gitignore | 3 + Makefile | 35 +++ config.h | 12 + config.mk | 4 + drw.c | 290 +++++++++++++++++++++ drw.h | 46 ++++ hash.h | 55 ++++ oom.h | 27 ++ protocols/wlr-layer-shell-unstable.xml | 390 +++++++++++++++++++++++++++++ util.c | 36 +++ util.h | 6 + wayland.c | 66 +++++ wayland.h | 10 + wlock.c | 443 +++++++++++++++++++++++++++++++++ 14 files changed, 1423 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 config.h create mode 100644 config.mk create mode 100644 drw.c create mode 100644 drw.h create mode 100644 hash.h create mode 100644 oom.h create mode 100644 protocols/wlr-layer-shell-unstable.xml create mode 100644 util.c create mode 100644 util.h create mode 100644 wayland.c create mode 100644 wayland.h create mode 100644 wlock.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4098f81 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +wlock +*.o +*-protocol.* diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..6d998b3 --- /dev/null +++ b/Makefile @@ -0,0 +1,35 @@ +include config.mk + +PROTOCOLS = wlr-layer-shell-protocol.c xdg-shell-protocol.c +SRC = wlock.c util.c drw.c wayland.c +OBJ = ${SRC:.c=.o} ${PROTOCOLS:.c=.o} +WLR_LAYER_SHELL = ./protocols/wlr-layer-shell-unstable.xml + +default_target: wlock + +wlr-layer-shell-protocol.h: + wayland-scanner client-header < ${WLR_LAYER_SHELL} > $@ + +wlr-layer-shell-protocol.c: wlr-layer-shell-protocol.h + wayland-scanner private-code < ${WLR_LAYER_SHELL} > $@ + +xdg-shell-protocol.h: + wayland-scanner client-header < ${XDG_SHELL} > $@ + +xdg-shell-protocol.c: xdg-shell-protocol.h + wayland-scanner private-code < ${XDG_SHELL} > $@ + +.c.o: + ${CC} -c $< ${CPPFLAGS} + +${OBJ}: ${PROTOCOLS} config.h + +wlock: ${OBJ} + ${CC} -o $@ ${OBJ} ${LDFLAGS} + +install: wlock + install wlock /usr/local/bin/ + chmod u+s /usr/local/bin/wlock + +clean: + rm ${OBJ} wlock ${PROTOCOLS:.c=.h} ${PROTOCOLS} diff --git a/config.h b/config.h new file mode 100644 index 0000000..d17810a --- /dev/null +++ b/config.h @@ -0,0 +1,12 @@ +#include + +static const char user[] = "nobody"; +static const char group[] = "nogroup"; + +static uint32_t background = 0xff282828; +static uint32_t foreground = 0xffebdbb2; +static uint32_t inputbar = 0xffb16286; + +static char fontpath[] = "/usr/share/fonts/TTF/Sauce Code Pro Nerd Font Complete Mono.ttf"; +static unsigned username_fontsize = 30; +static unsigned clock_fontsize = 50; diff --git a/config.mk b/config.mk new file mode 100644 index 0000000..b703df8 --- /dev/null +++ b/config.mk @@ -0,0 +1,4 @@ +LDFLAGS = -lfreetype -lwayland-client -lrt -lxkbcommon -lm -lgrapheme -lcrypt +CPPFLAGS = -DHAVE_SHADOW_H -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/harfbuzz -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/usr/include/sysprof-4 -pthread +XDG_SHELL = /usr/share/wayland-protocols/stable/xdg-shell/xdg-shell.xml +CC = cc diff --git a/drw.c b/drw.c new file mode 100644 index 0000000..e54902c --- /dev/null +++ b/drw.c @@ -0,0 +1,290 @@ +#include +#include +#include +#include +#include +#include + +#include "drw.h" +#include "util.h" + +/* static function declarations */ +static Color to_color(uint32_t color); +static uint32_t to_uint32_t(Color color); +static void draw_bitmap(Canvas *canvas, FT_Bitmap *bitmap, unsigned x, unsigned y, uint32_t color); + + +Color +to_color(uint32_t color) +{ + return *(Color*)(&color); +} + + +uint32_t +to_uint32_t(Color color) +{ + return *(uint32_t*)(&color); +} + + +Canvas* +create_drw(struct wl_shm *shm, unsigned width, unsigned height) +{ + struct wl_shm_pool *pool; + Canvas *canvas; + int stride; + int fd; + + canvas = malloc(sizeof(Canvas)); + canvas->width = width; + canvas->height = height; + + stride = width * sizeof(uint32_t); + canvas->size = stride * height; + + fd = allocate_shm_file(canvas->size); + if (fd == -1) { + return NULL; + } + + canvas->data = mmap( + NULL, + canvas->size, + PROT_READ | PROT_WRITE, + MAP_SHARED, + fd, + 0 + ); + + if (canvas->data == MAP_FAILED) { + close(fd); + return NULL; + } + + pool = wl_shm_create_pool( + shm, + fd, + canvas->size + ); + + canvas->buffer = wl_shm_pool_create_buffer( + pool, + 0, + width, + height, + stride, + WL_SHM_FORMAT_XRGB8888 + ); + + wl_shm_pool_destroy(pool); + close(fd); + + fd = allocate_shm_file(canvas->size); + canvas->tmp_data = mmap(NULL, canvas->size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); + + if (canvas->tmp_data == MAP_FAILED) { + perror("mmap failed"); + return NULL; + } + + close(fd); + return canvas; +} + + +void +free_drw(Canvas *canvas) +{ + munmap(canvas->data, canvas->size); + munmap(canvas->tmp_data, canvas->size); + free(canvas); +} + + +void +drw_push(Canvas *canvas) +{ + memcpy(canvas->data, canvas->tmp_data, canvas->size); +} + + +void +draw_point(Canvas *canvas, unsigned x, unsigned y, uint32_t color) +{ + if (!(x < canvas->width && y < canvas->height)) + return; + + canvas->tmp_data[x + canvas->width * y] = color; +} + + +void +draw_rect(Canvas *canvas, unsigned x, unsigned y, unsigned width, unsigned height, uint32_t color) { + int py; + int px; + + for (py = y; py < y + height; ++py) { + for (px = x; px < x + width; ++px) { + draw_point(canvas, px, py, color); + } + } +} + +Font * +create_font(const char *fontpath, unsigned size) +{ + FT_Error error; + Font * font; + + font = malloc(sizeof(Font)); + + error = FT_Init_FreeType(&font->library); + + if (error) + die("cannot init library"); + + error = FT_New_Face(font->library, fontpath, 0, &font->face); + if (error) + die("cannot open face"); + + error = FT_Set_Pixel_Sizes(font->face, 0, size); + if (error) + die("cannot set char size"); + + error = FT_Select_Charmap(font->face, ft_encoding_unicode); + if (error) + die("cannot set unicode"); + + return font; +} + +void +free_font(Font *font) +{ + FT_Done_Face(font->face); + FT_Done_FreeType(font->library); + free(font); +} + + +void +draw_bitmap(Canvas *canvas, FT_Bitmap *bitmap, unsigned x, unsigned y, uint32_t color) +{ + FT_Int i, j, p, q; + double strength; + uint32_t pixel; + + Color fg = to_color(color); + Color bg; + Color c; + + c.a = fg.a; + + i = x; + p = 0; + + while (p < bitmap->width) { + j = y; + q = 0; + + while (q < bitmap->rows) { + if (i < 0 || j < 0 || i >= canvas->width || j >= canvas->height) { + j++; + q++; + continue; + } + + bg = to_color(canvas->tmp_data[i + j * canvas->width]); + strength = bitmap->buffer[p + q * bitmap->width]; + strength /= 255; + + c.r = (strength * fg.r) + ((1 - strength) * bg.r); + c.g = (strength * fg.g) + ((1 - strength) * bg.g); + c.b = (strength * fg.b) + ((1 - strength) * bg.b); + + pixel = to_uint32_t(c); + draw_point(canvas, i, j, pixel); + + j++; + q++; + } + + i++; + p++; + } +} + + +unsigned +draw_font(Canvas *canvas, Font *font, const char *text, unsigned x, unsigned y, uint32_t color) +{ + FT_GlyphSlot slot; + FT_Error error; + FT_UInt glyph_index; + FT_UInt previous = 0; + uint_least32_t charcode; + FT_Bool has_kerning = FT_HAS_KERNING(font->face); + FT_Vector delta; + + slot = font->face->glyph; + + for (; *text;) { + text += grapheme_decode_utf8(text, sizeof(uint_least32_t), &charcode); + + glyph_index = FT_Get_Char_Index(font->face, charcode); + + if (has_kerning && previous && glyph_index) { + FT_Get_Kerning(font->face, previous, glyph_index, FT_KERNING_DEFAULT, &delta); + x += delta.x >> 6; + } + + error = FT_Load_Glyph(font->face, glyph_index, FT_LOAD_RENDER); + if (error) { + fprintf(stderr, "warning: char not loaded, skipping...\n"); + continue; + } + + draw_bitmap(canvas, &slot->bitmap, x + slot->bitmap_left, y - slot->bitmap_top, color); + + x += slot->advance.x >> 6; + } + + return x; +} + +unsigned +font_width(Font *font, const char *text) +{ + FT_GlyphSlot slot; + FT_Error error; + FT_UInt glyph_index; + FT_UInt previous = 0; + uint_least32_t charcode; + FT_Bool has_kerning = FT_HAS_KERNING(font->face); + FT_Vector delta; + unsigned x = 0; + + slot = font->face->glyph; + + for (; *text;) { + text += grapheme_decode_utf8(text, sizeof(uint_least32_t), &charcode); + + glyph_index = FT_Get_Char_Index(font->face, charcode); + + if (has_kerning && previous && glyph_index) { + FT_Get_Kerning(font->face, previous, glyph_index, FT_KERNING_DEFAULT, &delta); + x += delta.x >> 6; + } + + error = FT_Load_Glyph(font->face, glyph_index, FT_LOAD_RENDER); + if (error) { + fprintf(stderr, "warning: char not loaded, skipping...\n"); + continue; + } + + x += slot->advance.x >> 6; + } + + return x; +} diff --git a/drw.h b/drw.h new file mode 100644 index 0000000..2dab93d --- /dev/null +++ b/drw.h @@ -0,0 +1,46 @@ +#ifndef DRW_H +#define DRW_H + +#include +#include +#include FT_FREETYPE_H +#include FT_BITMAP_H + +#include "wayland.h" + +/* type definitions */ +typedef struct { + uint32_t *tmp_data; + uint32_t *data; + unsigned width; + unsigned height; + uint64_t size; + struct wl_buffer *buffer; +} Canvas; + +typedef struct { + FT_Library library; + FT_Face face; +} Font; + +typedef struct { + uint8_t r; + uint8_t g; + uint8_t b; + uint8_t a; +} Color; + +/* exported functions */ +Canvas* create_drw(struct wl_shm *shm, unsigned width, unsigned height); +void free_drw(Canvas *canvas); +void drw_push(Canvas *canvas); + +void draw_rect(Canvas *canvas, unsigned x, unsigned y, unsigned width, unsigned height, uint32_t color); +void draw_point(Canvas *canvas, unsigned x, unsigned y, uint32_t color); + +Font* create_font(const char *fontpath, unsigned size); +void free_font(Font *font); +unsigned draw_font(Canvas *canvas, Font *font, const char *text, unsigned x, unsigned y, uint32_t color); +unsigned font_width(Font *font, const char *text); + +#endif diff --git a/hash.h b/hash.h new file mode 100644 index 0000000..5de5d45 --- /dev/null +++ b/hash.h @@ -0,0 +1,55 @@ +#if HAVE_SHADOW_H +#include +#endif + +#include +#include +#include +#include +#include +#include + +#include "util.h" + +static const char *get_hash(); + +const char * +get_hash() +{ + const char *hash; + struct passwd *pw; + + /* Check if the current user has a password entry */ + errno = 0; + if (!(pw = getpwuid(getuid()))) { + if (errno) + die("slock: getpwuid: %s\n", strerror(errno)); + else + die("slock: cannot retrieve password entry\n"); + } + hash = pw->pw_passwd; + +#if HAVE_SHADOW_H + if (!strcmp(hash, "x")) { + struct spwd *sp; + if (!(sp = getspnam(pw->pw_name))) + die("slock: getspnam: cannot retrieve shadow entry. " + "Make sure to suid or sgid slock.\n"); + hash = sp->sp_pwdp; + } +#else + if (!strcmp(hash, "*")) { +#ifdef __OpenBSD__ + if (!(pw = getpwuid_shadow(getuid()))) + die("slock: getpwnam_shadow: cannot retrieve shadow entry. " + "Make sure to suid or sgid slock.\n"); + hash = pw->pw_passwd; +#else + die("slock: getpwuid: cannot retrieve shadow entry. " + "Make sure to suid or sgid slock.\n"); +#endif /* __OpenBSD__ */ + } +#endif /* HAVE_SHADOW_H */ + + return hash; +} diff --git a/oom.h b/oom.h new file mode 100644 index 0000000..04d94a7 --- /dev/null +++ b/oom.h @@ -0,0 +1,27 @@ +#ifdef __linux__ +static void disable_oom_killer(); + +#include +#include + +void +disable_oom_killer() +{ + FILE *f; + const char oomfile[] = "/proc/self/oom_score_adj"; + + if (!(f = fopen(oomfile, "w"))) { + if (errno == ENOENT) + return; + die("slock: fopen %s: %s\n", oomfile, strerror(errno)); + } + fprintf(f, "%d", OOM_SCORE_ADJ_MIN); + if (fclose(f)) { + if (errno == EACCES) + die("slock: unable to disable OOM killer. " + "Make sure to suid or sgid slock.\n"); + else + die("slock: fclose %s: %s\n", oomfile, strerror(errno)); + } +} +#endif diff --git a/protocols/wlr-layer-shell-unstable.xml b/protocols/wlr-layer-shell-unstable.xml new file mode 100644 index 0000000..d62fd51 --- /dev/null +++ b/protocols/wlr-layer-shell-unstable.xml @@ -0,0 +1,390 @@ + + + + Copyright © 2017 Drew DeVault + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + the copyright holders not be used in advertising or publicity + pertaining to distribution of the software without specific, + written prior permission. The copyright holders make no + representations about the suitability of this software for any + purpose. It is provided "as is" without express or implied + warranty. + + THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY + SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN + AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + THIS SOFTWARE. + + + + + 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. + + + + + 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. + + After creating a layer_surface object and setting it up, the client + must perform an initial commit without any buffer attached. + The compositor will reply with a layer_surface.configure event. + The client must acknowledge it and is then allowed to attach a buffer + to map the surface. + + 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. + + + + + + + + + + + + + + + + + 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. + + + + + + + + + + + + + This request indicates that the client will not use the layer_shell + object any more. Objects that have been created through this instance + are not affected. + + + + + + + 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 (layer, 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. + + Attaching a null buffer to a layer surface unmaps it. + + Unmapping a layer_surface means that the surface cannot be shown by the + compositor until it is explicitly mapped again. The layer_surface + returns to the state it had right after layer_shell.get_layer_surface. + The client can re-map the surface by performing a commit without any + buffer attached, waiting for a configure event and handling it as usual. + + + + + 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. + + + + + + + + Requests that the compositor anchor the surface to the specified edges + and corners. If two orthogonal 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. + + + + + + + Requests that the compositor avoids occluding an area 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 one + edge or an edge and both perpendicular edges. If the surface is not + anchored, anchored to only two perpendicular edges (a corner), anchored + to only two parallel edges or anchored to all edges, a positive value + will be treated the same as zero. + + A positive zone is the distance from the edge in surface-local + coordinates to consider 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 exclusive 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. + + + + + + + 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. + + + + + + + + + + Types of keyboard interaction possible for layer shell surfaces. The + rationale for this is twofold: (1) some applications are not interested + in keyboard events and not allowing them to be focused can improve the + desktop experience; (2) some applications will want to take exclusive + keyboard focus. + + + + + This value indicates that this surface is not interested in keyboard + events and the compositor should never assign it the keyboard focus. + + This is the default value, set for newly created layer shell surfaces. + + This is useful for e.g. desktop widgets that display information or + only have interaction with non-keyboard input devices. + + + + + Request exclusive keyboard focus if this surface is above the shell surface layer. + + For the top and overlay layers, the seat will always give + exclusive keyboard focus to the top-most layer which has keyboard + interactivity set to exclusive. If this layer contains multiple + surfaces with keyboard interactivity set to exclusive, the compositor + determines the one receiving keyboard events in an implementation- + defined manner. In this case, no guarantee is made when this surface + will receive keyboard focus (if ever). + + For the bottom and background layers, the compositor is allowed to use + normal focus semantics. + + This setting is mainly intended for applications that need to ensure + they receive all keyboard events, such as a lock screen or a password + prompt. + + + + + This requests the compositor to allow this surface to be focused and + unfocused by the user in an implementation-defined manner. The user + should be able to unfocus this surface even regardless of the layer + it is on. + + Typically, the compositor will want to use its normal mechanism to + manage keyboard focus between layer shell surfaces with this setting + and regular toplevels on the desktop layer (e.g. click to focus). + Nevertheless, it is possible for a compositor to require a special + interaction to focus or unfocus layer shell surfaces (e.g. requiring + a click even if focus follows the mouse normally, or providing a + keybinding to switch focus between layers). + + This setting is mainly intended for desktop shell components (e.g. + panels) that allow keyboard interaction. Using this option can allow + implementing a desktop shell that can be fully usable without the + mouse. + + + + + + + Set how keyboard events are delivered to this surface. By default, + layer shell surfaces do not receive keyboard events; this request can + be used to change this. + + This setting is inherited by child surfaces set by the get_popup + request. + + 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. + + Keyboard interactivity is double-buffered, see wl_surface.commit. + + + + + + + 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. + + + + + + + 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. + + + + + + + This request destroys the layer surface. + + + + + + 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. + + + + + + + + + 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. + + + + + + + + + + + + + + + + + + + + + + Change the layer that the surface is rendered on. + + Layer is double-buffered, see wl_surface.commit. + + + + + diff --git a/util.c b/util.c new file mode 100644 index 0000000..176f807 --- /dev/null +++ b/util.c @@ -0,0 +1,36 @@ +/* See LICENSE file for copyright and license details. */ +#include +#include +#include +#include + +#include "util.h" + +void * +ecalloc(size_t nmemb, size_t size) +{ + void *p; + + if (!(p = calloc(nmemb, size))) + die("calloc:"); + return p; +} + +void +die(const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + + if (fmt[0] && fmt[strlen(fmt)-1] == ':') { + fputc(' ', stderr); + perror(NULL); + } else { + fputc('\n', stderr); + } + + exit(1); +} diff --git a/util.h b/util.h new file mode 100644 index 0000000..ec475b1 --- /dev/null +++ b/util.h @@ -0,0 +1,6 @@ +#ifndef UTIL_H +#define UTIL_H + +void die(const char *fmt, ...); + +#endif diff --git a/wayland.c b/wayland.c new file mode 100644 index 0000000..0787ec3 --- /dev/null +++ b/wayland.c @@ -0,0 +1,66 @@ +#include +#include +#include +#include +#include + +#include "wayland.h" + +static void randname(char *buf); +static int create_shm_file(void); + + +void +randname(char *buf) +{ + struct timespec ts; + long r; + int i; + + clock_gettime(CLOCK_REALTIME, &ts); + r = ts.tv_nsec; + for (i = 0; i < 6; ++i) { + buf[i] = 'A'+(r&15)+(r&16)*2; + r >>= 5; + } +} + +int +create_shm_file(void) +{ + int fd; + int retries = 100; + char name[] = "/wl_shm-XXXXXX"; + + do { + randname(name + sizeof(name) - 7); + --retries; + fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + if (fd >= 0) { + shm_unlink(name); + return fd; + } + } while (retries > 0 && errno == EEXIST); + return -1; +} + +int +allocate_shm_file(size_t size) +{ + int ret; + int fd = create_shm_file(); + + if (fd < 0) + return -1; + + do { + ret = ftruncate(fd, size); + } while (ret < 0 && errno == EINTR); + + if (ret < 0) { + close(fd); + return -1; + } + + return fd; +} diff --git a/wayland.h b/wayland.h new file mode 100644 index 0000000..2f6a6ba --- /dev/null +++ b/wayland.h @@ -0,0 +1,10 @@ +#ifndef WAYLAND_H +#define WAYLAND_H + +#include +#include "xdg-shell-protocol.h" +#include "wlr-layer-shell-protocol.h" + +int allocate_shm_file(size_t size); + +#endif diff --git a/wlock.c b/wlock.c new file mode 100644 index 0000000..2574632 --- /dev/null +++ b/wlock.c @@ -0,0 +1,443 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "util.h" +#include "drw.h" +#include "config.h" +#include "oom.h" +#include "hash.h" + +/* macro definitions */ +#define MAX_LINE_LENGTH 1024 +#define match_then_bind(obj, inter, ver) \ + if (strcmp(interface, inter.name) == 0) { \ + obj = wl_registry_bind(wl_registry, name, &inter, ver); + +#define end_match } +#define or_match } else + +/* struct definitions */ +typedef struct { + struct wl_display *display; + struct wl_registry *registry; + struct wl_compositor *compositor; + struct wl_shm *shm; + struct zdwl_manager_v1 *dwl_manager; + struct zwlr_layer_shell_v1 *layer; + struct wl_seat *seat; + struct wl_keyboard *keyboard; + struct xkb_context *xkb_context; + struct xkb_state *xkb_state; + struct xkb_keymap *xkb_keymap; + struct { + uint32_t sym; + uint32_t state; + } keys; + struct { + int timer; + int delay; + int period; + } repeat; +} Client; + +typedef struct Monitor Monitor; +struct Monitor { + uint32_t width; + uint32_t height; + Canvas *canvas; + struct zdwl_output_v1 *dwl_output; + struct wl_output *output; + struct wl_surface *surface; + struct zwlr_layer_surface_v1 *wlr_surface; + Monitor *next; +}; + +/* function definition */ +static void draw_to_monitor(Monitor *mon); +static void update_time(); +static void setup(); +static Monitor *add_monitor(); +static void registry_global(void *data, struct wl_registry *wl_registry, uint32_t name, const char *interface, uint32_t version); +static void seat_capabilities(void *data, struct wl_seat *seat, uint32_t capabilities); +static void wlr_layer_surface_configure(void *data, struct zwlr_layer_surface_v1 *surface, uint32_t serial, uint32_t w, uint32_t h); +static void keyboard_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int32_t fd, uint32_t size); +static void keyboard_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state); +static void keyboard_repeat_info(void *data, struct wl_keyboard *keyboard, int32_t rate, int32_t delay); +static void handle_keyboard_event(); +static void dummy() {} + +/* global variables */ +static const struct wl_registry_listener registry_listnener = { + .global = registry_global, + .global_remove = dummy +}; + +static const struct zwlr_layer_surface_v1_listener wlr_layer_surface_listener = { + .closed = dummy, + .configure = wlr_layer_surface_configure, +}; + +static const struct wl_seat_listener seat_listener = { + .capabilities = seat_capabilities, + .name = dummy, +}; + +static const struct wl_keyboard_listener keyboard_listener = { + .keymap = keyboard_keymap, + .enter = dummy, + .key = keyboard_key, + .leave = dummy, + .modifiers = dummy, + .repeat_info = keyboard_repeat_info, +}; + +Client client = { 0 }; +Monitor *monitors = 0; +char input_field[MAX_LINE_LENGTH] = ""; +int running = 1; +const char *hash; +const char *username; +char timestr[64]; +Font *username_font; +Font *clock_font; + +/* function implementations */ +void +draw_to_monitor(Monitor *mon) +{ + int inputlen = strlen(input_field); + int x; + + draw_rect(mon->canvas, 0, 0, mon->width, mon->height, background); + draw_rect(mon->canvas, (mon->width - inputlen * 20) / 2, mon->height / 2, inputlen * 20, 10, inputbar); + + x = font_width(username_font, username); + draw_font(mon->canvas, username_font, username, (mon->width - x) / 2, mon->height / 2 - 2 * clock_fontsize - 20, foreground); + + x = font_width(clock_font, timestr); + draw_font(mon->canvas, clock_font, timestr, (mon->width - x) / 2, mon->height / 2 - clock_fontsize , foreground); + + drw_push(mon->canvas); + wl_surface_attach(mon->surface, (struct wl_buffer*)mon->canvas->buffer, 0, 0); + wl_surface_damage_buffer(mon->surface, 0, 0, mon->width, mon->height); + wl_surface_commit(mon->surface); +} + + +void +update_time() +{ + Monitor *mon; + time_t rawtime; + struct tm *timeinfo; + + time(&rawtime); + timeinfo = localtime(&rawtime); + sprintf(timestr, "%02d:%02d", timeinfo->tm_hour, timeinfo->tm_min); + + for (mon = monitors; mon; mon = mon->next) + draw_to_monitor(mon); +} + + +Monitor * +add_monitor() +{ + Monitor *last = monitors; + Monitor *mon = malloc(sizeof(Monitor)); + memset(mon, 0, sizeof(Monitor)); + + if (monitors == 0) { + monitors = mon; + } else { + for (; last->next; last = last->next); + last->next = mon; + } + + return mon; +} + +void +registry_global(void *data, struct wl_registry *wl_registry, uint32_t name, const char *interface, uint32_t version) +{ + struct wl_output *output; + Monitor *monitor; + + match_then_bind(client.shm, wl_shm_interface, 1) + or_match match_then_bind(client.compositor, wl_compositor_interface, 4) + or_match match_then_bind(client.layer, zwlr_layer_shell_v1_interface, 1) + or_match match_then_bind(client.seat, wl_seat_interface, 7) + wl_seat_add_listener(client.seat, &seat_listener, &client); + or_match match_then_bind(output, wl_output_interface, 1) + monitor = add_monitor(); + monitor->output = output; + end_match +} + + +void +seat_capabilities(void *data, struct wl_seat *seat, uint32_t capabilities) +{ + int has_keyboard = capabilities & WL_SEAT_CAPABILITY_KEYBOARD; + + if (has_keyboard && client.keyboard == NULL) { + client.keyboard = wl_seat_get_keyboard(client.seat); + wl_keyboard_add_listener(client.keyboard, &keyboard_listener, &client); + } else { + wl_keyboard_release(client.keyboard); + client.keyboard = NULL; + } +} + + +void +wlr_layer_surface_configure(void *data, struct zwlr_layer_surface_v1 *surface, uint32_t serial, uint32_t w, uint32_t h) +{ + Monitor *mon = data; + mon->width = w; + mon->height = h; + + zwlr_layer_surface_v1_ack_configure(surface, serial); + + if (mon->canvas == 0) { + mon->canvas = create_drw(client.shm, mon->width, mon->height); + + if (mon->canvas == 0) { + die("wlock: could not create canvas:", strerror(errno)); + } + } + + draw_to_monitor(mon); +} + + +void +keyboard_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int32_t fd, uint32_t size) +{ + char *key_shm; + struct xkb_keymap *keymap; + struct xkb_state *state; + + if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) + return; + + key_shm = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0); + + if (key_shm == MAP_FAILED) + return; + + keymap = xkb_keymap_new_from_string( + client.xkb_context, key_shm, + XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS + ); + + munmap(key_shm, size); + close(fd); + + state = xkb_state_new(keymap); + xkb_keymap_unref(client.xkb_keymap); + xkb_state_unref(client.xkb_state); + + client.xkb_state = state; + client.xkb_keymap = keymap; +} + + +void +keyboard_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state) +{ + struct itimerspec spec = { 0 }; + uint32_t keycode = key + 8; + xkb_keysym_t sym = xkb_state_key_get_one_sym(client.xkb_state, keycode); + client.keys.sym = sym; + client.keys.state = state; + handle_keyboard_event(); + + + if (client.keys.state == WL_KEYBOARD_KEY_STATE_PRESSED && client.repeat.period >= 0) { + spec.it_value.tv_sec = client.repeat.delay / 1000; + spec.it_value.tv_nsec = (client.repeat.delay % 1000) * 1000000; + timerfd_settime(client.repeat.timer, 0, &spec, 0); + } else if (client.keys.state == WL_KEYBOARD_KEY_STATE_RELEASED) { + timerfd_settime(client.repeat.timer, 0, &spec, 0); + } +} + + +void +keyboard_repeat_info(void *data, struct wl_keyboard *keyboard, int32_t rate, int32_t delay) +{ + client.repeat.delay = delay; + + if (rate > 0) + client.repeat.period = 1000 / rate; + else + client.repeat.period = -1; +} + + +void +handle_keyboard_event() +{ + char buf[8]; + char *inputhash; + Monitor *mon; + + if (client.keys.state == WL_KEYBOARD_KEY_STATE_PRESSED) { + switch (client.keys.sym) { + case XKB_KEY_Escape: + memset(input_field, 0, MAX_LINE_LENGTH); + break; + case XKB_KEY_KP_Enter: /* fallthrough */ + case XKB_KEY_Return: + if (!(inputhash = crypt(input_field, hash))) + fprintf(stderr, "slock: crypt: %s\n", strerror(errno)); + else + running = !!strcmp(inputhash, hash); + memset(input_field, 0, MAX_LINE_LENGTH); + break; + case XKB_KEY_BackSpace: + if (strlen(input_field)) + input_field[strlen(input_field) - 1] = 0; + break; + default: + if (xkb_keysym_to_utf8(client.keys.sym, buf, sizeof(buf))) { + strncpy(input_field + strlen(input_field), buf, MAX_LINE_LENGTH - strlen(input_field)); + } + break; + } + + if (running) { + for (mon = monitors; mon; mon = mon->next) + draw_to_monitor(mon); + } + } +} + +void +setup() +{ + Monitor *mon; + char namespace[] = "dmenu-wl"; + uint32_t layer = ZWLR_LAYER_SHELL_V1_LAYER_TOP; + uint32_t anchor = ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP | + ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM | + ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT | + ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT; + + username_font = create_font(fontpath, username_fontsize * 1.5); + clock_font = create_font(fontpath, clock_fontsize * 1.5); + client.repeat.timer = timerfd_create(CLOCK_MONOTONIC, 0); + client.xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + client.display = wl_display_connect(0); + client.registry = wl_display_get_registry(client.display); + wl_registry_add_listener(client.registry, ®istry_listnener, &client); + wl_display_roundtrip(client.display); + + for (mon = monitors; mon; mon = mon->next) { + + mon->surface = wl_compositor_create_surface(client.compositor); + mon->wlr_surface = zwlr_layer_shell_v1_get_layer_surface(client.layer, mon->surface, mon->output, layer, namespace); + + zwlr_layer_surface_v1_set_exclusive_zone(mon->wlr_surface, -1); + zwlr_layer_surface_v1_set_keyboard_interactivity(monitors->wlr_surface, 1); + + zwlr_layer_surface_v1_add_listener(mon->wlr_surface, &wlr_layer_surface_listener, mon); + + zwlr_layer_surface_v1_set_anchor(mon->wlr_surface, anchor); + + wl_surface_commit(mon->surface); + wl_display_roundtrip(client.display); + } +} + + +int +main(int argc, char *argv[]) +{ + struct itimerspec spec = { 0 }; + struct pollfd fds[3]; + struct passwd *pw; + struct group *grp; + + username = getenv("USER"); + + if (!(pw = getpwnam(user))) + die("slock: getpwname: user entry not found"); + if (!(grp = getgrnam(group))) + die("slock: getpwname: user entry not found"); + + hash = get_hash(); + if (!crypt("", hash)) + die("slock: crypt: %s\n", strerror(errno)); + +#ifdef __linux__ + disable_oom_killer(); +#endif + + /* TODO: Drop privileges */ + + setup(); + + fds[0].fd = wl_display_get_fd(client.display); + fds[0].events = POLLIN; + fds[1].fd = client.repeat.timer; + fds[1].events = POLLIN; + fds[2].fd = timerfd_create(CLOCK_MONOTONIC, 0); + fds[2].events = POLLIN; + + spec.it_interval.tv_sec = 1; + spec.it_value.tv_nsec = 1; + timerfd_settime(fds[2].fd, 0, &spec, 0); + spec.it_interval.tv_nsec = 0; + + while (running) { + if (wl_display_flush(client.display) < 0) { + if (errno == EAGAIN) + continue; + break; + } + + if (poll(fds, sizeof(fds) / sizeof(*fds), -1) < 0) { + if (errno == EAGAIN) + continue; + break; + } + + if (fds[0].revents & POLLIN) { + if (wl_display_dispatch(client.display) < 0) { + running = 0; + } + } + + if (fds[1].revents & POLLIN) { + handle_keyboard_event(); + spec.it_value.tv_sec = client.repeat.period / 1000; + spec.it_value.tv_nsec = (client.repeat.period % 1000) * 1000000; + timerfd_settime(client.repeat.timer, 0, &spec, 0); + } + + if (fds[2].revents & POLLIN) { + update_time(); + } + } + + wl_display_dispatch(client.display); +} -- cgit v1.2.3-70-g09d2