mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:22:39 +00:00
top-w5: net change of 4 commits
- top-w5: written by an agent - top-w5: review fixes (review-1.md) - top-w5: read_last_update doc follows the updater arm (review-1 item 2) - top-w5: the opening card's progress bar is named by the card's title (top run round)
This commit is contained in:
@@ -1,27 +1,37 @@
|
||||
//! `OpeningCard`: the card shown in the document area while a file opens.
|
||||
|
||||
use crate::contract::Pattern;
|
||||
use crate::runtime::env::Label;
|
||||
use egui::{Response, Ui};
|
||||
use super::words::ShellWords;
|
||||
use crate::buttons::Button;
|
||||
use crate::contract::{Gap, Outcome, Pad, Pattern, Props as _, Show as _, ShowContainer as _, Sizing, clicked};
|
||||
use crate::display::{Elide, Progress, Shade, Text};
|
||||
use crate::layout::RowAlign;
|
||||
use crate::layout_components::{Row, Stack};
|
||||
use crate::runtime::env::{Env, Label};
|
||||
use crate::style::{SurfaceKind, TypeRole};
|
||||
use egui::{Layout, Response, Ui, UiBuilder};
|
||||
|
||||
#[cfg(feature = "testing")]
|
||||
mod stories;
|
||||
|
||||
/// A centred card: "Opening {name}…" elided on one line with the full text on hover, the muted message, a progress bar
|
||||
/// (indeterminate without a fraction), the percentage at the start and Cancel at the end of the last row. Job UI
|
||||
/// only: the fraction and the cancel answer come from the app's engine job.
|
||||
///
|
||||
/// The card takes the room it is shown in and sits at its centre; its height follows its content. Cancel reports
|
||||
/// `cancelled` in the pass of the click only, so a second pass in the same frame, which gets no input, reports none.
|
||||
#[must_use = "show the card with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct OpeningCard {
|
||||
#[allow(dead_code)] // P3(top-w5): tp.T31
|
||||
name: Label,
|
||||
#[allow(dead_code)] // P3(top-w5): tp.T31
|
||||
message: Option<Label>,
|
||||
#[allow(dead_code)] // P3(top-w5): tp.T31
|
||||
fraction: Option<f32>,
|
||||
#[allow(dead_code)] // P3(top-w5): tp.T31
|
||||
cancel: Option<Label>,
|
||||
}
|
||||
|
||||
/// What an [`OpeningCard`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the app cancels the job when `cancelled` is set"]
|
||||
pub struct OpeningCardOutput {
|
||||
/// The card's response.
|
||||
pub response: Response,
|
||||
@@ -29,6 +39,14 @@ pub struct OpeningCardOutput {
|
||||
pub cancelled: bool,
|
||||
}
|
||||
|
||||
impl Outcome for OpeningCardOutput {
|
||||
type Value = crate::contract::NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
impl OpeningCard {
|
||||
/// A card for the file `name`.
|
||||
pub fn new(name: impl Into<Label>) -> Self {
|
||||
@@ -56,9 +74,43 @@ impl OpeningCard {
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the card centred in `ui`.
|
||||
/// Shows the card centred in `ui`'s free room.
|
||||
pub fn show(self, ui: &mut Ui) -> OpeningCardOutput {
|
||||
let _ = ui;
|
||||
todo!("tp.T31")
|
||||
let OpeningCard { name, message, fraction, cancel } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<ShellWords>();
|
||||
let title = words.opening.fill(&[("name", name.as_str())]);
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let width = room.width().min(env.tokens.size.dialog.least);
|
||||
let mut cancelled = false;
|
||||
let placed = ui.scope_builder(UiBuilder::new().max_rect(room).layout(Layout::centered_and_justified(egui::Direction::TopDown)), |ui| {
|
||||
ui.set_max_width(width);
|
||||
let _ = Stack::new().pad(Pad::Roomy).gap(Gap::Section).surface(SurfaceKind::Dialog).fill_width().show(ui, |ui, _| {
|
||||
let _ = Text::new(title.clone()).role(TypeRole::BodyStrong).elide(Elide::End).sizing(Sizing::FillWidth).show(ui);
|
||||
if let Some(message) = &message {
|
||||
let _ = Text::new(message.clone()).shade(Shade::Muted).elide(Elide::End).sizing(Sizing::FillWidth).show(ui);
|
||||
}
|
||||
let _ = match fraction {
|
||||
Some(fraction) => Progress::new(fraction).label(title.clone()).sizing(Sizing::FillWidth).show(ui),
|
||||
None => Progress::indeterminate().label(title.clone()).sizing(Sizing::FillWidth).show(ui),
|
||||
};
|
||||
let percent = fraction.map(|fraction| env.units().percent(f64::from((Progress::clamped(fraction) * 100.0).round())));
|
||||
if percent.is_some() || cancel.is_some() {
|
||||
// With one child a space-between row would put it at the start edge; Cancel alone belongs at the end.
|
||||
let align = if percent.is_some() { RowAlign::SpaceBetween } else { RowAlign::End };
|
||||
let _ = Row::new().align(align).fill_width().show(ui, |ui, _| {
|
||||
if let Some(percent) = &percent {
|
||||
let _ = Text::new(percent.clone()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
if let Some(cancel) = &cancel
|
||||
&& clicked(&Button::new(cancel.clone()).id_salt("cancel").show(ui))
|
||||
{
|
||||
cancelled = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
OpeningCardOutput { response: placed.response, cancelled }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
//! Stories of `OpeningCard`.
|
||||
|
||||
use super::OpeningCard;
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
#[story(OpeningCard, covers = [], drive = Drive::Never)]
|
||||
fn opening_card(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
|
||||
OpeningCard::new("Poster.psd").message("Reading layers…").fraction(Some(0.42)).cancel("Cancel").show(ui).into()
|
||||
}
|
||||
|
||||
#[story(OpeningCard, covers = [], drive = Drive::Never)]
|
||||
fn opening_card_with_a_long_name(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
|
||||
OpeningCard::new("a7rv-test_2024_02_17_shot_30_3705_with_an_even_longer_suffix_that_never_ends.psb")
|
||||
.message("Reading layers…")
|
||||
.fraction(Some(0.75))
|
||||
.cancel("Cancel")
|
||||
.show(ui)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[story(OpeningCard, covers = [], drive = Drive::Never)]
|
||||
fn opening_card_without_a_fraction(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
|
||||
OpeningCard::new("Poster.psd").message("Reading…").cancel("Cancel").show(ui).into()
|
||||
}
|
||||
|
||||
#[story(OpeningCard, covers = [], drive = Drive::Never)]
|
||||
fn opening_card_without_cancel(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
|
||||
OpeningCard::new("Poster.psd").fraction(Some(0.9)).show(ui).into()
|
||||
}
|
||||
@@ -4,10 +4,8 @@ use craft_i18n::Collator;
|
||||
use std::cmp::Ordering;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::primitives::Revision;
|
||||
|
||||
/// The key a start screen's thumbnail has in the app's texture store. The app loads the picture for the key and
|
||||
/// revision a card names; the screen only reads the store.
|
||||
/// The key a start screen's thumbnail has. The screen asks `Thumbnails::state` for the key at the painted cell, and
|
||||
/// the app's `ThumbSource` answers its revision and renders the picture.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum ThumbKey {
|
||||
@@ -29,15 +27,12 @@ pub struct RecentFile {
|
||||
pub opened: Option<i64>,
|
||||
/// Created, in seconds since the Unix epoch, for sorting by Created.
|
||||
pub created: Option<i64>,
|
||||
/// The revision of the picture stored under [`ThumbKey::Recent`] with this path; `None` for a file with no
|
||||
/// thumbnail.
|
||||
pub thumbnail: Option<Revision>,
|
||||
}
|
||||
|
||||
impl RecentFile {
|
||||
/// A recent file at `path` shown as `name`, with no dates and no thumbnail.
|
||||
/// A recent file at `path` shown as `name`, with no dates.
|
||||
pub fn new(path: impl Into<PathBuf>, name: impl Into<String>) -> Self {
|
||||
RecentFile { path: path.into(), name: name.into(), opened: None, created: None, thumbnail: None }
|
||||
RecentFile { path: path.into(), name: name.into(), opened: None, created: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,15 +46,12 @@ pub struct Template {
|
||||
pub name: String,
|
||||
/// The line under the name: "1920 × 1080 px".
|
||||
pub detail: String,
|
||||
/// The revision of the picture stored under [`ThumbKey::Template`] with this id; `None` for a card with no
|
||||
/// preview.
|
||||
pub thumbnail: Option<Revision>,
|
||||
}
|
||||
|
||||
impl Template {
|
||||
/// A template `id` named `name`, with `detail` under the name and no preview.
|
||||
/// A template `id` named `name`, with `detail` under the name.
|
||||
pub fn new(id: impl Into<String>, name: impl Into<String>, detail: impl Into<String>) -> Self {
|
||||
Template { id: id.into(), name: name.into(), detail: detail.into(), thumbnail: None }
|
||||
Template { id: id.into(), name: name.into(), detail: detail.into() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,27 +6,31 @@ mod stories;
|
||||
|
||||
use super::recent::{RecentFile, RecentSort, RecentView, Template, ThumbKey, sort_recent};
|
||||
use super::words::ShellWords;
|
||||
use crate::buttons::Button;
|
||||
use crate::buttons::{Button, Link};
|
||||
use crate::choice::Segmented;
|
||||
use crate::contract::{
|
||||
ActivateOn, Bind, CollectionEvent, Entry, Gap, NoValue, Outcome, Pad, Pattern, Props, Remember as _, Scroll, SelectMode, Show as _,
|
||||
ActivateOn, Bind, BodyCx, CollectionEvent, Entry, Gap, NoValue, Outcome, Pad, Pattern, Props, Remember as _, Scroll, SelectMode, Show as _,
|
||||
ShowCollection as _, ShowContainer as _, Sizing, clicked,
|
||||
};
|
||||
use crate::display::{Divider, Icon};
|
||||
use crate::layout_components::{Row, Stack};
|
||||
use crate::list::{List, ListRow, ThumbAspect};
|
||||
use crate::list::{List, ListRow, RowEvent, ThumbAspect, ThumbSize, TrailingFace, TrailingPart};
|
||||
use crate::menu::{Menu, MenuItem};
|
||||
use crate::notices::{Notice, NoticeLayout};
|
||||
use crate::pickers::Select;
|
||||
use crate::primitives::{CachedTexture, ContentPainterCx, IconSpec, Revision, TextureState, TextureStore, ThumbSource, Thumbnails};
|
||||
use crate::runtime::commands::CommandRef;
|
||||
use crate::primitives::{
|
||||
CheckerArea, ContentPainterCx, IconSpec, Priority, ThumbPaint, ThumbRequest, ThumbSource, Thumbnails,
|
||||
};
|
||||
use crate::runtime::commands::{self, CommandRef, FireSource};
|
||||
use crate::runtime::commands::{CommandSet as _, Commands as _};
|
||||
use crate::runtime::env::{AgeStyle, Env, Label};
|
||||
use crate::sections::Section;
|
||||
use crate::tile_grid::{CaptionPlace, Tile, TileGrid, TilePartEvent, TileStatus};
|
||||
use craft_behavior::{IconId, SelectionChange, keyed};
|
||||
use crate::style::{Corners, SurfaceKind, SurroundLook, paint_surround};
|
||||
use crate::tile_grid::{CaptionPlace, Tile, TileGrid, TilePartEvent};
|
||||
use craft_behavior::{IconId, Proposal, SelectionChange, keyed};
|
||||
use craft_theme::Variant;
|
||||
use craft_theme::variant::Tone;
|
||||
use egui::{Pos2, Rect, Response, Ui};
|
||||
use egui::{CornerRadius, Rect, Response, Ui, Vec2};
|
||||
use std::borrow::Cow;
|
||||
use std::cell::RefCell;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -41,6 +45,9 @@ const PICTURE_HIGH: u16 = 9;
|
||||
/// The number of recent files shown until `max_recent` says otherwise.
|
||||
const RECENT_SHOWN: usize = 12;
|
||||
|
||||
/// The revealed part of a recent row that takes the file off the list.
|
||||
const REMOVE: TrailingPart = TrailingPart::new(0);
|
||||
|
||||
/// The commands of a recent file's context menu. They act on the file that has the lead in the recent files, which a
|
||||
/// secondary click or the context-menu key gives to the file the menu is for. Delete at the lead of the recent files is
|
||||
/// the list's own delete request and reports the same `RemoveRecent`; `Remove` shows that chord in the menu.
|
||||
@@ -127,8 +134,12 @@ impl Outcome for StartOutput {
|
||||
/// - **Recent files.** A grid of cards or a list, by the `view` binding, in the order of the `sort` binding. A click or
|
||||
/// Enter opens a file; arrows move; the context menu (secondary click, the menu key or Shift+F10) and the
|
||||
/// [`StartRecentCommands`] remove it from the list, clear the list or show it in its folder.
|
||||
/// - **Thumbnails.** A file or template with a revision shows the picture the `thumbnails` store holds for its
|
||||
/// [`ThumbKey`] and that revision: a placeholder until the store has it, a failure mark when loading failed.
|
||||
/// - **Thumbnails.** With `thumbnails(store, source)`, each card, row and template asks the store for its
|
||||
/// [`ThumbKey`] at the size it paints: a placeholder until the picture is ready, a failure mark when loading failed,
|
||||
/// the file icon when the source has no picture for the key. Without it cards show the file icon.
|
||||
/// - **Links.** `links` adds a rail beside the page (New and Open, then the links) in a room wide enough, else the
|
||||
/// links follow the sections. A double click on the page's own room opens a file, as Open does.
|
||||
/// - **No recent files.** With a `drop_hint` the Recent section is a card that opens a file on a click, Enter or Space.
|
||||
/// - **State.** The app owns the list, the view and the sort. The screen writes a changed view or sort through its
|
||||
/// binding and reports everything else as [`StartAction`]s.
|
||||
///
|
||||
@@ -155,18 +166,13 @@ pub struct StartScreen<'a> {
|
||||
/// The time the age lines count from, in seconds since the Unix epoch. Without it the cards show no age.
|
||||
#[prop]
|
||||
now: Option<i64>,
|
||||
/// The store that holds the thumbnails and previews, which the app fills.
|
||||
thumbnails: Option<TextureStore<ThumbKey>>,
|
||||
/// The thumbnails and the source of each key's revision: cards, rows and templates ask `Thumbnails::state`.
|
||||
#[allow(dead_code)] // P3(top-w5): tp.T29
|
||||
shown: Option<(&'a Thumbnails<ThumbKey>, &'a dyn ThumbSource<ThumbKey>)>,
|
||||
thumbnails: Option<(&'a Thumbnails<ThumbKey>, &'a dyn ThumbSource<ThumbKey>)>,
|
||||
/// The links beside the page: New and Open at the rail's top, then these.
|
||||
#[prop]
|
||||
links: &'a [StartLink],
|
||||
/// With no recent files, the Recent body is a drop card with this hint, and a double click on the page's own room
|
||||
/// reports `StartAction::Open`.
|
||||
/// With no recent files, the Recent body is a drop card with this hint that opens a file on a click.
|
||||
#[prop(into)]
|
||||
#[allow(dead_code)] // P3(top-w5): cw.C45
|
||||
drop_hint: Option<Label>,
|
||||
}
|
||||
|
||||
@@ -216,7 +222,6 @@ impl<'a> StartScreen<'a> {
|
||||
max_recent: RECENT_SHOWN,
|
||||
now: None,
|
||||
thumbnails: None,
|
||||
shown: None,
|
||||
links: &[],
|
||||
drop_hint: None,
|
||||
}
|
||||
@@ -225,15 +230,7 @@ impl<'a> StartScreen<'a> {
|
||||
/// Cards, rows and templates ask `thumbnails.state(..)` for what they show; `source` gives each key's revision.
|
||||
#[must_use]
|
||||
pub fn thumbnails(mut self, thumbnails: &'a Thumbnails<ThumbKey>, source: &'a dyn ThumbSource<ThumbKey>) -> Self {
|
||||
self.shown = Some((thumbnails, source));
|
||||
self
|
||||
}
|
||||
|
||||
/// The store of thumbnails the page reads today.
|
||||
#[must_use]
|
||||
pub(crate) fn texture_store(mut self, store: TextureStore<ThumbKey>) -> Self {
|
||||
// P3(top-w5): tp.T29
|
||||
self.thumbnails = Some(store);
|
||||
self.thumbnails = Some((thumbnails, source));
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -245,29 +242,20 @@ struct Leads {
|
||||
pinned: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// What a card or row shows as its picture.
|
||||
enum Picture {
|
||||
/// The item has no thumbnail.
|
||||
None,
|
||||
/// The store has no picture yet.
|
||||
Pending,
|
||||
/// A picture to draw.
|
||||
Ready(CachedTexture),
|
||||
/// Loading the picture failed.
|
||||
Failed,
|
||||
}
|
||||
/// The thumbnails and the source of each key's revision.
|
||||
type ThumbHost<'p> = (&'p Thumbnails<ThumbKey>, &'p dyn ThumbSource<ThumbKey>);
|
||||
|
||||
/// What every section of one pass reads.
|
||||
struct Page<'p> {
|
||||
ctx: &'p egui::Context,
|
||||
env: &'p Env,
|
||||
words: &'p ShellWords,
|
||||
thumbnails: Option<&'p TextureStore<ThumbKey>>,
|
||||
thumbnails: Option<ThumbHost<'p>>,
|
||||
drop_hint: Option<&'p Label>,
|
||||
now: Option<i64>,
|
||||
actions: &'p RefCell<Vec<StartAction>>,
|
||||
}
|
||||
|
||||
impl Page<'_> {
|
||||
impl<'p> Page<'p> {
|
||||
fn push(&self, action: StartAction) {
|
||||
self.actions.borrow_mut().push(action);
|
||||
}
|
||||
@@ -278,29 +266,21 @@ impl Page<'_> {
|
||||
Some(self.env.relative_age(now.saturating_sub(then).max(0).unsigned_abs(), AgeStyle::Long))
|
||||
}
|
||||
|
||||
fn picture(&self, key: ThumbKey, revision: Option<Revision>) -> Picture {
|
||||
let (Some(store), Some(revision)) = (self.thumbnails, revision) else { return Picture::None };
|
||||
let state = store.state(self.ctx, &key, revision);
|
||||
if let Some(texture) = state.shown() {
|
||||
return Picture::Ready(texture);
|
||||
}
|
||||
match state {
|
||||
TextureState::Failed { .. } => Picture::Failed,
|
||||
TextureState::Empty => Picture::None,
|
||||
_ => Picture::Pending,
|
||||
}
|
||||
}
|
||||
|
||||
fn tile<'t>(&self, name: &str, detail: Option<String>, picture: Picture) -> Tile<'t> {
|
||||
/// A card named `name` whose picture is the thumbnail of `key`, asked for at the cell it paints in; the file icon
|
||||
/// without `thumbnails`.
|
||||
fn tile<'t>(&self, name: &str, detail: Option<String>, key: ThumbKey) -> Tile<'t>
|
||||
where
|
||||
'p: 't,
|
||||
{
|
||||
let mut tile = Tile::new(Label::from(name.to_owned()));
|
||||
if let Some(detail) = detail {
|
||||
tile = tile.detail(detail);
|
||||
}
|
||||
match picture {
|
||||
Picture::Ready(texture) => tile.thumb(ThumbAspect::new(PICTURE_WIDE, PICTURE_HIGH), move |cx, rect| paint_picture(cx, rect, texture)),
|
||||
Picture::Failed => tile.status(TileStatus::Failed),
|
||||
Picture::Pending => tile,
|
||||
Picture::None => tile.icon(IconId::new("file")),
|
||||
match self.thumbnails {
|
||||
Some((thumbnails, source)) => {
|
||||
tile.thumb(ThumbAspect::new(PICTURE_WIDE, PICTURE_HIGH), move |cx, rect| paint_thumb(cx, rect, thumbnails, source, &key))
|
||||
}
|
||||
None => tile.icon(IconId::new("file")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,16 +300,18 @@ impl Page<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture inside `rect`, as large as fits with its own proportions.
|
||||
fn paint_picture(cx: &ContentPainterCx, rect: Rect, texture: CachedTexture) {
|
||||
let size = texture.size_vec2();
|
||||
if size.x <= 0.0 || size.y <= 0.0 {
|
||||
/// The thumbnail of `key` in `rect`, asked for at the size it paints. The store paints the placeholder while the
|
||||
/// picture is not ready and the failure mark when it failed; a key the source has no picture for (`Blank`) gets the
|
||||
/// file icon on the sunken tile.
|
||||
fn paint_thumb(cx: &ContentPainterCx, rect: Rect, thumbnails: &Thumbnails<ThumbKey>, source: &dyn ThumbSource<ThumbKey>, key: &ThumbKey) {
|
||||
let request = ThumbRequest::for_cell(rect.width().max(rect.height()), cx.pixels_per_point());
|
||||
let state = thumbnails.state(cx.painter.ctx(), source, key, &request, Priority::VISIBLE);
|
||||
if thumbnails.paint(cx, rect, &state, &ThumbPaint::default()) {
|
||||
return;
|
||||
}
|
||||
let scale = (rect.width() / size.x).min(rect.height() / size.y);
|
||||
let fitted = Rect::from_center_size(rect.center(), size * scale);
|
||||
let uv = Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0));
|
||||
cx.picture(texture.id, fitted, uv, cx.style_cx().tokens.shape.radius.control);
|
||||
cx.surface(rect, SurfaceKind::Sunken, Corners::None);
|
||||
let side = cx.style_cx().tokens.size.icon.lg;
|
||||
cx.icon(Rect::from_center_size(rect.center(), Vec2::splat(side)), &IconSpec::svg(IconId::new("file")));
|
||||
}
|
||||
|
||||
/// The folder a path is in, for the line under a file's name.
|
||||
@@ -362,45 +344,113 @@ fn read_events<K: Clone, E>(events: Vec<CollectionEvent<K, E>>, lead: &mut Optio
|
||||
impl StartScreen<'_> {
|
||||
/// Shows the page across the available room and reports what the user did.
|
||||
pub fn show(self, ui: &mut Ui) -> StartOutput {
|
||||
let StartScreen { view, sort, recent, pinned, templates, max_recent, now, thumbnails, .. } = self; // P3(top-w5): tp.T29
|
||||
let StartScreen { view, sort, recent, pinned, templates, max_recent, now, thumbnails, links, drop_hint } = self;
|
||||
let env = Env::of(ui);
|
||||
let collator = env.collator();
|
||||
let words = env.words::<ShellWords>();
|
||||
let ctx = ui.ctx().clone();
|
||||
let actions = RefCell::new(Vec::new());
|
||||
let page = Page { ctx: &ctx, env: &env, words: &words, thumbnails: thumbnails.as_ref(), now, actions: &actions };
|
||||
let page = Page { env: &env, words: &words, thumbnails, drop_hint: drop_hint.as_ref(), now, actions: &actions };
|
||||
let view = RefCell::new(view);
|
||||
let sort = RefCell::new(sort);
|
||||
|
||||
let shown = Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| {
|
||||
Stack::new().gap(Gap::Section).pad(Pad::Regular).fill_width().show(ui, |ui, cx| {
|
||||
let current_view = view.borrow_mut().reborrow().read(cx).and_then(|held| held.same().copied()).unwrap_or_default();
|
||||
let current_sort = sort.borrow_mut().reborrow().read(cx).and_then(|held| held.same().copied()).unwrap_or_default();
|
||||
let mut files: Vec<RecentFile> = recent.iter().take(max_recent).cloned().collect();
|
||||
sort_recent(&mut files, current_sort, &collator);
|
||||
let room = ui.available_rect_before_wrap();
|
||||
// The page's surround is square.
|
||||
paint_surround(ui.painter(), CheckerArea::Rect(room, CornerRadius::ZERO), &SurroundLook::of(&env.tokens).shown(env.canvas_pattern));
|
||||
|
||||
Row::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
if clicked(&Button::new(words.new.clone()).id_salt("new").variant(Variant::PRIMARY).show(ui)) {
|
||||
page.push(StartAction::New);
|
||||
}
|
||||
if clicked(&Button::new(words.open.clone()).id_salt("open").show(ui)) {
|
||||
page.push(StartAction::Open);
|
||||
}
|
||||
let rail_stack = || Stack::new().gap(Gap::Tight).pad(Pad::Regular).label(words.start_links.clone());
|
||||
let rail_body = |ui: &mut Ui| {
|
||||
new_and_open(&page, ui);
|
||||
let _ = Divider::horizontal().show(ui);
|
||||
link_items(ui, links);
|
||||
};
|
||||
let page_stack = || Stack::new().gap(Gap::Section).pad(Pad::Regular).fill_width();
|
||||
// `beside` is whether the rail stands beside the page; without it New and Open lead the page and the links follow
|
||||
// the sections.
|
||||
let page_body = |ui: &mut Ui, cx: &mut BodyCx<'_>, beside: bool| {
|
||||
let current_view = view.borrow_mut().reborrow().read(cx).and_then(|held| held.same().copied()).unwrap_or_default();
|
||||
let current_sort = sort.borrow_mut().reborrow().read(cx).and_then(|held| held.same().copied()).unwrap_or_default();
|
||||
let mut files: Vec<RecentFile> = recent.iter().take(max_recent).cloned().collect();
|
||||
sort_recent(&mut files, current_sort, &collator);
|
||||
|
||||
if !beside {
|
||||
let _ = Row::new().gap(Gap::Tight).show(ui, |ui, _| new_and_open(&page, ui));
|
||||
}
|
||||
recent_section(&page, ui, &view, &sort, current_view, &files);
|
||||
if let Some(pinned) = pinned {
|
||||
pinned_section(&page, ui, pinned);
|
||||
}
|
||||
if !templates.is_empty() {
|
||||
templates_section(&page, ui, templates);
|
||||
}
|
||||
if !beside && !links.is_empty() {
|
||||
let _ = Stack::new().gap(Gap::Tight).label(words.start_links.clone()).show(ui, |ui, _| link_items(ui, links));
|
||||
}
|
||||
};
|
||||
|
||||
// The rail stands beside the sections when the room holds the rail, the gap and the sections' least width; a
|
||||
// narrower page keeps New and Open in its row and lists the links after the sections.
|
||||
let rail = !links.is_empty() && {
|
||||
let rail_width = rail_stack().measure_in(ui, Proposal::Ideal, |ui, _| rail_body(ui)).x;
|
||||
let sections_least = page_stack().measure_in(ui, Proposal::Min, |ui, cx| page_body(ui, cx, true)).x;
|
||||
ui.available_width() >= rail_width + env.tokens.space.gap.section + sections_least
|
||||
};
|
||||
|
||||
// The page senses its own surface for the empty-room double click (`BodyCx::surface_double_pressed`). A pass reads
|
||||
// only its own input, so a second pass of one frame reports the double click only if it holds the second press.
|
||||
let shown = Stack::new().fill().scroll(Scroll::vertical()).senses_surface().show(ui, |ui, cx| {
|
||||
if cx.surface_double_pressed() {
|
||||
page.push(StartAction::Open);
|
||||
}
|
||||
if rail {
|
||||
let _ = Row::new().gap(Gap::Section).fill_width().show(ui, |ui, _| {
|
||||
let _ = rail_stack().show(ui, |ui, _| rail_body(ui));
|
||||
let _ = page_stack().show(ui, |ui, cx| page_body(ui, cx, true));
|
||||
});
|
||||
|
||||
recent_section(&page, ui, &view, &sort, current_view, &files);
|
||||
if let Some(pinned) = pinned {
|
||||
pinned_section(&page, ui, pinned);
|
||||
}
|
||||
if !templates.is_empty() {
|
||||
templates_section(&page, ui, templates);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
let _ = page_stack().show(ui, |ui, cx| page_body(ui, cx, false));
|
||||
}
|
||||
});
|
||||
StartOutput { response: shown.output, actions: actions.into_inner() }
|
||||
}
|
||||
}
|
||||
|
||||
/// New and Open, the first Tab stops of the page.
|
||||
fn new_and_open(page: &Page<'_>, ui: &mut Ui) {
|
||||
let words = page.words;
|
||||
if clicked(&Button::new(words.new.clone()).id_salt("new").variant(Variant::PRIMARY).show(ui)) {
|
||||
page.push(StartAction::New);
|
||||
}
|
||||
if clicked(&Button::new(words.open.clone()).id_salt("open").show(ui)) {
|
||||
page.push(StartAction::Open);
|
||||
}
|
||||
}
|
||||
|
||||
/// The links, one under another: a URL opens through its `Link` (the URL is its tooltip), a command fires as a
|
||||
/// pointer activation.
|
||||
fn link_items(ui: &mut Ui, links: &[StartLink]) {
|
||||
for (at, link) in links.iter().enumerate() {
|
||||
match &link.target {
|
||||
StartLinkTarget::Url(url) => {
|
||||
let _ = Row::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
if let Some(icon) = &link.icon {
|
||||
let _ = Icon::new(IconSpec::svg(icon.clone())).id_salt(("start-link-icon", at)).show(ui);
|
||||
}
|
||||
let _ = Link::new(link.label.clone()).id_salt(("start-link", at)).url(url.clone()).tooltip(url.clone()).show(ui);
|
||||
});
|
||||
}
|
||||
StartLinkTarget::Command(command) => {
|
||||
let mut button = Button::new(link.label.clone()).id_salt(("start-link", at));
|
||||
if let Some(icon) = &link.icon {
|
||||
button = button.icon(icon.clone());
|
||||
}
|
||||
if clicked(&button.show(ui)) {
|
||||
let _ = commands::fire(ui.ctx(), command.clone(), FireSource::Pointer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn recent_section(
|
||||
page: &Page<'_>,
|
||||
ui: &mut Ui,
|
||||
@@ -441,7 +491,18 @@ fn recent_section(
|
||||
}
|
||||
}
|
||||
if files.is_empty() {
|
||||
let _ = Notice::new(Tone::Neutral, words.no_recent.clone()).layout(NoticeLayout::Centred).show(ui);
|
||||
match page.drop_hint {
|
||||
Some(hint) => {
|
||||
// The card is a button, so a click, Enter and Space open a file and it has its own Tab stop.
|
||||
let card = Button::new(hint.clone()).id_salt("drop").icon(IconId::new("image")).sizing(Sizing::FillWidth).show(ui);
|
||||
if clicked(&card) {
|
||||
page.push(StartAction::Open);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let _ = Notice::new(Tone::Neutral, words.no_recent.clone()).layout(NoticeLayout::Centred).show(ui);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let file_of = |path: &PathBuf| files.iter().find(|file| &file.path == path);
|
||||
@@ -449,7 +510,7 @@ fn recent_section(
|
||||
let (response, (opened, removed)) = if current == RecentView::Grid {
|
||||
let out = page.grid::<PathBuf>(words.recent.clone(), true).show_items(ui, &source, &mut |path, _| {
|
||||
let Some(file) = file_of(path) else { return Tile::new(Label::Empty) };
|
||||
page.tile(&file.name, page.age(file.opened), page.picture(ThumbKey::Recent(file.path.clone()), file.thumbnail))
|
||||
page.tile(&file.name, page.age(file.opened), ThumbKey::Recent(file.path.clone()))
|
||||
.corner_action(IconId::new("close"), StartRecentCommands::Remove)
|
||||
.tooltip(file.path.display().to_string())
|
||||
});
|
||||
@@ -479,9 +540,33 @@ fn recent_section(
|
||||
Some(age) => row.trailing(age),
|
||||
None => row,
|
||||
};
|
||||
row.icon(IconSpec::svg(IconId::new("file")))
|
||||
let row = row.trailing_part_revealed(
|
||||
REMOVE,
|
||||
TrailingFace::Icon(IconSpec::svg(IconId::new("close"))),
|
||||
words.remove_recent.fill(&[("name", file.name.as_str())]),
|
||||
);
|
||||
match page.thumbnails {
|
||||
Some((thumbnails, source)) => {
|
||||
let key = ThumbKey::Recent(file.path.clone());
|
||||
row.thumb_aspect(ThumbSize::Medium, ThumbAspect::new(PICTURE_WIDE, PICTURE_HIGH), move |cx, rect| {
|
||||
paint_thumb(cx, rect, thumbnails, source, &key);
|
||||
})
|
||||
}
|
||||
None => row.icon(IconSpec::svg(IconId::new("file"))),
|
||||
}
|
||||
});
|
||||
(out.response, read_events(out.events, &mut lead))
|
||||
// The revealed remove part reports `RowEvent::Trailing`, which `read_events` does not read.
|
||||
let part: Vec<PathBuf> = out
|
||||
.events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
CollectionEvent::Item(key, RowEvent::Trailing { part, .. }) if *part == REMOVE => Some(key.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let (opened, mut removed) = read_events(out.events, &mut lead);
|
||||
removed.extend(part);
|
||||
(out.response, (opened, removed))
|
||||
};
|
||||
for path in opened {
|
||||
page.push(StartAction::OpenRecent(path));
|
||||
@@ -554,7 +639,7 @@ fn templates_section(page: &Page<'_>, ui: &mut Ui, templates: &[Template]) {
|
||||
let out = page.grid::<String>(words.templates.clone(), false).show_items(ui, &source, &mut |id, _| {
|
||||
let Some(template) = templates.iter().find(|template| &template.id == id) else { return Tile::new(Label::Empty) };
|
||||
let detail = (!template.detail.is_empty()).then(|| template.detail.clone());
|
||||
page.tile(&template.name, detail, page.picture(ThumbKey::Template(template.id.clone()), template.thumbnail))
|
||||
page.tile(&template.name, detail, ThumbKey::Template(template.id.clone()))
|
||||
});
|
||||
let mut lead = None;
|
||||
for id in read_events(out.response.events, &mut lead).0 {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Stories of `StartScreen`.
|
||||
|
||||
use super::StartScreen;
|
||||
use super::{StartLink, StartScreen};
|
||||
use crate::contract::Bind;
|
||||
use crate::primitives::{LoadFailure, Revision, TextureState, TextureStore, TextureStoreOptions};
|
||||
use crate::shell::{RecentFile, RecentSort, RecentView, Template, ThumbKey};
|
||||
use crate::testing::pictures::sample_picture;
|
||||
use crate::primitives::{FakeThumbSource, ThumbnailOptions, Thumbnails};
|
||||
use crate::runtime::env::Label;
|
||||
use crate::shell::{RecentFile, RecentSort, RecentView, ScreenModeCommands, Template, ThumbKey};
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use craft_behavior::IconId;
|
||||
use egui::Ui;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -13,8 +14,6 @@ use std::path::PathBuf;
|
||||
const NOW: i64 = 1_800_000_000;
|
||||
const HOUR: i64 = 3_600;
|
||||
const DAY: i64 = 86_400;
|
||||
/// The size of the stored pictures.
|
||||
const PICTURE: [u32; 2] = [64, 36];
|
||||
|
||||
/// The view and sort the stories edit.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -23,45 +22,34 @@ struct Choice {
|
||||
sort: RecentSort,
|
||||
}
|
||||
|
||||
/// Five files, four with a picture revision (the fourth fails to load) and one without.
|
||||
fn recent_file(name: &str, folder: &str, days: i64) -> RecentFile {
|
||||
let mut file = RecentFile::new(PathBuf::from(folder).join(name), name);
|
||||
file.opened = Some(NOW - days * DAY);
|
||||
file.created = Some(NOW - (days + 30) * DAY);
|
||||
file
|
||||
}
|
||||
|
||||
/// Five files; the source fails to load "Broken.fig" and has no picture for "Notes.fig".
|
||||
fn picture_files() -> Vec<RecentFile> {
|
||||
let file = |name: &str, folder: &str, days: i64, thumbnail: Option<Revision>| {
|
||||
let mut file = RecentFile::new(PathBuf::from(folder).join(name), name);
|
||||
file.opened = Some(NOW - days * DAY);
|
||||
file.created = Some(NOW - (days + 30) * DAY);
|
||||
file.thumbnail = thumbnail;
|
||||
file
|
||||
};
|
||||
vec![
|
||||
file("Poster 2.fig", "/home/ana/Work", 0, Some(Revision::new(1))),
|
||||
file("Poster 10.fig", "/home/ana/Work", 2, Some(Revision::new(2))),
|
||||
file("Brochure.fig", "/home/ana/Print", 5, Some(Revision::new(3))),
|
||||
file("Broken.fig", "/home/ana/Print", 9, Some(Revision::new(4))),
|
||||
file("Notes.fig", "/home/ana/Notes", 30, None),
|
||||
recent_file("Poster 2.fig", "/home/ana/Work", 0),
|
||||
recent_file("Poster 10.fig", "/home/ana/Work", 2),
|
||||
recent_file("Brochure.fig", "/home/ana/Print", 5),
|
||||
recent_file("Broken.fig", "/home/ana/Print", 9),
|
||||
recent_file("Notes.fig", "/home/ana/Notes", 30),
|
||||
]
|
||||
}
|
||||
|
||||
fn picture_templates() -> Vec<Template> {
|
||||
let mut a4 = Template::new("a4", "A4", "210 × 297 mm");
|
||||
a4.thumbnail = Some(Revision::new(1));
|
||||
vec![a4, Template::new("hd", "Full HD", "1920 × 1080 px")]
|
||||
vec![Template::new("a4", "A4", "210 × 297 mm"), Template::new("hd", "Full HD", "1920 × 1080 px")]
|
||||
}
|
||||
|
||||
/// Fills the store with the pictures the stories name: ready for revisions 1 to 3 and the A4 template, failed for 4.
|
||||
fn fill(ui: &Ui) -> TextureStore<ThumbKey> {
|
||||
let ctx = ui.ctx();
|
||||
let store = TextureStore::<ThumbKey>::in_context(ctx, "start-stories", TextureStoreOptions::default());
|
||||
for (file, key) in picture_files().into_iter().take(3).zip(0..) {
|
||||
if let Some(revision) = file.thumbnail {
|
||||
let _ = store.get_or_put(ctx, ThumbKey::Recent(file.path), revision, || sample_picture(key, PICTURE));
|
||||
}
|
||||
}
|
||||
let _ = store.get_or_put(ctx, ThumbKey::Template("a4".to_owned()), Revision::new(1), || sample_picture(3, PICTURE));
|
||||
let broken = ThumbKey::Recent(PathBuf::from("/home/ana/Print").join("Broken.fig"));
|
||||
if matches!(store.state(ctx, &broken, Revision::new(4)), TextureState::Missing) {
|
||||
store.put_failure(ctx, broken, Revision::new(4), LoadFailure::Unreadable);
|
||||
}
|
||||
store
|
||||
/// The source of the picture stories: pictures for every key but the failing and the blank one.
|
||||
fn picture_source() -> FakeThumbSource<ThumbKey> {
|
||||
let print = PathBuf::from("/home/ana/Print");
|
||||
FakeThumbSource::new()
|
||||
.failing([ThumbKey::Recent(print.join("Broken.fig"))])
|
||||
.blank([ThumbKey::Recent(PathBuf::from("/home/ana/Notes").join("Notes.fig")), ThumbKey::Template("hd".to_owned())])
|
||||
}
|
||||
|
||||
/// Six files and three templates, none with a picture: every tile shows the placeholder.
|
||||
@@ -90,16 +78,37 @@ fn plain_templates() -> Vec<Template> {
|
||||
]
|
||||
}
|
||||
|
||||
fn screen(ui: &mut Ui, data: &mut StoryData, choice: Choice, files: &[RecentFile], pinned: &[PathBuf], templates: &[Template]) -> StoryOutput {
|
||||
let store = fill(ui);
|
||||
/// What a story passes besides its lists.
|
||||
#[derive(Default)]
|
||||
struct Extras<'a> {
|
||||
source: Option<&'a FakeThumbSource<ThumbKey>>,
|
||||
links: &'a [StartLink],
|
||||
drop_hint: Option<&'a str>,
|
||||
}
|
||||
|
||||
fn screen(
|
||||
ui: &mut Ui,
|
||||
data: &mut StoryData,
|
||||
choice: Choice,
|
||||
files: &[RecentFile],
|
||||
pinned: &[PathBuf],
|
||||
templates: &[Template],
|
||||
extras: Extras<'_>,
|
||||
) -> StoryOutput {
|
||||
let mut choice = data.value("choice", choice).clone();
|
||||
let shown = StartScreen::new(Bind::bound(&mut choice.view), Bind::bound(&mut choice.sort), files)
|
||||
let thumbnails = Thumbnails::<ThumbKey>::in_context(ui.ctx(), "start-stories", ThumbnailOptions::new());
|
||||
let mut start = StartScreen::new(Bind::bound(&mut choice.view), Bind::bound(&mut choice.sort), files)
|
||||
.pinned(pinned)
|
||||
.templates(templates)
|
||||
.now(NOW)
|
||||
.texture_store(store) // P3(top-w5): tp.T29
|
||||
.show(ui)
|
||||
.into();
|
||||
.links(extras.links);
|
||||
if let Some(source) = extras.source {
|
||||
start = start.thumbnails(&thumbnails, source);
|
||||
}
|
||||
if let Some(hint) = extras.drop_hint {
|
||||
start = start.drop_hint(Label::from(hint.to_owned()));
|
||||
}
|
||||
let shown = start.show(ui).into();
|
||||
*data.value("choice", Choice::default()) = choice;
|
||||
shown
|
||||
}
|
||||
@@ -107,22 +116,35 @@ fn screen(ui: &mut Ui, data: &mut StoryData, choice: Choice, files: &[RecentFile
|
||||
#[story(StartScreen<'static>, covers = [], drive = Drive::Never)]
|
||||
fn start_screen(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let pinned = [PathBuf::from("/home/user/Pictures"), PathBuf::from("/home/user/Projects")];
|
||||
screen(ui, data, Choice::default(), &plain_files(), &pinned, &plain_templates())
|
||||
screen(ui, data, Choice::default(), &plain_files(), &pinned, &plain_templates(), Extras::default())
|
||||
}
|
||||
|
||||
#[story(StartScreen<'static>, covers = [], drive = Drive::Never)]
|
||||
fn start_screen_with_pictures(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let pinned = [PathBuf::from("/home/ana/Work"), PathBuf::from("/home/ana/Print")];
|
||||
screen(ui, data, Choice::default(), &picture_files(), &pinned, &picture_templates())
|
||||
let source = picture_source();
|
||||
screen(ui, data, Choice::default(), &picture_files(), &pinned, &picture_templates(), Extras { source: Some(&source), ..Extras::default() })
|
||||
}
|
||||
|
||||
#[story(StartScreen<'static>, covers = [], drive = Drive::Never)]
|
||||
fn start_screen_list_sorted_by_name(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let choice = Choice { view: RecentView::List, sort: RecentSort::Name };
|
||||
screen(ui, data, choice, &picture_files(), &[], &picture_templates())
|
||||
let source = picture_source();
|
||||
screen(ui, data, choice, &picture_files(), &[], &picture_templates(), Extras { source: Some(&source), ..Extras::default() })
|
||||
}
|
||||
|
||||
#[story(StartScreen<'static>, covers = [], drive = Drive::Never)]
|
||||
fn start_screen_without_files(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
screen(ui, data, Choice::default(), &[], &[], &picture_templates())
|
||||
let extras = Extras { drop_hint: Some("Drop a file here or click to open one"), ..Extras::default() };
|
||||
screen(ui, data, Choice::default(), &[], &[], &picture_templates(), extras)
|
||||
}
|
||||
|
||||
#[story(StartScreen<'static>, covers = [], drive = Drive::Never)]
|
||||
fn start_screen_with_links(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let links = [
|
||||
StartLink::url("Documentation", Some(IconId::new("home")), "https://example.com/docs"),
|
||||
StartLink::url("Website", Some(IconId::new("globe")), "https://example.com"),
|
||||
StartLink::command("Cycle Screen Mode", None, ScreenModeCommands::Cycle),
|
||||
];
|
||||
screen(ui, data, Choice::default(), &plain_files(), &[], &plain_templates(), Extras { links: &links, ..Extras::default() })
|
||||
}
|
||||
|
||||
@@ -4,6 +4,9 @@ mod canvas_panel;
|
||||
mod caption_button;
|
||||
mod document_window;
|
||||
mod embed;
|
||||
mod opening;
|
||||
mod reveal;
|
||||
mod screen_mode;
|
||||
mod start;
|
||||
mod title_bar;
|
||||
mod window_parts;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! `OpeningCard`: the layout of its rows and its Cancel.
|
||||
|
||||
use craft_ui::shell::OpeningCard;
|
||||
use craft_ui::testing::{Fixture, Target, trial};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
const LONG: &str = "a7rv-test_2024_02_17_shot_30_3705_with_an_even_longer_suffix_that_never_ends.psb";
|
||||
|
||||
/// A card for `name` in a narrow room, and whether its Cancel was picked.
|
||||
fn card(name: &'static str) -> (Fixture, Rc<Cell<bool>>) {
|
||||
let cancelled = Rc::new(Cell::new(false));
|
||||
let seen = Rc::clone(&cancelled);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = OpeningCard::new(name).message("Reading layers…").fraction(Some(0.4)).cancel("Cancel").show(ui);
|
||||
if out.cancelled {
|
||||
seen.set(true);
|
||||
}
|
||||
});
|
||||
fixture.room(egui::Vec2::new(280.0, 400.0));
|
||||
fixture.settle();
|
||||
(fixture, cancelled)
|
||||
}
|
||||
|
||||
fn title(fixture: &Fixture, name: &str) -> Target {
|
||||
fixture.by_label(&format!("Opening {name}…")).expect("the title is in the tree under its whole text")
|
||||
}
|
||||
|
||||
/// A long file name is elided on one line, so the percentage row and Cancel stay inside the card, and a click on
|
||||
/// Cancel reports it.
|
||||
#[trial]
|
||||
fn the_opening_card_keeps_a_long_name_on_one_line_and_cancel_inside() {
|
||||
let (short, _) = card("short.psd");
|
||||
let one_line = title(&short, "short.psd").rect.height();
|
||||
|
||||
let (mut fixture, cancelled) = card(LONG);
|
||||
let title = title(&fixture, LONG);
|
||||
assert!(title.rect.height() <= one_line + 1.0, "the long title is one line: {:?} against {one_line}", title.rect);
|
||||
let cancel = fixture.by_label("Cancel").expect("Cancel shows");
|
||||
assert!(cancel.rect.top() >= title.rect.bottom(), "Cancel is under the title: {:?} / {:?}", cancel.rect, title.rect);
|
||||
assert!(
|
||||
cancel.rect.left() >= title.rect.left() && cancel.rect.right() <= title.rect.right() + 0.5,
|
||||
"Cancel is inside the card's width, which the elided title fills: {:?} / {:?}",
|
||||
cancel.rect,
|
||||
title.rect
|
||||
);
|
||||
assert!(fixture.by_label("40%").is_some(), "the percentage shows at the start of the last row");
|
||||
assert!(!cancelled.get(), "nothing was cancelled yet");
|
||||
fixture.click(&cancel);
|
||||
assert!(cancelled.get(), "a click on Cancel reports it");
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//! `StartScreen`: which part of the page takes a double click.
|
||||
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::shell::{RecentFile, RecentSort, RecentView, StartAction, StartLink, StartScreen};
|
||||
use craft_ui::testing::{Fixture, Target, trial};
|
||||
use std::cell::RefCell;
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
|
||||
type Log = Rc<RefCell<Vec<StartAction>>>;
|
||||
|
||||
/// A start screen of two recent files and a link in a room wide enough for the rail; every action it reports goes to
|
||||
/// the log.
|
||||
fn screen() -> (Fixture, Log) {
|
||||
let log: Log = Rc::default();
|
||||
let seen = Rc::clone(&log);
|
||||
let files = vec![RecentFile::new("/tmp/work/Poster.psd", "Poster.psd"), RecentFile::new("/tmp/work/Flyer.psd", "Flyer.psd")];
|
||||
let links = vec![StartLink::url("Docs", None, "https://example.test/docs")];
|
||||
let (mut view, mut sort) = (RecentView::Grid, RecentSort::Opened);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &files).links(&links).show(ui);
|
||||
seen.borrow_mut().extend(out.actions);
|
||||
});
|
||||
fixture.room(egui::Vec2::new(1100.0, 700.0));
|
||||
fixture.settle();
|
||||
log.borrow_mut().clear();
|
||||
(fixture, log)
|
||||
}
|
||||
|
||||
/// Two clicks at one point, inside the double-click time.
|
||||
fn double_click(fixture: &mut Fixture, target: &Target) {
|
||||
let at = target.center();
|
||||
fixture.click_at(at).click_at(at);
|
||||
}
|
||||
|
||||
fn opens(log: &Log) -> usize {
|
||||
log.borrow().iter().filter(|action| **action == StartAction::Open).count()
|
||||
}
|
||||
|
||||
/// The page's own room takes a double click as Open; a card, a button and a rail link keep theirs, because they sit
|
||||
/// above the page's room.
|
||||
#[trial]
|
||||
fn a_double_click_on_the_empty_room_opens_and_one_on_a_card_opens_only_its_file() {
|
||||
let (mut fixture, log) = screen();
|
||||
|
||||
let corner = fixture.shown().max - egui::vec2(30.0, 30.0);
|
||||
fixture.click_at(corner).click_at(corner);
|
||||
assert_eq!(*log.borrow(), vec![StartAction::Open], "a double click on empty room opens a file once");
|
||||
|
||||
log.borrow_mut().clear();
|
||||
let card = fixture.by_label("Poster.psd").expect("the card shows");
|
||||
double_click(&mut fixture, &card);
|
||||
let poster = PathBuf::from("/tmp/work/Poster.psd");
|
||||
assert!(!log.borrow().is_empty(), "a click on a card opens its file");
|
||||
assert!(log.borrow().iter().all(|action| *action == StartAction::OpenRecent(poster.clone())), "only the card's file opens: {:?}", log.borrow());
|
||||
|
||||
log.borrow_mut().clear();
|
||||
let new = fixture.by_label("New…").expect("New shows");
|
||||
double_click(&mut fixture, &new);
|
||||
assert_eq!(opens(&log), 0, "a double click on New does not open a file: {:?}", log.borrow());
|
||||
|
||||
log.borrow_mut().clear();
|
||||
let open = fixture.by_label("Open…").expect("Open shows");
|
||||
fixture.click(&open);
|
||||
let single = opens(&log);
|
||||
log.borrow_mut().clear();
|
||||
// The double click starts a new click count.
|
||||
fixture.advance(1.0);
|
||||
double_click(&mut fixture, &open);
|
||||
assert_eq!(opens(&log), 2 * single, "Open reports its own two clicks and the page's room adds none");
|
||||
|
||||
log.borrow_mut().clear();
|
||||
let link = fixture.by_label("Docs").expect("the rail link shows");
|
||||
double_click(&mut fixture, &link);
|
||||
assert_eq!(opens(&log), 0, "a double click on a rail link opens no file: {:?}", log.borrow());
|
||||
}
|
||||
@@ -209,6 +209,8 @@ pub struct Updater {
|
||||
/// The check running (or queued behind it) was asked for by the user.
|
||||
requested: bool,
|
||||
started: bool,
|
||||
/// The last update's outcome record was read ([`Updater::read_last_update`]).
|
||||
outcome_read: bool,
|
||||
check: Option<Receiver<Found>>,
|
||||
/// Replaces [`can_install_itself`] on the check's thread (tests).
|
||||
probe: Option<InstallProbe>,
|
||||
@@ -260,6 +262,7 @@ impl Updater {
|
||||
status: Status::Idle,
|
||||
requested: false,
|
||||
started: false,
|
||||
outcome_read: false,
|
||||
check: None,
|
||||
probe: None,
|
||||
installing_itself: false,
|
||||
@@ -338,9 +341,14 @@ impl Updater {
|
||||
self.paths.clone().or_else(|| if cfg!(test) { None } else { Paths::for_app(self.app).ok() })
|
||||
}
|
||||
|
||||
/// What the last update came to, once: [`Status::Updated`] when it installed the version
|
||||
/// running now, [`Status::InstallFailed`] with the reason when it failed.
|
||||
fn read_outcome(&mut self) {
|
||||
/// What the last update came to, once per launch: [`Status::Updated`] when it installed the version running now,
|
||||
/// [`Status::InstallFailed`] with the reason when it failed. The guard is inside the `Updater`, so
|
||||
/// [`Self::check_at_start`] and an app that starts no check (automatic checks off) can both call it. `Updated`
|
||||
/// stays until [`Self::dismiss_status`] or a requested check; a failure's reason moves into the next offer's prompt.
|
||||
pub fn read_last_update(&mut self) {
|
||||
if std::mem::replace(&mut self.outcome_read, true) {
|
||||
return;
|
||||
}
|
||||
let Some(paths) = self.outcome_paths() else { return };
|
||||
match self_update::take_outcome(&paths, &self.version) {
|
||||
Some(Outcome::Installed(version)) => self.status = Status::Updated(version.to_string()),
|
||||
@@ -390,7 +398,7 @@ impl Updater {
|
||||
/// status is not [`Status::Idle`]. The check itself stays quiet unless it finds a release.
|
||||
pub fn check_at_start(&mut self) {
|
||||
if !std::mem::replace(&mut self.started, true) {
|
||||
self.read_outcome();
|
||||
self.read_last_update();
|
||||
self.begin(false);
|
||||
}
|
||||
}
|
||||
@@ -529,14 +537,8 @@ impl Updater {
|
||||
Status::Ready
|
||||
}
|
||||
|
||||
/// Reads the last update's outcome once per launch, with its guard inside the `Updater`; `check_at_start` calls it.
|
||||
// P3(top-w5): tp.T33 `Updater::read_last_update`
|
||||
pub fn read_last_update(&mut self) {
|
||||
todo!("tp.T33")
|
||||
}
|
||||
|
||||
/// Sets the outcome of a check. The check at start leaves the status as it is: nothing, or
|
||||
/// the outcome of the last update ([`Self::read_outcome`]).
|
||||
/// the outcome of the last update ([`Self::read_last_update`]).
|
||||
fn finish_check(&mut self, answer: Found) {
|
||||
let requested = std::mem::take(&mut self.requested);
|
||||
// A check that was running when an installation started answers with the installation's
|
||||
@@ -575,7 +577,10 @@ impl Updater {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.status = Status::Idle;
|
||||
// A failure's reason moves into the prompt; only an install result stays shown until the user dismisses it or asks for a check.
|
||||
if requested || !matches!(self.status, Status::Updated(_)) {
|
||||
self.status = Status::Idle;
|
||||
}
|
||||
}
|
||||
Ok(None) if requested => self.status = Status::UpToDate,
|
||||
Ok(None) => {}
|
||||
|
||||
@@ -427,6 +427,38 @@ fn a_retry_after_a_helper_failure_while_the_app_runs_waits_for_the_exit() {
|
||||
assert_eq!(next.status(), &Status::Idle, "the retry is not recorded as a failure");
|
||||
}
|
||||
|
||||
/// An automatic check that finds a release keeps the last update's result in the status; a requested check replaces it.
|
||||
#[trial]
|
||||
fn an_automatic_check_that_finds_a_release_keeps_the_last_update_result() {
|
||||
let ctx = egui::Context::default();
|
||||
let (_dir, paths, mut u) = with_records("0.2.0");
|
||||
crate::paths::write_atomic(&paths.data.join("self-update-done.txt"), b"v0.2.0").unwrap();
|
||||
start_answered(&mut u, &ctx, Ok(Some(newer())));
|
||||
assert!(u.prompt.is_some(), "the release is offered");
|
||||
assert_eq!(u.status(), &Status::Updated("0.2.0".into()), "the automatic check leaves the result shown");
|
||||
|
||||
u.check_now();
|
||||
let (tx, rx) = channel();
|
||||
u.check = Some(rx);
|
||||
assert!(tx.send(Ok(Some((newer(), false)))).is_ok());
|
||||
u.tick(&ctx);
|
||||
assert_eq!(u.status(), &Status::Idle, "a requested check replaces it");
|
||||
}
|
||||
|
||||
/// Reading the last update's result starts no check; the check at start still runs once afterwards and keeps the
|
||||
/// result.
|
||||
#[trial]
|
||||
fn reading_the_last_update_starts_no_check() {
|
||||
let (_dir, paths, mut u) = with_records("0.2.0");
|
||||
crate::paths::write_atomic(&paths.data.join("self-update-done.txt"), b"v0.2.0").unwrap();
|
||||
u.read_last_update();
|
||||
assert_eq!(u.status(), &Status::Updated("0.2.0".into()));
|
||||
assert!(u.check.is_none(), "no check is in flight");
|
||||
u.check_at_start();
|
||||
assert!(u.check.is_some(), "the check at start runs after the read");
|
||||
assert_eq!(u.status(), &Status::Updated("0.2.0".into()), "the second read finds no record and keeps the result");
|
||||
}
|
||||
|
||||
/// An offer the app made before the check at start keeps its prompt; when the check finds the
|
||||
/// release too, that prompt says why the last update failed, once.
|
||||
#[trial]
|
||||
|
||||
Reference in New Issue
Block a user