diff --git a/spikes/gpui/Cargo.lock b/spikes/gpui/Cargo.lock index c377ab2..f411bb1 100644 --- a/spikes/gpui/Cargo.lock +++ b/spikes/gpui/Cargo.lock @@ -8284,6 +8284,19 @@ dependencies = [ "yuv", ] +[[package]] +name = "spike-composer" +version = "0.0.0" +dependencies = [ + "anyhow", + "gpui-kit", + "log", + "serde_json", + "spike-common", + "voelin-model", + "voelin-ui-vm", +] + [[package]] name = "spike-video" version = "0.0.0" @@ -9847,6 +9860,23 @@ dependencies = [ "voelin-media", ] +[[package]] +name = "voelin-ui-vm" +version = "0.0.1-alpha" +dependencies = [ + "chrono", + "image", + "miniz_oxide 0.8.9", + "serde", + "serde_json", + "unicode-segmentation", + "voelin-audio", + "voelin-core", + "voelin-gateway-proto", + "voelin-model", + "voelin-store", +] + [[package]] name = "vswhom" version = "0.1.0" diff --git a/spikes/gpui/Cargo.toml b/spikes/gpui/Cargo.toml index 9cff9b8..5bcf6a7 100644 --- a/spikes/gpui/Cargo.toml +++ b/spikes/gpui/Cargo.toml @@ -4,7 +4,7 @@ # into the checkout's target directory (.cargo/config.toml). [workspace] resolver = "3" -members = ["common", "video"] +members = ["common", "video", "composer"] [workspace.package] version = "0.0.0" diff --git a/spikes/gpui/composer/Cargo.toml b/spikes/gpui/composer/Cargo.toml new file mode 100644 index 0000000..9636457 --- /dev/null +++ b/spikes/gpui/composer/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "spike-composer" +description = "Spike 2: the composer (multi-line input, emoji, paste, Ctrl+Enter, preedit) and chat lines as StyledText." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +anyhow = "1" +gpui-kit = { workspace = true } +log = { workspace = true } +spike-common = { workspace = true } +serde_json = "1" +voelin-model = { workspace = true } +voelin-ui-vm = { workspace = true } + +[lints] +workspace = true diff --git a/spikes/gpui/composer/README.md b/spikes/gpui/composer/README.md new file mode 100644 index 0000000..ecccfd5 --- /dev/null +++ b/spikes/gpui/composer/README.md @@ -0,0 +1,51 @@ +# Spike 2: composer, IME and chat lines + +`spike-composer` is a chat view with a composer: + +- **Lines.** Sample messages in BBCode go through `voelin-ui-vm` + (`chat::line`: `bbcode` โ†’ `TextBlock`s of `TextRun`s, read only) and are + drawn as `StyledText` with one GPUI text run per `TextRun` (its font: + Inter, the theme's monospace font for code, Noto Color Emoji for the runs + marked as emoji; bold, italic, underline, strike, code background, the + author colour `ink_dark`) inside `InteractiveText`, whose clickable ranges + are the runs with a link (a click prints the link and whether it is + masked, which asks first). Quotes, code blocks, list items and rules are + blocks; one to three emoji alone are large (`ChatLine.jumbo`). Emoji are + characters drawn by a colour emoji font (`TextRun.emoji`, the Twemoji key, + only says that a run is one). +- **Emoji probe.** At start the spike lays out three lines of emoji the way + the list draws them, once with the emoji runs in Noto Color Emoji and once + in Inter with its fallback chain, and prints how many glyphs GPUI draws in + colour (`ShapedGlyph::is_emoji`). +- **Composer.** gpui-component's `Textarea` (`TextareaState`, auto-grow 1 + to 6 rows). The emoji button opens a picker of the first 96 emoji of + `voelin_ui_vm::emoji::archive().category(0)` (the names and characters of + the client's picker); a click inserts at the caret (`TextareaState::insert`) + and gives the focus back. Ctrl+Enter sends (bound to a `Send` action in the + `Input` context after gpui-component's own bindings, so its + "secondary enter" newline is not inserted first). `Textarea::on_paste` + takes pictures (`ClipboardEntry::Image`), files (`ExternalPaths`) and text + that is the absolute path of an existing file as attachments; other text + is pasted. +- **Preedit.** Nothing in the app: GPUI's platform input handler and + gpui-component's marked text. The spike reads the marked range ten times a + second and prints it. + +## Reproducing + +```sh +spikes/gpui/shell.sh sh -c 'cd spikes/gpui && cargo build --locked --release' +# the sample list, the picker, typing, emoji at the caret, Ctrl+Enter, +# picture and path paste, a link click: eight checks and the emoji probe's +# findings, screenshots in $OUT +spikes/gpui/shell.sh spikes/gpui/headless.sh -- spikes/gpui/composer/drive.sh +# X11 preedit: fcitx5 + Pinyin as the XIM server (on-the-spot), "nihao", +# Space, Ctrl+Enter: three checks, screenshots of the preedit +spikes/gpui/shell.sh spikes/gpui/headless.sh -- spikes/gpui/composer/ime.sh +``` + +`drive.sh` first opens the window once with a font configuration of only +Noto Color Emoji, Noto Sans CJK and Cantarell (`FONTCONFIG_FILE`), then with +the system's: the two screenshots and the probe's two lines show the colour +emoji finding in +[docs/design/gpui-spikes.md](../../../docs/design/gpui-spikes.md#spike-2-composer-ime-and-chat-lines). diff --git a/spikes/gpui/composer/drive.sh b/spikes/gpui/composer/drive.sh new file mode 100755 index 0000000..3bfb4a6 --- /dev/null +++ b/spikes/gpui/composer/drive.sh @@ -0,0 +1,115 @@ +#!/bin/sh +# Spike 2's scenario on the headless display: a screenshot of the sample +# chat lines, then typing, an emoji from the picker inserted at the caret, +# Ctrl+Enter, a picture and a file path pasted from the clipboard, a click +# on a masked link; then checks the events the spike printed. Screenshots +# and the event log go to $OUT. +# +# spikes/gpui/shell.sh spikes/gpui/headless.sh -- spikes/gpui/composer/drive.sh +set -eu +root=$(cd "$(dirname "$0")/../../.." && pwd) +out=${OUT:-$root/.scratch/gpui-spikes-results} +mkdir -p "$out" +out=$(cd "$out" && pwd) + +# First the same window with a font configuration of only Noto Color Emoji +# and Noto Sans CJK (no DejaVu Sans, whose monochrome U+1F600-U+1F640 win +# over the fallback chain's Noto Color Emoji), picker open: its emoji probe +# is the comparison for the system configuration's. +# GPUI itself needs one of its default UI fonts (Cantarell is one). +latin=$(nix build --no-link --print-out-paths nixpkgs#cantarell-fonts | head -1) +cat >"$out/fonts-noto-only.conf" < + + + $(dirname "$SPIKE_EMOJI_FONT") + $(dirname "$SPIKE_EXTRA_FONTS") + $latin/share/fonts + +CONF +FONTCONFIG_FILE=$out/fonts-noto-only.conf "$root/target/release/spike-composer" --picker --seconds 6 >"$out/composer-noto-only.jsonl" 2>/dev/null & +pid=$! +sleep 4 +win=$(xdotool search --name 'Composer \(spike\)' | head -1) +xwd -id "$win" -silent | magick xwd:- "png:$out/composer-noto-only.png" +wait "$pid" || true +events=$out/composer-events.jsonl +"$root/target/release/spike-composer" --seconds 90 >"$events" 2>"$out/composer.log" & +pid=$! +step() { echo "== $*" >&2; } +i=0 +until win=$(xdotool search --name 'Composer \(spike\)' 2>/dev/null | head -1) && [ -n "$win" ]; do + i=$((i + 1)) + [ $i -lt 150 ] || { echo "no window" >&2; exit 1; } + sleep 0.1 +done +xdotool windowactivate --sync "$win" +sleep 2.5 +xwd -id "$win" -silent | magick xwd:- "png:$out/composer-messages.png" +eval "$(xdotool getwindowgeometry --shell "$win")" +step "typing, then the caret one character back" +xdotool type --delay 80 'ab' +xdotool key Left +sleep 0.3 +step "the emoji button, then the picker's first emoji" +xdotool mousemove --window "$win" 30 $((HEIGHT - 30)) click 1 +sleep 0.8 +xwd -id "$win" -silent | magick xwd:- "png:$out/composer-picker.png" +xdotool mousemove --window "$win" 37 $((HEIGHT - 12 - 36 - 8 - 180 + 8 + 17)) click 1 +sleep 0.5 +step "Ctrl+Enter sends" +xdotool key ctrl+Return +sleep 0.5 +step "a picture on the clipboard, Ctrl+V" +magick -size 64x48 xc:'#3b6cf6' "$out/paste.png" +xclip -selection clipboard -t image/png -i "$out/paste.png" +sleep 0.3 +xdotool key ctrl+v +sleep 0.8 +step "a file's path on the clipboard, Ctrl+V" +printf '%s' "$out/paste.png" | xclip -selection clipboard +sleep 0.3 +xdotool key ctrl+v +sleep 0.8 +xdotool type --delay 80 'files' +xwd -id "$win" -silent | magick xwd:- "png:$out/composer-attachments.png" +xdotool key ctrl+Return +sleep 0.5 +step "a click on the first message's masked link" +# Held 120 ms: InteractiveText installs its mouse-up listener on the frame +# after the mouse-down, so a click shorter than a frame is lost. +xdotool mousemove --window "$win" 50 59 mousedown 1 +sleep 0.12 +xdotool mouseup 1 +sleep 0.5 +xwd -id "$win" -silent | magick xwd:- "png:$out/composer-after.png" +kill "$pid" 2>/dev/null || true +wait "$pid" 2>/dev/null || true + +fail=0 +check() { + if jq -e -s "$2" "$events" >/dev/null; then + echo "PASS $1" + else + echo "FAIL $1" + fail=1 + fi +} +ev='[.[] | select(.event)]' +probe='[.[] | select(.event == "emoji probe")]' +check "the emoji font is loaded" "$ev | any(.event == \"fonts\" and .emoji != null)" +check "voelin-ui-vm marks every emoji of the probe as an emoji run" "$probe | length == 3 and all(.emoji_runs > 0)" +# Findings, not checks (docs/design/gpui-spikes.md, spike 2, "Colour +# emoji"): of each probe text's emoji, how many GPUI draws in colour, with +# the emoji runs in the emoji font and with the UI font's fallback chain +# alone, under the system's font configuration and under the Noto-only one. +for f in "$events" "$out/composer-noto-only.jsonl"; do + jq -c -s --arg f "$(basename "$f")" '[.[] | select(.event == "emoji probe") | {text, emoji_font: .emoji_font.colour_glyphs, fallback_chain: .fallback_chain.colour_glyphs}] | {file: $f, colour_glyphs: .}' "$f" | sed 's/^/FINDING /' +done +check "an emoji from the picker goes in at the caret" "$ev | any(.event == \"emoji inserted\" and (.value | startswith(\"a\") and endswith(\"b\") and length > 2))" +check "Ctrl+Enter sends the text with the emoji (no newline)" "$ev | any(.event == \"sent\" and (.text | startswith(\"a\") and endswith(\"b\")) and (.text | contains(\"\n\") | not))" +check "a pasted picture is attached" "$ev | any(.event == \"attached\" and (.what[0] | startswith(\"picture Png\")))" +check "a pasted file path is attached" "$ev | any(.event == \"attached\" and (.what[0] | startswith(\"file \")))" +check "the message goes with both attachments" "$ev | any(.event == \"sent\" and .text == \"files\" and (.attachments | length) == 2)" +check "a click on a masked link reaches the app, which asks first" "$ev | any(.event == \"link clicked\" and .masked and .url == \"https://example.com/raid\")" +exit $fail diff --git a/spikes/gpui/composer/ime.sh b/spikes/gpui/composer/ime.sh new file mode 100755 index 0000000..934e03d --- /dev/null +++ b/spikes/gpui/composer/ime.sh @@ -0,0 +1,97 @@ +#!/bin/sh +# X11 preedit with a CJK input method on the headless display: fcitx5 with +# Pinyin (fcitx5-chinese-addons) as the XIM server, the composer as its +# client (XMODIFIERS=@im=fcitx), "nihao" typed: the preedit must show in +# the input (marked text), Space commits ไฝ ๅฅฝ, Ctrl+Enter sends it. fcitx5's +# configuration and state stay in the headless session's XDG directories. +# +# spikes/gpui/shell.sh spikes/gpui/headless.sh -- spikes/gpui/composer/ime.sh +# +# FCITX5: an fcitx5 with the Pinyin addon (default: built from nixpkgs). +set -eu +root=$(cd "$(dirname "$0")/../../.." && pwd) +out=${OUT:-$root/.scratch/gpui-spikes-results} +mkdir -p "$out" +out=$(cd "$out" && pwd) +if [ -z "${FCITX5:-}" ]; then + FCITX5=$(nix build --option substituters "https://cache.nixos.org/ https://nix-community.cachix.org" \ + --no-link --print-out-paths --impure --expr \ + 'let p = (builtins.getFlake "nixpkgs").legacyPackages.x86_64-linux; in p.qt6Packages.fcitx5-with-addons.override { addons = [ p.qt6Packages.fcitx5-chinese-addons ]; }') +fi +mkdir -p "$XDG_CONFIG_HOME/fcitx5" +cat >"$XDG_CONFIG_HOME/fcitx5/profile" <<'PROFILE' +[Groups/0] +Name=Default +Default Layout=us +DefaultIM=pinyin + +[Groups/0/Items/0] +Name=keyboard-us +Layout= + +[Groups/0/Items/1] +Name=pinyin +Layout= + +[GroupOrder] +0=Default +PROFILE +cat >"$XDG_CONFIG_HOME/fcitx5/config" <<'CONFIG' +[Behavior] +ActiveByDefault=True +ShareInputState=All +CONFIG +# On-the-spot: the preedit goes to the client (GPUI asks for +# XIMPreeditCallbacks); fcitx5 draws it in its own window otherwise. +mkdir -p "$XDG_CONFIG_HOME/fcitx5/conf" +printf 'UseOnTheSpot=True\n' >"$XDG_CONFIG_HOME/fcitx5/conf/xim.conf" +"$FCITX5/bin/fcitx5" --replace --disable=wayland,waylandim,notificationitem,kimpanel >"$out/fcitx5.log" 2>&1 & +fcitx=$! +i=0 +until "$FCITX5/bin/fcitx5-remote" >/dev/null 2>&1; do + i=$((i + 1)) + [ $i -lt 100 ] || { echo "fcitx5 did not start" >&2; break; } + sleep 0.1 +done +sleep 1 +events=$out/ime-events.jsonl +XMODIFIERS=@im=fcitx "$root/target/release/spike-composer" --seconds 60 >"$events" 2>"$out/ime.log" & +pid=$! +i=0 +until win=$(xdotool search --name 'Composer \(spike\)' 2>/dev/null | head -1) && [ -n "$win" ]; do + i=$((i + 1)) + [ $i -lt 150 ] || { echo "no window" >&2; exit 1; } + sleep 0.1 +done +xdotool windowactivate --sync "$win" +sleep 2 +"$FCITX5/bin/fcitx5-remote" -o || true +echo "fcitx5 state: $("$FCITX5/bin/fcitx5-remote" 2>&1) (2: active)" >&2 +sleep 0.5 +xdotool type --delay 150 'nihao' +sleep 1.5 +xwd -root -silent | magick xwd:- -resize 50% "png:$out/ime-preedit.png" +xwd -id "$win" -silent | magick xwd:- "png:$out/ime-preedit-window.png" +xdotool key space +sleep 1 +xwd -id "$win" -silent | magick xwd:- "png:$out/ime-committed.png" +xdotool key ctrl+Return +sleep 0.8 +kill "$pid" 2>/dev/null || true +wait "$pid" 2>/dev/null || true +kill "$fcitx" 2>/dev/null || true + +fail=0 +check() { + if jq -e -s "$2" "$events" >/dev/null; then + echo "PASS $1" + else + echo "FAIL $1" + fail=1 + fi +} +ev='[.[] | select(.event)]' +check "the input shows the preedit as marked text" "$ev | any(.event == \"preedit\" and .marked != null and (.marked | length) > 0)" +check "the commit puts Chinese text in the input" "$ev | any((.value // \"\") | explode | any(. >= 19968 and . <= 40959))" +check "Ctrl+Enter sends it" "$ev | any(.event == \"sent\" and (.text | explode | any(. >= 19968 and . <= 40959)))" +exit $fail diff --git a/spikes/gpui/composer/src/main.rs b/spikes/gpui/composer/src/main.rs new file mode 100644 index 0000000..e918a38 --- /dev/null +++ b/spikes/gpui/composer/src/main.rs @@ -0,0 +1,657 @@ +//! Spike 2, the composer and chat lines (plan section 6 step 1): +//! gpui-component's multi-line input with emoji inserted at the caret from a +//! picker (names from `voelin-ui-vm`'s emoji module), file and picture +//! paste, Ctrl+Enter to send, IME preedit (the platform's, through GPUI's +//! input handler), and chat lines made by `voelin-ui-vm` (`chat::line`: +//! BBCode โ†’ `TextBlock`s of `TextRun`s) drawn as `StyledText` in +//! `InteractiveText` with clickable links and inline colour emoji (the runs +//! `voelin-ui-vm` marks as emoji in the colour emoji font). +//! +//! ```text +//! spike-composer [--picker] [--seconds N] +//! ``` +//! +//! Every event (sent, attached, emoji inserted, link clicked, the input's +//! text and preedit) is a JSON line on stdout, which `drive.sh` checks. + +use std::ops::Range; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Instant; + +use gpui_kit::component::ActiveTheme as _; +use gpui_kit::component::input::{InputEvent, Textarea, TextareaState}; +use gpui_kit::{ + App, AppContext as _, Context, Entity, EntityInputHandler as _, FocusHandle, Font, FontStyle, + FontWeight, Hsla, Image, ImageSource, InteractiveElement as _, InteractiveText, IntoElement, + KeyBinding, ParentElement as _, Render, StatefulInteractiveElement as _, StrikethroughStyle, + Styled as _, StyledText, TitlebarOptions, UnderlineStyle, Window, WindowBounds, WindowOptions, + actions, div, img, point, px, rgb, size, svg, +}; +use serde_json::json; +use voelin_model::{ChatMessage, ChatTarget}; +use voelin_ui_vm::bridge::{ChatLine, TextBlock}; +use voelin_ui_vm::chat; +use voelin_ui_vm::emoji; + +actions!( + spike_composer, + [ + /// Send the composer's text and attachments. + Send, + /// Open or close the emoji picker. + TogglePicker, + ] +); + +/// The messages the list starts with: what the chat must draw (styles, +/// colours, masked and bare links, code, quotes, lists, emoji, a ZWJ +/// sequence, a flag, CJK text, jumbo emoji). +const SAMPLES: &[(&str, &str)] = &[ + ( + "Mira", + "[url=https://example.com/raid]raid board[/url] for tonight (a masked link: asks before it opens)", + ), + ("Mira", "Raid tonight at [b]21:00[/b]! Bring the flask ๐ŸŽ‰"), + ( + "Mira", + "[i]Bring[/i] [u]consumables[/u], [s]not[/s] snacks. Colours: [color=#e5484d]red[/color] [color=#46a758]green[/color]", + ), + ( + "Jonas", + "Patch notes: https://example.org/notes/2026-10, see `voice --fix` and [code]let gain = -6.0;\nmixer.set(gain);[/code]", + ), + ("Jonas", "[quote=Mira]Who brings the flask?[/quote]Me ๐Ÿ™‹ โ€” and a ๐Ÿ‘ฉโ€๐Ÿ’ป for the logs ๐Ÿ‡ซ๐Ÿ‡ท"), + ("Aiko", "ๆ—ฅๆœฌ่ชžใฎใƒ†ใ‚ญใ‚นใƒˆใ€ไธญๆ–‡็š„ๆ–‡ๆœฌใ€ํ•œ๊ตญ์–ด ํ…์ŠคํŠธ โ€” CJK through the system fonts"), + ("Aiko", "[list][*]first item[*]second with ๐Ÿ™‚[*]third[/list]"), + // U+1F600 to U+1F640, which DejaVu Sans also has (in monochrome). + ("Jonas", "Smileys DejaVu also has: ๐Ÿ˜€ ๐Ÿ˜‚ ๐Ÿ˜ ๐Ÿ™€, and one it lacks: ๐Ÿ™‚"), + ("Aiko", "๐ŸŽ‰๐ŸŽ‰"), + ( + "Mira", + "Join us: ts3server://voice.example.com?port=9987 or [url=javascript:alert(1)]this[/url] (refused)", + ), +]; + +/// A file or picture waiting to go with the next message. +#[derive(Clone)] +enum Attachment { + File(PathBuf), + Picture(Arc), +} + +/// The fonts chat runs are drawn in: the UI font (Inter and its fallback +/// chain), the colour emoji font for the runs `voelin-ui-vm` marks as emoji +/// (`TextRun.emoji`, the Twemoji key, is only used to know that), and the +/// theme's monospace font for code. +#[derive(Clone)] +struct RunFonts { + ui: Font, + emoji: Font, + mono: Font, +} + +impl RunFonts { + fn new(cx: &App) -> Self { + Self { + ui: spike_common::fonts::ui_font(), + emoji: spike_common::fonts::emoji_font(), + mono: Font { + family: cx.theme().mono_font_family.clone(), + ..spike_common::fonts::ui_font() + }, + } + } +} + +struct Composer { + start: Instant, + fonts: RunFonts, + input: Entity, + lines: Vec, + previous: Option, + attachments: Vec, + picker_open: bool, + picker: Vec, + focus: FocusHandle, + last_preedit: Option, +} + +fn event(start: Instant, what: serde_json::Value) { + let mut line = what; + line["t"] = json!((start.elapsed().as_secs_f64() * 10.0).round() / 10.0); + println!("{line}"); +} + +fn hex(rgb_value: u32) -> Hsla { + rgb(rgb_value).into() +} + +impl Composer { + fn new(window: &mut Window, cx: &mut Context) -> Self { + let input = cx.new(|cx| { + let mut state = + TextareaState::new(window, cx).placeholder("Message #Lobby (Ctrl+Enter sends)"); + state.set_auto_grow(1, 6, cx); + state + }); + cx.subscribe_in(&input, window, |this: &mut Self, input, e: &InputEvent, _, cx| { + if let InputEvent::Change = e { + let value = input.read(cx).value().to_string(); + event(this.start, json!({"event": "changed", "value": value})); + } + }) + .detach(); + // The preedit, read as the platform's IME sees it (the marked range of + // GPUI's input handler) ten times a second: a preedit is not a change + // of the input's value. + cx.spawn_in(window, async move |this, cx| { + loop { + cx.background_executor().timer(std::time::Duration::from_millis(100)).await; + if this.update_in(cx, |this, window, cx| this.poll_preedit(window, cx)).is_err() { + break; + } + } + }) + .detach(); + let mut lines = Vec::new(); + let mut previous = None; + for (i, (author, text)) in SAMPLES.iter().enumerate() { + let message = ChatMessage { + target: ChatTarget::Channel(1), + author_name: (*author).to_owned(), + author_uid: None, + author_id: None, + text: (*text).to_owned(), + ts_ms: 1_792_830_000_000 + i as i64 * 60_000, + via_relay: false, + blocked: false, + }; + lines.push(chat::line(&message, previous.as_ref())); + previous = Some(chat::Previous::of(&message)); + } + let picker = emoji::archive().category(0).into_iter().take(96).collect(); + Self { + start: Instant::now(), + fonts: RunFonts::new(cx), + input, + lines, + previous, + attachments: Vec::new(), + picker_open: spike_common::flag("picker"), + picker, + focus: cx.focus_handle(), + last_preedit: None, + } + } + + /// Log the input's preedit (marked text) when it changes. + fn poll_preedit(&mut self, window: &mut Window, cx: &mut Context) { + let value = self.input.read(cx).value().to_string(); + let marked = self.input.update(cx, |s, cx| { + s.marked_text_range(window, cx).map(|r| { + let utf16: Vec = value.encode_utf16().collect(); + String::from_utf16_lossy(utf16.get(r).unwrap_or_default()) + }) + }); + if marked != self.last_preedit { + event(self.start, json!({"event": "preedit", "marked": marked, "value": value})); + self.last_preedit = marked; + } + } + + fn send(&mut self, window: &mut Window, cx: &mut Context) { + let text = self.input.read(cx).value().trim().to_owned(); + if text.is_empty() && self.attachments.is_empty() { + return; + } + let names: Vec = self + .attachments + .drain(..) + .map(|a| match a { + Attachment::File(p) => p.display().to_string(), + Attachment::Picture(i) => { + format!("picture ({:?}, {} bytes)", i.format, i.bytes.len()) + } + }) + .collect(); + let mut body = text.clone(); + for name in &names { + body.push_str(&format!("\n๐Ÿ“Ž {name}")); + } + let message = ChatMessage { + target: ChatTarget::Channel(1), + author_name: "me".into(), + author_uid: None, + author_id: None, + text: body, + ts_ms: 1_792_840_000_000, + via_relay: false, + blocked: false, + }; + self.lines.push(chat::line(&message, self.previous.as_ref())); + self.previous = Some(chat::Previous::of(&message)); + event(self.start, json!({"event": "sent", "text": text, "attachments": names})); + self.input.update(cx, |s, cx| s.set_value("", window, cx)); + cx.notify(); + } + + fn insert_emoji(&mut self, text: &str, window: &mut Window, cx: &mut Context) { + self.input.update(cx, |s, cx| { + s.insert(text.to_owned(), window, cx); + s.focus(window, cx); + }); + let value = self.input.read(cx).value().to_string(); + event(self.start, json!({"event": "emoji inserted", "emoji": text, "value": value})); + } + + /// A paste: pictures and files become attachments (and nothing is + /// inserted); a path to an existing file in text does too; other text is + /// pasted as usual. + fn paste(&mut self, item: &gpui_kit::ClipboardItem, cx: &mut App) -> bool { + let mut taken = Vec::new(); + for entry in item.entries() { + match entry { + gpui_kit::ClipboardEntry::Image(image) => { + taken.push(Attachment::Picture(Arc::new(image.clone()))) + } + gpui_kit::ClipboardEntry::ExternalPaths(paths) => { + taken.extend(paths.paths().iter().cloned().map(Attachment::File)) + } + gpui_kit::ClipboardEntry::String(s) => { + let paths: Vec = s + .text() + .lines() + .map(|l| PathBuf::from(l.trim().trim_start_matches("file://"))) + .collect(); + if !paths.is_empty() && paths.iter().all(|p| p.is_absolute() && p.is_file()) { + taken.extend(paths.into_iter().map(Attachment::File)); + } + } + } + } + if taken.is_empty() { + return false; + } + let names: Vec = taken + .iter() + .map(|a| match a { + Attachment::File(p) => format!("file {}", p.display()), + Attachment::Picture(i) => format!("picture {:?} {} bytes", i.format, i.bytes.len()), + }) + .collect(); + event(self.start, json!({"event": "attached", "what": names})); + self.attachments.extend(taken); + cx.refresh_windows(); + true + } +} + +/// A clickable range of a block: the link and whether it is masked. +type Link = (Range, String, bool); + +/// One text block as GPUI text runs: the runs' text joined, each run with +/// its font (emoji runs in the emoji font, code in the monospace one), colour +/// (`base` unless the run has its own) and decoration, and the link ranges. +fn gpui_runs( + block: &TextBlock, + fonts: &RunFonts, + base: Hsla, +) -> (String, Vec, Vec) { + let mut text = String::new(); + let mut runs = Vec::new(); + let mut links: Vec = Vec::new(); + let line = |thickness| UnderlineStyle { thickness, ..Default::default() }; + for run in &block.runs { + let from = text.len(); + text.push_str(&run.text); + let range = from..text.len(); + let mut font = if !run.emoji.is_empty() { + fonts.emoji.clone() + } else if run.code || block.kind == 2 { + fonts.mono.clone() + } else { + fonts.ui.clone() + }; + if run.bold { + font.weight = FontWeight::BOLD; + } + if run.italic { + font.style = FontStyle::Italic; + } + let mut color = run.ink_dark.map_or(base, |ink| hex(ink.0 & 0xffffff)); + let mut underline = run.underline.then(|| line(px(1.0))); + if !run.link.is_empty() { + color = hex(0x7aa2ff); + underline = Some(line(px(1.0))); + // Runs of one link follow each other: one clickable range. + match links.last_mut() { + Some((r, url, _)) if r.end == from && *url == *run.link => r.end = range.end, + _ => links.push((range.clone(), run.link.to_string(), run.masked)), + } + } + runs.push(gpui_kit::TextRun { + len: range.len(), + font, + color, + background_color: run.code.then(|| hex(0x1f2a3d)), + underline, + strikethrough: run + .strike + .then(|| StrikethroughStyle { thickness: px(1.0), ..Default::default() }), + }); + } + (text, runs, links) +} + +/// One text block of a line as styled text with its links clickable. +fn block_text( + start: Instant, + id: (usize, usize), + block: &TextBlock, + jumbo: bool, + fonts: &RunFonts, +) -> impl IntoElement { + let base = if block.kind == 1 { hex(0xb4c0d3) } else { hex(0xe6edf7) }; + let (text, runs, links) = gpui_runs(block, fonts, base); + let ranges: Vec> = links.iter().map(|(r, _, _)| r.clone()).collect(); + let targets: Vec<(String, bool)> = links.into_iter().map(|(_, u, m)| (u, m)).collect(); + let styled = StyledText::new(text).with_runs(runs); + let body = InteractiveText::new(("block", id.0 * 1000 + id.1), styled).on_click( + ranges, + move |i, _, _| { + if let Some((url, masked)) = targets.get(i) { + event( + start, + json!({"event": "link clicked", "url": url, "masked": masked, "asks_first": masked}), + ); + } + }, + ); + let row = div().child(body); + let row = if jumbo { row.text_size(px(40.0)) } else { row }; + match block.kind { + 1 => row.pl_3().border_l_2().border_color(rgb(0x3b4a63)), + 2 => row.bg(rgb(0x111a2b)).px_2(), + 3 => div().flex().gap_2().child("โ€ข").child(row), + 4 => div().h(px(1.0)).w_full().bg(rgb(0x3b4a63)), + _ => row, + } +} + +fn line_view(start: Instant, index: usize, line: &ChatLine, fonts: &RunFonts) -> impl IntoElement { + let header = (!line.continued).then(|| { + div() + .flex() + .gap_2() + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .text_color(hex(line.tint.0 & 0xffffff)) + .child(line.author.to_string()), + ) + .child(div().text_xs().text_color(rgb(0x7d8aa3)).child(line.time.to_string())) + }); + let body = if line.rich { + div() + .flex() + .flex_col() + .children( + line.blocks + .iter() + .enumerate() + .map(|(b, block)| block_text(start, (index, b), block, line.jumbo, fonts)), + ) + .into_any_element() + } else { + div().child(line.text.to_string()).into_any_element() + }; + div().flex().flex_col().gap_1().children(header).child(body) +} + +impl Render for Composer { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let start = self.start; + let picker = self.picker_open.then(|| { + div() + .id("picker") + .flex() + .flex_wrap() + .gap_1() + .p_2() + .max_h(px(180.0)) + .overflow_y_scroll() + .bg(rgb(0x131c2e)) + .rounded_md() + .children(self.picker.iter().enumerate().map(|(i, e)| { + let text = e.text.clone(); + div() + .id(("emoji", i)) + .w(px(34.0)) + .h(px(34.0)) + .flex() + .items_center() + .justify_center() + .text_size(px(22.0)) + .font_family(spike_common::fonts::EMOJI_FAMILY) + .rounded_md() + .hover(|s| s.bg(rgb(0x24324a))) + .child(e.text.clone()) + .on_click(cx.listener(move |this, _, window, cx| { + this.insert_emoji(&text, window, cx) + })) + })) + }); + let attachments = (!self.attachments.is_empty()).then(|| { + div().flex().gap_2().children(self.attachments.iter().enumerate().map(|(i, a)| { + match a { + Attachment::File(p) => div() + .id(("attachment", i)) + .px_2() + .py_1() + .rounded_md() + .bg(rgb(0x1f2a3d)) + .child(format!( + "๐Ÿ“Ž {}", + p.file_name().map(|n| n.to_string_lossy()).unwrap_or_default() + )) + .into_any_element(), + Attachment::Picture(image) => div() + .id(("attachment", i)) + .child(img(ImageSource::Image(image.clone())).w(px(96.0)).h(px(64.0))) + .into_any_element(), + } + })) + }); + let input = self.input.clone(); + div() + .id("composer-root") + .key_context("Composer") + .track_focus(&self.focus) + .on_action(cx.listener(|this, _: &Send, window, cx| this.send(window, cx))) + .on_action(cx.listener(|this, _: &TogglePicker, _, cx| { + this.picker_open = !this.picker_open; + cx.notify(); + })) + .size_full() + .flex() + .flex_col() + .bg(rgb(0x0b1220)) + .text_color(rgb(0xe6edf7)) + .font(spike_common::fonts::ui_font()) + .child( + div() + .id("messages") + .flex_1() + .overflow_y_scroll() + .p_4() + .flex() + .flex_col() + .gap_3() + .children( + self.lines + .iter() + .enumerate() + .map(|(i, l)| line_view(start, i, l, &self.fonts)), + ), + ) + .child( + div().p_3().flex().flex_col().gap_2().children(picker).children(attachments).child( + div() + .flex() + .gap_2() + .items_end() + .child( + div() + .id("emoji-button") + .size(px(36.0)) + .flex() + .items_center() + .justify_center() + .rounded_md() + .bg(rgb(0x1f2a3d)) + .child( + svg() + .path("voelin/smile.svg") + .size(px(20.0)) + .text_color(rgb(0xc8d3e6)), + ) + .on_click(cx.listener(|this, _, _, cx| { + this.picker_open = !this.picker_open; + cx.notify(); + })), + ) + .child(div().flex_1().child(Textarea::new(&input).on_paste({ + let this = cx.entity().downgrade(); + move |item, _, cx| { + this.update(cx, |this, cx| this.paste(item, cx)).unwrap_or(false) + } + }))) + .child( + div() + .id("send") + .px_3() + .h(px(36.0)) + .flex() + .items_center() + .rounded_md() + .bg(rgb(0x3b6cf6)) + .child( + svg() + .path("icons/send.svg") + .size(px(18.0)) + .text_color(rgb(0xffffff)), + ) + .on_click(cx.listener(|this, _, window, cx| this.send(window, cx))), + ), + ), + ) + } +} + +fn main() -> anyhow::Result<()> { + spike_common::init_logging(); + let seconds: Option = spike_common::arg("seconds").map(|v| v.parse()).transpose()?; + gpui_kit::application().with_assets(spike_common::assets::Assets::default()).run(move |cx| { + gpui_kit::init(cx); + let emoji_font = spike_common::fonts::load(cx); + // The client is dark: gpui-component's inputs follow its theme. + gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, cx); + println!( + "{}", + json!({"event": "fonts", "ui": spike_common::fonts::UI_FAMILY, "emoji": emoji_font}) + ); + // After gpui-component's bindings, so Ctrl+Enter in the input is + // Send rather than the input's own "secondary enter" (a newline). + cx.bind_keys([ + KeyBinding::new("ctrl-enter", Send, Some("Input")), + KeyBinding::new("ctrl-e", TogglePicker, None), + ]); + let window = gpui_kit::open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(gpui_kit::Bounds { + origin: point(px(20.0), px(40.0)), + size: size(px(900.0), px(1000.0)), + })), + titlebar: Some(TitlebarOptions { + title: Some("Composer (spike)".into()), + ..Default::default() + }), + ..Default::default() + }, + cx, + |window, cx| cx.new(|cx| Composer::new(window, cx)), + ) + .expect("a window"); + // The input has focus from the start. + let _ = window.0.update(cx, |_, window, cx| { + window.dispatch_action(Box::new(gpui_kit::component::input::MoveToEnd), cx) + }); + // Which glyphs GPUI draws in colour (`ShapedGlyph::is_emoji`: from the + // colour emoji font), for lines made by `voelin-ui-vm` and drawn as the + // list draws them, once with the emoji runs in the emoji font and once + // in the UI font and its fallback chain. + let _ = window.0.update(cx, |_, window, cx| { + let fonts = RunFonts::new(cx); + let fallback = RunFonts { emoji: fonts.ui.clone(), ..fonts.clone() }; + for sample in [ + "a\u{1f600}b", + "\u{1f602}\u{1f640}\u{1f642}\u{1f389}", + "\u{1f469}\u{200d}\u{1f4bb}", + ] { + let message = ChatMessage { + target: ChatTarget::Channel(1), + author_name: "probe".into(), + author_uid: None, + author_id: None, + text: sample.into(), + ts_ms: 0, + via_relay: false, + blocked: false, + }; + let line = chat::line(&message, None); + let count = |fonts: &RunFonts| { + let (mut colour, mut glyphs) = (0, 0); + for block in &line.blocks { + let (text, runs, _) = gpui_runs(block, fonts, hex(0xffffff)); + let layout = window.text_system().layout_line(&text, px(16.0), &runs, None); + for run in &layout.runs { + glyphs += run.glyphs.len(); + colour += run.glyphs.iter().filter(|g| g.is_emoji).count(); + } + } + json!({"colour_glyphs": colour, "glyphs": glyphs}) + }; + let emoji_runs: usize = line + .blocks + .iter() + .flat_map(|b| &b.runs) + .filter(|r| !r.emoji.is_empty()) + .count(); + println!( + "{}", + json!({ + "event": "emoji probe", + "text": sample, + "emoji_runs": emoji_runs, + "emoji_font": count(&fonts), + "fallback_chain": count(&fallback), + }) + ); + } + }); + let composer = window.1; + let _ = window.0.update(cx, |_, window, cx| { + let input = composer.read(cx).input.clone(); + input.update(cx, |s, cx| s.focus(window, cx)); + }); + if let Some(seconds) = seconds { + cx.spawn(async move |cx| { + cx.background_executor().timer(std::time::Duration::from_secs(seconds)).await; + cx.update(|cx| cx.quit()); + }) + .detach(); + } + }); + Ok(()) +}