mirror of
https://github.com/storytold/figcraft.git
synced 2026-12-04 19:41:51 -05:00
Merge pull request #2247 from johanneswilm/system-account-user-name
Your name: a desktop start takes the operating system account's name instead of "You"
This commit is contained in:
Generated
+1
@@ -2873,6 +2873,7 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"rfd",
|
||||
"rustix 1.1.6",
|
||||
"serde_json",
|
||||
"wat",
|
||||
"wayland-client",
|
||||
|
||||
@@ -140,6 +140,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
- **2026-12-01** · Saving a file open in two desktop app instances (M1, #1388): a filesystem watcher notices saved changes without repainting stable files, and `file.refresh` reloads clean native tabs, keeping their identity and view. Local edits, gestures, text and version previews, live sessions and open branch tabs are kept; conflicting saves are refused, including an explicit Save path or Save as to the same file. Path aliases reuse the open tab, and Save as cannot replace another open tab's file. Unsaved edits between independent processes still need a live session. Numbers unchanged.
|
||||
|
||||
- **2026-12-01** · Motion: keyframe animation (the Motion panel) lands — the timeline, the inspector and the easing panel all drive the engine commands (`motion.keyframe`, `motion.keyframeMove`, `motion.keyframeDelete`, `motion.keyframeEase`, `motion.clip`, `motion.clipUpdate`, `motion.clipDelete`, `motion.track`, `motion.replace`, `motion.timeline`), so a motion edit is one undo step and a read-only document refuses it; Animation is an entry beside Prototype in the mode switcher and opens the Motion timeline, and the preview renders the document at the playhead without ever swapping it into the document. The command set is registered and driven by the timeline, inspector and easing panels, and is exercised by the engine and UI unit tests; the engine command count rises by 10.
|
||||
- **2026-11-11** · M9: a first desktop start signs work with the operating system account's name instead of the default "You". `apps/figcraft/src/user_name.rs` resolves it: on Windows the account's first and last name, else its display name (the Windows Runtime's `Windows.System.User`, a safe API); on Linux and the BSDs the full name in the account's `/etc/passwd` entry (its GECOS field, in the line whose uid field is the uid the kernel gives for this process, which no name can stand in for); on macOS `/usr/bin/id -F`; everywhere else, and as the fallback, the logon name (`USERNAME`/`USER`/`LOGNAME`). It fills Preferences ▸ Your name on any desktop run that has a settings folder and no name chosen yet, so a name set there wins and is never asked over; clearing it there puts the default back, and the next start fills the account's name again, because FigCraft has no empty name to keep (WordCraft #4368 does keep one). The browser build, `figcraft-cli`, the MCP server and a `--control` run never ask, so what an agent signs stays the same on every machine. The two lookups that go through the machine's directory services (Windows Runtime, `/usr/bin/id -F`) run on their own thread with a 2 s deadline, so a directory service that never answers cannot hold up opening the window. The name is cleaned by `pref.userName`, as one typed in Preferences is (trimmed, control characters out, 64 characters). Same change as wordcraft's PR #6286. Tests: `user_name_tests` (7), `system_name_tests` (8). Numbers unchanged.
|
||||
- **2026-11-07** · M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged.
|
||||
- **2026-11-05** · M2, #1823: Suggest auto layout is its own command. `layout.suggest` used to run `layout.add` and made one row of everything. It now splits a frame's layers into rows or columns by the gaps between them, wraps each band of several layers in a hugging frame without fill and repeats inside it, so the design gets as many auto layout frames as it needs and keeps its placement where the gaps are even (the frame keeps its size). Uneven gaps, bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes are reported as `warnings`, and instances and layers inside them are refused. `layout.add` is unchanged. Tests in `layout_suggest_tests.rs`. Numbers unchanged.
|
||||
- **2026-11-05** · M3, #2002: the Local variables window selects several variables with a click, Shift+click (range) and Cmd/Ctrl+click (toggle), cleared by Escape or a click on the empty space; delete, move to a group and scope act on the selected local variables as one undo step (`command.batch`); inherited variables can be selected but are left out, since they change in their own collection, and the bulk menu needs two or more local variables selected (otherwise the row shows its own menu). Rename and value edits stay single-row.
|
||||
@@ -407,6 +408,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
| 2026-11-16 | patch | M9, #2365: native and browser clients accept the complete legacy `Welcome` layout without its later reconnect secret, preserving explicit access and rejecting incomplete or trailing data. A host that supplies no secret is rejoined with the share link instead of an unauthenticated `Resume`. Numbers unchanged. |
|
||||
| 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), the exported frame itself hugs where it hugs in the design, a clip is written only on a frame fixed on both axes, and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). |
|
||||
| 2026-11-10 | minor | M6: Uno Platform C# Markup code (ours; the incumbent generates CSS, iOS and Android only): `inspect.code {language: uno}` (aliases `csharp-markup`, `cs-markup`) writes a `UserControl` class whose content is a fluent C# Markup tree for a layer: a frame, group or rectangle is a `Border` (fill as `Color.FromArgb`, border brush and thickness, per-side thickness, per-corner radius, opacity, rotation) holding a `Canvas` with the children at their offsets (a stroke and children put the border behind the canvas in a `Grid`, so the stroke does not push the children in), an ellipse is an `Ellipse`, text is a `TextBlock` (family, size, weight, italic, colour, line height, character spacing, alignment, wrapping, trimming and max lines from the auto resize mode, decoration, case applied when the code runs, mixed styles as `Run`s) and vectors and other shapes are an `Image` on an SVG asset (`ms-appx:///Assets/<name>.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Headline numbers unchanged. |
|
||||
| 2026-11-11 | patch | M9: a first desktop start takes the operating system account's name as the name from Preferences ▸ Your name, so comments and board work are signed with it instead of the default "You" (`apps/figcraft/src/user_name.rs`: Windows Runtime first and last name, else display name; `/etc/passwd` GECOS name on Linux and the BSDs; `id -F` on macOS; the logon name as the fallback). Asked whenever the name in the preferences is still the default and the run has a settings folder, never by the browser build, `figcraft-cli`, the MCP server or a `--control` run, and bounded by 2 s so a silent directory service cannot hold up the window. Tests: `user_name_tests` (7), `system_name_tests` (8). Numbers unchanged |
|
||||
| 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged |
|
||||
| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. |
|
||||
| 2026-11-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. |
|
||||
|
||||
@@ -41,10 +41,18 @@ image = { workspace = true }
|
||||
env_logger = { version = "0.11", default-features = false, features = ["auto-color", "humantime"] }
|
||||
|
||||
# The system's reduce-motion setting (UISettings.AnimationsEnabled), interface language
|
||||
# (GlobalizationPreferences.Languages) and controllers for prototypes (Gaming.Input.Gamepad).
|
||||
# (GlobalizationPreferences.Languages), controllers for prototypes (Gaming.Input.Gamepad) and the
|
||||
# account's name a first start signs work with (`user_name`: Windows.System.User). `System_UserProfile`
|
||||
# already pulls in `System`; it is named to say why the app asks the account for its name.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
windows = { version = "0.62", default-features = false, features = ["UI_ViewManagement", "System_UserProfile", "Foundation_Collections", "Gaming_Input"] }
|
||||
windows = { version = "0.62", default-features = false, features = [
|
||||
"UI_ViewManagement",
|
||||
"System_UserProfile",
|
||||
"System",
|
||||
"Foundation_Collections",
|
||||
"Gaming_Input",
|
||||
] }
|
||||
# The custom title bar's window styles (src/window_frame.rs): safe Win32 wrappers (MIT); the `user`
|
||||
# feature is User32.dll only. Same version as DesignCraft and PhotoCraft.
|
||||
# `shell` is the process identity the Nightly sets for its own taskbar group (process_identity.rs).
|
||||
@@ -55,6 +63,11 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user", "s
|
||||
# accesskit already; this only makes it direct.
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
zbus = { version = "5", default-features = false, features = ["async-io", "blocking-api"] }
|
||||
# The account's uid, for the `user_name` passwd lookup: the environment's logon name can say
|
||||
# anything, and a non-dumpable process's `/proc/self` belongs to root (proc(5)), so neither says
|
||||
# which account this process runs as. `getuid` through `libc` needs unsafe, which the workspace
|
||||
# forbids; rustix is already in the build at this version, and this adds only its `process` module.
|
||||
rustix = { version = "1.1", default-features = false, features = ["std", "process"] }
|
||||
|
||||
# Finder double-clicks, Open With, Dock drops and `open -a FigCraft file.figcraft` arrive as a
|
||||
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle. This crate (also used by GridCraft,
|
||||
|
||||
@@ -42,6 +42,7 @@ mod profile_root;
|
||||
mod recovery;
|
||||
mod services;
|
||||
mod startup;
|
||||
mod user_name;
|
||||
mod window_frame;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod xwayland_pen;
|
||||
@@ -419,6 +420,16 @@ fn main() -> eframe::Result {
|
||||
if let Some(prefs) = svc.prefs.clone() {
|
||||
session.prefs = prefs;
|
||||
}
|
||||
// A desktop run that holds no chosen name signs comments, board stickies and live sessions with
|
||||
// the system account's name rather than the default "You" ([`user_name`]). Asked here, where
|
||||
// what this run is stays known: whether it has a settings folder to keep a name in, and whether
|
||||
// an agent started it. Nothing has been commented or drawn yet, so the name is in place before
|
||||
// anything can be signed.
|
||||
use_system_user_name(&mut session, asks_for_user_name(svc.has_settings(), port.is_some()), user_name::system);
|
||||
if svc.prefs.is_none() {
|
||||
// A first start never signed anything as "You", so no "You" message is this profile's.
|
||||
session.prefs.was_default_name = false;
|
||||
}
|
||||
figcraft_engine::keymap::set_custom(&session.prefs.shortcuts);
|
||||
let first_run = svc.prefs.is_none() && args.join.is_none();
|
||||
// Initialise the interface language before opening files, as startup can now show an import
|
||||
@@ -649,6 +660,43 @@ fn opens_new_file(first_run: bool, control: bool) -> bool {
|
||||
!first_run && control
|
||||
}
|
||||
|
||||
/// Whether this start should ask the system for a name to sign work with ([`user_name`]): the run
|
||||
/// has a settings folder, so a name taken now is kept with the preferences and never asked for
|
||||
/// again, and it was not started for an agent (`--control`, `FIGCRAFT_CONTROL_PORT`), which has to
|
||||
/// sign the same way on every machine. A machine that gives the app nowhere to keep anything
|
||||
/// (`FIGCRAFT_CONFIG_DIR` set empty) asks nothing either. The browser build, `figcraft-cli` and the
|
||||
/// commands over the control channel never come through here at all.
|
||||
fn asks_for_user_name(settings: bool, control: bool) -> bool {
|
||||
settings && !control
|
||||
}
|
||||
|
||||
/// The system account's name ([`user_name`]) as the name from Preferences, while that is still the
|
||||
/// default: on a start before the person has named themselves, and on preferences saved back when
|
||||
/// "You" was the only name there. `ask` is the caller's decision ([`asks_for_user_name`]), so no
|
||||
/// part of this reads the environment and the tests cover both kinds of run. A name set in
|
||||
/// Preferences ▸ Your name always wins, and the system is asked only until one is saved.
|
||||
///
|
||||
/// A blank stored name counts as that default too, because that is what `pref.userName` keeps:
|
||||
/// clearing Preferences ▸ Your name puts the default back, there being no empty name to hold. So,
|
||||
/// unlike WordCraft (#4368, where a name cleared in Options stays empty), a FigCraft name cleared
|
||||
/// on a desktop start is filled from the account again; the name to keep is one typed there.
|
||||
///
|
||||
/// The name goes through `pref.userName`, as one typed in Preferences does, so it is cleaned the
|
||||
/// same way: trimmed, control characters out, capped at `figcraft_engine::live::MAX_NAME`. That
|
||||
/// command is not journaled and touches no document, so nothing becomes dirty and no undo step
|
||||
/// appears, and a live session renames you at once, as typing the name does.
|
||||
fn use_system_user_name(session: &mut Session, ask: bool, system: impl FnOnce() -> Option<String>) {
|
||||
let stored = session.prefs.user_name.trim();
|
||||
if !ask || !(stored.is_empty() || stored == figcraft_engine::cmd::comment::DEFAULT_AUTHOR) {
|
||||
return;
|
||||
}
|
||||
if let Some(name) = system()
|
||||
&& let Err(e) = session.execute("pref.userName", &json!({"name": name}))
|
||||
{
|
||||
log::debug!("user name: the system's isn't usable: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The window frame FigCraft starts with, decided by the shared craft-window crate so every Craft app
|
||||
/// agrees on who draws the frame per desktop. The override variable is `FIGCRAFT_TITLEBAR`
|
||||
/// (`app` / `system`). macOS keeps its inset traffic lights unchanged (craft-window returns the
|
||||
@@ -875,3 +923,141 @@ mod macos_menu_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod system_name_tests {
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use super::{asks_for_user_name, use_system_user_name};
|
||||
|
||||
/// The name comments are signed with until the user sets theirs.
|
||||
const DEFAULT: &str = figcraft_engine::cmd::comment::DEFAULT_AUTHOR;
|
||||
|
||||
#[test]
|
||||
fn the_system_user_name_replaces_only_the_default() {
|
||||
let mut s = Session::new();
|
||||
use_system_user_name(&mut s, true, || Some(" Ada\u{7} Lovelace\n".into()));
|
||||
assert_eq!(s.prefs.user_name, "Ada Lovelace", "cleaned as a name typed in Preferences is");
|
||||
assert_eq!(figcraft_engine::live::display_name(&s.prefs), "Ada Lovelace", "and it names you in a live session");
|
||||
// A name chosen since, this run or an earlier one, is never asked over.
|
||||
let mut asked = false;
|
||||
use_system_user_name(&mut s, true, || {
|
||||
asked = true;
|
||||
Some("Grace Hopper".into())
|
||||
});
|
||||
assert!(!asked, "the system isn't asked once a name is there");
|
||||
assert_eq!(s.prefs.user_name, "Ada Lovelace");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_from_preferences_wins_and_a_blank_one_counts_as_the_default() {
|
||||
let mut s = Session::new();
|
||||
s.execute("pref.userName", &json!({"name": "Grace Hopper"})).unwrap();
|
||||
let mut asked = false;
|
||||
use_system_user_name(&mut s, true, || {
|
||||
asked = true;
|
||||
Some("Ada Lovelace".into())
|
||||
});
|
||||
assert!(!asked, "a name the person set asks nothing");
|
||||
assert_eq!(s.prefs.user_name, "Grace Hopper");
|
||||
// Preferences saved before this change hold the default, and a hand-edited settings file
|
||||
// can hold nothing: both are the missing name the system fills.
|
||||
for stored in [DEFAULT, "", " "] {
|
||||
let mut s = Session::new();
|
||||
s.prefs.user_name = stored.into();
|
||||
use_system_user_name(&mut s, true, || Some("Ada Lovelace".into()));
|
||||
assert_eq!(s.prefs.user_name, "Ada Lovelace", "{stored:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_signed_with_the_system_name_is_still_yours() {
|
||||
// Which comments are yours is the name in the message against the name in the preferences,
|
||||
// so taking the system's name signs and owns them like any other name.
|
||||
let mut s = Session::new();
|
||||
use_system_user_name(&mut s, true, || Some("Ada Lovelace".into()));
|
||||
let c = s.execute("comment.add", &json!({"x": 0, "y": 0, "text": "Mine"})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_eq!(s.doc().unwrap().comment(c).unwrap().first.author, "Ada Lovelace");
|
||||
s.execute("comment.edit", &json!({"id": c, "text": "Still mine"})).unwrap();
|
||||
s.execute("comment.delete", &json!({"id": c})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_saved_as_you_stay_mine_after_the_system_name_arrives() {
|
||||
// The upgrade regression: a file written under the old default keeps its authors on disk, and
|
||||
// its threads stay in the renamed person's Mine. Nothing more: a file can't say which "You"
|
||||
// wrote a message, so changing one still takes the name it was signed with.
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-system-name-upgrade-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("comments.figcraft").to_string_lossy().into_owned();
|
||||
|
||||
let mut before = Session::new();
|
||||
let c = before.execute("comment.add", &json!({"x": 0, "y": 0, "text": "Old note"})).unwrap()["id"].as_u64().unwrap();
|
||||
before.execute("comment.reply", &json!({"id": c, "text": "Old reply"})).unwrap();
|
||||
before.execute("file.saveAs", &json!({"path": path})).unwrap();
|
||||
|
||||
let mut s = Session::new();
|
||||
use_system_user_name(&mut s, true, || Some("Ada Lovelace".into()));
|
||||
assert_eq!(s.prefs.user_name, "Ada Lovelace");
|
||||
s.execute("file.open", &json!({"path": path})).unwrap();
|
||||
let saved = s.doc().unwrap().comment(c).unwrap().clone();
|
||||
assert_eq!(saved.first.author, DEFAULT, "opening the file does not rewrite its author");
|
||||
assert_eq!(saved.replies[0].author, DEFAULT, "nor its replies");
|
||||
|
||||
let mine = s.execute("comment.list", &json!({"page": "all", "filter": "mine"})).unwrap();
|
||||
assert!(mine["comments"].as_array().unwrap().iter().any(|comment| comment["id"] == c), "the old thread is Mine");
|
||||
assert!(s.execute("comment.edit", &json!({"id": c, "text": "Updated"})).is_err());
|
||||
assert!(s.execute("comment.delete", &json!({"id": c})).is_err());
|
||||
s.execute("comment.edit", &json!({"id": c, "text": "Updated", "author": DEFAULT})).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_run_with_a_settings_folder_and_no_agent_asks() {
|
||||
assert!(asks_for_user_name(true, false), "a desktop run with somewhere to keep the name");
|
||||
assert!(!asks_for_user_name(false, false), "nowhere to keep a name");
|
||||
assert!(!asks_for_user_name(true, true), "--control: started for an agent");
|
||||
assert!(!asks_for_user_name(false, true), "neither a settings folder nor a person");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cleared_name_is_the_default_and_is_taken_from_the_account_again() {
|
||||
// Clearing Preferences ▸ Your name puts the default back (`pref.userName` has no empty name
|
||||
// to hold), so the next desktop start reads it as "no name chosen" and fills the account's.
|
||||
// WordCraft (#4368) keeps a cleared name empty; FigCraft has no cleared state to honour, so
|
||||
// the name to keep is one typed there.
|
||||
let mut s = Session::new();
|
||||
s.execute("pref.userName", &json!({"name": "Grace Hopper"})).unwrap();
|
||||
s.execute("pref.userName", &json!({"name": " "})).unwrap();
|
||||
assert_eq!(s.prefs.user_name, DEFAULT, "cleared: the default, not an empty name");
|
||||
use_system_user_name(&mut s, asks_for_user_name(true, false), || Some("Ada Lovelace".into()));
|
||||
assert_eq!(s.prefs.user_name, "Ada Lovelace", "the account names the run again");
|
||||
use_system_user_name(&mut s, asks_for_user_name(true, false), || Some("Someone Else".into()));
|
||||
assert_eq!(s.prefs.user_name, "Ada Lovelace", "and is never asked over a chosen name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_without_a_settings_folder_or_an_agents_run_never_asks() {
|
||||
for (settings, control, why) in [(false, false, "no settings folder"), (true, true, "started for an agent")] {
|
||||
let mut asked = false;
|
||||
let mut s = Session::new();
|
||||
use_system_user_name(&mut s, asks_for_user_name(settings, control), || {
|
||||
asked = true;
|
||||
Some("Ada Lovelace".into())
|
||||
});
|
||||
assert!(!asked, "{why}: no lookup at all");
|
||||
assert_eq!(s.prefs.user_name, DEFAULT, "{why}: the default signs");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_usable_system_name_keeps_the_default() {
|
||||
for system in [None, Some(String::new()), Some(" \t\n".into()), Some("\u{0}\u{1b}".into())] {
|
||||
let mut s = Session::new();
|
||||
use_system_user_name(&mut s, true, || system.clone());
|
||||
assert_eq!(s.prefs.user_name, DEFAULT, "{system:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,6 +131,12 @@ impl Desktop {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this run has a settings folder to read preferences from and keep them in
|
||||
/// ([`config_dir`]; they may not be there yet, on a first start).
|
||||
pub fn has_settings(&self) -> bool {
|
||||
self.dir.is_some()
|
||||
}
|
||||
|
||||
/// winit reports no system theme on Linux and the BSDs: there the freedesktop colour scheme
|
||||
/// answers instead, read once and then watched in the background, calling `wake` when it
|
||||
/// changes (an idle window draws no frames). Elsewhere this does nothing.
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
//! The user name a desktop start takes while none has been chosen: the system account's, so
|
||||
//! comments, board stickies and live sessions carry the designer's name rather than the default
|
||||
//! "You" (`figcraft_engine::cmd::comment::DEFAULT_AUTHOR`). A name set in Preferences ▸ Your name
|
||||
//! is saved and wins from then on (`crate::use_system_user_name`).
|
||||
//!
|
||||
//! - Windows: the account's first and last name, else its display name (only a domain or work
|
||||
//! account has one), read through the Windows Runtime's `Windows.System.User`: a safe API,
|
||||
//! where the Win32 `GetUserNameExW` needs unsafe, which our workspace forbids. Without either
|
||||
//! (an account with no name, or account info access turned off in Settings › Privacy), the
|
||||
//! logon name.
|
||||
//! - Linux, the BSDs: the full name in the running account's `/etc/passwd` entry — the line whose
|
||||
//! uid field is our uid, asked of the kernel rather than inferred: an environment variable can say
|
||||
//! anything, and the line named by the logon name can only ever be somebody else's. The name is
|
||||
//! the GECOS field up to its first comma, as `chfn` sets it. Accounts from a directory service
|
||||
//! (LDAP, SSSD) have no line in that file at all, under their uid or their name, and take the
|
||||
//! logon name.
|
||||
//! - macOS: the full name Directory Services keeps for the account, from the system's own lookup
|
||||
//! (`/usr/bin/id -F`), else the logon name. `objc2-app-kit` binds no `NSFullUserName`, and reading
|
||||
//! Directory Services directly needs unsafe, which our workspace forbids. A directory service
|
||||
//! that doesn't answer must not hold up the start, so like the Windows call it is asked on its
|
||||
//! own thread with a timeout ([`LOOKUP_TIMEOUT`]), and its `id` process is stopped and waited
|
||||
//! for when that deadline passes instead of being left running for the next start to repeat.
|
||||
//! - Runs the app keeps no preferences for (no settings folder: `FIGCRAFT_CONFIG_DIR` set empty),
|
||||
//! runs started for an agent (`--control`, `FIGCRAFT_CONTROL_PORT`) and the browser build,
|
||||
//! `figcraft-cli` and the MCP server, which never call this, keep the default: what they sign or
|
||||
//! save must stay the same on every machine (the desktop start passes that decision as `ask`).
|
||||
//!
|
||||
//! Every source is untrusted: the name still goes through `pref.userName`, as one typed in
|
||||
//! Preferences does, which trims it, drops control characters and caps it at
|
||||
//! `figcraft_engine::live::MAX_NAME`.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
/// The variables holding the logon name; the first with a usable one wins.
|
||||
#[cfg(target_os = "windows")]
|
||||
const LOGON_VARS: &[&str] = &["USERNAME"];
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
const LOGON_VARS: &[&str] = &["USER", "LOGNAME"];
|
||||
|
||||
/// How long a host account lookup may take before the logon name is used instead. Both the
|
||||
/// Windows Runtime call and macOS's `id -F` go through the directory services of the machine, and
|
||||
/// neither is guaranteed to answer when one of them is misconfigured or unreachable. The Windows
|
||||
/// call is left to its own thread when it overruns, a Windows Runtime call not being one anyone can
|
||||
/// interrupt; the `id` process is stopped and waited for at the same deadline.
|
||||
#[cfg(any(target_os = "windows", target_os = "macos", all(test, unix)))]
|
||||
const LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// The most of `/etc/passwd` read: far more than any real one holds.
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
const MAX_PASSWD_BYTES: u64 = 4 << 20;
|
||||
|
||||
/// The name of the account running FigCraft: its full name where the system has one, else its
|
||||
/// logon name; `None` without either.
|
||||
pub fn system() -> Option<String> {
|
||||
let login = logon_name(|var| std::env::var_os(var));
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
if let Some(name) = windows_account_name() {
|
||||
return Some(name);
|
||||
}
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
{
|
||||
if let Some(name) = passwd_full_name() {
|
||||
return Some(name);
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if let Some(name) = directory_services_full_name() {
|
||||
return Some(name);
|
||||
}
|
||||
}
|
||||
login
|
||||
}
|
||||
|
||||
/// The logon name: the first of [`LOGON_VARS`] that holds a Unicode, non-blank one.
|
||||
fn logon_name(var: impl Fn(&str) -> Option<OsString>) -> Option<String> {
|
||||
LOGON_VARS.iter().find_map(|name| Some(var(name)?.into_string().ok()?.trim().to_owned()).filter(|v| !v.is_empty()))
|
||||
}
|
||||
|
||||
/// The account's name from the Windows Runtime ([`account_name`]), bounded by [`ask_with_timeout`].
|
||||
/// `None` when there is none, or on any failure (logged).
|
||||
#[cfg(target_os = "windows")]
|
||||
fn windows_account_name() -> Option<String> {
|
||||
ask_with_timeout("account lookup", || match account_name() {
|
||||
Ok(name) => Some(name).filter(|n| !n.trim().is_empty()),
|
||||
Err(e) => {
|
||||
log::debug!("user name: account lookup failed: {e}");
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// `ask`'s answer, asked on a thread of its own so a host lookup that never answers can't hold up
|
||||
/// opening the window: `what` names it in the log, [`LOOKUP_TIMEOUT`] bounds the wait. A lookup
|
||||
/// still running when the timeout passes carries on and finishes on its own, its own thread
|
||||
/// waiting for it (so an `id -F` child is still waited for and reaped); the start doesn't.
|
||||
#[cfg(any(target_os = "windows", target_os = "macos"))]
|
||||
fn ask_with_timeout(what: &str, ask: impl FnOnce() -> Option<String> + Send + 'static) -> Option<String> {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
if let Err(e) = std::thread::Builder::new().name("user-name".into()).spawn(move || {
|
||||
let _ = tx.send(ask());
|
||||
}) {
|
||||
log::debug!("user name: no {what} thread: {e}");
|
||||
return None;
|
||||
}
|
||||
match rx.recv_timeout(LOOKUP_TIMEOUT) {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => {
|
||||
log::debug!("user name: {what} gave no answer within {LOOKUP_TIMEOUT:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The account's name ([`chosen`] from its first, last and display names). Empty when the account
|
||||
/// has none of them.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn account_name() -> windows::core::Result<String> {
|
||||
use windows::System::{KnownUserProperties, User};
|
||||
// Only `GetDefault` names an account here: it names the account this process runs as. There is
|
||||
// deliberately no fallback to `FindAllAsync`, which enumerates the session's users: a sole
|
||||
// session user is not established to be the process's account (the review threads on this
|
||||
// change), so when `GetDefault` errors the account has no name from us and the logon name
|
||||
// follows, rather than a guess at whose name this is.
|
||||
let user = User::GetDefault().inspect_err(|e| log::debug!("user name: no default account: {e}"))?;
|
||||
let first = user_property(&user, "first name", KnownUserProperties::FirstName);
|
||||
let last = user_property(&user, "last name", KnownUserProperties::LastName);
|
||||
Ok(chosen(&first, &last, || user_property(&user, "display name", KnownUserProperties::DisplayName)).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// One of `user`'s text properties (`what` names it in the log); empty when the account doesn't
|
||||
/// have it, or when the lookup fails (logged), so the next source is still tried.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn user_property(user: &windows::System::User, what: &str, name: fn() -> windows::core::Result<windows::core::HSTRING>) -> String {
|
||||
use windows::Foundation::IReference;
|
||||
use windows::core::{HSTRING, Interface};
|
||||
let read = || -> windows::core::Result<String> {
|
||||
let value = user.GetPropertyAsync(&name()?)?.join()?;
|
||||
Ok(value.cast::<IReference<HSTRING>>()?.Value()?.to_string())
|
||||
};
|
||||
read().unwrap_or_else(|e| {
|
||||
log::debug!("user name: account {what}: {e}");
|
||||
String::new()
|
||||
})
|
||||
}
|
||||
|
||||
/// Which of the account's names is the user name: its first and last name ([`joined`]), else its
|
||||
/// display name (asked only then) — Windows has a display name only for a domain or work account,
|
||||
/// a first and last name for any account. `None` when all are blank.
|
||||
#[cfg(any(test, target_os = "windows"))]
|
||||
fn chosen(first: &str, last: &str, display: impl FnOnce() -> String) -> Option<String> {
|
||||
joined(first, last).or_else(|| Some(display().trim().to_owned()).filter(|n| !n.is_empty()))
|
||||
}
|
||||
|
||||
/// A first and a last name as one name (`Ada` + `Lovelace` → `Ada Lovelace`), either alone when
|
||||
/// the other is blank; `None` when both are.
|
||||
#[cfg(any(test, target_os = "windows"))]
|
||||
fn joined(first: &str, last: &str) -> Option<String> {
|
||||
let name = [first.trim(), last.trim()].into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join(" ");
|
||||
Some(name).filter(|n| !n.is_empty())
|
||||
}
|
||||
|
||||
/// The running account's full name in `/etc/passwd` ([`full_name`]), in the line whose uid field is
|
||||
/// the one the kernel gives for this process; `None` when the file can't be read or has no line for
|
||||
/// it. The uid comes from the system rather than from the environment or from procfs ownership: a
|
||||
/// logon name can say anything, and a non-dumpable process's `/proc/self` reads as root (proc(5)).
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
fn passwd_full_name() -> Option<String> {
|
||||
use std::io::Read;
|
||||
let uid = rustix::process::getuid().as_raw().to_string();
|
||||
let mut passwd = Vec::new();
|
||||
match std::fs::File::open("/etc/passwd").and_then(|f| f.take(MAX_PASSWD_BYTES).read_to_end(&mut passwd)) {
|
||||
Ok(_) => full_name(&passwd, &uid),
|
||||
Err(e) => {
|
||||
log::debug!("user name: /etc/passwd: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The full name in the entry of a `passwd` file (`name:password:UID:GID:GECOS:home:shell` lines)
|
||||
/// whose uid field reads exactly `uid`, as the system's own lookup reads it. The name is the
|
||||
/// GECOS field up to its first comma (the rest is office and phone numbers), with `&` standing for
|
||||
/// the entry's name capitalised, a BSD convention. `None` without an entry, with a full name that
|
||||
/// has nothing any cleaning could keep (empty, blanks, control characters), or with a *name* that
|
||||
/// isn't UTF-8: the office and phone fields behind the first comma are never read, so a Latin-1 in
|
||||
/// one of them keeps nothing.
|
||||
#[cfg(any(test, all(unix, not(target_os = "macos"), not(target_arch = "wasm32"))))]
|
||||
fn full_name(passwd: &[u8], uid: &str) -> Option<String> {
|
||||
// As `getpwuid` reads the file: a line whose first character that is neither a space nor a tab is
|
||||
// `#` is a comment in the file, not an account, so it is skipped rather than matched. A
|
||||
// commented-out `#ada:x:1000:...` would otherwise answer for uid 1000 and outrank the live
|
||||
// `ada:x:1000:...` line below it, indented just as much, since the uid is still its third field.
|
||||
let is_comment = |line: &[u8]| matches!(line.iter().find(|b| !matches!(**b, b' ' | b'\t')), Some(&b'#'));
|
||||
let entries: Vec<Vec<&[u8]>> =
|
||||
passwd.split(|&b| b == b'\n').filter(|line| !is_comment(line)).map(|line| line.split(|&b| b == b':').collect()).collect();
|
||||
// Our own entry, and only ours. The entry named by the logon name is not a candidate: an
|
||||
// account from a directory service has no line in this file under its uid or its name, so a
|
||||
// match by name can only ever land on somebody else's local entry - and a full name is
|
||||
// somebody's, so guessing wrong signs their work. The uid is matched whole, not as a prefix, so
|
||||
// `100` never takes `1000`'s entry, and the first line with our uid is the one, as `getpwuid`.
|
||||
let entry = entries.iter().find(|fields| fields.get(2) == Some(&uid.as_bytes()))?;
|
||||
let account = std::str::from_utf8(entry.first()?).ok()?;
|
||||
// Only the part of GECOS before the first comma has to be UTF-8. The office and phone fields
|
||||
// behind it are never read, and a Latin-1 in one of them must not cost the person their name.
|
||||
let gecos = entry.get(4)?;
|
||||
let name = match gecos.iter().position(|&b| b == b',') {
|
||||
Some(comma) => &gecos[..comma],
|
||||
None => gecos,
|
||||
};
|
||||
let name = std::str::from_utf8(name).ok()?;
|
||||
let name = if name.contains('&') { name.replace('&', &capitalised(account)) } else { name.to_owned() };
|
||||
// A full name with nothing in it that a cleaning could keep - blanks, control characters - is no
|
||||
// name at all: `None` lets the logon name have its turn, rather than one stray control character
|
||||
// in the GECOS field leaving the person with the placeholder. The name itself is handed on as it
|
||||
// stands, each app cleaning a name the same way it cleans one typed in.
|
||||
let nothing_left = name.chars().filter(|c| !c.is_control()).collect::<String>().trim().is_empty();
|
||||
(!nothing_left).then(|| name.trim().to_owned())
|
||||
}
|
||||
|
||||
/// The macOS account's full name, from the system's own Directory Services lookup (`id -F`, which
|
||||
/// prints the login name when the account has no real name), bounded by [`ask_with_timeout`] so the
|
||||
/// window never waits on it; `None` when it fails.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn directory_services_full_name() -> Option<String> {
|
||||
ask_with_timeout("id -F", lookup_id_dash_f)
|
||||
}
|
||||
|
||||
/// Wait for `child` until `deadline`; `None` if it has not answered by then, in which case it is
|
||||
/// stopped and waited for, so a lookup that never finishes leaves no process behind for the next
|
||||
/// start to add to. `what` names it in the log. Split out from the `id -F` lookup because a test
|
||||
/// cannot make Directory Services unresponsive, but it can hand a wait like this a child that never
|
||||
/// ends, which is what `a_child_that_never_answers_is_stopped_at_its_deadline` does.
|
||||
#[cfg(any(target_os = "macos", all(test, unix)))]
|
||||
fn wait_with_deadline(mut child: std::process::Child, deadline: std::time::Instant, what: &str) -> Option<std::process::ExitStatus> {
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => return Some(status),
|
||||
Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(10)),
|
||||
Ok(None) => {
|
||||
log::debug!("user name: {what} gave no answer within {LOOKUP_TIMEOUT:?}");
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
Err(e) => {
|
||||
log::debug!("user name: {what}: {e}");
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The most of a lookup's output read: a name is far shorter, so an answer this long is not one.
|
||||
#[cfg(any(target_os = "macos", all(test, unix)))]
|
||||
const MAX_ANSWER_BYTES: u64 = 4096;
|
||||
|
||||
/// The system's own `id -F`, run as `/usr/bin/id`: a GNU coreutils `id` earlier in `PATH`, easy to
|
||||
/// have on a Mac with coreutils installed, has no `-F` and would only print an error.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn lookup_id_dash_f() -> Option<String> {
|
||||
let mut command = std::process::Command::new("/usr/bin/id");
|
||||
command.arg("-F");
|
||||
answer_of(command, "id -F")
|
||||
}
|
||||
|
||||
/// What `command` prints, trimmed, when it succeeds within [`LOOKUP_TIMEOUT`] with a non-empty
|
||||
/// answer of at most [`MAX_ANSWER_BYTES`]; `None` otherwise (`what` names it in the log). Its
|
||||
/// output is read while it runs, not after: a child whose answer fills the pipe would otherwise
|
||||
/// stall writing it until the deadline. The read stops at the cap and closes the pipe, so a child
|
||||
/// that keeps writing is ended by the broken pipe; one that never answers is stopped at the
|
||||
/// deadline ([`wait_with_deadline`]), which closes the pipe and ends the read too.
|
||||
#[cfg(any(target_os = "macos", all(test, unix)))]
|
||||
fn answer_of(mut command: std::process::Command, what: &str) -> Option<String> {
|
||||
use std::io::Read;
|
||||
use std::process::Stdio;
|
||||
let mut child = match command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn() {
|
||||
Ok(child) => child,
|
||||
Err(e) => {
|
||||
log::debug!("user name: {what}: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let deadline = std::time::Instant::now() + LOOKUP_TIMEOUT;
|
||||
let out = child.stdout.take()?;
|
||||
let reader = std::thread::spawn(move || {
|
||||
let mut answer = Vec::new();
|
||||
out.take(MAX_ANSWER_BYTES + 1).read_to_end(&mut answer).map(|_| answer)
|
||||
});
|
||||
let status = wait_with_deadline(child, deadline, what)?;
|
||||
let Ok(Ok(answer)) = reader.join() else { return None };
|
||||
if !status.success() {
|
||||
log::debug!("user name: {what} failed: {status}");
|
||||
return None;
|
||||
}
|
||||
if answer.len() as u64 > MAX_ANSWER_BYTES {
|
||||
log::debug!("user name: {what} answered with more than {MAX_ANSWER_BYTES} bytes");
|
||||
return None;
|
||||
}
|
||||
Some(String::from_utf8(answer).ok()?.trim().to_owned()).filter(|n| !n.is_empty())
|
||||
}
|
||||
|
||||
/// `word` with its first letter upper case (`ada` → `Ada`).
|
||||
#[cfg(any(test, all(unix, not(target_os = "macos"))))]
|
||||
fn capitalised(word: &str) -> String {
|
||||
let mut chars = word.chars();
|
||||
chars.next().map(|first| first.to_uppercase().chain(chars).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "user_name_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,158 @@
|
||||
//! The shapes [`crate::user_name`] accepts and rejects: the GECOS forms of a `/etc/passwd` entry,
|
||||
//! the logon-name variables, and the names the Windows Runtime returns. The file is a synthetic
|
||||
//! one; no real account or personal name is in it.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The deadline half of the macOS lookup, which is otherwise untestable: no test can make Directory
|
||||
/// Services unresponsive, so the child here is a `sleep` and the waiting code is the same. The wait
|
||||
/// must end at its deadline with the child stopped and reaped, not run to the child's own end.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_child_that_never_answers_is_stopped_at_its_deadline() {
|
||||
use std::process::Stdio;
|
||||
// `sleep` itself, not a shell standing in front of it: the process the check below looks for
|
||||
// has to be the one the wait is meant to stop.
|
||||
let Ok(child) = std::process::Command::new("sleep").arg("30").stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() else {
|
||||
return; // no `sleep` to time out on: the waiting code is not what changed
|
||||
};
|
||||
let started = std::time::Instant::now();
|
||||
let pid = child.id();
|
||||
let deadline = started + std::time::Duration::from_millis(200);
|
||||
assert!(wait_with_deadline(child, deadline, "sleep").is_none(), "the deadline ends the wait, not the child");
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "and it ends it at the deadline, not after the sleep: {:?}", started.elapsed());
|
||||
// Stopped *and* waited for: a child that was only killed would still be a process, and
|
||||
// `kill -0` finds zombies. So nothing is left for the next start to pile up behind.
|
||||
let still_there = std::process::Command::new("sh").arg("-c").arg(format!("kill -0 {pid}")).status().is_ok_and(|status| status.success());
|
||||
assert!(!still_there, "the child is reaped, not left running or waiting");
|
||||
}
|
||||
|
||||
/// The output half of the macOS lookup: an answer is read while the child runs, so one too long
|
||||
/// for a pipe neither stalls the child until the deadline nor passes for a name, while an ordinary
|
||||
/// one is the name.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn an_oversized_answer_is_no_name_and_does_not_wait_for_the_deadline() {
|
||||
let command = |program: &str, args: &[&str]| {
|
||||
let mut command = std::process::Command::new(program);
|
||||
command.args(args);
|
||||
command
|
||||
};
|
||||
assert_eq!(answer_of(command("echo", &[" Ada Lovelace "]), "echo").as_deref(), Some("Ada Lovelace"));
|
||||
// Endless output: more than the read takes and far more than a pipe holds.
|
||||
let started = std::time::Instant::now();
|
||||
assert_eq!(answer_of(command("yes", &["Ada Lovelace"]), "yes"), None, "an answer past the cap is not a name");
|
||||
assert!(started.elapsed() < LOOKUP_TIMEOUT, "the capped read ends the child before the deadline: {:?}", started.elapsed());
|
||||
}
|
||||
|
||||
const PASSWD: &[u8] = b"# local accounts\n\
|
||||
#ada:x:1000:1000:Older Ada,commented out:/home/not-ada:/bin/sh\n\
|
||||
\t#ada2:x:1000:1000:Older Ada,indented comment:/home/not-ada2:/bin/sh\n\
|
||||
root:x:0:0:root:/root:/bin/bash\n\
|
||||
ada:x:1000:1000:Ada Lovelace,Room 1,+44 20,,:/home/ada:/bin/zsh\n\
|
||||
anna:x:1001:1001:& Smith:/home/anna:/bin/sh\r\n\
|
||||
bob:x:1002:1002::/home/bob:/bin/sh\n\
|
||||
carl:x:1003:1003: ,office:/home/carl:/bin/sh\n\
|
||||
dee:x:1004:1004:Dee \xe9:/home/dee:/bin/sh\n\
|
||||
ren:x:1008:1008:Rene Dupont,Office \xe9:/home/ren:/bin/sh\n\
|
||||
eve:x:1005\n\
|
||||
zoe:x:1006:1006:Zo\xc3\xab Kowalska:/home/zoe:/bin/sh\n\
|
||||
zoe:x:1007:1007:Someone Else:/home/zoe2:/bin/sh\n\
|
||||
gus:x:1009:1009:\x07\x02:/home/gus:/bin/sh\n\
|
||||
+ldapuser::::::";
|
||||
|
||||
#[test]
|
||||
fn the_passwd_full_name_is_the_gecos_name_without_office_and_phones() {
|
||||
assert_eq!(full_name(PASSWD, "0").as_deref(), Some("root"));
|
||||
// The commented-out line above with the same uid is not an account, and is skipped as
|
||||
// `getpwuid` skips it; the real entry below is the one.
|
||||
assert_eq!(full_name(PASSWD, "1000").as_deref(), Some("Ada Lovelace"));
|
||||
// `&` is the entry's own name, capitalised; a Windows line ending is no part of the name.
|
||||
assert_eq!(full_name(PASSWD, "1001").as_deref(), Some("Anna Smith"));
|
||||
// The first line with our uid is the one, as `getpwuid` reads it.
|
||||
assert_eq!(full_name(PASSWD, "1006").as_deref(), Some("Zoë Kowalska"));
|
||||
assert_eq!(full_name(PASSWD, "1007").as_deref(), Some("Someone Else"));
|
||||
// A Latin-1 in the office field behind the name costs nothing: only the name half is read.
|
||||
assert_eq!(full_name(PASSWD, "1008").as_deref(), Some("Rene Dupont"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_usable_passwd_name_falls_back_to_the_logon_name() {
|
||||
for (uid, why) in [
|
||||
("1002", "an empty GECOS field"),
|
||||
("1003", "a full name of blanks"),
|
||||
("1004", "a full name that isn't UTF-8 (Latin-1)"),
|
||||
("1005", "a cut-off entry"),
|
||||
("1009", "a full name of control characters only"),
|
||||
("4242", "no line for our uid"),
|
||||
("", "the empty uid field of a NIS `+` line"),
|
||||
("100", "a prefix of another uid, not a whole match"),
|
||||
("ada", "a logon name is no uid, and the line named by it is somebody else's"),
|
||||
] {
|
||||
assert_eq!(full_name(PASSWD, uid), None, "{why} ({uid:?})");
|
||||
}
|
||||
assert_eq!(full_name(b"", "1000"), None, "an empty file");
|
||||
assert_eq!(full_name(b"ada:x:1000:1000:Ada Lovelace", "1000").as_deref(), Some("Ada Lovelace"), "no shell or home");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_logon_name_skips_blank_and_non_unicode_variables() {
|
||||
let env =
|
||||
|vars: &'static [(&'static str, &'static str)]| move |name: &str| vars.iter().find(|(k, _)| *k == name).map(|(_, v)| OsString::from(*v));
|
||||
let first = LOGON_VARS.first().copied().unwrap_or_default();
|
||||
assert_eq!(logon_name(env(&[])), None);
|
||||
assert_eq!(logon_name(|name| (name == first).then(|| OsString::from(" ada \t"))).as_deref(), Some("ada"));
|
||||
assert_eq!(logon_name(|name| (name == first).then(|| OsString::from(" \t "))), None);
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
assert_eq!(logon_name(env(&[("USER", "ada"), ("LOGNAME", "root")])).as_deref(), Some("ada"), "USER first");
|
||||
assert_eq!(logon_name(env(&[("USER", " "), ("LOGNAME", "ada")])).as_deref(), Some("ada"));
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let bad = |name: &str| match name {
|
||||
"USER" => Some(OsString::from_vec(b"caf\xe9".to_vec())),
|
||||
"LOGNAME" => Some(OsString::from("ada")),
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!(logon_name(bad).as_deref(), Some("ada"), "a name that isn't UTF-8 is skipped");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_first_and_last_name_join_into_one() {
|
||||
assert_eq!(joined("Ada", "Lovelace").as_deref(), Some("Ada Lovelace"));
|
||||
assert_eq!(joined(" Zoë ", "\tKowalska ").as_deref(), Some("Zoë Kowalska"));
|
||||
// Either alone is the name; with neither the display name is tried.
|
||||
assert_eq!(joined("Ada", "").as_deref(), Some("Ada"));
|
||||
assert_eq!(joined(" ", "Lovelace").as_deref(), Some("Lovelace"));
|
||||
assert_eq!(joined("", ""), None);
|
||||
assert_eq!(joined(" \t", " "), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_and_last_name_win_over_the_display_name() {
|
||||
let asked = std::cell::Cell::new(false);
|
||||
let display = |name: &'static str| {
|
||||
let asked = &asked;
|
||||
move || {
|
||||
asked.set(true);
|
||||
name.to_owned()
|
||||
}
|
||||
};
|
||||
assert_eq!(chosen("Ada", "Lovelace", display("Contoso Admin")).as_deref(), Some("Ada Lovelace"));
|
||||
assert!(!asked.get(), "the display name is asked only without a first or last name");
|
||||
assert_eq!(chosen("", "Lovelace", display("Contoso Admin")).as_deref(), Some("Lovelace"));
|
||||
// Without either (a domain account may have only a display name), the display name.
|
||||
assert_eq!(chosen(" ", "", display(" Ada Lovelace ")).as_deref(), Some("Ada Lovelace"));
|
||||
assert!(asked.get());
|
||||
assert_eq!(chosen("", "", display(" \t")), None, "no name at all: the logon name follows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capitalised_upper_cases_the_first_letter_only() {
|
||||
assert_eq!(capitalised("ada"), "Ada");
|
||||
assert_eq!(capitalised("éva"), "Éva");
|
||||
assert_eq!(capitalised("ß"), "SS");
|
||||
assert_eq!(capitalised(""), "");
|
||||
}
|
||||
@@ -152,3 +152,6 @@ sync_github_name = true
|
||||
real_name = "Bryton Cooper"
|
||||
display_name = "Bryton Cooper"
|
||||
sync_github_name = true
|
||||
|
||||
[people.johanneswilm]
|
||||
real_name = "Johannes Wilm"
|
||||
|
||||
@@ -6,6 +6,14 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Document, NodeId};
|
||||
|
||||
/// Whether `name` (a message's author or an @mentioned name) is `user`, counting `legacy_user` as
|
||||
/// `user` too: the old default name the local person may have written under before their real name
|
||||
/// replaced it. For views only (Mine): a file can't say which "You" wrote a message, so the alias
|
||||
/// never grants a change.
|
||||
pub fn is_user(name: &str, user: &str, legacy_user: Option<&str>) -> bool {
|
||||
name == user || legacy_user == Some(name)
|
||||
}
|
||||
|
||||
/// An emoji reaction on a message and who left it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Reaction {
|
||||
@@ -148,7 +156,14 @@ impl Comment {
|
||||
|
||||
/// `user` wrote in the thread or is @mentioned in it.
|
||||
pub fn involves(&self, user: &str) -> bool {
|
||||
self.messages().any(|m| m.author == user || !mention_ranges(&m.text, &[user]).is_empty())
|
||||
self.involves_as(user, None)
|
||||
}
|
||||
|
||||
/// [`Self::involves`], with `legacy_user` counting as `user` too ([`is_user`]), as an author and
|
||||
/// as an @mention.
|
||||
pub fn involves_as(&self, user: &str, legacy_user: Option<&str>) -> bool {
|
||||
let names: Vec<&str> = std::iter::once(user).chain(legacy_user).collect();
|
||||
self.messages().any(|m| is_user(&m.author, user, legacy_user) || !mention_ranges(&m.text, &names).is_empty())
|
||||
}
|
||||
|
||||
/// The thread has something `user` hasn't read.
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
//! Messages are addressed by `reply` (an index into the replies; omitted: the thread's first
|
||||
//! message). `author` is who is acting (default: the AI agent the command runs for, else the name
|
||||
//! from Preferences, `pref.userName`): only a message's author edits or deletes it, and only the
|
||||
//! thread's author deletes the thread.
|
||||
//! thread's author deletes the thread. A thread signed or @mentioning the old default `You` still
|
||||
//! shows as Mine after the local person's real name arrives; editing or deleting it takes the name
|
||||
//! it was signed with, since a file can't say which `You` wrote it.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
@@ -99,12 +101,12 @@ impl Filter {
|
||||
Self::ALL.into_iter().find(|f| f.id().eq_ignore_ascii_case(s.trim()))
|
||||
}
|
||||
|
||||
pub fn keeps(self, c: &Comment, user: &str) -> bool {
|
||||
pub fn keeps(self, c: &Comment, user: &str, legacy_user: Option<&str>) -> bool {
|
||||
match self {
|
||||
Filter::All => true,
|
||||
Filter::Open => !c.resolved,
|
||||
Filter::Resolved => c.resolved,
|
||||
Filter::Mine => c.involves(user),
|
||||
Filter::Mine => c.involves_as(user, legacy_user),
|
||||
Filter::Unread => c.is_unread(user),
|
||||
}
|
||||
}
|
||||
@@ -161,15 +163,16 @@ impl Default for Query<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The comments `q` asks for, as `user` sees them, in order.
|
||||
pub fn query<'a>(doc: &'a Document, q: &Query, user: &str) -> Vec<&'a Comment> {
|
||||
/// The comments `q` asks for, as `user` sees them, in order. `legacy_user` is an old placeholder
|
||||
/// name (the default author) that still counts as `user` after a real name replaces it.
|
||||
pub fn query<'a>(doc: &'a Document, q: &Query, user: &str, legacy_user: Option<&str>) -> Vec<&'a Comment> {
|
||||
let needle = q.text.trim().to_lowercase();
|
||||
let mut out: Vec<&Comment> = doc
|
||||
.comments
|
||||
.iter()
|
||||
.filter(|c| doc.pages.contains(&c.page))
|
||||
.filter(|c| q.page.is_none_or(|p| c.page == p))
|
||||
.filter(|c| q.filter.keeps(c, user))
|
||||
.filter(|c| q.filter.keeps(c, user, legacy_user))
|
||||
.filter(|c| q.frame.is_none_or(|f| frame_of(doc, c) == Some(f)))
|
||||
.filter(|c| needle.is_empty() || matches_text(doc, c, &needle))
|
||||
.collect();
|
||||
@@ -290,6 +293,18 @@ fn author(s: &Session, p: &Value) -> String {
|
||||
string(p, "author").map(|a| a.trim().to_string()).filter(|a| !a.is_empty()).unwrap_or_else(|| acting_name(s))
|
||||
}
|
||||
|
||||
/// The old default author, when it may still name `who` in this session: `who` is the local person
|
||||
/// (not an AI agent acting for them) whose profile signed as `You` until a real name replaced it
|
||||
/// (`Prefs::was_default_name`). A profile that always had a name, other people and agents get none.
|
||||
///
|
||||
/// Views only: threads signed or @mentioning `You` stay in Mine (so their pins drag like the
|
||||
/// person's own, which grants nothing: `comment.move` checks no author), and `@You` reports `you`.
|
||||
/// A file can't say which `You` wrote a message, so the alias never lets anyone edit, delete, react
|
||||
/// or mark read under it; those act under the name they are given.
|
||||
pub fn legacy_default(s: &Session, who: &str) -> Option<&'static str> {
|
||||
(s.prefs.was_default_name && s.agent.is_none() && who == user_name(s) && who != DEFAULT_AUTHOR).then_some(DEFAULT_AUTHOR)
|
||||
}
|
||||
|
||||
/// A new message by `who`, marked as an agent's when the command runs for one.
|
||||
fn new_message(s: &Session, who: String, text: String) -> Message {
|
||||
Message { agent: s.agent.is_some(), ..Message::new(who, text, now_secs()) }
|
||||
@@ -371,16 +386,21 @@ fn listed<'s>(cmd: &str, s: &'s Session, p: &Value, who: &str, people: &[&str])
|
||||
let (page, filter, sort, text) = list_params(cmd, s, p)?;
|
||||
let want = mentions_param(cmd, p)?;
|
||||
let q = Query { page, frame: id(p, "frame"), filter, sort, text: &text };
|
||||
Ok(query(s.doc()?, &q, who).into_iter().filter(|c| want.as_deref().is_none_or(|w| thread_mentions(c, people, w))).collect())
|
||||
Ok(query(s.doc()?, &q, who, legacy_default(s, who))
|
||||
.into_iter()
|
||||
.filter(|c| want.as_deref().is_none_or(|w| thread_mentions(c, people, w)))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Add the names `text` @mentions to `named` as `{name, known, you}`, each once.
|
||||
fn push_mentions(named: &mut Vec<Value>, text: &str, people: &[&str], user: &str) {
|
||||
/// Add the names `text` @mentions to `named` as `{name, known, you}`, each once; `you` counts
|
||||
/// `legacy_user` ([`legacy_default`]) as `user` too.
|
||||
fn push_mentions(named: &mut Vec<Value>, text: &str, people: &[&str], user: &str, legacy_user: Option<&str>) {
|
||||
// `known` and `you` follow from the name, so the name alone tells a repeat.
|
||||
let mut seen: std::collections::BTreeSet<String> = named.iter().filter_map(|v| v.get("name")?.as_str().map(str::to_string)).collect();
|
||||
for (name, known) in mentioned(text, people) {
|
||||
if seen.insert(name.to_string()) {
|
||||
named.push(json!({"name": name, "known": known, "you": known && name.eq_ignore_ascii_case(user)}));
|
||||
let you = [Some(user), legacy_user].into_iter().flatten().any(|u| name.eq_ignore_ascii_case(u));
|
||||
named.push(json!({"name": name, "known": known, "you": known && you}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -411,9 +431,9 @@ fn people_and_mentioned(doc: &Document, you: &str) -> Vec<String> {
|
||||
|
||||
/// A message as JSON, with the names it @mentions: `{name, known, you}` each, resolved against
|
||||
/// `people` (`mentionable`); `known: false` is a name nobody in the file has.
|
||||
fn message_json(m: &Message, people: &[&str], user: &str) -> Value {
|
||||
fn message_json(m: &Message, people: &[&str], user: &str, legacy_user: Option<&str>) -> Value {
|
||||
let mut named: Vec<Value> = Vec::new();
|
||||
push_mentions(&mut named, &m.text, people, user);
|
||||
push_mentions(&mut named, &m.text, people, user, legacy_user);
|
||||
json!({
|
||||
"author": m.author, "agent": m.agent, "text": m.text, "created": m.created, "edited": m.edited,
|
||||
"reactions": m.reactions.iter().map(|r| json!({"emoji": r.emoji, "users": r.users})).collect::<Vec<_>>(),
|
||||
@@ -423,16 +443,16 @@ fn message_json(m: &Message, people: &[&str], user: &str) -> Value {
|
||||
|
||||
/// JSON view of a comment as `user` sees it: its page position, frame, read state and link, the
|
||||
/// first message's fields, and the replies; mentions resolve against `people` (`mentionable`).
|
||||
pub fn comment_json(doc: &Document, c: &Comment, user: &str, people: &[&str]) -> Value {
|
||||
pub fn comment_json(doc: &Document, c: &Comment, user: &str, people: &[&str], legacy_user: Option<&str>) -> Value {
|
||||
let (x, y) = c.position(doc);
|
||||
let frame = frame_of(doc, c);
|
||||
let mut v = message_json(&c.first, people, user);
|
||||
let mut v = message_json(&c.first, people, user, legacy_user);
|
||||
let extra = json!({
|
||||
"id": c.id, "page": c.page, "pageName": doc.node(c.page).map(|n| n.name.as_str()),
|
||||
"x": x, "y": y, "anchor": c.anchor,
|
||||
"frame": frame, "frameName": frame.and_then(|f| doc.node(f)).map(|n| n.name.as_str()),
|
||||
"resolved": c.resolved, "unread": c.is_unread(user), "link": link(c.id),
|
||||
"replies": c.replies.iter().map(|m| message_json(m, people, user)).collect::<Vec<_>>(),
|
||||
"replies": c.replies.iter().map(|m| message_json(m, people, user, legacy_user)).collect::<Vec<_>>(),
|
||||
});
|
||||
if let (Some(m), Value::Object(e)) = (v.as_object_mut(), extra) {
|
||||
m.extend(e);
|
||||
@@ -442,13 +462,13 @@ pub fn comment_json(doc: &Document, c: &Comment, user: &str, people: &[&str]) ->
|
||||
|
||||
/// Bounded metadata for `comment.prompt`'s `comments` list. Full messages and replies stay in
|
||||
/// `comment.list`; a prompt over thousands of threads must not repeat all of them here.
|
||||
fn comment_brief_json(doc: &Document, c: &Comment, user: &str, people: &[&str]) -> Value {
|
||||
fn comment_brief_json(doc: &Document, c: &Comment, user: &str, people: &[&str], legacy_user: Option<&str>) -> Value {
|
||||
let (x, y) = c.position(doc);
|
||||
let frame = frame_of(doc, c);
|
||||
// The names the whole thread @mentions, as `comment.list` reports them per message.
|
||||
let mut named = Vec::new();
|
||||
for m in c.messages() {
|
||||
push_mentions(&mut named, &m.text, people, user);
|
||||
push_mentions(&mut named, &m.text, people, user, legacy_user);
|
||||
if named.len() >= PROMPT_MAX_MENTIONS {
|
||||
break;
|
||||
}
|
||||
@@ -503,6 +523,7 @@ fn reveal(s: &mut Session, id: u64, how: &str) -> crate::Result<()> {
|
||||
|
||||
/// Reveal a thread (`how`: fit, center or keep), mark it read for `who` and ask the UI to open it.
|
||||
fn open(s: &mut Session, id: u64, how: &str, who: &str) -> crate::Result<Value> {
|
||||
let legacy = legacy_default(s, who);
|
||||
reveal(s, id, how)?;
|
||||
if s.doc()?.comment(id).is_some_and(|c| c.is_unread(who))
|
||||
&& let Some(c) = s.doc_mut()?.comment_mut(id)
|
||||
@@ -513,7 +534,7 @@ fn open(s: &mut Session, id: u64, how: &str, who: &str) -> crate::Result<Value>
|
||||
let doc = s.doc()?;
|
||||
let c = doc.comment(id).ok_or_else(|| bad("comment.open", "no comment"))?;
|
||||
let people = doc.comment_people();
|
||||
Ok(comment_json(doc, c, who, &mentionable(&people, who)))
|
||||
Ok(comment_json(doc, c, who, &mentionable(&people, who), legacy))
|
||||
}
|
||||
|
||||
/// A list's page (None: every page), filter, sort and search text from params.
|
||||
@@ -904,8 +925,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let who = author(s, p);
|
||||
let people = doc.comment_people();
|
||||
let people = mentionable(&people, &who);
|
||||
let legacy = legacy_default(s, &who);
|
||||
let list: Vec<Value> =
|
||||
listed("comment.list", s, p, &who, &people)?.into_iter().map(|c| comment_json(doc, c, &who, &people)).collect();
|
||||
listed("comment.list", s, p, &who, &people)?.into_iter().map(|c| comment_json(doc, c, &who, &people, legacy)).collect();
|
||||
Ok(json!({"comments": list}))
|
||||
}
|
||||
),
|
||||
@@ -954,6 +976,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
Some(_) => return Err(bad("comment.prompt", "`ids` must be an array of comment ids")),
|
||||
};
|
||||
let who = acting_name(s);
|
||||
let legacy = legacy_default(s, &who);
|
||||
let selected: Vec<&Comment> = if let Some(ids) = ids {
|
||||
let mut out = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
@@ -962,13 +985,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
out
|
||||
} else {
|
||||
let search = string(p, "query").unwrap_or_default();
|
||||
query(doc, &Query { page, frame: None, filter, sort, text: &search }, &who)
|
||||
query(doc, &Query { page, frame: None, filter, sort, text: &search }, &who, legacy)
|
||||
};
|
||||
let count = selected.len();
|
||||
let (text, truncated) = prompt_text(doc, path.as_deref(), &selected);
|
||||
let people = doc.comment_people();
|
||||
let people = mentionable(&people, &who);
|
||||
let comments: Vec<Value> = selected.iter().take(PROMPT_MAX_THREADS).map(|c| comment_brief_json(doc, c, &who, &people)).collect();
|
||||
let comments: Vec<Value> =
|
||||
selected.iter().take(PROMPT_MAX_THREADS).map(|c| comment_brief_json(doc, c, &who, &people, legacy)).collect();
|
||||
Ok(json!({"count": count, "truncated": truncated, "text": text, "comments": comments}))
|
||||
}
|
||||
),
|
||||
|
||||
@@ -572,7 +572,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|s, p| {
|
||||
let name = req_string("pref.userName", p, "name")?;
|
||||
let name: String = name.trim().chars().filter(|c| !c.is_control()).take(crate::live::MAX_NAME).collect();
|
||||
let was_default = super::comment::user_name(s) == super::comment::DEFAULT_AUTHOR;
|
||||
s.prefs.user_name = if name.is_empty() { super::comment::DEFAULT_AUTHOR.into() } else { name };
|
||||
s.prefs.was_default_name |= was_default && s.prefs.user_name != super::comment::DEFAULT_AUTHOR;
|
||||
s.live_rename();
|
||||
Ok(json!({"name": s.prefs.user_name}))
|
||||
}
|
||||
|
||||
@@ -100,6 +100,72 @@ fn only_authors_edit_and_delete_their_messages() {
|
||||
assert_eq!(s.prefs.user_name, "You");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_renamed_person_sees_you_threads_as_mine_but_changes_nothing_under_you() {
|
||||
// A shared file's "You" messages may be anyone's: the file can't say which "You" wrote them.
|
||||
// Renaming from the default (the normal `pref.userName` path) keeps them in Mine, and nothing
|
||||
// more: edits, deletes, reactions and read marks act under the real name only.
|
||||
let mut s = Session::new();
|
||||
let c = add(&mut s, 0.0, 0.0, "First", "You");
|
||||
s.execute("comment.reply", &json!({"id": c, "text": "A reply"})).unwrap();
|
||||
s.execute("comment.react", &json!({"id": c, "emoji": "👍"})).unwrap();
|
||||
s.execute("pref.userName", &json!({"name": "Ada"})).unwrap();
|
||||
assert!(s.prefs.was_default_name);
|
||||
assert_eq!(list(&mut s, json!({"page": "all", "filter": "mine"})), vec![c], "still Mine");
|
||||
|
||||
assert!(s.execute("comment.edit", &json!({"id": c, "text": "No"})).is_err());
|
||||
assert!(s.execute("comment.edit", &json!({"id": c, "reply": 0, "text": "No"})).is_err());
|
||||
assert!(s.execute("comment.delete", &json!({"id": c, "reply": 0})).is_err());
|
||||
assert!(s.execute("comment.delete", &json!({"id": c})).is_err());
|
||||
assert_eq!(comment(&s, c).first.text, "First");
|
||||
|
||||
// A toggle adds Ada's reaction and leaves the one signed "You".
|
||||
assert_eq!(s.execute("comment.react", &json!({"id": c, "emoji": "👍"})).unwrap()["on"], true);
|
||||
assert_eq!(comment(&s, c).first.reactions[0].users, ["You", "Ada"]);
|
||||
// Marking unread for Ada leaves the "You" reader alone.
|
||||
s.execute("comment.markRead", &json!({"id": c})).unwrap();
|
||||
s.execute("comment.markRead", &json!({"id": c, "read": false})).unwrap();
|
||||
assert!(!comment(&s, c).is_unread("You"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thread_mentioning_you_stays_mine_after_the_rename() {
|
||||
let mut s = Session::new();
|
||||
let c = add(&mut s, 0.0, 0.0, "Can @You check this?", "Sam");
|
||||
s.execute("pref.userName", &json!({"name": "Ada"})).unwrap();
|
||||
assert_eq!(list(&mut s, json!({"page": "all", "filter": "mine"})), [c], "@You still names the renamed person");
|
||||
assert!(list(&mut s, json!({"page": "all", "filter": "mine", "author": "Lee"})).is_empty(), "nobody else is @You");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_at_you_mention_reports_the_renamed_person_as_you() {
|
||||
let mut s = Session::new();
|
||||
let c = add(&mut s, 0.0, 0.0, "Can @You check this?", "You");
|
||||
s.execute("pref.userName", &json!({"name": "Ada"})).unwrap();
|
||||
let listed = s.execute("comment.list", &json!({"page": "all"})).unwrap();
|
||||
assert_eq!(listed["comments"][0]["mentions"][0]["you"], true, "comment.list: @You is the renamed person");
|
||||
let prompt = s.execute("comment.prompt", &json!({"ids": [c]})).unwrap();
|
||||
assert_eq!(prompt["comments"][0]["mentions"][0]["you"], true, "comment.prompt: the same");
|
||||
let other = s.execute("comment.list", &json!({"page": "all", "author": "Lee"})).unwrap();
|
||||
assert_eq!(other["comments"][0]["mentions"][0]["you"], false, "nobody else is @You");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_that_always_had_a_name_has_no_claim_on_you_messages() {
|
||||
// Opening a shared file whose comments were signed with the default: someone who never signed
|
||||
// as "You" in this profile doesn't see them as theirs (nor edits or deletes them).
|
||||
let mut s = Session::new();
|
||||
let c = add(&mut s, 0.0, 0.0, "Can @You check this?", "You");
|
||||
s.prefs.user_name = "Grace".into();
|
||||
assert!(!s.prefs.was_default_name);
|
||||
assert!(list(&mut s, json!({"page": "all", "filter": "mine"})).is_empty(), "not Mine");
|
||||
assert!(s.execute("comment.edit", &json!({"id": c, "text": "No"})).is_err());
|
||||
assert!(s.execute("comment.delete", &json!({"id": c})).is_err());
|
||||
// A later rename keeps it that way: the profile still never was the default.
|
||||
s.execute("pref.userName", &json!({"name": "Grace Hopper"})).unwrap();
|
||||
assert!(s.execute("comment.edit", &json!({"id": c, "text": "No"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reactions_toggle_per_person() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -59,6 +59,11 @@ pub struct Prefs {
|
||||
pub language: String,
|
||||
/// The name comments are signed with (and whose comments count as yours).
|
||||
pub user_name: String,
|
||||
/// This profile signed as the default name ("You") before a real name replaced it, so messages,
|
||||
/// reads and reactions under the default are its own (`cmd::comment::legacy_default`). Off for a
|
||||
/// profile that never was the default, so a shared file's "You" messages aren't someone else's to
|
||||
/// edit.
|
||||
pub was_default_name: bool,
|
||||
/// Reduce motion: the interface's own animations are off (the system's setting turns them off
|
||||
/// too). Prototype transitions still play.
|
||||
pub reduce_motion: bool,
|
||||
@@ -203,6 +208,7 @@ impl Default for Prefs {
|
||||
pages_height: None,
|
||||
language: "system".into(),
|
||||
user_name: cmd::comment::DEFAULT_AUTHOR.into(),
|
||||
was_default_name: false,
|
||||
reduce_motion: false,
|
||||
nav_bar_auto_hide: false,
|
||||
ui_scale: 1.0,
|
||||
|
||||
@@ -232,8 +232,15 @@ struct Pin {
|
||||
}
|
||||
|
||||
impl Pin {
|
||||
fn of(c: &Comment, me: &str, at: Pos2) -> Self {
|
||||
Pin { id: c.id, author: c.first.author.clone(), resolved: c.resolved, unread: c.is_unread(me), mine: c.first.author == me, at }
|
||||
fn of(c: &Comment, me: &str, legacy_user: Option<&str>, at: Pos2) -> Self {
|
||||
Pin {
|
||||
id: c.id,
|
||||
author: c.first.author.clone(),
|
||||
resolved: c.resolved,
|
||||
unread: c.is_unread(me),
|
||||
mine: figcraft_doc::is_user(&c.first.author, me, legacy_user),
|
||||
at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,9 +249,10 @@ impl Pin {
|
||||
fn pins(app: &FigApp) -> Vec<Pin> {
|
||||
let Ok(ds) = app.session.ds() else { return Vec::new() };
|
||||
let me = me(app);
|
||||
let legacy = cc::legacy_default(&app.session, &me);
|
||||
let cu = &app.ui.comments;
|
||||
let q = Query { page: Some(ds.page), filter: cu.filter, ..Query::default() };
|
||||
let mut list = cc::query(&ds.doc, &q, &me);
|
||||
let mut list = cc::query(&ds.doc, &q, &me, legacy);
|
||||
list.reverse();
|
||||
if let Some(c) = cu.open.and_then(|o| ds.doc.comment(o)).filter(|c| c.page == ds.page && !list.iter().any(|x| x.id == c.id)) {
|
||||
list.push(c);
|
||||
@@ -260,7 +268,7 @@ fn pins(app: &FigApp) -> Vec<Pin> {
|
||||
app.to_screen(x, y)
|
||||
}
|
||||
};
|
||||
Pin::of(c, &me, at)
|
||||
Pin::of(c, &me, legacy, at)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1078,6 +1086,7 @@ pub fn panel(app: &mut FigApp, ui: &mut Ui) {
|
||||
let page = ds.page;
|
||||
let doc = ds.doc.clone();
|
||||
let me = me(app);
|
||||
let legacy = cc::legacy_default(&app.session, &me);
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(16.0);
|
||||
@@ -1136,7 +1145,7 @@ pub fn panel(app: &mut FigApp, ui: &mut Ui) {
|
||||
ui.add_space(8.0);
|
||||
let search = app.ui.comments.search.clone();
|
||||
let q = Query { page: None, frame: None, filter: app.ui.comments.filter, sort: app.ui.comments.sort, text: &search };
|
||||
let list = cc::query(&doc, &q, &me);
|
||||
let list = cc::query(&doc, &q, &me, legacy);
|
||||
if list.is_empty() {
|
||||
let (title, sub) = if doc.comments.iter().any(|c| doc.pages.contains(&c.page)) {
|
||||
(tr("No matching comments"), tr("Try another search or filter."))
|
||||
@@ -1230,16 +1239,17 @@ pub fn presenter(app: &mut FigApp, ctx: &egui::Context, frame: NodeId, place: cr
|
||||
let doc = ds.doc.clone();
|
||||
let Some(fb) = doc.world_bounds(frame) else { return };
|
||||
let me = me(app);
|
||||
let legacy = cc::legacy_default(&app.session, &me);
|
||||
let open = app.ui.comments.open;
|
||||
// The frame as designed maps onto the frame as presented.
|
||||
let to_screen = |(x, y): (f64, f64)| place.pt(place.page_min.0 + x - fb.x0, place.page_min.1 + y - fb.y0);
|
||||
let q = Query { frame: Some(frame), filter: app.ui.comments.filter, ..Query::default() };
|
||||
let mut list = cc::query(&doc, &q, &me);
|
||||
let mut list = cc::query(&doc, &q, &me, legacy);
|
||||
list.reverse();
|
||||
if let Some(c) = open.and_then(|o| doc.comment(o)).filter(|c| cc::frame_of(&doc, c) == Some(frame) && !list.iter().any(|x| x.id == c.id)) {
|
||||
list.push(c);
|
||||
}
|
||||
let pins: Vec<Pin> = list.iter().map(|c| Pin::of(c, &me, to_screen(c.position(&doc)))).filter(|p| clip.contains(p.at)).collect();
|
||||
let pins: Vec<Pin> = list.iter().map(|c| Pin::of(c, &me, legacy, to_screen(c.position(&doc)))).filter(|p| clip.contains(p.at)).collect();
|
||||
let mut clicked = None;
|
||||
for p in &pins {
|
||||
let r = pin_rect(p.at);
|
||||
|
||||
@@ -466,7 +466,12 @@ resuming with its offline edits, and leaving the session going back to snapshot
|
||||
coordinates on whatever page you look at and nothing is outlined.
|
||||
- Colours and names: the host hands out the first free colour of an eight-colour palette and
|
||||
"Guest N" to people without a name (Preferences ▸ Your name, `pref.userName`; also in the Share
|
||||
popover and the Join dialog). Changing it while in a session renames you there at once (a
|
||||
popover and the Join dialog; a desktop start arrives named unless you have set one, because it
|
||||
takes the system account's name into that preference). Clearing it goes back to "Guest N" as
|
||||
before, with one exception worth knowing: clearing is not a lasting choice - the next desktop
|
||||
start fills the name from the account again, so it stays cleared only for as long as that run
|
||||
lasts, or until a name of your own is set, which the start-up does not touch. Changing it while
|
||||
in a session renames you there at once (a
|
||||
`name` signal, sent again after a reconnect, whose hello has the old name); clearing it keeps
|
||||
the session's name until you join again. After a newcomer's `Welcome` the host sends it its own `PeerJoined`, which is how it
|
||||
learns its name and colour.
|
||||
|
||||
+9
-3
@@ -1705,9 +1705,15 @@ and read state are its own, it can edit and delete only its own messages, and it
|
||||
`"agent": true` in `comment.list` (the app shows an **Agent** label by the name); the user's name in
|
||||
Preferences is unchanged. It is set once per connection, so no command needs `author`; an `author`
|
||||
param still wins. In the app, comments act as the name from Preferences (`pref.userName {name}`,
|
||||
default "You"); only a message's author can edit or delete it. `@Name` in a message mentions
|
||||
someone (`comment.people` lists the names used in the file: everyone who wrote or reacted, and
|
||||
every name a message @mentions, once each in any case; and, as `you`, who is acting).
|
||||
default "You"); only a message's author can edit or delete it. A first desktop start takes the
|
||||
operating system account's name into that preference instead of "You"; the CLI, this server and a
|
||||
`--control` run never ask the account (a `--control` run keeps a name already saved in Preferences),
|
||||
so what an agent signs is the same on every machine. Threads signed or `@You`-mentioned from before a profile took a real
|
||||
name stay in that person's Mine filter (and `@You` reports `you`); a file can't say which "You"
|
||||
wrote a message, so editing, deleting, reacting and read marks still go by the name a message was
|
||||
signed with. `@Name` in a
|
||||
message mentions someone (`comment.people` lists the names used in the file: everyone who wrote or
|
||||
reacted, and every name a message @mentions, once each in any case; and, as `you`, who is acting).
|
||||
|
||||
Read state is kept per name: a new message is unread for everyone but its author;
|
||||
`comment.markRead {id? | link?, read?}` marks one thread (or, without `id`, all of them) read or
|
||||
|
||||
Reference in New Issue
Block a user