diff --git a/crates/voelin-ui-vm/Cargo.toml b/crates/voelin-ui-vm/Cargo.toml
index 17f3587..5eebc51 100644
--- a/crates/voelin-ui-vm/Cargo.toml
+++ b/crates/voelin-ui-vm/Cargo.toml
@@ -29,14 +29,13 @@ roxmltree = { version = "0.21", default-features = false, features = ["std"] }
miniz_oxide = "0.8"
# Grapheme clusters for emoji in chat text.
unicode-segmentation = "1.13"
+# The sample pictures of the demo data (VOELIN_DEMO_UI) and the tests.
+png = "0.18"
voelin-audio = { path = "../voelin-audio", default-features = false }
voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] }
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
voelin-model = { path = "../voelin-model" }
voelin-store = { path = "../voelin-store" }
-[dev-dependencies]
-png = "0.18"
-
[lints]
workspace = true
diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui-vm/src/dev/logic.rs
similarity index 61%
rename from crates/voelin-ui/src/dev.rs
rename to crates/voelin-ui-vm/src/dev/logic.rs
index 3903cab..7d0a7e3 100644
--- a/crates/voelin-ui/src/dev.rs
+++ b/crates/voelin-ui-vm/src/dev/logic.rs
@@ -1,77 +1,19 @@
-//! Development switches (environment variables), for trying screens and
-//! taking screenshots without a server:
-//!
-//! - `VOELIN_DATA_DIR=
`: the database (app.rs).
-//! - `VOELIN_AUTOCONNECT=voice|observe`: connect the first bookmark on start.
-//! - `VOELIN_SCREENSHOT=`: save the window after
-//! `VOELIN_SCREENSHOT_DELAY` seconds (default 4) and exit.
-//! - `VOELIN_WINDOW_SIZE=x`: the window's size (e.g. `390x844` for the
-//! phone layout).
-//! - `VOELIN_DEMO_UI=1`: sample servers, channels, chat (two pages of older
-//! messages answer scrolling up) and streams, no server needed (nothing is
-//! stored).
-//! - `VOELIN_DEMO_STREAM=1`: a local test stream in the viewer.
-//! - `VOELIN_OPEN=[,...]`: open screens on start: `home`,
-//! `server` (`server:chat`: its server chat), `settings[:]`
-//! (voice, keybinds, streaming, privacy, appearance, or 0-4), `about`,
-//! `share`, `bookmark` (add a server, also `join`;
-//! `bookmark:edit` the current one, Advanced open),
-//! `emoji` (the picker), `client` (the volume dialog of the first other
-//! client once connected), `panel` / `no-panel` (the members panel),
-//! `voice` (the voice channel view; on the phone its own screen;
-//! `voice:compact` with the smaller stage, not stored),
-//! `more` (after `voice` on the phone: the voice screen's More menu,
-//! opened once the screen is laid out),
-//! `members` (the phone's members page), `notification` (a tapped voice
-//! notification), `shared:` (text shared to the app on Android),
-//! `pins`, `topics` (the drawers),
-//! `topic:` (a topic's messages), `member` (the member card of the
-//! first other client), `poke` (the poke dialog: for the contact shown
-//! after `friends`, else for the first other client, its card open),
-//! `channel-password` (the password dialog of the first locked channel,
-//! the sample's Officers; `channel-password:wrong` as after a refused
-//! one), `actions` (the last message's actions, as if hovered),
-//! `first-run` (home's banner as before the first server, over the
-//! sample data),
-//! `unread` (the current chat read up to five messages before its end:
-//! the "New" divider, scrolled up to; `unread:end` ten messages before,
-//! at the list's end, under the bar that counts the new messages),
-//! `link-confirm[:]` (the question before a masked link opens, by
-//! default the sample's raid board), `link:` (a TeamSpeak link
-//! opened: the server dialog filled in from it, or in voice on its
-//! server a move into its channel), `watch` (the first stream; with
-//! sample data the local test pattern in its place), `theatre` (after
-//! `watch`: in theatre mode), `popout` (`watch` in a window of its own),
-//! `tab:` (phone layout); `friends[:]`,
-//! `messages[:]` (a private chat), `inbox` (offline messages),
-//! `library`, `events`, `event-form`, `search[:]`,
-//! `notifications` (the bell), `offline` (an offline message), `picture`
-//! (a chat picture opened large), `camera` (the settings' camera
-//! preview); settings sections also `account`,
-//! `profiles` (also `identities`), `devices`, `notifications`,
-//! `integrations`, `advanced` (5-10);
-//! `studio[:]`: the Stream Studio (with `VOELIN_DEMO_UI` a demo
-//! studio from synthetic sources), `studio:window` in a window of its own,
-//! `studio:live` going live (also with a screen opened after it:
-//! `studio:live,server,voice` shows our stream's card with the studio's
-//! picture), `studio:record`, or a dialog: `studio:source`,
-//! `studio:audio`, `studio:camera`, `studio:scene`, `studio:settings`.
-//! A screenshot also saves the studio's window, or the stream's
-//! (`-window.png`), and draws it over the main window.
-//! - `VOELIN_AUTOWATCH=1`: watch the first stream that shows up.
-//! - `VOELIN_AUTOSHARE=test-pattern`: share the test pattern (accepting
-//! everyone) once connected to a TeamSpeak 6 server.
+//! Sample data of `VOELIN_DEMO_UI`: servers, channels, people, chats,
+//! contacts, notices and pictures, as plain values and as the events a
+//! server would send. A front end feeds the events to
+//! [`crate::events::handle`], so the screens are filled by the same code
+//! that fills them from a real server; nothing here touches the engine,
+//! the store or a toolkit. The pictures are PNG bytes the front end saves
+//! where it wants.
+use std::path::PathBuf;
use std::sync::Arc;
-use std::time::Duration;
-use anyhow::Result;
-use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
use voelin_core::gateway::Pin;
use voelin_core::stream::{StreamInfo, StreamKind};
use voelin_core::{
- BackendInfo, Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, JoinFailure,
- ObserveState, OfflineMessageInfo, Relation, SessionState, Source, VoiceState,
+ BackendInfo, Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, ObserveState,
+ OfflineMessageInfo, Relation, SessionState, Source, VoiceState,
};
use voelin_gateway_proto::{
Action, Attendee, ConfigEntry, ConfigSource, EventInfo, EventKind, EventSpec, PermRule,
@@ -79,426 +21,19 @@ use voelin_gateway_proto::{
feature,
};
use voelin_model::{
- BannerMode, Capabilities, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, Presence,
+ BannerMode, Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo,
+ GroupInfo, Presence,
};
use voelin_store::{Bookmark, MessageSource};
-use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app};
+use crate::bridge::RecordingItem;
use crate::settings::LastVoice;
-use crate::vm::bridge::RecordingItem;
+use crate::social::logic::Social;
+use crate::social::{NoticeKind, NoticeRequest, NoticeTarget};
+use crate::state::{AppState, Lines};
-/// The switches read at start.
-#[derive(Clone, Debug, Default)]
-pub(crate) struct Switches {
- pub demo_stream: bool,
- pub demo_ui: bool,
- pub autoshare: bool,
- pub open_client: bool,
- open: Vec,
- autoconnect: Option,
- screenshot: Option,
- screenshot_delay: u64,
- window_size: Option<(f32, f32)>,
-}
-
-fn flag(name: &str) -> bool {
- std::env::var(name).is_ok_and(|v| v == "1")
-}
-
-/// `390x844` → (390, 844).
-fn parse_size(text: &str) -> Option<(f32, f32)> {
- let (w, h) = text.split_once(['x', 'X'])?;
- Some((w.trim().parse().ok()?, h.trim().parse().ok()?))
-}
-
-impl Switches {
- pub fn from_env() -> Self {
- let open: Vec = std::env::var("VOELIN_OPEN")
- .unwrap_or_default()
- .split(',')
- .map(|s| s.trim().to_owned())
- .filter(|s| !s.is_empty())
- .collect();
- Self {
- demo_stream: flag("VOELIN_DEMO_STREAM"),
- demo_ui: flag("VOELIN_DEMO_UI"),
- autoshare: std::env::var("VOELIN_AUTOSHARE").is_ok_and(|v| v == "test-pattern"),
- open_client: open.iter().any(|o| o == "client"),
- open,
- autoconnect: std::env::var("VOELIN_AUTOCONNECT").ok(),
- screenshot: std::env::var_os("VOELIN_SCREENSHOT").map(Into::into),
- screenshot_delay: std::env::var("VOELIN_SCREENSHOT_DELAY")
- .ok()
- .and_then(|d| d.parse().ok())
- .unwrap_or(4),
- window_size: std::env::var("VOELIN_WINDOW_SIZE").ok().as_deref().and_then(parse_size),
- }
- }
-}
-
-fn section(name: &str) -> SettingsSection {
- match name {
- "1" | "keybinds" | "ptt" => SettingsSection::Keybinds,
- "2" | "streaming" => SettingsSection::Streaming,
- "3" | "privacy" => SettingsSection::Privacy,
- "4" | "appearance" => SettingsSection::Appearance,
- "5" | "account" => SettingsSection::Account,
- "6" | "profiles" | "identities" => SettingsSection::Profiles,
- "7" | "devices" => SettingsSection::Devices,
- "8" | "notifications" => SettingsSection::Notifications,
- "9" | "integrations" => SettingsSection::Integrations,
- "10" | "advanced" => SettingsSection::Advanced,
- _ => SettingsSection::Voice,
- }
-}
-
-fn mobile_tab(name: &str) -> MobileTab {
- match name {
- "home" => MobileTab::Home,
- "servers" => MobileTab::Servers,
- "activity" => MobileTab::Activity,
- "you" => MobileTab::You,
- _ => MobileTab::Chat,
- }
-}
-
-/// Timers that must live while the window runs.
-pub(crate) struct Running {
- _screenshot: Option,
- _resize: Option,
- _scroll: Option,
- _more: Option,
-}
-
-/// Apply the switches once the app is set up.
-pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
- if let Some((w, h)) = switches.window_size {
- ui.window().set_size(slint::LogicalSize::new(w, h));
- }
- if switches.demo_ui {
- with_app(demo_ui);
- }
- match switches.autoconnect.as_deref() {
- Some("voice") => {
- with_app(|app| app.connect_voice());
- }
- Some("observe") => {
- with_app(|app| {
- if let Some(id) = app.state.current {
- app.observe(id);
- }
- });
- }
- _ => {}
- }
- let nav = ui.global::();
- for open in &switches.open {
- let (what, arg) = open.split_once(':').unwrap_or((open.as_str(), ""));
- match what {
- "home" => nav.invoke_show(Page::Home),
- "server" => {
- nav.invoke_show(Page::Server);
- // The server chat, which starts with the welcome message.
- if arg == "chat" {
- with_app(|app| app.select_tab(0));
- }
- }
- "settings" => nav.invoke_open_settings(section(arg)),
- "about" => nav.invoke_open_about(),
- "share" => {
- nav.invoke_open_share();
- // The sample share of the test pattern, live at once.
- if arg == "live" && switches.demo_ui {
- with_app(|app| app.demo_share());
- }
- }
- // The current server's dialog, Advanced open.
- "bookmark" if arg == "edit" => {
- if let Some(id) = with_app(|app| app.state.current).flatten() {
- nav.invoke_edit_server(id as i32);
- }
- }
- // `join`: the same dialog (Join a server was one of its own).
- "bookmark" | "join" => nav.invoke_add_server(),
- "emoji" => nav.set_emoji_open(true),
- "panel" => nav.set_right_panel_open(true),
- "no-panel" => nav.set_right_panel_open(false),
- "tab" => nav.set_mobile_tab(mobile_tab(arg)),
- "voice" => {
- nav.invoke_show_voice(true);
- // The smaller stage, for this run only.
- if arg == "compact" {
- nav.set_voice_compact(true);
- }
- }
- "pins" => nav.invoke_show_pins(true),
- // Opened once laid out (below).
- "more" => {}
- // The phone's members page.
- "members" => nav.set_members_open(true),
- // What Android hands over: a tapped voice notification, text
- // shared to the app.
- "notification" => crate::inbox::request(crate::inbox::Request::ShowVoice),
- "shared" => crate::inbox::request(crate::inbox::Request::Share {
- text: Some(arg.to_owned()),
- files: Vec::new(),
- }),
- "topics" => nav.invoke_show_topics(true),
- "topic" => {
- with_app(|app| {
- app.open_topic(arg.parse().unwrap_or(1));
- // No gateway answers in demo mode.
- if switches.demo_ui {
- demo_topic(app);
- }
- });
- }
- "member" => {
- with_app(|app| app.open_first_member());
- }
- // After `friends` the contact path (Kairo without a contact
- // chosen), else the member card's.
- "poke" => {
- let friends = nav.get_page() == Page::Friends;
- with_app(|app| {
- if friends {
- let uid = app.social.selected.clone().unwrap_or_else(|| "demo-3".into());
- app.contact_action(&uid, "poke");
- } else {
- app.open_first_member();
- app.member_action("poke");
- }
- });
- }
- "channel-password" => {
- with_app(|app| open_channel_password(app, arg == "wrong"));
- }
- // A screenshot cannot hover.
- "actions" => nav.set_show_actions(true),
- // Home as before the first server, over the sample data.
- "first-run" => nav.set_first_run(true),
- // `end`: further back, so the divider is above the view.
- "unread" => {
- with_app(|app| open_unread(app, if arg == "end" { 10 } else { 5 }));
- }
- "link-confirm" => {
- let url = if arg.is_empty() { DEMO_RAID_BOARD } else { arg };
- with_app(|app| app.open_link_text(url, true));
- }
- // As a link from the platform comes.
- "link" => crate::inbox::request(crate::inbox::Request::OpenLink(arg.to_owned())),
- "watch" | "popout" => {
- with_app(|app| {
- if switches.demo_ui {
- app.demo_watch();
- } else {
- app.watch_first_stream();
- }
- if what == "popout" {
- app.viewer_pop_out();
- }
- });
- }
- "theatre" => nav.set_theatre(true),
- // Home, friends, messages, events, the bell, the search.
- "friends" => {
- with_app(|app| app.select_contact(arg.to_owned()));
- nav.invoke_show(Page::Friends);
- }
- "messages" | "dm" => {
- let uid = if arg.is_empty() { "demo-3" } else { arg };
- with_app(|app| app.open_dm_with(Some(DEMO), uid));
- nav.invoke_show(Page::Messages);
- }
- "inbox" => {
- nav.set_dm_tab(2);
- with_app(|app| app.dm_tab(2));
- nav.invoke_show(Page::Messages);
- }
- "library" => nav.invoke_show(Page::Library),
- "events" => nav.invoke_show(Page::Events),
- "event-form" => nav.invoke_create_event(),
- "search" => nav.invoke_open_search(arg.into()),
- "notifications" => nav.set_notifications_open(true),
- "offline" => nav.invoke_write_offline("demo-ari".into(), "Ari".into()),
- "picture" => {
- let picture = demo_picture(1280, 720, 16);
- let image = crate::images::picture("demo:lightbox", &picture);
- nav.set_lightbox(image);
- nav.set_lightbox_open(true);
- }
- // The camera preview of the settings (the test pattern).
- "camera" => {
- with_app(|app| {
- app.start_camera();
- app.refresh_pages();
- });
- }
- "studio" => {
- if arg != "window" {
- nav.invoke_open_studio();
- }
- with_app(|app| app.studio_dev(arg));
- }
- // Opened once connected (settings_page.rs).
- "client" => {}
- other => eprintln!("VOELIN_OPEN: unknown screen {other:?}"),
- }
- }
- // A window manager can refuse the size set before the window opened,
- // so ask again once it is up. (Under `xvfb-run` in a Wayland session,
- // remove WAYLAND_DISPLAY, or winit opens the window on the desktop.)
- let resize = switches.window_size.map(|(w, h)| {
- let weak = ui.as_weak();
- let timer = slint::Timer::default();
- timer.start(
- slint::TimerMode::SingleShot,
- Duration::from_millis(switches.screenshot_delay * 1000 / 2),
- move || {
- if let Some(ui) = weak.upgrade() {
- ui.window().set_size(slint::LogicalSize::new(w, h));
- }
- },
- );
- timer
- });
- // `unread`: up to the divider once the list is laid out (after the
- // resize above).
- let scroll = switches.open.iter().any(|o| o == "unread").then(|| {
- late(ui, switches, |ui| {
- let bridge = ui.global::();
- bridge.set_jump_index(bridge.get_unread_index());
- bridge.set_jump_requests(bridge.get_jump_requests().wrapping_add(1));
- })
- });
- // `more`: the phone voice screen's More menu (a screenshot cannot tap).
- let more = switches.open.iter().any(|o| o == "more").then(|| {
- late(ui, switches, |ui| {
- let nav = ui.global::();
- nav.set_more_requests(nav.get_more_requests().wrapping_add(1));
- })
- });
- let screenshot = switches.screenshot.clone().map(|path| {
- let weak = ui.as_weak();
- let timer = slint::Timer::default();
- timer.start(
- slint::TimerMode::SingleShot,
- Duration::from_secs(switches.screenshot_delay),
- move || {
- if let Some(ui) = weak.upgrade() {
- if let Err(e) = save_screenshot(&ui, &path) {
- eprintln!("screenshot failed: {e}");
- }
- let _ = ui.hide();
- // Also when the studio's or the stream's own window is
- // open.
- let _ = slint::quit_event_loop();
- }
- },
- );
- timer
- });
- Running { _screenshot: screenshot, _resize: resize, _scroll: scroll, _more: more }
-}
-
-/// A timer that runs `action` at three quarters of the screenshot delay, once
-/// the window has its size and the screens are laid out.
-fn late(
- ui: &MainWindow,
- switches: &Switches,
- action: impl Fn(&MainWindow) + 'static,
-) -> slint::Timer {
- let weak = ui.as_weak();
- let timer = slint::Timer::default();
- timer.start(
- slint::TimerMode::SingleShot,
- Duration::from_millis(switches.screenshot_delay * 1000 * 3 / 4),
- move || {
- if let Some(ui) = weak.upgrade() {
- action(&ui);
- }
- },
- );
- timer
-}
-
-/// The current chat's read marker `back` messages before its end, as if
-/// they came while away, its "New" divider shown (`VOELIN_OPEN=unread`).
-fn open_unread(app: &mut App, back: usize) {
- let Some(id) = app.state.current else { return };
- let own_uids = app.state.own_uids.clone();
- let Some(view) = app.state.sessions.get_mut(&id) else { return };
- let own_client = view.state.own_client;
- let own = |m: &ChatMessage| crate::vm::social::own_message(&own_uids, own_client, m);
- let index = view.current_tab;
- let tab = &mut view.tabs[index];
- let Some(at) = tab.messages.len().checked_sub(back + 1) else { return };
- let read = &tab.messages[at].message;
- tab.read = Some((read.message.ts_ms, read.id));
- tab.divider = None;
- tab.count_unread(own);
- tab.enter(own);
- app.refresh_chat();
- app.refresh_servers();
-}
-
-fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> {
- let mut image = ui.window().take_snapshot()?;
- let window = with_app(|app| app.studio_snapshot().or_else(|| app.viewer_snapshot())).flatten();
- if let Some(window) = window {
- let stem = path.file_stem().unwrap_or_default().to_string_lossy();
- save_png(&window, &path.with_file_name(format!("{stem}-window.png")))?;
- paste(&mut image, &window);
- }
- save_png(&image, path)
-}
-
-/// Draw `top` over the bottom right of `image` with a border, as a second
-/// window sits on a desktop.
-fn paste(image: &mut SharedPixelBuffer, top: &SharedPixelBuffer) {
- let (w, h) = (image.width() as usize, image.height() as usize);
- let (tw, th) = (top.width() as usize, top.height() as usize);
- let (x0, y0) = (w.saturating_sub(tw + 24), h.saturating_sub(th + 24));
- let border = Rgba8Pixel { r: 0x3f, g: 0x7b, b: 0xff, a: 0xff };
- let pixels = image.make_mut_slice();
- for y in y0.saturating_sub(1)..(y0 + th + 1).min(h) {
- for x in x0.saturating_sub(1)..(x0 + tw + 1).min(w) {
- let (ty, tx) = (y.wrapping_sub(y0), x.wrapping_sub(x0));
- pixels[y * w + x] =
- if ty < th && tx < tw { top.as_slice()[ty * tw + tx] } else { border };
- }
- }
-}
-
-fn save_png(image: &SharedPixelBuffer, path: &std::path::Path) -> Result<()> {
- let file = std::io::BufWriter::new(std::fs::File::create(path)?);
- let mut encoder = png::Encoder::new(file, image.width(), image.height());
- encoder.set_color(png::ColorType::Rgba);
- encoder.set_depth(png::BitDepth::Eight);
- encoder.write_header()?.write_image_data(image.as_bytes())?;
- Ok(())
-}
-
-/// `VOELIN_OPEN=channel-password`: join the current server's first locked
-/// channel, which asks for its password; `wrong` as if the server had
-/// refused one.
-fn open_channel_password(app: &mut App, wrong: bool) {
- let Some(session) = app.state.current else { return };
- let locked = app
- .view()
- .and_then(|v| v.presence.channels.values().filter(|c| c.has_password).map(|c| c.id).min());
- let Some(channel) = locked else { return };
- if wrong {
- if let Some(view) = app.view_mut() {
- view.channel_passwords.insert(channel, "guess".into());
- }
- app.join_failed(session, channel, JoinFailure::Password);
- } else {
- app.join_channel(session, channel);
- }
-}
-
-const DEMO: i64 = 9001;
+/// The id of the first sample server (the others follow).
+pub const DEMO: i64 = 9001;
/// The software of the sample voice server, as a link reports it, and what
/// that software can do (streams, files, offline messages).
@@ -534,8 +69,8 @@ fn client(id: u16, channel: u64, name: &str) -> ClientInfo {
}
}
-/// Sample data through the same events a server would send.
-fn demo_ui(app: &mut App) {
+/// The saved servers of the sample.
+pub fn bookmarks() -> Vec {
let bookmark = |id: i64, name: &str, address: &str| Bookmark {
id,
name: name.into(),
@@ -549,22 +84,31 @@ fn demo_ui(app: &mut App) {
client_version: None,
cached_server_icon: None,
};
- app.state.bookmarks = vec![
+ vec![
Bookmark {
gateway_url: Some("wss://gw.nightfall.example/v1".into()),
..bookmark(DEMO, "Nightfall Guild", "ts.nightfall.example:9987")
},
bookmark(DEMO + 1, "Pixel Lounge", "pixel.example"),
bookmark(DEMO + 2, "Dev TS3", "127.0.0.1:9987"),
- ];
- // Home's "Continue where you left off": a channel of a server without
- // voice, so it shows Join.
- app.state.settings.last_voice = Some(LastVoice {
+ ]
+}
+
+/// Home's "Continue where you left off": a channel of a server without
+/// voice, so it shows Join.
+pub fn last_voice() -> LastVoice {
+ LastVoice {
bookmark: DEMO + 1,
address: "pixel.example".into(),
channel: vec!["Art Corner".into()],
- });
- app.state.current = Some(DEMO);
+ }
+}
+
+/// What the first sample server tells when it is connected with voice:
+/// its name and software, its groups, its presence (channels with
+/// pictures, people with groups and badges), the session's state, a
+/// gateway, a talker, a stream, and the second server observed.
+pub fn server_events() -> Vec {
let session = DEMO as u64;
let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() };
@@ -661,7 +205,7 @@ fn demo_ui(app: &mut App) {
..Default::default()
};
let (backend, capabilities) = demo_teamspeak_6();
- let events = [
+ let events = vec![
Event::ServerInfo { session, name: "Nightfall Guild".into(), backend, capabilities },
Event::Groups {
session,
@@ -727,482 +271,7 @@ fn demo_ui(app: &mut App) {
state: SessionState { observe: ObserveState::Observing, ..Default::default() },
},
];
- for event in events {
- app.handle_event(event);
- }
- demo_pictures(app);
- demo_chat(app, session);
- demo_social(app);
- // No toast over the screenshots.
- app.set_status("");
- app.refresh_all();
-}
-
-/// Sample people, private chats, pokes, notifications, events, a picture
-/// and recordings for the home, friends, messages, events and settings
-/// screens (`VOELIN_DEMO_UI`).
-fn demo_social(app: &mut App) {
- let session = DEMO as u64;
- let now = chrono::Utc::now().timestamp_millis();
- let min = 60_000;
- // The second sample server is observed: a few people there.
- let mut lounge = Presence { server_name: "Pixel Lounge".into(), ..Default::default() };
- for c in [channel(1, 0, 0, "Lobby"), channel(2, 0, 1, "Art Corner"), channel(3, 0, 2, "Music")]
- {
- lounge.channels.insert(c.id, c);
- }
- let mut ivy = client(21, 2, "Ivy");
- ivy.uid = Some("demo-ivy".into());
- let mut sora = client(22, 3, "Sora");
- sora.uid = Some("demo-sora".into());
- sora.away = Some("painting".into());
- let mut pixel = client(23, 1, "Pixel");
- pixel.uid = Some("demo-pixel".into());
- for c in [ivy, sora, pixel] {
- lounge.clients.insert(c.id, c);
- }
- app.handle_event(Event::Presence { session: session + 1, presence: Arc::new(lounge) });
- app.handle_event(Event::State {
- session: session + 1,
- state: SessionState {
- observe: ObserveState::Observing,
- presence_source: Some(Source::Gateway),
- server_uid: Some("demo-lounge".into()),
- ..Default::default()
- },
- });
- app.handle_event(Event::ServerInfo {
- session: session + 1,
- name: "Pixel Lounge".into(),
- backend: demo_teamspeak_3(),
- capabilities: Default::default(),
- });
-
- // Contacts: friends here and there, some offline, one blocked.
- let contact =
- |uid: &str, nick: &str, relation: Relation, seen_min: i64, server: &str| Contact {
- uid: uid.into(),
- nickname: nick.into(),
- relation,
- note: String::new(),
- muted: false,
- volume: 1.0,
- added_ms: now - 400 * 86_400_000,
- last_seen_ms: if seen_min > 0 { now - seen_min * min } else { 0 },
- last_server: (!server.is_empty()).then(|| server.to_owned()),
- };
- let mut kairo = contact("demo-3", "Kairo", Relation::Friend, 1, "Nightfall Guild");
- kairo.note = "Tank on Tuesday raids. Always down for co-op.".into();
- let contacts = vec![
- contact("demo-2", "Lumen", Relation::Friend, 1, "Nightfall Guild"),
- kairo,
- contact("demo-4", "Mira", Relation::Friend, 1, "Nightfall Guild"),
- contact("demo-5", "dex", Relation::Friend, 1, "Nightfall Guild"),
- contact("demo-6", "Talon", Relation::Friend, 1, "Nightfall Guild"),
- contact("demo-7", "Zeph", Relation::Friend, 1, "Nightfall Guild"),
- contact("demo-ivy", "Ivy", Relation::Friend, 1, "Pixel Lounge"),
- contact("demo-sora", "Sora", Relation::Friend, 1, "Pixel Lounge"),
- contact("demo-ari", "Ari", Relation::Friend, 130, "Nightfall Guild"),
- contact("demo-neon", "Neon", Relation::Friend, 26 * 60, "Dev TS3"),
- contact("demo-9", "Rin", Relation::Neutral, 1, "Nightfall Guild"),
- contact("demo-spam", "FreeSkinsBot", Relation::Blocked, 3 * 24 * 60, "Pixel Lounge"),
- ];
- app.handle_event(Event::ContactsChanged { contacts: Arc::new(contacts) });
- for (uid, ago) in [
- ("demo-2", 12),
- ("demo-3", 28),
- ("demo-4", 42),
- ("demo-5", 64),
- ("demo-6", 95),
- ("demo-7", 130),
- ("demo-ivy", 8),
- ("demo-sora", 50),
- ] {
- app.social.online_since.insert(uid.into(), now - ago * min);
- }
-
- // Private chats: with Kairo (a picture, a file), Mira, Lumen, dex,
- // and Ivy on the other server; Neon's is only stored.
- let picture = file_link(2, "night-castle.png", 412_331);
- let private =
- |id: i64, peer: &str, from_me: bool, author: (&str, u16), text: String, ago: i64| {
- HistoryMessage {
- id,
- message: ChatMessage {
- target: ChatTarget::Private(peer.into()),
- author_name: author.0.into(),
- author_uid: Some(if from_me { "demo-1".into() } else { peer.into() }),
- author_id: (author.1 > 0).then_some(author.1),
- text,
- ts_ms: now - ago * min,
- via_relay: false,
- blocked: false,
- },
- source: MessageSource::Voice,
- remote_id: None,
- topic_id: None,
- reactions: Vec::new(),
- pinned: false,
- rev: 0,
- }
- };
- let nova = ("Nova", 1);
- let kairo = ("Kairo", 3);
- let lines = vec![
- private(
- 300,
- "demo-3",
- true,
- nova,
- format!("Hey! Check out this shot I got last night while exploring 👀 {picture}"),
- 95,
- ),
- private(301, "demo-3", false, kairo, "That looks incredible! Where was this?".into(), 93),
- private(
- 302,
- "demo-3",
- true,
- nova,
- "In the northern region. The lighting was perfect.".into(),
- 91,
- ),
- private(
- 303,
- "demo-3",
- false,
- kairo,
- "We should explore together this weekend! I found some cool locations too.".into(),
- 89,
- ),
- private(
- 304,
- "demo-3",
- false,
- kairo,
- format!(
- "Here are the spots I marked. {}",
- file_link(2, "exploration-routes.pdf", 2_516_582)
- ),
- 88,
- ),
- private(305, "demo-3", true, nova, "That sunset looks unreal. Let's do it! 🙌".into(), 6),
- private(
- 310,
- "demo-4",
- false,
- ("Mira", 4),
- "Working on a new video today, want to see a sneak peek?".into(),
- 70,
- ),
- private(311, "demo-2", false, ("Lumen", 2), "Let's run it tonight!".into(), 120),
- private(312, "demo-5", false, ("dex", 5), file_link(2, "map-notes.png", 96_120), 26 * 60),
- ];
- for m in lines {
- let target = m.message.target.clone();
- app.handle_event(Event::ChatHistory {
- session,
- target,
- messages: vec![m],
- source: HistorySource::Gateway,
- complete: true,
- });
- }
- app.handle_event(Event::ChatHistory {
- session: session + 1,
- target: ChatTarget::Private("demo-ivy".into()),
- messages: vec![HistoryMessage {
- message: ChatMessage {
- target: ChatTarget::Private("demo-ivy".into()),
- author_name: "Ivy".into(),
- author_uid: Some("demo-ivy".into()),
- author_id: Some(21),
- text: "Same here! The new channel is great.".into(),
- ts_ms: now - 30 * min,
- via_relay: true,
- blocked: false,
- },
- ..private(320, "demo-ivy", false, ("Ivy", 21), String::new(), 30)
- }],
- source: HistorySource::Gateway,
- complete: true,
- });
- let mut neon = private(
- 330,
- "demo-neon",
- false,
- ("Neon", 0),
- "Sent you the config, check the server folder.".into(),
- 3 * 24 * 60,
- );
- neon.message.author_id = None;
- app.social.dm.stored.push(("demo-dev".into(), neon));
- app.social.dm.bookmark_of.insert("demo-dev".into(), DEMO + 2);
- // The samples came one by one, as new ones do: all are read (no "New"
- // line, which a gateway page on screen gets), but for Mira's and
- // Lumen's messages, which came while away.
- for view in app.state.sessions.values_mut() {
- for tab in &mut view.tabs {
- tab.divider = None;
- tab.catch_up();
- match &tab.target {
- ChatTarget::Private(uid) if uid == "demo-4" => tab.unread = 1,
- ChatTarget::Private(uid) if uid == "demo-2" => tab.unread = 2,
- _ => continue,
- }
- tab.read = None;
- }
- }
- // A poke from Kairo, shown among the messages and in the bell.
- app.handle_event(Event::Poke {
- session,
- from: 3,
- from_uid: Some("demo-3".into()),
- from_name: "Kairo".into(),
- message: "raid in 5?".into(),
- blocked: false,
- });
- if let Some(p) = app.social.pokes.last_mut() {
- p.ts_ms = now - 7 * min;
- }
- // Offline messages the server keeps (the Inbox tab).
- let mail = |id: u32, from: &str, subject: &str, ago_min: i64, read: bool| OfflineMessageInfo {
- id,
- from_uid: from.into(),
- subject: subject.into(),
- ts_s: (now - ago_min * min) / 1000,
- read,
- };
- app.handle_event(Event::OfflineMessages {
- session,
- request: 0,
- result: Ok(vec![
- mail(1, "demo-ari", "Raid roster for Friday", 3 * 60, false),
- mail(2, "demo-neon", "The config for the dev server", 26 * 60, true),
- mail(3, "demo-4", "Thumbnails for the stream", 3 * 24 * 60, true),
- ]),
- });
-
- // The pictures of the links, as if downloaded.
- if let Some(view) = app.state.sessions.get_mut(&DEMO) {
- for (channel, name) in
- [(2, "night-castle.png"), (2, "guild-banner.png"), (2, "map-notes.png")]
- {
- let file = voelin_model::FileRef {
- channel,
- path: "/".into(),
- name: name.into(),
- ..Default::default()
- };
- view.extra.previews.insert(
- crate::vm::previews::link_key(&file),
- crate::vm::state::Preview::Ready(voelin_core::Bytes(
- demo_picture(640, 360, name.len() as u32).into(),
- )),
- );
- }
- }
-
- // The gateway's events (one is live), its configuration and rules.
- let by = |name: &str, uid: &str| UserRef { uid: uid.into(), name: name.into() };
- let event =
- |id: i64, title: &str, start: i64, hours: i64, channel: Option, stream: bool| {
- EventInfo {
- id,
- spec: EventSpec {
- title: title.into(),
- description: String::new(),
- start_ms: start,
- end_ms: Some(start + hours * 3_600_000),
- channel,
- kind: if stream { EventKind::Stream } else { EventKind::General },
- stream_title: None,
- stream_game: None,
- host_uid: None,
- },
- creator: by("Nova", "demo-1"),
- created_ms: now - 86_400_000,
- updated_ms: now - 86_400_000,
- going: 0,
- maybe: 0,
- not_going: 0,
- my_rsvp: None,
- attendees: Vec::new(),
- live_stream: None,
- }
- };
- let hour = 3_600_000;
- let tomorrow = (now / 86_400_000 + 1) * 86_400_000 + 18 * hour;
- let mut raid = event(1, "Raid Night: The Frozen Citadel", tomorrow, 3, Some(4), false);
- raid.spec.description = "Bring elixirs and fire resistance. Voice in Raid Night.".into();
- raid.going = 12;
- raid.maybe = 4;
- raid.not_going = 1;
- raid.my_rsvp = Some(RsvpStatus::Going);
- raid.attendees = vec![
- Attendee { user: by("Nova", "demo-1"), status: RsvpStatus::Going, ts_ms: now },
- Attendee { user: by("Kairo", "demo-3"), status: RsvpStatus::Going, ts_ms: now },
- Attendee { user: by("Mira", "demo-4"), status: RsvpStatus::Maybe, ts_ms: now },
- Attendee { user: by("dex", "demo-5"), status: RsvpStatus::NotGoing, ts_ms: now },
- ];
- let mut live = event(2, "Exploring the Lands Between", now - 12 * min, 2, Some(2), true);
- live.spec.stream_title = Some("Exploring the Lands Between".into());
- live.spec.stream_game = Some("Elden Ring".into());
- live.creator = by("Lumen", "demo-2");
- live.going = 8;
- live.live_stream = Some("demo-stream".into());
- let mut night = event(3, "Community Game Night", tomorrow + 2 * 86_400_000, 3, None, false);
- night.spec.description = "Party games for everyone: drop in any time.".into();
- night.creator = by("Talon", "demo-6");
- night.going = 23;
- night.maybe = 9;
- let mut lofi = event(4, "Late Night Lofi & Chat", now + 50 * min, 2, Some(5), true);
- lofi.spec.stream_title = Some("Lofi beats to raid to".into());
- lofi.creator = by("Mira", "demo-4");
- lofi.going = 5;
- lofi.maybe = 2;
- app.handle_event(Event::Gateway {
- session,
- update: GatewayUpdate::Events { events: vec![raid, live, night, lofi] },
- });
- app.handle_event(Event::Gateway {
- session,
- update: GatewayUpdate::Permissions {
- channel: None,
- actions: vec![
- Action::React,
- Action::Pin,
- Action::CreateEvent,
- Action::Rsvp,
- Action::Moderate,
- Action::Admin,
- ],
- },
- });
- let config = |key: &str, value: serde_json::Value, source: ConfigSource, description: &str| {
- ConfigEntry {
- key: key.into(),
- default: value.clone(),
- value,
- source,
- value_type: "int".into(),
- description: description.into(),
- bootstrap: false,
- }
- };
- app.handle_event(Event::Gateway {
- session,
- update: GatewayUpdate::Config {
- entries: vec![
- config(
- "history.retention_days",
- serde_json::json!(90),
- ConfigSource::Db,
- "Days of chat history the gateway keeps.",
- ),
- config(
- "events.reminders_min",
- serde_json::json!([60, 15, 0]),
- ConfigSource::File,
- "Minutes before an event when reminders go out.",
- ),
- config(
- "streams.directory",
- serde_json::json!(true),
- ConfigSource::Default,
- "Keep a directory of the server's streams.",
- ),
- ],
- },
- });
- app.handle_event(Event::Gateway {
- session,
- update: GatewayUpdate::PermRules {
- rules: vec![
- PermRuleInfo {
- action: Action::CreateEvent,
- rule: Some(PermRule {
- everyone: false,
- server_groups: vec![GROUP_ADMIN, GROUP_MOD],
- channel_groups: vec![],
- }),
- source: ConfigSource::Db,
- default: "server admins".into(),
- },
- PermRuleInfo {
- action: Action::Pin,
- rule: None,
- source: ConfigSource::Default,
- default: "moderators".into(),
- },
- ],
- },
- });
-
- // Notifications: two mentions (unread: home shows them), a message, an
- // event, a friend online (and the poke above).
- use crate::social::{NoticeKind, NoticeTarget};
- app.notify(
- NoticeKind::Mention,
- "Talon mentioned you".into(),
- "Nova, can you open the raid at 20:00? — Chill Zone · Nightfall Guild".into(),
- NoticeTarget::Chat(DEMO, ChatTarget::Channel(2)),
- "Talon".into(),
- Some("demo-6".into()),
- );
- app.notify(
- NoticeKind::Mention,
- "Zeph mentioned you".into(),
- "Nova, are you healing tonight? — Raid Night · Nightfall Guild".into(),
- NoticeTarget::Chat(DEMO, ChatTarget::Channel(4)),
- "Zeph".into(),
- Some("demo-7".into()),
- );
- app.notify(
- NoticeKind::Event,
- "Late Night Lofi & Chat starts in 50 min".into(),
- "on Nightfall Guild".into(),
- NoticeTarget::Event(DEMO, 4),
- "Mira".into(),
- Some("demo-4".into()),
- );
- app.notify(
- NoticeKind::Friend,
- "Ivy is online".into(),
- "on Pixel Lounge · Art Corner".into(),
- NoticeTarget::Contact("demo-ivy".into()),
- "Ivy".into(),
- Some("demo-ivy".into()),
- );
- app.notify(
- NoticeKind::Message,
- "Mira".into(),
- "Working on a new video today, want to see a sneak peek?".into(),
- NoticeTarget::Dm(DEMO, "demo-4".into()),
- "Mira".into(),
- Some("demo-4".into()),
- );
- for (i, n) in app.social.notices.iter_mut().enumerate() {
- n.ts_ms = now - (i as i64 * 9 + 2) * min;
- n.unread = i < 3 || n.kind == NoticeKind::Mention;
- }
- app.refresh_notices();
-
- // Recordings and clips of the Studio.
- let recording = |name: &str, detail: &str| RecordingItem {
- name: name.into(),
- detail: detail.into(),
- clip: name.contains("clip"),
- path: format!("/tmp/{name}").into(),
- };
- app.models.social.recordings.sync(&[
- recording("raid-night-2026-10-02.webm", "1.2 GB · 2 Oct 22:41"),
- recording("clip-boss-down.mkv", "38.4 MB · 2 Oct 21:57"),
- recording("lands-between-stream.mkv", "2.8 GB · 28 Sep 20:12"),
- recording("clip-lucky-parry.mkv", "12.1 MB · 28 Sep 19:40"),
- ]);
- app.refresh_chats();
- app.refresh_people();
- app.refresh_home();
+ events
}
/// Addresses and icon ids of the sample server's pictures.
@@ -1213,7 +282,7 @@ const DEMO_RAID_BANNER: &str = "https://nightfall.example/raid.png";
/// A picture a message shows (`[img]`).
const DEMO_LOOT_PICTURE: &str = "https://nightfall.example/loot.png";
/// The sample's masked link (`VOELIN_OPEN=link-confirm`).
-const DEMO_RAID_BOARD: &str = "https://nightfall.example/raids";
+pub const DEMO_RAID_BOARD: &str = "https://nightfall.example/raids";
const DEMO_SERVER_ICON: u32 = 3_120_211_001;
const DEMO_ADMIN_ICON: u32 = 3_120_211_002;
const DEMO_MOD_ICON: u32 = 3_120_211_003;
@@ -1231,18 +300,14 @@ const DEMO_BADGES: [&str; 5] = [
/// Avatars, icons, banners and badges as the engine reports them once they
/// are in its cache (here a folder of synthetic pictures in the temporary
/// directory).
-fn demo_pictures(app: &mut App) {
+///
+/// `address` is the first sample server's; `save` stores a picture's bytes
+/// under a file name and gives the path of the file.
+pub fn pictures(address: &str, mut save: impl FnMut(&str, Vec) -> PathBuf) -> Vec {
let session = DEMO as u64;
- let dir = std::env::temp_dir().join("voelin-demo-pictures");
- let _ = std::fs::create_dir_all(&dir);
- let save = |name: &str, png: Vec| {
- let path = dir.join(name);
- let _ = std::fs::write(&path, png);
- path
- };
let mut events = vec![Event::ServerDetails {
session,
- address: app.state.bookmarks.iter().find(|b| b.id == DEMO).unwrap().address.clone(),
+ address: address.to_owned(),
details: Arc::new(voelin_model::ServerDetails {
icon: DEMO_SERVER_ICON,
..Default::default()
@@ -1297,9 +362,7 @@ fn demo_pictures(app: &mut App) {
hash: String::new(),
});
}
- for event in events {
- app.handle_event(event);
- }
+ events
}
/// Shapes of the sample icons.
@@ -1375,7 +438,7 @@ fn png_of(width: u32, height: u32, rgba: &[u8]) -> Vec {
}
/// A painted night: sky, moon, stars, hills and a castle; PNG bytes.
-fn demo_picture(width: u32, height: u32, seed: u32) -> Vec {
+pub fn demo_picture(width: u32, height: u32, seed: u32) -> Vec {
let mut rgba = Vec::with_capacity((width * height * 4) as usize);
let (w, h) = (width as f32, height as f32);
let (mx, my, mr) = (w * 0.68, h * 0.3, h * 0.17);
@@ -1450,9 +513,12 @@ fn file_link(channel: u64, name: &str, size: u64) -> String {
type SampleLine =
(i64, &'static str, u16, String, i64, bool, Vec, bool, Option);
-/// The sample chats, as stored messages with reactions, pins and topics.
-fn demo_chat(app: &mut App, session: u64) {
- let now = chrono::Utc::now().timestamp_millis();
+/// The sample chats, as stored messages with reactions, pins and topics,
+/// and the gateway's answers (the stream directory, the pins and the topics
+/// for the drawers); `now` in milliseconds since the epoch.
+pub fn chat_events(now: i64) -> Vec {
+ let session = DEMO as u64;
+ let mut events = Vec::new();
let react =
|emoji: &str, count: u32, me: bool| ReactionCount { emoji: emoji.into(), count, me };
let lines: Vec = vec![
@@ -1659,7 +725,7 @@ fn demo_chat(app: &mut App, session: u64) {
if pin {
pinned.push(message.clone());
}
- app.handle_event(Event::ChatHistory {
+ events.push(Event::ChatHistory {
session: if chat == DEMO { session } else { session + 1 },
target,
messages: vec![message],
@@ -1668,7 +734,7 @@ fn demo_chat(app: &mut App, session: u64) {
});
}
// A server chat besides the channel chat.
- app.handle_event(Event::ChatHistory {
+ events.push(Event::ChatHistory {
session,
target: ChatTarget::Server,
messages: vec![HistoryMessage {
@@ -1695,7 +761,7 @@ fn demo_chat(app: &mut App, session: u64) {
});
// The gateway's answers (no gateway runs in demo mode): the stream
// directory, and the pins and topics for the drawers.
- app.handle_event(Event::Gateway {
+ events.push(Event::Gateway {
session,
update: GatewayUpdate::Streams {
streams: vec![
@@ -1742,7 +808,7 @@ fn demo_chat(app: &mut App, session: u64) {
},
});
let by = |name: &str| UserRef { uid: format!("demo-{name}"), name: name.into() };
- app.handle_event(Event::Gateway {
+ events.push(Event::Gateway {
session,
update: GatewayUpdate::Pins {
target: ChatTarget::Channel(2),
@@ -1767,7 +833,7 @@ fn demo_chat(app: &mut App, session: u64) {
message_count: count,
archived: false,
};
- app.handle_event(Event::Gateway {
+ events.push(Event::Gateway {
session,
update: GatewayUpdate::Topics {
target: ChatTarget::Channel(2),
@@ -1778,13 +844,13 @@ fn demo_chat(app: &mut App, session: u64) {
],
},
});
+ events
}
/// The messages of the sample topic, as the gateway answers when it is
-/// opened.
-fn demo_topic(app: &mut App) {
- let now = chrono::Utc::now().timestamp_millis();
- app.handle_event(Event::Gateway {
+/// opened; `now` in milliseconds since the epoch.
+pub fn topic_history(now: i64) -> Event {
+ Event::Gateway {
session: DEMO as u64,
update: GatewayUpdate::TopicHistory {
target: ChatTarget::Channel(2),
@@ -1818,20 +884,21 @@ fn demo_topic(app: &mut App) {
.collect(),
has_more: false,
},
- });
+ }
}
-/// The sample messages before the sample chats' first ones: how many, how
-/// many a page, and their ids (the sample chats use ids below 500).
-const OLDER: i64 = 30;
-const OLDER_PAGE: i64 = 15;
-const OLDER_ID: i64 = 500;
+/// How many sample messages come before the sample chats' first ones.
+pub const OLDER: i64 = 30;
+/// How many of them a page has.
+pub const OLDER_PAGE: i64 = 15;
+/// The id of the first of them (the sample chats use ids below 500).
+pub const OLDER_ID: i64 = 500;
/// The page before `oldest` of a sample chat, as the engine answers
/// `Command::LoadOlderHistory`: older small talk, a page at a time, the last
/// one `complete`. The first page goes back from `oldest` (from `now_ms` in
/// an empty chat), the next ones from the sample message before.
-pub(crate) fn demo_older(
+pub fn demo_older(
target: &ChatTarget,
oldest: Option<&HistoryMessage>,
now_ms: i64,
@@ -1884,22 +951,599 @@ pub(crate) fn demo_older(
(messages, last >= OLDER)
}
-/// Answer [`App::load_older`] in demo mode (no engine runs) with
-/// [`demo_older`], a moment later as a server would.
-pub(crate) fn answer_older(session: i64, target: ChatTarget, oldest: Option) {
- slint::Timer::single_shot(Duration::from_millis(600), move || {
- let now = chrono::Utc::now().timestamp_millis();
- let (messages, complete) = demo_older(&target, oldest.as_ref(), now);
- with_app(|app| {
- app.handle_event(Event::ChatHistory {
- session: session as u64,
- target,
- messages,
- source: HistorySource::Gateway,
- complete,
- });
- });
+/// The second sample server, observed: a few people there (presence,
+/// state and software).
+pub fn lounge_events() -> Vec {
+ // The second sample server is observed: a few people there.
+ let session = DEMO as u64;
+ let mut events = Vec::new();
+ let mut lounge = Presence { server_name: "Pixel Lounge".into(), ..Default::default() };
+ for c in [channel(1, 0, 0, "Lobby"), channel(2, 0, 1, "Art Corner"), channel(3, 0, 2, "Music")]
+ {
+ lounge.channels.insert(c.id, c);
+ }
+ let mut ivy = client(21, 2, "Ivy");
+ ivy.uid = Some("demo-ivy".into());
+ let mut sora = client(22, 3, "Sora");
+ sora.uid = Some("demo-sora".into());
+ sora.away = Some("painting".into());
+ let mut pixel = client(23, 1, "Pixel");
+ pixel.uid = Some("demo-pixel".into());
+ for c in [ivy, sora, pixel] {
+ lounge.clients.insert(c.id, c);
+ }
+ events.push(Event::Presence { session: session + 1, presence: Arc::new(lounge) });
+ events.push(Event::State {
+ session: session + 1,
+ state: SessionState {
+ observe: ObserveState::Observing,
+ presence_source: Some(Source::Gateway),
+ server_uid: Some("demo-lounge".into()),
+ ..Default::default()
+ },
});
+ events.push(Event::ServerInfo {
+ session: session + 1,
+ name: "Pixel Lounge".into(),
+ backend: demo_teamspeak_3(),
+ capabilities: Default::default(),
+ });
+ events
+}
+
+/// Contacts: friends here and there, some offline, one blocked; `now` in
+/// milliseconds since the epoch.
+pub fn contacts(now: i64) -> Vec {
+ // Contacts: friends here and there, some offline, one blocked.
+ let min = 60_000;
+ let contact =
+ |uid: &str, nick: &str, relation: Relation, seen_min: i64, server: &str| Contact {
+ uid: uid.into(),
+ nickname: nick.into(),
+ relation,
+ note: String::new(),
+ muted: false,
+ volume: 1.0,
+ added_ms: now - 400 * 86_400_000,
+ last_seen_ms: if seen_min > 0 { now - seen_min * min } else { 0 },
+ last_server: (!server.is_empty()).then(|| server.to_owned()),
+ };
+ let mut kairo = contact("demo-3", "Kairo", Relation::Friend, 1, "Nightfall Guild");
+ kairo.note = "Tank on Tuesday raids. Always down for co-op.".into();
+ let contacts = vec![
+ contact("demo-2", "Lumen", Relation::Friend, 1, "Nightfall Guild"),
+ kairo,
+ contact("demo-4", "Mira", Relation::Friend, 1, "Nightfall Guild"),
+ contact("demo-5", "dex", Relation::Friend, 1, "Nightfall Guild"),
+ contact("demo-6", "Talon", Relation::Friend, 1, "Nightfall Guild"),
+ contact("demo-7", "Zeph", Relation::Friend, 1, "Nightfall Guild"),
+ contact("demo-ivy", "Ivy", Relation::Friend, 1, "Pixel Lounge"),
+ contact("demo-sora", "Sora", Relation::Friend, 1, "Pixel Lounge"),
+ contact("demo-ari", "Ari", Relation::Friend, 130, "Nightfall Guild"),
+ contact("demo-neon", "Neon", Relation::Friend, 26 * 60, "Dev TS3"),
+ contact("demo-9", "Rin", Relation::Neutral, 1, "Nightfall Guild"),
+ contact("demo-spam", "FreeSkinsBot", Relation::Blocked, 3 * 24 * 60, "Pixel Lounge"),
+ ];
+ contacts
+}
+
+/// Friends who are somewhere, and since when (milliseconds since the
+/// epoch).
+pub fn online_since(now: i64) -> Vec<(&'static str, i64)> {
+ let min = 60_000;
+ let mut since = Vec::new();
+ for (uid, ago) in [
+ ("demo-2", 12),
+ ("demo-3", 28),
+ ("demo-4", 42),
+ ("demo-5", 64),
+ ("demo-6", 95),
+ ("demo-7", 130),
+ ("demo-ivy", 8),
+ ("demo-sora", 50),
+ ] {
+ since.push((uid, now - ago * min));
+ }
+ since
+}
+
+/// Private chats: with Kairo (a picture, a file), Mira, Lumen, dex, and
+/// Ivy on the other server (Neon's is only stored, [`stored_chat`]).
+pub fn private_chat_events(now: i64) -> Vec {
+ // Private chats: with Kairo (a picture, a file), Mira, Lumen, dex,
+ // and Ivy on the other server; Neon's is only stored.
+ let min = 60_000;
+ let session = DEMO as u64;
+ let mut events = Vec::new();
+ let picture = file_link(2, "night-castle.png", 412_331);
+ let nova = ("Nova", 1);
+ let kairo = ("Kairo", 3);
+ let lines = vec![
+ private(
+ now,
+ 300,
+ "demo-3",
+ true,
+ nova,
+ format!("Hey! Check out this shot I got last night while exploring 👀 {picture}"),
+ 95,
+ ),
+ private(
+ now,
+ 301,
+ "demo-3",
+ false,
+ kairo,
+ "That looks incredible! Where was this?".into(),
+ 93,
+ ),
+ private(
+ now,
+ 302,
+ "demo-3",
+ true,
+ nova,
+ "In the northern region. The lighting was perfect.".into(),
+ 91,
+ ),
+ private(
+ now,
+ 303,
+ "demo-3",
+ false,
+ kairo,
+ "We should explore together this weekend! I found some cool locations too.".into(),
+ 89,
+ ),
+ private(
+ now,
+ 304,
+ "demo-3",
+ false,
+ kairo,
+ format!(
+ "Here are the spots I marked. {}",
+ file_link(2, "exploration-routes.pdf", 2_516_582)
+ ),
+ 88,
+ ),
+ private(
+ now,
+ 305,
+ "demo-3",
+ true,
+ nova,
+ "That sunset looks unreal. Let's do it! 🙌".into(),
+ 6,
+ ),
+ private(
+ now,
+ 310,
+ "demo-4",
+ false,
+ ("Mira", 4),
+ "Working on a new video today, want to see a sneak peek?".into(),
+ 70,
+ ),
+ private(now, 311, "demo-2", false, ("Lumen", 2), "Let's run it tonight!".into(), 120),
+ private(
+ now,
+ 312,
+ "demo-5",
+ false,
+ ("dex", 5),
+ file_link(2, "map-notes.png", 96_120),
+ 26 * 60,
+ ),
+ ];
+ for m in lines {
+ let target = m.message.target.clone();
+ events.push(Event::ChatHistory {
+ session,
+ target,
+ messages: vec![m],
+ source: HistorySource::Gateway,
+ complete: true,
+ });
+ }
+ events.push(Event::ChatHistory {
+ session: session + 1,
+ target: ChatTarget::Private("demo-ivy".into()),
+ messages: vec![HistoryMessage {
+ message: ChatMessage {
+ target: ChatTarget::Private("demo-ivy".into()),
+ author_name: "Ivy".into(),
+ author_uid: Some("demo-ivy".into()),
+ author_id: Some(21),
+ text: "Same here! The new channel is great.".into(),
+ ts_ms: now - 30 * min,
+ via_relay: true,
+ blocked: false,
+ },
+ ..private(now, 320, "demo-ivy", false, ("Ivy", 21), String::new(), 30)
+ }],
+ source: HistorySource::Gateway,
+ complete: true,
+ });
+ events
+}
+
+/// One sample private message, `ago` minutes old.
+fn private(
+ now: i64,
+ id: i64,
+ peer: &str,
+ from_me: bool,
+ author: (&str, u16),
+ text: String,
+ ago: i64,
+) -> HistoryMessage {
+ let min = 60_000;
+ HistoryMessage {
+ id,
+ message: ChatMessage {
+ target: ChatTarget::Private(peer.into()),
+ author_name: author.0.into(),
+ author_uid: Some(if from_me { "demo-1".into() } else { peer.into() }),
+ author_id: (author.1 > 0).then_some(author.1),
+ text,
+ ts_ms: now - ago * min,
+ via_relay: false,
+ blocked: false,
+ },
+ source: MessageSource::Voice,
+ remote_id: None,
+ topic_id: None,
+ reactions: Vec::new(),
+ pinned: false,
+ rev: 0,
+ }
+}
+
+/// A chat only in the store (its server is not connected): the server's
+/// unique id, the newest message and the bookmark the server is remembered
+/// for.
+pub fn stored_chat(now: i64) -> (&'static str, HistoryMessage, i64) {
+ let mut neon = private(
+ now,
+ 330,
+ "demo-neon",
+ false,
+ ("Neon", 0),
+ "Sent you the config, check the server folder.".into(),
+ 3 * 24 * 60,
+ );
+ neon.message.author_id = None;
+ ("demo-dev", neon, DEMO + 2)
+}
+
+/// The samples came one by one, as new ones do: all are read (no "New"
+/// line, which a gateway page on screen gets), but for Mira's and
+/// Lumen's messages, which came while away.
+pub fn read_samples(state: &mut AppState) {
+ for view in state.sessions.values_mut() {
+ for tab in &mut view.tabs {
+ tab.divider = None;
+ tab.catch_up();
+ match &tab.target {
+ ChatTarget::Private(uid) if uid == "demo-4" => tab.unread = 1,
+ ChatTarget::Private(uid) if uid == "demo-2" => tab.unread = 2,
+ _ => continue,
+ }
+ tab.read = None;
+ }
+ }
+}
+
+/// A poke from Kairo, shown among the messages and in the bell, and when
+/// it came (milliseconds since the epoch).
+pub fn poke(now: i64) -> (Event, i64) {
+ let session = DEMO as u64;
+ let event = Event::Poke {
+ session,
+ from: 3,
+ from_uid: Some("demo-3".into()),
+ from_name: "Kairo".into(),
+ message: "raid in 5?".into(),
+ blocked: false,
+ };
+ (event, now - 7 * 60_000)
+}
+
+/// Offline messages the server keeps (the Inbox tab).
+pub fn offline_messages(now: i64) -> Event {
+ let min = 60_000;
+ let session = DEMO as u64;
+ let mail = |id: u32, from: &str, subject: &str, ago_min: i64, read: bool| OfflineMessageInfo {
+ id,
+ from_uid: from.into(),
+ subject: subject.into(),
+ ts_s: (now - ago_min * min) / 1000,
+ read,
+ };
+ Event::OfflineMessages {
+ session,
+ request: 0,
+ result: Ok(vec![
+ mail(1, "demo-ari", "Raid roster for Friday", 3 * 60, false),
+ mail(2, "demo-neon", "The config for the dev server", 26 * 60, true),
+ mail(3, "demo-4", "Thumbnails for the stream", 3 * 24 * 60, true),
+ ]),
+ }
+}
+
+/// The pictures of the links, as if downloaded.
+pub fn link_previews(state: &mut AppState) {
+ if let Some(view) = state.sessions.get_mut(&DEMO) {
+ for (channel, name) in
+ [(2, "night-castle.png"), (2, "guild-banner.png"), (2, "map-notes.png")]
+ {
+ let file = voelin_model::FileRef {
+ channel,
+ path: "/".into(),
+ name: name.into(),
+ ..Default::default()
+ };
+ view.extra.previews.insert(
+ crate::previews::link_key(&file),
+ crate::state::Preview::Ready(voelin_core::Bytes(
+ demo_picture(640, 360, name.len() as u32).into(),
+ )),
+ );
+ }
+ }
+}
+
+/// The gateway's events (one is live), its permissions, configuration and
+/// rules.
+pub fn gateway_events(now: i64) -> Vec {
+ let min = 60_000;
+ let session = DEMO as u64;
+ let mut events = Vec::new();
+ let by = |name: &str, uid: &str| UserRef { uid: uid.into(), name: name.into() };
+ let event =
+ |id: i64, title: &str, start: i64, hours: i64, channel: Option, stream: bool| {
+ EventInfo {
+ id,
+ spec: EventSpec {
+ title: title.into(),
+ description: String::new(),
+ start_ms: start,
+ end_ms: Some(start + hours * 3_600_000),
+ channel,
+ kind: if stream { EventKind::Stream } else { EventKind::General },
+ stream_title: None,
+ stream_game: None,
+ host_uid: None,
+ },
+ creator: by("Nova", "demo-1"),
+ created_ms: now - 86_400_000,
+ updated_ms: now - 86_400_000,
+ going: 0,
+ maybe: 0,
+ not_going: 0,
+ my_rsvp: None,
+ attendees: Vec::new(),
+ live_stream: None,
+ }
+ };
+ let hour = 3_600_000;
+ let tomorrow = (now / 86_400_000 + 1) * 86_400_000 + 18 * hour;
+ let mut raid = event(1, "Raid Night: The Frozen Citadel", tomorrow, 3, Some(4), false);
+ raid.spec.description = "Bring elixirs and fire resistance. Voice in Raid Night.".into();
+ raid.going = 12;
+ raid.maybe = 4;
+ raid.not_going = 1;
+ raid.my_rsvp = Some(RsvpStatus::Going);
+ raid.attendees = vec![
+ Attendee { user: by("Nova", "demo-1"), status: RsvpStatus::Going, ts_ms: now },
+ Attendee { user: by("Kairo", "demo-3"), status: RsvpStatus::Going, ts_ms: now },
+ Attendee { user: by("Mira", "demo-4"), status: RsvpStatus::Maybe, ts_ms: now },
+ Attendee { user: by("dex", "demo-5"), status: RsvpStatus::NotGoing, ts_ms: now },
+ ];
+ let mut live = event(2, "Exploring the Lands Between", now - 12 * min, 2, Some(2), true);
+ live.spec.stream_title = Some("Exploring the Lands Between".into());
+ live.spec.stream_game = Some("Elden Ring".into());
+ live.creator = by("Lumen", "demo-2");
+ live.going = 8;
+ live.live_stream = Some("demo-stream".into());
+ let mut night = event(3, "Community Game Night", tomorrow + 2 * 86_400_000, 3, None, false);
+ night.spec.description = "Party games for everyone: drop in any time.".into();
+ night.creator = by("Talon", "demo-6");
+ night.going = 23;
+ night.maybe = 9;
+ let mut lofi = event(4, "Late Night Lofi & Chat", now + 50 * min, 2, Some(5), true);
+ lofi.spec.stream_title = Some("Lofi beats to raid to".into());
+ lofi.creator = by("Mira", "demo-4");
+ lofi.going = 5;
+ lofi.maybe = 2;
+ events.push(Event::Gateway {
+ session,
+ update: GatewayUpdate::Events { events: vec![raid, live, night, lofi] },
+ });
+ events.push(Event::Gateway {
+ session,
+ update: GatewayUpdate::Permissions {
+ channel: None,
+ actions: vec![
+ Action::React,
+ Action::Pin,
+ Action::CreateEvent,
+ Action::Rsvp,
+ Action::Moderate,
+ Action::Admin,
+ ],
+ },
+ });
+ let config = |key: &str, value: serde_json::Value, source: ConfigSource, description: &str| {
+ ConfigEntry {
+ key: key.into(),
+ default: value.clone(),
+ value,
+ source,
+ value_type: "int".into(),
+ description: description.into(),
+ bootstrap: false,
+ }
+ };
+ events.push(Event::Gateway {
+ session,
+ update: GatewayUpdate::Config {
+ entries: vec![
+ config(
+ "history.retention_days",
+ serde_json::json!(90),
+ ConfigSource::Db,
+ "Days of chat history the gateway keeps.",
+ ),
+ config(
+ "events.reminders_min",
+ serde_json::json!([60, 15, 0]),
+ ConfigSource::File,
+ "Minutes before an event when reminders go out.",
+ ),
+ config(
+ "streams.directory",
+ serde_json::json!(true),
+ ConfigSource::Default,
+ "Keep a directory of the server's streams.",
+ ),
+ ],
+ },
+ });
+ events.push(Event::Gateway {
+ session,
+ update: GatewayUpdate::PermRules {
+ rules: vec![
+ PermRuleInfo {
+ action: Action::CreateEvent,
+ rule: Some(PermRule {
+ everyone: false,
+ server_groups: vec![GROUP_ADMIN, GROUP_MOD],
+ channel_groups: vec![],
+ }),
+ source: ConfigSource::Db,
+ default: "server admins".into(),
+ },
+ PermRuleInfo {
+ action: Action::Pin,
+ rule: None,
+ source: ConfigSource::Default,
+ default: "moderators".into(),
+ },
+ ],
+ },
+ });
+ events
+}
+
+/// Recordings and clips of the Studio.
+pub fn recordings() -> Vec {
+ let recording = |name: &str, detail: &str| RecordingItem {
+ name: name.into(),
+ detail: detail.into(),
+ clip: name.contains("clip"),
+ path: format!("/tmp/{name}").into(),
+ };
+ vec![
+ recording("raid-night-2026-10-02.webm", "1.2 GB · 2 Oct 22:41"),
+ recording("clip-boss-down.mkv", "38.4 MB · 2 Oct 21:57"),
+ recording("lands-between-stream.mkv", "2.8 GB · 28 Sep 20:12"),
+ recording("clip-lucky-parry.mkv", "12.1 MB · 28 Sep 19:40"),
+ ]
+}
+
+/// Notifications: two mentions (unread: home shows them), a message, an
+/// event, a friend online (and the poke).
+pub fn notices() -> Vec {
+ vec![
+ NoticeRequest {
+ kind: NoticeKind::Mention,
+ title: "Talon mentioned you".into(),
+ body: "Nova, can you open the raid at 20:00? — Chill Zone · Nightfall Guild".into(),
+ target: NoticeTarget::Chat(DEMO, ChatTarget::Channel(2)),
+ name: "Talon".into(),
+ uid: Some("demo-6".into()),
+ },
+ NoticeRequest {
+ kind: NoticeKind::Mention,
+ title: "Zeph mentioned you".into(),
+ body: "Nova, are you healing tonight? — Raid Night · Nightfall Guild".into(),
+ target: NoticeTarget::Chat(DEMO, ChatTarget::Channel(4)),
+ name: "Zeph".into(),
+ uid: Some("demo-7".into()),
+ },
+ NoticeRequest {
+ kind: NoticeKind::Event,
+ title: "Late Night Lofi & Chat starts in 50 min".into(),
+ body: "on Nightfall Guild".into(),
+ target: NoticeTarget::Event(DEMO, 4),
+ name: "Mira".into(),
+ uid: Some("demo-4".into()),
+ },
+ NoticeRequest {
+ kind: NoticeKind::Friend,
+ title: "Ivy is online".into(),
+ body: "on Pixel Lounge · Art Corner".into(),
+ target: NoticeTarget::Contact("demo-ivy".into()),
+ name: "Ivy".into(),
+ uid: Some("demo-ivy".into()),
+ },
+ NoticeRequest {
+ kind: NoticeKind::Message,
+ title: "Mira".into(),
+ body: "Working on a new video today, want to see a sneak peek?".into(),
+ target: NoticeTarget::Dm(DEMO, "demo-4".into()),
+ name: "Mira".into(),
+ uid: Some("demo-4".into()),
+ },
+ ]
+}
+
+/// The bell's samples came a few minutes apart, the first three and the
+/// mentions unread.
+pub fn age_notices(social: &mut Social, now: i64) {
+ let min = 60_000;
+ for (i, n) in social.notices.iter_mut().enumerate() {
+ n.ts_ms = now - (i as i64 * 9 + 2) * min;
+ n.unread = i < 3 || n.kind == NoticeKind::Mention;
+ }
+}
+
+/// `VOELIN_OPEN=unread`: the current chat's read marker `back` messages
+/// before its end, as if they came while away, its "New" divider shown.
+/// Whether the chat changed.
+pub fn unread_from(state: &mut AppState, back: usize) -> bool {
+ let Some(id) = state.current else { return false };
+ let own_uids = state.own_uids.clone();
+ let Some(view) = state.sessions.get_mut(&id) else { return false };
+ let own_client = view.state.own_client;
+ let own = |m: &ChatMessage| crate::social::own_message(&own_uids, own_client, m);
+ let index = view.current_tab;
+ let tab = &mut view.tabs[index];
+ let Some(at) = tab.messages.len().checked_sub(back + 1) else { return false };
+ let read = &tab.messages[at].message;
+ tab.read = Some((read.message.ts_ms, read.id));
+ tab.divider = None;
+ tab.count_unread(own);
+ tab.enter(own);
+ true
+}
+
+/// `VOELIN_OPEN=channel-password`: the current server and its first
+/// locked channel, the one with the lowest id.
+pub fn first_locked_channel(state: &AppState) -> Option<(i64, ChannelId)> {
+ let session = state.current?;
+ let channel = state
+ .sessions
+ .get(&session)?
+ .presence
+ .channels
+ .values()
+ .filter(|c| c.has_password)
+ .map(|c| c.id)
+ .min()?;
+ Some((session, channel))
}
#[cfg(test)]
@@ -1954,4 +1598,189 @@ mod tests {
let (rest, complete) = demo_older(&target, second.last(), 0);
assert!(rest.is_empty() && complete);
}
+
+ /// The whole sample, event by event, as a front end feeds it.
+ fn demo_state() -> (crate::host::testing::State, Social<()>, crate::host::testing::Fake, i64) {
+ use crate::events::handle;
+ use crate::host::testing::Fake;
+
+ let now = 1_760_000_000_000;
+ let mut st = AppState::new(
+ bookmarks(),
+ crate::settings::UiSettings::default(),
+ voelin_core::AudioSettings::default(),
+ crate::settings::ClientPlaybackMap::new(),
+ );
+ st.settings.last_voice = Some(last_voice());
+ st.current = Some(DEMO);
+ let mut social = Social::<()>::default();
+ let host = Fake { demo: true, ..Default::default() };
+ host.now.set(now);
+ let mut events = server_events();
+ events.extend(pictures("ts.nightfall.example:9987", |name, _| PathBuf::from(name)));
+ events.extend(chat_events(now));
+ events.extend(lounge_events());
+ events.push(Event::ContactsChanged { contacts: Arc::new(contacts(now)) });
+ events.extend(private_chat_events(now));
+ events.push(poke(now).0);
+ events.push(offline_messages(now));
+ events.extend(gateway_events(now));
+ for event in events {
+ handle(&mut st, &mut social, &host, event);
+ }
+ (st, social, host, now)
+ }
+
+ #[test]
+ fn the_sample_servers_are_filled_by_the_same_events_as_real_ones() {
+ let (st, social, ..) = demo_state();
+ assert_eq!(
+ st.bookmarks.iter().map(|b| b.name.as_str()).collect::>(),
+ ["Nightfall Guild", "Pixel Lounge", "Dev TS3"]
+ );
+ let mut ids: Vec = st.sessions.keys().copied().collect();
+ ids.sort_unstable();
+ assert_eq!(ids, [DEMO, DEMO + 1]);
+ // The first: connected with voice into Chill Zone, as Nova.
+ let view = &st.sessions[&DEMO];
+ assert_eq!(view.state.voice, VoiceState::Connected);
+ assert_eq!((view.state.own_channel, view.state.own_client), (Some(2), Some(1)));
+ assert_eq!((view.presence.channels.len(), view.presence.clients.len()), (9, 9));
+ assert_eq!(view.extra.product, "TeamSpeak 6");
+ assert_eq!(view.streams.len(), 1);
+ assert_eq!(view.server_groups.len(), 4);
+ // Its pictures arrived: banners, icons, badges and avatars.
+ assert_eq!(view.avatars.len(), 5);
+ assert_eq!(view.icons.len(), 4);
+ assert!(view.pictures.contains_key(DEMO_HOST_BANNER));
+ // The chats: the channel's, the server's and the private ones.
+ let channel = view.tabs.iter().find(|t| t.target == ChatTarget::Channel(2)).unwrap();
+ assert_eq!(channel.messages.len(), 16);
+ assert!(channel.messages.iter().any(|m| m.message.reactions.len() == 2));
+ assert!(view.tabs.iter().any(|t| t.target == ChatTarget::Server));
+ let private: Vec<&str> = view
+ .tabs
+ .iter()
+ .filter_map(|t| match &t.target {
+ ChatTarget::Private(uid) => Some(uid.as_str()),
+ _ => None,
+ })
+ .collect();
+ for uid in ["demo-2", "demo-3", "demo-4", "demo-5"] {
+ assert!(private.contains(&uid), "{uid} in {private:?}");
+ }
+ // The gateway's pins, topics, events, and what we may do.
+ assert_eq!(view.extra.events.len(), 4);
+ assert_eq!(view.extra.actions.len(), 6);
+ assert_eq!(view.extra.inbox.len(), 3);
+ assert!(view.extra.directory.len() == 3 && !view.extra.config.is_empty());
+ // The second server is observed, with its own people and chat.
+ let lounge = &st.sessions[&(DEMO + 1)];
+ assert_eq!(lounge.state.observe, ObserveState::Observing);
+ assert_eq!(lounge.presence.clients.len(), 3);
+ assert_eq!(lounge.extra.product, "TeamSpeak 3");
+ assert!(lounge.tabs.iter().any(|t| t.target == ChatTarget::Private("demo-ivy".into())));
+ // People: twelve contacts, one blocked; Kairo's poke is in the list.
+ assert_eq!(st.contacts.len(), 12);
+ assert_eq!(st.contacts.values().filter(|c| c.relation == Relation::Blocked).count(), 1);
+ assert_eq!(social.pokes.len(), 1);
+ assert_eq!(social.pokes[0].name, "Kairo");
+ }
+
+ #[test]
+ fn the_sample_notices_are_read_as_the_bell_shows_them() {
+ let (st, mut social, host, now) = demo_state();
+ // The poke came with a notice of its own; the rest are asked for.
+ let before = social.notices.len();
+ for n in notices() {
+ let request = n;
+ crate::social::logic::notify(
+ &mut social,
+ crate::settings::NotifyLevel::App,
+ host.demo,
+ request,
+ now,
+ );
+ }
+ assert_eq!(social.notices.len(), before + 5);
+ age_notices(&mut social, now);
+ let rows = crate::social::logic::notice_rows(&st, &social);
+ // The newest are the samples; the three newest and the mentions are unread.
+ assert!(social.notices[0].ts_ms > now - 3 * 60_000);
+ assert_eq!(social.notices[0].ts_ms, now - 2 * 60_000);
+ assert!(rows.unread >= 3);
+ assert_eq!(rows.mentions.len(), 2);
+ }
+
+ #[test]
+ fn the_samples_are_read_but_for_two_chats() {
+ let (mut st, ..) = demo_state();
+ read_samples(&mut st);
+ for view in st.sessions.values() {
+ for tab in &view.tabs {
+ let unread = match &tab.target {
+ ChatTarget::Private(uid) if uid == "demo-4" => 1,
+ ChatTarget::Private(uid) if uid == "demo-2" => 2,
+ _ => 0,
+ };
+ assert_eq!((tab.unread, tab.divider), (unread, None), "{:?}", tab.target);
+ }
+ }
+ }
+
+ #[test]
+ fn unread_from_puts_the_divider_where_asked() {
+ let (mut st, ..) = demo_state();
+ assert!(unread_from(&mut st, 5));
+ let view = &st.sessions[&DEMO];
+ let tab = &view.tabs[view.current_tab];
+ // The divider is above the first message of the last five that is not
+ // ours; all is read.
+ let last = &tab.messages[tab.messages.len() - 5..];
+ assert!(last.iter().any(|m| Some(m.message.id) == tab.divider), "{:?}", tab.divider);
+ assert_eq!(tab.unread, 0);
+ // A chat with fewer messages than that stays as it is.
+ assert!(!unread_from(&mut st, 10_000));
+ st.current = None;
+ assert!(!unread_from(&mut st, 1));
+ }
+
+ #[test]
+ fn the_locked_channel_is_the_officers() {
+ let (mut st, ..) = demo_state();
+ assert_eq!(first_locked_channel(&st), Some((DEMO, 7)));
+ st.current = Some(DEMO + 2);
+ assert_eq!(first_locked_channel(&st), None, "no session there");
+ }
+
+ #[test]
+ fn the_pictures_are_png_files_with_their_events() {
+ let mut saved = Vec::new();
+ let events = pictures("example", |name, png| {
+ assert_eq!(&png[1..4], b"PNG", "{name}");
+ saved.push(name.to_owned());
+ PathBuf::from(name)
+ });
+ // The server's icon, 5 pictures, 4 icons, 5 badges, 6 avatars.
+ assert_eq!(saved.len(), 5 + 4 + 5 + 6);
+ assert_eq!(events.len(), 1 + saved.len());
+ assert!(matches!(&events[0], Event::ServerDetails { address, .. } if address == "example"));
+ assert!(saved.contains(&"avatar-demo-ivy".to_owned()));
+ // The same sample twice gives the same pictures.
+ assert_eq!(demo_picture(64, 36, 3), demo_picture(64, 36, 3));
+ assert_ne!(demo_picture(64, 36, 3), demo_picture(64, 36, 4));
+ }
+
+ #[test]
+ fn the_sample_stores_a_chat_that_only_the_store_has() {
+ let (uid, message, bookmark) = stored_chat(1_000_000);
+ assert_eq!((uid, bookmark), ("demo-dev", DEMO + 2));
+ assert_eq!(message.message.target, ChatTarget::Private("demo-neon".into()));
+ assert_eq!(message.message.author_id, None);
+ let (poke, ts) = poke(1_000_000);
+ assert!(matches!(poke, Event::Poke { from: 3, .. }));
+ assert_eq!(ts, 1_000_000 - 7 * 60_000);
+ assert_eq!(recordings().iter().filter(|r| r.clip).count(), 2);
+ assert_eq!(online_since(1_000_000).len(), 8);
+ }
}
diff --git a/crates/voelin-ui-vm/src/dev/mod.rs b/crates/voelin-ui-vm/src/dev/mod.rs
new file mode 100644
index 0000000..4a284a9
--- /dev/null
+++ b/crates/voelin-ui-vm/src/dev/mod.rs
@@ -0,0 +1,6 @@
+//! The sample data of `VOELIN_DEMO_UI` and the helpers of the development
+//! switches that only look at the state. [`logic`] has the sample servers,
+//! people, chats, contacts, notices and pictures as plain values and as the
+//! events a server would send.
+
+pub mod logic;
diff --git a/crates/voelin-ui-vm/src/lib.rs b/crates/voelin-ui-vm/src/lib.rs
index d2a41fe..4068ae6 100644
--- a/crates/voelin-ui-vm/src/lib.rs
+++ b/crates/voelin-ui-vm/src/lib.rs
@@ -15,6 +15,7 @@ pub mod bbcode;
pub mod bridge;
pub mod chat;
pub mod color;
+pub mod dev;
pub mod emoji;
pub mod events;
pub mod home;
diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs
index 71caa38..0244fee 100644
--- a/crates/voelin-ui/src/app.rs
+++ b/crates/voelin-ui/src/app.rs
@@ -2,11 +2,12 @@
//! event loop glue and the state the screens share.
//!
//! The screens' logic is elsewhere: servers and the channel tree in
-//! `servers.rs`, chat in `chat.rs`, streams in `streams.rs`, the settings
-//! page in `settings_page.rs` and `appearance.rs`, the settings pages in
-//! `settings_pages/`, the Stream Studio in `studio/`, the view models in the
-//! `voelin-ui-vm` crate (`vm`), callbacks in `bind/`, development switches in
-//! `dev.rs`.
+//! `servers/`, chat in `chat/`, streams in `streams/`, the people, the bell
+//! and the search in `social/`, the settings page in `settings_page/` and
+//! `appearance.rs`, the settings pages in `settings_pages/`, the Stream
+//! Studio in `studio/`, what the screens show and what a move or an event
+//! does in the `voelin-ui-vm` crate (`vm`), callbacks in `bind/`,
+//! development switches in `dev/`.
use std::cell::RefCell;
use std::path::{Path, PathBuf};
@@ -234,7 +235,7 @@ pub(crate) struct App {
pub decoder: Option,
/// `VOELIN_DEMO_STREAM`: the viewer shows a local test stream.
pub demo: bool,
- /// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev.rs).
+ /// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev/).
pub demo_ui: bool,
/// `VOELIN_AUTOSHARE=test-pattern`: share the test pattern once streams work.
pub autoshare: bool,
@@ -350,7 +351,7 @@ pub fn run(options: RunOptions) -> Result<()> {
let HostedEngine { engine, runtime, mut events } = hosted;
// VOELIN_DATA_DIR isolates the database; the other development
- // switches are in dev.rs.
+ // switches are in dev/.
// A host that names the data directory (Android) has no platform cache
// directory either: avatars and icons go next to the database.
if let Some(dir) = &options.data_dir {
diff --git a/crates/voelin-ui/src/dev/bind.rs b/crates/voelin-ui/src/dev/bind.rs
new file mode 100644
index 0000000..4ed5083
--- /dev/null
+++ b/crates/voelin-ui/src/dev/bind.rs
@@ -0,0 +1,506 @@
+//! The Slint side of the development switches: the window's size, the
+//! screenshot, the screens opened at start (`VOELIN_OPEN`), and the sample
+//! data fed through the app's own events. The sample data itself is in
+//! `voelin_ui_vm::dev::logic`.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::Result;
+use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
+use voelin_core::{Event, HistoryMessage, HistorySource, JoinFailure};
+use voelin_model::ChatTarget;
+
+use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app};
+use crate::social::now_ms;
+use crate::vm::dev::logic::{self, DEMO};
+
+/// The switches read at start.
+#[derive(Clone, Debug, Default)]
+pub(crate) struct Switches {
+ pub demo_stream: bool,
+ pub demo_ui: bool,
+ pub autoshare: bool,
+ pub open_client: bool,
+ open: Vec,
+ autoconnect: Option,
+ screenshot: Option,
+ screenshot_delay: u64,
+ window_size: Option<(f32, f32)>,
+}
+
+fn flag(name: &str) -> bool {
+ std::env::var(name).is_ok_and(|v| v == "1")
+}
+
+/// `390x844` → (390, 844).
+fn parse_size(text: &str) -> Option<(f32, f32)> {
+ let (w, h) = text.split_once(['x', 'X'])?;
+ Some((w.trim().parse().ok()?, h.trim().parse().ok()?))
+}
+
+impl Switches {
+ pub fn from_env() -> Self {
+ let open: Vec = std::env::var("VOELIN_OPEN")
+ .unwrap_or_default()
+ .split(',')
+ .map(|s| s.trim().to_owned())
+ .filter(|s| !s.is_empty())
+ .collect();
+ Self {
+ demo_stream: flag("VOELIN_DEMO_STREAM"),
+ demo_ui: flag("VOELIN_DEMO_UI"),
+ autoshare: std::env::var("VOELIN_AUTOSHARE").is_ok_and(|v| v == "test-pattern"),
+ open_client: open.iter().any(|o| o == "client"),
+ open,
+ autoconnect: std::env::var("VOELIN_AUTOCONNECT").ok(),
+ screenshot: std::env::var_os("VOELIN_SCREENSHOT").map(Into::into),
+ screenshot_delay: std::env::var("VOELIN_SCREENSHOT_DELAY")
+ .ok()
+ .and_then(|d| d.parse().ok())
+ .unwrap_or(4),
+ window_size: std::env::var("VOELIN_WINDOW_SIZE").ok().as_deref().and_then(parse_size),
+ }
+ }
+}
+
+fn section(name: &str) -> SettingsSection {
+ match name {
+ "1" | "keybinds" | "ptt" => SettingsSection::Keybinds,
+ "2" | "streaming" => SettingsSection::Streaming,
+ "3" | "privacy" => SettingsSection::Privacy,
+ "4" | "appearance" => SettingsSection::Appearance,
+ "5" | "account" => SettingsSection::Account,
+ "6" | "profiles" | "identities" => SettingsSection::Profiles,
+ "7" | "devices" => SettingsSection::Devices,
+ "8" | "notifications" => SettingsSection::Notifications,
+ "9" | "integrations" => SettingsSection::Integrations,
+ "10" | "advanced" => SettingsSection::Advanced,
+ _ => SettingsSection::Voice,
+ }
+}
+
+fn mobile_tab(name: &str) -> MobileTab {
+ match name {
+ "home" => MobileTab::Home,
+ "servers" => MobileTab::Servers,
+ "activity" => MobileTab::Activity,
+ "you" => MobileTab::You,
+ _ => MobileTab::Chat,
+ }
+}
+
+/// Timers that must live while the window runs.
+pub(crate) struct Running {
+ _screenshot: Option,
+ _resize: Option,
+ _scroll: Option,
+ _more: Option,
+}
+
+/// Apply the switches once the app is set up.
+pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
+ if let Some((w, h)) = switches.window_size {
+ ui.window().set_size(slint::LogicalSize::new(w, h));
+ }
+ if switches.demo_ui {
+ with_app(demo_ui);
+ }
+ match switches.autoconnect.as_deref() {
+ Some("voice") => {
+ with_app(|app| app.connect_voice());
+ }
+ Some("observe") => {
+ with_app(|app| {
+ if let Some(id) = app.state.current {
+ app.observe(id);
+ }
+ });
+ }
+ _ => {}
+ }
+ let nav = ui.global::();
+ for open in &switches.open {
+ let (what, arg) = open.split_once(':').unwrap_or((open.as_str(), ""));
+ match what {
+ "home" => nav.invoke_show(Page::Home),
+ "server" => {
+ nav.invoke_show(Page::Server);
+ // The server chat, which starts with the welcome message.
+ if arg == "chat" {
+ with_app(|app| app.select_tab(0));
+ }
+ }
+ "settings" => nav.invoke_open_settings(section(arg)),
+ "about" => nav.invoke_open_about(),
+ "share" => {
+ nav.invoke_open_share();
+ // The sample share of the test pattern, live at once.
+ if arg == "live" && switches.demo_ui {
+ with_app(|app| app.demo_share());
+ }
+ }
+ // The current server's dialog, Advanced open.
+ "bookmark" if arg == "edit" => {
+ if let Some(id) = with_app(|app| app.state.current).flatten() {
+ nav.invoke_edit_server(id as i32);
+ }
+ }
+ // `join`: the same dialog (Join a server was one of its own).
+ "bookmark" | "join" => nav.invoke_add_server(),
+ "emoji" => nav.set_emoji_open(true),
+ "panel" => nav.set_right_panel_open(true),
+ "no-panel" => nav.set_right_panel_open(false),
+ "tab" => nav.set_mobile_tab(mobile_tab(arg)),
+ "voice" => {
+ nav.invoke_show_voice(true);
+ // The smaller stage, for this run only.
+ if arg == "compact" {
+ nav.set_voice_compact(true);
+ }
+ }
+ "pins" => nav.invoke_show_pins(true),
+ // Opened once laid out (below).
+ "more" => {}
+ // The phone's members page.
+ "members" => nav.set_members_open(true),
+ // What Android hands over: a tapped voice notification, text
+ // shared to the app.
+ "notification" => crate::inbox::request(crate::inbox::Request::ShowVoice),
+ "shared" => crate::inbox::request(crate::inbox::Request::Share {
+ text: Some(arg.to_owned()),
+ files: Vec::new(),
+ }),
+ "topics" => nav.invoke_show_topics(true),
+ "topic" => {
+ with_app(|app| {
+ app.open_topic(arg.parse().unwrap_or(1));
+ // No gateway answers in demo mode.
+ if switches.demo_ui {
+ app.handle_event(logic::topic_history(now_ms()));
+ }
+ });
+ }
+ "member" => {
+ with_app(|app| app.open_first_member());
+ }
+ // After `friends` the contact path (Kairo without a contact
+ // chosen), else the member card's.
+ "poke" => {
+ let friends = nav.get_page() == Page::Friends;
+ with_app(|app| {
+ if friends {
+ let uid = app.social.selected.clone().unwrap_or_else(|| "demo-3".into());
+ app.contact_action(&uid, "poke");
+ } else {
+ app.open_first_member();
+ app.member_action("poke");
+ }
+ });
+ }
+ "channel-password" => {
+ with_app(|app| open_channel_password(app, arg == "wrong"));
+ }
+ // A screenshot cannot hover.
+ "actions" => nav.set_show_actions(true),
+ // Home as before the first server, over the sample data.
+ "first-run" => nav.set_first_run(true),
+ // `end`: further back, so the divider is above the view.
+ "unread" => {
+ with_app(|app| open_unread(app, if arg == "end" { 10 } else { 5 }));
+ }
+ "link-confirm" => {
+ let url = if arg.is_empty() { logic::DEMO_RAID_BOARD } else { arg };
+ with_app(|app| app.open_link_text(url, true));
+ }
+ // As a link from the platform comes.
+ "link" => crate::inbox::request(crate::inbox::Request::OpenLink(arg.to_owned())),
+ "watch" | "popout" => {
+ with_app(|app| {
+ if switches.demo_ui {
+ app.demo_watch();
+ } else {
+ app.watch_first_stream();
+ }
+ if what == "popout" {
+ app.viewer_pop_out();
+ }
+ });
+ }
+ "theatre" => nav.set_theatre(true),
+ // Home, friends, messages, events, the bell, the search.
+ "friends" => {
+ with_app(|app| app.select_contact(arg.to_owned()));
+ nav.invoke_show(Page::Friends);
+ }
+ "messages" | "dm" => {
+ let uid = if arg.is_empty() { "demo-3" } else { arg };
+ with_app(|app| app.open_dm_with(Some(logic::DEMO), uid));
+ nav.invoke_show(Page::Messages);
+ }
+ "inbox" => {
+ nav.set_dm_tab(2);
+ with_app(|app| app.dm_tab(2));
+ nav.invoke_show(Page::Messages);
+ }
+ "library" => nav.invoke_show(Page::Library),
+ "events" => nav.invoke_show(Page::Events),
+ "event-form" => nav.invoke_create_event(),
+ "search" => nav.invoke_open_search(arg.into()),
+ "notifications" => nav.set_notifications_open(true),
+ "offline" => nav.invoke_write_offline("demo-ari".into(), "Ari".into()),
+ "picture" => {
+ let picture = logic::demo_picture(1280, 720, 16);
+ let image = crate::images::picture("demo:lightbox", &picture);
+ nav.set_lightbox(image);
+ nav.set_lightbox_open(true);
+ }
+ // The camera preview of the settings (the test pattern).
+ "camera" => {
+ with_app(|app| {
+ app.start_camera();
+ app.refresh_pages();
+ });
+ }
+ "studio" => {
+ if arg != "window" {
+ nav.invoke_open_studio();
+ }
+ with_app(|app| app.studio_dev(arg));
+ }
+ // Opened once connected (settings_page.rs).
+ "client" => {}
+ other => eprintln!("VOELIN_OPEN: unknown screen {other:?}"),
+ }
+ }
+ // A window manager can refuse the size set before the window opened,
+ // so ask again once it is up. (Under `xvfb-run` in a Wayland session,
+ // remove WAYLAND_DISPLAY, or winit opens the window on the desktop.)
+ let resize = switches.window_size.map(|(w, h)| {
+ let weak = ui.as_weak();
+ let timer = slint::Timer::default();
+ timer.start(
+ slint::TimerMode::SingleShot,
+ Duration::from_millis(switches.screenshot_delay * 1000 / 2),
+ move || {
+ if let Some(ui) = weak.upgrade() {
+ ui.window().set_size(slint::LogicalSize::new(w, h));
+ }
+ },
+ );
+ timer
+ });
+ // `unread`: up to the divider once the list is laid out (after the
+ // resize above).
+ let scroll = switches.open.iter().any(|o| o == "unread").then(|| {
+ late(ui, switches, |ui| {
+ let bridge = ui.global::();
+ bridge.set_jump_index(bridge.get_unread_index());
+ bridge.set_jump_requests(bridge.get_jump_requests().wrapping_add(1));
+ })
+ });
+ // `more`: the phone voice screen's More menu (a screenshot cannot tap).
+ let more = switches.open.iter().any(|o| o == "more").then(|| {
+ late(ui, switches, |ui| {
+ let nav = ui.global::();
+ nav.set_more_requests(nav.get_more_requests().wrapping_add(1));
+ })
+ });
+ let screenshot = switches.screenshot.clone().map(|path| {
+ let weak = ui.as_weak();
+ let timer = slint::Timer::default();
+ timer.start(
+ slint::TimerMode::SingleShot,
+ Duration::from_secs(switches.screenshot_delay),
+ move || {
+ if let Some(ui) = weak.upgrade() {
+ if let Err(e) = save_screenshot(&ui, &path) {
+ eprintln!("screenshot failed: {e}");
+ }
+ let _ = ui.hide();
+ // Also when the studio's or the stream's own window is
+ // open.
+ let _ = slint::quit_event_loop();
+ }
+ },
+ );
+ timer
+ });
+ Running { _screenshot: screenshot, _resize: resize, _scroll: scroll, _more: more }
+}
+
+/// A timer that runs `action` at three quarters of the screenshot delay, once
+/// the window has its size and the screens are laid out.
+fn late(
+ ui: &MainWindow,
+ switches: &Switches,
+ action: impl Fn(&MainWindow) + 'static,
+) -> slint::Timer {
+ let weak = ui.as_weak();
+ let timer = slint::Timer::default();
+ timer.start(
+ slint::TimerMode::SingleShot,
+ Duration::from_millis(switches.screenshot_delay * 1000 * 3 / 4),
+ move || {
+ if let Some(ui) = weak.upgrade() {
+ action(&ui);
+ }
+ },
+ );
+ timer
+}
+
+fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> {
+ let mut image = ui.window().take_snapshot()?;
+ let window = with_app(|app| app.studio_snapshot().or_else(|| app.viewer_snapshot())).flatten();
+ if let Some(window) = window {
+ let stem = path.file_stem().unwrap_or_default().to_string_lossy();
+ save_png(&window, &path.with_file_name(format!("{stem}-window.png")))?;
+ paste(&mut image, &window);
+ }
+ save_png(&image, path)
+}
+
+/// Draw `top` over the bottom right of `image` with a border, as a second
+/// window sits on a desktop.
+fn paste(image: &mut SharedPixelBuffer, top: &SharedPixelBuffer) {
+ let (w, h) = (image.width() as usize, image.height() as usize);
+ let (tw, th) = (top.width() as usize, top.height() as usize);
+ let (x0, y0) = (w.saturating_sub(tw + 24), h.saturating_sub(th + 24));
+ let border = Rgba8Pixel { r: 0x3f, g: 0x7b, b: 0xff, a: 0xff };
+ let pixels = image.make_mut_slice();
+ for y in y0.saturating_sub(1)..(y0 + th + 1).min(h) {
+ for x in x0.saturating_sub(1)..(x0 + tw + 1).min(w) {
+ let (ty, tx) = (y.wrapping_sub(y0), x.wrapping_sub(x0));
+ pixels[y * w + x] =
+ if ty < th && tx < tw { top.as_slice()[ty * tw + tx] } else { border };
+ }
+ }
+}
+
+fn save_png(image: &SharedPixelBuffer, path: &std::path::Path) -> Result<()> {
+ let file = std::io::BufWriter::new(std::fs::File::create(path)?);
+ let mut encoder = png::Encoder::new(file, image.width(), image.height());
+ encoder.set_color(png::ColorType::Rgba);
+ encoder.set_depth(png::BitDepth::Eight);
+ encoder.write_header()?.write_image_data(image.as_bytes())?;
+ Ok(())
+}
+
+/// The current chat's read marker `back` messages before its end
+/// ([`logic::unread_from`]), its "New" divider shown (`VOELIN_OPEN=unread`).
+fn open_unread(app: &mut App, back: usize) {
+ if logic::unread_from(&mut app.state, back) {
+ app.refresh_chat();
+ app.refresh_servers();
+ }
+}
+
+/// `VOELIN_OPEN=channel-password`: join the current server's first locked
+/// channel, which asks for its password; `wrong` as if the server had
+/// refused one.
+fn open_channel_password(app: &mut App, wrong: bool) {
+ let Some((session, channel)) = logic::first_locked_channel(&app.state) else { return };
+ if wrong {
+ if let Some(view) = app.view_mut() {
+ view.channel_passwords.insert(channel, "guess".into());
+ }
+ app.join_failed(session, channel, JoinFailure::Password);
+ } else {
+ app.join_channel(session, channel);
+ }
+}
+
+/// Sample data through the same events a server would send.
+fn demo_ui(app: &mut App) {
+ app.state.bookmarks = logic::bookmarks();
+ app.state.settings.last_voice = Some(logic::last_voice());
+ app.state.current = Some(DEMO);
+ for event in logic::server_events() {
+ app.handle_event(event);
+ }
+ demo_pictures(app);
+ for event in logic::chat_events(now_ms()) {
+ app.handle_event(event);
+ }
+ demo_social(app);
+ // No toast over the screenshots.
+ app.set_status("");
+ app.refresh_all();
+}
+
+/// Avatars, icons, banners and badges as the engine reports them once they
+/// are in its cache (here a folder of synthetic pictures in the temporary
+/// directory).
+fn demo_pictures(app: &mut App) {
+ let dir = std::env::temp_dir().join("voelin-demo-pictures");
+ let _ = std::fs::create_dir_all(&dir);
+ let address = app.bookmark(DEMO).map(|b| b.address.clone()).unwrap_or_default();
+ let events = logic::pictures(&address, |name, png| {
+ let path = dir.join(name);
+ let _ = std::fs::write(&path, png);
+ path
+ });
+ for event in events {
+ app.handle_event(event);
+ }
+}
+
+/// Sample people, private chats, pokes, notifications, events, a picture
+/// and recordings for the home, friends, messages, events and settings
+/// screens (`VOELIN_DEMO_UI`).
+fn demo_social(app: &mut App) {
+ let now = now_ms();
+ // The second sample server is observed: a few people there.
+ for event in logic::lounge_events() {
+ app.handle_event(event);
+ }
+ app.handle_event(Event::ContactsChanged { contacts: Arc::new(logic::contacts(now)) });
+ for (uid, since) in logic::online_since(now) {
+ app.social.online_since.insert(uid.into(), since);
+ }
+ for event in logic::private_chat_events(now) {
+ app.handle_event(event);
+ }
+ let (server_uid, chat, bookmark) = logic::stored_chat(now);
+ app.social.dm.stored.push((server_uid.into(), chat));
+ app.social.dm.bookmark_of.insert(server_uid.into(), bookmark);
+ logic::read_samples(&mut app.state);
+ let (poke, ts_ms) = logic::poke(now);
+ app.handle_event(poke);
+ if let Some(p) = app.social.pokes.last_mut() {
+ p.ts_ms = ts_ms;
+ }
+ app.handle_event(logic::offline_messages(now));
+ logic::link_previews(&mut app.state);
+ for event in logic::gateway_events(now) {
+ app.handle_event(event);
+ }
+ for n in logic::notices() {
+ app.notify(n.kind, n.title, n.body, n.target, n.name, n.uid);
+ }
+ logic::age_notices(&mut app.social, now);
+ app.refresh_notices();
+ app.models.social.recordings.sync(&logic::recordings());
+ app.refresh_chats();
+ app.refresh_people();
+ app.refresh_home();
+}
+
+/// Answer [`App::load_older`] in demo mode (no engine runs) with
+/// [`logic::demo_older`], a moment later as a server would.
+pub(crate) fn answer_older(session: i64, target: ChatTarget, oldest: Option) {
+ slint::Timer::single_shot(Duration::from_millis(600), move || {
+ let now = now_ms();
+ let (messages, complete) = logic::demo_older(&target, oldest.as_ref(), now);
+ with_app(|app| {
+ app.handle_event(Event::ChatHistory {
+ session: session as u64,
+ target,
+ messages,
+ source: HistorySource::Gateway,
+ complete,
+ });
+ });
+ });
+}
diff --git a/crates/voelin-ui/src/dev/mod.rs b/crates/voelin-ui/src/dev/mod.rs
new file mode 100644
index 0000000..5575ca7
--- /dev/null
+++ b/crates/voelin-ui/src/dev/mod.rs
@@ -0,0 +1,67 @@
+//! Development switches (environment variables), for trying screens and
+//! taking screenshots without a server:
+//!
+//! - `VOELIN_DATA_DIR=`: the database (app.rs).
+//! - `VOELIN_AUTOCONNECT=voice|observe`: connect the first bookmark on start.
+//! - `VOELIN_SCREENSHOT=`: save the window after
+//! `VOELIN_SCREENSHOT_DELAY` seconds (default 4) and exit.
+//! - `VOELIN_WINDOW_SIZE=x`: the window's size (e.g. `390x844` for the
+//! phone layout).
+//! - `VOELIN_DEMO_UI=1`: sample servers, channels, chat (two pages of older
+//! messages answer scrolling up) and streams, no server needed (nothing is
+//! stored).
+//! - `VOELIN_DEMO_STREAM=1`: a local test stream in the viewer.
+//! - `VOELIN_OPEN=[,...]`: open screens on start: `home`,
+//! `server` (`server:chat`: its server chat), `settings[:]`
+//! (voice, keybinds, streaming, privacy, appearance, or 0-4), `about`,
+//! `share`, `bookmark` (add a server, also `join`;
+//! `bookmark:edit` the current one, Advanced open),
+//! `emoji` (the picker), `client` (the volume dialog of the first other
+//! client once connected), `panel` / `no-panel` (the members panel),
+//! `voice` (the voice channel view; on the phone its own screen;
+//! `voice:compact` with the smaller stage, not stored),
+//! `more` (after `voice` on the phone: the voice screen's More menu,
+//! opened once the screen is laid out),
+//! `members` (the phone's members page), `notification` (a tapped voice
+//! notification), `shared:` (text shared to the app on Android),
+//! `pins`, `topics` (the drawers),
+//! `topic:` (a topic's messages), `member` (the member card of the
+//! first other client), `poke` (the poke dialog: for the contact shown
+//! after `friends`, else for the first other client, its card open),
+//! `channel-password` (the password dialog of the first locked channel,
+//! the sample's Officers; `channel-password:wrong` as after a refused
+//! one), `actions` (the last message's actions, as if hovered),
+//! `first-run` (home's banner as before the first server, over the
+//! sample data),
+//! `unread` (the current chat read up to five messages before its end:
+//! the "New" divider, scrolled up to; `unread:end` ten messages before,
+//! at the list's end, under the bar that counts the new messages),
+//! `link-confirm[:]` (the question before a masked link opens, by
+//! default the sample's raid board), `link:` (a TeamSpeak link
+//! opened: the server dialog filled in from it, or in voice on its
+//! server a move into its channel), `watch` (the first stream; with
+//! sample data the local test pattern in its place), `theatre` (after
+//! `watch`: in theatre mode), `popout` (`watch` in a window of its own),
+//! `tab:` (phone layout); `friends[:]`,
+//! `messages[:]` (a private chat), `inbox` (offline messages),
+//! `library`, `events`, `event-form`, `search[:]`,
+//! `notifications` (the bell), `offline` (an offline message), `picture`
+//! (a chat picture opened large), `camera` (the settings' camera
+//! preview); settings sections also `account`,
+//! `profiles` (also `identities`), `devices`, `notifications`,
+//! `integrations`, `advanced` (5-10);
+//! `studio[:]`: the Stream Studio (with `VOELIN_DEMO_UI` a demo
+//! studio from synthetic sources), `studio:window` in a window of its own,
+//! `studio:live` going live (also with a screen opened after it:
+//! `studio:live,server,voice` shows our stream's card with the studio's
+//! picture), `studio:record`, or a dialog: `studio:source`,
+//! `studio:audio`, `studio:camera`, `studio:scene`, `studio:settings`.
+//! A screenshot also saves the studio's window, or the stream's
+//! (`-window.png`), and draws it over the main window.
+//! - `VOELIN_AUTOWATCH=1`: watch the first stream that shows up.
+//! - `VOELIN_AUTOSHARE=test-pattern`: share the test pattern (accepting
+//! everyone) once connected to a TeamSpeak 6 server.
+
+mod bind;
+
+pub(crate) use bind::{Switches, answer_older, start};
diff --git a/crates/voelin-ui/src/popout.rs b/crates/voelin-ui/src/popout.rs
index fa06a7b..f3f6792 100644
--- a/crates/voelin-ui/src/popout.rs
+++ b/crates/voelin-ui/src/popout.rs
@@ -129,7 +129,7 @@ impl App {
self.with_player(|_, window| crate::streams::show_cursor(window, shown));
}
- /// A picture of the viewer's window (screenshots, dev.rs).
+ /// A picture of the viewer's window (screenshots, dev/).
pub(crate) fn viewer_snapshot(&self) -> Option> {
self.popout.window.as_ref()?.window().take_snapshot().ok()
}
diff --git a/crates/voelin-ui/src/studio/bind.rs b/crates/voelin-ui/src/studio/bind.rs
index fd9a3cc..14c5cc4 100644
--- a/crates/voelin-ui/src/studio/bind.rs
+++ b/crates/voelin-ui/src/studio/bind.rs
@@ -1253,12 +1253,12 @@ impl App {
});
}
- /// A picture of the studio window (screenshots, dev.rs).
+ /// A picture of the studio window (screenshots, dev/).
pub(crate) fn studio_snapshot(&self) -> Option> {
self.studio.window.as_ref()?.window().take_snapshot().ok()
}
- // Development switches and sample data (dev.rs).
+ // Development switches and sample data (dev/).
/// `VOELIN_OPEN=studio:`: `window` (the window of its own), `live`,
/// `record`, or a dialog: `source`, `audio`, `camera`, `scene`, `settings`.
diff --git a/crates/voelin-ui/ui/nav.slint b/crates/voelin-ui/ui/nav.slint
index bdf8a41..f558a7b 100644
--- a/crates/voelin-ui/ui/nav.slint
+++ b/crates/voelin-ui/ui/nav.slint
@@ -1,6 +1,6 @@
// Where the user is: the page, open dialogs, panel sizes. Any screen can
// navigate through these functions; Rust sets the same properties for the
-// development switch VOELIN_OPEN (src/dev.rs).
+// development switch VOELIN_OPEN (src/dev/mod.rs).
import { Bridge, BookmarkForm, ShareForm, EventForm, OfflineForm } from "bridge.slint";
import { StudioBridge } from "studio-bridge.slint";
diff --git a/docs/ui.md b/docs/ui.md
index c0c6f7a..bcd3976 100644
--- a/docs/ui.md
+++ b/docs/ui.md
@@ -39,6 +39,7 @@ crates/voelin-ui-vm/ view models and state, no UI toolkit
settings.rs the UI's settings keys, the audio form
settings_pages/logic.rs, studio/logic.rs
the decisions of the settings pages and of the Stream Studio
+ dev/logic.rs the sample data of `VOELIN_DEMO_UI` as plain values and events
social/logic.rs the friends, the bell and the search as rows, what the user's moves on
them do, and what an event does to the friends, pokes and notices
settings_page/logic.rs
@@ -93,7 +94,9 @@ crates/voelin-ui/ the Slint front end
(plain values → Slint values), rows.rs (a Slint model kept in step
with a plain list)
images.rs the image cache (LRU, bounded by `ui.image_cache_mb`)
- dev.rs development switches (screenshots, sample data)
+ dev/ mod.rs (the switches, listed), bind.rs: the window's size, the
+ screenshot, the screens opened at start, the sample data fed through
+ the app's own events
```
Models are created once (`app::Models`) and updated row by row with
@@ -164,7 +167,7 @@ this file is `voelin_ui_vm::chat`. The boundary:
settings service, the `AppState` and plain rows; they return rows,
commands or messages for the status line, and write no Bridge) and
` /bind.rs` in `voelin-ui` (the Bridge and model writes, windows,
- timers, threads, engine commands). Done: `settings_pages`, `studio`, `streams`, `chat`, `servers`, `settings_page` and `social`.
+ timers, threads, engine commands). Done: `settings_pages`, `studio`, `streams`, `chat`, `servers`, `settings_page`, `social` and `dev`.
The pure code is tested in `voelin-ui-vm` (`cargo test -p voelin-ui-vm`,
no display); the Slint crate's tests are what needs the window types.
@@ -186,7 +189,6 @@ the same shape as `settings_pages` and `studio`: move the decisions into
| File | `.set_` calls | What it mixes |
|---|---|---|
| `app.rs` | 31 | setup, the status line, the toolbar and tree refreshes (the event dispatch is `vm::events::apply`) |
-| `dev.rs` | 23 | development switches and the sample data (the switches stay with the window; the sample rows can move) |
| `images.rs` | 13 | the decoded-picture cache |
| `messages.rs` | 12 | direct messages |
| `appearance.rs` | 11 | theme, font scale and breakpoints |
@@ -583,7 +585,7 @@ for importing the official clients' identities on start
the Slint side as `impl App` in `voelin-ui/src/.rs`, with the
decisions in the view-model crate (`/logic.rs`, [Two
crates](#two-crates)).
-5. A development switch to open it (`dev.rs`, `VOELIN_OPEN=`), a
+5. A development switch to open it (`dev/bind.rs`, `VOELIN_OPEN=`), a
screenshot (below) and a line in this file.
## Settings
@@ -669,7 +671,7 @@ notifications and the home's news show the text on one line
## Development switches and screenshots
-Environment variables (see `src/dev.rs`):
+Environment variables (see `src/dev/mod.rs`):
- `VOELIN_DEMO_UI=1`: sample servers, channels, members, chat with
formatting and emoji (and two pages of older messages, which load when