craft-cloud: cut-down contract plus ui pages

This commit is contained in:
William Dunn
2026-11-16 23:47:58 -05:00
parent 453b0da782
commit 8334fd3c83
26 changed files with 7848 additions and 0 deletions
+2
View File
@@ -55,6 +55,8 @@ craft-captions = { path = "crates/captions" }
craft-cfb = { path = "crates/cfb" }
craft-codepage = { path = "crates/codepage" }
craft-cms = { path = "crates/cms" }
craft-cloud = { path = "crates/cloud" }
craft-cloud-local = { path = "crates/cloud-local" }
craft-color = { path = "crates/color" }
craft-frame = { path = "crates/frame" }
craft-crs = { path = "crates/crs" }
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "craft-cloud-local"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
description = "A reference CloudBackend over a local folder, proving the contract needs no specific provider"
[lints]
workspace = true
[dependencies]
craft-cloud = { workspace = true }
craft-ui = { workspace = true, features = ["cloud"] }
[dev-dependencies]
tempfile = "3"
egui = { workspace = true }
+256
View File
@@ -0,0 +1,256 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
//! A reference [`CloudBackend`] that treats one folder on disk as the cloud.
//!
//! [`craft_ui::cloud::CloudBackend`] names a contract and nothing about who
//! answers it. This crate is the proof: a working implementation that reaches
//! no service, a vendor, or a personal repo anybody else has to trust. An app
//! wires [`LocalBackend`] the same way it would wire a provider's own client,
//! by calling [`craft_ui::cloud::CloudFiles::connect`]. Swapping one for the
//! other is the whole point; nothing above the [`CloudBackend`] seam can tell
//! the difference.
//!
//! What this is not: a sync engine, a sharing service, or a place to keep a
//! credential. A folder has no concept of another account, so
//! [`Job::SharedWithMe`] answers empty and [`Job::Conversation`] answers with
//! a [`Fault`], and [`Account::capabilities`] claims neither. Reporting a
//! capability this backend cannot honour would be the broken window the
//! contract's own docs warn about.
//!
//! Every job answers on its own [`std::thread`]. [`CloudBackend::submit`]
//! must return before the file is opened, let alone read, or a twenty
//! megabyte document would freeze the window that called it.
use std::fs;
use std::path::{Path, PathBuf};
use craft_cloud::{Capability, Entry, EntryKind};
use craft_ui::cloud::{Account, CloudBackend, Event, Fault, Job, Post};
/// Where "the cloud" lives for this backend: one directory on disk.
///
/// `Entry::id` and `Entry::path` are the same slash-separated path relative to
/// `root`, always starting with `/` below the root itself (the root's own
/// path is the empty string, matching [`Job::List`]'s contract). Neither is
/// an OS path; both go through [`resolve`] before anything touches a
/// filesystem, so a name containing `..` can never walk out of `root`.
pub struct LocalBackend {
root: PathBuf,
/// Shown in the account badge. Nothing else reads it.
display: String,
}
impl LocalBackend {
/// Treat `root` as the cloud. The directory is not created here; a
/// listing of a root that does not exist yet answers with a [`Fault`]
/// the same way a real provider's missing folder would.
pub fn new(root: PathBuf) -> LocalBackend {
LocalBackend { root, display: "Local disk".to_owned() }
}
/// Name shown in the account badge, in place of the default "Local disk".
pub fn named(mut self, display: impl Into<String>) -> LocalBackend {
self.display = display.into();
self
}
}
impl CloudBackend for LocalBackend {
fn submit(&self, job: Job, post: Post) {
let root = self.root.clone();
match job {
// Nothing is saved between runs and nothing was ever signed into,
// so there is nothing to forget. The trait states no answer for
// this job; CloudFiles::sign_out clears its own state regardless
// of whether anything ever arrives.
Job::SignOut => {}
Job::Account | Job::SignIn => {
let display = self.display.clone();
std::thread::spawn(move || post.send(Event::Account(Ok(account(display)))));
}
// There is no browser round trip: a local folder is already
// "linked" the moment it exists. Reporting that immediately,
// rather than inventing a URL nobody needs to visit, is what the
// contract calls honest.
Job::LinkStart | Job::LinkPoll(_) => {
std::thread::spawn(move || post.send(Event::Linked(Ok(true))));
}
Job::List(path) => {
std::thread::spawn(move || post.send(Event::Listed { entries: list(&root, &path), path }));
}
Job::SharedWithMe => {
std::thread::spawn(move || post.send(Event::Shared(Ok(Vec::new()))));
}
Job::Read { entry, into } => {
std::thread::spawn(move || {
let bytes = read(&root, &entry);
post.send(Event::Read { entry, into, bytes });
});
}
Job::Write { uid, entry, bytes } => {
std::thread::spawn(move || post.send(Event::Saved { uid, entry: write(&root, &entry, &bytes) }));
}
Job::Create { uid, folder, name, bytes } => {
std::thread::spawn(move || post.send(Event::Saved { uid, entry: create(&root, &folder, &name, &bytes) }));
}
// No sharing, no accounts beyond this one, and so nowhere for a
// conversation to live. A reference backend that invented one
// would be lying about what a folder on disk can do.
Job::Conversation(_) => {
std::thread::spawn(move || {
post.send(Event::Conversation(Err(Fault::Refused("this reference backend has no shared workspace to converse in".to_owned()))))
});
}
}
}
}
fn account(display: String) -> Account {
Account { display, capabilities: vec![Capability::Files, Capability::Etags], provider_linked: true }
}
/// Turns a [`Job`]'s slash-separated path into a real filesystem path under
/// `root`, refusing anything that would walk back out of it.
///
/// `..` is the only way out, so `..` is the only segment refused. `.` and
/// repeated or leading slashes are just an empty segment and are skipped,
/// the same way a browser's address bar collapses them.
fn resolve(root: &Path, path: &str) -> Result<PathBuf, Fault> {
let mut real = root.to_path_buf();
for segment in path.split('/') {
if segment.is_empty() || segment == "." {
continue;
}
if segment == ".." {
return Err(Fault::Refused(format!("{path} reaches outside this folder")));
}
real.push(segment);
}
Ok(real)
}
/// The path a listed child gets, given the folder it was found in.
fn child_path(folder: &str, name: &str) -> String {
format!("{}/{name}", folder.trim_end_matches('/'))
}
/// An opaque version token for a file's current bytes.
///
/// Not a timestamp for a person to read (that would go through `chrono`, per
/// this workspace's rule); just enough to tell "the file I read" from "the
/// file as it is now" apart, which is all a conditional write needs.
fn etag_of(meta: &fs::Metadata) -> String {
let stamp = meta.modified().ok().and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_nanos()).unwrap_or(0);
format!("{}-{stamp}", meta.len())
}
fn io_fault(error: &std::io::Error) -> Fault {
use std::io::ErrorKind;
match error.kind() {
ErrorKind::NotFound => Fault::Refused("no such file or folder".to_owned()),
ErrorKind::PermissionDenied => Fault::Refused("permission denied".to_owned()),
_ => Fault::Unreachable(error.to_string()),
}
}
fn list(root: &Path, path: &str) -> Result<Vec<Entry>, Fault> {
let dir = resolve(root, path)?;
let read = fs::read_dir(&dir).map_err(|error| io_fault(&error))?;
let mut entries = Vec::new();
for item in read {
let item = item.map_err(|error| io_fault(&error))?;
let meta = item.metadata().map_err(|error| io_fault(&error))?;
let name = item.file_name().to_string_lossy().into_owned();
let id = child_path(path, &name);
entries.push(Entry {
room: format!("local:{id}"),
name,
kind: if meta.is_dir() { EntryKind::Folder } else { EntryKind::File },
size: if meta.is_dir() { None } else { Some(meta.len()) },
modified: None,
mime: None,
etag: if meta.is_dir() { None } else { Some(etag_of(&meta)) },
writable: true,
shared_by: None,
path: id.clone(),
id,
});
}
entries.sort_by(|a, b| (a.kind != EntryKind::Folder, &a.name).cmp(&(b.kind != EntryKind::Folder, &b.name)));
Ok(entries)
}
fn read(root: &Path, entry: &Entry) -> Result<Vec<u8>, Fault> {
let file = resolve(root, &entry.id)?;
fs::read(&file).map_err(|error| io_fault(&error))
}
/// Saves back over `entry`, refusing the write when the file moved on since
/// `entry.etag` was read. A file that no longer exists has nothing to
/// conflict with, the same way a provider treats a deleted document.
fn write(root: &Path, entry: &Entry, bytes: &[u8]) -> Result<Entry, Fault> {
let file = resolve(root, &entry.id)?;
if let Ok(meta) = fs::metadata(&file) {
if Some(etag_of(&meta)) != entry.etag {
return Err(Fault::Conflict);
}
}
if let Some(parent) = file.parent() {
fs::create_dir_all(parent).map_err(|error| io_fault(&error))?;
}
fs::write(&file, bytes).map_err(|error| io_fault(&error))?;
let meta = fs::metadata(&file).map_err(|error| io_fault(&error))?;
Ok(Entry { size: Some(meta.len()), etag: Some(etag_of(&meta)), ..entry.clone() })
}
fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result<Entry, Fault> {
let dir = resolve(root, folder)?;
fs::create_dir_all(&dir).map_err(|error| io_fault(&error))?;
let file = dir.join(name);
if file.exists() {
return Err(Fault::Refused(format!("{name} already exists")));
}
fs::write(&file, bytes).map_err(|error| io_fault(&error))?;
let meta = fs::metadata(&file).map_err(|error| io_fault(&error))?;
let id = child_path(folder, name);
Ok(Entry {
room: format!("local:{id}"),
name: name.to_owned(),
kind: EntryKind::File,
size: Some(meta.len()),
modified: None,
mime: None,
etag: Some(etag_of(&meta)),
writable: true,
shared_by: None,
path: id.clone(),
id,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_parent_segment_cannot_walk_out_of_root() {
let root = PathBuf::from("/cloud/root");
assert!(resolve(&root, "../secrets").is_err());
assert!(resolve(&root, "Archive/../../../etc/passwd").is_err());
}
#[test]
fn repeated_and_trailing_slashes_collapse_like_a_browser_address_bar() {
let root = PathBuf::from("/cloud/root");
assert_eq!(resolve(&root, "//Archive//2026/").unwrap(), root.join("Archive").join("2026"));
assert_eq!(resolve(&root, "").unwrap(), root);
}
#[test]
fn a_folder_announces_no_capability_this_backend_cannot_honour() {
let reported = account("Local disk".to_owned()).capabilities;
for absent in [Capability::SharedWithMe, Capability::Sharing, Capability::Conversation, Capability::Contacts] {
assert!(!reported.contains(&absent), "a folder has no {absent:?}");
}
}
}
+241
View File
@@ -0,0 +1,241 @@
//! Drives [`craft_cloud_local::LocalBackend`] the way an app does: through
//! `craft_ui::cloud`'s own public functions, never by calling the backend
//! directly. That is the seam this crate exists to prove, so the tests stay
//! on the application's side of it.
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use craft_cloud::{Entry, EntryKind};
use craft_cloud_local::LocalBackend;
use craft_ui::cloud::{self, Account, CloudApp, CloudFiles, Destination, DocumentKind, Job};
const NOTE: DocumentKind = DocumentKind { extensions: &["txt"], mimes: &["text/plain"], noun: "note", default_extension: "txt" };
/// The least a [`CloudApp`] can be. What it was told to open is recorded, so a
/// round trip can be checked by content and not only by the entry metadata
/// `craft_ui` itself remembers.
struct Harness {
cloud: CloudFiles,
share: craft_ui::share::ShareDialog,
presence: craft_ui::presence::PresenceBar,
opened: Arc<Mutex<Vec<(String, Vec<u8>)>>>,
said: Arc<Mutex<Vec<String>>>,
}
impl Harness {
fn new() -> Harness {
Harness {
cloud: CloudFiles::new(),
share: craft_ui::share::ShareDialog::new(),
presence: craft_ui::presence::PresenceBar::new(),
opened: Arc::new(Mutex::new(Vec::new())),
said: Arc::new(Mutex::new(Vec::new())),
}
}
}
impl CloudApp for Harness {
fn cloud(&self) -> &CloudFiles {
&self.cloud
}
fn cloud_mut(&mut self) -> &mut CloudFiles {
&mut self.cloud
}
fn kind(&self) -> DocumentKind {
NOTE
}
fn active(&self) -> Option<u64> {
None
}
fn title(&self, _uid: u64) -> String {
String::new()
}
fn open_bytes(&mut self, name: &str, bytes: Vec<u8>) -> Result<Option<u64>, String> {
self.opened.lock().unwrap().push((name.to_owned(), bytes));
Ok(Some(1))
}
fn encode(&mut self, _uid: u64, _into: Destination<'_>) -> Result<Vec<u8>, String> {
Ok(Vec::new())
}
fn close(&mut self, _uid: u64) {}
fn sharing(&mut self) -> &mut craft_ui::share::ShareDialog {
&mut self.share
}
fn presence(&mut self) -> &mut craft_ui::presence::PresenceBar {
&mut self.presence
}
fn paint_icon(&self, _painter: &egui::Painter, _rect: egui::Rect, _kind: EntryKind, _colour: egui::Color32) {}
fn open_url(&self, _url: &str) {}
fn say(&mut self, text: String) {
self.said.lock().unwrap().push(text);
}
fn app_name(&self) -> &str {
"Harness"
}
}
fn wired(root: std::path::PathBuf) -> (Harness, egui::Context) {
let mut app = Harness::new();
app.cloud.connect(LocalBackend::new(root));
(app, egui::Context::default())
}
/// Drains whatever the backend's worker threads have sent so far, until
/// `done` says the state the test is waiting for arrived or five seconds pass.
/// Five seconds is far more than a thread doing local file IO ever needs; it
/// only guards against a real bug leaving the test to hang forever.
fn settle(app: &mut Harness, ctx: &egui::Context, mut done: impl FnMut(&Harness) -> bool) {
let start = Instant::now();
loop {
ctx.begin_pass(Default::default());
cloud::pump(app, ctx);
ctx.end_pass().textures_delta.clear();
if done(app) {
return;
}
assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for the backend's worker thread");
std::thread::sleep(Duration::from_millis(5));
}
}
#[test]
fn account_and_sign_in_report_the_same_fixed_identity_with_no_browser_round_trip() {
let dir = tempfile::tempdir().unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
cloud::start(&mut app);
settle(&mut app, &ctx, |app| app.cloud().account.is_some());
assert_eq!(
app.cloud().account,
Some(Account {
display: "Local disk".to_owned(),
capabilities: vec![craft_cloud::Capability::Files, craft_cloud::Capability::Etags],
provider_linked: true
})
);
// There was never an account to link, so nothing was ever offered.
assert!(app.cloud().link.is_none());
}
#[test]
fn creating_a_document_writes_real_bytes_a_read_gets_back() {
let dir = tempfile::tempdir().unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
cloud::submit(&app, Job::Create { uid: 1, folder: String::new(), name: "Minutes.txt".to_owned(), bytes: b"first draft".to_vec() });
settle(&mut app, &ctx, |app| app.cloud().origins.contains_key(&1));
let entry = app.cloud().origins.get(&1).unwrap().entry.clone();
assert_eq!(entry.name, "Minutes.txt");
assert_eq!(entry.id, "/Minutes.txt");
assert_eq!(fs_read(dir.path(), "Minutes.txt"), b"first draft");
cloud::submit(&app, Job::Read { entry, into: None });
settle(&mut app, &ctx, |app| !app.opened.lock().unwrap().is_empty());
let opened = app.opened.lock().unwrap().clone();
assert_eq!(opened, vec![("Minutes.txt".to_owned(), b"first draft".to_vec())], "the read got back exactly what the create wrote");
}
#[test]
fn a_write_under_a_stale_version_is_refused_and_never_overwrites_the_newer_file() {
let dir = tempfile::tempdir().unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
cloud::submit(&app, Job::Create { uid: 1, folder: String::new(), name: "Minutes.txt".to_owned(), bytes: b"v1".to_vec() });
settle(&mut app, &ctx, |app| app.cloud().origins.contains_key(&1));
let stale = app.cloud().origins.get(&1).unwrap().entry.clone();
// Somebody else saves first, changing the file's etag without going
// through this window at all.
std::fs::write(dir.path().join("Minutes.txt"), b"somebody else's edit").unwrap();
cloud::submit(&app, Job::Write { uid: 1, entry: stale, bytes: b"this window's edit".to_vec() });
settle(&mut app, &ctx, |app| app.cloud().conflict.is_some());
assert_eq!(app.cloud().conflict.as_ref().unwrap().uid, 1);
assert_eq!(fs_read(dir.path(), "Minutes.txt"), b"somebody else's edit", "the refused write never touched the file");
}
#[test]
fn listing_the_root_reflects_a_file_nobody_went_through_this_backend_to_write() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("Agenda.txt"), b"1. roll call").unwrap();
std::fs::create_dir(dir.path().join("Archive")).unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
cloud::browse(&mut app, "");
settle(&mut app, &ctx, |app| app.cloud().mine.loaded);
let names: Vec<_> = app.cloud().mine.entries.iter().map(|entry| entry.name.clone()).collect();
assert_eq!(names, vec!["Archive".to_owned(), "Agenda.txt".to_owned()], "folders first, then files, each alphabetised");
let folder = app.cloud().mine.entries.iter().find(|entry| entry.name == "Archive").unwrap();
assert_eq!(folder.kind, EntryKind::Folder);
assert!(folder.size.is_none());
}
#[test]
fn nobody_has_shared_anything_with_a_folder() {
let dir = tempfile::tempdir().unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
cloud::load_shared(&mut app);
settle(&mut app, &ctx, |app| app.cloud().shared.loaded);
assert_eq!(app.cloud().shared.entries, Vec::new());
assert!(app.cloud().shared.error.is_none(), "an empty share list is not a failure");
}
#[test]
fn a_conversation_is_a_fault_this_backend_is_honest_about() {
let dir = tempfile::tempdir().unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
cloud::submit(&app, Job::Conversation("/Minutes.txt".to_owned()));
settle(&mut app, &ctx, |app| app.cloud().status.is_some());
assert_eq!(app.cloud().status, Some("this reference backend has no shared workspace to converse in".to_owned()));
}
#[test]
fn a_read_of_a_document_that_is_not_there_is_put_to_the_user_not_silently_dropped() {
let dir = tempfile::tempdir().unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
let ghost = Entry {
id: "/ghost.txt".to_owned(),
room: "local:/ghost.txt".to_owned(),
name: "ghost.txt".to_owned(),
path: "/ghost.txt".to_owned(),
kind: EntryKind::File,
size: None,
modified: None,
mime: None,
etag: None,
writable: true,
shared_by: None,
};
cloud::submit(&app, Job::Read { entry: ghost, into: None });
settle(&mut app, &ctx, |app| !app.said.lock().unwrap().is_empty());
assert!(app.said.lock().unwrap()[0].contains("ghost.txt"), "the message names the document, not just that something failed");
}
fn fs_read(root: &std::path::Path, name: &str) -> Vec<u8> {
std::fs::read(root.join(name)).unwrap()
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "craft-cloud"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
description = "What a cloud provider offers the Craft apps: files, sharing, contacts, notifications and mail as contracts, with no vendor and no IO"
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
thiserror = { workspace = true }
+68
View File
@@ -0,0 +1,68 @@
//! One error type for every contract.
//!
//! The cases are the ones a caller acts on differently. A UI shows a different
//! thing for "you may not" than for "the server is unreachable", and a save
//! retries on a conflict where it would not on a refusal.
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
/// The provider could not be reached. Worth retrying.
#[error("the provider could not be reached: {0}")]
Unreachable(String),
/// The credential was rejected. The user has to sign in again.
#[error("the provider rejected the credential")]
Unauthenticated,
/// Authenticated, and not allowed to do this. Signing in again will not
/// help, so a UI must not offer it.
#[error("not permitted: {0}")]
Forbidden(String),
/// No such document, folder or share.
#[error("{what} not found: {id}")]
NotFound { what: &'static str, id: String },
/// The document changed since the caller last read it. A save that would
/// have overwritten somebody else's work lands here.
#[error("{0} changed since you opened it")]
Conflict(String),
/// The provider does not offer this at all.
///
/// Distinct from [`Error::Forbidden`]: there is nothing to grant. A UI
/// hides the feature rather than explaining it.
#[error("this provider does not support {0}")]
Unsupported(&'static str),
/// The answer did not match the protocol.
#[error("malformed {what}: {detail}")]
Malformed { what: &'static str, detail: String },
/// A name or path could not be used safely. Carried, never panicked.
#[error("invalid {what}: {detail}")]
Invalid { what: &'static str, detail: String },
}
impl Error {
pub fn not_found(what: &'static str, id: impl Into<String>) -> Error {
Error::NotFound { what, id: id.into() }
}
pub fn malformed(what: &'static str, detail: impl Into<String>) -> Error {
Error::Malformed { what, detail: detail.into() }
}
pub fn invalid(what: &'static str, detail: impl Into<String>) -> Error {
Error::Invalid { what, detail: detail.into() }
}
/// Whether trying again could succeed without the user doing anything.
pub fn is_transient(&self) -> bool {
matches!(self, Error::Unreachable(_))
}
}
pub type Result<T> = std::result::Result<T, Error>;
+189
View File
@@ -0,0 +1,189 @@
//! What a cloud provider has to offer the Craft apps, and nothing about who
//! provides it.
//!
//! Every capability here is an RFC or an ordinary HTTP API that many systems
//! implement. Files are WebDAV. Contacts are CardDAV. Calendars are CalDAV.
//! Sharing and notification are the only genuinely vendor-shaped parts, and
//! they are small. So there is no reason for an app to know which server it is
//! talking to, and no reason to write the same logic again for the next one.
//!
//! Nothing in this crate opens a socket. Each trait is implemented by a
//! provider crate that brings its own transport, which keeps this testable
//! with no server and keeps the contracts honest about what they need.
//!
//! No type here names a vendor. If a field only makes sense for one product,
//! it belongs in that provider's crate.
//!
//! Nothing here says where an implementation runs. A local adapter may
//! implement these traits against a provider directly, and an application may
//! consume them that way. The contracts do not care.
//!
//! CollabCraft chooses otherwise for its own apps. They reach one service, and
//! that service is the single place a provider is configured, a credential is
//! held and a permission is decided. A desktop binary carrying a provider
//! credential leaks one the moment somebody copies the file, which is what
//! that arrangement exists to prevent. It is a deployment policy, and this
//! crate imposes it on nobody.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod error;
mod types;
pub use error::{Error, Result};
pub use types::{
Capability, Contact, Conversation, Entry, EntryKind, Identity, MailMessage, Notification, Permission, Share, ShareOptions, ShareTarget,
};
/// Reading and writing documents.
///
/// `list` and `shared_with_me` are separate because they answer different
/// questions. One is a folder's contents, the other is everything another
/// person has given this user access to, which has no single parent folder.
pub trait Files {
/// One folder's contents. An empty path means the user's root.
fn list(&self, path: &str) -> Result<Vec<Entry>>;
/// Everything shared with this user, wherever it lives.
///
/// A provider with no concept of this returns an empty list rather than an
/// error, because "nobody has shared anything with you" and "this server
/// cannot tell you" look the same to a file picker.
fn shared_with_me(&self) -> Result<Vec<Entry>>;
/// One document's bytes.
fn read(&self, id: &str) -> Result<Vec<u8>>;
/// A byte range of one document.
///
/// Defaulted to a full [`read`] and a slice, so providers that have no
/// ranged GET still satisfy the trait. A provider with real range support
/// overrides this.
fn read_range(&self, id: &str, offset: u64, length: u64) -> Result<Vec<u8>> {
let bytes = self.read(id)?;
let start = usize::try_from(offset).unwrap_or(usize::MAX);
if start >= bytes.len() {
return Ok(Vec::new());
}
let take = usize::try_from(length).unwrap_or(usize::MAX);
let end = start.saturating_add(take).min(bytes.len());
Ok(bytes[start..end].to_vec())
}
/// Replace one document's bytes.
///
/// `if_match` carries the etag the caller last saw. A provider that
/// supports conditional writes uses it to refuse a save that would
/// overwrite somebody else's, returning [`Error::Conflict`]. Passing
/// `None` means "write regardless", which is what a Save As does.
fn write(&self, id: &str, bytes: &[u8], if_match: Option<&str>) -> Result<Entry>;
/// Create a document and return it.
fn create(&self, folder: &str, name: &str, bytes: &[u8]) -> Result<Entry>;
/// One document's metadata, without its bytes.
fn stat(&self, id: &str) -> Result<Entry>;
}
/// Giving other people access to a document.
///
/// Persisting a share through the provider matters more than it looks. A share
/// recorded only by the caller would be invisible in the provider's own file
/// manager, so the two would disagree about who can open what. The provider
/// stays the authority.
pub trait Sharing {
/// Share a document.
///
/// A link share has no recipient, so [`ShareTarget::Link`] is how a caller
/// asks for one. The returned [`Share::url`] is what to hand out.
fn share(&self, id: &str, with: &ShareTarget, permission: Permission, options: &ShareOptions) -> Result<Share>;
/// Who currently has access.
fn shares(&self, id: &str) -> Result<Vec<Share>>;
/// Withdraw one share.
fn unshare(&self, share_id: &str) -> Result<()>;
}
/// Looking people up, for a share dialog's autocomplete.
///
/// This is the only thing the share dialog needs, so it is the only thing the
/// contract exposes. A full address book API would be a bigger surface for no
/// gain.
pub trait Contacts {
/// People matching a partial name or address.
///
/// `limit` exists because this runs on every keystroke. A provider is free
/// to return fewer.
fn search(&self, query: &str, limit: usize) -> Result<Vec<Contact>>;
}
/// Telling somebody something happened.
///
/// Separate from [`Mail`] on purpose. An in-app notification is cheap, arrives
/// instantly and is read in context. An email is none of those and is the
/// right choice for somebody who is not currently in the app. A share usually
/// wants both.
pub trait Notifications {
fn notify(&self, user: &str, notification: &Notification) -> Result<()>;
}
/// Sending mail as the provider.
pub trait Mail {
fn send(&self, message: &MailMessage) -> Result<()>;
}
/// Who the caller is, according to the provider.
pub trait Accounts {
/// Resolve the signed-in user.
fn me(&self) -> Result<Identity>;
}
/// Working together on a document, through whatever the provider calls it.
///
/// Defaulted throughout. A provider without the feature writes an empty
/// `impl` and reports [`Capability::Conversation`] as absent. The caller
/// then draws no control at all.
pub trait Conversations {
/// What this provider calls the feature. `None` where it has none.
///
/// Separate from the capability on purpose. The name is a property of
/// the provider. Whether it is available is a property of the
/// instance, and an administrator decides that one.
fn conversation_name(&self) -> Option<String> {
None
}
/// Start a conversation about a document, or join the one already there.
///
/// Two people pressing the same control have to arrive in the same
/// place, so this is expected to be idempotent for a given document.
///
/// `id` is the provider's own handle and means nothing outside the
/// account it came from. A conversation is therefore keyed on the
/// provider, the account and the document together, and `self` carries
/// the first two. A document copied into another account is a different
/// document to its provider, so it gets a conversation of its own.
/// Nothing here can attach one account's thread to another's.
fn conversation(&self, _id: &str, _title: &str) -> Result<Conversation> {
Err(Error::Unsupported("conversations"))
}
}
/// Everything one provider can do.
///
/// A provider implements the capabilities it has and reports the rest as
/// absent, so a caller can hide a share button on a server with no sharing
/// rather than offering a feature that will fail.
pub trait Provider: Files + Sharing + Contacts + Notifications + Mail + Accounts + Conversations {
/// A stable identifier, such as `nextcloud`. Used in configuration and
/// logs, never shown to a user.
fn id(&self) -> &str;
/// What this provider actually supports.
fn capabilities(&self) -> Vec<Capability>;
fn supports(&self, capability: Capability) -> bool {
self.capabilities().contains(&capability)
}
}
+216
View File
@@ -0,0 +1,216 @@
//! The data the contracts pass around.
//!
//! Every type here is plain and vendor-neutral. A field that only means
//! something to one product belongs in that provider's crate.
use serde::{Deserialize, Serialize};
/// What a provider can do.
///
/// Reported rather than assumed, so a caller hides a share button on a
/// server without sharing instead of offering a feature that fails on use.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Capability {
Files,
SharedWithMe,
Sharing,
Contacts,
Notifications,
Mail,
/// Conditional writes, so a save can refuse to clobber a newer version.
Etags,
/// Public links. Absent on a server that forbids them, and the dialog then
/// offers no Copy link rather than a button that fails.
LinkShares,
/// A key on a public link. This is what most places mean when they talk
/// about sharing with somebody who has no account.
LinkPassword,
/// The server requires that key, so a link cannot be made without one.
LinkPasswordRequired,
/// An expiry date on a share.
ShareExpiry,
/// The provider can tell a recipient that something was shared with them.
///
/// Distinct from [`Capability::Mail`], which is about sending arbitrary
/// mail. A provider commonly has this and not that: it will notify the
/// person a share names without offering any way to send mail in general.
ShareNotify,
/// A conversation about a document, such as a call or a chat room.
///
/// Every provider that has this calls it something else, so the name
/// comes from [`crate::Conversations::conversation_name`]. Reported
/// separately from that name: a provider knows what it would call the
/// feature whether or not an administrator installed it.
Conversation,
}
/// A file or folder.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entry {
/// An opaque handle for reading, writing and sharing this entry.
///
/// Only the provider that issued it may interpret it. A caller passes it
/// back and never parses it.
pub id: String,
/// The stable identity used for a collaboration room.
///
/// Separate from `id` on purpose. A provider's read and write handle is
/// often a path, and a path changes when somebody renames or moves the
/// file. A room keyed on that would silently split in two mid-session,
/// with each half seeing only its own edits. This one survives a rename.
pub room: String,
/// What to show the user.
pub name: String,
/// Where it sits, for a breadcrumb. Never a handle.
pub path: String,
pub kind: EntryKind,
/// Bytes, absent for a folder.
pub size: Option<u64>,
/// RFC 3339. Absent when the provider does not say.
pub modified: Option<String>,
/// For matching a document to the app that opens it.
pub mime: Option<String>,
/// The version the caller last saw, for a conditional write.
pub etag: Option<String>,
/// Whether this user may change it. A read-only share still lists.
pub writable: bool,
/// Who shared it, when it came from somebody else.
pub shared_by: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EntryKind {
File,
Folder,
}
/// A person, as a share dialog needs them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Contact {
/// What the provider wants back when sharing with this person.
pub id: String,
/// How to share with them, decided by the provider and never guessed.
///
/// The distinction is not cosmetic. A contact with an account is a user
/// share. One known only by address is an email share. Sharing an address
/// as though it were a user id fails with "not found", because no such
/// user exists, and nothing in `id` alone says which case this is.
pub target: ShareTarget,
/// What to show. A display name where there is one.
pub name: String,
pub email: Option<String>,
/// An avatar, as a URL the client may fetch. Never image bytes: a search
/// returning ten people would otherwise carry ten pictures nobody asked
/// for yet.
pub avatar: Option<String>,
/// A group rather than a person. Shown differently and shared differently.
pub is_group: bool,
}
/// Who to share with.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", content = "id")]
pub enum ShareTarget {
User(String),
Group(String),
/// Somebody with no account, reached by address.
Email(String),
/// Anybody holding the link.
Link,
}
/// What a share allows.
///
/// Deliberately coarse. Providers disagree on the fine detail, and a dialog
/// offering a distinction the server cannot keep is worse than one that does
/// not.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Permission {
/// Open and read. No edits reach the document.
View,
/// Open and edit.
Edit,
}
/// Everything optional about a share.
///
/// A struct rather than more positional arguments. The list grew past the
/// point where a call site reads correctly, and a provider that cannot honour
/// one of these needs to see which it was given.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareOptions {
/// Shown to the recipient.
pub note: Option<String>,
/// Send mail where the provider can.
pub notify: bool,
/// A key the recipient must present. Only meaningful for a link, and
/// refused by a server that does not allow one.
pub password: Option<String>,
/// `YYYY-MM-DD`. After this the share stops working.
pub expires: Option<String>,
}
/// Where to go to work together on a document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Conversation {
/// Where to join. Handed to a browser, or to the provider's own app.
pub url: String,
/// What the provider calls the feature, for the control's wording. A
/// menu item reading "Work together in Talk" is built from this.
pub name: String,
}
/// A share that exists.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Share {
pub id: String,
pub target: ShareTarget,
/// What to call the recipient, where the provider says.
///
/// A share carries the handle the server wants back, which for a user is
/// an account id. People are not known to each other by account id. A
/// provider that knows the difference says so here.
pub display: Option<String>,
pub permission: Permission,
/// Present for a link share, absent otherwise.
pub url: Option<String>,
pub note: Option<String>,
/// RFC 3339.
pub created: Option<String>,
}
/// Something worth telling a user about, in the app.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Notification {
/// A short machine-readable kind, such as `document_shared`. Lets a client
/// decide how to render without parsing prose.
pub kind: String,
pub subject: String,
pub body: Option<String>,
/// Where to go when it is clicked.
pub link: Option<String>,
}
/// An email to send.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct MailMessage {
pub to: Vec<String>,
pub subject: String,
pub body: String,
/// Whether `body` is HTML. Plain text otherwise.
pub html: bool,
}
/// The signed-in user, as the provider sees them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Identity {
/// The provider's identifier for this account.
pub id: String,
/// What to show. Never an identity: two people can share a display name.
pub display: String,
pub email: Option<String>,
pub avatar: Option<String>,
}
+11
View File
@@ -19,6 +19,12 @@ log = "0.4"
serde = { version = "1", features = ["derive"], optional = true }
# Same version as epaint's, for reading a face's character map.
skrifa = { version = "0.44", default-features = false, features = ["std"] }
# The vendor-neutral vocabulary the share dialog speaks. No IO and no
# vendor, so this stays buildable for the web.
craft-cloud = { workspace = true, optional = true }
# The control channel's report of the cloud state. One serialiser here
# rather than one per application. No IO and no vendor.
serde_json = { workspace = true, optional = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Screenshot and input tests of an app's screens (the screen-testing feature).
@@ -54,6 +60,11 @@ testing = []
# craft_ui::testing: per-language screenshot tests, IME smoke tests, input steps and review
# screenshots with egui_kittest (desktop only).
screen-testing = ["dep:egui_kittest"]
# The share dialog and the backend contract it states its work through.
share = ["dep:craft-cloud"]
# Open and Save against cloud storage. Needs the share dialog, which a
# document's overflow menu and the Share split button both open.
cloud = ["share", "dep:serde_json"]
[dev-dependencies]
# serde: the IME tests read events that only the suite's egui fork has from JSON.
+60
View File
@@ -705,6 +705,66 @@ verify the actual pixels as well as callback routing.
`text::align_galley_rows` positions already shaped rows inside a fixed-width reading area without changing glyphs or logical text. Supply a per-row alignment, for example the paragraph direction from the application shaper. The helper uses stock egui APIs and keeps cached glyph meshes shared. Its logical rectangle is the requested width; ink may overflow, so clip the painter when drawing cards. Use it for read-only painting, keeping the original galley for editable hit testing.
## Sharing
`share::ShareDialog` is a whole dialog. It holds a recipient picker with autocomplete and
removable chips. It offers a view-or-edit choice, a note and a notify-by-email box. Under those it
lists who already has access, with a withdrawal beside each entry. Every Craft app gets the same
dialog. An application's own part comes to three lines.
```rust
// Once, at startup. The host supplies the half that reaches the service.
app.share.connect(my_backend);
// Every frame, open or shut. This is also where answers are collected.
app.share.show(ctx);
// From the app's Share control, drawn only while `available()` is true.
if app.share.available() && share_button.clicked() {
app.share.open(entry.id.clone(), entry.name.clone());
}
```
The dialog opens no socket, names no provider and holds no credential. It states each piece of
work as a `share::Request` and hands it to a `share::ShareBackend`. That backend answers through a
`share::Replier` whenever it is ready. Nothing in this crate implements that trait. A host writes
the half that opens a socket, and this crate never learns what it reaches. The interface half
therefore builds for the web, and every flow is testable with no server running.
Autocomplete waits `share::DEBOUNCE` after the last keystroke before it asks anything. An answer
to a query the user has already typed past is dropped before it reaches the list. A list that
flickers back to stale matches is worse than one that arrives late.
Partial success is rendered as partial success. A share aimed at five people with one wrong
address reaches four. The dialog names the fifth with the reason the service gave. It keeps that
one recipient in the picker. A correction then takes one edit. `outcome()` hands back both halves.
Capability is reported and never assumed. `available()` stays false until the service says the
provider supports sharing and an account is linked. `open` does nothing while it is false. An
application draws no Share control in that state. A hidden feature beats a button that fails on
use. Contacts and mail are reported separately. A server with no address book accepts typed
addresses only. A server that cannot send mail disables the notify box and says why.
`ShareLabels` holds every string the dialog shows. The defaults are English. A localized
application replaces them without touching this crate.
A contact's `avatar` is a URL. The dialog asks for the bytes through the same backend, as the row
that needs the picture is painted and only while that row is on screen. A search answering with
ten people costs no pictures until somebody looks at them. Each URL is asked about once. A refusal
is remembered, with initials painted in its place. The host decides whether a picture may be
fetched at all. A backend that refuses `share::Request::Avatar` gets initials painted instead, and
a host that would rather not have an application reach a provider's avatar URL directly can say
so by refusing it. A host that relays pictures answers it. Nothing else changes.
### The account
`account::AccountMenu` is the badge every suite puts in the top right. It shows who is signed in,
where they are signed in, and whether storage is linked. It holds no credential. It asks the
service who the caller is, through the application. It reports what the user asked for through
`take_action`. The application owns what signing in means.
Without linked storage, Open and Save have nowhere to go. The menu says so at rest. A failure at
the moment of saving arrives too late to be useful.
## Compatibility and checks
The crate uses egui 0.37 and Rust 1.95 or later. Its production dependency disables egui's default
+449
View File
@@ -0,0 +1,449 @@
//! Who is signed in, which account is in use, and how to stop being signed in.
//!
//! Every office suite puts this in the same place, for the same reason. A
//! document is about to be saved somewhere and shared with somebody. The
//! account decides both the destination and the identity. An application that
//! never shows it leaves the user guessing which of their identities is in
//! play.
//!
//! A person commonly holds more than one. A work account and a personal one
//! are two different places to save, with two different sets of colleagues to
//! share with, and confusing them is the expensive mistake this control exists
//! to prevent. So the control holds a list and marks which one is in use.
//!
//! This holds no credential. It asks the service who the caller is and shows
//! the answer. A sign-out makes the service forget the session.
use std::sync::mpsc::{Receiver, Sender, channel};
use egui::{Align, Context, Layout, RichText, Ui};
/// One account the user is signed in to.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Account {
/// How the service names this account. Never shown.
pub id: String,
/// What to show. A display name, never an identity.
pub display: String,
pub email: Option<String>,
/// Where they are signed in, such as the service's host. Shown because
/// somebody with accounts on two deployments needs to tell them apart.
pub service: String,
/// Whether storage is linked. Without it Open and Save have nowhere to go,
/// and saying so here is kinder than a failure at the moment of saving.
pub linked: bool,
}
impl Account {
pub fn new(id: impl Into<String>, display: impl Into<String>) -> Account {
Account { id: id.into(), display: display.into(), ..Account::default() }
}
/// The letter on the badge. The first character of the display name, which
/// is what every suite uses and what people recognise at that size.
pub fn initial(&self) -> String {
self.display.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_else(|| "?".to_owned())
}
}
/// What the menu asks the application to do.
///
/// Each one names the account it is about. A control that said only "sign out"
/// would be ambiguous the moment somebody held two.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AccountAction {
/// Begin a sign-in with nobody signed in yet.
SignIn,
/// Add another account alongside the ones already here.
AddAccount,
/// Work as this account from now on.
Use(String),
/// End this account's session, at the service and here.
SignOut(String),
/// Connect storage for an account that has none.
Link(String),
/// Open the service's own page for this account.
Manage(String),
}
/// Strings, so an application can translate them.
#[derive(Clone, Debug)]
pub struct AccountLabels {
pub signed_out: String,
pub sign_in: String,
pub sign_out: String,
pub add_account: String,
pub other_accounts: String,
pub link: String,
pub linked: String,
pub not_linked: String,
pub manage: String,
pub working: String,
/// The badge's accessible name. `{name}` is replaced.
///
/// A button announcing only a person's name says nothing about what
/// pressing it does, and collides with every other place that name is
/// written.
pub badge: String,
/// Shown when accounts are signed in and none is in use.
pub choose: String,
/// Why that happened, since a person who did not sign out needs telling.
pub choose_why: String,
}
impl Default for AccountLabels {
fn default() -> AccountLabels {
AccountLabels {
signed_out: "Not signed in".into(),
sign_in: "Sign in".into(),
sign_out: "Sign out".into(),
add_account: "Add an account".into(),
other_accounts: "Other accounts".into(),
link: "Connect storage".into(),
linked: "Storage connected".into(),
not_linked: "No storage connected".into(),
manage: "Account settings".into(),
working: "Working\u{2026}".into(),
badge: "Account, {name}".into(),
choose: "Choose an account".into(),
choose_why: "The account you were using is no longer signed in.".into(),
}
}
}
/// The account badge and its menu.
pub struct AccountMenu {
accounts: Vec<Account>,
/// Which account the application is working as. Held by id rather than by
/// index, since the list is replaced wholesale whenever the service answers.
active: Option<String>,
labels: AccountLabels,
/// Set while a sign-in or sign-out is in flight, so the control says so
/// rather than looking unresponsive.
busy: bool,
/// Whether the host can hold more than one account at once.
///
/// Off until a host says otherwise. An application that keeps one
/// session would otherwise draw an Add an account that signs the user
/// in again as the account they are already using, which reads as a
/// button that does nothing.
more_allowed: bool,
actions: (Sender<AccountAction>, Receiver<AccountAction>),
}
impl Default for AccountMenu {
fn default() -> AccountMenu {
AccountMenu::new()
}
}
impl AccountMenu {
pub fn new() -> AccountMenu {
AccountMenu { accounts: Vec::new(), active: None, labels: AccountLabels::default(), busy: false, more_allowed: false, actions: channel() }
}
pub fn with_labels(mut self, labels: AccountLabels) -> AccountMenu {
self.labels = labels;
self
}
/// Say that this host can hold more than one account at once.
///
/// Until a host says so, the menu offers no way to add one. Signing in
/// again as the account already in use is not an action worth drawing.
pub fn allowing_more(mut self) -> AccountMenu {
self.more_allowed = true;
self
}
/// Replace the whole set of accounts.
///
/// Wholesale rather than one at a time. A session that missed a sign-out
/// elsewhere would otherwise keep offering an account that is gone.
///
/// The account in use is kept when it is still in the list.
///
/// When it has gone, nothing takes its place. A work session that expires
/// would otherwise hand the next save, share and open to a personal
/// account without saying so, and sending a document to the wrong tenant
/// is not a mistake a person can take back. The control asks instead.
///
/// The first account is chosen only when none was in use at all, which is
/// the first sign-in.
pub fn set(&mut self, accounts: Vec<Account>) {
let chose_before = self.active.is_some();
let kept = self.active.take().filter(|id| accounts.iter().any(|a| a.id == *id));
self.active = match kept {
Some(id) => Some(id),
None if chose_before => None,
None => accounts.first().map(|a| a.id.clone()),
};
self.accounts = accounts;
self.busy = false;
}
/// Work as this account. Ignored for an account that is not here.
pub fn set_active(&mut self, id: &str) {
if self.accounts.iter().any(|a| a.id == id) {
self.active = Some(id.to_owned());
}
}
pub fn active(&self) -> Option<&Account> {
let id = self.active.as_deref()?;
self.accounts.iter().find(|a| a.id == id)
}
pub fn accounts(&self) -> &[Account] {
&self.accounts
}
pub fn is_signed_in(&self) -> bool {
!self.accounts.is_empty()
}
/// Mark something as in flight. Cleared by the next [`AccountMenu::set`].
pub fn working(&mut self) {
self.busy = true;
}
/// What the user asked for since the last call, if anything.
///
/// Drained rather than handed a callback, so the application acts on its
/// own thread and this stays free of any notion of what signing in means.
pub fn take_action(&mut self) -> Option<AccountAction> {
self.actions.1.try_recv().ok()
}
/// Draw the badge. Put it where the window's own controls are.
pub fn show(&mut self, ui: &mut Ui) {
let tx = self.actions.0.clone();
let labels = self.labels.clone();
let busy = self.busy;
let Some(account) = self.active().cloned() else {
// Nobody signed in, or signed in with the account that was in use
// now gone. The two read differently. One offers a sign-in. The
// other has accounts to offer and must say so, since saving has
// nowhere to go until somebody picks one.
if self.accounts.is_empty() {
let label = if busy { labels.working.as_str() } else { labels.sign_in.as_str() };
if ui.add_enabled(!busy, egui::Button::new(label).small()).clicked() {
let _ = tx.send(AccountAction::SignIn);
}
return;
}
let waiting = self.accounts.clone();
let hit = ui.add_enabled(!busy, egui::Button::new(labels.choose.as_str()).small());
egui::Popup::menu(&hit).show(|ui| {
ui.set_min_width(240.0);
ui.label(RichText::new(labels.choose_why.as_str()).small().color(ui.visuals().warn_fg_color));
ui.separator();
for one in &waiting {
let label = format!("{}\n{}", one.display, one.service);
let row = ui.add(egui::Button::new(label).wrap_mode(egui::TextWrapMode::Extend));
let name = one.display.clone();
row.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, name.as_str()));
if row.clicked() {
let _ = tx.send(AccountAction::Use(one.id.clone()));
ui.close();
}
}
ui.add_space(4.0);
if ui.button(labels.sign_in.as_str()).clicked() {
let _ = tx.send(AccountAction::SignIn);
ui.close();
}
});
return;
};
let others: Vec<Account> = self.accounts.iter().filter(|a| a.id != account.id).cloned().collect();
let more_allowed = self.more_allowed;
let badge = egui::Button::new(RichText::new(account.initial()).strong()).min_size(egui::vec2(26.0, 26.0)).corner_radius(13.0);
let hit = ui.add(badge);
let spoken = labels.badge.replace("{name}", &account.display);
hit.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, spoken.as_str()));
let hit = hit.on_hover_text(account.display.as_str());
egui::Popup::menu(&hit).show(|ui| {
ui.set_min_width(260.0);
// The deployment first, because somebody with an account on two of
// them needs to know which one this is before reading anything
// else.
ui.horizontal(|ui| {
ui.label(RichText::new(account.service.as_str()).small().color(ui.visuals().weak_text_color()));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.small_button(labels.sign_out.as_str()).clicked() {
let _ = tx.send(AccountAction::SignOut(account.id.clone()));
ui.close();
}
});
});
ui.separator();
ui.horizontal(|ui| {
ui.label(RichText::new(account.initial()).size(26.0).strong());
ui.vertical(|ui| {
ui.label(RichText::new(account.display.as_str()).strong().size(15.0));
if let Some(email) = &account.email {
ui.label(RichText::new(email.as_str()).small().color(ui.visuals().weak_text_color()));
}
});
});
ui.add_space(6.0);
// Storage, which is the thing that actually stops working when it
// is missing. Said here rather than discovered at the moment of
// saving.
if account.linked {
ui.label(RichText::new(labels.linked.as_str()).small().color(ui.visuals().weak_text_color()));
} else {
ui.label(RichText::new(labels.not_linked.as_str()).small().color(ui.visuals().warn_fg_color));
if ui.button(labels.link.as_str()).clicked() {
let _ = tx.send(AccountAction::Link(account.id.clone()));
ui.close();
}
}
if !others.is_empty() {
ui.add_space(6.0);
ui.separator();
ui.label(RichText::new(labels.other_accounts.as_str()).small().color(ui.visuals().weak_text_color()));
for other in &others {
// Both lines in one control. A name above a subtitle, where
// only the name answers a press, makes half the row look
// broken to anybody who aims at the wrong half. The
// deployment is on the second line because two accounts
// both reading "Will Dunn" tell nobody which is the work
// one.
let label = format!("{}\n{}", other.display, other.service);
let row = ui.add(egui::Button::new(label).wrap_mode(egui::TextWrapMode::Extend));
let name = other.display.clone();
row.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, name.as_str()));
if row.clicked() {
let _ = tx.send(AccountAction::Use(other.id.clone()));
ui.close();
}
}
}
if more_allowed {
ui.add_space(6.0);
if ui.button(labels.add_account.as_str()).clicked() {
let _ = tx.send(AccountAction::AddAccount);
ui.close();
}
}
ui.add_space(4.0);
if ui.link(labels.manage.as_str()).clicked() {
let _ = tx.send(AccountAction::Manage(account.id.clone()));
ui.close();
}
});
}
/// Draw the badge in a context that has no `Ui` to hand.
pub fn show_in_ctx(&mut self, ctx: &Context) {
egui::Area::new(egui::Id::new("craft-ui/account")).anchor(egui::Align2::RIGHT_TOP, egui::vec2(-8.0, 8.0)).show(ctx, |ui| {
self.show(ui);
});
}
}
#[cfg(test)]
mod tests {
use super::*;
fn account(id: &str, display: &str) -> Account {
Account { id: id.into(), display: display.into(), service: "one.example.com".into(), ..Account::default() }
}
#[test]
fn nobody_signed_in_has_no_active_account() {
let menu = AccountMenu::new();
assert!(!menu.is_signed_in());
assert_eq!(menu.active(), None);
}
#[test]
fn the_first_account_becomes_the_active_one() {
let mut menu = AccountMenu::new();
menu.set(vec![account("a", "Work"), account("b", "Personal")]);
assert_eq!(menu.active().map(|a| a.id.as_str()), Some("a"));
}
#[test]
fn replacing_the_list_keeps_the_account_in_use() {
let mut menu = AccountMenu::new();
menu.set(vec![account("a", "Work"), account("b", "Personal")]);
menu.set_active("b");
menu.set(vec![account("a", "Work"), account("b", "Personal"), account("c", "Lab")]);
assert_eq!(menu.active().map(|a| a.id.as_str()), Some("b"), "an unrelated refresh must not switch accounts");
}
#[test]
fn an_account_that_signed_out_elsewhere_leaves_nobody_in_use() {
let mut menu = AccountMenu::new();
menu.set(vec![account("a", "Work"), account("b", "Personal")]);
menu.set_active("b");
menu.set(vec![account("a", "Work")]);
// Not account a. A work session that expires must not hand the next
// save to a personal account without anybody saying so.
assert_eq!(menu.active(), None, "the one that is gone cannot be replaced in silence");
assert!(menu.is_signed_in(), "there is still an account here to choose");
}
#[test]
fn choosing_again_after_one_disappeared_works() {
let mut menu = AccountMenu::new();
menu.set(vec![account("a", "Work"), account("b", "Personal")]);
menu.set_active("b");
menu.set(vec![account("a", "Work")]);
menu.set_active("a");
assert_eq!(menu.active().map(|a| a.id.as_str()), Some("a"));
}
#[test]
fn a_refresh_that_keeps_the_account_keeps_it_in_use() {
let mut menu = AccountMenu::new();
menu.set(vec![account("a", "Work"), account("b", "Personal")]);
menu.set_active("b");
menu.set(vec![account("b", "Personal"), account("c", "Lab")]);
assert_eq!(menu.active().map(|a| a.id.as_str()), Some("b"));
}
#[test]
fn the_last_account_leaving_signs_everybody_out() {
let mut menu = AccountMenu::new();
menu.set(vec![account("a", "Work")]);
menu.set(Vec::new());
assert!(!menu.is_signed_in());
assert_eq!(menu.active(), None);
}
#[test]
fn switching_to_an_account_that_is_not_here_changes_nothing() {
let mut menu = AccountMenu::new();
menu.set(vec![account("a", "Work")]);
menu.set_active("nobody");
assert_eq!(menu.active().map(|a| a.id.as_str()), Some("a"));
}
#[test]
fn the_badge_says_what_it_is_as_well_as_who() {
let labels = AccountLabels::default();
let spoken = labels.badge.replace("{name}", "Ada Lovelace");
assert_eq!(spoken, "Account, Ada Lovelace");
assert_ne!(spoken, "Ada Lovelace", "a bare name collides with every other place it is written");
}
#[test]
fn an_initial_survives_a_name_that_starts_oddly() {
assert_eq!(account("1", "ann").initial(), "A");
assert_eq!(account("1", "").initial(), "?");
assert_eq!(account("1", "\u{e9}lodie").initial(), "\u{c9}");
}
}
+15
View File
@@ -120,3 +120,18 @@ fn bounded_stroke(stroke: Stroke, rect: Rect) -> Stroke {
#[cfg(test)]
mod tests;
/// A downward triangle at the right-hand end of a control.
///
/// Painted rather than typed. The chevron character is absent from the default
/// font set, where it renders as a missing-glyph box. A caller leaves room for
/// it by padding the label, then paints it over the response.
pub fn chevron(ui: &Ui, rect: egui::Rect, colour: egui::Color32) {
let middle = rect.right_center() - egui::vec2(9.0, 0.0);
let half = 3.5;
ui.painter().add(egui::Shape::convex_polygon(
vec![middle + egui::vec2(-half, -half * 0.6), middle + egui::vec2(half, -half * 0.6), middle + egui::vec2(0.0, half * 0.9)],
colour,
egui::Stroke::NONE,
));
}
+255
View File
@@ -0,0 +1,255 @@
//! What this module needs from the application around it.
//!
//! Two operations here belong to the application alone. One turns bytes into an
//! open document. The other turns an open document into bytes. Both need the
//! application's own mutable state. That state is what holds the
//! [`CloudFiles`](crate::cloud::CloudFiles) this module keeps its own state in.
//! The pages are therefore free functions over this trait. An application
//! reaches its cloud state back through [`CloudApp::cloud_mut`].
//!
//! Every method here is something only the application can answer. The ones
//! with a body are the ones a plain application can leave alone.
use egui::{Color32, FontFamily, Painter, Rect, Ui};
use craft_cloud::EntryKind;
/// What one of the application's documents is, as a file list needs to know.
///
/// Four pieces of static data, usually one `const` in the application. These
/// four are the whole of what an application has to say about its own
/// documents. They are data because every one of them as a trait method would
/// have been a pure function of nothing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DocumentKind {
/// Extensions this application opens, lower case and without a dot. The
/// same set its desktop file picker offers.
pub extensions: &'static [&'static str],
/// Content types it opens, matched against the start of what the provider
/// said. The match is a prefix. A provider commonly appends a profile to a
/// type it is otherwise right about.
pub mimes: &'static [&'static str],
/// What one is called in a sentence a user reads. "workbook", "document",
/// "drawing".
pub noun: &'static str,
/// The extension a typed name without a known one gets.
pub default_extension: &'static str,
}
/// The colours and faces these pages draw in.
///
/// The Open and Save pages sit inside the application's own Backstage view and
/// have to match the surface around them. `ui.visuals()` alone cannot say what
/// that surface is. An application with a palette of its own passes it in. One
/// without takes [`CloudStyle::from_visuals`] and writes nothing.
#[derive(Clone, Debug)]
pub struct CloudStyle {
/// Behind a bordered column.
pub surface: Color32,
pub border: Color32,
pub text: Color32,
/// Second lines, hints and the status line.
pub dim: Color32,
/// Behind a file row the pointer is over.
pub hover: Color32,
/// Behind the panel that offers to link an account. Tinted and never
/// alarming. No account yet is a state with an obvious next step.
pub soft: Color32,
pub family: FontFamily,
pub bold: FontFamily,
}
impl CloudStyle {
/// Colours from egui's own visuals, for an application with no palette.
pub fn from_visuals(visuals: &egui::Visuals) -> CloudStyle {
CloudStyle {
surface: visuals.faint_bg_color,
border: visuals.widgets.noninteractive.bg_stroke.color,
text: visuals.text_color(),
dim: visuals.weak_text_color(),
hover: visuals.widgets.hovered.bg_fill,
soft: visuals.faint_bg_color,
family: FontFamily::Proportional,
bold: FontFamily::Proportional,
}
}
}
/// One of the application's own Save a Copy formats, for the second half of
/// the Share menu.
///
/// The application's own. What a spreadsheet exports and what a page layout
/// application exports have nothing in common.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CopyFormat {
/// Handed back untouched when this one is chosen.
pub id: String,
pub label: String,
}
impl CopyFormat {
pub fn new(id: impl Into<String>, label: impl Into<String>) -> CopyFormat {
CopyFormat { id: id.into(), label: label.into() }
}
}
/// An application that opens and saves documents in cloud storage.
/// Where a save is going.
///
/// Carried as a pair because neither half is reliable alone. A provider hands
/// back `application/octet-stream` for a perfectly good document, and a file
/// exported by a web application often has a correct content type and no
/// extension at all. The same reasoning as [`DocumentKind`], which reads both
/// when deciding whether a document opens.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Destination<'a> {
/// The file name the bytes are going to.
pub name: &'a str,
/// What the provider says is already there, where it says anything. Absent
/// for a document that does not exist yet.
pub mime: Option<&'a str>,
}
impl<'a> Destination<'a> {
pub fn new(name: &'a str) -> Destination<'a> {
Destination { name, mime: None }
}
/// The extension the name carries, lower cased, when it carries one.
///
/// Empty for a bare name. A caller that gets nothing here has the content
/// type left to read.
pub fn extension(&self) -> String {
self.name.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase()).filter(|ext| !ext.is_empty()).unwrap_or_default()
}
}
pub trait CloudApp {
// ---- the state these pages keep -------------------------------------
fn cloud(&self) -> &crate::cloud::CloudFiles;
fn cloud_mut(&mut self) -> &mut crate::cloud::CloudFiles;
// ---- its documents ---------------------------------------------------
fn kind(&self) -> DocumentKind;
/// The document in this window, when there is one.
fn active(&self) -> Option<u64>;
/// What to call one, for the Save As name field.
fn title(&self, uid: u64) -> String;
/// Turn bytes into an open document, answering with the one it opened as.
///
/// `Ok(None)` when the application took the bytes somewhere else, such as
/// a prompt for a password. Nothing is said about them yet. `Err` is put
/// to the user.
fn open_bytes(&mut self, name: &str, bytes: Vec<u8>) -> Result<Option<u64>, String>;
/// Turn one open document into the bytes to save, for `into`.
///
/// [`Destination`] is where the bytes are going. A document opened from
/// the cloud as `figures.csv` has to go back as a CSV. Encoding it in the
/// application's own format under that name hands the user a file no other
/// application can read, and nothing tells them it happened.
///
/// The name is the first answer. A provider that issued no extension at
/// all still says what the thing is, so the content type is the second.
/// Both appear often: a file exported by a web application commonly has a
/// correct content type and a bare name.
///
/// An application that cannot write what the destination asks for should
/// refuse and say which formats it can write. A refusal a person can act
/// on beats a file that silently is not what it claims.
///
/// Takes `&mut self` so the application can record which version of the
/// document these bytes were. A save that lands clears the dirty flag for
/// exactly that version. An edit made while the bytes were on the wire
/// stays unsaved. [`CloudApp::mark_saved`] and [`CloudApp::drop_pending`]
/// say which happened.
fn encode(&mut self, uid: u64, into: Destination<'_>) -> Result<Vec<u8>, String>;
/// Close a document a reload replaced. Called only once the replacement is
/// open. A read that failed leaves the user's work where it was.
fn close(&mut self, uid: u64);
/// The bytes [`CloudApp::encode`] made reached the service.
fn mark_saved(&mut self, _uid: u64) {}
/// They did not. Forget the version it recorded.
fn drop_pending(&mut self, _uid: u64) {}
/// Finish whatever the user is still typing. False stops the save.
fn ready_to_save(&mut self) -> bool {
true
}
// ---- the window around them ------------------------------------------
/// The share dialog this window holds. Opened from a document's overflow
/// menu and from the Share button. Refreshed when who is signed in
/// changes.
fn sharing(&mut self) -> &mut crate::share::ShareDialog;
/// Who else is in the document. Drawn beside the account badge.
fn presence(&mut self) -> &mut crate::presence::PresenceBar;
/// Paint the icon for one row of a file list. Every application already
/// owns an icon set. None of them agree on how it is reached.
fn paint_icon(&self, painter: &Painter, rect: Rect, kind: EntryKind, colour: Color32);
/// Open a URL in the user's browser. A browser is the application's
/// business. This crate opens nothing.
fn open_url(&self, url: &str);
/// Open the provider's conversation for this document.
///
/// Desktop hosts may hand this to the operating system so a registered
/// chat application can claim it. Browser hosts may navigate the current
/// tab, which remains reliable after an asynchronous provider lookup.
fn open_conversation(&self, url: &str) {
self.open_url(url);
}
/// Say something that needs the user's attention, in the application's own
/// message box.
fn say(&mut self, text: String);
/// Say something that does not, in passing.
fn toast(&mut self, _text: String) {}
/// Take the user to the application's own Save As page, with the name
/// [`CloudFiles::save_name`](crate::cloud::CloudFiles::save_name) now
/// holding. Called when a refused save is answered with Save as a copy.
fn go_to_save_as(&mut self) {}
// ---- its words -------------------------------------------------------
/// What the application is called, for the one sentence that names it.
fn app_name(&self) -> &str;
/// Translate one English string. The default leaves it alone. An
/// application with no translation table writes nothing.
fn tr(&self, text: &str) -> String {
text.to_owned()
}
/// The host part of the service address, for the account menu's first
/// line. Somebody with an account on two deployments needs to know which
/// one a document is about to land in.
fn service(&self) -> String {
String::new()
}
/// A line under the Save page's name field, about the format this
/// application saves in.
fn save_note(&self) -> Option<String> {
None
}
/// The colours and faces to draw in.
fn style(&self, ui: &Ui) -> CloudStyle {
CloudStyle::from_visuals(ui.visuals())
}
}
+195
View File
@@ -0,0 +1,195 @@
//! Where Open and Save do their waiting. It is never on the frame.
//!
//! Every call a cloud provider needs is blocking. A blocking read of a twenty
//! megabyte document inside `update()` freezes the window for seconds. So this
//! module states a [`Job`] and reads an [`Event`]. Something behind
//! [`CloudBackend`] does the waiting.
//!
//! Nothing here opens a socket. That keeps the pages buildable for the web and
//! testable with no service running. A host supplies the half that does. This
//! crate never learns what it reaches.
use std::sync::mpsc::Sender;
use craft_cloud::{Capability, Conversation, Entry};
/// Work for a host's worker. Each one answers with one or more [`Event`].
pub enum Job {
/// Who is signed in, and what the provider behind the service can do.
Account,
/// Begin signing in to the service through the browser or device flow.
SignIn,
/// Begin linking a cloud account. The answer carries a URL to open.
LinkStart,
/// Whether the user has finished in the browser yet.
LinkPoll(String),
/// One folder's contents. An empty path is the user's root.
List(String),
/// Everything other people have shared with this user.
SharedWithMe,
/// A document's bytes. `into` names the open document a reload replaces.
Read { entry: Entry, into: Option<u64> },
/// Save back over `entry`, refusing to overwrite a newer version.
Write { uid: u64, entry: Entry, bytes: Vec<u8> },
/// Save under a new name in `folder`.
Create { uid: u64, folder: String, name: String, bytes: Vec<u8> },
/// End the session and forget the saved token.
SignOut,
/// Where to go to work together on a document.
Conversation(String),
}
/// What a worker reports back.
pub enum Event {
/// Where to go to work together, or why there is nowhere.
Conversation(Result<Conversation, Fault>),
Account(Result<Account, Fault>),
/// A link or a sign-in needs the user's browser. `handle` is polled until
/// they are done, when the service gave one.
Browser {
url: String,
handle: Option<String>,
},
/// `Ok(true)` means the account is linked now.
Linked(Result<bool, Fault>),
Listed {
path: String,
entries: Result<Vec<Entry>, Fault>,
},
Shared(Result<Vec<Entry>, Fault>),
Read {
entry: Entry,
into: Option<u64>,
bytes: Result<Vec<u8>, Fault>,
},
Saved {
uid: u64,
entry: Result<Entry, Fault>,
},
}
/// Where a worker's answers go.
///
/// Handed to [`CloudBackend::submit`] with the job it belongs to. A worker is
/// free to keep it and send later, or to send several times. That is how a
/// sign-in reports the URL it wants a browser pointed at and then reports that
/// the user finished there. A send after the window closed is not a failure.
pub struct Post {
tx: Sender<Event>,
}
impl Post {
pub(crate) fn new(tx: Sender<Event>) -> Post {
Post { tx }
}
/// Another handle to the same place, for a worker that answers more than
/// once or hands the job on.
pub fn dup(&self) -> Post {
Post { tx: self.tx.clone() }
}
pub fn send(&self, event: Event) {
let _ = self.tx.send(event);
}
}
impl std::fmt::Debug for Post {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Post").finish()
}
}
/// Somewhere a [`Job`] can run without blocking a frame.
///
/// `submit` must return immediately. Answers arrive through `post` whenever
/// they are ready, or never. The pages survive either.
pub trait CloudBackend {
fn submit(&self, job: Job, post: Post);
}
/// What the service said about the signed-in user.
///
/// Capabilities are reported by the service and never assumed here. A provider
/// without incoming shares hides that side of the Open page. An empty list
/// where a feature should be reads to a user as a broken window.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Account {
pub display: String,
pub capabilities: Vec<Capability>,
/// Until this is true, Open and Save have nowhere to go.
pub provider_linked: bool,
}
impl Account {
pub fn can(&self, capability: Capability) -> bool {
self.capabilities.contains(&capability)
}
}
/// A call that did not succeed, in the shapes the pages act on differently.
///
/// One case is worth telling apart from every other refusal. A conditional
/// write the server refused means somebody else's work is in the stored copy.
/// That one must never be retried and must never be forced. That is why
/// [`Fault::Conflict`] has a shape of its own.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Fault {
/// No cloud account is linked yet. This is a state with an obvious next
/// step. It is never drawn as an error.
NotLinked,
/// Somebody else saved while this user was editing. The save was refused
/// and their work is intact.
Conflict,
/// The session expired. The user signs in again.
Unauthenticated,
Unreachable(String),
Refused(String),
}
impl Fault {
/// One sentence for a person to read. `noun` is what the application calls
/// one of its documents, from [`crate::cloud::DocumentKind::noun`].
pub fn text(&self, noun: &str) -> String {
match self {
Fault::NotLinked => "No cloud account is linked yet.".to_owned(),
Fault::Conflict => format!("Somebody else saved this {noun} while you were editing it."),
Fault::Unauthenticated => "Your cloud session has expired. Sign in again.".to_owned(),
Fault::Unreachable(detail) => format!("The cloud service could not be reached. {detail}"),
Fault::Refused(detail) => detail.clone(),
}
}
/// A short machine-readable name, for a control channel.
pub fn code(&self) -> &'static str {
match self {
Fault::NotLinked => "not_linked",
Fault::Conflict => "conflict",
Fault::Unauthenticated => "unauthenticated",
Fault::Unreachable(_) => "unreachable",
Fault::Refused(_) => "refused",
}
}
}
/// The contract's own error, in the shapes the pages act on.
///
/// For a host that reaches a provider through [`craft_cloud`] directly. A host
/// that reaches a service through its own client crate maps that crate's error
/// instead, since only it knows which code that service answers a refused
/// conditional write with.
///
/// [`craft_cloud::Error::Conflict`] is the one case worth telling apart. It
/// means somebody else's work is in the stored copy. The save must never be
/// retried and never be forced.
impl From<craft_cloud::Error> for Fault {
fn from(error: craft_cloud::Error) -> Fault {
use craft_cloud::Error;
match error {
Error::Unreachable(detail) => Fault::Unreachable(detail),
Error::Unauthenticated => Fault::Unauthenticated,
Error::Conflict(_) => Fault::Conflict,
other => Fault::Refused(other.to_string()),
}
}
}
+852
View File
@@ -0,0 +1,852 @@
//! Open and Save against cloud storage, the same pages in every Craft app.
//!
//! What this offers is what a person asks for when they say "open the one in
//! my cloud": a Backstage page with their own files on one side and what other
//! people shared with them on the other, folders to walk into, an account badge
//! that says whose storage this is, a Save As page that picks a folder and
//! names a file, and a save that refuses to overwrite somebody else's work.
//!
//! Three things shape the implementation.
//!
//! Nothing here opens a socket. Every call goes through [`CloudBackend`]. A
//! host writes that half. This module never learns what it reaches. That keeps
//! it buildable for the web and testable with no service running.
//!
//! Nothing here blocks. A job goes to a worker, the answer arrives on a
//! channel, and [`pump`] drains it on a later frame. A blocking read of a
//! twenty megabyte document inside a frame would freeze the window for seconds.
//!
//! Nothing here is assumed about the provider. Every side of the Open page is
//! drawn only where the service reported the capability behind it. An empty
//! list under a heading reads to a user as a broken window. A feature the
//! provider does not have is therefore absent, heading and all.
//!
//! The application supplies [`CloudApp`]. That is what it alone can answer.
//! What its documents are, how bytes become one and back, and the words it
//! shows them in.
use std::collections::HashMap;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::Duration;
use craft_cloud::{Capability, Entry, EntryKind};
use egui::{Align2, Rect, RichText, Sense, Stroke, Ui, pos2, vec2};
use serde_json::{Value as Json, json};
mod app;
mod backend;
mod pages;
#[cfg(test)]
mod tests;
mod title;
pub use app::{CloudApp, CloudStyle, CopyFormat, Destination, DocumentKind};
pub use backend::{Account, CloudBackend, Event, Fault, Job, Post};
pub use pages::{conflict_modal, open_page, progress, save_page};
pub use title::{destination_name, prefers_cloud, share_button, shares, who};
/// How long to wait between asking whether the user has finished linking an
/// account in their browser.
const LINK_POLL: f64 = 1.5;
/// What a command says when no cloud service is configured. Not a failure of
/// the service: there is no service to fail.
pub const UNAVAILABLE: &str = "no cloud service is configured";
// ---------------------------------------------------------------- state
/// One folder, as it is being browsed.
#[derive(Clone, Debug, Default)]
pub struct Folder {
pub path: String,
pub entries: Vec<Entry>,
pub loading: bool,
pub error: Option<Fault>,
/// Answered at least once. An empty folder then reads as empty. Without
/// this it would read as still loading.
pub loaded: bool,
}
impl Folder {
fn begin(&mut self, path: &str) {
self.path = path.to_owned();
self.entries.clear();
self.loading = true;
self.loaded = false;
self.error = None;
}
fn fill(&mut self, answer: Result<Vec<Entry>, Fault>) {
self.loading = false;
self.loaded = true;
match answer {
Ok(entries) => {
self.entries = entries;
self.error = None;
}
Err(fault) => {
self.entries.clear();
self.error = Some(fault);
}
}
}
}
/// Where the document in this window came from, and the version it came at.
///
/// `entry.id` is the opaque handle a save passes back. `entry.etag` is the
/// version the conditional write is made against. `entry.room` is neither of
/// those. It is the collaboration identity, and it survives a rename.
#[derive(Clone, Debug)]
pub struct Origin {
pub entry: Entry,
}
/// What the pages are waiting for. Drawn as progress while they wait.
#[derive(Clone, Debug)]
pub enum Busy {
Opening { name: String },
Saving { name: String, bytes: usize },
}
impl Busy {
pub fn text(&self) -> String {
match self {
Busy::Opening { name } => format!("Opening {name}…"),
Busy::Saving { name, bytes } => format!("Saving {name} ({})…", size_text(Some(*bytes as u64))),
}
}
}
/// A save that was refused because the stored copy had moved on.
#[derive(Clone, Debug)]
pub struct Conflict {
/// The document that could not be saved.
pub uid: u64,
pub entry: Entry,
}
/// Linking a cloud account, which takes a browser round trip.
#[derive(Clone, Debug)]
pub enum Link {
/// Offered and not started. Never drawn as an error.
Offered,
Starting,
/// The browser is open. `handle` is polled until the user is done.
Waiting {
url: String,
handle: Option<String>,
next_poll: f64,
},
Failed(Fault),
}
/// Which side of the Open page a selection came from.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Source {
#[default]
Mine,
Shared,
}
/// Who a document was shared with, when nobody is signed in.
///
/// Somebody who followed a keyed link has no account at the service and none
/// at the provider behind it. So there is nothing to sign out of, no second
/// account to switch to and no storage to connect. An account menu offered to
/// them would be a menu whose every item fails.
///
/// This is what a title bar says instead. It names the address the link was
/// sent to, because that is the only identity a recipient has here, and it
/// offers nothing.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Guest {
/// The address the link was sent to.
pub recipient: String,
/// Whether the share opens the document for reading only.
pub read_only: bool,
}
/// Everything these pages keep about cloud storage.
///
/// One per window. The application declares a field of this type, hands it
/// back through [`CloudApp::cloud_mut`], and connects a backend once one
/// exists.
pub struct CloudFiles {
backend: Option<Box<dyn CloudBackend>>,
events: (Sender<Event>, Receiver<Event>),
/// The badge and its menu. Signing in is the only way into any of this.
/// The badge is the only control that offers it. It lives here. An
/// application declares no field for it.
accounts: crate::account::AccountMenu,
/// Frame time, in seconds, as of the last [`pump`]. Kept because a link
/// poll is scheduled from an answer that arrives with no frame in hand.
clock: f64,
pub account: Option<Account>,
pub account_fault: Option<Fault>,
/// The account is asked for once per run. A frame never asks again.
asked_account: bool,
/// The folder being browsed. Shared by the Open and Save As pages, which
/// are never on screen together.
pub mine: Folder,
pub shared: Folder,
pub source: Source,
pub busy: Option<Busy>,
pub link: Option<Link>,
pub conflict: Option<Conflict>,
/// Save As: the file name being typed.
pub save_name: String,
/// Documents that came from the cloud, by document uid.
pub origins: HashMap<u64, Origin>,
/// The last thing that happened, for the line under the page title.
pub status: Option<String>,
/// Whether the transfer in flight was started by the share dialog, which
/// is waiting to be told how it went.
pub sharing_save: bool,
/// Set when this window belongs to somebody who followed a shared link
/// rather than to somebody signed in.
guest: Option<Guest>,
/// Set when the account menu starts sign-in. Browser builds open a login
/// popup from this gesture instead of inferring it from `status`, which can
/// stay set after a failed sign-in.
sign_in_from_menu: bool,
}
impl Default for CloudFiles {
fn default() -> CloudFiles {
CloudFiles::new()
}
}
impl CloudFiles {
pub fn new() -> CloudFiles {
CloudFiles {
backend: None,
events: channel(),
accounts: crate::account::AccountMenu::new(),
clock: 0.0,
account: None,
account_fault: None,
asked_account: false,
mine: Folder::default(),
shared: Folder::default(),
source: Source::default(),
busy: None,
link: None,
conflict: None,
save_name: String::new(),
origins: HashMap::new(),
status: None,
sharing_save: false,
guest: None,
sign_in_from_menu: false,
}
}
/// Whether the account menu just asked to sign in. Consumed by browser hosts
/// that need a user-gesture signal to open a login popup.
pub fn take_sign_in_from_menu(&mut self) -> bool {
std::mem::take(&mut self.sign_in_from_menu)
}
/// Attach the thing that does the waiting.
///
/// Until this is called nothing cloud-shaped is offered anywhere. That is
/// what a build with no service configured wants.
pub fn connect(&mut self, backend: impl CloudBackend + 'static) {
self.backend = Some(Box::new(backend));
}
/// Whether a service is wired at all.
pub fn available(&self) -> bool {
self.backend.is_some()
}
/// Say that this window belongs to somebody who followed a shared link.
///
/// Called once, before anything is drawn, by whatever landed them here.
/// It changes what the title bar says and nothing else: a recipient has no
/// file list and no account, so none of the pages here were ever offered
/// to them.
///
/// An address of only spaces leaves no guest. A badge with nothing on it
/// reads as a fault, and saying nothing is better than that.
pub fn as_guest(&mut self, recipient: impl Into<String>, read_only: bool) {
let recipient = recipient.into().trim().to_owned();
self.guest = if recipient.is_empty() { None } else { Some(Guest { recipient, read_only }) };
}
/// Who this window's document was shared with, when nobody is signed in.
pub fn guest(&self) -> Option<&Guest> {
self.guest.as_ref()
}
/// The account badge's own strings, for a localized application that
/// would rather translate them itself than through
/// [`CloudApp::tr`](crate::cloud::CloudApp::tr).
pub fn account_menu_mut(&mut self) -> &mut crate::account::AccountMenu {
&mut self.accounts
}
/// Whether the provider offers somewhere to talk about a document.
pub fn can_converse(&self) -> bool {
self.can(Capability::Conversation)
}
fn can(&self, capability: Capability) -> bool {
self.account.as_ref().is_some_and(|a| a.can(capability))
}
}
// ---------------------------------------------------------------- asking
/// Whether the host wired a cloud service. When it did not, nothing
/// cloud-shaped is offered anywhere in the interface.
pub fn available<A: CloudApp>(app: &A) -> bool {
app.cloud().available()
}
/// Whether the provider offers somewhere to talk about a document.
pub fn can_converse<A: CloudApp>(app: &A) -> bool {
app.cloud().can_converse()
}
/// Hands a job to the host's worker.
pub fn submit<A: CloudApp>(app: &A, job: Job) {
let cloud = app.cloud();
if let Some(backend) = &cloud.backend {
backend.submit(job, Post::new(cloud.events.0.clone()));
}
}
/// Asks who is signed in, once per run, and lists the root folder.
pub fn start<A: CloudApp>(app: &mut A) {
if !available(app) {
return;
}
if !app.cloud().asked_account {
app.cloud_mut().asked_account = true;
submit(app, Job::Account);
}
if !app.cloud().mine.loaded && !app.cloud().mine.loading {
browse(app, "");
}
}
/// Begins signing in to the service.
///
/// [`Job::SignIn`] is its own job so [`Job::Account`] can stay read-only on
/// cold start. The badge says it is working, because the worker then blocks
/// until the user finishes in the browser and a button that looks idle for a
/// minute reads as broken.
pub fn sign_in<A: CloudApp>(app: &mut A) {
if !available(app) {
return;
}
let working = app.tr("Finish signing in, in your browser");
let cloud = app.cloud_mut();
cloud.accounts.working();
cloud.account_fault = None;
// Cleared first. A sign-in that failed leaves this set, and a second press
// would then be swallowed by the guard that stops a frame asking twice. A
// button that does nothing the second time reads as a broken button.
cloud.asked_account = true;
cloud.link = None;
cloud.status = Some(working);
submit(app, Job::SignIn);
}
/// Ends the session, here and at the service.
///
/// The saved token goes too. Forgetting the account on screen while leaving the
/// token on disk would sign the user back in on the next run.
pub fn sign_out<A: CloudApp>(app: &mut A) {
let signed_out = app.tr("Signed out");
let cloud = app.cloud_mut();
cloud.account = None;
cloud.account_fault = None;
cloud.asked_account = false;
cloud.link = None;
cloud.mine = Folder::default();
cloud.shared = Folder::default();
cloud.origins.clear();
cloud.status = Some(signed_out);
submit(app, Job::SignOut);
}
/// Lists one folder. An empty path is the user's root.
pub fn browse<A: CloudApp>(app: &mut A, path: &str) {
if !available(app) {
return;
}
app.cloud_mut().mine.begin(path);
submit(app, Job::List(path.to_owned()));
}
/// Lists what other people have shared with this user.
pub fn load_shared<A: CloudApp>(app: &mut A) {
if !available(app) {
return;
}
app.cloud_mut().shared.begin("");
submit(app, Job::SharedWithMe);
}
/// Begins linking a cloud account.
pub fn link<A: CloudApp>(app: &mut A) {
if !available(app) {
return;
}
app.cloud_mut().link = Some(Link::Starting);
submit(app, Job::LinkStart);
}
/// Asks where to work together on the open document, then opens it.
///
/// Only offered where the provider reports it. A document that has never been
/// in the cloud has no handle to key a room on, so there is nothing to ask
/// about either.
pub fn work_together<A: CloudApp>(app: &mut A) {
if !available(app) {
return;
}
let Some(id) = origin(app).map(|o| o.entry.id.clone()) else {
let noun = app.kind().noun;
app.cloud_mut().status = Some(app.tr(&format!("Save this {noun} to the cloud first")));
return;
};
converse(app, id);
}
/// Asks the provider where to work together on one document.
fn converse<A: CloudApp>(app: &mut A, id: String) {
let opening = app.tr("Opening a conversation");
app.cloud_mut().status = Some(opening);
submit(app, Job::Conversation(id));
}
/// The parent of a path. `None` at the root.
pub fn parent_of(path: &str) -> Option<String> {
let trimmed = path.trim_end_matches('/');
if trimmed.is_empty() {
return None;
}
match trimmed.rfind('/') {
Some(0) | None => Some(String::new()),
Some(cut) => Some(trimmed[..cut].to_owned()),
}
}
/// Whether this application can open an entry, judged by its extension and by
/// what the provider says it is.
///
/// Both signals are read because neither is reliable alone. A WebDAV server
/// hands back `application/octet-stream` for a perfectly good spreadsheet. A
/// file exported by a web application often has a correct content type and no
/// extension at all.
pub fn opens(entry: &Entry, kind: DocumentKind) -> bool {
if entry.kind == EntryKind::Folder {
return false;
}
let extension = entry.name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
let by_name = extension.is_some_and(|e| kind.extensions.contains(&e.as_str()));
by_name || entry.mime.as_deref().is_some_and(|mime| mime_opens(mime, kind))
}
fn mime_opens(mime: &str, kind: DocumentKind) -> bool {
let mime = mime.split(';').next().unwrap_or("").trim().to_ascii_lowercase();
kind.mimes.iter().any(|known| mime.starts_with(known))
}
/// A typed name as a document file name. Any folder separators are dropped and
/// a missing or unknown extension becomes the application's own.
pub fn document_name(typed: &str, kind: DocumentKind) -> String {
let base = typed.rsplit(['/', '\\']).next().unwrap_or("").trim();
if base.is_empty() {
return String::new();
}
let known = base.rsplit_once('.').is_some_and(|(stem, ext)| !stem.is_empty() && kind.extensions.contains(&ext.to_ascii_lowercase().as_str()));
if known { base.to_owned() } else { format!("{base}.{}", kind.default_extension) }
}
/// One sentence with a value in it, translated whole.
///
/// The template reaches [`CloudApp::tr`] with its `{}` intact. A translator
/// sees the whole sentence and can put the value where their own language
/// wants it. A sentence assembled from translated fragments cannot be made to
/// read correctly in a language that orders them differently.
fn fill<A: CloudApp>(app: &A, template: &str, value: &str) -> String {
app.tr(template).replacen("{}", value, 1)
}
/// A file name without its extension.
fn stem_of(name: &str) -> String {
match name.rsplit_once('.') {
Some((stem, _)) if !stem.is_empty() => stem.to_owned(),
_ => name.to_owned(),
}
}
// ---------------------------------------------------------------- opening
/// Reads a document and opens it. `into` names an open document the bytes
/// replace, which is how a reload after a conflict works.
pub fn open_entry<A: CloudApp>(app: &mut A, entry: Entry, into: Option<u64>) {
if !available(app) || app.cloud().busy.is_some() {
return;
}
let cloud = app.cloud_mut();
cloud.status = None;
cloud.busy = Some(Busy::Opening { name: entry.name.clone() });
submit(app, Job::Read { entry, into });
}
/// Reads the active document's stored copy again. Local edits are discarded.
pub fn reload_active<A: CloudApp>(app: &mut A) -> Result<Json, String> {
let noun = app.kind().noun;
let Some(uid) = app.active() else { return Err(format!("no {noun} open")) };
let Some(origin) = app.cloud().origins.get(&uid).cloned() else { return Err(format!("this {noun} did not come from the cloud")) };
app.cloud_mut().conflict = None;
let name = origin.entry.name.clone();
open_entry(app, origin.entry, Some(uid));
Ok(json!({"reloading": name}))
}
// ---------------------------------------------------------------- saving
/// The cloud document the active one came from, when it came from one.
pub fn origin<A: CloudApp>(app: &A) -> Option<&Origin> {
let uid = app.active()?;
app.cloud().origins.get(&uid)
}
/// Whether Save has somewhere to go without asking. A Backstage view uses this
/// to choose between Save and the Save As page.
pub fn has_target<A: CloudApp>(app: &A) -> bool {
origin(app).is_some_and(|o| o.entry.writable)
}
/// Save: writes back over the entry this document came from.
///
/// The etag the document was read at goes out as the condition. A server whose
/// copy has moved on refuses the write. That arrives as [`Fault::Conflict`] and
/// is put to the user. It is never retried.
pub fn save<A: CloudApp>(app: &mut A) -> Result<Json, String> {
let noun = app.kind().noun;
let uid = app.active().ok_or(format!("no {noun} open"))?;
let origin = app.cloud().origins.get(&uid).cloned().ok_or(format!("this {noun} did not come from the cloud"))?;
if !origin.entry.writable {
return Err("this document was shared with you for reading only. Save As keeps a copy of your own.".to_owned());
}
if app.cloud().busy.is_some() {
return Err("a cloud transfer is already running".to_owned());
}
let bytes = app.encode(uid, Destination { name: &origin.entry.name, mime: origin.entry.mime.as_deref() })?;
let size = bytes.len();
let cloud = app.cloud_mut();
cloud.status = None;
cloud.busy = Some(Busy::Saving { name: origin.entry.name.clone(), bytes: size });
let answer = json!({"saving": origin.entry.name, "bytes": size, "ifMatch": origin.entry.etag});
submit(app, Job::Write { uid, entry: origin.entry, bytes });
Ok(answer)
}
/// Save As: writes a new document into `folder` under `name`.
pub fn save_as<A: CloudApp>(app: &mut A, folder: &str, name: &str) -> Result<Json, String> {
let kind = app.kind();
let uid = app.active().ok_or(format!("no {} open", kind.noun))?;
let name = document_name(name, kind);
if name.is_empty() {
return Err("type a file name".to_owned());
}
if app.cloud().busy.is_some() {
return Err("a cloud transfer is already running".to_owned());
}
// A document that does not exist yet has no content type to read. The
// name a person just typed is the whole of what was asked for.
let bytes = app.encode(uid, Destination::new(&name))?;
let size = bytes.len();
let cloud = app.cloud_mut();
cloud.status = None;
cloud.busy = Some(Busy::Saving { name: name.clone(), bytes: size });
let answer = json!({"saving": name, "folder": folder, "bytes": size});
submit(app, Job::Create { uid, folder: folder.to_owned(), name, bytes });
Ok(answer)
}
// ---------------------------------------------------------------- reading the answers
/// Drains the host's answers and keeps a link or a transfer moving. Called
/// once a frame, before anything is drawn.
pub fn pump<A: CloudApp>(app: &mut A, ctx: &egui::Context) {
if !available(app) {
return;
}
app.cloud_mut().clock = ctx.input(|i| i.time);
// Taken in one pass, then applied. An answer that arrives because of a job
// this frame sent belongs to the next frame. A worker on its own thread
// would have delivered it that way anyway.
let mut arrived = Vec::new();
while let Ok(event) = app.cloud().events.1.try_recv() {
arrived.push(event);
}
for event in arrived {
apply(app, event);
}
poll_link(app);
// A worker answering is not a local event. Without this the progress line
// would sit frozen until the user moved the mouse.
if app.cloud().busy.is_some() || matches!(app.cloud().link, Some(Link::Starting | Link::Waiting { .. })) {
ctx.request_repaint_after(Duration::from_millis(120));
}
}
fn apply<A: CloudApp>(app: &mut A, event: Event) {
let noun = app.kind().noun;
match event {
Event::Account(Ok(account)) => {
let linked = account.provider_linked;
// Who is signed in has changed, so what the provider can do may
// have changed with it. The dialog keeps its first answer, and on a
// cold start that answer is "nobody is signed in".
app.sharing().refresh();
let cloud = app.cloud_mut();
cloud.account = Some(account);
cloud.account_fault = None;
if linked {
cloud.link = None;
} else if cloud.link.is_none() {
cloud.link = Some(Link::Offered);
}
}
// No account linked yet is a state with an obvious next step. It is an
// offer to link, and never an error message.
Event::Account(Err(Fault::NotLinked)) => {
let cloud = app.cloud_mut();
cloud.account_fault = None;
if cloud.link.is_none() {
cloud.link = Some(Link::Offered);
}
}
Event::Account(Err(fault)) => app.cloud_mut().account_fault = Some(fault),
Event::Conversation(Ok(conversation)) => {
let said = fill(app, "Opened in {}", &conversation.name);
app.cloud_mut().status = Some(said);
app.open_conversation(&conversation.url);
}
Event::Conversation(Err(fault)) => {
let text = fault.text(noun);
app.cloud_mut().status = Some(text);
}
Event::Browser { url, handle } => {
app.open_url(&url);
let next_poll = app.cloud().clock + LINK_POLL;
app.cloud_mut().link = Some(Link::Waiting { url, handle, next_poll });
}
Event::Linked(Ok(true)) => {
// Storage just arrived, so ask what it can do.
app.sharing().refresh();
let linked = app.tr("Cloud account linked.");
let cloud = app.cloud_mut();
cloud.link = None;
cloud.status = Some(linked);
cloud.asked_account = false;
submit(app, Job::Account);
browse(app, "");
app.cloud_mut().shared.loaded = false;
}
// The ordinary answer while the user is still in the browser.
Event::Linked(Ok(false)) | Event::Linked(Err(Fault::NotLinked)) => {}
Event::Linked(Err(fault)) => app.cloud_mut().link = Some(Link::Failed(fault)),
Event::Listed { path, entries } => {
let cloud = app.cloud_mut();
if path == cloud.mine.path {
cloud.mine.fill(entries);
}
}
Event::Shared(entries) => app.cloud_mut().shared.fill(entries),
Event::Read { entry, into, bytes } => {
app.cloud_mut().busy = None;
match bytes {
Ok(bytes) => opened(app, entry, into, bytes),
Err(Fault::NotLinked) => app.cloud_mut().link = Some(Link::Offered),
Err(fault) => {
let text = format!("{}. {}", fill(app, "{} could not be opened", &entry.name), fault.text(noun));
app.say(text);
}
}
}
Event::Saved { uid, entry } => {
app.cloud_mut().busy = None;
match entry {
Ok(entry) => {
app.mark_saved(uid);
stored(app, uid, entry);
}
// The one failure that must never be retried and never forced.
Err(Fault::Conflict) => {
app.drop_pending(uid);
match app.cloud().origins.get(&uid).cloned() {
Some(origin) => app.cloud_mut().conflict = Some(Conflict { uid, entry: origin.entry }),
None => app.say(Fault::Conflict.text(noun)),
}
}
Err(Fault::NotLinked) => {
app.drop_pending(uid);
app.cloud_mut().link = Some(Link::Offered);
}
Err(fault) => {
app.drop_pending(uid);
let text = format!("{} {}", app.tr(&format!("The {noun} was not saved.")), fault.text(noun));
app.say(text);
}
}
}
}
}
/// Bytes arrived. The application opens them. The document then remembers
/// where they came from.
fn opened<A: CloudApp>(app: &mut A, entry: Entry, into: Option<u64>, bytes: Vec<u8>) {
let name = entry.name.clone();
match app.open_bytes(&name, bytes) {
Ok(now) => {
if let Some(uid) = now {
app.cloud_mut().origins.insert(uid, Origin { entry });
}
// A reload closes the document it replaced only once the new one is
// open. A read that fails leaves the user's work where it was.
if let (Some(old), Some(new)) = (into, now)
&& old != new
{
let cloud = app.cloud_mut();
cloud.origins.remove(&old);
app.drop_pending(old);
app.close(old);
}
if now.is_some() {
let said = fill(app, "Opened {} from the cloud.", &name);
app.cloud_mut().status = Some(said);
}
}
Err(reason) => app.say(reason),
}
}
/// A save landed. The document now belongs to the entry the server returned, at
/// the version it returned.
fn stored<A: CloudApp>(app: &mut A, uid: u64, entry: Entry) {
let name = entry.name.clone();
let line = fill(app, "Saved {} to the cloud.", &name);
app.toast(fill(app, "Saved {} to the cloud", &name));
let cloud = app.cloud_mut();
cloud.conflict = None;
cloud.status = Some(line);
cloud.origins.insert(uid, Origin { entry });
}
/// Keeps asking whether the user has finished linking in their browser.
fn poll_link<A: CloudApp>(app: &mut A) {
let now = app.cloud().clock;
let handle = {
let Some(Link::Waiting { handle: Some(handle), next_poll, .. }) = &mut app.cloud_mut().link else { return };
if now < *next_poll {
return;
}
*next_poll = now + LINK_POLL;
handle.clone()
};
submit(app, Job::LinkPoll(handle));
}
// ---------------------------------------------------------------- reporting
/// The whole of the cloud state, for a control channel and for tests.
pub fn report<A: CloudApp>(app: &A) -> Json {
let kind = app.kind();
let cloud = app.cloud();
let account = cloud.account.as_ref().map(|a| {
json!({
"display": a.display,
"providerLinked": a.provider_linked,
"capabilities": a.capabilities.iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect::<Vec<_>>(),
})
});
let came_from = origin(app)
.map(|o| json!({"id": o.entry.id, "room": o.entry.room, "name": o.entry.name, "etag": o.entry.etag, "writable": o.entry.writable}));
json!({
"available": cloud.available(),
"account": account,
"accountError": cloud.account_fault.as_ref().map(Fault::code),
"folder": cloud.mine.path,
"entries": cloud.mine.entries.iter().map(|e| e.name.clone()).collect::<Vec<_>>(),
"openable": cloud.mine.entries.iter().filter(|e| opens(e, kind)).map(|e| e.name.clone()).collect::<Vec<_>>(),
"shared": cloud.shared.entries.iter().map(|e| json!({"name": e.name, "sharedBy": e.shared_by, "writable": e.writable, "openable": opens(e, kind)})).collect::<Vec<_>>(),
"busy": cloud.busy.as_ref().map(Busy::text),
"link": match &cloud.link {
None => Json::Null,
Some(Link::Offered) => json!("offered"),
Some(Link::Starting) => json!("starting"),
Some(Link::Waiting { url, .. }) => json!({"waiting": url}),
Some(Link::Failed(fault)) => json!({"failed": fault.code()}),
},
"conflict": cloud.conflict.as_ref().map(|c| json!({"name": c.entry.name})),
"origin": came_from,
"status": cloud.status,
"guest": cloud.guest.as_ref().map(|g| json!({"recipient": g.recipient, "readOnly": g.read_only})),
})
}
// ---------------------------------------------------------------- shared drawing
/// Bytes as a person reads them.
pub fn size_text(bytes: Option<u64>) -> String {
let Some(bytes) = bytes else { return String::new() };
const UNITS: [&str; 4] = ["bytes", "KB", "MB", "GB"];
let mut size = bytes as f64;
let mut unit = 0;
while size >= 1024.0 && unit + 1 < UNITS.len() {
size /= 1024.0;
unit += 1;
}
match UNITS.get(unit) {
Some(name) if unit > 0 => format!("{size:.1} {name}"),
_ => format!("{bytes} bytes"),
}
}
fn dim(ui: &mut Ui, style: &CloudStyle, text: &str) {
ui.label(RichText::new(text).font(egui::FontId::new(12.5, style.family.clone())).color(style.dim));
}
/// A bordered column with a heading. This is how the two Open sources sit side
/// by side.
fn column(ui: &mut Ui, style: &CloudStyle, heading: &str, body: impl FnOnce(&mut Ui)) {
egui::Frame::NONE.fill(style.surface).stroke(Stroke::new(1.0, style.border)).corner_radius(6.0).inner_margin(10).show(ui, |ui| {
ui.label(RichText::new(heading).font(egui::FontId::new(13.0, style.bold.clone())).color(style.text));
ui.add_space(6.0);
egui::ScrollArea::vertical().id_salt(heading.to_owned()).max_height(300.0).auto_shrink([false, false]).show(ui, body);
});
}
/// One row in a file list, with a second line for the detail that matters on
/// that side of the page (a size for your own files, who shared it for
/// somebody else's).
fn entry_row<A: CloudApp>(app: &A, ui: &mut Ui, entry: &Entry, detail: &str, reserve: f32) -> egui::Response {
let style = app.style(ui);
let width = (ui.available_width() - reserve).max(60.0);
let (rect, resp) = ui.allocate_exact_size(vec2(width, 40.0), Sense::click());
let label = entry.name.clone();
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &label));
let p = ui.painter();
if resp.hovered() {
p.rect_filled(rect, 4.0, style.hover);
}
app.paint_icon(p, Rect::from_center_size(pos2(rect.left() + 18.0, rect.center().y), vec2(18.0, 18.0)), entry.kind, style.text);
let (name_y, detail_y) = if detail.is_empty() { (rect.center().y, rect.center().y) } else { (rect.center().y - 8.0, rect.center().y + 9.0) };
p.text(pos2(rect.left() + 38.0, name_y), Align2::LEFT_CENTER, &entry.name, egui::FontId::new(13.0, style.family.clone()), style.text);
if !detail.is_empty() {
p.text(pos2(rect.left() + 38.0, detail_y), Align2::LEFT_CENTER, detail, egui::FontId::new(11.0, style.family.clone()), style.dim);
}
resp
}
+511
View File
@@ -0,0 +1,511 @@
//! The Backstage pages: File › Open and File › Save As, and the modal a
//! refused save puts up.
//!
//! Every side of a page is drawn only where the service reported the
//! capability behind it. A list under a heading the provider cannot fill reads
//! to a user as a broken window, so the heading goes too.
use craft_cloud::{Capability, Entry, EntryKind};
use egui::{RichText, Ui};
use super::{
CloudApp, Link, Source, browse, column, converse, dim, document_name, entry_row, fill, link, load_shared, open_entry, opens, parent_of,
reload_active, save_as, size_text, start, stem_of,
};
/// The character a label ends with when choosing it opens a dialog.
const ELLIPSIS: &str = "\u{2026}";
/// What an overflow menu asked for, deferred until the list is no longer being
/// drawn. Opening a dialog while borrowing the list is not possible.
enum Act {
Share(Entry),
Talk(Entry),
}
/// The account line, or the reason there is nothing to show yet.
fn header<A: CloudApp>(app: &mut A, ui: &mut Ui) {
let style = app.style(ui);
let mut retry = false;
match (&app.cloud().account, &app.cloud().account_fault) {
(_, Some(fault)) => {
let text = fault.text(app.kind().noun);
let again = app.tr("Try again");
ui.horizontal(|ui| {
dim(ui, &style, &text);
if ui.button(again).clicked() {
retry = true;
}
});
}
(Some(account), None) => {
let line = if account.display.is_empty() { app.tr("Signed in") } else { account.display.clone() };
dim(ui, &style, &line);
}
(None, None) => {
let waiting = app.tr("Connecting to your cloud account…");
dim(ui, &style, &waiting);
}
}
if retry {
let cloud = app.cloud_mut();
cloud.account_fault = None;
cloud.asked_account = false;
start(app);
}
}
/// The offer to link an account, and the wait while the browser is open.
/// Returns true when it drew, because there is nothing else to show until an
/// account exists.
///
/// None of this is an error. The whole state means one thing: there is no
/// account yet, and linking one is a button away.
fn link_panel<A: CloudApp>(app: &mut A, ui: &mut Ui) -> bool {
let Some(state) = app.cloud().link.clone() else { return false };
let style = app.style(ui);
let noun = app.kind().noun;
let mut begin = false;
let mut cancel = false;
let mut browse_to: Option<String> = None;
let words = LinkWords {
none_yet: app.tr("No cloud account is linked yet."),
why: app.tr(&format!("Link one to open and save {noun}s in your cloud storage.")),
link_one: app.tr("Link a cloud account"),
starting: app.tr("Starting…"),
finish: app.tr("Finish linking in your browser."),
waiting: app.tr("Waiting for your browser…"),
open_in_browser: app.tr("Open in browser"),
copy_link: app.tr("Copy link"),
cancel: app.tr("Cancel"),
again: app.tr("Try again"),
};
egui::Frame::NONE.fill(style.soft).corner_radius(6.0).inner_margin(12).show(ui, |ui| match state {
Link::Offered => {
ui.label(RichText::new(&words.none_yet).font(egui::FontId::new(13.0, style.bold.clone())).color(style.text));
dim(ui, &style, &words.why);
ui.add_space(8.0);
begin = ui.button(&words.link_one).clicked();
}
Link::Starting => {
ui.horizontal(|ui| {
ui.add(egui::Spinner::new().size(14.0));
dim(ui, &style, &words.starting);
});
}
Link::Waiting { url, .. } => {
ui.label(RichText::new(&words.finish).font(egui::FontId::new(13.0, style.bold.clone())).color(style.text));
ui.horizontal(|ui| {
ui.add(egui::Spinner::new().size(14.0));
dim(ui, &style, &words.waiting);
});
ui.add_space(6.0);
// A link alone is not enough. When the browser cannot be opened,
// or opens the wrong thing, the only way out is carrying the
// address across by hand, and a label cannot be selected.
ui.horizontal(|ui| {
if ui.button(&words.open_in_browser).clicked() {
browse_to = Some(url.clone());
}
if ui.button(&words.copy_link).clicked() {
ui.ctx().copy_text(url.clone());
}
});
ui.add_space(4.0);
if ui.link(&url).clicked() {
browse_to = Some(url.clone());
}
ui.add_space(8.0);
cancel = ui.button(&words.cancel).clicked();
}
Link::Failed(fault) => {
ui.label(RichText::new(fault.text(noun)).font(egui::FontId::new(13.0, style.family.clone())).color(style.text));
ui.add_space(8.0);
begin = ui.button(&words.again).clicked();
}
});
if let Some(url) = browse_to {
app.open_url(&url);
}
if begin {
link(app);
} else if cancel {
app.cloud_mut().link = Some(Link::Offered);
}
true
}
/// The panel's strings, read before it is drawn. The application is borrowed
/// mutably inside the frame, so nothing can be asked of it there.
struct LinkWords {
none_yet: String,
why: String,
link_one: String,
starting: String,
finish: String,
waiting: String,
open_in_browser: String,
copy_link: String,
cancel: String,
again: String,
}
/// The progress line for a read or a write in flight.
pub fn progress<A: CloudApp>(app: &A, ui: &mut Ui) {
let Some(busy) = app.cloud().busy.clone() else { return };
let style = app.style(ui);
ui.horizontal(|ui| {
ui.add(egui::Spinner::new().size(15.0));
ui.label(RichText::new(busy.text()).font(egui::FontId::new(12.5, style.family.clone())).color(style.text));
});
}
/// The `…` beside a document, and what a person chose from it.
///
/// Only the actions the provider actually offers appear. A greyed-out item says
/// the action exists and is not possible right now. An absent one says this
/// provider does not do that at all, and those are different facts.
fn row_actions<A: CloudApp>(app: &A, ui: &mut Ui, entry: &Entry) -> Option<String> {
let can = |c: Capability| app.cloud().account.as_ref().is_some_and(|a| a.can(c));
let mut items = vec![crate::menu::MenuItem::new("open", app.tr("Open"))];
if can(Capability::Sharing) {
items.push(
crate::menu::MenuItem::new("share", format!("{}{}", app.tr("Share"), ELLIPSIS))
.detail(app.tr("See who this is shared with, and invite somebody"))
.separated(),
);
}
if can(Capability::Conversation) {
items.push(crate::menu::MenuItem::new("talk", app.tr("Work together")).detail(app.tr("Open a conversation about this document")));
}
let labels = crate::menu::MenuLabels { more: app.tr("More options"), ..Default::default() };
// Salted by the handle. Two rows drawing the same control need two menus,
// and the handle is the one thing that differs between them.
ui.push_id(entry.id.clone(), |ui| crate::menu::overflow(ui, &items, &labels)).inner
}
/// File › Open, the cloud part. Your own files sit on one side and what other
/// people shared with you sits on the other.
pub fn open_page<A: CloudApp>(app: &mut A, ui: &mut Ui) {
start(app);
header(app, ui);
ui.add_space(8.0);
if link_panel(app, ui) {
return;
}
progress(app, ui);
// Hidden where the provider has no incoming shares at all. An empty list
// under that heading would read as a broken feature.
let shared_offered = app.cloud().account.as_ref().is_some_and(|a| a.can(Capability::SharedWithMe));
if shared_offered && !app.cloud().shared.loaded && !app.cloud().shared.loading {
load_shared(app);
}
let mut pick: Option<(Entry, Source)> = None;
let mut go: Option<String> = None;
let mut act: Option<Act> = None;
if shared_offered {
ui.columns(2, |columns| {
if let Some(ui) = columns.get_mut(0) {
my_files(app, ui, &mut pick, &mut go, &mut act);
}
if let Some(ui) = columns.get_mut(1) {
shared_files(app, ui, &mut pick, &mut act);
}
});
} else {
my_files(app, ui, &mut pick, &mut go, &mut act);
}
match act {
// Sharing a document in the list, which is not the one that happens to
// be open. The dialog is told which.
Some(Act::Share(entry)) => app.sharing().open(entry.id.clone(), entry.name.clone()),
Some(Act::Talk(entry)) => converse(app, entry.id.clone()),
None => {}
}
if let Some(path) = go {
browse(app, &path);
} else if let Some((entry, source)) = pick {
app.cloud_mut().source = source;
open_entry(app, entry, None);
}
if let Some(status) = app.cloud().status.clone() {
let style = app.style(ui);
ui.add_space(10.0);
dim(ui, &style, &status);
}
}
/// Your own files: where you are, a way up, then the folders and the documents
/// this application can open.
fn my_files<A: CloudApp>(app: &mut A, ui: &mut Ui, pick: &mut Option<(Entry, Source)>, go: &mut Option<String>, act: &mut Option<Act>) {
let style = app.style(ui);
let kind = app.kind();
let folder = app.cloud().mine.clone();
let heading = app.tr("My files");
let (home, up, loading) = (app.tr("Home"), app.tr("Up"), app.tr("Loading…"));
let nothing = app.tr(&format!("Nothing here that {} can open.", app.app_name()));
column(ui, &style, &heading, |ui| {
let here = if folder.path.is_empty() { home } else { folder.path.clone() };
ui.horizontal(|ui| {
if let Some(parent) = parent_of(&folder.path)
&& ui.button(&up).clicked()
{
*go = Some(parent);
}
dim(ui, &style, &here);
});
ui.add_space(4.0);
if folder.loading {
ui.horizontal(|ui| {
ui.add(egui::Spinner::new().size(14.0));
dim(ui, &style, &loading);
});
return;
}
if let Some(fault) = &folder.error {
dim(ui, &style, &fault.text(kind.noun));
return;
}
let mut shown = 0;
for entry in &folder.entries {
let is_folder = entry.kind == EntryKind::Folder;
if !is_folder && !opens(entry, kind) {
continue;
}
shown += 1;
let detail = if is_folder { String::new() } else { size_text(entry.size) };
// A folder has nothing behind an ellipsis. Opening it is the only
// thing to do with one here.
let reserve = if is_folder { 0.0 } else { 26.0 };
let (row, chose) = ui
.horizontal(|ui| {
let row = entry_row(app, ui, entry, &detail, reserve).clicked();
let chose = if is_folder { None } else { row_actions(app, ui, entry) };
(row, chose)
})
.inner;
match chose.as_deref() {
Some("share") => *act = Some(Act::Share(entry.clone())),
Some("talk") => *act = Some(Act::Talk(entry.clone())),
Some("open") => *pick = Some((entry.clone(), Source::Mine)),
_ if row => {
if is_folder {
*go = Some(entry.path.clone());
} else {
*pick = Some((entry.clone(), Source::Mine));
}
}
_ => {}
}
}
if shown == 0 && folder.loaded {
dim(ui, &style, &nothing);
}
});
}
/// What other people shared with you. One flat list, because an incoming share
/// has no folder of yours to sit in. Each row says who shared it.
fn shared_files<A: CloudApp>(app: &mut A, ui: &mut Ui, pick: &mut Option<(Entry, Source)>, act: &mut Option<Act>) {
let style = app.style(ui);
let kind = app.kind();
let shared = app.cloud().shared.clone();
let heading = app.tr("Shared with me");
let (loading, with_you, read_only) = (app.tr("Loading…"), app.tr("Shared with you"), app.tr("read-only"));
let nobody = app.tr(&format!("Nobody has shared a {} with you.", kind.noun));
column(ui, &style, &heading, |ui| {
if shared.loading {
ui.horizontal(|ui| {
ui.add(egui::Spinner::new().size(14.0));
dim(ui, &style, &loading);
});
return;
}
if let Some(fault) = &shared.error {
dim(ui, &style, &fault.text(kind.noun));
return;
}
let mut shown = 0;
for entry in shared.entries.iter().filter(|e| opens(e, kind)) {
shown += 1;
let who = entry.shared_by.clone().unwrap_or_else(|| with_you.clone());
let detail = if entry.writable { who } else { format!("{who} ({read_only})") };
let (row, chose) = ui
.horizontal(|ui| {
let row = entry_row(app, ui, entry, &detail, 26.0).clicked();
(row, row_actions(app, ui, entry))
})
.inner;
match chose.as_deref() {
Some("share") => *act = Some(Act::Share(entry.clone())),
Some("talk") => *act = Some(Act::Talk(entry.clone())),
_ if row || chose.is_some() => *pick = Some((entry.clone(), Source::Shared)),
_ => {}
}
}
if shown == 0 && shared.loaded {
dim(ui, &style, &nobody);
}
});
}
/// File › Save As, the cloud destination. Pick a folder, name the file, save.
/// Returns true when a save started, so a Backstage view can return to the
/// document.
pub fn save_page<A: CloudApp>(app: &mut A, ui: &mut Ui) -> bool {
let style = app.style(ui);
let kind = app.kind();
start(app);
// The destination above already names the account. This line is here to
// say when something is wrong with it.
if app.cloud().account.is_none() || app.cloud().account_fault.is_some() {
header(app, ui);
ui.add_space(8.0);
}
if link_panel(app, ui) {
return false;
}
progress(app, ui);
if app.cloud().save_name.is_empty() {
let suggested = app.active().map(|uid| app.title(uid)).unwrap_or_default();
app.cloud_mut().save_name = document_name(&suggested, kind);
}
let folder = app.cloud().mine.clone();
let heading = app.tr("Folder");
let (home, up, loading) = (app.tr("Home"), app.tr("Up"), app.tr("Loading…"));
let only_folder = app.tr(&format!("No folders here. The {} saves in this one.", kind.noun));
let mut go: Option<String> = None;
column(ui, &style, &heading, |ui| {
let here = if folder.path.is_empty() { home } else { folder.path.clone() };
ui.horizontal(|ui| {
if let Some(parent) = parent_of(&folder.path)
&& ui.button(&up).clicked()
{
go = Some(parent);
}
dim(ui, &style, &here);
});
ui.add_space(4.0);
if folder.loading {
ui.horizontal(|ui| {
ui.add(egui::Spinner::new().size(14.0));
dim(ui, &style, &loading);
});
return;
}
if let Some(fault) = &folder.error {
dim(ui, &style, &fault.text(kind.noun));
return;
}
let mut folders = 0;
for entry in folder.entries.iter().filter(|e| e.kind == EntryKind::Folder) {
folders += 1;
if entry_row(app, ui, entry, "", 0.0).clicked() {
go = Some(entry.path.clone());
}
}
if folders == 0 && folder.loaded {
dim(ui, &style, &only_folder);
}
});
if let Some(path) = go {
browse(app, &path);
}
ui.add_space(12.0);
let (file_name, save_label) = (app.tr("File name"), app.tr("Save to the cloud"));
let mut asked = false;
ui.horizontal(|ui| {
ui.label(file_name);
let typing = ui.add(egui::TextEdit::singleline(&mut app.cloud_mut().save_name).desired_width(280.0));
asked = typing.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
});
ui.add_space(10.0);
let ready = app.cloud().busy.is_none() && !document_name(&app.cloud().save_name, kind).is_empty();
if ui.add_enabled(ready, egui::Button::new(save_label)).clicked() {
asked = true;
}
if let Some(note) = app.save_note() {
ui.add_space(8.0);
dim(ui, &style, &note);
}
// A provider with no conditional writes cannot refuse one, so a save here
// can land on top of somebody else's. Said plainly, because the user is the
// only one who can decide whether that matters.
if app.cloud().account.as_ref().is_some_and(|a| !a.can(Capability::Etags)) {
let warning = app.tr("This cloud account cannot detect a save that would overwrite somebody else's changes.");
ui.add_space(4.0);
dim(ui, &style, &warning);
}
if asked && ready && app.ready_to_save() {
let (folder, name) = (app.cloud().mine.path.clone(), app.cloud().save_name.clone());
match save_as(app, &folder, &name) {
Ok(_) => return true,
Err(error) => app.say(error),
}
}
false
}
/// A save refused because the stored copy had moved on.
///
/// Three ways out, and none of them throws anything away without saying so.
/// Reloading is the one a user usually wants, so it comes first. The text says
/// plainly that it discards their edits.
pub fn conflict_modal<A: CloudApp>(app: &mut A, ctx: &egui::Context) {
let Some(conflict) = app.cloud().conflict.clone() else { return };
let noun = app.kind().noun;
let words = ConflictWords {
title: app.tr(&format!("This {noun} was not saved")),
what: fill(
app,
"Somebody else saved {} while you were editing it. Nothing was written: saving now would overwrite their work.",
&conflict.entry.name,
),
yours: app.tr("Your own changes are still open here. Reloading replaces them with the stored copy."),
reload: app.tr("Reload from the cloud"),
copy: app.tr(&format!("Save as a copy{ELLIPSIS}")),
keep: app.tr("Keep editing"),
};
let mut reload = false;
let mut copy = false;
let mut dismiss = false;
egui::Modal::new(egui::Id::new("craft-ui/cloud/conflict")).show(ctx, |ui| {
let style = app.style(ui);
ui.set_width(430.0);
ui.label(RichText::new(&words.title).font(egui::FontId::new(15.0, style.bold.clone())));
ui.add_space(8.0);
ui.add(egui::Label::new(&words.what).wrap());
ui.add_space(6.0);
ui.add(egui::Label::new(&words.yours).wrap());
ui.add_space(12.0);
ui.horizontal(|ui| {
reload = ui.button(&words.reload).clicked();
copy = ui.button(&words.copy).clicked();
dismiss = ui.button(&words.keep).clicked();
});
});
if reload {
app.cloud_mut().conflict = None;
if let Err(error) = reload_active(app) {
app.say(error);
}
} else if copy {
let name = document_name(&format!("{} (copy)", stem_of(&conflict.entry.name)), app.kind());
let cloud = app.cloud_mut();
cloud.conflict = None;
cloud.save_name = name;
app.go_to_save_as();
} else if dismiss {
app.cloud_mut().conflict = None;
}
}
/// The modal's strings, read before it is drawn.
struct ConflictWords {
title: String,
what: String,
yours: String,
reload: String,
copy: String,
keep: String,
}
+573
View File
@@ -0,0 +1,573 @@
//! The pages driven by an application that holds no documents.
//!
//! The point of these is the seam. A fake application answers every question
//! [`CloudApp`] asks and records what it was told to do, so what crosses the
//! boundary is visible without a spreadsheet, a service or a window.
use std::sync::{Arc, Mutex};
use craft_cloud::{Capability, Entry, EntryKind};
use super::*;
/// Everything the fake application was asked to do.
#[derive(Default)]
struct Did {
opened: Vec<String>,
closed: Vec<u64>,
encoded: Vec<u64>,
/// The name each encode was asked for, which is where the bytes go.
encoded_as: Vec<String>,
/// The content type beside it, where the provider gave one.
encoded_mime: Vec<Option<String>>,
marked_saved: Vec<u64>,
dropped: Vec<u64>,
said: Vec<String>,
toasted: Vec<String>,
urls: Vec<String>,
conversations: Vec<String>,
went_to_save_as: usize,
}
const NOTES: DocumentKind =
DocumentKind { extensions: &["note", "txt"], mimes: &["text/plain", "application/x-note"], noun: "note", default_extension: "note" };
struct Notebook {
cloud: CloudFiles,
share: crate::share::ShareDialog,
presence: crate::presence::PresenceBar,
/// The document in the window, and what it is called.
open: Option<(u64, String)>,
/// What the next `open_bytes` answers with.
opens_as: Result<Option<u64>, String>,
did: Arc<Mutex<Did>>,
}
impl Notebook {
fn new() -> Notebook {
Notebook {
cloud: CloudFiles::new(),
share: crate::share::ShareDialog::new(),
presence: crate::presence::PresenceBar::new(),
open: Some((1, "Untitled")).map(|(uid, name)| (uid, name.to_owned())),
opens_as: Ok(Some(1)),
did: Arc::new(Mutex::new(Did::default())),
}
}
fn did(&self) -> std::sync::MutexGuard<'_, Did> {
self.did.lock().unwrap()
}
}
impl CloudApp for Notebook {
fn cloud(&self) -> &CloudFiles {
&self.cloud
}
fn cloud_mut(&mut self) -> &mut CloudFiles {
&mut self.cloud
}
fn kind(&self) -> DocumentKind {
NOTES
}
fn active(&self) -> Option<u64> {
self.open.as_ref().map(|(uid, _)| *uid)
}
fn title(&self, _uid: u64) -> String {
self.open.as_ref().map(|(_, name)| name.clone()).unwrap_or_default()
}
fn open_bytes(&mut self, name: &str, _bytes: Vec<u8>) -> Result<Option<u64>, String> {
self.did().opened.push(name.to_owned());
self.opens_as.clone()
}
fn encode(&mut self, uid: u64, into: Destination<'_>) -> Result<Vec<u8>, String> {
self.did().encoded.push(uid);
self.did().encoded_as.push(into.name.to_owned());
self.did().encoded_mime.push(into.mime.map(str::to_owned));
Ok(b"a note".to_vec())
}
fn close(&mut self, uid: u64) {
self.did().closed.push(uid);
}
fn mark_saved(&mut self, uid: u64) {
self.did().marked_saved.push(uid);
}
fn drop_pending(&mut self, uid: u64) {
self.did().dropped.push(uid);
}
fn sharing(&mut self) -> &mut crate::share::ShareDialog {
&mut self.share
}
fn presence(&mut self) -> &mut crate::presence::PresenceBar {
&mut self.presence
}
fn paint_icon(&self, _painter: &egui::Painter, _rect: egui::Rect, _kind: EntryKind, _colour: egui::Color32) {}
fn open_url(&self, url: &str) {
self.did.lock().unwrap().urls.push(url.to_owned());
}
fn open_conversation(&self, url: &str) {
self.did.lock().unwrap().conversations.push(url.to_owned());
}
fn say(&mut self, text: String) {
self.did().said.push(text);
}
fn toast(&mut self, text: String) {
self.did().toasted.push(text);
}
fn go_to_save_as(&mut self) {
self.did().went_to_save_as += 1;
}
fn app_name(&self) -> &str {
"Notes"
}
}
/// A service that answers on the calling thread, so a job submitted during a
/// test is answered before the next line.
struct Service(Arc<Mutex<Vec<Job>>>);
impl CloudBackend for Service {
fn submit(&self, job: Job, post: Post) {
let answer = match &job {
Job::Account | Job::SignIn => Some(Event::Account(Ok(Account {
display: "Ada Lovelace".to_owned(),
capabilities: vec![Capability::Files, Capability::Etags],
provider_linked: true,
}))),
Job::List(path) => Some(Event::Listed { path: path.clone(), entries: Ok(vec![file("/Minutes.note"), folder("/Archive")]) }),
Job::Read { entry, into } => Some(Event::Read { entry: entry.clone(), into: *into, bytes: Ok(b"a note".to_vec()) }),
Job::Write { uid, entry, .. } => {
let mut stored = entry.clone();
stored.etag = Some("v2".to_owned());
Some(Event::Saved { uid: *uid, entry: Ok(stored) })
}
_ => None,
};
self.0.lock().unwrap().push(job);
if let Some(event) = answer {
post.send(event);
}
}
}
fn file(path: &str) -> Entry {
Entry {
id: path.to_owned(),
room: format!("room:{path}"),
name: path.rsplit('/').next().unwrap_or(path).to_owned(),
path: path.to_owned(),
kind: EntryKind::File,
size: Some(2048),
modified: None,
mime: None,
etag: Some("v1".to_owned()),
writable: true,
shared_by: None,
}
}
fn folder(path: &str) -> Entry {
Entry { kind: EntryKind::Folder, size: None, etag: None, ..file(path) }
}
/// One frame's worth of draining, with no window.
fn pumped(app: &mut Notebook, ctx: &egui::Context) {
ctx.begin_pass(Default::default());
pump(app, ctx);
// Nothing is painted here, so the pass's textures go nowhere. egui insists
// they are accounted for rather than dropped on the floor.
ctx.end_pass().textures_delta.clear();
}
fn wired() -> (Notebook, Arc<Mutex<Vec<Job>>>, egui::Context) {
let mut app = Notebook::new();
let jobs = Arc::new(Mutex::new(Vec::new()));
app.cloud.connect(Service(jobs.clone()));
(app, jobs, egui::Context::default())
}
#[test]
fn nothing_is_offered_until_a_service_is_wired() {
let app = Notebook::new();
assert!(!available(&app), "a build with no service offers nothing cloud-shaped");
assert_eq!(report(&app)["available"], false);
}
#[test]
fn the_account_is_asked_for_once_per_run() {
let (mut app, jobs, ctx) = wired();
start(&mut app);
start(&mut app);
let asked = jobs.lock().unwrap().iter().filter(|j| matches!(j, Job::Account)).count();
assert_eq!(asked, 1, "a frame that asks again would ask on every frame");
pumped(&mut app, &ctx);
assert_eq!(report(&app)["account"]["display"], "Ada Lovelace");
}
#[test]
fn only_the_documents_this_application_opens_are_offered() {
let (mut app, _jobs, ctx) = wired();
start(&mut app);
pumped(&mut app, &ctx);
let listing = report(&app);
assert_eq!(listing["entries"], serde_json::json!(["Minutes.note", "Archive"]));
assert_eq!(listing["openable"], serde_json::json!(["Minutes.note"]), "a folder is not something to open");
}
#[test]
fn a_content_type_opens_a_document_with_no_extension() {
let mut exported = file("/exported");
exported.mime = Some("text/plain; charset=utf-8".to_owned());
assert!(opens(&exported, NOTES), "a provider that gives no extension still says what the bytes are");
let mut picture = file("/holiday");
picture.mime = Some("image/png".to_owned());
assert!(!opens(&picture, NOTES));
assert!(!opens(&folder("/Archive"), NOTES), "a folder opens nothing");
}
#[test]
fn a_typed_name_becomes_a_file_name_of_this_applications_own_kind() {
assert_eq!(document_name(" Minutes ", NOTES), "Minutes.note");
assert_eq!(document_name("Minutes.txt", NOTES), "Minutes.txt", "an extension this application opens is kept");
assert_eq!(document_name("Minutes.v2", NOTES), "Minutes.v2.note", "an unknown suffix is part of the name");
assert_eq!(document_name("/a/b/Minutes", NOTES), "Minutes.note", "a pasted path cannot become a folder");
assert_eq!(document_name(" ", NOTES), "");
}
#[test]
fn walking_up_from_the_root_has_nowhere_to_go() {
assert_eq!(parent_of(""), None);
assert_eq!(parent_of("/Archive"), Some(String::new()));
assert_eq!(parent_of("/Archive/2026"), Some("/Archive".to_owned()));
}
#[test]
fn opening_hands_the_bytes_to_the_application_and_remembers_the_entry() {
let (mut app, _jobs, ctx) = wired();
start(&mut app);
pumped(&mut app, &ctx);
open_entry(&mut app, file("/Minutes.note"), None);
pumped(&mut app, &ctx);
assert_eq!(app.did().opened, vec!["Minutes.note".to_owned()], "the application alone turns bytes into a document");
let origin = report(&app)["origin"].clone();
assert_eq!(origin["id"], "/Minutes.note", "the opaque handle is kept for the save");
assert_eq!(origin["etag"], "v1", "so is the version it was read at");
assert_eq!(origin["room"], "room:/Minutes.note", "and the collaboration identity, which is not the handle");
}
#[test]
fn a_reload_closes_the_document_it_replaced_only_once_the_new_one_is_open() {
let (mut app, _jobs, ctx) = wired();
app.opens_as = Ok(Some(2));
open_entry(&mut app, file("/Minutes.note"), Some(1));
pumped(&mut app, &ctx);
assert_eq!(app.did().closed, vec![1], "the one it replaced is gone");
assert_eq!(app.did().dropped, vec![1], "and so is whatever was recorded about saving it");
// A read the application could not use leaves the user's work where it was.
let (mut app, _jobs, ctx) = wired();
app.opens_as = Err("these bytes are not a note".to_owned());
open_entry(&mut app, file("/Minutes.note"), Some(1));
pumped(&mut app, &ctx);
assert!(app.did().closed.is_empty(), "nothing was closed, because nothing opened");
assert_eq!(app.did().said, vec!["these bytes are not a note".to_owned()]);
}
#[test]
fn a_document_the_application_took_elsewhere_is_not_announced() {
let (mut app, _jobs, ctx) = wired();
// What an application answers while it prompts for a password.
app.opens_as = Ok(None);
open_entry(&mut app, file("/Minutes.note"), None);
pumped(&mut app, &ctx);
assert_eq!(report(&app)["status"], serde_json::Value::Null);
assert_eq!(report(&app)["origin"], serde_json::Value::Null, "nothing came from the cloud yet");
}
#[test]
fn a_save_goes_out_under_the_version_the_document_was_read_at() {
let (mut app, jobs, ctx) = wired();
open_entry(&mut app, file("/Minutes.note"), None);
pumped(&mut app, &ctx);
save(&mut app).unwrap();
assert_eq!(app.did().encoded, vec![1], "the application alone turns a document into bytes");
assert_eq!(app.did().encoded_as, vec!["Minutes.note".to_owned()], "the bytes are asked for under the name they are going to");
let condition = jobs.lock().unwrap().iter().find_map(|j| match j {
Job::Write { entry, .. } => Some(entry.etag.clone()),
_ => None,
});
assert_eq!(condition, Some(Some("v1".to_owned())), "the etag it was read at is the condition");
pumped(&mut app, &ctx);
assert_eq!(app.did().marked_saved, vec![1], "the version that reached the service is the saved one");
assert_eq!(report(&app)["origin"]["etag"], "v2", "and the document moves on to the version the service returned");
}
#[test]
fn a_read_only_share_is_never_saved_over() {
let (mut app, _jobs, ctx) = wired();
let mut theirs = file("/Team.note");
theirs.writable = false;
open_entry(&mut app, theirs, None);
pumped(&mut app, &ctx);
assert!(!has_target(&app), "Save has nowhere of its own to go");
let refused = save(&mut app).unwrap_err();
assert!(refused.contains("reading only"), "and saying why names the fix: {refused}");
}
#[test]
fn a_refused_save_is_put_to_the_user_and_never_retried() {
let (mut app, jobs, ctx) = wired();
open_entry(&mut app, file("/Minutes.note"), None);
pumped(&mut app, &ctx);
jobs.lock().unwrap().clear();
// What a service answers when somebody else saved first.
app.cloud.events.0.send(Event::Saved { uid: 1, entry: Err(Fault::Conflict) }).unwrap();
pumped(&mut app, &ctx);
assert_eq!(report(&app)["conflict"]["name"], "Minutes.note", "the user is told, and asked what to do");
assert_eq!(app.did().dropped, vec![1], "the version that did not land is forgotten");
assert!(jobs.lock().unwrap().is_empty(), "nothing went out again on its own");
}
#[test]
fn no_account_yet_is_an_offer_to_link_and_never_an_error() {
let (mut app, _jobs, ctx) = wired();
app.cloud.events.0.send(Event::Account(Err(Fault::NotLinked))).unwrap();
pumped(&mut app, &ctx);
assert_eq!(report(&app)["link"], "offered");
assert_eq!(report(&app)["accountError"], serde_json::Value::Null, "not having linked an account yet is not a failure");
assert!(app.did().said.is_empty());
}
#[test]
fn a_browser_round_trip_is_polled_until_the_user_is_done() {
let (mut app, jobs, ctx) = wired();
app.cloud.events.0.send(Event::Browser { url: "https://cloud.example/link/abc".to_owned(), handle: Some("abc".to_owned()) }).unwrap();
pumped(&mut app, &ctx);
assert_eq!(app.did().urls, vec!["https://cloud.example/link/abc".to_owned()], "the browser is opened for them");
assert_eq!(report(&app)["link"]["waiting"], "https://cloud.example/link/abc");
// The wait is not polled again until it is due.
jobs.lock().unwrap().clear();
pumped(&mut app, &ctx);
assert!(jobs.lock().unwrap().iter().all(|j| !matches!(j, Job::LinkPoll(_))), "a poll every frame would be a poll every sixteen milliseconds");
if let Some(Link::Waiting { next_poll, .. }) = &mut app.cloud.link {
*next_poll = 0.0;
}
pumped(&mut app, &ctx);
assert!(jobs.lock().unwrap().iter().any(|j| matches!(j, Job::LinkPoll(_))));
}
#[test]
fn what_a_person_reads_is_about_their_own_kind_of_document() {
let app = Notebook::new();
assert_eq!(Fault::Conflict.text(app.kind().noun), "Somebody else saved this note while you were editing it.");
assert_eq!(Fault::Conflict.code(), "conflict", "and the control channel reads the same fact as a word");
}
#[test]
fn working_together_needs_somewhere_for_the_room_to_be_keyed_on() {
let (mut app, jobs, ctx) = wired();
app.cloud.account = Some(Account { display: "Ada".to_owned(), capabilities: vec![Capability::Conversation], provider_linked: true });
assert!(can_converse(&app));
// A document that has never been in the cloud has no handle.
work_together(&mut app);
assert_eq!(report(&app)["status"], "Save this note to the cloud first");
assert!(jobs.lock().unwrap().iter().all(|j| !matches!(j, Job::Conversation(_))));
open_entry(&mut app, file("/Minutes.note"), None);
pumped(&mut app, &ctx);
work_together(&mut app);
let asked = jobs.lock().unwrap().iter().any(|j| matches!(j, Job::Conversation(id) if id == "/Minutes.note"));
assert!(asked, "the provider is asked about the handle it issued");
}
#[test]
fn a_conversation_uses_the_hosts_chat_opener() {
let (mut app, _, ctx) = wired();
app.cloud
.events
.0
.send(Event::Conversation(Ok(craft_cloud::Conversation { url: "https://cloud.example.net/call/room".to_owned(), name: "Talk".to_owned() })))
.unwrap();
pumped(&mut app, &ctx);
assert_eq!(app.did().conversations, ["https://cloud.example.net/call/room"]);
assert!(app.did().urls.is_empty(), "ordinary browser links and conversations remain separate host decisions");
}
#[test]
fn signing_out_forgets_everything_this_window_knew() {
let (mut app, jobs, ctx) = wired();
start(&mut app);
pumped(&mut app, &ctx);
open_entry(&mut app, file("/Minutes.note"), None);
pumped(&mut app, &ctx);
sign_out(&mut app);
let state = report(&app);
assert_eq!(state["account"], serde_json::Value::Null);
assert_eq!(state["origin"], serde_json::Value::Null);
assert_eq!(state["entries"], serde_json::json!([]));
assert!(jobs.lock().unwrap().iter().any(|j| matches!(j, Job::SignOut)), "the service is told, so the saved token goes too");
}
#[test]
fn bytes_are_said_the_way_a_person_reads_them() {
assert_eq!(size_text(None), "");
assert_eq!(size_text(Some(512)), "512 bytes");
assert_eq!(size_text(Some(2048)), "2.0 KB");
assert_eq!(size_text(Some(5 * 1024 * 1024)), "5.0 MB");
}
#[test]
fn a_destination_is_named_after_the_account_it_belongs_to() {
let mut app = Notebook::new();
assert_eq!(destination_name(&app), "Cloud storage", "two entries reading the same tell nobody which account this is");
app.cloud.account = Some(Account { display: "Ada Lovelace".to_owned(), capabilities: Vec::new(), provider_linked: true });
assert_eq!(destination_name(&app), "Ada Lovelace");
}
#[test]
fn the_contracts_own_conflict_is_the_one_a_save_must_not_retry() {
assert_eq!(Fault::from(craft_cloud::Error::Conflict("Minutes.note".to_owned())), Fault::Conflict);
assert_eq!(Fault::from(craft_cloud::Error::Unauthenticated), Fault::Unauthenticated);
assert!(matches!(Fault::from(craft_cloud::Error::Unsupported("sharing")), Fault::Refused(_)));
}
#[test]
fn a_save_asks_for_the_bytes_under_the_name_they_are_going_to() {
// A document opened as one format and saved in the application's own would
// hand the user a file no other application reads, under a name that says
// it is readable. The application cannot avoid that without being told
// where the bytes are going.
let (mut app, _jobs, ctx) = wired();
let mut sheet = file("/figures.csv");
sheet.mime = Some("text/csv".to_owned());
open_entry(&mut app, sheet, None);
pumped(&mut app, &ctx);
save(&mut app).unwrap();
assert_eq!(app.did().encoded_as, vec!["figures.csv".to_owned()]);
assert_eq!(app.did().encoded_mime, vec![Some("text/csv".to_owned())], "the provider's own word for it comes too");
// And Save As, where the name is the one just typed rather than the one
// the document arrived under.
let (mut app, _jobs, ctx) = wired();
open_entry(&mut app, file("/figures.csv"), None);
pumped(&mut app, &ctx);
save_as(&mut app, "", "a copy.note").unwrap();
assert_eq!(app.did().encoded_as, vec!["a copy.note".to_owned()]);
assert_eq!(app.did().encoded_mime, vec![None], "nothing is there yet, so nothing says what it is");
}
#[test]
fn a_destination_reads_its_own_extension() {
assert_eq!(Destination::new("figures.csv").extension(), "csv");
assert_eq!(Destination::new("FIGURES.CSV").extension(), "csv", "a shouted name is the same name");
assert_eq!(Destination::new("report.2026.xlsx").extension(), "xlsx", "the last one wins");
// A bare name, which is what a web application's export commonly has.
// Everything an application can learn is in the content type instead.
assert_eq!(Destination::new("exported").extension(), "");
assert_eq!(Destination::new("trailing.").extension(), "");
}
// ---- somebody who followed a shared link ----------------------------------
/// One frame of the title bar's right-hand end, as the accessibility tree
/// reported it.
///
/// Read off the tree rather than out of the state, because the question is
/// what a recipient can reach. A field saying "no menu" proves nothing about
/// what was drawn.
fn title_bar(app: &mut Notebook) -> Vec<(egui::accesskit::Role, String)> {
let ctx = egui::Context::default();
ctx.enable_accesskit();
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 48.0))), ..Default::default() };
let mut output = ctx.run_ui(raw, |ui| who(app, ui));
output.textures_delta.clear();
let Some(tree) = output.platform_output.accesskit_update.as_ref() else { return Vec::new() };
tree.nodes
.iter()
.filter_map(|(_, node)| {
// egui puts a plain label's text in the accessibility value and a
// control's text in the label, so both are text on screen.
node.label().or_else(|| node.value()).map(|text| (node.role(), text.to_owned()))
})
.collect()
}
fn pressable(seen: &[(egui::accesskit::Role, String)]) -> Vec<String> {
seen.iter().filter(|(role, _)| *role == egui::accesskit::Role::Button).map(|(_, text)| text.clone()).collect()
}
fn reads(seen: &[(egui::accesskit::Role, String)], fragment: &str) -> bool {
seen.iter().any(|(_, text)| text.contains(fragment))
}
#[test]
fn a_recipient_is_named_and_offered_nothing() {
let mut app = Notebook::new();
app.cloud.as_guest("outsider@example.org", false);
let seen = title_bar(&mut app);
assert!(reads(&seen, "outsider@example.org"), "a recipient has no account, so their own address is the identity to show: {seen:?}");
// The whole point. Every item an account menu holds is a sign-out, a
// switch or a storage connection, and a recipient has none of those.
assert_eq!(pressable(&seen), Vec::<String>::new(), "nothing here may be pressed: {seen:?}");
for offer in ["Sign in", "Sign out", "Account", "Connect storage", "Add an account"] {
assert!(!reads(&seen, offer), "a recipient was offered {offer}");
}
}
#[test]
fn a_read_only_share_says_so_before_anybody_tries_to_save() {
let mut app = Notebook::new();
app.cloud.as_guest("outsider@example.org", true);
assert!(reads(&title_bar(&mut app), "Reading only"), "finding out at the moment of saving means doing the work twice");
app.cloud.as_guest("outsider@example.org", false);
assert!(!reads(&title_bar(&mut app), "Reading only"), "a share that allows an edit must not say otherwise");
}
#[test]
fn an_address_of_only_spaces_leaves_no_badge() {
let mut app = Notebook::new();
app.cloud.as_guest(" ", false);
assert!(app.cloud.guest().is_none(), "a badge with nothing on it reads as a fault");
assert_eq!(title_bar(&mut app), Vec::new());
}
#[test]
fn a_signed_in_window_still_gets_its_account_badge() {
let (mut app, _jobs, ctx) = wired();
start(&mut app);
pumped(&mut app, &ctx);
let seen = title_bar(&mut app);
assert!(!pressable(&seen).is_empty(), "somebody with an account still has a menu to reach: {seen:?}");
assert!(reads(&seen, "Ada Lovelace"));
}
#[test]
fn the_report_says_who_this_window_is_for() {
let mut app = Notebook::new();
assert_eq!(report(&app)["guest"], serde_json::Value::Null, "most windows belong to nobody in particular yet");
app.cloud.as_guest("outsider@example.org", true);
assert_eq!(report(&app)["guest"], serde_json::json!({"recipient": "outsider@example.org", "readOnly": true}));
}
+173
View File
@@ -0,0 +1,173 @@
//! The right-hand end of a title bar, plus the Save As destination.
//!
//! Who is signed in, who else is here, and Share. Every office suite puts
//! these three in the same corner, in that order. A person coming from one of
//! them looks there first.
use egui::{RichText, Ui};
use super::{CloudApp, CopyFormat, Guest, available, fill, link, origin, sign_in, sign_out, work_together};
/// Who this window is for. Who else is in the document, beside them.
///
/// Three cases, each a different person. Somebody signed in gets the account
/// badge and its menu. Somebody who followed a shared link gets their own
/// address and no menu, having no account to manage. A build with no service
/// configured gets neither. A badge that cannot sign anybody in would be a
/// control that fails on use.
///
/// Nothing is asked for here. Drawing a badge must not begin a sign-in: a
/// worker signs in before any job it is given, and it then blocks polling the
/// browser for minutes. Starting that from a paint call pops a browser open at
/// launch and leaves every later job queued behind it. Signing in is a gesture,
/// so it waits for a press.
pub fn who<A: CloudApp>(app: &mut A, ui: &mut Ui) {
match app.cloud().guest().cloned() {
Some(guest) => shared_with(app, ui, &guest),
None => account(app, ui),
}
// Who else is here, beside whoever this window belongs to. Nothing is
// drawn while a person is working alone, which keeps a solitary document
// looking like one.
if app.presence().shared() {
ui.add_space(6.0);
app.presence().show(ui);
}
}
/// Who a shared link was sent to, for somebody with no account anywhere.
///
/// A label and not a button. Every item an account menu holds is a sign-out, a
/// switch or a storage connection, and a recipient has none of those. A
/// control that opens a menu of failures is worse than no control.
fn shared_with<A: CloudApp>(app: &mut A, ui: &mut Ui, guest: &Guest) {
let explained = fill(app, "This document was shared with {}", &guest.recipient);
let reading = app.tr("Reading only");
let dim = ui.visuals().weak_text_color();
if guest.read_only {
// Said where the account would be. Both answer what this window may
// do with the document in it. A recipient who finds out at the moment
// of saving has already done the work twice.
ui.label(RichText::new(reading).small().color(dim));
ui.add_space(6.0);
}
ui.label(RichText::new(guest.recipient.as_str()).small().color(dim)).on_hover_text(explained);
}
/// The account badge and its menu, for somebody signed in.
fn account<A: CloudApp>(app: &mut A, ui: &mut Ui) {
if !available(app) {
return;
}
let service = app.service();
let known = app.cloud().account.as_ref().map(|a| crate::account::Account {
// One account for now. The control already holds a list, so a second
// deployment is a second entry here and nothing else changes.
id: "default".to_owned(),
display: a.display.clone(),
email: None,
service,
linked: a.provider_linked,
});
let new_accounts: Vec<_> = known.into_iter().collect();
let cloud = app.cloud_mut();
if cloud.accounts.accounts() != new_accounts.as_slice() {
cloud.accounts.set(new_accounts);
}
cloud.accounts.show(ui);
while let Some(action) = app.cloud_mut().accounts.take_action() {
use crate::account::AccountAction as Act;
match action {
// Signing in and connecting storage are two different things.
// Signing in is the device flow against the service, which every
// job already triggers when there is no token. Asking who the
// account is therefore starts it. Linking storage comes after, and
// needs that session to exist first.
Act::SignIn | Act::AddAccount => {
app.cloud_mut().sign_in_from_menu = true;
sign_in(app);
}
Act::Link(_) => link(app),
Act::SignOut(_) => sign_out(app),
// One account, so there is nothing to switch to yet.
Act::Use(_) => {}
Act::Manage(_) => {
let host = app.service();
if !host.is_empty() {
app.open_url(&format!("https://{host}/account"));
}
}
}
}
}
/// Whether the Share split button can be drawn.
///
/// False until the service says the provider supports sharing. An application
/// draws whatever it offered before. A button that fails on use is worse than
/// no button at all.
pub fn shares<A: CloudApp>(app: &mut A) -> bool {
app.sharing().available()
}
/// Share, as a split button.
///
/// Pressing the label shares, which is what somebody wants most of the time.
/// The chevron carries the variations, and working together is one of them.
/// `copies` are the application's own Save a Copy formats. Those have nothing
/// in common between one application and the next.
///
/// Answers with the identifier of a copy format, when that is what was chosen.
/// Everything else is carried out here.
pub fn share_button<A: CloudApp>(app: &mut A, ui: &mut Ui, copies: &[CopyFormat]) -> Option<String> {
let noun = app.kind().noun;
let mut items = Vec::new();
if app.cloud().can_converse() {
let detail = app.tr(&format!("Open a chat about this {noun}"));
items.push(crate::menu::MenuItem::new("talk", app.tr("Open chat")).detail(detail));
}
for (at, copy) in copies.iter().enumerate() {
let item = crate::menu::MenuItem::new(copy.id.clone(), copy.label.clone());
// A rule above the first copy, so sharing and exporting read as two
// groups rather than one long list.
items.push(if at == 0 && !items.is_empty() { item.separated() } else { item });
}
let labels = crate::menu::MenuLabels::default();
let primary = app.tr("Share");
match crate::menu::split(ui, &primary, &items, &labels)? {
crate::menu::SplitHit::Primary => {
// The handle the provider issued, which is what a share is about.
// A document that has never been in the cloud has none, and the
// dialog says so.
let (id, title) = match origin(app) {
Some(origin) => (origin.entry.id.clone(), origin.entry.name.clone()),
None => (String::new(), app.active().map(|uid| app.title(uid)).unwrap_or_default()),
};
app.sharing().open(id, title);
None
}
crate::menu::SplitHit::Item(what) if what == "talk" => {
work_together(app);
None
}
crate::menu::SplitHit::Item(format) => Some(format),
}
}
/// What to call the cloud destination on a Save As page.
///
/// The account's own name. The destination then reads as the user's own
/// storage. Somebody with an account on two deployments needs to know which
/// one a document is about to land in.
pub fn destination_name<A: CloudApp>(app: &A) -> String {
app.cloud().account.as_ref().map(|a| a.display.clone()).filter(|display| !display.is_empty()).unwrap_or_else(|| app.tr("Cloud storage"))
}
/// Whether the cloud destination is the one to offer first.
///
/// A document that came from the cloud is saved back there unless the user says
/// otherwise. One that came from this computer is not.
pub fn prefers_cloud<A: CloudApp>(app: &A) -> bool {
available(app) && origin(app).is_some()
}
+8
View File
@@ -5,9 +5,13 @@
//! Applications own their assets, themes, layouts, commands and document semantics. Components
//! accept focused style values and return egui responses; no application engine is required.
#[cfg(feature = "share")]
pub mod account;
pub mod backdrop;
pub mod buttons;
pub mod capture;
#[cfg(feature = "cloud")]
pub mod cloud;
pub mod combo;
pub mod direction;
pub mod docking;
@@ -17,9 +21,13 @@ pub mod icons;
pub mod ime;
pub mod layout;
pub mod localized;
pub mod menu;
pub mod panes;
pub mod presence;
pub mod printing;
pub mod shapes;
#[cfg(feature = "share")]
pub mod share;
pub mod tabs;
#[cfg(all(feature = "screen-testing", not(target_arch = "wasm32")))]
pub mod testing;
+222
View File
@@ -0,0 +1,222 @@
//! The two controls that offer more than one action.
//!
//! An overflow menu is the `…` that holds what did not earn a place on the
//! toolbar. A split button is a primary action with a chevron beside it, where
//! the chevron offers the variations. Share is the usual example. Most of the
//! time a person wants to share, and once in a while they want to copy a link
//! or start a call about the document instead.
//!
//! They are one module because they are the same control underneath. Building
//! them twice would mean getting the accessible naming right twice, and an
//! icon-only button that announces itself as an ellipsis character is useless
//! to anybody reading the screen rather than looking at it.
//!
//! Neither control knows what any item does. Each answers with the identifier
//! of the item a person chose. The application holds the meaning.
use egui::{Response, RichText, Ui};
/// One line in a menu.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MenuItem {
/// What the caller recognises this by. Never shown.
pub id: String,
pub label: String,
/// A second line, smaller. Worth having where the label alone leaves a
/// person guessing what the action will do to their document.
pub detail: Option<String>,
/// A leading glyph. Decoration only, so it is never the accessible name.
pub icon: Option<String>,
pub enabled: bool,
/// Draw a rule above this item. A group of related actions reads as a
/// group only when something separates it from the last one.
pub separator_before: bool,
}
impl MenuItem {
pub fn new(id: impl Into<String>, label: impl Into<String>) -> MenuItem {
MenuItem { id: id.into(), label: label.into(), enabled: true, ..MenuItem::default() }
}
pub fn detail(mut self, detail: impl Into<String>) -> MenuItem {
self.detail = Some(detail.into());
self
}
pub fn icon(mut self, icon: impl Into<String>) -> MenuItem {
self.icon = Some(icon.into());
self
}
/// Present but unavailable, with a reason on hover.
///
/// Greying an item out says the action exists and is not possible now.
/// Removing it says the action does not exist. They are different facts and
/// a person reads them differently.
pub fn disabled(mut self, why: impl Into<String>) -> MenuItem {
self.enabled = false;
self.detail = Some(why.into());
self
}
pub fn separated(mut self) -> MenuItem {
self.separator_before = true;
self
}
}
/// What a person did to a split button.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SplitHit {
/// They pressed the button itself.
Primary,
/// They chose something from the chevron's menu.
Item(String),
}
/// The accessible name of the chevron, and of the overflow button.
///
/// Public so an application can translate them. A glyph is not a name, and
/// these two are the only strings in this module that are not supplied by the
/// caller.
#[derive(Clone, Debug)]
pub struct MenuLabels {
/// The `…` button.
pub more: String,
/// The chevron on a split button. `{action}` is replaced with the primary
/// action's own label, so a screen reader says "more share options" rather
/// than "more options" on a toolbar holding four of them.
pub more_for: String,
}
impl Default for MenuLabels {
fn default() -> MenuLabels {
MenuLabels { more: "More options".into(), more_for: "More {action} options".into() }
}
}
/// The `…` button and its menu.
///
/// Answers with the identifier of the item chosen, if any.
pub fn overflow(ui: &mut Ui, items: &[MenuItem], labels: &MenuLabels) -> Option<String> {
// A horizontal ellipsis, not three periods. Three periods are three
// characters to anything reading the screen aloud.
let button = egui::Button::new(RichText::new("\u{2026}").size(15.0)).frame(false);
let hit = ui.add(button);
let name = labels.more.clone();
hit.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, name.as_str()));
let hit = hit.on_hover_text(labels.more.as_str());
items_of(&hit, items)
}
/// A primary action with a chevron beside it.
///
/// The two halves are two controls. Pressing the label does the thing. Pressing
/// the chevron offers the variations. One control that did both would leave a
/// person guessing which half they had hit.
pub fn split(ui: &mut Ui, primary: &str, items: &[MenuItem], labels: &MenuLabels) -> Option<SplitHit> {
let mut hit = None;
ui.horizontal(|ui| {
// The halves touch, so they read as one control with two parts. Square
// off the inside corners as well. Two default radii leave a pair of
// notches at the seam, which reads as two buttons that happen to abut.
ui.spacing_mut().item_spacing.x = 0.0;
let radius = ui.visuals().widgets.inactive.corner_radius;
// A toolbar that fills from its right edge hands this control a
// right-to-left layout, and whatever is added first lands furthest
// right. The label still belongs before the chevron, so the halves are
// added in the order that puts them there.
let backwards = ui.layout().main_dir() == egui::Direction::RightToLeft;
let (outer, inner) = if backwards {
(egui::CornerRadius { nw: 0, sw: 0, ..radius }, egui::CornerRadius { ne: 0, se: 0, ..radius })
} else {
(egui::CornerRadius { ne: 0, se: 0, ..radius }, egui::CornerRadius { nw: 0, sw: 0, ..radius })
};
let label = |ui: &mut Ui, hit: &mut Option<SplitHit>| {
if ui.add(egui::Button::new(primary).corner_radius(if backwards { inner } else { outer })).clicked() {
*hit = Some(SplitHit::Primary);
}
};
let chevron = |ui: &mut Ui, hit: &mut Option<SplitHit>| {
// Room for the triangle, which is painted rather than typed.
let more = ui.add(egui::Button::new(" ").corner_radius(if backwards { outer } else { inner }));
crate::buttons::chevron(ui, more.rect, ui.visuals().text_color());
let name = labels.more_for.replace("{action}", &primary.to_lowercase());
more.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, name.as_str()));
let more = more.on_hover_text(name.as_str());
if let Some(id) = items_of(&more, items) {
*hit = Some(SplitHit::Item(id));
}
};
if backwards {
chevron(ui, &mut hit);
label(ui, &mut hit);
} else {
label(ui, &mut hit);
chevron(ui, &mut hit);
}
});
hit
}
/// The menu both controls open.
fn items_of(anchor: &Response, items: &[MenuItem]) -> Option<String> {
let mut chosen = None;
egui::Popup::menu(anchor).show(|ui| {
ui.set_min_width(210.0);
let weak = ui.visuals().weak_text_color();
for item in items {
if item.separator_before {
ui.separator();
}
let label = match &item.icon {
Some(icon) => format!("{icon} {}", item.label),
None => item.label.clone(),
};
let row = ui.add_enabled(item.enabled, egui::Button::new(label).frame(false));
// The icon is decoration. The name is the label alone.
let name = item.label.clone();
let enabled = item.enabled;
row.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, enabled, name.as_str()));
if row.clicked() {
chosen = Some(item.id.clone());
ui.close();
}
if let Some(detail) = &item.detail {
ui.label(RichText::new(detail.as_str()).small().color(weak));
ui.add_space(2.0);
}
}
});
chosen
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_item_is_enabled_until_it_is_not() {
assert!(MenuItem::new("copy", "Copy link").enabled);
let off = MenuItem::new("copy", "Copy link").disabled("this server forbids public links");
assert!(!off.enabled);
assert_eq!(off.detail.as_deref(), Some("this server forbids public links"));
}
#[test]
fn the_chevrons_name_says_which_action_it_belongs_to() {
let labels = MenuLabels::default();
assert_eq!(labels.more_for.replace("{action}", "share"), "More share options");
}
#[test]
fn a_builder_keeps_what_it_was_given() {
let item = MenuItem::new("talk", "Work together").icon("\u{1f4de}").detail("Start a call").separated();
assert_eq!(item.id, "talk");
assert_eq!(item.label, "Work together");
assert_eq!(item.icon.as_deref(), Some("\u{1f4de}"));
assert_eq!(item.detail.as_deref(), Some("Start a call"));
assert!(item.separator_before);
assert!(item.enabled);
}
}
+424
View File
@@ -0,0 +1,424 @@
//! Who else is in the document.
//!
//! A person editing alone and a person editing alongside three colleagues are
//! in very different situations. Only one of them has to worry about somebody
//! else changing the cell they are about to type in. An application that shows
//! nothing leaves them to find out by surprise.
//!
//! So this is a row of badges, one per person, with the count folded into a
//! final badge once the row would get long. It is the same control every
//! collaborative editor puts in the same corner, for the same reason.
//!
//! A peer's colour comes from the peer's own identifier. Two things need to
//! agree on it: the badge here, and whatever the document draws at that
//! person's cursor. Deriving it rather than assigning it means they agree with
//! no state passed between them, and the colour survives a reconnection.
use egui::{Align, Color32, Layout, Response, RichText, Ui};
/// How wide a badge is, and how far the next one overlaps it.
const BADGE: f32 = 24.0;
const OVERLAP: f32 = 7.0;
/// Somebody else in the document right now.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Peer {
/// The session's own identifier, stable for as long as they are connected.
pub id: String,
/// What to show. A display name, never an identity.
pub display: String,
/// Where they are working, when the document can say. A spreadsheet knows
/// the cell. A word processor knows the page. Shown on hover only.
pub at: Option<String>,
}
impl Peer {
pub fn new(id: impl Into<String>, display: impl Into<String>) -> Peer {
Peer { id: id.into(), display: display.into(), at: None }
}
/// Where they are working, for the tooltip.
pub fn at(mut self, at: impl Into<String>) -> Peer {
self.at = Some(at.into());
self
}
/// The letter on the badge.
pub fn initial(&self) -> String {
self.display.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_else(|| "?".to_owned())
}
/// This peer's colour.
pub fn colour(&self) -> Color32 {
colour_for(&self.id)
}
}
/// How many colours the wheel carries.
///
/// Sixteen, spaced evenly. More than that and neighbouring slots stop being
/// distinguishable, which defeats the point of having them.
pub const SLOTS: usize = 16;
/// The colour in one slot of the wheel.
pub fn slot(index: usize) -> Color32 {
let step = 360.0 / SLOTS as f32;
// Alternate the lightness as the wheel turns, so two neighbouring hues are
// also two different weights. Hue alone is not enough for anybody who sees
// colour differently from the person who chose it.
let dim = index % 2 == 1;
hsv((index % SLOTS) as f32 * step, if dim { 0.66 } else { 0.52 }, if dim { 0.68 } else { 0.84 })
}
/// Which slot an identifier would like.
fn preferred(id: &str) -> usize {
// FNV-1a, which is small and has no dependency.
let mut hash: u32 = 0x811c_9dc5;
for byte in id.as_bytes() {
hash ^= u32::from(*byte);
hash = hash.wrapping_mul(0x0100_0193);
}
// Then an avalanche. FNV alone leaves keys that differ in one byte close
// together, and session ids from one relay run in sequence.
hash ^= hash >> 16;
hash = hash.wrapping_mul(0x7feb_352d);
hash ^= hash >> 15;
hash = hash.wrapping_mul(0x846c_a68b);
hash ^= hash >> 16;
hash as usize % SLOTS
}
/// A stable colour for one identifier, with nobody else to consider.
///
/// Public because the badge is not the only thing that needs it. Use
/// [`colours_for`] wherever a whole room is on screen. This one cannot promise
/// anything about the other people in it.
pub fn colour_for(id: &str) -> Color32 {
slot(preferred(id))
}
/// Colours for a whole room, every one distinguishable from the others.
///
/// Each peer prefers the slot its identifier hashes to. A peer whose slot is
/// already taken moves to the next free one, walking the list in a fixed order
/// so the answer does not depend on who connected first.
///
/// A document drawing remote cursors calls this with the same identifiers and
/// gets the same answer, which is what makes a cursor and the badge above it
/// the same person. That holds on one screen whatever else is happening,
/// since both calls see that client's own list.
///
/// Two clients mid-transition can disagree for a frame or two. One has seen
/// somebody join and the other has not, so the walk resolves differently
/// until both lists match. It settles by itself, and nobody is comparing two
/// screens while it does. The durable fix is for the relay to hand out slots
/// with the peer list, which takes a protocol change.
///
/// Beyond [`SLOTS`] peers the wheel repeats, since there is no seventeenth
/// colour anybody could tell from the first sixteen.
pub fn colours_for(ids: &[String]) -> Vec<Color32> {
let mut order: Vec<usize> = (0..ids.len()).collect();
order.sort_by(|a, b| ids[*a].cmp(&ids[*b]));
let mut taken = [false; SLOTS];
let mut out = vec![Color32::BLACK; ids.len()];
for position in order {
let want = preferred(&ids[position]);
let mut at = want;
for step in 0..SLOTS {
at = (want + step) % SLOTS;
if !taken[at] {
break;
}
}
taken[at] = true;
out[position] = slot(at);
}
out
}
fn hsv(hue: f32, saturation: f32, value: f32) -> Color32 {
let c = value * saturation;
let h = hue / 60.0;
let x = c * (1.0 - ((h % 2.0) - 1.0).abs());
let (r, g, b) = match h as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = value - c;
let to_byte = |f: f32| (f.clamp(0.0, 1.0) * 255.0).round() as u8;
Color32::from_rgb(to_byte(r + m), to_byte(g + m), to_byte(b + m))
}
/// Strings, so an application can translate them.
#[derive(Clone, Debug)]
pub struct PresenceLabels {
/// Said when nobody else is here. An application may leave this empty to
/// draw nothing at all in that case.
pub alone: String,
/// With one other person. `{name}` is replaced.
pub with_one: String,
/// With several. `{count}` is replaced.
pub with_many: String,
/// The badge that stands for the people who did not fit. `{count}` is
/// replaced.
pub and_more: String,
/// The accessible name of the whole row.
pub who: String,
}
impl Default for PresenceLabels {
fn default() -> PresenceLabels {
PresenceLabels {
alone: String::new(),
with_one: "Editing with {name}".into(),
with_many: "Editing with {count} others".into(),
and_more: "{count} more".into(),
who: "Who is here".into(),
}
}
}
/// The row of badges.
#[derive(Clone)]
pub struct PresenceBar {
peers: Vec<Peer>,
/// How many badges to draw before folding the rest into a count. Four is
/// what fits beside a title bar without crowding it.
shown: usize,
labels: PresenceLabels,
/// Whether to write the sentence beside the badges. A narrow toolbar wants
/// the badges alone.
summary: bool,
}
impl Default for PresenceBar {
fn default() -> PresenceBar {
PresenceBar::new()
}
}
impl PresenceBar {
pub fn new() -> PresenceBar {
PresenceBar { peers: Vec::new(), shown: 4, labels: PresenceLabels::default(), summary: true }
}
pub fn with_labels(mut self, labels: PresenceLabels) -> PresenceBar {
self.labels = labels;
self
}
/// How many badges before the row folds into a count.
pub fn with_shown(mut self, shown: usize) -> PresenceBar {
self.shown = shown.max(1);
self
}
/// Draw the badges only, with no sentence beside them.
pub fn badges_only(mut self) -> PresenceBar {
self.summary = false;
self
}
/// Replace the set of people in the document.
///
/// Takes the whole set rather than a change, because a session that missed
/// a departure would otherwise show somebody who left until the next
/// reconnection.
pub fn set(&mut self, peers: Vec<Peer>) {
self.peers = peers;
}
pub fn peers(&self) -> &[Peer] {
&self.peers
}
/// Whether anybody else is here. An application draws nothing when this is
/// false, which keeps a solitary document looking like one.
pub fn shared(&self) -> bool {
!self.peers.is_empty()
}
/// What the row says in words. Also the accessible summary.
pub fn summary(&self) -> String {
match self.peers.len() {
0 => self.labels.alone.clone(),
1 => self.peers.first().map(|p| self.labels.with_one.replace("{name}", &p.display)).unwrap_or_default(),
n => self.labels.with_many.replace("{count}", &n.to_string()),
}
}
/// Draw it. Answers with the peer a person clicked, when they clicked one.
///
/// A click is worth answering because a name is where "take me to what
/// they are editing" belongs. The application decides whether it can.
pub fn show(&mut self, ui: &mut Ui) -> Option<String> {
if self.peers.is_empty() {
if !self.labels.alone.is_empty() {
ui.label(RichText::new(self.labels.alone.as_str()).small().color(ui.visuals().weak_text_color()));
}
return None;
}
let mut clicked = None;
ui.horizontal(|ui| {
// Badges overlap, the way a stack of cards does. Without it four
// circles read as four separate controls instead of one group.
ui.spacing_mut().item_spacing.x = -OVERLAP;
// Right to left, so the first person sits on top of the stack.
//
// Allocated to just the width the badges need. A right-to-left
// layout given the whole container takes it, which pushes the row
// to the far edge of a toolbar and strands the sentence after it.
let shown = self.peers.len().min(self.shown);
let hidden = self.peers.len().saturating_sub(self.shown);
let count = shown + usize::from(hidden > 0);
let width = BADGE + (count.saturating_sub(1) as f32) * (BADGE - OVERLAP);
ui.allocate_ui_with_layout(egui::vec2(width, BADGE), Layout::right_to_left(Align::Center), |ui| {
if hidden > 0 {
let more = self.labels.and_more.replace("{count}", &hidden.to_string());
let weak = ui.visuals().widgets.inactive.bg_fill;
let badge = badge(ui, &format!("+{hidden}"), weak, ui.visuals().text_color());
badge.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, more.as_str()));
badge.on_hover_text(self.peers.iter().skip(self.shown).map(|p| p.display.as_str()).collect::<Vec<_>>().join("\n"));
}
let ids: Vec<String> = self.peers.iter().map(|p| p.id.clone()).collect();
let colours = colours_for(&ids);
for (at, peer) in self.peers.iter().enumerate().take(self.shown).rev() {
let ink = colours.get(at).copied().unwrap_or_else(|| peer.colour());
let hit = badge(ui, &peer.initial(), ink, Color32::WHITE);
let name = peer.display.clone();
hit.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, name.as_str()));
let tip = match &peer.at {
Some(at) => format!("{}\n{at}", peer.display),
None => peer.display.clone(),
};
if hit.on_hover_text(tip).clicked() {
clicked = Some(peer.id.clone());
}
}
});
if self.summary {
ui.spacing_mut().item_spacing.x = 8.0;
ui.label(RichText::new(self.summary()).small().color(ui.visuals().weak_text_color()));
}
});
clicked
}
}
/// One round badge. Painted as a button so it is focusable and announces
/// itself, which a bare circle would not.
fn badge(ui: &mut Ui, text: &str, fill: Color32, ink: Color32) -> Response {
let button = egui::Button::new(RichText::new(text).color(ink).size(11.0).strong())
.fill(fill)
.corner_radius(BADGE / 2.0)
.min_size(egui::vec2(BADGE, BADGE))
.stroke(egui::Stroke::new(1.5, ui.visuals().panel_fill));
ui.add(button)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_colour_is_the_same_every_time_for_the_same_peer() {
assert_eq!(colour_for("session-a"), colour_for("session-a"));
}
/// How far apart two colours are, summed over the channels. Crude, and
/// enough to tell "two different oranges" from "orange and teal".
fn apart(a: Color32, b: Color32) -> i32 {
(i32::from(a.r()) - i32::from(b.r())).abs() + (i32::from(a.g()) - i32::from(b.g())).abs() + (i32::from(a.b()) - i32::from(b.b())).abs()
}
fn ids(of: &[&str]) -> Vec<String> {
of.iter().map(|s| (*s).to_owned()).collect()
}
#[test]
fn a_room_of_sequential_ids_is_a_room_of_distinguishable_colours() {
// The shape a relay actually hands out. A colour derived from one id
// alone cannot promise this, which is how six people came out looking
// like two.
let room = ids(&["s1", "s2", "s3", "s4", "s5", "s6"]);
let colours = colours_for(&room);
for (i, a) in colours.iter().enumerate() {
for (j, b) in colours.iter().enumerate().skip(i + 1) {
let distance = apart(*a, *b);
assert!(distance >= 60, "{} and {} are {distance} apart", room[i], room[j]);
}
}
}
#[test]
fn a_full_wheel_is_still_all_distinct() {
let room: Vec<String> = (0..SLOTS).map(|n| format!("session-{n}")).collect();
let colours = colours_for(&room);
for (i, a) in colours.iter().enumerate() {
for (j, b) in colours.iter().enumerate().skip(i + 1) {
assert!(apart(*a, *b) > 0, "{} and {} share a colour", room[i], room[j]);
}
}
}
#[test]
fn the_same_room_always_gets_the_same_colours() {
let room = ids(&["b", "a", "c"]);
assert_eq!(colours_for(&room), colours_for(&room));
}
#[test]
fn the_answer_does_not_depend_on_who_connected_first() {
let one = colours_for(&ids(&["a", "b", "c"]));
let other = colours_for(&ids(&["c", "b", "a"]));
// Same people, listed backwards. Each still gets the colour it had.
assert_eq!(one, other.into_iter().rev().collect::<Vec<_>>());
}
#[test]
fn a_colour_is_dark_enough_to_hold_white_text() {
for id in ["a", "b", "zzz", "session-41", "", "\u{1f600}"] {
let c = colour_for(id);
// Rec. 601 luma, which is what readability of white ink tracks.
let luma = 0.299 * f32::from(c.r()) + 0.587 * f32::from(c.g()) + 0.114 * f32::from(c.b());
assert!(luma < 200.0, "{id:?} gave a colour too pale for white text, luma {luma}");
}
}
#[test]
fn an_empty_room_is_not_shared_and_says_nothing() {
let bar = PresenceBar::new();
assert!(!bar.shared());
assert_eq!(bar.summary(), "");
}
#[test]
fn one_other_person_is_named_and_several_are_counted() {
let mut bar = PresenceBar::new();
bar.set(vec![Peer::new("1", "Ann Reed")]);
assert_eq!(bar.summary(), "Editing with Ann Reed");
bar.set(vec![Peer::new("1", "Ann Reed"), Peer::new("2", "Bob Vine")]);
assert_eq!(bar.summary(), "Editing with 2 others");
}
#[test]
fn a_departure_leaves_nobody_behind() {
let mut bar = PresenceBar::new();
bar.set(vec![Peer::new("1", "Ann Reed"), Peer::new("2", "Bob Vine")]);
bar.set(vec![Peer::new("1", "Ann Reed")]);
assert_eq!(bar.peers().len(), 1, "the whole set replaces the old one");
}
#[test]
fn an_initial_survives_a_name_that_starts_oddly() {
assert_eq!(Peer::new("1", "ann").initial(), "A");
assert_eq!(Peer::new("1", "").initial(), "?");
assert_eq!(Peer::new("1", "\u{e9}lodie").initial(), "\u{c9}");
}
}
+170
View File
@@ -0,0 +1,170 @@
//! Where the share dialog's work happens, which is never on the frame.
//!
//! Every call a share needs is blocking, and a blocking call inside `update()`
//! freezes the window for as long as the server takes. So the dialog states
//! what it wants and reads answers off a channel, and something behind this
//! trait does the waiting.
//!
//! The dialog itself opens no socket, which keeps it buildable for the web
//! and testable with no server. A host supplies the half that does, and this
//! crate never learns what it reaches.
use craft_cloud::{Capability, Contact, Permission, Share, ShareTarget};
/// One thing the dialog needs done.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Request {
/// What the provider behind the service can actually do.
Capabilities,
/// People matching what has been typed so far.
Lookup { query: String, limit: usize },
/// Who already has access to one document.
Access { id: String },
/// Give several people access at once.
Grant(Grant),
/// Take one existing share away.
Withdraw { share_id: String },
/// Where this document could be saved, so it can be shared.
///
/// Asked for only when there is nothing to share yet. A list rather than a
/// single answer, because more than one provider may be configured and the
/// user picks.
Destinations,
/// Link an account for a destination that is configured but not connected.
Link { destination: String },
/// One contact's picture, by the URL that contact carried.
///
/// A separate request because a search answering with ten people must not
/// cost ten pictures before anybody has looked at them. The dialog asks
/// for a picture when it first paints the row that needs it, once per URL.
Avatar { url: String },
}
/// A share to create, as the dialog has it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Grant {
/// A key the recipient must present. Only meaningful for a link share, and
/// refused by a server that does not allow one.
pub password: Option<String>,
/// The document, as an opaque handle the app was given.
pub id: String,
pub targets: Vec<ShareTarget>,
pub permission: Permission,
pub note: Option<String>,
pub notify: bool,
}
/// What came back.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Answer {
Capabilities {
capabilities: Vec<Capability>,
/// Whether this user has a cloud account attached at all.
linked: bool,
},
Lookup(Vec<Contact>),
Access(Vec<Share>),
/// Partial success is the ordinary case, so both halves come back.
Granted {
shared: Vec<Share>,
failed: Vec<Failure>,
},
Withdrawn {
share_id: String,
},
Destinations(Vec<Destination>),
/// An account was linked, so the destinations are worth asking for again.
Linked,
Avatar {
url: String,
/// Encoded image bytes, in whatever format the server sent. Decoding
/// is egui's image loaders' job, which the application installs.
bytes: Vec<u8>,
},
}
/// Somewhere a document could be saved.
///
/// `account` is what makes this choosable. Two entries reading "Cloud" tell
/// nobody which of their accounts a document is about to land in, which is the
/// one thing somebody needs to know before pressing it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Destination {
/// Opaque to the dialog, handed back with the save.
pub id: String,
/// What to show, such as the service's own name.
pub name: String,
/// Which account, when one is linked.
pub account: Option<String>,
/// False when the destination is configured but has no account yet. The
/// dialog offers a sign-in rather than a save.
pub linked: bool,
}
/// One recipient a share did not reach.
///
/// Named rather than counted. Sharing with five people where one address is
/// wrong shares with four and says which one failed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Failure {
pub target: ShareTarget,
pub code: String,
pub detail: String,
}
/// Where one answer goes.
///
/// Carries the sequence number of the request it answers. Autocomplete fires
/// per keystroke, and a service is free to answer the third query before the
/// second, so the dialog keeps the newest sequence it asked for and drops
/// anything older. Without that the list flickers between a stale set of
/// matches and a current one.
pub struct Replier {
seq: u64,
tx: std::sync::mpsc::Sender<(u64, Result<Answer, String>)>,
}
impl Replier {
pub(crate) fn new(seq: u64, tx: std::sync::mpsc::Sender<(u64, Result<Answer, String>)>) -> Replier {
Replier { seq, tx }
}
/// Which request this answers.
pub fn seq(&self) -> u64 {
self.seq
}
/// Another handle to the same answer slot, for a backend that has to give
/// up after moving the first one into a worker.
pub fn dup(&self) -> Replier {
Replier { seq: self.seq, tx: self.tx.clone() }
}
pub fn answer(self, answer: Answer) {
self.deliver(Ok(answer));
}
/// Say why it could not be done, in words a user can read.
pub fn refuse(self, reason: impl Into<String>) {
self.deliver(Err(reason.into()));
}
/// A dropped receiver means the dialog closed, which is not a failure.
fn deliver(self, result: Result<Answer, String>) {
let _ = self.tx.send((self.seq, result));
}
}
impl std::fmt::Debug for Replier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Replier").field("seq", &self.seq).finish()
}
}
/// Somewhere a [`Request`] can run without blocking a frame.
///
/// `submit` must return immediately. The answer arrives through `reply`
/// whenever it is ready, or never, which the dialog survives.
pub trait ShareBackend {
fn submit(&self, request: Request, reply: Replier);
}
File diff suppressed because it is too large Load Diff
+527
View File
@@ -0,0 +1,527 @@
//! The dialog's state machine, with no server and no window.
//!
//! What matters here is what the dialog does with answers: that it offers
//! nothing until the service says sharing exists, that an answer the user has
//! typed past is thrown away rather than painted, that a share reaching four
//! of five people says which one it missed, and that a picture nobody can
//! fetch is asked for once.
use std::sync::{Arc, Mutex};
use super::*;
/// A backend that records what was asked and answers nothing, so a test
/// decides when each answer arrives and in which order.
#[derive(Clone, Default)]
struct Silent(Arc<Mutex<Vec<Request>>>);
impl Silent {
fn seen(&self) -> Vec<Request> {
self.0.lock().map(|seen| seen.clone()).unwrap_or_default()
}
}
impl ShareBackend for Silent {
fn submit(&self, request: Request, _reply: Replier) {
if let Ok(mut seen) = self.0.lock() {
seen.push(request);
}
}
}
fn can(capabilities: Vec<Capability>) -> Answer {
Answer::Capabilities { capabilities, linked: true }
}
fn everything() -> Answer {
can(vec![Capability::Sharing, Capability::Contacts, Capability::Mail])
}
/// A connected dialog that has been told sharing works, open on one document.
fn ready() -> (Context, ShareDialog, Silent) {
let ctx = Context::default();
let backend = Silent::default();
let mut dialog = ShareDialog::new();
dialog.connect(backend.clone());
dialog.collect(&ctx);
dialog.receive(&ctx, 1, Ok(everything()));
dialog.open("files/budget.xlsx", "Budget");
(ctx, dialog, backend)
}
fn person(id: &str, name: &str) -> Contact {
Contact {
id: id.into(),
target: ShareTarget::User(id.into()),
name: name.into(),
email: Some(format!("{id}@example.com")),
avatar: None,
is_group: false,
}
}
fn share(id: &str, target: ShareTarget) -> Share {
Share { id: id.into(), target, display: None, permission: Permission::View, url: None, note: None, created: None }
}
#[test]
fn a_share_is_labelled_with_the_name_the_provider_gave() {
let labels = ShareLabels::default();
let mut one = share("s1", ShareTarget::User("adunn".to_owned()));
assert_eq!(super::share_label(&one, &labels), "adunn", "the handle is all there is");
one.display = Some("Ada Lovelace".to_owned());
assert_eq!(super::share_label(&one, &labels), "Ada Lovelace");
// A provider that answers with an empty string has said nothing.
one.display = Some(" ".to_owned());
assert_eq!(super::share_label(&one, &labels), "adunn");
let mut team = share("s2", ShareTarget::Group("eng".to_owned()));
team.display = Some("Engineering".to_owned());
assert_eq!(super::share_label(&team, &labels), format!("Engineering ({})", labels.group));
// A link is not a person and never carries one.
assert_eq!(super::share_label(&share("s3", ShareTarget::Link), &labels), labels.anyone_with_link);
}
#[test]
fn nothing_is_offered_until_the_service_says_sharing_exists() {
let ctx = Context::default();
let backend = Silent::default();
let mut dialog = ShareDialog::new();
assert!(!dialog.available(), "an unconnected dialog cannot share");
dialog.connect(backend.clone());
assert_eq!(backend.seen(), Vec::new(), "connecting alone asks nothing");
dialog.collect(&ctx);
assert_eq!(backend.seen(), vec![Request::Capabilities]);
// Still unanswered: the question is outstanding, so the answer is no.
assert!(!dialog.available());
dialog.open("files/budget.xlsx", "Budget");
assert!(!dialog.is_open(), "the dialog must not open before the answer");
// A provider with files but no sharing hides the feature rather than
// offering a button that fails.
dialog.receive(&ctx, 1, Ok(can(vec![Capability::Files, Capability::Contacts])));
assert!(!dialog.available());
dialog.open("files/budget.xlsx", "Budget");
assert!(!dialog.is_open());
dialog.receive(&ctx, 1, Ok(everything()));
assert!(dialog.available());
dialog.open("files/budget.xlsx", "Budget");
assert!(dialog.is_open());
}
#[test]
fn an_unlinked_account_cannot_share_even_where_the_provider_can() {
let ctx = Context::default();
let mut dialog = ShareDialog::new();
dialog.connect(Silent::default());
dialog.receive(&ctx, 1, Ok(Answer::Capabilities { capabilities: vec![Capability::Sharing], linked: false }));
assert!(!dialog.available());
}
#[test]
fn losing_sharing_closes_a_dialog_that_was_already_up() {
let (ctx, mut dialog, _) = ready();
assert!(dialog.is_open());
dialog.receive(&ctx, 1, Ok(can(vec![Capability::Files])));
assert!(!dialog.is_open(), "a dialog that cannot do anything must not stay up");
}
#[test]
fn opening_asks_who_already_has_access() {
let (_ctx, dialog, backend) = ready();
assert_eq!(backend.seen(), vec![Request::Capabilities, Request::Access { id: "files/budget.xlsx".into() }]);
assert!(dialog.is_open());
}
#[test]
fn an_unsaved_document_asks_where_it_could_go_and_never_about_a_handle() {
let ctx = Context::default();
let backend = Silent::default();
let mut dialog = ShareDialog::new();
dialog.connect(backend.clone());
dialog.collect(&ctx);
dialog.receive(&ctx, 1, Ok(everything()));
dialog.open("", "Book1");
assert!(dialog.is_open());
// Sharing an unsaved document means saving it first. The dialog therefore
// needs somewhere to offer. It asks nothing about a handle. There is none.
assert_eq!(backend.seen(), vec![Request::Capabilities, Request::Destinations]);
assert!(!backend.seen().iter().any(|r| matches!(r, Request::Access { .. })), "there is no handle to ask about");
}
#[test]
fn an_answer_the_user_has_typed_past_is_dropped() {
let (ctx, mut dialog, _) = ready();
let early = dialog.issue(Request::Lookup { query: "an".into(), limit: MATCHES });
let late = dialog.issue(Request::Lookup { query: "ann".into(), limit: MATCHES });
if let Some(sheet) = &mut dialog.open {
sheet.lookup = Some(late);
sheet.searching = true;
}
// The first query answers second, which is what a service under load
// does. Painting it would show matches for "an" under the text "ann".
dialog.receive(&ctx, late, Ok(Answer::Lookup(vec![person("ann", "Ann Reed")])));
dialog.receive(&ctx, early, Ok(Answer::Lookup(vec![person("andy", "Andy Shaw"), person("anna", "Anna Beck")])));
let sheet = dialog.open.as_ref().expect("still open");
assert_eq!(sheet.matches.len(), 1);
assert_eq!(sheet.matches.first().map(|c| c.name.as_str()), Some("Ann Reed"));
assert!(!sheet.searching);
}
#[test]
fn several_recipients_can_be_picked_and_each_only_once() {
let (_ctx, mut dialog, _) = ready();
let sheet = dialog.open.as_mut().expect("open");
for contact in [person("ann", "Ann Reed"), person("bob", "Bob Vine"), person("ann", "Ann Reed")] {
choose(sheet, &contact);
}
choose(
sheet,
&Contact {
id: "finance".into(),
target: ShareTarget::Group("finance".into()),
name: "Finance".into(),
email: None,
avatar: None,
is_group: true,
},
);
let picked: Vec<&ShareTarget> = sheet.chosen.iter().map(|c| &c.target).collect();
assert_eq!(
picked,
vec![&ShareTarget::User("ann".into()), &ShareTarget::User("bob".into()), &ShareTarget::Group("finance".into())],
"a group shares as a group, and picking the same person twice adds one chip"
);
assert!(sheet.query.is_empty(), "picking clears what was typed");
}
#[test]
fn a_share_reaching_four_of_five_names_the_fifth() {
let (ctx, mut dialog, _) = ready();
let sheet = dialog.open.as_mut().expect("open");
for who in ["ann", "bob", "cal", "dee"] {
choose(sheet, &person(who, who));
}
add(sheet, ShareTarget::Email("nobody@@".into()), "nobody@@".into(), None, None);
let granting = dialog.issue(Request::Grant(Grant {
id: "files/budget.xlsx".into(),
password: None,
targets: Vec::new(),
permission: Permission::Edit,
note: None,
notify: true,
}));
if let Some(sheet) = &mut dialog.open {
sheet.granting = Some(granting);
}
let shared: Vec<Share> =
["ann", "bob", "cal", "dee"].iter().enumerate().map(|(i, who)| share(&format!("s{i}"), ShareTarget::User((*who).into()))).collect();
let failed =
vec![Failure { target: ShareTarget::Email("nobody@@".into()), code: "invalid_address".into(), detail: "nobody@@ is not an address".into() }];
dialog.receive(&ctx, granting, Ok(Answer::Granted { shared, failed }));
let (shared, failed) = dialog.outcome();
assert_eq!(shared.len(), 4);
assert_eq!(failed.len(), 1, "a wrong address is named, not folded into one error");
assert_eq!(failed.first().map(|f| f.detail.as_str()), Some("nobody@@ is not an address"));
// The four that went through leave the picker; the one that did not stays,
// so correcting it is one edit rather than a retyped list.
let left = dialog.open.as_ref().expect("open");
assert_eq!(left.chosen.len(), 1);
assert_eq!(left.chosen.first().map(|c| &c.target), Some(&ShareTarget::Email("nobody@@".into())));
}
#[test]
fn a_refusal_that_stopped_the_whole_call_is_not_a_failed_recipient() {
let (ctx, mut dialog, _) = ready();
let granting = dialog.issue(Request::Grant(Grant {
id: "files/budget.xlsx".into(),
password: None,
targets: vec![ShareTarget::User("ann".into())],
permission: Permission::View,
note: None,
notify: false,
}));
if let Some(sheet) = &mut dialog.open {
sheet.granting = Some(granting);
}
dialog.receive(&ctx, granting, Err("sign in again".into()));
let sheet = dialog.open.as_ref().expect("open");
assert_eq!(sheet.error.as_deref(), Some("sign in again"));
assert!(sheet.failed.is_empty());
assert!(sheet.granting.is_none(), "the button must come back");
}
#[test]
fn a_successful_share_reloads_who_has_access() {
let (ctx, mut dialog, backend) = ready();
let granting = dialog.issue(Request::Grant(Grant {
id: "files/budget.xlsx".into(),
password: None,
targets: vec![ShareTarget::User("ann".into())],
permission: Permission::View,
note: None,
notify: false,
}));
if let Some(sheet) = &mut dialog.open {
sheet.granting = Some(granting);
}
dialog.receive(&ctx, granting, Ok(Answer::Granted { shared: vec![share("s1", ShareTarget::User("ann".into()))], failed: Vec::new() }));
let asked = backend.seen().iter().filter(|r| **r == Request::Access { id: "files/budget.xlsx".into() }).count();
assert_eq!(asked, 2, "the list is stale the moment a share succeeds");
}
#[test]
fn withdrawing_takes_it_off_the_list_and_only_then() {
let (ctx, mut dialog, backend) = ready();
let access = dialog.open.as_ref().and_then(|s| s.access_seq).expect("asked");
dialog.receive(
&ctx,
access,
Ok(Answer::Access(vec![share("s1", ShareTarget::User("ann".into())), share("s2", ShareTarget::Group("finance".into()))])),
);
dialog.apply(&ctx, vec![Act::Withdraw("s1".into())]);
let waiting = dialog.open.as_ref().expect("open");
assert_eq!(waiting.access.as_ref().map(Vec::len), Some(2), "it stays until the server agrees");
assert_eq!(waiting.withdrawing.len(), 1);
assert!(backend.seen().contains(&Request::Withdraw { share_id: "s1".into() }));
let seq = waiting.withdrawing.first().map(|(seq, _)| *seq).expect("in flight");
dialog.receive(&ctx, seq, Ok(Answer::Withdrawn { share_id: "s1".into() }));
let after = dialog.open.as_ref().expect("open");
assert_eq!(after.access.as_ref().map(|a| a.iter().map(|s| s.id.as_str()).collect::<Vec<_>>()), Some(vec!["s2"]));
assert!(after.withdrawing.is_empty());
}
#[test]
fn a_refused_withdrawal_leaves_the_share_and_says_why() {
let (ctx, mut dialog, _) = ready();
let access = dialog.open.as_ref().and_then(|s| s.access_seq).expect("asked");
dialog.receive(&ctx, access, Ok(Answer::Access(vec![share("s1", ShareTarget::User("ann".into()))])));
dialog.apply(&ctx, vec![Act::Withdraw("s1".into())]);
let seq = dialog.open.as_ref().and_then(|s| s.withdrawing.first().map(|(seq, _)| *seq)).expect("in flight");
dialog.receive(&ctx, seq, Err("you do not own this share".into()));
let sheet = dialog.open.as_ref().expect("open");
assert_eq!(sheet.access.as_ref().map(Vec::len), Some(1));
assert!(sheet.withdrawing.is_empty(), "the button must come back");
assert_eq!(sheet.error.as_deref(), Some("you do not own this share"));
}
#[test]
fn a_picture_is_asked_for_once_and_a_refusal_is_remembered() {
let (ctx, mut dialog, backend) = ready();
let url = "https://cloud.example.com/avatar/ann/64";
dialog.apply(&ctx, vec![Act::Avatar(url.into()), Act::Avatar(url.into())]);
let asked = backend.seen().iter().filter(|r| **r == Request::Avatar { url: url.into() }).count();
assert_eq!(asked, 1, "one row painted twice is one picture");
let seq = match dialog.avatars.get(url) {
Some(Avatar::Pending(seq)) => *seq,
other => panic!("expected a pending picture, got {other:?}"),
};
dialog.receive(&ctx, seq, Err("this build does not fetch contact pictures".into()));
assert_eq!(dialog.avatars.get(url), Some(&Avatar::Missing));
// Refused once is refused. Painting the row again must not ask again.
dialog.apply(&ctx, vec![Act::Avatar(url.into())]);
let asked = backend.seen().iter().filter(|r| **r == Request::Avatar { url: url.into() }).count();
assert_eq!(asked, 1);
// And a refused picture is the dialog's business, not the user's.
assert_eq!(dialog.open.as_ref().and_then(|s| s.error.clone()), None);
}
#[test]
fn an_unanswered_capability_question_is_asked_again_later() {
let ctx = Context::default();
let backend = Silent::default();
let mut dialog = ShareDialog::new();
dialog.connect(backend.clone());
dialog.collect(&ctx);
dialog.collect(&ctx);
assert_eq!(backend.seen().len(), 1, "a question already outstanding is not asked every frame");
dialog.asked = Some(-RETRY);
dialog.collect(&ctx);
assert_eq!(backend.seen().len(), 2, "one unreachable moment must not hide Share for the session");
dialog.receive(&ctx, 2, Ok(everything()));
dialog.asked = Some(-RETRY);
dialog.collect(&ctx);
assert_eq!(backend.seen().len(), 2, "an answered question is not asked again");
}
#[test]
fn what_counts_as_an_address() {
for typed in ["ann@example.com", " ann.reed+tag@mail.example.co.uk "] {
assert!(address(typed).is_some(), "{typed} is an address");
}
for typed in ["ann", "ann@", "@example.com", "ann@example", "ann reed@example.com", "ann@.com", "a@b@c.com", ""] {
assert!(address(typed).is_none(), "{typed} is not an address");
}
assert_eq!(address(" ann@example.com "), Some("ann@example.com".to_owned()), "the trim is kept");
}
#[test]
fn initials_come_from_the_name_and_never_from_an_index() {
assert_eq!(initials("Ann Reed"), "AR");
assert_eq!(initials("ann"), "A");
assert_eq!(initials("Ann Marie Reed"), "AM");
assert_eq!(initials(""), "");
assert_eq!(initials(" "), "");
assert_eq!(initials("Ærø Ødegård"), "ÆØ");
assert_eq!(initials("张 伟"), "张伟");
}
#[test]
fn every_kind_of_recipient_reads_as_something() {
let labels = ShareLabels::default();
assert_eq!(target_label(&ShareTarget::User("ann".into()), &labels), "ann");
assert_eq!(target_label(&ShareTarget::Group("finance".into()), &labels), "finance (group)");
assert_eq!(target_label(&ShareTarget::Email("ann@example.com".into()), &labels), "ann@example.com");
assert_eq!(target_label(&ShareTarget::Link, &labels), "Anyone with the link");
}
#[test]
fn a_failure_with_no_detail_still_says_something() {
let bare = Failure { target: ShareTarget::Link, code: "forbidden".into(), detail: " ".into() };
assert_eq!(describe(&bare), "forbidden");
let told = Failure { target: ShareTarget::Link, code: "forbidden".into(), detail: "link shares are off".into() };
assert_eq!(describe(&told), "link shares are off");
}
#[test]
fn two_contacts_never_share_one_picture_cache_entry() {
let one = avatar_uri("https://cloud.example.com/avatar/ann/64");
let two = avatar_uri("https://cloud.example.com/avatar/anna/64");
assert_ne!(one, two);
assert_eq!(one, avatar_uri("https://cloud.example.com/avatar/ann/64"), "the same URL is the same entry");
assert!(one.starts_with("bytes://"), "egui's own loaders have to recognize it");
}
fn ready_unsaved() -> (Context, ShareDialog, Silent) {
let ctx = Context::default();
let backend = Silent::default();
let mut dialog = ShareDialog::new();
dialog.connect(backend.clone());
dialog.collect(&ctx);
dialog.receive(&ctx, 1, Ok(everything()));
dialog.open("", "Book1");
(ctx, dialog, backend)
}
fn start_save(dialog: &mut ShareDialog, ctx: &Context, destination: &str, name: &str) -> u64 {
dialog.apply(ctx, vec![Act::SaveAs { destination: destination.into(), name: name.into() }]);
let request = dialog.take_save_request().expect("save was handed to the application");
assert_ne!(request.generation, 0, "taken saves carry the open sheet generation");
request.generation
}
#[test]
fn a_stale_save_completion_after_close_does_nothing() {
let (ctx, mut dialog, backend) = ready_unsaved();
let generation = start_save(&mut dialog, &ctx, "cloud", "Budget");
dialog.close();
assert!(!dialog.is_open());
dialog.saved("files/wrong.xlsx", "Wrong");
dialog.saved_if(generation, "files/wrong.xlsx", "Wrong");
assert!(!dialog.is_open());
assert!(
!backend.seen().iter().any(|r| matches!(r, Request::Access { id } if id == "files/wrong.xlsx")),
"a completion after close must not ask about the saved handle"
);
}
#[test]
fn a_stale_save_completion_after_reopening_another_document_does_nothing() {
let (ctx, mut dialog, backend) = ready_unsaved();
let generation = start_save(&mut dialog, &ctx, "cloud", "Budget");
dialog.close();
dialog.open("files/other.xlsx", "Other");
assert_eq!(dialog.open.as_ref().map(|s| s.id.as_str()), Some("files/other.xlsx"));
dialog.saved("files/budget.xlsx", "Budget");
dialog.saved_if(generation, "files/budget.xlsx", "Budget");
let sheet = dialog.open.as_ref().expect("still open on the other document");
assert_eq!(sheet.id, "files/other.xlsx");
assert_eq!(sheet.title, "Other");
assert!(sheet.saving.is_none());
assert!(
!backend.seen().iter().any(|r| matches!(r, Request::Access { id } if id == "files/budget.xlsx")),
"the first document's completion must not rebind the second"
);
}
#[test]
fn a_save_completion_on_the_same_open_updates_the_sheet() {
let (ctx, mut dialog, backend) = ready_unsaved();
let generation = start_save(&mut dialog, &ctx, "cloud", "Budget");
dialog.saved_if(generation, "files/budget.xlsx", "Budget");
let sheet = dialog.open.as_ref().expect("open");
assert_eq!(sheet.id, "files/budget.xlsx");
assert_eq!(sheet.title, "Budget");
assert!(sheet.saving.is_none());
assert!(backend.seen().iter().any(|r| matches!(r, Request::Access { id } if id == "files/budget.xlsx")));
}
#[test]
fn take_save_request_returns_the_open_sheet_generation() {
let (ctx, mut dialog, _) = ready_unsaved();
let before = dialog.sheet_generation();
assert_ne!(before, 0);
dialog.apply(&ctx, vec![Act::SaveAs { destination: "cloud".into(), name: "Budget".into() }]);
let request = dialog.take_save_request().expect("taken");
assert_eq!(request.generation, before);
assert_eq!(request.destination, "cloud");
assert_eq!(request.name, "Budget");
}
#[test]
fn a_closed_dialog_still_collects_and_reports_nothing() {
let (ctx, mut dialog, _) = ready();
dialog.close();
assert!(!dialog.is_open());
dialog.receive(&ctx, 99, Ok(Answer::Lookup(vec![person("ann", "Ann Reed")])));
dialog.receive(&ctx, 99, Err("gone".into()));
let (shared, failed) = dialog.outcome();
assert!(shared.is_empty() && failed.is_empty());
}
#[test]
fn pressing_return_takes_the_first_match_or_an_address() {
let (_ctx, mut dialog, _) = ready();
let sheet = dialog.open.as_mut().expect("open");
// With matches on screen, Return takes the one at the top.
sheet.query = "an".into();
sheet.matches = vec![person("ann", "Ann Reed"), person("andy", "Andy Shaw")];
commit(sheet);
assert_eq!(sheet.chosen.first().map(|c| &c.target), Some(&ShareTarget::User("ann".into())));
// With none, an address is taken as itself. Somebody with no account on
// this server is reached by address or not at all.
sheet.query = "outside@example.com".into();
commit(sheet);
assert_eq!(sheet.chosen.len(), 2);
assert_eq!(sheet.chosen.last().map(|c| &c.target), Some(&ShareTarget::Email("outside@example.com".into())));
// A name that matched nothing is not a recipient.
sheet.query = "nobody".into();
commit(sheet);
assert_eq!(sheet.chosen.len(), 2);
assert_eq!(sheet.query, "nobody", "and what was typed is left alone to be corrected");
}
+343
View File
@@ -0,0 +1,343 @@
//! Gated on the `share` feature, which is off by default.
#![cfg(feature = "share")]
//! Renders of the shared controls, for review.
//!
//! The other suites read the accessibility tree and never look at pixels. That
//! catches wrong wording and missing names. It cannot show whether a dialog
//! looks like it belongs in an office suite, and these two controls will sit in
//! every Craft app, so somebody has to be able to see them.
//!
//! Writes nothing unless `CRAFT_UI_RENDERS` names a directory. A suite that
//! wrote files on every run would turn a checkout dirty by testing it.
//!
//! ```sh
//! CRAFT_UI_RENDERS=/tmp/renders cargo test -p craft-ui --all-features --test renders
//! ```
use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use craft_cloud::{Capability, Contact, Permission, Share, ShareTarget};
use craft_ui::account::{Account, AccountMenu};
use craft_ui::presence::{Peer, PresenceBar};
use craft_ui::share::{Answer, Failure, Replier, Request, ShareBackend, ShareDialog};
use egui::{Context, Event, FullOutput, PointerButton, Pos2, RawInput, Rect, Theme, Visuals, accesskit, pos2, vec2};
use egui_kittest::{TestRenderer, wgpu::WgpuTestRenderer};
const DOCUMENT: &str = "files/Budget 2026.xlsx";
/// A backend that answers what a control needs and parks the rest.
#[derive(Clone, Default)]
struct Fake {
capabilities: Vec<Capability>,
access: Vec<Share>,
parked: Arc<Mutex<Vec<(Request, Replier)>>>,
}
impl ShareBackend for Fake {
fn submit(&self, request: Request, reply: Replier) {
match &request {
Request::Capabilities => {
reply.answer(Answer::Capabilities { capabilities: self.capabilities.clone(), linked: true });
}
Request::Access { .. } => reply.answer(Answer::Access(self.access.clone())),
_ => {
if let Ok(mut parked) = self.parked.lock() {
parked.push((request, reply));
}
}
}
}
}
impl Fake {
fn answer(&self, answer: Answer) {
let taken = self.parked.lock().ok().and_then(|mut p| if p.is_empty() { None } else { Some(p.remove(0)) });
if let Some((_, reply)) = taken {
reply.answer(answer);
}
}
}
/// One control, driven frame by frame, with the pixels kept.
struct Shot {
ctx: Context,
/// One renderer per context. A renderer shared between two contexts
/// takes a texture id from the first and is then asked by the second
/// to free one it never registered.
renderer: WgpuTestRenderer,
time: f64,
size: [f32; 2],
typing: bool,
/// The ground the control is painted on. Without it the render carries a
/// transparent background, which reads as a rendering fault.
fill: egui::Color32,
}
impl Shot {
fn new(theme: Theme, size: [f32; 2]) -> Shot {
let ctx = Context::default();
ctx.enable_accesskit();
let visuals = if theme == Theme::Dark { Visuals::dark() } else { Visuals::light() };
let fill = visuals.panel_fill;
ctx.set_visuals(visuals);
ctx.all_styles_mut(|style| {
style.animation_time = 0.0;
style.visuals.text_cursor.blink = false;
});
Shot { ctx, renderer: WgpuTestRenderer::new(), time: 0.0, size, typing: false, fill }
}
fn frame(&mut self, events: Vec<Event>, mut draw: impl FnMut(&mut egui::Ui)) -> FullOutput {
self.time += 1.0 / 60.0;
let raw = RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(self.size[0], self.size[1]))),
time: Some(self.time),
events,
..Default::default()
};
let ctx = self.ctx.clone();
if self.typing {
ctx.memory_mut(|m| m.request_focus(ShareDialog::query_field_id()));
}
let fill = self.fill;
let size = self.size;
let mut output = ctx.run_ui(raw, |ui| {
let screen = Rect::from_min_size(Pos2::ZERO, vec2(size[0], size[1]));
ui.painter().rect_filled(screen, 0.0, fill);
draw(ui);
});
// Every frame's delta has to reach the renderer. The font atlas arrives
// on the first frame, and a renderer that saw only the last one paints
// no text at all.
self.renderer.handle_delta(&mut output.textures_delta);
output
}
/// Write what the last frame drew.
fn save(&mut self, into: &std::path::Path, name: &str, theme: Theme, output: &FullOutput) {
let image = self.renderer.render(&self.ctx, output).expect("an offscreen renderer is required to write renders");
let suffix = if theme == Theme::Dark { "dark" } else { "light" };
let path = into.join(format!("{name}-{suffix}.png"));
image.save(&path).expect("the render directory must be writable");
println!("wrote {}", path.display());
}
/// Press the control carrying this exact accessible name.
fn click(&mut self, label: &str, draw: &mut impl FnMut(&mut egui::Ui)) {
let output = self.frame(Vec::new(), &mut *draw);
let Some(at) = control(&output, label) else { panic!("nothing to click named {label:?}; on screen are {:?}", controls(&output)) };
self.frame(vec![Event::PointerMoved(at)], &mut *draw);
self.frame(vec![press(at, true)], &mut *draw);
self.frame(vec![press(at, false)], &mut *draw);
}
}
fn press(at: Pos2, down: bool) -> Event {
Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: down, modifiers: egui::Modifiers::default() }
}
struct Seen {
role: accesskit::Role,
label: String,
bounds: Option<accesskit::Rect>,
disabled: bool,
}
impl Seen {
fn interactive(&self) -> bool {
matches!(self.role, accesskit::Role::Button | accesskit::Role::TextInput | accesskit::Role::CheckBox | accesskit::Role::Link)
}
fn at(&self) -> Option<Pos2> {
self.bounds.map(|b| pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32))
}
}
fn seen(output: &FullOutput) -> Vec<Seen> {
let Some(update) = &output.platform_output.accesskit_update else { return Vec::new() };
update
.nodes
.iter()
.filter_map(|(_, node)| {
node.label().or_else(|| node.value()).map(|text| Seen {
role: node.role(),
label: text.to_owned(),
bounds: node.bounds(),
disabled: node.is_disabled(),
})
})
.collect()
}
fn control(output: &FullOutput, label: &str) -> Option<Pos2> {
seen(output).iter().find(|s| s.interactive() && !s.disabled && s.label == label).and_then(Seen::at)
}
fn controls(output: &FullOutput) -> Vec<String> {
seen(output).into_iter().filter(Seen::interactive).map(|s| s.label).collect()
}
fn person(id: &str, name: &str) -> Contact {
Contact {
id: id.into(),
target: ShareTarget::User(id.into()),
name: name.into(),
email: Some(format!("{id}@example.com")),
avatar: None,
is_group: false,
}
}
fn existing(id: &str, target: ShareTarget, permission: Permission) -> Share {
Share { id: id.into(), target, display: None, permission, url: None, note: None, created: None }
}
fn ordinary() -> Vec<Capability> {
vec![Capability::Files, Capability::Sharing, Capability::Contacts, Capability::ShareNotify, Capability::LinkShares]
}
#[test]
fn renders_of_every_state_in_both_themes() {
let Ok(directory) = std::env::var("CRAFT_UI_RENDERS") else {
println!("set CRAFT_UI_RENDERS to a directory to write renders");
return;
};
let into = PathBuf::from(directory);
std::fs::create_dir_all(&into).expect("the render directory must be creatable");
for theme in [Theme::Light, Theme::Dark] {
// ---- the account control -------------------------------------------
let mut shot = Shot::new(theme, [320.0, 300.0]);
// A fresh menu is a signed-out one, which is the first state.
let mut draw = {
let mut menu = AccountMenu::new();
move |ui: &mut egui::Ui| menu.show(ui)
};
let output = shot.frame(Vec::new(), &mut draw);
shot.save(&into, "account-signed-out", theme, &output);
for (name, linked) in [("account-no-storage", false), ("account-linked", true)] {
let mut shot = Shot::new(theme, [320.0, 300.0]);
let mut draw = {
let mut menu = AccountMenu::new();
menu.set(vec![
Account {
id: "work".into(),
display: "Will Dunn".into(),
email: Some("will@example.com".into()),
service: "collabcraft.example.com".into(),
linked,
},
Account {
id: "personal".into(),
display: "Will at home".into(),
email: Some("will@example.net".into()),
service: "cloud.example.net".into(),
linked: true,
},
]);
move |ui: &mut egui::Ui| menu.show(ui)
};
// The menu is behind the badge, so it takes a press to show.
shot.click("Account, Will Dunn", &mut draw);
let output = shot.frame(Vec::new(), &mut draw);
shot.save(&into, name, theme, &output);
}
// ---- who else is here ----------------------------------------------
let mut shot = Shot::new(theme, [420.0, 80.0]);
let mut bar = PresenceBar::new();
bar.set(vec![
Peer::new("s1", "Ann Reed").at("editing B4"),
Peer::new("s2", "Bob Vine").at("editing D12"),
Peer::new("s3", "Cal Nye"),
Peer::new("s4", "Dee Shaw"),
Peer::new("s5", "Eve Marsh"),
Peer::new("s6", "Fay Orr"),
]);
let mut draw = move |ui: &mut egui::Ui| {
ui.add_space(24.0);
bar.show(ui);
};
let output = shot.frame(Vec::new(), &mut draw);
shot.save(&into, "presence", theme, &output);
// ---- the share dialog ----------------------------------------------
let cases: Vec<(&str, Vec<Capability>, Vec<Share>, &str)> = vec![
("dialog-fresh", ordinary(), Vec::new(), DOCUMENT),
(
"dialog-who-has-access",
ordinary(),
vec![
existing("s1", ShareTarget::User("ann".into()), Permission::Edit),
existing("s2", ShareTarget::Group("finance".into()), Permission::View),
],
DOCUMENT,
),
("dialog-no-link-shares", vec![Capability::Sharing, Capability::Contacts], Vec::new(), DOCUMENT),
("dialog-unsaved", ordinary(), Vec::new(), ""),
];
for (name, capabilities, access, id) in cases {
let mut shot = Shot::new(theme, [620.0, 560.0]);
let fake = Fake { capabilities, access, parked: Arc::default() };
let mut dialog = ShareDialog::new();
dialog.connect(fake.clone());
let held = Rc::new(RefCell::new(dialog));
let mut draw = {
let held = Rc::clone(&held);
move |ui: &mut egui::Ui| held.borrow_mut().show_in(ui)
};
// One frame asks what the provider can do, the next reads the answer.
shot.frame(Vec::new(), &mut draw);
shot.frame(Vec::new(), &mut draw);
held.borrow_mut().open(id.to_owned(), "Budget 2026");
shot.frame(Vec::new(), &mut draw);
let output = shot.frame(Vec::new(), &mut draw);
shot.save(&into, name, theme, &output);
}
// ---- recipients picked, then one of them refused -------------------
let fake = Fake { capabilities: ordinary(), access: Vec::new(), parked: Arc::default() };
let mut dialog = ShareDialog::new();
dialog.connect(fake.clone());
let held = Rc::new(RefCell::new(dialog));
let mut draw = {
let held = Rc::clone(&held);
move |ui: &mut egui::Ui| held.borrow_mut().show_in(ui)
};
let mut shot = Shot::new(theme, [620.0, 560.0]);
// One frame asks what the provider can do, the next reads the answer.
// Opening before that answer arrives does nothing, which is the point
// of a control that refuses to appear when it cannot work.
shot.frame(Vec::new(), &mut draw);
shot.frame(Vec::new(), &mut draw);
held.borrow_mut().open(DOCUMENT.to_owned(), "Budget 2026");
shot.frame(Vec::new(), &mut draw);
shot.typing = true;
shot.frame(vec![Event::Text("an".to_owned())], &mut draw);
shot.time += 0.25;
shot.frame(Vec::new(), &mut draw);
fake.answer(Answer::Lookup(vec![person("ann", "Ann Reed")]));
shot.frame(Vec::new(), &mut draw);
shot.click("Ann Reed", &mut draw);
shot.typing = false;
let output = shot.frame(Vec::new(), &mut draw);
shot.save(&into, "dialog-recipients", theme, &output);
shot.click("Send", &mut draw);
fake.answer(Answer::Granted {
shared: vec![existing("s1", ShareTarget::User("ann".into()), Permission::View)],
failed: vec![Failure {
target: ShareTarget::User("bob".into()),
code: "invalid_address".into(),
detail: "bob@example.con was rejected".into(),
}],
});
let output = shot.frame(Vec::new(), &mut draw);
shot.save(&into, "dialog-partial-failure", theme, &output);
}
}
+589
View File
@@ -0,0 +1,589 @@
//! Gated on the `share` feature, which is off by default.
#![cfg(feature = "share")]
//! The share dialog driven through its real widgets, offscreen.
//!
//! Every assertion here reads the accessibility tree the dialog actually
//! produced, or the requests it actually sent, rather than its private state.
//! No window is opened, no GPU is touched and no server is contacted: the
//! backend is a fake that parks each request until a test answers it, which is
//! also how answers are made to arrive late or in the wrong order.
use std::sync::{Arc, Mutex};
use craft_cloud::{Capability, Contact, Permission, Share, ShareTarget};
use craft_ui::share::{Answer, Failure, Replier, Request, ShareBackend, ShareDialog};
use egui::{Context, Event, FullOutput, Modifiers, PointerButton, Pos2, RawInput, Rect, accesskit, pos2, vec2};
const SCREEN: [f32; 2] = [620.0, 900.0];
const DOCUMENT: &str = "files/Budget 2026.xlsx";
#[derive(Default)]
struct Log {
seen: Vec<Request>,
parked: Vec<(Request, Replier)>,
}
/// A backend that answers what the dialog needs to get going and parks the
/// rest, so a test decides when each answer arrives.
#[derive(Clone)]
struct Fake {
log: Arc<Mutex<Log>>,
capabilities: Vec<Capability>,
access: Vec<Share>,
}
impl Fake {
fn new(capabilities: Vec<Capability>, access: Vec<Share>) -> Fake {
Fake { log: Arc::new(Mutex::new(Log::default())), capabilities, access }
}
fn seen(&self) -> Vec<Request> {
self.log.lock().map(|log| log.seen.clone()).unwrap_or_default()
}
fn parked(&self) -> Vec<Request> {
self.log.lock().map(|log| log.parked.iter().map(|(r, _)| r.clone()).collect()).unwrap_or_default()
}
/// Answer the request that has waited longest, which is the ordinary case.
fn answer(&self, answer: Answer) {
self.answer_nth(0, answer);
}
/// Answer the request parked at `index`, oldest first, so a test can
/// deliver a late answer after a newer one.
fn answer_nth(&self, index: usize, answer: Answer) {
let Some((_, reply)) = self.take(index) else { panic!("nothing is waiting at {index}") };
reply.answer(answer);
}
/// Take one parked request back, to refuse it or inspect its contents.
fn take(&self, index: usize) -> Option<(Request, Replier)> {
self.log.lock().ok().and_then(|mut log| if index < log.parked.len() { Some(log.parked.remove(index)) } else { None })
}
}
impl ShareBackend for Fake {
fn submit(&self, request: Request, reply: Replier) {
let Ok(mut log) = self.log.lock() else { return };
log.seen.push(request.clone());
match &request {
Request::Capabilities => {
reply.answer(Answer::Capabilities { capabilities: self.capabilities.clone(), linked: true });
}
Request::Access { .. } => reply.answer(Answer::Access(self.access.clone())),
_ => log.parked.push((request, reply)),
}
}
}
struct Harness {
ctx: Context,
dialog: ShareDialog,
time: f64,
typing: bool,
}
impl Harness {
fn new(capabilities: Vec<Capability>, access: Vec<Share>) -> (Harness, Fake) {
let ctx = Context::default();
ctx.enable_accesskit();
ctx.all_styles_mut(|style| {
style.animation_time = 0.0;
style.visuals.text_cursor.blink = false;
});
let fake = Fake::new(capabilities, access);
let mut dialog = ShareDialog::new();
dialog.connect(fake.clone());
let mut harness = Harness { ctx, dialog, time: 0.0, typing: false };
// One frame asks what the provider can do, the next reads the answer.
harness.frame(Vec::new());
harness.frame(Vec::new());
(harness, fake)
}
/// An ordinary deployment: files, sharing, contacts and mail.
fn everything() -> (Harness, Fake) {
Harness::new(
// Everything, which has to include ShareNotify. Notifying a
// recipient of a share is a separate ability from sending
// arbitrary mail, and the box is gated on the former.
vec![Capability::Files, Capability::Sharing, Capability::Contacts, Capability::Mail, Capability::ShareNotify],
Vec::new(),
)
}
fn frame(&mut self, events: Vec<Event>) -> FullOutput {
self.time += 1.0 / 60.0;
let raw = RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(SCREEN[0], SCREEN[1]))),
time: Some(self.time),
events,
..Default::default()
};
let ctx = self.ctx.clone();
if self.typing {
// Keeping the recipient field focused is what a user holding the
// caret there does; nothing else in the dialog wants focus.
ctx.memory_mut(|m| m.request_focus(ShareDialog::query_field_id()));
}
let dialog = &mut self.dialog;
let mut output = ctx.run_ui(raw, |ui| dialog.show_in(ui));
output.textures_delta.clear();
output
}
/// Let the clock run, for the debounce.
fn wait(&mut self, seconds: f64) -> FullOutput {
self.time += seconds;
self.frame(Vec::new())
}
fn open(&mut self) {
self.dialog.open(DOCUMENT, "Budget 2026.xlsx");
assert!(self.dialog.is_open(), "the dialog should have opened");
self.frame(Vec::new());
}
/// Type into the recipient field, then let the debounce elapse.
fn type_and_settle(&mut self, text: &str) {
self.typing = true;
self.frame(vec![Event::Text(text.to_owned())]);
self.wait(0.25);
}
fn click(&mut self, label: &str) {
let output = self.frame(Vec::new());
let Some(at) = control(&output, label) else {
panic!("nothing to click labelled {label:?}; the controls on screen are {:?}", controls(&output))
};
self.frame(vec![Event::PointerMoved(at)]);
self.frame(vec![press(at, true)]);
self.frame(vec![press(at, false)]);
self.frame(Vec::new());
}
}
fn press(at: Pos2, pressed: bool) -> Event {
Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }
}
fn key(key: egui::Key) -> Event {
Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }
}
/// One widget as the accessibility tree reported it.
struct Seen {
role: accesskit::Role,
label: String,
bounds: Option<accesskit::Rect>,
disabled: bool,
}
impl Seen {
/// Something a pointer can act on, as opposed to a piece of text.
fn interactive(&self) -> bool {
matches!(self.role, accesskit::Role::Button | accesskit::Role::RadioButton | accesskit::Role::CheckBox)
}
fn at(&self) -> Option<Pos2> {
self.bounds.map(|b| pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32))
}
}
fn seen(output: &FullOutput) -> Vec<Seen> {
let Some(tree) = output.platform_output.accesskit_update.as_ref() else { return Vec::new() };
tree.nodes
.iter()
.filter_map(|(_, node)| {
// egui puts a plain label's text in the accessibility value and a
// control's text in the label, so both are text on screen.
node.label().or_else(|| node.value()).map(|text| Seen {
role: node.role(),
label: text.to_owned(),
bounds: node.bounds(),
disabled: node.is_disabled(),
})
})
.collect()
}
/// Where to click the control carrying this exact label.
fn control(output: &FullOutput, label: &str) -> Option<Pos2> {
seen(output).iter().find(|s| s.interactive() && !s.disabled && s.label == label).and_then(Seen::at)
}
fn controls(output: &FullOutput) -> Vec<String> {
seen(output).into_iter().filter(Seen::interactive).map(|s| s.label).collect()
}
/// The buttons alone, which is what a chip and a match row are.
fn buttons(output: &FullOutput) -> Vec<String> {
seen(output).into_iter().filter(|s| s.role == accesskit::Role::Button).map(|s| s.label).collect()
}
/// Every piece of text on screen, for asserting what the user was told.
fn text(output: &FullOutput) -> Vec<String> {
seen(output).into_iter().map(|s| s.label).collect()
}
/// The primary action, taken from the defaults the dialog actually draws.
/// A literal here drifts the moment the wording changes.
const SEND: &str = "Send";
/// The permission dropdown, chevron included. It is a menu, not a toggle.
const PERMISSION: &str = "View";
fn says(output: &FullOutput, fragment: &str) -> bool {
text(output).iter().any(|line| line.contains(fragment))
}
fn person(id: &str, name: &str) -> Contact {
Contact {
id: id.into(),
target: ShareTarget::User(id.into()),
name: name.into(),
email: Some(format!("{id}@example.com")),
avatar: None,
is_group: false,
}
}
fn group(id: &str, name: &str) -> Contact {
Contact { id: id.into(), target: ShareTarget::Group(id.into()), name: name.into(), email: None, avatar: None, is_group: true }
}
fn existing(id: &str, target: ShareTarget, permission: Permission) -> Share {
Share { id: id.into(), target, display: None, permission, url: None, note: None, created: None }
}
fn lookup(found: Vec<Contact>) -> Answer {
Answer::Lookup(found)
}
// ---- the picker -----------------------------------------------------------
#[test]
fn typing_a_few_letters_offers_matches_and_picking_them_builds_chips() {
let (mut h, fake) = Harness::everything();
h.open();
h.type_and_settle("an");
h.frame(Vec::new());
assert_eq!(
fake.parked(),
vec![Request::Lookup { query: "an".into(), limit: 8 }],
"one lookup for the whole burst of typing, not one per keystroke"
);
fake.answer(lookup(vec![person("ann", "Ann Reed"), person("andy", "Andy Shaw"), group("finance", "Finance")]));
let output = h.frame(Vec::new());
for name in ["Ann Reed", "Andy Shaw", "Finance"] {
assert!(buttons(&output).iter().any(|b| b == name), "{name} should be offered; saw {:?}", buttons(&output));
}
// Three recipients, picked one after another. Each lands as a chip whose
// whole body is the control that takes it back again.
h.click("Ann Reed");
h.type_and_settle("an");
fake.answer(lookup(vec![person("andy", "Andy Shaw")]));
h.frame(Vec::new());
h.click("Andy Shaw");
h.type_and_settle("fin");
fake.answer(lookup(vec![group("finance", "Finance")]));
h.frame(Vec::new());
h.click("Finance");
let output = h.frame(Vec::new());
for name in ["Remove Ann Reed", "Remove Andy Shaw", "Remove Finance"] {
assert!(buttons(&output).iter().any(|b| b == name), "{name} should be a chip; saw {:?}", buttons(&output));
}
}
#[test]
fn a_chip_takes_one_recipient_back_and_leaves_the_others() {
let (mut h, fake) = Harness::everything();
h.open();
for (query, found) in [("an", person("ann", "Ann Reed")), ("bo", person("bob", "Bob Vine")), ("ca", person("cal", "Cal Nye"))] {
h.type_and_settle(query);
fake.answer(lookup(vec![found.clone()]));
h.frame(Vec::new());
h.click(&found.name);
}
h.typing = false;
h.click("Remove Bob Vine");
let output = h.frame(Vec::new());
assert!(buttons(&output).iter().any(|b| b == "Remove Ann Reed"));
assert!(buttons(&output).iter().any(|b| b == "Remove Cal Nye"));
assert!(!buttons(&output).iter().any(|b| b == "Remove Bob Vine"), "the removed chip is gone; saw {:?}", buttons(&output));
// And the share that follows carries the two that are left.
h.click(SEND);
let parked = fake.parked();
let Some(Request::Grant(grant)) = parked.first() else { panic!("expected a share, saw {parked:?}") };
assert_eq!(grant.targets, vec![ShareTarget::User("ann".into()), ShareTarget::User("cal".into())]);
}
#[test]
fn an_answer_the_user_has_typed_past_never_reaches_the_list() {
let (mut h, fake) = Harness::everything();
h.open();
// Two bursts of typing, so two lookups are outstanding at once.
h.type_and_settle("an");
h.frame(Vec::new());
h.type_and_settle("ann");
h.frame(Vec::new());
assert_eq!(fake.parked().len(), 2);
// The newer one answers first and the older one arrives late, which is
// what a service under load does.
fake.answer_nth(1, lookup(vec![person("ann", "Ann Reed")]));
h.frame(Vec::new());
fake.answer_nth(0, lookup(vec![person("andy", "Andy Shaw"), person("anna", "Anna Beck")]));
let output = h.frame(Vec::new());
assert!(buttons(&output).iter().any(|b| b == "Ann Reed"), "the current answer stays");
assert!(!says(&output, "Andy Shaw"), "the stale answer must not flicker in");
assert!(!says(&output, "Anna Beck"));
}
#[test]
fn one_letter_is_not_worth_asking_about() {
let (mut h, fake) = Harness::everything();
h.open();
h.type_and_settle("a");
h.frame(Vec::new());
assert!(fake.parked().is_empty(), "a single letter matches most of an address book");
h.frame(vec![Event::Text("n".to_owned())]);
h.wait(0.25);
h.frame(Vec::new());
assert_eq!(fake.parked(), vec![Request::Lookup { query: "an".into(), limit: 8 }]);
}
#[test]
fn nothing_is_asked_until_the_typing_stops() {
let (mut h, fake) = Harness::everything();
h.open();
h.typing = true;
// Five keystrokes inside the debounce window.
for letter in ["a", "n", "n", "i", "e"] {
h.frame(vec![Event::Text(letter.to_owned())]);
h.wait(0.03);
}
assert!(fake.parked().is_empty(), "nothing asked while the user is still typing");
h.wait(0.25);
h.frame(Vec::new());
assert_eq!(fake.parked(), vec![Request::Lookup { query: "annie".into(), limit: 8 }], "one question for the whole word");
}
// ---- what a share says ----------------------------------------------------
#[test]
fn sharing_with_five_where_one_address_is_wrong_names_the_one_that_failed() {
let (mut h, fake) = Harness::everything();
h.open();
for (query, found) in [("an", person("ann", "Ann Reed")), ("bo", person("bob", "Bob Vine"))] {
h.type_and_settle(query);
fake.answer(lookup(vec![found.clone()]));
h.frame(Vec::new());
h.click(&found.name);
}
h.typing = false;
h.click(SEND);
fake.answer(Answer::Granted {
shared: vec![existing("s1", ShareTarget::User("ann".into()), Permission::View)],
failed: vec![Failure {
target: ShareTarget::User("bob".into()),
code: "invalid_address".into(),
detail: "bob@example.con was rejected".into(),
}],
});
let output = h.frame(Vec::new());
assert!(says(&output, "Shared with"), "the ones that went through are named");
assert!(says(&output, "ann"));
assert!(says(&output, "Not shared with"), "and so is the one that did not");
assert!(says(&output, "bob@example.con was rejected"), "with the reason, not a count; saw {:?}", text(&output));
// The failed recipient stays in the picker so a correction is one edit.
assert!(buttons(&output).iter().any(|b| b == "Remove Bob Vine"));
assert!(!buttons(&output).iter().any(|b| b == "Remove Ann Reed"), "the one that worked has left");
}
#[test]
fn a_refusal_that_stopped_everything_is_shown_as_itself() {
let (mut h, fake) = Harness::everything();
h.open();
h.type_and_settle("an");
fake.answer(lookup(vec![person("ann", "Ann Reed")]));
h.frame(Vec::new());
h.click("Ann Reed");
h.typing = false;
h.click(SEND);
let Some((_, reply)) = fake.take(0) else { panic!("expected a share in flight") };
reply.refuse("sign in again");
let output = h.frame(Vec::new());
assert!(says(&output, "sign in again"));
assert!(!says(&output, "Not shared with"), "a refusal is not a per-recipient failure");
assert!(control(&output, SEND).is_some(), "the button comes back");
}
#[test]
fn a_note_and_a_permission_travel_with_the_share() {
let (mut h, fake) = Harness::everything();
h.open();
h.type_and_settle("an");
fake.answer(lookup(vec![person("ann", "Ann Reed")]));
h.frame(Vec::new());
h.click("Ann Reed");
h.typing = false;
// The permission is a menu now, so it takes opening before choosing.
h.click(PERMISSION);
h.click("Edit");
h.click(SEND);
let parked = fake.parked();
let Some(Request::Grant(grant)) = parked.first() else { panic!("expected a share, saw {parked:?}") };
assert_eq!(grant.permission, Permission::Edit);
assert_eq!(grant.id, DOCUMENT, "the handle goes back untouched");
assert!(grant.notify, "mail works here, and the box is ticked by default");
assert_eq!(grant.note, None, "an empty note is no note");
}
#[test]
fn a_server_that_cannot_send_mail_is_never_promised_a_notification() {
let (mut h, fake) = Harness::new(vec![Capability::Sharing, Capability::Contacts], Vec::new());
h.open();
h.type_and_settle("an");
fake.answer(lookup(vec![person("ann", "Ann Reed")]));
h.frame(Vec::new());
h.click("Ann Reed");
h.typing = false;
h.click(SEND);
let parked = fake.parked();
let Some(Request::Grant(grant)) = parked.first() else { panic!("expected a share, saw {parked:?}") };
assert!(!grant.notify, "a checkbox for mail a server cannot send must not be honoured");
}
#[test]
fn a_server_without_contacts_asks_nobody_anything() {
let (mut h, fake) = Harness::new(vec![Capability::Sharing], Vec::new());
h.open();
h.type_and_settle("ann");
h.frame(Vec::new());
assert!(fake.parked().is_empty(), "there is no address book to search");
}
// ---- who already has access ----------------------------------------------
#[test]
fn who_has_access_is_listed_and_one_can_be_withdrawn() {
let (mut h, fake) = Harness::new(
vec![Capability::Sharing, Capability::Contacts, Capability::Mail],
vec![
existing("s1", ShareTarget::User("ann".into()), Permission::Edit),
existing("s2", ShareTarget::Group("finance".into()), Permission::View),
],
);
h.open();
let output = h.frame(Vec::new());
assert!(says(&output, "Who has access"));
assert!(says(&output, "ann"));
assert!(says(&output, "finance (group)"));
assert_eq!(buttons(&output).iter().filter(|b| *b == "Withdraw").count(), 2);
h.click("Withdraw");
assert!(fake.seen().iter().any(|r| matches!(r, Request::Withdraw { share_id } if share_id == "s1" || share_id == "s2")));
// It stays on the list until the server agrees it is gone.
let output = h.frame(Vec::new());
assert!(says(&output, "Withdrawing…"));
let Some((Request::Withdraw { share_id }, reply)) = fake.take(0) else { panic!("expected a withdrawal in flight") };
reply.answer(Answer::Withdrawn { share_id: share_id.clone() });
let output = h.frame(Vec::new());
assert_eq!(buttons(&output).iter().filter(|b| *b == "Withdraw").count(), 1, "one left");
}
#[test]
fn a_document_nobody_has_been_given_says_so() {
let (mut h, _fake) = Harness::everything();
h.open();
let output = h.frame(Vec::new());
assert!(says(&output, "Nobody else yet"));
}
// ---- what the dialog refuses to offer -------------------------------------
#[test]
fn a_server_without_sharing_draws_no_dialog_at_all() {
let (mut h, fake) = Harness::new(vec![Capability::Files, Capability::Contacts], Vec::new());
assert!(!h.dialog.available());
h.dialog.open(DOCUMENT, "Budget 2026.xlsx");
assert!(!h.dialog.is_open(), "a feature the provider lacks is hidden, not offered");
let output = h.frame(Vec::new());
assert!(buttons(&output).is_empty(), "nothing to click; saw {:?}", buttons(&output));
assert!(!fake.seen().iter().any(|r| matches!(r, Request::Access { .. })), "and nothing was asked about the document");
}
#[test]
fn an_unsaved_document_is_told_to_save_rather_than_refused_by_the_server() {
let (mut h, fake) = Harness::everything();
h.dialog.open("", "Book1");
let output = h.frame(Vec::new());
assert!(says(&output, "Save this document somewhere to share it."));
assert!(control(&output, SEND).is_none(), "there is nothing to share yet");
assert!(!fake.seen().iter().any(|r| matches!(r, Request::Access { .. })));
}
#[test]
fn closing_puts_the_dialog_away() {
let (mut h, _fake) = Harness::everything();
h.open();
h.click("Close");
assert!(!h.dialog.is_open());
let output = h.frame(Vec::new());
assert!(buttons(&output).is_empty());
}
#[test]
fn a_typed_address_says_how_to_add_it_and_adding_it_works() {
let (mut h, fake) = Harness::everything();
h.open();
h.type_and_settle("outside@example.com");
fake.answer(lookup(Vec::new()));
let output = h.frame(Vec::new());
assert!(says(&output, "Press Return to share with this address"), "saw {:?}", text(&output));
assert!(!says(&output, "No matches"), "an address that matched nobody is still a recipient");
// Return takes it, and the share carries it as an address.
h.frame(vec![key(egui::Key::Enter)]);
h.frame(Vec::new());
h.typing = false;
let output = h.frame(Vec::new());
assert!(buttons(&output).iter().any(|b| b == "Remove outside@example.com"), "saw {:?}", buttons(&output));
h.click(SEND);
let parked = fake.parked();
let Some(Request::Grant(grant)) = parked.first() else { panic!("expected a share, saw {parked:?}") };
assert_eq!(grant.targets, vec![ShareTarget::Email("outside@example.com".into())]);
}
#[test]
fn a_name_that_matched_nobody_is_not_offered_as_an_address() {
let (mut h, fake) = Harness::everything();
h.open();
h.type_and_settle("nobody");
fake.answer(lookup(Vec::new()));
let output = h.frame(Vec::new());
assert!(says(&output, "No matches"));
assert!(!says(&output, "Press Return"));
}