diff options
| author | user <user@clank> | 2026-09-02 14:57:46 +0200 |
|---|---|---|
| committer | user <user@clank> | 2026-09-02 14:57:46 +0200 |
| commit | bac4b796f3f729d8d76b9c7c973126eac49872f2 (patch) | |
| tree | 0d040eb64e433122f982ea45912eba37ab54822a | |
| parent | webdemo: version from contrib/version, published by ship (diff) | |
| parent | multi-attach: the config knobs (diff) | |
| download | slosh-bac4b796f3f729d8d76b9c7c973126eac49872f2.tar.gz slosh-bac4b796f3f729d8d76b9c7c973126eac49872f2.tar.xz slosh-bac4b796f3f729d8d76b9c7c973126eac49872f2.zip | |
Merge branch 'multiplayer': shared multi-client attach
Several terminals can attach to one session at once: the canonical
screen becomes a model projected into every client's own size, with
per-client diff history, input parsing and kitty graphics state. The
active client (newest attach, then last input) sizes the canvas by
default; multi_attach and size_follows in the config control both
halves of the policy.
| -rw-r--r-- | Makefile | 11 | ||||
| -rw-r--r-- | README.md | 7 | ||||
| -rw-r--r-- | config/config.kdl | 16 | ||||
| -rw-r--r-- | docs/config.md | 2 | ||||
| -rw-r--r-- | docs/index.md | 4 | ||||
| -rw-r--r-- | docs/slosh.1 | 20 | ||||
| -rw-r--r-- | docs/slosh.5 | 20 | ||||
| -rw-r--r-- | include/app.h | 18 | ||||
| -rw-r--r-- | include/config.h | 19 | ||||
| -rw-r--r-- | include/graphics.h | 1 | ||||
| -rw-r--r-- | include/proto.h | 2 | ||||
| -rw-r--r-- | include/slosh.h | 8 | ||||
| -rw-r--r-- | src/app.c | 24 | ||||
| -rw-r--r-- | src/app_draw.c | 119 | ||||
| -rw-r--r-- | src/config.c | 27 | ||||
| -rw-r--r-- | src/main.c | 11 | ||||
| -rw-r--r-- | src/screen.c | 76 | ||||
| -rw-r--r-- | src/server.c | 493 | ||||
| -rw-r--r-- | tests/live_graphics.py | 29 | ||||
| -rw-r--r-- | tests/screen_test.c | 79 | ||||
| -rw-r--r-- | tests/test_nested.py | 6 | ||||
| -rw-r--r-- | tests/test_session.py | 144 |
22 files changed, 986 insertions, 150 deletions
@@ -170,6 +170,12 @@ $(EXPR_EVAL): tests/expr_eval.c src/expr.c | build SHADER_TEST := build/shader_test +SCREEN_TEST := build/screen_test + +$(SCREEN_TEST): tests/screen_test.c src/screen.c src/json.c $(VT_LIB) | build + $(call say,[LD],$@) + $(Q)$(CC) $(CFLAGS) tests/screen_test.c src/screen.c src/json.c $(VT_LIB) -o $@ + $(SHADER_TEST): tests/shader_test.c src/shader.c src/screen.c src/json.c src/expr.c $(VT_LIB) | build $(call say,[LD],$@) $(Q)$(CC) $(CFLAGS) tests/shader_test.c src/shader.c src/screen.c src/json.c src/expr.c $(VT_LIB) -o $@ @@ -182,10 +188,11 @@ build/.pass-%: tests/%.py tests/harness.py $(BIN) | build @printf ' ok %-24s %s\n' "$(notdir $<)" "$$(grep -c '^ok' build/.log-$* 2>/dev/null || echo ?) checks" @touch $@ -test: $(BIN) $(TEST_BIN) $(KDL_TEST) $(SHADER_TEST) $(EXPR_TEST) $(EXPR_EVAL) $(PATH_TEST) ## unit + headless checks (fast) +test: $(BIN) $(TEST_BIN) $(KDL_TEST) $(SHADER_TEST) $(SCREEN_TEST) $(EXPR_TEST) $(EXPR_EVAL) $(PATH_TEST) ## unit + headless checks (fast) @./$(TEST_BIN) >/dev/null && ./$(KDL_TEST) >/dev/null && ./$(SHADER_TEST) >/dev/null \ + && ./$(SCREEN_TEST) >/dev/null \ && ./$(EXPR_TEST) >/dev/null && ./$(PATH_TEST) >/dev/null \ - && printf ' ok %-24s %s\n' "C unit tests" "5 binaries" + && printf ' ok %-24s %s\n' "C unit tests" "6 binaries" @$(MAKE) --no-print-directory -j$(JOBS) $(PY_STAMPS) @printf '\nall green\n' @@ -77,8 +77,11 @@ slosh -s work # a named session slosh ls # what is running ``` -Sessions survive detaching, and your ssh connection dying. Then `C-a \` to -split, `C-a ?` for the keys, `C-a p` for every command by name. +Sessions survive detaching and your ssh connection dying, and several terminals +can share one at once. The last client to interact controls the layout size; +smaller terminals follow the cursor over a crop and larger ones get blank +filler. Then `C-a \` to split, `C-a ?` for the keys, `C-a p` for every command +by name. ## Docs diff --git a/config/config.kdl b/config/config.kdl index ec020ed..5cae65e 100644 --- a/config/config.kdl +++ b/config/config.kdl @@ -287,6 +287,22 @@ status_pad 4 // expands a collapsed pane just because the pointer crossed its header. focus_follows_mouse true +// Several terminals may attach to one session at once. Turning this off +// restores the classic rule: a new client displaces the one before it -- +// which is what "move my session over here, and close it over there" +// actually wants. +multi_attach true + +// Whose size the shared screen takes when several clients are attached: +// "active" the newest attachment, then the last client to type or +// click. Smaller clients see a cursor-following crop, +// larger ones get blank filler. +// "smallest" the smallest attached terminal (the tmux rule): nobody is +// ever cropped, and the roomiest terminal pays in filler. +// "largest" the largest one: the big display gets everything, small +// ones follow the cursor over a crop. +size_follows "active" + // Ctrl-D at an idle shell prompt exits that shell. // // On POSIX the tty does this: ^D on an empty line is EOF, the shell reads it diff --git a/docs/config.md b/docs/config.md index 72668f0..71ca297 100644 --- a/docs/config.md +++ b/docs/config.md @@ -84,7 +84,7 @@ theme { frame_focus "#00ff88" } // ...but that one colour is mine | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | geometry | `gap` `gap_aspect` `padding` `compact` `rounded` `title_align` `title_inset` `min_pane` `min_split` | | chrome | `status_bar` `status_line` `status_pad` `hints` `version_banner` `pane_buttons` `bell_indicator` and the marks (`zoom_mark` `zoom_on_mark` `close_mark` `min_mark` `newtab_mark` `bell_mark`) | -| behaviour | `focus_follows_mouse` `ctrl_d_exits` `scroll_lines` `scrollback` `scrollback_bytes` `toast_ms` `splash_ms` `hover_delay_ms` `double_click_ms` `word_separators` `anim_ms` `modal_scrim` `dim_unfocused` `float_shadow` `keep_dead` `in_band_shaders` `shell` `editor` | +| behaviour | `focus_follows_mouse` `ctrl_d_exits` `scroll_lines` `scrollback` `scrollback_bytes` `toast_ms` `splash_ms` `hover_delay_ms` `double_click_ms` `word_separators` `anim_ms` `modal_scrim` `dim_unfocused` `float_shadow` `keep_dead` `in_band_shaders` `multi_attach` `size_follows` `shell` `editor` | | projects | `project_roots` `project_layout` (see [workspaces](workspaces.md)) | | colour | `theme { }` | | effects | `shaders { }`, `states { }` (see [shaders](shaders.md) and [chrome](chrome.md)) | diff --git a/docs/index.md b/docs/index.md index 09b0466..c4d9746 100644 --- a/docs/index.md +++ b/docs/index.md @@ -62,7 +62,9 @@ slosh ls # what is running ``` Sessions keep running when you detach, or when your terminal or ssh connection -goes away. Reattach with the same command. +goes away. Several terminals can attach at once: the last one to interact sets +the shared layout size, while the others see a cursor-following crop or blank +filler. Reattach with the same command. **TIP:** press `C-a ?` for the key combo cheatsheet, or `C-a p` for the command palette. diff --git a/docs/slosh.1 b/docs/slosh.1 index 4a473af..3fb3ff1 100644 --- a/docs/slosh.1 +++ b/docs/slosh.1 @@ -51,6 +51,18 @@ creating it if nobody is home; detaching (or losing the connection) leaves the session and everything in it running, and the same command reattaches. .PP +Several terminals may attach to one session at once. The newest attachment, +then the client with the most recent keyboard or mouse activity, sets the +shared screen size. Resizing that active client resizes the session; resizing +another client changes only its view. A smaller view follows the cursor over +the shared screen, and a larger one is filled with blank cells. Detaching +leaves the other clients attached. Both halves are configurable: +.B multi_attach +restores the old displacing attach, and +.B size_follows +picks whose size rules \(em see +.BR slosh (5). +.PP A trailing .B \-\- .I command\ ... @@ -58,9 +70,9 @@ is run in the first pane instead of the configured shell. Every other pane runs the shell the configuration names, or .BR $SHELL . .PP -Attaching from inside a pane of the same session is refused, because the -new client would displace the very view it was typed into; the error -message names the escape hatches. +Attaching from inside a pane of the same session is refused, because it would +draw the session recursively inside itself; the error message names the +escape hatches. Attaching to a .I different session from inside a pane is nesting, and allowed. @@ -123,7 +135,7 @@ This is what the test suite drives. .TP .BI \-\-cols\ n ,\ \-\-rows\ n The screen size for the headless modes (default 80\(mu24). -When attaching from a terminal, the terminal's own size wins. +When attaching from a terminal, its size enters the latest-active rule above. .TP .BI \-\-idle\-ms\ n How long diff --git a/docs/slosh.5 b/docs/slosh.5 index f523da0..4437035 100644 --- a/docs/slosh.5 +++ b/docs/slosh.5 @@ -147,6 +147,22 @@ The glyphs themselves, each one string. Hovering focuses \(em never at the cost of what you were doing: not during a prefix, a drag, or a modal. .TP +.BI multi_attach\ bool +Several terminals may attach to one session at once (the default). +Off, a new client displaces the previous one, which is the classic +\[dq]move my session here and close it there\[dq]. +.TP +.BI size_follows\ active\ |\ smallest\ |\ largest +Whose size the shared screen takes when several clients are attached. +.B active +(the default) follows the newest attachment, then the last client to type or +click; smaller clients see a cursor-following crop and larger ones blank +filler. +.B smallest +is the tmux rule: nobody is cropped, the roomiest terminal pays in filler. +.B largest +gives the big display everything and the small ones a crop. +.TP .BI ctrl_d_exits\ bool Ctrl-D at an idle shell prompt sends .B exit @@ -167,8 +183,8 @@ Applied to the next pane you open: shrinking history retroactively would throw away output somebody is reading. .TP .BR toast_ms\ \fIn\fR ,\ splash_ms\ \fIn\fR -How long an announcement stays up, and how long the logo greets an -attach (0 for never). +How long an announcement stays up, and how long the logo greets the first +attach after a session had no viewers (0 for never). .TP .BI hover_delay_ms\ n How long the pointer must rest on a border before the split guide arms. diff --git a/include/app.h b/include/app.h index a203858..b3dd57c 100644 --- a/include/app.h +++ b/include/app.h @@ -5,6 +5,7 @@ #ifndef SLOSH_APP_H #define SLOSH_APP_H +#include "graphics.h" #include "kdl.h" #include "project.h" #include "shader.h" @@ -22,10 +23,16 @@ void app_event(app_t *a, const input_event_t *ev); /* Kitty graphics for this frame: the bytes the client's terminal needs, and * the same thing as JSON for tests. Bytes are borrowed until the next call. */ const char *app_graphics(app_t *a, size_t *len); +/* The same frame for one attached terminal. `state` is that terminal's own + * transmission/deletion history; the viewport is in canonical screen cells. */ +const char *app_graphics_view(app_t *a, graphics_t *state, uint16_t x, + uint16_t y, uint16_t cols, uint16_t rows, + size_t *len); void app_graphics_reset(app_t *a); /* Did the last app_graphics() stream reach the client? Undelivered frames * are regenerated: transmissions repeat and deletions stay owed. */ void app_graphics_commit(app_t *a, bool delivered); +void app_graphics_view_commit(graphics_t *state, bool delivered); char *app_graphics_json(app_t *a); /* Transient announcements, drawn bottom-right and expiring on their own. */ @@ -52,6 +59,11 @@ bool app_reload_config(char *err, size_t errcap); /* The files the config in force was read from: the one that was loaded and * everything it included, existing or not. What the watcher watches. */ size_t app_config_files(const char **out, size_t max); +/* The attach-sharing knobs, read fresh so a config reload changes policy on + * a running session: may several clients attach at once, and whose size the + * shared screen takes (SIZE_FOLLOWS_* in config.h). */ +bool app_cfg_multi_attach(void); +int app_cfg_size_follows(void); /* What the config in force complained about while loading, or "". A complaint is * not a failure -- an include that is not there, a shader nobody has heard of -- * so the session is running either way; this is for saying so. */ @@ -87,6 +99,12 @@ bool app_should_quit(const app_t *a); /* C-a d asks the client to leave while the session keeps running. */ bool app_detach_requested(const app_t *a); void app_clear_detach(app_t *a); +/* A different display took over the shared input stream. End state that cannot + * safely span clients (leader chord, pointer drag and hover position). */ +void app_cancel_client_interaction(app_t *a); +/* A release over client-side filler has no canonical target, but still ends a + * pointer gesture without disturbing that client's keyboard leader state. */ +void app_cancel_client_pointer(app_t *a); size_t app_pane_count(const app_t *a); /* Tabs. A tab is a layout tree; panes in every tab keep running. */ diff --git a/include/config.h b/include/config.h index fee6b2e..9db9c53 100644 --- a/include/config.h +++ b/include/config.h @@ -112,6 +112,13 @@ typedef struct { typedef enum { ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT } align_t; +/* size_follows: which attached client sizes the shared screen. */ +enum { + SIZE_FOLLOWS_ACTIVE = 0, /* newest attach, then last input */ + SIZE_FOLLOWS_SMALLEST, /* min over clients: filler, never a crop */ + SIZE_FOLLOWS_LARGEST, /* max over clients: crops, never filler */ +}; + /* How many files one config may be built from: itself plus its includes. Small * and fixed, because a config assembled from more than this many pieces is a * thing nobody can read. */ @@ -306,6 +313,18 @@ typedef struct { uint16_t status_pad; bool focus_follows_mouse; + /* Several terminals may attach to one session at once (the default). + * false restores the classic rule: a new client displaces the one before + * it, which is what anyone using attach-from-elsewhere as "move my session + * here and *close it there*" actually wants. */ + bool multi_attach; + /* Whose size the shared screen takes when several clients are attached: + * the active client (newest attach, then last input -- the default), or + * the smallest / largest attached one. Smallest is the tmux rule: nobody + * is cropped and the roomiest terminal pays in filler; largest gives the + * big display everything and small ones a cursor-following crop. */ + int size_follows; + /* Whether Ctrl-D at an idle shell prompt exits that shell, the way the tty * line discipline would do it on POSIX. * diff --git a/include/graphics.h b/include/graphics.h index 6a338df..13cc5dc 100644 --- a/include/graphics.h +++ b/include/graphics.h @@ -66,6 +66,7 @@ typedef struct { uint32_t x_off, y_off; /* offset within the first cell, in pixels */ uint32_t sx, sy, sw, sh; /* source rectangle, in image pixels */ uint32_t px_w, px_h; /* the image's own size */ + uint32_t cell_px_w, cell_px_h; /* canonical pixels represented by a cell */ int format, compression; const uint8_t *data; /* NULL once the client has it */ size_t data_len; diff --git a/include/proto.h b/include/proto.h index 67b45f0..4df52a6 100644 --- a/include/proto.h +++ b/include/proto.h @@ -30,7 +30,7 @@ enum { enum { EXIT_SESSION_ENDED = 0, /* the last pane closed */ EXIT_DETACHED = 1, /* the user detached */ - EXIT_REPLACED = 2, /* another client attached */ + EXIT_REPLACED = 2, /* legacy: retained so new clients speak to old servers */ }; typedef struct { diff --git a/include/slosh.h b/include/slosh.h index e624bda..75aa658 100644 --- a/include/slosh.h +++ b/include/slosh.h @@ -76,6 +76,14 @@ void screen_init(screen_t *s, uint16_t cols, uint16_t rows); void screen_free(screen_t *s); void screen_resize(screen_t *s, uint16_t cols, uint16_t rows); void screen_clear(screen_t *s); +/* Project a canonical screen into a client-sized one. The source starts at + * (x,y); anything beyond its edges is blank filler. Diff history in `dst` is + * deliberately left alone, so every attached terminal advances independently. */ +void screen_project(screen_t *dst, const screen_t *src, uint16_t x, uint16_t y); +/* Move an existing client viewport only as far as needed to keep the canonical + * cursor visible, then clamp it to the canonical screen. */ +void screen_follow_cursor(const screen_t *src, uint16_t cols, uint16_t rows, + uint16_t *x, uint16_t *y); cell_t *screen_at(screen_t *s, uint16_t x, uint16_t y); void screen_put_utf8(screen_t *s, uint16_t x, uint16_t y, const char *txt, size_t len, color_t fg, color_t bg, uint16_t attrs); @@ -88,6 +88,16 @@ size_t app_config_files(const char **out, size_t max) { return config_files(&CFG, out, max); } +bool app_cfg_multi_attach(void) { + ensure_config(); + return CFG.multi_attach; +} + +int app_cfg_size_follows(void) { + ensure_config(); + return CFG.size_follows; +} + /* ---- tree --------------------------------------------------------------- */ #include "app_internal.h" @@ -871,6 +881,20 @@ bool app_should_quit(const app_t *a) { return a->quit || a->ntabs == 0; } bool app_detach_requested(const app_t *a) { return a->detach; } void app_clear_detach(app_t *a) { a->detach = false; } +void app_cancel_client_pointer(app_t *a) { + if (a->drag.kind == DRAG_SELECT) { + node_t *n = pane_by_id(a, a->drag.src); + if (n) pane_select_done(n->pane); + } + memset(&a->drag, 0, sizeof a->drag); + a->ptr_valid = false; +} + +void app_cancel_client_interaction(app_t *a) { + a->prefix = false; + app_cancel_client_pointer(a); +} + /* ---- walking ------------------------------------------------------------ */ typedef void (*leaf_fn)(node_t *, void *); diff --git a/src/app_draw.c b/src/app_draw.c index 85f20fd..2955c11 100644 --- a/src/app_draw.c +++ b/src/app_draw.c @@ -2219,7 +2219,9 @@ void draw_floats(app_t *a, screen_t *s) { struct gfx_ctx { app_t *a; + graphics_t *out; node_t *leaf; + rect_t viewport; /* The float rects drawn over this leaf's cells: every visible float for a * tiled pane, the higher-raised ones for a float. A placement is clipped * against them below, because kitty images are drawn by the client's @@ -2229,6 +2231,84 @@ struct gfx_ctx { size_t nocc; }; +/* Crop one canonical placement to an attached client's viewport, then move it + * into that client's coordinates. Kitty's c=/r= scale and source rectangle + * make this more than clipping four integers: losing cells must lose the + * corresponding source pixels, or the image is squeezed rather than cropped. */ +static void gfx_place_view(graphics_t *out, gfx_req_t r, rect_t v) { + uint32_t x1 = (uint32_t)r.col + r.cols; + uint32_t y1 = (uint32_t)r.row + r.rows; + uint32_t vx1 = (uint32_t)v.x + v.w; + uint32_t vy1 = (uint32_t)v.y + v.h; + if (x1 <= v.x || r.col >= vx1 || y1 <= v.y || r.row >= vy1) return; + + if (r.col < v.x) { + uint16_t old = r.cols, cut = (uint16_t)(v.x - r.col); + if (r.scale_cols) { + uint32_t drop = old ? (uint32_t)((uint64_t)r.sw * cut / old) : 0; + r.sx += drop; + r.sw -= drop; + } else { + uint32_t px = (uint32_t)cut * r.cell_px_w; + px = px > r.x_off ? px - r.x_off : 0; + r.x_off = 0; + uint32_t drop = px < r.sw ? px : r.sw; + r.sx += drop; + r.sw -= drop; + } + r.col = v.x; + r.cols = (uint16_t)(old - cut); + } + if (r.row < v.y) { + uint16_t old = r.rows, cut = (uint16_t)(v.y - r.row); + if (r.scale_rows) { + uint32_t drop = old ? (uint32_t)((uint64_t)r.sh * cut / old) : 0; + r.sy += drop; + r.sh -= drop; + } else { + uint32_t px = (uint32_t)cut * r.cell_px_h; + px = px > r.y_off ? px - r.y_off : 0; + r.y_off = 0; + uint32_t drop = px < r.sh ? px : r.sh; + r.sy += drop; + r.sh -= drop; + } + r.row = v.y; + r.rows = (uint16_t)(old - cut); + } + if ((uint32_t)r.col + r.cols > vx1) { + uint16_t old = r.cols, keep = (uint16_t)(vx1 - r.col); + if (r.scale_cols) + r.sw = old ? (uint32_t)((uint64_t)r.sw * keep / old) : 0; + else { + uint32_t px = (uint32_t)keep * r.cell_px_w; + px = px > r.x_off ? px - r.x_off : 0; + if (r.sw > px) r.sw = px; + } + r.cols = keep; + } + if ((uint32_t)r.row + r.rows > vy1) { + uint16_t old = r.rows, keep = (uint16_t)(vy1 - r.row); + if (r.scale_rows) + r.sh = old ? (uint32_t)((uint64_t)r.sh * keep / old) : 0; + else { + uint32_t px = (uint32_t)keep * r.cell_px_h; + px = px > r.y_off ? px - r.y_off : 0; + if (r.sh > px) r.sh = px; + } + r.rows = keep; + } + /* Keep the old emitter's representability rule: a very small source scaled + * over many cells can round a cropped source extent to zero, but it is still + * a live placement and must not disappear from the model. */ + if (!r.cols || !r.rows) return; + if (r.scale_cols) r.scale_cols = r.cols; + if (r.scale_rows) r.scale_rows = r.rows; + r.col = (uint16_t)(r.col - v.x); + r.row = (uint16_t)(r.row - v.y); + gfx_place(out, &r); +} + static void gfx_from_pane(pane_t *p, const pane_gfx_t *g, void *ud) { struct gfx_ctx *c = ud; node_t *leaf = c->leaf; @@ -2360,9 +2440,9 @@ static void gfx_from_pane(pane_t *p, const pane_gfx_t *g, void *ud) { if (!cols || !rows || !sw || !sh) return; } - gfx_place( - c->a->gfx, - &(gfx_req_t){ + gfx_place_view( + c->out, + (gfx_req_t){ .pane = leaf->id, .src_id = g->image_id, .gen = g->generation, @@ -2385,17 +2465,22 @@ static void gfx_from_pane(pane_t *p, const pane_gfx_t *g, void *ud) { .sh = sh, .px_w = g->src_w, .px_h = g->src_h, + .cell_px_w = g->cell_px_w, + .cell_px_h = g->cell_px_h, .format = g->format, .compression = g->compression, .data = g->data, .data_len = g->data_len, - }); + }, + c->viewport); } /* One frame's worth of "what covers what": the visible floats, so every * leaf's placements can be clipped by the ones above it. */ struct gfx_walk { app_t *a; + graphics_t *out; + rect_t viewport; rect_t occ[64]; uint32_t raised[64]; size_t n; @@ -2411,16 +2496,24 @@ static void gfx_leaf_cb(node_t *n, void *ud) { size_t k = 0; for (size_t i = 0; i < w->n; i++) if (!n->floating || w->raised[i] > n->raised) occ[k++] = w->occ[i]; - struct gfx_ctx ctx = {w->a, n, occ, k}; + struct gfx_ctx ctx = {.a = w->a, + .out = w->out, + .leaf = n, + .viewport = w->viewport, + .occ = occ, + .nocc = k}; pane_graphics(n->pane, gfx_from_pane, &ctx); } /* Walk the visible tab's panes and produce the bytes the client's terminal * needs this frame. Borrowed until the next call. */ -const char *app_graphics(app_t *a, size_t *len) { - gfx_begin(a->gfx); +const char *app_graphics_view(app_t *a, graphics_t *state, uint16_t x, + uint16_t y, uint16_t cols, uint16_t rows, + size_t *len) { + gfx_begin(state); if (a->ntabs && cur(a)->root) { - struct gfx_walk w = {.a = a}; + struct gfx_walk w = { + .a = a, .out = state, .viewport = (rect_t){x, y, cols, rows}}; node_t *fl[64]; size_t nf = collect_floating(cur(a)->root, fl, 64, 0); for (size_t i = 0; i < nf && w.n < 64; i++) { @@ -2430,7 +2523,11 @@ const char *app_graphics(app_t *a, size_t *len) { } walk(cur(a)->root, gfx_leaf_cb, &w); } - return gfx_flush(a->gfx, len); + return gfx_flush(state, len); +} + +const char *app_graphics(app_t *a, size_t *len) { + return app_graphics_view(a, a->gfx, 0, 0, a->cols, a->rows, len); } void app_graphics_reset(app_t *a) { gfx_reset(a->gfx); } @@ -2439,6 +2536,10 @@ void app_graphics_commit(app_t *a, bool delivered) { gfx_commit(a->gfx, delivered); } +void app_graphics_view_commit(graphics_t *state, bool delivered) { + gfx_commit(state, delivered); +} + char *app_graphics_json(app_t *a) { size_t len = 0; app_graphics(a, &len); /* refresh the model; the bytes are the caller's job */ diff --git a/src/config.c b/src/config.c index 0c7af63..bfbfdf7 100644 --- a/src/config.c +++ b/src/config.c @@ -918,6 +918,8 @@ void config_defaults(config_t *c) { * than as another row of it. */ c->status_pad = 4; c->focus_follows_mouse = true; + c->multi_attach = true; + c->size_follows = SIZE_FOLLOWS_ACTIVE; c->in_band_shaders = false; /* Windows has no VEOF for the line discipline to act on, so ^D there is a * key that does nothing until we make it mean something. POSIX already has @@ -1607,6 +1609,14 @@ char *config_render(const config_t *c) { cb_add(&b, "\n// ---- behaviour ----\n"); cb_add(&b, "focus_follows_mouse %s\n", yesno(c->focus_follows_mouse)); + cb_add(&b, + "multi_attach %s // several terminals at once; off: a new " + "client displaces the old\n", + yesno(c->multi_attach)); + cb_add(&b, "size_follows \"%s\" // or \"smallest\" / \"largest\"\n", + c->size_follows == SIZE_FOLLOWS_SMALLEST ? "smallest" + : c->size_follows == SIZE_FOLLOWS_LARGEST ? "largest" + : "active"); cb_add(&b, "in_band_shaders %s\n", yesno(c->in_band_shaders)); cb_add(&b, "ctrl_d_exits %s // ^D at an idle prompt exits the shell; " @@ -1861,6 +1871,7 @@ static const char *const KNOWN_TOP[] = { "keys", "min_mark", "min_pane", + "multi_attach", "min_split", "modal_scrim", "newtab_mark", @@ -1875,6 +1886,7 @@ static const char *const KNOWN_TOP[] = { "select_scroll_ms", "shaders", "shell", + "size_follows", "splash_ms", "states", "status_bar", @@ -2081,6 +2093,21 @@ static bool load_into(config_t *c, const char *path, int depth, char *err, (uint16_t)kdl_arg_int(kdl_child(root, "status_pad"), 0, c->status_pad); c->focus_follows_mouse = kdl_arg_bool(kdl_child(root, "focus_follows_mouse"), 0, c->focus_follows_mouse); + c->multi_attach = + kdl_arg_bool(kdl_child(root, "multi_attach"), 0, c->multi_attach); + const char *sizef = kdl_arg(kdl_child(root, "size_follows"), 0, NULL); + if (sizef) { + if (strcmp(sizef, "active") == 0) + c->size_follows = SIZE_FOLLOWS_ACTIVE; + else if (strcmp(sizef, "smallest") == 0) + c->size_follows = SIZE_FOLLOWS_SMALLEST; + else if (strcmp(sizef, "largest") == 0) + c->size_follows = SIZE_FOLLOWS_LARGEST; + else + complain(c, err, errcap, 0, + "size_follows wants active, smallest or largest, not \"%s\"", + sizef); + } c->in_band_shaders = kdl_arg_bool(kdl_child(root, "in_band_shaders"), 0, c->in_band_shaders); c->ctrl_d_exits = @@ -249,14 +249,13 @@ int main(int argc, char **argv) { if (isatty(STDOUT_FILENO)) term_size(&cols, &rows); if (server) return server_run(name, cmd_argv, cols, rows, layout, watch); - /* Not to the session this process is already inside. A new client - * displaces the current display (EXIT_REPLACED), so `slosh` typed into a - * pane of "main" attaches to main, displaces the very client showing that - * pane, and the user watches their own session detach from inside it. + /* Not to the session this process is already inside. `slosh` typed into a + * pane of "main" would attach that pane's terminal back to the session which + * is drawing it: a recursive view whose own output becomes its next input. * SLOSH_SESSION names the pane's own session; asking for any *other* name * is deliberate nesting and none of our business. The one legitimate shape * this refuses — a fresh terminal launched from a pane, inheriting the - * variables, attaching to take over as the display — gets its escape hatch + * variables, deliberately making that recursive attachment — gets its escape hatch * named in the message rather than a flag: it is exactly what unsetting * the variable means. */ const char *inside = getenv("SLOSH") ? getenv("SLOSH_SESSION") : NULL; @@ -264,7 +263,7 @@ int main(int argc, char **argv) { fprintf(stderr, "slosh: this pane is already inside session %s\n" " (C-a d detaches; `slosh -s NAME` nests another session;\n" - " unset SLOSH_SESSION to attach anyway, displacing this view)\n", + " unset SLOSH_SESSION to attach recursively anyway)\n", name); return 1; } diff --git a/src/screen.c b/src/screen.c index 7bd474a..b768162 100644 --- a/src/screen.c +++ b/src/screen.c @@ -135,6 +135,82 @@ void screen_clear(screen_t *s) { memset(s->cur_link, 0, n * sizeof(uint16_t)); } +void screen_project(screen_t *dst, const screen_t *src, uint16_t x0, + uint16_t y0) { + screen_clear(dst); + hit_reset(&dst->hits); + dst->cursor_visible = false; + + for (uint16_t y = 0; y < dst->rows && (uint32_t)y0 + y < src->rows; y++) { + uint16_t sy = (uint16_t)(y0 + y); + for (uint16_t x = 0; x < dst->cols && (uint32_t)x0 + x < src->cols; x++) { + uint16_t sx = (uint16_t)(x0 + x); + size_t si = (size_t)sy * src->cols + sx; + size_t di = (size_t)y * dst->cols + x; + const cell_t *c = &src->cur[si]; + + /* A viewport cannot display half a wide grapheme. A tail at its left + * edge and a head at its right edge both remain filler rather than + * relying on terminal-dependent wrapping or replacement glyphs. */ + if (c->width == 0) continue; + if (c->width == 2 && + ((uint32_t)sx + 1 >= src->cols || (uint32_t)x + 1 >= dst->cols)) + continue; + + dst->cur[di] = *c; + uint16_t link = src->cur_link[si]; + if (link && link <= src->nlinks) { + const char *uri = src->links[link - 1]; + dst->cur_link[di] = screen_link_id(dst, uri, strlen(uri)); + } + if (c->width == 2) { + dst->cur[di + 1] = src->cur[si + 1]; + uint16_t tail_link = src->cur_link[si + 1]; + if (tail_link && tail_link <= src->nlinks) { + const char *uri = src->links[tail_link - 1]; + dst->cur_link[di + 1] = screen_link_id(dst, uri, strlen(uri)); + } + x++; + } + } + } + + if (src->cursor_visible && src->cursor_x >= x0 && src->cursor_y >= y0 && + (uint32_t)src->cursor_x < (uint32_t)x0 + dst->cols && + (uint32_t)src->cursor_y < (uint32_t)y0 + dst->rows) { + dst->cursor_visible = true; + dst->cursor_x = (uint16_t)(src->cursor_x - x0); + dst->cursor_y = (uint16_t)(src->cursor_y - y0); + } +} + +void screen_follow_cursor(const screen_t *src, uint16_t cols, uint16_t rows, + uint16_t *x, uint16_t *y) { + uint16_t vx = x ? *x : 0, vy = y ? *y : 0; + uint16_t max_x = src->cols > cols ? (uint16_t)(src->cols - cols) : 0; + uint16_t max_y = src->rows > rows ? (uint16_t)(src->rows - rows) : 0; + if (!max_x) + vx = 0; + else if (src->cursor_visible) { + if (src->cursor_x < vx) + vx = src->cursor_x; + else if ((uint32_t)src->cursor_x >= (uint32_t)vx + cols) + vx = (uint16_t)(src->cursor_x - cols + 1); + } + if (!max_y) + vy = 0; + else if (src->cursor_visible) { + if (src->cursor_y < vy) + vy = src->cursor_y; + else if ((uint32_t)src->cursor_y >= (uint32_t)vy + rows) + vy = (uint16_t)(src->cursor_y - rows + 1); + } + if (vx > max_x) vx = max_x; + if (vy > max_y) vy = max_y; + if (x) *x = vx; + if (y) *y = vy; +} + uint16_t screen_link_id(screen_t *s, const char *uri, size_t len) { if (!uri || !len || len > 1024) return 0; /* A URI is emitted verbatim inside an OSC, so a control byte in one is a diff --git a/src/server.c b/src/server.c index 96e79cd..7443648 100644 --- a/src/server.c +++ b/src/server.c @@ -1,6 +1,6 @@ -/* The server: owns the panes and the layout, renders, and talks to at most one - * attached client (D10). It outlives every client, which is the entire point — - * agents keep running while you are gone. */ +/* The server: owns the panes and shared layout, renders once, and projects that + * screen into every attached client. It outlives all of them, which is the + * entire point — agents keep running while you are gone. */ #define _GNU_SOURCE #include "server.h" @@ -87,6 +87,14 @@ typedef struct { int fd; msg_reader_t reader; bool display; + uint16_t cols, rows, cell_w, cell_h; + uint16_t view_x, view_y, shown_cols, shown_rows; + uint64_t activity; + input_parser_t *in; + int64_t esc_due; + screen_t view; + bool view_init; + graphics_t *gfx; uint8_t *out; /* queued bytes, already framed */ size_t out_len, out_off, out_cap; } conn_t; @@ -94,22 +102,41 @@ typedef struct { typedef struct { app_t *app; screen_t screen; - input_parser_t *in; + input_parser_t *cmd_in; conn_t conns[MAX_CONNS]; size_t nconns; + int active_fd; + uint64_t activity_seq; + uint16_t fallback_cell_w, fallback_cell_h; + bool pending_paint; + int64_t next_frame; } server_t; -static conn_t *display_conn(server_t *s) { +static conn_t *active_conn(server_t *s) { for (size_t i = 0; i < s->nconns; i++) - if (s->conns[i].display) return &s->conns[i]; + if (s->conns[i].display && s->conns[i].fd == s->active_fd) + return &s->conns[i]; return NULL; } -static void conn_close(server_t *s, size_t i) { +static size_t display_count(const server_t *s) { + size_t n = 0; + for (size_t i = 0; i < s->nconns; i++) + if (s->conns[i].display) n++; + return n; +} + +static bool conn_close(server_t *s, size_t i) { + bool active = s->conns[i].fd == s->active_fd; close(s->conns[i].fd); msg_reader_free(&s->conns[i].reader); + input_free(s->conns[i].in); + if (s->conns[i].view_init) screen_free(&s->conns[i].view); + gfx_free(s->conns[i].gfx); free(s->conns[i].out); s->conns[i] = s->conns[--s->nconns]; + if (active) s->active_fd = -1; + return active; } /* Push what is queued. Returns false when the connection is finished with -- @@ -171,13 +198,14 @@ static bool conn_send(conn_t *c, uint8_t type, const void *data, size_t len) { return conn_flush(c); } -static void conn_drop(server_t *s, size_t i, uint8_t reason) { +static bool conn_drop(server_t *s, size_t i, uint8_t reason) { conn_send(&s->conns[i], MSG_EXIT, &reason, 1); - conn_close(s, i); + return conn_close(s, i); } -static void srv_event(const input_event_t *ev, void *ud) { - app_event(((server_t *)ud)->app, ev); +static void request_paint(server_t *s, bool immediate) { + s->pending_paint = true; + if (immediate || !s->next_frame) s->next_frame = now_ms(); } static int listen_socket(const char *path) { @@ -229,26 +257,25 @@ static char *b64(const char *in, size_t len, size_t *out_len) { * a frame here silently was how a scrolled-away screenshot stayed parked on * the screen: its deletion left with the dropped bytes and was never owed * again. */ -static bool push_graphics(server_t *s) { - conn_t *c = display_conn(s); - if (!c) return true; +static bool push_graphics(server_t *s, conn_t *c) { size_t len = 0; - const char *bytes = app_graphics(s->app, &len); + const char *bytes = app_graphics_view(s->app, c->gfx, c->view_x, c->view_y, + c->cols, c->rows, &len); if (!len) { - app_graphics_commit(s->app, true); + app_graphics_view_commit(c->gfx, true); return true; } bool ok = conn_send(c, MSG_OUTPUT, bytes, len); - app_graphics_commit(s->app, ok); + app_graphics_view_commit(c->gfx, ok); return ok; } /* The clipboard lives on the client's machine, not ours, so a copy travels as - * OSC 52 for the outer terminal to honour. */ -static void push_clipboard(server_t *s) { + * OSC 52 for the outer terminal to honour. Input-driven copies name their + * originating connection; asynchronous pane copies use the active one. */ +static void push_clipboard_to(server_t *s, conn_t *c) { char *text = app_take_clipboard(s->app); if (!text) return; - conn_t *c = display_conn(s); if (c) { size_t b64len = 0; char *enc = b64(text, strlen(text), &b64len); @@ -262,31 +289,220 @@ static void push_clipboard(server_t *s) { free(text); } -/* Send whatever the last compose produced to the display client. */ -/* Returns whether the client has the frame (or there is none to owe it to). +static void push_clipboard(server_t *s) { + push_clipboard_to(s, active_conn(s)); +} + +/* Send whatever the last compose produced to one display client. */ +/* Returns whether this client has the frame. * A refused send is a full outbox, not a dead client: the diff that was not * queued is lost, so the client's cells are unknown from here on and the next * attempt must be a full repaint. The caller keeps the paint pending, and the * outbox drains on POLLOUT between frames; a client that truly went away * shows up as a write error there, not here. */ -static bool push_frame(server_t *s) { - conn_t *c = display_conn(s); - if (!c) return true; - screen_render(&s->screen); - if (!s->screen.out_len) return true; - if (!conn_send(c, MSG_OUTPUT, s->screen.out, s->screen.out_len)) { - s->screen.force_full = true; +static void update_viewport(conn_t *c, const screen_t *src) { + screen_follow_cursor(src, c->cols, c->rows, &c->view_x, &c->view_y); + c->shown_cols = src->cols > c->view_x ? (uint16_t)(src->cols - c->view_x) : 0; + c->shown_rows = src->rows > c->view_y ? (uint16_t)(src->rows - c->view_y) : 0; + if (c->shown_cols > c->cols) c->shown_cols = c->cols; + if (c->shown_rows > c->rows) c->shown_rows = c->rows; +} + +static bool push_frame(server_t *s, conn_t *c) { + uint16_t old_x = c->view_x, old_y = c->view_y; + uint16_t old_cols = c->shown_cols, old_rows = c->shown_rows; + update_viewport(c, &s->screen); + screen_project(&c->view, &s->screen, c->view_x, c->view_y); + screen_render(&c->view); + if (!c->view.out_len) return true; + if (!conn_send(c, MSG_OUTPUT, c->view.out, c->view.out_len)) { + /* The projection never entered this client's stream. Keep mouse mapping + * tied to the last viewport we did enqueue, then retry this one in full. */ + c->view_x = old_x; + c->view_y = old_y; + c->shown_cols = old_cols; + c->shown_rows = old_rows; + c->view.force_full = true; return false; } return true; } -static void drop_display(server_t *s, uint8_t reason) { +static bool push_clients(server_t *s) { + /* cmd_exec(), config reloads and canonical resizes request a terminal reset + * on the canonical screen. It is never rendered directly now, so carry that + * request into every independently diffed client view and consume it here. + * A newly attached view starts force_full on its own, including when there + * were no displays around to receive an earlier request. */ + if (s->screen.force_full) { + for (size_t i = 0; i < s->nconns; i++) + if (s->conns[i].display) s->conns[i].view.force_full = true; + s->screen.force_full = false; + } + + bool ok = true; + for (size_t i = 0; i < s->nconns; i++) { + conn_t *c = &s->conns[i]; + if (!c->display) continue; + bool frame_ok = push_frame(s, c); + bool gfx_ok = push_graphics(s, c); + if (!(frame_ok && gfx_ok)) ok = false; + } + return ok; +} + +/* Size the canonical screen by policy (size_follows). "active" takes the + * active client's size; "smallest"/"largest" fold every attached display, so + * any attach, resize or departure can move the canvas. The active client + * still supplies the cell pixel size either way: graphics go to terminals, + * and the active one is the best guess at what a cell is worth. */ +static void apply_canvas(server_t *s) { + conn_t *a = active_conn(s); + int policy = app_cfg_size_follows(); + uint16_t cols = 0, rows = 0; + if (policy == SIZE_FOLLOWS_ACTIVE) { + if (a) { + cols = a->cols; + rows = a->rows; + } + } else { + for (size_t i = 0; i < s->nconns; i++) { + conn_t *c = &s->conns[i]; + if (!c->display || !c->cols || !c->rows) continue; + if (!cols) { + cols = c->cols; + rows = c->rows; + } else if (policy == SIZE_FOLLOWS_SMALLEST) { + if (c->cols < cols) cols = c->cols; + if (c->rows < rows) rows = c->rows; + } else { + if (c->cols > cols) cols = c->cols; + if (c->rows > rows) rows = c->rows; + } + } + } + if (!cols || !rows) { /* nobody is looking: leave the canvas standing */ + request_paint(s, true); + return; + } + bool changed = cols != s->screen.cols || rows != s->screen.rows; + uint16_t old_w = 0, old_h = 0; + app_cell_px(s->app, &old_w, &old_h); + uint16_t cell_w = a && a->cell_w ? a->cell_w : s->fallback_cell_w; + uint16_t cell_h = a && a->cell_h ? a->cell_h : s->fallback_cell_h; + bool px_changed = cell_w != old_w || cell_h != old_h; + if (changed) { + screen_resize(&s->screen, cols, rows); + app_resize(s->app, cols, rows); + } + if (px_changed) app_set_cell_px(s->app, cell_w, cell_h); + if (changed || px_changed) app_compose(s->app, &s->screen); + request_paint(s, true); +} + +static void make_active(server_t *s, conn_t *c, bool new_activity) { + if (s->active_fd != c->fd) app_cancel_client_interaction(s->app); + s->active_fd = c->fd; + if (new_activity) c->activity = ++s->activity_seq; + apply_canvas(s); +} + +static void promote_latest(server_t *s) { + conn_t *latest = NULL; + for (size_t i = 0; i < s->nconns; i++) { + conn_t *c = &s->conns[i]; + if (c->display && (!latest || c->activity > latest->activity)) latest = c; + } + app_cancel_client_interaction(s->app); + if (!latest) { + s->active_fd = -1; + request_paint(s, true); + return; + } + s->active_fd = latest->fd; + apply_canvas(s); +} + +/* A non-active departure changes nothing under "active", but under + * "smallest"/"largest" the canvas may have been sized by the very client + * that just left. */ +static void close_conn(server_t *s, size_t i) { + if (conn_close(s, i)) + promote_latest(s); + else + apply_canvas(s); +} + +static void drop_conn(server_t *s, size_t i, uint8_t reason) { + if (conn_drop(s, i, reason)) + promote_latest(s); + else + apply_canvas(s); +} + +static void drop_fd(server_t *s, int fd, uint8_t reason) { for (size_t i = 0; i < s->nconns; i++) - if (s->conns[i].display) { - conn_drop(s, i, reason); + if (s->conns[i].fd == fd) { + drop_conn(s, i, reason); + return; + } +} + +typedef struct { + server_t *server; + conn_t *conn; + bool activity; +} client_input_t; + +static void client_event(const input_event_t *ev, void *ud) { + client_input_t *ctx = ud; + server_t *s = ctx->server; + conn_t *c = ctx->conn; + bool user = + ev->kind == EV_KEY || ev->kind == EV_MOUSE || ev->kind == EV_PASTE; + if (user && !ctx->activity) { + if (s->active_fd != c->fd) app_cancel_client_interaction(s->app); + s->active_fd = c->fd; + c->activity = ++s->activity_seq; + ctx->activity = true; + } + + if (ev->kind == EV_MOUSE) { + /* The event names the frame this client actually saw. Filler has no target; + * a cropped cell maps back into the canonical screen before hit-testing. */ + if (ev->mx >= c->shown_cols || ev->my >= c->shown_rows) { + /* Filler has no hit target, but a release there still has to terminate + * a drag that began over real content. Otherwise the shared app keeps a + * button logically held until somebody happens to press a key. */ + if (ev->maction == MOUSE_RELEASE) app_cancel_client_pointer(s->app); return; } + input_event_t mapped = *ev; + mapped.mx = (uint16_t)(mapped.mx + c->view_x); + mapped.my = (uint16_t)(mapped.my + c->view_y); + app_event(s->app, &mapped); + return; + } + app_event(s->app, ev); +} + +static bool feed_client(server_t *s, conn_t *c, const uint8_t *data, size_t len, + bool timeout) { + client_input_t ctx = {.server = s, .conn = c}; + if (timeout) + input_timeout(c->in, client_event, &ctx); + else + input_feed(c->in, data, len, client_event, &ctx); + if (ctx.activity) apply_canvas(s); + if (input_pending(c->in)) c->esc_due = now_ms() + ESC_MS; + return ctx.activity; +} + +static void queue_detach(int fds[MAX_CONNS], size_t *n, int fd) { + if (fd < 0) return; + for (size_t i = 0; i < *n; i++) + if (fds[i] == fd) return; + if (*n < MAX_CONNS) fds[(*n)++] = fd; } /* What the config watcher is watching: a directory per config file, and the @@ -501,10 +717,11 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, signal(SIGCHLD, SIG_DFL); #endif - server_t s = {0}; + server_t s = {.active_fd = -1}; s.app = app_new(argv, cols, rows); if (s.app) app_set_session(s.app, name); if (!s.app) return 1; + app_cell_px(s.app, &s.fallback_cell_w, &s.fallback_cell_h); if (layout) { char err[256] = {0}; if (!app_apply_layout_file(s.app, layout, true, err, sizeof err)) @@ -512,7 +729,7 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, } app_resize(s.app, cols, rows); screen_init(&s.screen, cols, rows); - s.in = input_new(); + s.cmd_in = input_new(); app_compose(s.app, &s.screen); /* a click resolves against a painted frame */ @@ -552,9 +769,8 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, watch_config(&watches); } - bool pending_paint = true; - int64_t next_frame = now_ms(); - int64_t esc_due = 0; + s.pending_paint = true; + s.next_frame = now_ms(); while (!g_stop && !app_should_quit(s.app)) { int fds[MAX_PANES]; @@ -576,15 +792,16 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, if (inofd >= 0) pfds[n++] = (struct pollfd){.fd = inofd, .events = POLLIN}; int timeout = -1; - if (pending_paint) { - int64_t due = next_frame - now_ms(); + if (s.pending_paint) { + int64_t due = s.next_frame - now_ms(); timeout = due <= 0 ? 0 : (int)due; } - if (input_pending(s.in)) { - int64_t due = esc_due - now_ms(); - int t = due <= 0 ? 0 : (int)due; - if (timeout < 0 || t < timeout) timeout = t; - } + for (size_t i = 0; i < s.nconns; i++) + if (s.conns[i].display && input_pending(s.conns[i].in)) { + int64_t due = s.conns[i].esc_due - now_ms(); + int t = due <= 0 ? 0 : (int)due; + if (timeout < 0 || t < timeout) timeout = t; + } /* some things happen without an event: a toast expiring, a hover guide * arming under a pointer that is deliberately not moving */ if (reload_due >= 0) { @@ -595,7 +812,7 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, int self_due = app_next_deadline_ms(s.app); if (self_due >= 0 && (timeout < 0 || self_due < timeout)) { timeout = self_due; - pending_paint = true; + s.pending_paint = true; } int r = poll(pfds, (nfds_t)n, timeout); @@ -618,6 +835,8 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, } } + int detach_fds[MAX_CONNS]; + size_t ndetach = 0; for (size_t ci = 0; ci < s.nconns;) { struct pollfd *pf = &pfds[conn_slot + ci]; if (pf->fd != s.conns[ci].fd) { @@ -626,7 +845,7 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, } if (pf->revents & POLLOUT) { if (!conn_flush(&s.conns[ci])) { - conn_close(&s, + close_conn(&s, ci); /* gone, or too far behind to still be a display */ continue; } @@ -638,7 +857,7 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, uint8_t buf[65536]; ssize_t got = read(s.conns[ci].fd, buf, sizeof buf); if (got <= 0) { - conn_close(&s, ci); /* gone: the session keeps running regardless */ + close_conn(&s, ci); /* gone: the session keeps running regardless */ continue; } msg_reader_feed(&s.conns[ci].reader, buf, (size_t)got); @@ -647,49 +866,89 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, while (!closed && msg_reader_next(&s.conns[ci].reader, &m)) { switch (m.type) { case MSG_HELLO: - case MSG_RESIZE: - if (m.type == MSG_HELLO && !s.conns[ci].display) { - /* now it is a client: the previous display is displaced */ - for (size_t j = 0; j < s.nconns; j++) + case MSG_RESIZE: { + conn_t *c = &s.conns[ci]; + bool fresh = m.type == MSG_HELLO && !c->display; + bool first_viewer = fresh && display_count(&s) == 0; + if (!c->display && !fresh) break; + + /* multi_attach false is the classic rule: the new client displaces + * every display before it (EXIT_REPLACED, which old clients already + * understand). Dropping compacts the array, so the index -- and the + * pointer taken from it -- are re-derived afterwards. */ + if (fresh && !app_cfg_multi_attach()) { + for (size_t j = 0; j < s.nconns;) { if (j != ci && s.conns[j].display) { conn_drop(&s, j, EXIT_REPLACED); if (j < ci) ci--; /* the array compacted under us */ - break; - } - s.conns[ci].display = true; - /* Someone is now looking, which is the one moment a greeting - * makes sense: a headless or scripted session never gets here. */ - app_splash(s.app); + } else + j++; + } + c = &s.conns[ci]; + first_viewer = display_count(&s) == 0; } - if (m.len >= 4 && s.conns[ci].display) { - uint16_t c = (uint16_t)(m.data[0] << 8 | m.data[1]); - uint16_t rr = (uint16_t)(m.data[2] << 8 | m.data[3]); - if (c && rr) { - screen_resize(&s.screen, c, rr); - app_resize(s.app, c, rr); + + uint16_t cols = c->cols ? c->cols : s.screen.cols; + uint16_t rows = c->rows ? c->rows : s.screen.rows; + if (m.len >= 4) { + uint16_t got_cols = (uint16_t)(m.data[0] << 8 | m.data[1]); + uint16_t got_rows = (uint16_t)(m.data[2] << 8 | m.data[3]); + if (got_cols && got_rows) { + cols = got_cols; + rows = got_rows; } - /* The cell size arrived with it, from a client new enough to - * send one and a terminal willing to say. Zero means neither, - * and app_set_cell_px leaves the default standing. */ - if (m.len >= 8) { - uint16_t cw = (uint16_t)(m.data[4] << 8 | m.data[5]); - uint16_t ch = (uint16_t)(m.data[6] << 8 | m.data[7]); - app_set_cell_px(s.app, cw, ch); + } + uint16_t cell_w = c->cell_w, cell_h = c->cell_h; + if (m.len >= 8) { + cell_w = (uint16_t)(m.data[4] << 8 | m.data[5]); + cell_h = (uint16_t)(m.data[6] << 8 | m.data[7]); + } + + if (fresh) { + c->display = true; + c->cols = cols; + c->rows = rows; + c->cell_w = cell_w; + c->cell_h = cell_h; + c->in = input_new(); + c->gfx = gfx_new(); + screen_init(&c->view, cols, rows); + c->view_init = true; + make_active(&s, c, true); + if (first_viewer) { + app_splash(s.app); + app_compose(s.app, &s.screen); } + } else { + bool local_resize = cols != c->cols || rows != c->rows; + c->cols = cols; + c->rows = rows; + c->cell_w = cell_w; + c->cell_h = cell_h; + if (local_resize) screen_resize(&c->view, cols, rows); + /* Unconditional: under "active" a non-active resize changes + * nothing (apply_canvas reads the active client), but under + * "smallest"/"largest" every display's size is a vote. */ + apply_canvas(&s); } - s.screen.force_full = true; /* a fresh client knows nothing */ - app_graphics_reset(s.app); /* including any image we had sent */ - pending_paint = true; - next_frame = now_ms(); + update_viewport(c, &s.screen); + request_paint(&s, true); break; + } case MSG_INPUT: - if (!s.conns[ci].display) break; /* only the client types */ - input_feed(s.in, m.data, m.len, srv_event, &s); - esc_due = now_ms() + ESC_MS; - pending_paint = true; + if (!s.conns[ci].display) break; /* only display clients type */ + feed_client(&s, &s.conns[ci], m.data, m.len, false); + /* A selection copy belongs to the terminal whose mouse released it, + * even if another client types before this poll cycle is painted. */ + push_clipboard_to(&s, &s.conns[ci]); + if (app_detach_requested(s.app)) { + app_clear_detach(s.app); + queue_detach(detach_fds, &ndetach, s.conns[ci].fd); + } + request_paint(&s, true); break; case MSG_DETACH: - conn_drop(&s, ci, EXIT_DETACHED); + drop_conn(&s, ci, EXIT_DETACHED); closed = true; break; case MSG_CMD: { @@ -697,14 +956,17 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, * script written against one works against the other. */ bool q = false; char *reply = - cmd_exec(s.app, &s.screen, s.in, (const char *)m.data, &q); + cmd_exec(s.app, &s.screen, s.cmd_in, (const char *)m.data, &q); const char *body = reply ? reply : "{\"error\":\"unknown command\"}"; conn_send(&s.conns[ci], MSG_REPLY, body, strlen(body)); free(reply); if (q) g_stop = 1; s.screen.force_full = true; /* it may have changed the layout */ - pending_paint = true; - next_frame = now_ms(); + if (app_detach_requested(s.app)) { + app_clear_detach(s.app); + queue_detach(detach_fds, &ndetach, s.active_fd); + } + request_paint(&s, true); break; } default: break; @@ -713,15 +975,27 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, if (!closed) ci++; } - if (input_pending(s.in) && now_ms() >= esc_due) - input_timeout(s.in, srv_event, &s); + for (size_t i = 0; i < s.nconns; i++) { + conn_t *c = &s.conns[i]; + if (c->display && input_pending(c->in) && now_ms() >= c->esc_due) { + feed_client(&s, c, NULL, 0, true); + push_clipboard_to(&s, c); + if (app_detach_requested(s.app)) { + app_clear_detach(s.app); + queue_detach(detach_fds, &ndetach, c->fd); + } + request_paint(&s, true); + } + } + for (size_t i = 0; i < ndetach; i++) + drop_fd(&s, detach_fds[i], EXIT_DETACHED); for (size_t i = 0; i < npanes; i++) { if (pfds[pane_slot + i].revents & (POLLIN | POLLHUP)) { app_pump_fd(s.app, pfds[pane_slot + i].fd); - if (!pending_paint) { - pending_paint = true; - next_frame = now_ms() + FRAME_MS; + if (!s.pending_paint) { + s.pending_paint = true; + s.next_frame = now_ms() + FRAME_MS; } } } @@ -747,12 +1021,24 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, * include becomes ten minutes of wondering. */ const char *why = app_config_complaint(); app_toast(s.app, why && *why ? why : "config reloaded"); + /* The knobs this loop lives by may have moved. multi_attach turned + * off evicts every display but the active one -- the reloaded config + * says one client, so one client it is -- and a changed size_follows + * re-sizes the canvas to the policy now in force. */ + if (!app_cfg_multi_attach()) { + for (size_t i = 0; i < s.nconns;) { + if (s.conns[i].display && s.conns[i].fd != s.active_fd) + drop_conn(&s, i, EXIT_REPLACED); + else + i++; + } + } + apply_canvas(&s); } else { app_toast(s.app, err[0] ? err : "config reload failed"); } s.screen.force_full = true; - pending_paint = true; - next_frame = now_ms(); + request_paint(&s, true); } app_reap(s.app); @@ -760,35 +1046,34 @@ int server_run(const char *name, const char *const argv[], uint16_t cols, /* The event-less work: a selection drag held past a pane's edge scrolls * on a clock (app_next_deadline_ms is what woke the poll for it), and a * step that moved anything is a frame the client is owed. */ - if (app_tick(s.app) && !pending_paint) { - pending_paint = true; - next_frame = now_ms(); + if (app_tick(s.app) && !s.pending_paint) { + s.pending_paint = true; + s.next_frame = now_ms(); } + /* A detach raised by a non-display control command belongs to the active + * display. Display input records its own fd above before another client can + * become active. */ if (app_detach_requested(s.app)) { app_clear_detach(s.app); - drop_display(&s, EXIT_DETACHED); + drop_fd(&s, s.active_fd, EXIT_DETACHED); } - if (pending_paint && now_ms() >= next_frame) { + if (s.pending_paint && now_ms() >= s.next_frame) { app_compose(s.app, &s.screen); - /* Either push can find the outbox full and drop its frame. The model - * remembers what the client is owed (a full repaint, the graphics - * deletions and transmissions), so the retry that this keeps pending - * is what eventually says it -- the outbox drains on POLLOUT between - * frames. */ - bool frame_ok = push_frame(&s); - bool gfx_ok = push_graphics(&s); + /* Each client remembers its own full repaint and image transmissions. + * One full outbox keeps a retry pending without holding anybody else up. */ + bool clients_ok = push_clients(&s); push_clipboard(&s); - pending_paint = !(frame_ok && gfx_ok); - next_frame = now_ms() + (pending_paint ? FRAME_MS : 0); + s.pending_paint = !clients_ok; + s.next_frame = now_ms() + (s.pending_paint ? FRAME_MS : 0); } } while (s.nconns) conn_drop(&s, 0, EXIT_SESSION_ENDED); unlink(path); close(lfd); - input_free(s.in); + input_free(s.cmd_in); screen_free(&s.screen); app_free(s.app); return 0; diff --git a/tests/live_graphics.py b/tests/live_graphics.py index 97dbdd4..74e4b2c 100644 --- a/tests/live_graphics.py +++ b/tests/live_graphics.py @@ -156,12 +156,29 @@ def main(): str(back[:6]), ) - os.write(fd, b"\x01q") - drain(fd, idle=0.2, limit=2.0) - try: - os.kill(pid, 9) - except ProcessLookupError: - pass + # A second terminal has its own kitty image namespace. The first client's + # `sent` bit must not make a new viewer receive only a placement for pixels + # its terminal has never seen. + pid2, fd2 = spawn() + second = drain(fd2, idle=0.6, limit=30.0) + second_cmds = gfx_commands(second) + ok &= check( + "a joining client receives its own image transmission", + any(c.startswith(b"a=t") for c, _ in second_cmds), + str(second_cmds[:8]), + ) + ok &= check( + "and joining it leaves the first client attached", + os.waitpid(pid, os.WNOHANG) == (0, 0), + ) + + os.write(fd2, b"\x01q") + drain(fd2, idle=0.2, limit=2.0) + for child in (pid, pid2): + try: + os.kill(child, 9) + except ProcessLookupError: + pass return 0 if ok else 1 diff --git a/tests/screen_test.c b/tests/screen_test.c new file mode 100644 index 0000000..248479e --- /dev/null +++ b/tests/screen_test.c @@ -0,0 +1,79 @@ +/* Canonical-screen projection into independently sized client views. */ +#include "slosh.h" + +#include <stdio.h> +#include <string.h> + +static int fails; + +static void ok(const char *name, bool cond) { + if (!cond) fails++; + printf("%s %s\n", cond ? "ok " : "FAIL", name); +} + +static char at(screen_t *s, uint16_t x, uint16_t y) { + cell_t *c = screen_at(s, x, y); + return c && c->len ? c->text[0] : ' '; +} + +int main(void) { + screen_t src, view; + screen_init(&src, 6, 4); + for (uint16_t y = 0; y < src.rows; y++) + for (uint16_t x = 0; x < src.cols; x++) { + char ch = (char)('A' + y * src.cols + x); + screen_put_utf8(&src, x, y, &ch, 1, (color_t){0}, (color_t){0}, 0); + } + src.cursor_visible = true; + src.cursor_x = 4; + src.cursor_y = 2; + uint16_t link = screen_link_id(&src, "https://example.test", 20); + screen_set_link(&src, 3, 2, link); + screen_at(&src, 3, 2)->attrs = ATTR_BOLD; + + screen_init(&view, 8, 5); + screen_project(&view, &src, 0, 0); + ok("a larger client gets the canonical top-left", at(&view, 5, 3) == 'X'); + ok("columns beyond the canonical screen are filler", at(&view, 6, 0) == ' '); + ok("rows beyond the canonical screen are filler", at(&view, 0, 4) == ' '); + ok("the cursor is translated into the client", + view.cursor_visible && view.cursor_x == 4 && view.cursor_y == 2); + + screen_resize(&view, 3, 2); + screen_project(&view, &src, 2, 1); + ok("a smaller client receives the selected crop", + at(&view, 0, 0) == 'I' && at(&view, 2, 1) == 'Q'); + ok("styles survive projection", (screen_at(&view, 1, 1)->attrs & ATTR_BOLD)); + ok("hyperlinks survive projection", + view.cur_link[4] != 0 && + strcmp(view.links[view.cur_link[4] - 1], "https://example.test") == 0); + ok("a cursor in the crop uses local coordinates", + view.cursor_visible && view.cursor_x == 2 && view.cursor_y == 1); + + uint16_t vx = 0, vy = 0; + screen_follow_cursor(&src, 3, 2, &vx, &vy); + ok("a small viewport follows the cursor minimally", vx == 2 && vy == 1); + src.cursor_x = 1; + src.cursor_y = 0; + screen_follow_cursor(&src, 3, 2, &vx, &vy); + ok("the viewport follows the cursor back toward the origin", + vx == 1 && vy == 0); + src.cursor_visible = false; + vx = 99; + vy = 99; + screen_follow_cursor(&src, 3, 2, &vx, &vy); + ok("a hidden cursor retains and clamps the viewport", vx == 3 && vy == 2); + + screen_put_utf8(&src, 4, 0, "日", strlen("日"), (color_t){0}, (color_t){0}, + 0); + screen_resize(&view, 5, 1); + screen_project(&view, &src, 0, 0); + ok("a wide glyph cut at the right edge is blank", at(&view, 4, 0) == ' '); + screen_project(&view, &src, 5, 0); + ok("a wide-glyph tail cut at the left edge is blank", at(&view, 0, 0) == ' '); + + screen_free(&view); + screen_free(&src); + printf("\n%s (%d failures)\n", fails ? "FAILED" : "all green", fails); + return fails ? 1 : 0; +} diff --git a/tests/test_nested.py b/tests/test_nested.py index 16c10ed..78c2df7 100644 --- a/tests/test_nested.py +++ b/tests/test_nested.py @@ -1,9 +1,9 @@ #!/usr/bin/env python3 """Running slosh from inside slosh. -A new client displaces the current display, so `slosh` typed into a pane of -the very session it would attach used to displace the client showing that -pane — you watched your own session detach, from inside it. The pane's +`slosh` typed into a pane of the very session it would attach would feed the +session's display back through one of its own panes: a recursive view with no +useful stopping point. The pane's environment (SLOSH, SLOSH_SESSION) says which session this is, so the attach path refuses that one name and only that one name: any other is deliberate nesting, and the control verbs (`cmd`, `ls`) are how a program in a pane is diff --git a/tests/test_session.py b/tests/test_session.py index 7c3f22b..5878945 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -6,6 +6,7 @@ the assertions are about what survives: content, layout, and the process. """ import fcntl +import json import os import pty import select @@ -86,6 +87,23 @@ def control(name, line): return out.stdout.strip() +def screen_size(name): + snap = json.loads(control(name, "snapshot json")) + return snap["cols"], snap["rows"] + + +def resize(pid, fd, cols, rows): + fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0)) + os.kill(pid, signal.SIGWINCH) + + +def running(pid): + try: + return os.waitpid(pid, os.WNOHANG)[0] == 0 + except ChildProcessError: + return False + + def wait_gone(pid, timeout=3.0): end = time.time() + timeout while time.time() < end: @@ -188,22 +206,75 @@ def main(): out = drain(fd2) check("input works after reattach", b"beta" in out, repr(out[-60:])) - # --- a second client replaces the first ----------------------------- - pid3, fd3 = attach(name) + # --- multiple attached clients share one session -------------------- + pid3, fd3 = attach(name, cols=50, rows=12) drain(fd3) tail = drain(fd2, idle=0.2, limit=2.0) check( - "the displaced client is told it was replaced", - b"replaced" in tail or wait_gone(pid2, 1.0), + "a second client leaves the first attached", + b"replaced" not in tail and running(pid2), repr(tail[-60:]), ) + check("the newest attachment owns the size", screen_size(name) == (50, 12)) - # --- closing the last pane ends the session ------------------------- - os.write(fd3, b"\x01x") # close pane 2 + # The control path asks the canonical screen for a full repaint. Since the + # canonical screen is now only a model, that request has to fan out to both + # clients' independent diff histories. + drain(fd2) + drain(fd3) + control(name, "reload") + repaint2 = drain(fd2) + repaint3 = drain(fd3) + check( + "a canonical repaint reaches every attached client", + b"\x1b[2J" in repaint2 and b"\x1b[2J" in repaint3, + repr((repaint2[-80:], repaint3[-80:])), + ) + + os.write(fd2, b"-from-first-client") + out2 = drain(fd2) + out3 = drain(fd3) + shared = control(name, "snapshot text") + check( + "either client can type into the shared pane", + b"t-client" in out2 + and b"t-client" in out3 + and "from-firs" in shared + and "t-client" in shared, + repr((out2[-80:], out3[-80:])), + ) + check("the last client to type owns the size", screen_size(name) == (80, 24)) + + resize(pid3, fd3, 40, 10) drain(fd3) - os.write(fd3, b"\x01x") # close the last one - drain(fd3, idle=0.3, limit=2.0) - check("the client exits when the session ends", wait_gone(pid3)) + check( + "resizing an inactive client does not steal the size", + screen_size(name) == (80, 24), + ) + resize(pid2, fd2, 70, 20) + drain(fd2) + check("the active client's resize wins", screen_size(name) == (70, 20)) + + os.write(fd3, b"-small-client-active") + drain(fd3) + drain(fd2) + check("input promotes the smaller client", screen_size(name) == (40, 10)) + + os.write(fd3, b"\x01d") + tail = drain(fd3, idle=0.2, limit=2.0) + check("detach exits only its issuing client", wait_gone(pid3), repr(tail[-60:])) + check("the other client stays attached", running(pid2)) + check( + "disconnecting the active client restores the previous active size", + screen_size(name) == (70, 20), + ) + + # --- closing the last pane ends the session ------------------------- + os.write(fd2, b"\x01x") # close pane 2 + drain(fd2) + os.write(fd2, b"\x01x") # close the last one + drain(fd2, idle=0.3, limit=2.0) + check("every client exits when the session ends", wait_gone(pid2)) time.sleep(0.3) listing = subprocess.run([BIN, "ls"], capture_output=True, text=True).stdout @@ -215,6 +286,61 @@ def main(): except ProcessLookupError: pass + # --- the config knobs ----------------------------------------------- + # multi_attach false restores the displacing attach; size_follows + # "smallest" sizes the shared screen to the tightest attached terminal. + # Each knob gets a fresh session, whose config exists before its server + # starts (the server reads it once at startup, plus on reload). + with open(CONFIG, "w") as f: + f.write("splash_ms 0\nmulti_attach false\n") + name_x = "t" + uuid.uuid4().hex[:8] + pid_a, fd_a = attach(name_x) + drain(fd_a) + pid_b, fd_b = attach(name_x) + drain(fd_b) + tail = drain(fd_a, idle=0.2, limit=2.0) + check( + "multi_attach false: the old client is displaced", + b"replaced" in tail or wait_gone(pid_a, 1.0), + repr(tail[-60:]), + ) + check("multi_attach false: the new client is attached", running(pid_b)) + control(name_x, "quit") + drain(fd_b, idle=0.2, limit=2.0) + + with open(CONFIG, "w") as f: + f.write('splash_ms 0\nsize_follows "smallest"\n') + name_y = "t" + uuid.uuid4().hex[:8] + pid_c, fd_c = attach(name_y, cols=80, rows=24) + drain(fd_c) + pid_d, fd_d = attach(name_y, cols=50, rows=12) + drain(fd_d) + drain(fd_c) + check( + "size_follows smallest: the tightest client sizes the screen", + screen_size(name_y) == (50, 12), + ) + os.write(fd_c, b"x") # input on the big client must not steal the size + drain(fd_c) + check( + "size_follows smallest: input does not steal the size", + screen_size(name_y) == (50, 12), + ) + os.write(fd_d, b"\x01d") # the small client leaves; the floor rises + drain(fd_d, idle=0.2, limit=2.0) + check( + "size_follows smallest: a departing client raises the floor", + screen_size(name_y) == (80, 24), + ) + control(name_y, "quit") + drain(fd_c, idle=0.2, limit=2.0) + + for p in (pid_a, pid_b, pid_c, pid_d): + try: + os.kill(p, signal.SIGKILL) + except ProcessLookupError: + pass + print(f"\n{'FAILED' if fails else 'all green'} ({fails} failures)") return 1 if fails else 0 |
