Merge branches 'port/stubs-6' and 'port/stubs-7' into port/stubs

This commit is contained in:
bflatastic
2026-11-21 13:53:17 +07:00
47 changed files with 1141 additions and 162 deletions
Generated
+1
View File
@@ -2070,6 +2070,7 @@ dependencies = [
"sha2 0.10.9",
"tempfile",
"thiserror 2.0.21",
"web-time",
]
[[package]]
+7 -6
View File
@@ -40,16 +40,17 @@ craft-ui = { workspace = true, optional = true }
egui = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
# The control channel, its server and client, screenshots, the profiler and the trace.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
base64 = "0.22"
craft-platform = { workspace = true }
craft-host = { workspace = true, optional = true }
getrandom = "0.3"
hmac = "0.12"
craft-platform = { workspace = true }
log = "0.4"
png = "0.17"
web-time = "1.1"
# The control channel's server and client, the profiler and the trace.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
getrandom = "0.3"
hmac = "0.12"
sha2 = { version = "0.10", default-features = false, features = ["std"] }
thiserror = { workspace = true }
+69
View File
@@ -0,0 +1,69 @@
//! Named controls over the window's access tree: the controls a client finds by name and role, describes, and places
//! a pointer on. Built with the in-process channel, under the `ui` feature.
use craft_ui::runtime::egui::access::{AccessTree, NodeKey};
use craft_ui::runtime::windows::WindowHost;
use egui::ViewportId;
use serde_json::Value;
/// The error of a request made before the first kept pass has an access tree.
pub const NO_TREE: &str = "the window has no access tree yet";
/// The error of a target no control matches.
pub const NO_CONTROL: &str = "no control matches the target";
/// The error of a target several controls match, with no `index`.
pub const AMBIGUOUS: &str = "more than one control matches the target; add `index`, `role` or `within`";
/// The error of a control with no bounds to place a point on.
pub const NO_PLACE: &str = "the control has no bounds to place a point on";
/// The largest `index` a target takes.
pub const MAX_INDEX: usize = 1024;
/// A control named by `{name, role?, within?, index?}`.
///
/// A name match ignores surrounding white space and one trailing `:`; `role` is an AccessKit role name, compared
/// ignoring case; `within` is the name of any matching ancestor. Without `index` exactly one control matches; the
/// reading order is depth first.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Target {
/// The control's accessible name.
pub name: String,
/// The control's role.
pub role: Option<String>,
/// The name of an ancestor the control is inside.
pub within: Option<String>,
/// Which match to take, in reading order.
pub index: Option<usize>,
}
impl Target {
/// The target `value` names: `{name, role?, within?, index?}` and no other field.
pub fn from_params(value: &Value) -> Result<Self, String> {
let _ = value;
todo!("wg.W51")
}
/// The control of `tree` this target names: [`NO_CONTROL`] when none matches, [`AMBIGUOUS`] when several do and
/// there is no `index`.
pub fn find(&self, tree: &AccessTree) -> Result<NodeKey, String> {
let _ = tree;
todo!("wg.W51")
}
}
/// What `ui.find` answers for the control `key`: `{name, role, rect or null, enabled, focused, value?, numeric?,
/// expanded?, selected?, toggled?}`, the rect in screen points.
pub fn describe(tree: &AccessTree, key: NodeKey) -> Value {
let _ = (tree, key);
todo!("wg.W52")
}
/// Runs the access method `method` with `params` in `viewport` from the tree the host kept ([`NO_TREE`] before the
/// first); `None` for a method this module does not have.
pub fn access_method(method: &str, params: &Value, host: &WindowHost, viewport: ViewportId) -> Option<Result<Value, String>> {
let _ = (method, params, host, viewport);
todo!("wg.W52")
}
+15
View File
@@ -457,6 +457,21 @@ impl ActionList {
Ok(())
}
/// Renames the set `set` to `name` (trimmed) in the order and in every member's `set`: [`ActionListError::EmptyName`]
/// for an empty name, [`ActionListError::NameTaken`] for a name another set has, [`ActionListError::NoSuchSet`] for an
/// unknown set. The same name succeeds and changes nothing.
pub fn rename_set(&mut self, set: &str, name: &str) -> Result<(), ActionListError> {
let _ = (set, name);
todo!("mn.M50")
}
/// Removes the set `set` from the order and its actions from the list, and returns the actions in list order:
/// [`ActionListError::NoSuchSet`] for an unknown set.
pub fn delete_set(&mut self, set: &str) -> Result<Vec<Action>, ActionListError> {
let _ = set;
todo!("mn.M51")
}
/// Duplicates the set `set` under a unique name and returns that name; `shift` is as for
/// [`duplicate_action`](Self::duplicate_action). The copies of its actions go after its last
/// action; a set with none becomes an empty set after it.
+4
View File
@@ -161,6 +161,10 @@ pub struct Action {
/// Written by an automation client: playback keeps that client's gate.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub automation: bool,
/// The app's own options for the action. The framework never reads them; every edit, duplicate, move, merge and
/// the file keep them.
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
pub options: serde_json::Map<String, serde_json::Value>,
}
fn is_no_color(color: &ActionColor) -> bool {
+1 -1
View File
@@ -14,11 +14,11 @@
//! two happened, once, between the UI thread and the transport.
use std::sync::mpsc::{Receiver, Sender};
use std::time::Instant;
use craft_ui::runtime::motion;
use craft_ui::runtime::windows::WindowHost;
use serde_json::{Value, json};
use web_time::Instant;
use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotRequest, screenshot_reply};
use crate::synthetic::TARGET_CHANGED;
+3
View File
@@ -12,6 +12,9 @@ use serde_json::{Value, json};
use crate::protocol::Params;
/// The most `fields` one `ui.dialog.set` call takes.
pub const MAX_DIALOG_FIELDS: usize = 256;
/// The open dialogs, the top one last: `{id, parent, key, fields}`, `null` for a missing parent, key or fields. Ids
/// are 64-bit hashes, so they are listed as decimal strings, which every JSON reader keeps exact.
pub fn inspect(host: &DialogHost) -> Value {
+8 -8
View File
@@ -21,21 +21,22 @@ pub mod agents;
#[cfg(feature = "ui")]
pub mod ui;
#[cfg(feature = "ui")]
pub mod access;
#[cfg(not(target_arch = "wasm32"))]
pub mod args;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
#[cfg(feature = "ui")]
pub mod control;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
#[cfg(feature = "ui")]
pub mod dialogs;
#[cfg(not(target_arch = "wasm32"))]
pub mod profiler;
#[cfg(not(target_arch = "wasm32"))]
pub mod protocol;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
#[cfg(feature = "ui")]
pub mod screenshot;
#[cfg(not(target_arch = "wasm32"))]
pub mod security;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
#[cfg(feature = "ui")]
pub mod synthetic;
#[cfg(not(target_arch = "wasm32"))]
pub mod trace;
@@ -45,11 +46,10 @@ pub mod client;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
pub mod server;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
#[cfg(feature = "ui")]
pub use control::{ControlChannel, ControlRequest, ControlResponse, Dispatch, Reply};
#[cfg(not(target_arch = "wasm32"))]
pub use protocol::REPLY_DEADLINE;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
#[cfg(feature = "ui")]
pub use screenshot::Captures;
#[cfg(not(target_arch = "wasm32"))]
pub use security::AutomationError;
+2 -1
View File
@@ -18,11 +18,12 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::mpsc::Sender;
use std::time::{Duration, Instant};
use std::time::Duration;
use base64::Engine as _;
use craft_ui::runtime::windows::{ScreenshotFacts, ScreenshotSlot, WindowHost};
use egui::{ColorImage, ViewportId};
use web_time::Instant;
use crate::control::ControlResponse;
+24 -10
View File
@@ -20,10 +20,12 @@
use craft_behavior::PointerButton;
use craft_keymap::{Key, Mods};
use craft_ui::runtime::egui::access::AccessTree;
use craft_ui::runtime::windows::{Released, WindowHost};
use egui::{Pos2, Vec2, ViewportId, pos2, vec2};
use serde_json::Value;
use crate::access;
use crate::protocol::{BUTTONS, KEY_MODIFIERS, Params};
/// Most clicks one `ui.click` may ask for (`count`).
@@ -53,14 +55,22 @@ pub const NOT_FINITE: &str = "the point must be finite";
/// shows a document. Applications without documents pass `&|_| None`.
pub type DocumentMap<'a> = &'a dyn Fn(Pos2) -> Option<Pos2>;
/// A point of a request: screen points, or document points the application maps.
#[derive(Clone, Copy, Debug, PartialEq)]
/// A point of a request: screen points, document points the application maps, or an offset from a named control.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum At {
/// Screen points.
Screen(Pos2),
/// Document points.
Document(Pos2),
/// An offset from the centre of the rect of the control `target` names.
#[non_exhaustive]
Control {
/// The control.
target: access::Target,
/// The offset from the rect's centre.
offset: Vec2,
},
}
impl At {
@@ -77,8 +87,10 @@ impl At {
/// The screen point, through `map` for a document point; [`NO_DOCUMENT`] when the map has none, and
/// [`OFF_SCREEN`] when it maps beyond [`MAX_SCREEN_POINT`]; a point that is not finite is [`NOT_FINITE`].
pub fn resolve(self, map: DocumentMap<'_>) -> Result<Pos2, String> {
match self {
pub fn resolve(&self, map: DocumentMap<'_>, tree: Option<&AccessTree>) -> Result<Pos2, String> {
let _ = tree; // P3(widgets-w8): wg.W53
match *self {
Self::Control { .. } => todo!("wg.W53"),
Self::Screen(at) if at.x.is_finite() && at.y.is_finite() => Ok(at),
Self::Screen(_) => Err(NOT_FINITE.to_owned()),
Self::Document(at) if !(at.x.is_finite() && at.y.is_finite()) => Err(NOT_FINITE.to_owned()),
@@ -156,7 +168,7 @@ impl Click {
/// Queues a move to the target, then `count` presses and releases of the button, in `viewport`.
pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> {
let count = u32::try_from(self.count).unwrap_or(u32::MAX);
host.inject_click(viewport, self.at.resolve(map)?, self.button, count, self.mods, self.hold);
host.inject_click(viewport, self.at.resolve(map, None)?, self.button, count, self.mods, self.hold); // P3(widgets-w8): wg.W53
Ok(())
}
}
@@ -187,7 +199,7 @@ impl Move {
/// Queues the move in `viewport`.
pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> {
host.inject_move(viewport, self.at.resolve(map)?, self.mods, self.rest);
host.inject_move(viewport, self.at.resolve(map, None)?, self.mods, self.rest); // P3(widgets-w8): wg.W53
Ok(())
}
}
@@ -200,6 +212,8 @@ pub struct Wheel {
pub at: At,
/// The scroll in points, as egui reports it (positive `y` scrolls towards the content's top).
pub delta: Vec2,
/// Whether `delta` is in points or in whole notches of lines.
pub unit: egui::MouseWheelUnit,
/// Modifiers held from the turn on.
pub mods: Mods,
}
@@ -211,12 +225,12 @@ impl Wheel {
let p = Params(&p);
let dx = p.number_in("dx", "dx", None)?.unwrap_or(0.0) as f32;
let dy = p.number_in("dy", "dy", None)?.unwrap_or(0.0) as f32;
Ok(Self { at: At::from_params(&p)?, delta: vec2(dx, dy), mods: p.modifiers(&KEY_MODIFIERS)? })
Ok(Self { at: At::from_params(&p)?, delta: vec2(dx, dy), unit: egui::MouseWheelUnit::Point, mods: p.modifiers(&KEY_MODIFIERS)? })
}
/// Queues the move and the turn in `viewport`.
pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> {
host.inject_wheel(viewport, self.at.resolve(map)?, self.delta, self.mods);
host.inject_wheel(viewport, self.at.resolve(map, None)?, self.delta, self.unit, self.mods); // P3(widgets-w8): wg.W53, sh.K4
Ok(())
}
}
@@ -250,7 +264,7 @@ impl KeyPress {
}
/// A validated `ui.release`.
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Release {
/// Where the release happens; where the pointer is when absent.
@@ -277,7 +291,7 @@ impl Release {
/// Queues the release in `viewport`.
pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> {
let at = self.at.map(|at| at.resolve(map)).transpose()?;
let at = self.at.as_ref().map(|at| at.resolve(map, None)).transpose()?; // P3(widgets-w8): wg.W53
host.inject_release(viewport, at, self.released);
Ok(())
}
+3 -1
View File
@@ -23,7 +23,9 @@ mod words;
pub use body::{ActionMove, ActionPlace};
pub use menu::{ActionsMenuAction, ActionsMenuFacts, ActionsPanelCommands, panel_rows};
pub use panel::{ActionSelection, ActionsEvent, ActionsHost, ActionsPanel, ActionsPanelOutput, ActionsPanelState, ActionsSettings, ShortcutChoice};
pub use panel::{
ActionSelection, ActionsEvent, ActionsHost, ActionsPanel, ActionsPanelOutput, ActionsPanelState, ActionsSettings, ShortcutChoice, StepCells,
};
pub use prompt::LibraryPrompt;
pub use rows::{DIALOG_COLUMN, INCLUDE_COLUMN};
pub use words::ActionsWords;
+23
View File
@@ -98,6 +98,20 @@ pub struct ActionsPanelState {
pub selected: Option<ActionSelection>,
/// The expanded actions, by name (names are unique, so expansion survives moves).
pub expanded: BTreeSet<String>,
/// The sets a shift-click selected, from the current set to the clicked one, in the set order; empty when there is
/// no range.
pub selected_sets: Vec<String>,
}
/// Which step cells the rows show.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StepCells {
/// The include cell and the dialog cell.
#[default]
IncludeAndDialog,
/// The include cell only: the dialog column is left out of the cells and the list's columns.
Include,
}
/// A function-key shortcut chosen in the context menu (Photoshop's Action Options).
@@ -235,6 +249,8 @@ pub enum ActionsEvent {
/// Duplicate this row ([`ActionList::duplicate_action`], [`ActionList::duplicate_step`],
/// [`ActionList::duplicate_set`]): from the menu row or a row dropped on New Action.
Duplicate(ActionSelection),
/// Delete with a range of sets selected: the range, in one event, so the app asks one question.
DeleteSets(Vec<String>),
/// Record Again: replace step `step` of `action` with a new recording
/// ([`ActionList::replace_step`]).
#[non_exhaustive]
@@ -395,6 +411,13 @@ impl<'a> ActionsPanel<'a> {
self
}
/// Which step cells the rows show.
#[must_use]
pub fn step_cells(self, cells: StepCells) -> Self {
let _ = cells;
todo!("mn.M40")
}
/// Whether the panel takes input (default true).
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
+2 -2
View File
@@ -410,8 +410,8 @@ fn ui_ime_reaches_a_focused_text_field_as_a_preedit_then_a_commit_in_order() {
fn a_point_that_is_not_finite_is_refused() {
for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
for at in [At::Screen(pos2(bad, 1.0)), At::Screen(pos2(1.0, bad)), At::Document(pos2(bad, 1.0))] {
assert_eq!(at.resolve(&|p| Some(p)), Err(NOT_FINITE.to_owned()), "{at:?}");
assert_eq!(at.resolve(&|p| Some(p), None), Err(NOT_FINITE.to_owned()), "{at:?}"); // P3(widgets-w8): wg.W53
}
}
assert_eq!(At::Screen(pos2(3.0, 4.0)).resolve(&|_| None), Ok(pos2(3.0, 4.0)));
assert_eq!(At::Screen(pos2(3.0, 4.0)).resolve(&|_| None, None), Ok(pos2(3.0, 4.0))); // P3(widgets-w8): wg.W53
}
+4
View File
@@ -2,9 +2,13 @@
//! that edits them (Photoshop's Properties › Character axis sliders; FigCraft's axis panel). The data types
//! and reading them from a font are always available; the sliders are on `ui`.
#[cfg(feature = "ui")]
mod button;
#[cfg(feature = "ui")]
mod sliders;
#[cfg(feature = "ui")]
pub use button::AxesButton;
#[cfg(feature = "ui")]
pub use sliders::*;
use skrifa::string::StringId;
+40
View File
@@ -0,0 +1,40 @@
//! The axes behind one button: a `Button` that opens the axis sliders in a popover.
use craft_ui::contract::{Bind, Pattern, Props};
use craft_ui::runtime::env::Label;
use egui::Ui;
use super::{AxisSlidersOutput, AxisValues, FontAxis, NamedInstance};
/// A `Button` with the label that opens an anchored `Popover` holding `AxisSliders` over the same props. The open
/// state is the button's own memory. The output is the sliders' (`edit`, `instance`), with the button's response.
#[must_use = "show the button with `show`"]
#[derive(Pattern, Props)]
#[allow(dead_code)] // P3(type-w3): ty.X21
pub struct AxesButton<'a> {
label: Label,
axes: &'a [FontAxis],
values: Bind<'a, AxisValues>,
/// The named instances of the face, listed above the sliders.
#[prop]
instances: &'a [NamedInstance],
/// The style's weight, which an unset `wght` axis shows (an unset axis shows its default without it).
#[prop(quantity = "font weight, the `wght` coordinate")]
weight: Option<f32>,
/// Whether the style is italic: an unset `ital` axis then shows its maximum, once a weight is given.
#[prop]
italic: bool,
}
impl<'a> AxesButton<'a> {
/// A button named `label` over the `axes` of a face, editing the coordinates `values`.
pub fn new(label: impl Into<Label>, axes: &'a [FontAxis], values: Bind<'a, AxisValues>) -> Self {
AxesButton { label: label.into(), axes, values, instances: &[], weight: None, italic: false }
}
/// Draws the button and, while it is open, the sliders; reports the sliders' edit made this pass.
pub fn show(self, ui: &mut Ui) -> AxisSlidersOutput {
let _ = ui;
todo!("ty.X21")
}
}
+126 -10
View File
@@ -10,8 +10,8 @@ use std::sync::Arc;
use craft_behavior::Selection;
use craft_host::Section;
use craft_ui::contract::{
ActivateOn, Bind, CollectionEvent, Entry, NoValue, Outcome, Pad, Pattern, Props, Remember as _, SelectMode, Show as _, ShowCollection as _,
ShowContainer as _,
ActivateOn, Bind, CollectionEvent, CommandSet, Entry, NoValue, Outcome, Pad, Pattern, Props, Remember as _, SelectMode, Show as _,
ShowCollection as _, ShowContainer as _,
};
use craft_ui::display::{Shade, Spinner, Text};
use craft_ui::layout_components::{Row, Stack};
@@ -48,6 +48,12 @@ craft_ui::words! {
selected: template "glyphs.selected" = "U+{code} · {count}";
/// `{char}` the glyph, `{code}` its code point.
cell: template "glyphs.cell" = "{char}, U+{code}";
/// `{code}` the lead character's code point, `{gid}` its glyph id, `{count}` the count word.
selected_glyph: template "glyphs.selectedGlyph" = "U+{code} glyph {gid} · {count}";
/// `{gid}` the lead glyph's id, `{count}` the count word.
unencoded: template "glyphs.unencoded" = "glyph {gid} · {count}";
/// `{name}` the glyph's name, `{gid}` its id.
glyph_cell: template "glyphs.glyphCell" = "{name}, glyph {gid}";
punctuation: "glyphs.categoryPunctuation" = "Punctuation";
alternates: "glyphs.categoryAlternates" = "Alternates for Selection";
numbers: "glyphs.categoryNumbers" = "Numbers";
@@ -108,14 +114,43 @@ impl GlyphsWords {
}
}
/// A grid cell: a character the face maps, or a glyph no character maps (unencoded, positional forms).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum GlyphCell {
/// A character the face maps.
Char(char),
/// A glyph id no character maps.
Glyph(u32),
}
/// What the source says about one shown cell this pass.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct CellInfo {
/// The glyph id.
pub gid: Option<u32>,
/// The glyph's name.
pub name: Option<String>,
/// A note line.
pub note: Option<String>,
/// Whether the cell is shown dimmed.
pub dimmed: bool,
/// Whether the cell has alternate glyphs.
pub has_alternates: bool,
}
/// Where glyph cells come from: the app's text engine draws a glyph of a face at a pixel size and lists the
/// characters a face has. Apps plug in their own.
pub trait GlyphSource: Send + Sync {
/// Every character the face (family, style) has a glyph for, in code point order.
fn charmap(&self, family: &str, style: &str) -> Vec<char>;
/// The glyph of `c` in the face, `px` pixels tall, as an image for a texture; `None` when the face lacks it.
/// The panel tints the image with the text colour, so a glyph is white with its coverage in the alpha channel.
fn glyph(&self, family: &str, style: &str, c: char, px: u32) -> Option<ColorImage>;
/// The cells of a category: characters in code point order, then unencoded glyphs. `"Entire Font"` is every
/// cell; any other id is a [`CATEGORIES`] id or one of the source's [`categories`](GlyphSource::categories).
fn cells(&self, family: &str, style: &str, category: &str) -> Vec<GlyphCell>;
/// The glyph of a character or glyph id in the face, `px` pixels tall, as an image for a texture; `None` when
/// the face lacks it. The panel tints the image with the text colour, so a glyph is white with its coverage in
/// the alpha channel.
fn glyph(&self, family: &str, style: &str, cell: GlyphCell, px: u32) -> Option<ColorImage>;
/// Whether `c` is in `category` (one of [`CATEGORIES`]).
fn in_category(&self, c: char, category: &str) -> bool;
/// Whether the fonts are read. Not ready, the panel shows a spinner and muted text and no grid, and asks for a
@@ -127,6 +162,21 @@ pub trait GlyphSource: Send + Sync {
fn revision(&self) -> u64 {
0
}
/// The face's own categories (id, shown name), listed after [`CATEGORIES`].
fn categories(&self, family: &str, style: &str) -> Vec<(String, String)> {
let _ = (family, style);
Vec::new()
}
/// Glyph id and name, a note line, dimmed, alternates; called for shown cells only.
fn describe(&self, family: &str, style: &str, cell: GlyphCell) -> CellInfo {
let _ = (family, style, cell);
CellInfo::default()
}
/// The popup's cells, the cell's own glyph first; called when the popup opens.
fn alternates(&self, family: &str, style: &str, cell: GlyphCell) -> Vec<GlyphCell> {
let _ = (family, style, cell);
Vec::new()
}
}
/// The panel's remembered state (`[glyphs_panel]`): category, zoom and the recent glyphs.
@@ -155,10 +205,52 @@ pub struct GlyphsPanelOutput {
pub response: Response,
/// A glyph to insert at the caret (double-click, Enter on the focused cell); only where the app can insert.
pub insert: Option<String>,
/// Double-click or Enter on a cell (grid or recents) while `can_insert`; the host inserts or applies it. A
/// `Char` cell still enters the recents.
pub activated: Option<GlyphCell>,
/// A pick in a cell's alternates popup.
pub alternate: Option<AlternatePick>,
/// The family or style changed in the panel's own pickers.
pub font_changed: bool,
}
/// The cell whose popup was used and the picked glyph.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AlternatePick {
/// The cell whose alternates popup was used.
pub cell: GlyphCell,
/// The picked glyph.
pub glyph: GlyphCell,
}
/// The label, tooltip and state of the cell's corner action; the panel takes it in its own scope.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet)]
#[command(prefix = "glyphs", scope = "glyphs")]
#[non_exhaustive]
pub enum GlyphsCommand {
/// Opens the cell's alternates popup.
#[command(label = "Show Alternates")]
Alternates,
}
/// The one way to paint a glyph cell (thumbnail cache, inset, tint): the panel's grid, recents and popup, and an
/// app's own glyph cells. The painter owns a clone of `ctx` and copies of `family` and `style`, so it borrows only
/// `source`.
pub fn glyph_painter<'s>(
ctx: &egui::Context,
source: &'s dyn GlyphSource,
family: &str,
style: &str,
cell: GlyphCell,
) -> impl Fn(&ContentPainterCx, Rect) + use<'s> {
let _ = (ctx, family, style, cell);
move |_, _| {
let _ = source;
todo!("ty.X54")
}
}
impl Outcome for GlyphsPanelOutput {
type Value = NoValue;
@@ -193,7 +285,8 @@ impl ThumbSource<GlyphKey> for GlyphPictures<'_> {
}
fn render(&self, key: &GlyphKey, request: &ThumbRequest) -> ThumbRender {
match self.0.glyph(&key.family, &key.style, key.c, request.side) {
// P3(type-w4): ty.X43
match self.0.glyph(&key.family, &key.style, GlyphCell::Char(key.c), request.side) {
Some(image) => ThumbRender::Ready(image),
None => ThumbRender::Blank,
}
@@ -284,6 +377,16 @@ pub struct GlyphsPanel<'a> {
/// Whether the app has a place to insert a glyph: a double click or Enter inserts.
#[prop]
can_insert: bool,
/// The host's cell (the selected character); the grid selects it.
#[prop]
marked: Option<GlyphCell>,
/// In this pass only, the grid moves its lead to that cell and scrolls it into view. The host passes it in the
/// pass its marked cell changes.
#[prop]
reveal: Option<GlyphCell>,
/// Shown in place of the grid when the category has no cells.
#[prop(into)]
empty: Option<Label>,
}
impl<'a> GlyphsPanel<'a> {
@@ -295,12 +398,25 @@ impl<'a> GlyphsPanel<'a> {
style: Bind<'a, String>,
settings: Bind<'a, GlyphsPanelSettings>,
) -> Self {
GlyphsPanel { label: label.into(), source, family, style, settings, families: &[], styles: &[], can_insert: false }
GlyphsPanel {
label: label.into(),
source,
family,
style,
settings,
families: &[],
styles: &[],
can_insert: false,
marked: None,
reveal: None,
empty: None,
}
}
/// Shows the panel.
pub fn show(self, ui: &mut Ui) -> GlyphsPanelOutput {
let GlyphsPanel { label, source, mut family, mut style, mut settings, families, styles, can_insert } = self;
let GlyphsPanel { label, source, mut family, mut style, mut settings, families, styles, can_insert, marked, reveal, empty } = self;
let _ = (marked, reveal, empty); // P3(type-w4): ty.X47, ty.X48
let env = Env::of(ui);
let words = env.words::<GlyphsWords>();
if !source.ready() {
@@ -311,7 +427,7 @@ impl<'a> GlyphsPanel<'a> {
});
});
craft_ui::runtime::frame::request_repaint_after(ui.ctx(), SCAN_POLL_SECONDS);
return GlyphsPanelOutput { response: shown.output, insert: None, font_changed: false };
return GlyphsPanelOutput { response: shown.output, insert: None, activated: None, alternate: None, font_changed: false };
}
let thumbs = Thumbnails::<GlyphKey>::in_context(ui.ctx(), "craft-font-manager-glyphs", ThumbnailOptions::new());
let pictures = GlyphPictures(source);
@@ -455,6 +571,6 @@ impl<'a> GlyphsPanel<'a> {
write_bind(&mut settings, cx, state, "Glyphs panel");
}
});
GlyphsPanelOutput { response: shown.output, insert, font_changed }
GlyphsPanelOutput { response: shown.output, insert, activated: None, alternate: None, font_changed }
}
}
+13 -3
View File
@@ -8,7 +8,7 @@ use skrifa::instance::{LocationRef, Size};
use skrifa::outline::{DrawSettings, OutlinePen};
use skrifa::{FontRef, MetadataProvider as _};
use super::{GlyphSource, GlyphsPanel, GlyphsPanelSettings};
use super::{GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings};
const UBUNTU: &[u8] = epaint_default_fonts::UBUNTU_LIGHT;
const HACK: &[u8] = epaint_default_fonts::HACK_REGULAR;
@@ -67,7 +67,11 @@ impl GlyphSource for NotReady {
Vec::new()
}
fn glyph(&self, _: &str, _: &str, _: char, _: u32) -> Option<ColorImage> {
fn cells(&self, _: &str, _: &str, _: &str) -> Vec<GlyphCell> {
todo!("ty.X41")
}
fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option<ColorImage> {
None
}
@@ -98,7 +102,13 @@ impl GlyphSource for FaceGlyphs {
chars
}
fn glyph(&self, family: &str, _style: &str, c: char, px: u32) -> Option<ColorImage> {
fn cells(&self, _: &str, _: &str, _: &str) -> Vec<GlyphCell> {
todo!("ty.X41")
}
fn glyph(&self, family: &str, _style: &str, cell: GlyphCell, px: u32) -> Option<ColorImage> {
// P3(type-w4): ty.X43
let GlyphCell::Char(c) = cell else { return None };
let font = Self::font(family)?;
let id = font.charmap().map(c)?;
let em = px as f32 * 0.8;
+109 -3
View File
@@ -75,6 +75,21 @@ craft_ui::words! {
format_true_type: "fontPicker.formatTrueType" = "TrueType";
format_variable: "fontPicker.formatVariable" = "Variable";
served: "fontPicker.served" = "Not installed";
all_scripts: "fontPicker.allScripts" = "All Scripts";
script_latin: "fontPicker.scriptLatin" = "Latin";
script_japanese: "fontPicker.scriptJapanese" = "Japanese";
script_thai: "fontPicker.scriptThai" = "Thai";
any_kind: "fontPicker.anyKind" = "Any Kind";
font_technology: "fontPicker.fontTechnology" = "Font Technology";
preview_size: "fontPicker.previewSize" = "Font Preview Size";
preview_small: "fontPicker.previewSmall" = "Small";
preview_medium: "fontPicker.previewMedium" = "Medium";
preview_large: "fontPicker.previewLarge" = "Large";
/// The similar-fonts chip, with `{family}` for the reference family.
similar_to: template "fontPicker.similarTo" = "≈ {family}";
clear_similar: "fontPicker.clearSimilar" = "Clear Similar Fonts";
/// The name of a row's show-similar action, with `{row}` for the row's label.
show_similar: template "fontPicker.showSimilar" = "Show fonts similar to {row}";
}
}
@@ -155,6 +170,75 @@ impl FontPreviewSize {
}
}
/// Coverage from the face: Latin, the basic Latin letters in the cmap; Japanese, the OS/2 kana or CJK unicode-range
/// bits or the JIS code page bit, or a Japanese family name; Thai, U+0E01 and U+0E32 in the cmap. Read lazily like the
/// class.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FontScript {
/// The basic Latin letters.
Latin,
/// Japanese kana and CJK.
Japanese,
/// Thai.
Thai,
}
impl FontScript {
/// Every script the script row can offer, in order.
pub const ALL: [FontScript; 3] = [FontScript::Latin, FontScript::Japanese, FontScript::Thai];
}
/// A family set the host gives (VectorCraft: Document, Recently Added), one filter toggle each. An `ordered` set that
/// is on lists in its own order. A disabled set's toggle is off and dimmed, with its hint as the reason.
#[allow(dead_code)] // P3(type-w2): ty.X11
pub struct FamilySet<'a> {
key: &'a str,
label: Label,
hint: Option<Label>,
families: &'a [String],
ordered: bool,
enabled: bool,
}
impl<'a> FamilySet<'a> {
/// The set `key` named `label` over `families`.
pub fn new(key: &'a str, label: impl Into<Label>, families: &'a [String]) -> Self {
let _ = (key, label.into(), families);
todo!("ty.X11")
}
/// The reason shown while the set is disabled.
pub fn hint(self, hint: impl Into<Label>) -> Self {
let _ = hint.into();
todo!("ty.X11")
}
/// Lists the set in its own order while it is on.
pub fn ordered(self) -> Self {
todo!("ty.X11")
}
/// Whether the set's toggle can be turned on.
pub fn enabled(self, on: bool) -> Self {
let _ = on;
todo!("ty.X11")
}
}
/// Named layout of the list's filter area. `Toolbar`: the toggle row and class column. `Chips`: rows of chip toggles
/// (the script row; Favorites, the host sets, Any Kind and the classes; Font Technology and Variable; the Font
/// Preview Size row).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FilterLayout {
/// The toggle row and class column.
#[default]
Toolbar,
/// Rows of chip toggles.
Chips,
}
/// What narrows the list. Every filter off shows every installed family.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
@@ -165,14 +249,18 @@ pub struct FontFilters {
pub favorites: bool,
/// Only variable fonts.
pub variable: bool,
/// Families like the current one, most alike first ([`SIMILAR_COUNT`] of them).
pub similar: bool,
/// The reference family of Show Similar Fonts, most alike first ([`SIMILAR_COUNT`] of them); `None` is off.
pub similar: Option<String>,
/// Only families whose regular face covers the script.
pub script: Option<FontScript>,
/// Keys of the host family sets that are on; each keeps only its families.
pub sets: Vec<String>,
}
impl FontFilters {
/// Whether any filter narrows the list (Clear All is enabled).
pub fn any(&self) -> bool {
self.class.is_some() || self.favorites || self.variable || self.similar
self.class.is_some() || self.favorites || self.variable || self.similar.is_some() || self.script.is_some() || !self.sets.is_empty()
}
/// Clear All: every filter off.
@@ -200,6 +288,8 @@ pub struct FontPickerSettings {
pub preview: FontPreviewSize,
/// Show family names in English rather than their own language (Type › Show Font Names in English).
pub names_in_english: bool,
/// Row samples and the banner paint black type on a white paper fill, in every theme.
pub samples_on_white: bool,
}
impl Default for FontPickerSettings {
@@ -210,6 +300,7 @@ impl Default for FontPickerSettings {
recent_limit: 10,
preview: FontPreviewSize::default(),
names_in_english: false,
samples_on_white: false,
}
}
}
@@ -461,6 +552,18 @@ pub struct FontPicker<'a> {
/// Families the host can fetch but that are not installed, listed with the served mark.
#[prop]
served: &'a [String],
/// The host's family sets; their toggles follow Favorites.
#[prop]
#[allow(dead_code)] // P3(type-w2): ty.X12
sets: &'a [FamilySet<'a>],
/// The scripts the script row offers (with All Scripts first); empty: no script row.
#[prop]
#[allow(dead_code)] // P3(type-w2): ty.X13
scripts: &'a [FontScript],
/// Picks the layout of the filter area.
#[prop]
#[allow(dead_code)] // P3(type-w2): ty.X15
filter_layout: FilterLayout,
}
impl<'a> FontPicker<'a> {
@@ -478,6 +581,9 @@ impl<'a> FontPicker<'a> {
preview: Preview::Unchanged,
preview_text: None,
served: &[],
sets: &[],
scripts: &[],
filter_layout: FilterLayout::default(),
}
.label(label)
}
+2 -1
View File
@@ -342,7 +342,8 @@ pub(super) fn list(catalog: &Arc<Catalog>, infos: &Infos, listing: &Listing<'_>,
});
}
let mut comparable = true;
if filters.similar {
// P3(type-w2): ty.X7
if filters.similar.is_some() {
let reference = infos.traits(catalog, listing.current).filter(|t| t.class.is_some() || t.panose.iter().any(|d| *d > 1));
if let Some(reference) = reference {
let mut scored: Vec<(f32, FamilyRow)> = rows
+11 -5
View File
@@ -192,14 +192,19 @@ fn format_label(format: FontFormat, words: &FontPickerWords) -> Label {
/// The filter toggles above the list: the class column's collapse button, variable fonts, favourites and similar
/// fonts, and Clear All.
fn filter_bar(ui: &mut egui::Ui, filters: &mut FontFilters, hide_classes: &mut bool, words: &FontPickerWords) {
fn filter_bar(ui: &mut egui::Ui, filters: &mut FontFilters, hide_classes: &mut bool, current: &str, words: &FontPickerWords) {
Row::new().show(ui, |ui, _| {
let (icon, label) = if *hide_classes { ("chevrons_right", &words.show_classes) } else { ("chevrons_left", &words.hide_classes) };
ToggleButton::new(label.clone(), Bind::bound(hide_classes)).icon(IconId::new(icon)).icon_only().show(ui);
ToggleButton::new(words.variable.clone(), Bind::bound(&mut filters.variable)).icon(IconId::new("font_variable")).icon_only().show(ui);
let star = if filters.favorites { "star_filled" } else { "star" };
ToggleButton::new(words.favorites.clone(), Bind::bound(&mut filters.favorites)).icon(IconId::new(star)).icon_only().show(ui);
ToggleButton::new(words.similar.clone(), Bind::bound(&mut filters.similar)).icon(IconId::new("font_similar")).icon_only().show(ui);
// P3(type-w2): ty.X7
let mut similar = filters.similar.is_some();
ToggleButton::new(words.similar.clone(), Bind::bound(&mut similar)).icon(IconId::new("font_similar")).icon_only().show(ui);
if similar != filters.similar.is_some() {
filters.similar = similar.then(|| current.to_owned());
}
let clear = Button::new(words.clear_all.clone()).enabled(filters.any()).show(ui);
if clicked(&clear) {
filters.clear();
@@ -320,7 +325,8 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
let favorites_empty = settings.as_ref().is_none_or(|s| s.favorites.is_empty());
// Rows are keyed, so the stamp names only what rebuilds the list: opening a family keeps the lead.
let mut stamp = DefaultHasher::new();
(&query, narrowing.class, narrowing.favorites, narrowing.variable, narrowing.similar).hash(&mut stamp);
// P3(type-w2): ty.X7
(&query, narrowing.class, narrowing.favorites, narrowing.variable, &narrowing.similar).hash(&mut stamp);
let banner_family = lead.unwrap_or_else(|| family.clone());
let banner_text = picker.preview_text;
let name = words.list.clone();
@@ -335,14 +341,14 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
banner(ui, catalog, &infos, &banner_family, &shown_name, text);
}
if let Some(filters) = filters.as_mut() {
filter_bar(ui, filters, &mut hide_classes, &words);
filter_bar(ui, filters, &mut hide_classes, &family, &words);
}
Row::new().show(ui, |ui, _| {
if let (Some(filters), false) = (filters.as_mut(), hide_classes) {
class_column(ui, filters, &words);
}
Stack::new().show(ui, |ui, _| {
if narrowing.similar && !comparable {
if narrowing.similar.is_some() && !comparable {
Text::new(words.no_similar.clone()).show(ui);
}
if slots.is_empty() {
+1 -1
View File
@@ -114,7 +114,7 @@ fn a_served_family_lists_without_a_sample_and_is_reported_rested_once() {
fn similar_fonts_put_the_current_family_first_and_leave_the_list_alone_without_a_reference() {
let catalog = catalog_of(&[epaint_default_fonts::HACK_REGULAR, epaint_default_fonts::UBUNTU_LIGHT, INTER_REGULAR]);
let mut similar = FontFilters::default();
similar.similar = true;
similar.similar = Some("Inter".to_owned()); // P3(type-w2): ty.X7
let rows = family_rows(&catalog, "", None, &similar, "Inter", "en");
let names: Vec<&str> = rows.iter().map(|row| row.family.as_str()).collect();
assert_eq!(names.first(), Some(&"Inter"), "the current family first, though it is not first by name");
+4 -1
View File
@@ -63,6 +63,9 @@ pub struct MenuBarOutput {
/// The menu titles alone, without the room the bar leaves after them
/// ([`craft_ui::menu::MenuBarOutput::titles`]).
pub titles: Rect,
/// True in the one pass where a menu of the bar opened while none was open
/// ([`craft_ui::menu::MenuBarOutput::opened`]).
pub opened: bool,
}
/// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, in a top panel.
@@ -143,6 +146,6 @@ impl<'a> MenuBarUi<'a> {
if let Some(menu) = help {
bar = bar.help(MenuHelp::new(menu, &entries));
}
MenuBarOutput { titles: bar.show(ui).titles }
MenuBarOutput { titles: bar.show(ui).titles, opened: false } // P3(menus-w3): mn.M26
}
}
+2 -1
View File
@@ -136,6 +136,7 @@ impl<'a> Rows<'a> {
Menu::submenu_row(ui, label, |ui, _| self.show(ui, children));
}
}
Node::Heading(_) => todo!("mn.M7"),
Node::Standard { .. } => {}
}
}
@@ -213,7 +214,7 @@ fn is_dead(nodes: &[Node]) -> bool {
!nodes.iter().any(|node| match node {
Node::Item(item) => item.enabled,
Node::Submenu { children, .. } => !is_dead(children),
Node::Separator | Node::Standard { .. } => false,
Node::Separator | Node::Heading(_) | Node::Standard { .. } => false,
})
}
+12
View File
@@ -27,6 +27,8 @@ pub enum Event {
/// A click the app's [`NativeMenu::on_command`] hook ran; [`NativeMenu::take_clicks`] leaves it
/// out.
Handled(CommandRef),
/// The platform began tracking a native menu.
Opened,
}
/// How ⌘C, ⌘X and ⌘V reach egui when the native menu takes them as key equivalents (an Edit
@@ -222,6 +224,9 @@ pub struct NativeMenu {
/// The commands whose items were check items in a layout so far: they stay check items, so
/// that `checked` going from `Some` to `None` doesn't rebuild the menus.
checkable: HashSet<String>,
/// A backend reported [`Event::Opened`] since [`NativeMenu::take_opened`] last answered.
#[allow(dead_code)] // P3(menus-w1): mn.M10
opened: bool,
}
impl NativeMenu {
@@ -244,6 +249,7 @@ impl NativeMenu {
bar: None,
synced_gate: None,
checkable: HashSet::new(),
opened: false,
}
}
@@ -338,11 +344,17 @@ impl NativeMenu {
Event::Tap(chord) => self.add_key(&host, &chord, true),
Event::Click(command) => self.clicks.push(command),
Event::Handled(_) => {}
Event::Opened => todo!("mn.M10"),
}
self.dirty = true;
}
}
/// Whether a backend reported [`Event::Opened`] since the last call; reports it once and clears it.
pub fn take_opened(&mut self) -> bool {
todo!("mn.M10")
}
/// `tap`: a press and its release, for a click that stands for the key (no key-up follows).
fn add_key(&mut self, host: &WindowHost, chord: &Chord, tap: bool) {
let clipboard = self.clipboard == ClipboardKeys::Egui && chord.mods == Mods::CMD && !self.gate.recording_shortcut;
+1
View File
@@ -174,6 +174,7 @@ fn lower_nodes(nodes: &[Node], targets: &mut HashMap<String, Target>) -> Vec<nat
.map(|n| match n {
Node::Separator => native::Node::Separator,
Node::Submenu { label, children, .. } => native::Node::Submenu { label: label.clone(), children: lower_nodes(children, targets) },
Node::Heading(_) => todo!("mn.M9"),
Node::Standard { kind, label } => native::Node::Platform {
kind: match kind {
Standard::Services => native::Platform::Services,
+24 -4
View File
@@ -6,6 +6,7 @@ use std::ops::BitOr;
use craft_keymap::{Chord, CommandRef, Mods};
use craft_theme::Srgba;
use craft_ui::primitives::FacePaint;
/// The app's menus, in order, and its open documents.
#[derive(Clone, Debug, Default, PartialEq)]
@@ -151,6 +152,8 @@ pub enum Node {
/// The platforms it is shown on.
platforms: Platforms,
},
/// A caption over the rows that follow it. Never a command.
Heading(String),
/// An item AppKit provides and runs itself (Services, Zoom, …), with the label to show.
#[non_exhaustive]
Standard {
@@ -194,6 +197,9 @@ pub struct Item {
pub tooltip: Option<String>,
/// The command the item runs instead while its modifiers are held as it is chosen.
pub alternate: Option<Alternate>,
/// A small painted sample shown in the row (in-window bar only; the native menu ignores it, as it
/// ignores `tint`).
pub sample: Option<FacePaint>,
}
/// The command a row runs while `mods` are held as it is chosen (Alt on Merge Visible runs Stamp
@@ -362,6 +368,7 @@ impl Item {
tint: None,
tooltip: None,
alternate: None,
sample: None,
}
}
@@ -418,6 +425,12 @@ impl Item {
self.tooltip = Some(text.into());
self
}
/// Show `sample` in the row, painted by the in-window bar.
pub fn sample(self, sample: FacePaint) -> Item {
let _ = sample;
todo!("mn.M6")
}
}
impl From<Item> for Node {
@@ -437,12 +450,18 @@ impl Node {
Node::Submenu { label: label.into(), children, role: None, platforms: Platforms::ALL }
}
/// A caption over the rows that follow it.
pub fn heading(label: impl Into<String>) -> Node {
let _ = label;
todo!("mn.M2")
}
/// Give an item or a submenu a role: `Node::submenu("Theme", pages).role(ItemRole::Appearance)`.
pub fn role(mut self, role: ItemRole) -> Node {
match &mut self {
Node::Item(it) => it.role = Some(role),
Node::Submenu { role: r, .. } => *r = Some(role),
Node::Separator | Node::Standard { .. } => {}
Node::Separator | Node::Heading(_) | Node::Standard { .. } => {}
}
self
}
@@ -452,7 +471,7 @@ impl Node {
match &mut self {
Node::Item(it) => it.platforms = platforms,
Node::Submenu { platforms: p, .. } => *p = platforms,
Node::Separator | Node::Standard { .. } => {}
Node::Separator | Node::Heading(_) | Node::Standard { .. } => {}
}
self
}
@@ -490,7 +509,7 @@ impl MenuBar {
match n {
Node::Item(it) => out.push(it),
Node::Submenu { children, .. } => walk(children, out),
Node::Separator | Node::Standard { .. } => {}
Node::Separator | Node::Heading(_) | Node::Standard { .. } => {}
}
}
}
@@ -508,7 +527,7 @@ impl MenuBar {
match n {
Node::Item(it) => f(it),
Node::Submenu { children, .. } => walk(children, f),
Node::Separator | Node::Standard { .. } => {}
Node::Separator | Node::Heading(_) | Node::Standard { .. } => {}
}
}
}
@@ -770,6 +789,7 @@ fn hash_nodes(nodes: &[Node], h: &mut DefaultHasher) {
']'.hash(h);
}
Node::Standard { kind, label } => ('s', kind, label).hash(h),
Node::Heading(_) => todo!("mn.M4"),
}
}
}
+1 -1
View File
@@ -53,7 +53,7 @@ fn collect(nodes: &[Node], path: &mut Vec<String>, english_of: &dyn Fn(Labeled<'
collect(children, path, english_of, entries);
path.pop();
}
Node::Item(_) | Node::Separator | Node::Standard { .. } => {}
Node::Item(_) | Node::Separator | Node::Heading(_) | Node::Standard { .. } => {}
}
}
}
+29 -4
View File
@@ -33,7 +33,7 @@
//! Some(Outcome::Import { formats, .. }) => self.pick_import_file(formats),
//! Some(Outcome::Export { name, json, .. }) => self.save_file(&name, json),
//! Some(Outcome::Summary { name, html, .. }) => self.show_summary(&name, html),
//! Some(Outcome::Remembered(answers)) => self.settings.import_answers.extend(answers),
//! Some(Outcome::Remembered { targets, codes }) => self.settings.import_answers.extend(targets, codes),
//! _ => {}
//! }
//! if !state.is_open() {
@@ -52,7 +52,7 @@
//! | `Import { formats }` | Opens a file of one of the formats, then calls [`ShortcutsDialog::import_json`] (craft-keymap JSON, [`JSON_FORMAT`]) or reads it into a `ForeignSet` and calls [`ShortcutsDialog::review_import`]. |
//! | `Export { name, json }`, `ExportAs { format, name, keymap }` | Writes the set where the user chooses (a download on the web). |
//! | `Summary { name, html, text }` | Shows, saves or prints the summary. |
//! | `Remembered(answers)` | Keeps the user's import answers for the next import (`ImportOptions::remembered`). |
//! | `Remembered { targets, codes }` | Keeps the user's import answers for the next import (`ImportOptions::remembered` and `ImportOptions::codes`). |
//!
//! The crate never opens a file dialog or touches the file system. When the app's own step fails
//! while the dialog is open (a file it cannot read), [`DialogState::show_error`] shows the
@@ -77,6 +77,7 @@
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use craft_behavior::edit_history::Step;
use craft_keymap::{Binding, Builtins, CommandDef, CommandRef, ForeignSet, ImportOptions, Keymap, ProfileError, Profiles, Trigger};
@@ -172,8 +173,14 @@ pub enum Outcome {
/// The summary as plain text.
text: String,
},
/// Import answers the user gave (item → command), for the app to keep for later imports.
Remembered(BTreeMap<String, CommandRef>),
/// Import answers the user gave, for the app to keep for later imports.
#[non_exhaustive]
Remembered {
/// The target picked by remember key (`None`: No equivalent), feeding `ImportOptions::remembered`.
targets: BTreeMap<String, Option<CommandRef>>,
/// The answer for each undecided code by `key:N` / `mods:N`, feeding `ImportOptions::codes`.
codes: BTreeMap<String, Option<String>>,
},
}
/// What happens when a recorded chord is held by other commands.
@@ -361,6 +368,17 @@ impl craft_ui::contract::Outcome for ShortcutsOutput {
}
}
/// The Hold Shortcuts setting the dialog shows and edits.
#[derive(Clone, Debug, PartialEq)]
pub struct HoldSetting {
/// Whether hold shortcuts are on.
pub on: bool,
/// The delay, in seconds, before a held key counts as a hold.
pub delay: f64,
/// The delays the field accepts.
pub range: RangeInclusive<f64>,
}
/// The dialog for one pass: what it edits, borrowed, and how it behaves.
#[must_use = "show the dialog with `show`"]
#[derive(Pattern)]
@@ -372,6 +390,13 @@ pub struct ShortcutsDialog<'a> {
}
impl<'a> ShortcutsDialog<'a> {
/// Shows the Hold Shortcuts switch, its delay and the explanation, and a Hold column recorded like the
/// shortcut column. Cancel restores the setting; the app saves it on [`Outcome::Ok`].
pub fn holds(self, holds: &'a mut HoldSetting) -> Self {
let _ = holds;
todo!("kb.C16a")
}
/// A dialog editing `keymap`; without further builder calls it has no sets and default options.
pub fn new(keymap: &'a mut Keymap) -> Self {
ShortcutsDialog { keymap, sets: None, options: None, tabs: None }
+6
View File
@@ -126,6 +126,10 @@ pub struct DialogSnapshot {
pub set: Option<String>,
/// Whether there is an edit to undo.
pub can_undo: bool,
/// Whether Hold Shortcuts is on, with the hold setting shown.
pub holds: Option<bool>,
/// The command a hold is being recorded for.
pub recording_hold: Option<CommandRef>,
}
impl DialogState {
@@ -149,6 +153,8 @@ impl DialogState {
}),
set: self.set.clone(),
can_undo: self.can_undo(),
holds: None,
recording_hold: None,
})
}
}
+38 -4
View File
@@ -4,7 +4,7 @@
use std::collections::BTreeSet;
use craft_keymap::editor::{self, DOUBLE_PRESS, EditSession, Recorded, Recorder};
use craft_keymap::import::{self, ForeignSet, ImportOptions, ImportPlan, ImportReport};
use craft_keymap::import::{self, ForeignSet, ImportOptions, ImportPlan, ImportReport, Start};
use craft_keymap::profiles::{Builtins, ProfileError, Profiles, set_name};
use craft_keymap::{
AssignError, Assigned, Binding, BindingError, Chord, CommandRef, Holder, Key, Keymap, MAX_BINDINGS, Overrides, ParseError, Policy, Scope, Trigger,
@@ -154,6 +154,12 @@ pub(crate) struct Review {
pub name: String,
/// After Import as New Set: the set's name and the report.
pub done: Option<(String, ImportReport)>,
/// Whether each entry of the set is imported.
#[allow(dead_code)] // P3(shortcuts-w4): kb.C12
pub included: Vec<bool>,
/// The search over label, path and key text.
#[allow(dead_code)] // P3(shortcuts-w4): kb.C12
pub search: String,
}
/// The set row's inline form: New Set… or Rename….
@@ -1074,7 +1080,7 @@ impl DialogState {
let name = plan.report.set.clone().unwrap_or_else(|| word!(env, imported));
self.stop_recording();
self.conflict = None;
self.review = Some(Review { set, options, plan, name, done: None });
self.review = Some(Review { set, options, plan, name, done: None, included: Vec::new(), search: String::new() });
}
/// Picks candidate `candidate` for suggestion `suggestion`, re-plans, and reports the answers
@@ -1084,9 +1090,37 @@ impl DialogState {
let Some(s) = r.plan.report.suggestions.get(suggestion) else { return };
let Some(command) = s.candidates.get(candidate).cloned() else { return };
let Some(entry) = r.set.entries.iter().find(|e| e.item() == s.item && e.line == s.line) else { return };
r.options.remembered.insert(entry.remember_key(), command);
r.options.remembered.insert(entry.remember_key(), Some(command)); // P3(shortcuts-w4): kb.C12
r.plan = import::plan(&r.set, env.keymap, &r.options);
self.outcome = Some(Outcome::Remembered(r.options.remembered.clone()));
self.outcome = Some(Outcome::Remembered { targets: r.options.remembered.clone(), codes: r.options.codes.clone() }); // P3(shortcuts-w4): kb.C29
}
/// Starts the review from `start` and re-plans.
#[allow(dead_code)] // P3(shortcuts-w4): kb.C12
pub(crate) fn set_start(&mut self, env: &Env, start: Start) {
let _ = (env, start);
todo!("kb.C12")
}
/// Imports entry `entry` or leaves it out, and re-plans.
#[allow(dead_code)] // P3(shortcuts-w4): kb.C12
pub(crate) fn include(&mut self, env: &Env, entry: usize, on: bool) {
let _ = (env, entry, on);
todo!("kb.C12")
}
/// Picks `command` for entry `entry` (`None` is No equivalent), re-plans and reports the answer.
#[allow(dead_code)] // P3(shortcuts-w4): kb.C12
pub(crate) fn pick_target(&mut self, env: &Env, entry: usize, command: Option<CommandRef>) {
let _ = (env, entry, command);
todo!("kb.C12")
}
/// Answers the undecided `code` (`None` is No equivalent), re-plans and reports the answer.
#[allow(dead_code)] // P3(shortcuts-w4): kb.C12
pub(crate) fn answer_code(&mut self, env: &Env, code: String, answer: Option<String>) {
let _ = (env, code, answer);
todo!("kb.C12")
}
/// Import as New Set (with sets), else applies the plan to the keymap as one undo step.
+2 -1
View File
@@ -21,7 +21,8 @@ const FIT_MARGIN: f64 = 24.0;
/// screen whatever the size of `view.rect`.
pub fn fitted_page(view: &mut CanvasView, pixels_per_point: f32) -> PlacedPage {
let size = Size::new(LETTER_WIDTH, LETTER_HEIGHT);
craft_behavior::canvas::zoom::fit(view, size, pixels_per_point, FIT_MARGIN);
// P3(canvas-w1): cv.F3
craft_behavior::canvas::zoom::fit(view, size, pixels_per_point, FIT_MARGIN, &craft_behavior::canvas::zoom::ZoomScheme::PHOTOSHOP);
let rect = Rect::from_min_max(view.to_screen(kurbo::Point::ZERO), view.to_screen(kurbo::Point::new(LETTER_WIDTH, LETTER_HEIGHT)));
PlacedPage::new(0, rect, view.zoom, (0.0, rect.height()))
}
+18 -1
View File
@@ -50,6 +50,11 @@ craft_ui::words! {
visibility: "pageList.visibility" = "Visibility {row}";
lock: "pageList.lock" = "Lock";
locking: "pageList.locking" = "Lock {row}";
move_up: "pageList.moveUp" = "Move Up";
move_down: "pageList.moveDown" = "Move Down";
rearrange: "pageList.rearrange" = "Rearrange All Artboards";
lock_row: "pageList.lockRow" = "Lock {row}";
unlock_row: "pageList.unlockRow" = "Unlock {row}";
}
}
@@ -125,6 +130,16 @@ pub enum PageListEvent {
/// eyes off, or on again when it is the only one on; `UndoShowOnly` puts the eyes back as they were. The lock
/// column ignores Alt. The app groups one sweep as one undo step.
Toggle(SweepStep<usize>),
/// A click on a row's lock.
#[non_exhaustive]
Lock {
/// The row whose lock was clicked.
row: usize,
/// Whether the row is locked after the click.
locked: bool,
},
/// The Rearrange button.
Rearrange,
/// New, Duplicate, or a row dropped on New (`duplicate`, the dragged rows' grabbed row); `options` with Alt held
/// (open the options for the new one first).
#[non_exhaustive]
@@ -153,6 +168,8 @@ pub struct PageListOutput {
pub response: Response,
/// What the user did this pass, in order.
pub events: Vec<PageListEvent>,
/// Key focus is in the list this pass (the table's response).
pub focused: bool,
}
impl Outcome for PageListOutput {
@@ -336,6 +353,6 @@ impl<'a> PageList<'a> {
}
shown.response
});
PageListOutput { response: response.output.response, events: events.into_inner() }
PageListOutput { response: response.output.response, events: events.into_inner(), focused: false }
}
}
+7
View File
@@ -42,6 +42,12 @@ pub enum HiddenMark {
ParagraphEnd,
/// #.
StoryEnd,
/// ˚ (centred on the space).
NarrowNoBreakSpace,
/// ˈ (centred on the space).
FixedSpace,
/// ¬ (the discretionary hyphen's mark).
DiscretionaryHyphen,
}
impl HiddenMark {
@@ -54,6 +60,7 @@ impl HiddenMark {
HiddenMark::NoBreakSpace => "°",
HiddenMark::ParagraphEnd => "",
HiddenMark::StoryEnd => "#",
HiddenMark::NarrowNoBreakSpace | HiddenMark::FixedSpace | HiddenMark::DiscretionaryHyphen => todo!("cv.F43"),
}
}
+8
View File
@@ -52,6 +52,14 @@ impl Printer {
}
}
impl From<crate::Printer> for Printer {
/// The dialog's printer for a discovered one: `name`, the `description` as the label, and `default`.
fn from(printer: crate::Printer) -> Self {
let _ = printer;
todo!("ex.E58")
}
}
/// The text the dialog shows for each of `printers`, in order: its label, or its name when it has
/// none. Text two printers would share is followed by the name in brackets, so neither hides the
/// other; when even that text is shared (another printer's label is `Office (Office_1)`), those
+16
View File
@@ -37,6 +37,18 @@ pub use row::GridRow;
pub(crate) use geometry::{digits_of, header_insets, row_digits};
pub(crate) use reference::edges;
/// Where a column's resize edge is drawn.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ColumnEdges {
/// Only on the column headers.
#[default]
Headers,
/// Also over the cell rows in view, with the header edge's drag, cursor and double press; a press beside the
/// band selects the cell.
Cells,
}
/// The rows of a sheet as the collection's source: one key per row, equal to its position.
struct SheetRows(Positions);
@@ -192,6 +204,9 @@ pub struct CellGrid<'a> {
/// The cell whose problem shows an error tag, with its fixes.
#[prop]
error_tag: Option<CellProblem<'a>>,
/// Where a column's resize edge is drawn.
#[prop]
column_edges: ColumnEdges,
outline: Option<(&'a OutlineAxis, &'a OutlineAxis)>,
selectable: Box<dyn Fn(CellAt<u32>) -> bool + 'a>,
frame: Option<paint::Frame>,
@@ -222,6 +237,7 @@ impl<'a> CellGrid<'a> {
copy_mark: &[],
filters: &[],
error_tag: None,
column_edges: ColumnEdges::default(),
outline: None,
selectable: Box::new(move |cell| model.selectable(cell)),
frame: None,
+2 -2
View File
@@ -46,8 +46,8 @@ pub use fields::{
pub use filter::{FilterButton, FilterButtonEvent, FilterButtonOutput, FilterButtonStyle, FilterButtonWords};
pub use grid::{
CellAdvance, CellAt, CellDirection, CellEdit, CellGrid, CellGridStyle, CellGridWords, CellProblem, CellRange, CellSelection, CellSpace,
ColumnFilter, GridEdit, GridLayout, GridMenuTarget, GridModel, GridOutput, GridRow, GridState, HEADER_MIN_ZOOM, LineIndex, Positions,
SHEET_COLUMNS, SHEET_ROWS, SHEET_ZOOM, SheetGeometry, SheetMetrics, absolute_range_reference, absolute_reference, column_letters,
ColumnEdges, ColumnFilter, GridEdit, GridLayout, GridMenuTarget, GridModel, GridOutput, GridRow, GridState, HEADER_MIN_ZOOM, LineIndex,
Positions, SHEET_COLUMNS, SHEET_ROWS, SHEET_ZOOM, SheetGeometry, SheetMetrics, absolute_range_reference, absolute_reference, column_letters,
};
pub use outline::{OutlineAction, OutlineAxis, OutlineBand, OutlineBandOutput, OutlineBandStyle, OutlineBandWords, OutlineGroup};
pub use refpick::ReferencePicker;
+235 -4
View File
@@ -10,12 +10,13 @@ use craft_font_manager::Catalog;
#[cfg(feature = "font-picker")]
use craft_font_manager::axes::AxisSliders;
#[cfg(feature = "font-picker")]
use craft_font_manager::picker::{FontFilters, FontPickerSettings};
use craft_font_manager::picker::{FamilySet, FilterLayout, FontFilters, FontPickerSettings, FontScript};
use std::ops::RangeInclusive;
#[cfg(feature = "font-picker")]
use std::sync::Arc;
use crate::ui::length::DocUnit;
use crate::ui::type_options::TextAntiAlias;
use craft_behavior::{ColumnWidth, EditEvent, IconId, Preview};
use craft_theme::{Rgba, Srgba};
use craft_ui::choice::Swatch;
@@ -36,7 +37,9 @@ pub(crate) mod rows;
mod stories;
mod style_options;
pub use paragraph::{ParagraphChange, ParagraphControls, ParagraphControlsOutput, ParagraphDirection, ParagraphValues, ParagraphWords, TextAlign};
pub use paragraph::{
DirectionRow, ParagraphChange, ParagraphControls, ParagraphControlsOutput, ParagraphDirection, ParagraphValues, ParagraphWords, TextAlign,
};
pub use paragraph_dialog::{
LineSpacing, ParagraphAlign, ParagraphAnswer, ParagraphDialog, ParagraphDialogWords, ParagraphFormat, ParagraphPreview, ParagraphPreviewStyle,
SpacingKind, SpecialIndent,
@@ -90,9 +93,108 @@ craft_ui::words! {
ordinals: "character.ordinals" = "Ordinals";
fractions: "character.fractions" = "Fractions";
language: "character.language" = "Language";
rotation: "character.rotation" = "Rotation";
anti_alias: "character.antiAlias" = "Anti-aliasing";
font_height: "character.fontHeight" = "Set Font Height Reference";
em_box: "character.emBox" = "Em Box";
cap_height: "character.capHeight" = "Cap Height";
x_height: "character.xHeight" = "x-Height";
icf_box: "character.icfBox" = "ICF Box";
aki_left: "character.akiLeft" = "Insert Aki Left";
aki_right: "character.akiRight" = "Insert Aki Right";
tsume: "character.tsume" = "Tsume";
diacritic_x: "character.diacriticX" = "Horizontal Diacritic Position";
diacritic_y: "character.diacriticY" = "Vertical Diacritic Position";
variable_font: "character.variableFont" = "Variable Font";
}
}
/// The document keys of the family, size, leading, kerning and tracking fields, which a host focuses with
/// `runtime::focus::request(ctx, FocusTarget::Doc(keys::SIZE))`.
pub mod keys {
use craft_behavior::DocKey;
/// The family field.
pub const FAMILY: DocKey = DocKey::new("craft-text.character.family");
/// The size field.
pub const SIZE: DocKey = DocKey::new("craft-text.character.size");
/// The leading field.
pub const LEADING: DocKey = DocKey::new("craft-text.character.leading");
/// The kerning field.
pub const KERNING: DocKey = DocKey::new("craft-text.character.kerning");
/// The tracking field.
pub const TRACKING: DocKey = DocKey::new("craft-text.character.tracking");
}
/// The groups of rows the Character controls show, as named sets the host turns on or off.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CharacterRows(u16);
impl CharacterRows {
/// The colour swatch beside the baseline shift.
pub const COLOR: CharacterRows = CharacterRows(1 << 0);
/// Faux Bold and Faux Italic.
pub const FAUX: CharacterRows = CharacterRows(1 << 1);
/// Vertical and horizontal scale and baseline shift.
pub const SCALES: CharacterRows = CharacterRows(1 << 2);
/// Rotation.
pub const ROTATION: CharacterRows = CharacterRows(1 << 3);
/// Anti-aliasing.
pub const ANTI_ALIAS: CharacterRows = CharacterRows(1 << 4);
/// Set Font Height Reference.
pub const FONT_HEIGHT: CharacterRows = CharacterRows(1 << 5);
/// Superscript and Subscript.
pub const SUPERSCRIPT: CharacterRows = CharacterRows(1 << 6);
/// The OpenType buttons.
pub const OPENTYPE: CharacterRows = CharacterRows(1 << 7);
/// Insert Aki Left and Right, Tsume.
pub const EAST_ASIAN: CharacterRows = CharacterRows(1 << 8);
/// Horizontal and vertical diacritic positions.
pub const MIDDLE_EASTERN: CharacterRows = CharacterRows(1 << 9);
/// The set `show` draws by default.
pub const PHOTOSHOP: CharacterRows = CharacterRows(Self::COLOR.0 | Self::FAUX.0 | Self::SCALES.0 | Self::OPENTYPE.0);
/// Whether every group in `rows` is on.
pub const fn contains(self, rows: CharacterRows) -> bool {
self.0 & rows.0 == rows.0
}
/// The set with every group in `rows` turned on or off.
#[must_use]
pub const fn with(self, rows: CharacterRows, on: bool) -> Self {
CharacterRows(if on { self.0 | rows.0 } else { self.0 & !rows.0 })
}
}
impl std::ops::BitOr for CharacterRows {
type Output = CharacterRows;
fn bitor(self, other: CharacterRows) -> CharacterRows {
CharacterRows(self.0 | other.0)
}
}
impl Default for CharacterRows {
fn default() -> Self {
CharacterRows::PHOTOSHOP
}
}
/// The Set Font Height Reference values.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FontHeightReference {
/// The em box.
#[default]
EmBox,
/// The cap height.
CapHeight,
/// The x-height.
XHeight,
/// The ideographic character face box.
IcfBox,
}
/// The font size menu's presets, in points (PhotoCraft's `SIZE_PRESETS`, Photoshop's list); the
/// leading menu uses them too.
pub const SIZE_PRESETS: [f32; 17] = [6.0, 8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 16.0, 18.0, 24.0, 30.0, 36.0, 48.0, 60.0, 72.0, 150.0, 300.0];
@@ -134,6 +236,26 @@ const SHIFT_RANGE: RangeInclusive<f64> = -1296.0..=1296.0;
const TRACKING_RANGE: RangeInclusive<f64> = -1000.0..=10000.0;
/// The range of the scale fields, percent.
const SCALE_RANGE: RangeInclusive<f64> = 0.0..=1000.0;
/// The rotation presets, degrees.
pub const ROTATION_PRESETS: [f32; 9] = [-180.0, -135.0, -90.0, -45.0, 0.0, 45.0, 90.0, 135.0, 180.0];
/// The Insert Aki Left and Right presets, thousandths of an em.
pub const AKI_PRESETS: [f32; 4] = [0.0, 250.0, 500.0, 1000.0];
/// The Tsume presets, percent.
pub const TSUME_PRESETS: [f32; 5] = [0.0, 25.0, 50.0, 75.0, 100.0];
/// The diacritic position presets, thousandths of an em.
pub const DIACRITIC_PRESETS: [f32; 7] = [-200.0, -100.0, -50.0, 0.0, 50.0, 100.0, 200.0];
/// The range of the rotation field, degrees.
#[allow(dead_code)] // P3(type-w3): ty.X34
const ROTATION_RANGE: RangeInclusive<f64> = -360.0..=360.0;
/// The range of the Insert Aki fields, thousandths of an em.
#[allow(dead_code)] // P3(type-w3): ty.X34
const AKI_RANGE: RangeInclusive<f64> = 0.0..=1000.0;
/// The range of the Tsume field, percent.
#[allow(dead_code)] // P3(type-w3): ty.X34
const TSUME_RANGE: RangeInclusive<f64> = 0.0..=100.0;
/// The range of the diacritic position fields, thousandths of an em.
#[allow(dead_code)] // P3(type-w3): ty.X34
const DIACRITIC_RANGE: RangeInclusive<f64> = -1000.0..=1000.0;
/// Two columns of the same share, for the rows of two fields.
const TWO_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)];
@@ -172,6 +294,18 @@ impl<'a> FaceAxes<'a> {
}
}
/// How the axes show: the sliders under the style row, or one button that opens them.
#[cfg(feature = "font-picker")]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum AxesLayout {
/// The sliders under the style row.
#[default]
Sliders,
/// `AxesButton` under the style row.
Button,
}
/// What the family field's font picker takes: the catalog, the app's stars, recents and filters, and the preview.
#[cfg(feature = "font-picker")]
#[non_exhaustive]
@@ -186,13 +320,28 @@ pub struct FontPickerSource<'a> {
pub preview_text: Option<&'a str>,
/// The families the app serves.
pub served: &'a [String],
/// The host's family sets.
pub sets: &'a [FamilySet<'a>],
/// The scripts the script row offers.
pub scripts: &'a [FontScript],
/// The layout of the list's filter area.
pub filter_layout: FilterLayout,
}
#[cfg(feature = "font-picker")]
impl<'a> FontPickerSource<'a> {
/// A source over `catalog` with the app's `settings` and `filters`.
pub fn new(catalog: &'a Arc<Catalog>, settings: Bind<'a, FontPickerSettings>, filters: Bind<'a, FontFilters>) -> Self {
FontPickerSource { catalog, settings, filters, preview_text: None, served: &[] }
FontPickerSource {
catalog,
settings,
filters,
preview_text: None,
served: &[],
sets: &[],
scripts: &[],
filter_layout: FilterLayout::default(),
}
}
/// The text the previews show.
@@ -206,6 +355,24 @@ impl<'a> FontPickerSource<'a> {
self.served = served;
self
}
/// The host's family sets, passed on to the family field's picker.
pub fn sets(self, sets: &'a [FamilySet<'a>]) -> Self {
let _ = sets;
todo!("ty.X31")
}
/// The scripts the picker's script row offers.
pub fn scripts(self, scripts: &'a [FontScript]) -> Self {
let _ = scripts;
todo!("ty.X31")
}
/// The layout of the picker's filter area.
pub fn filter_layout(self, layout: FilterLayout) -> Self {
let _ = layout;
todo!("ty.X31")
}
}
/// Leading: automatic (the font size × the paragraph's auto-leading, 120 % by default) or set.
@@ -340,6 +507,25 @@ pub struct CharacterValues {
pub language: Option<String>,
/// The variable-font axis values of the selection, by axis tag; `None` while the selection mixes them or has none.
pub axes: Option<Vec<([u8; 4], f32)>>,
/// Rotation in degrees.
pub rotation: Option<f32>,
/// Insert Aki Left, thousandths of an em.
pub aki_left: Option<f32>,
/// Insert Aki Right, thousandths of an em.
pub aki_right: Option<f32>,
/// Tsume, percent.
pub tsume: Option<f32>,
/// Horizontal diacritic position, thousandths of an em.
pub diacritic_x: Option<f32>,
/// Vertical diacritic position, thousandths of an em.
pub diacritic_y: Option<f32>,
/// The pair kerning Metrics or Optical gives at the caret; while the kerning is one of them the field shows it in
/// parentheses, and typing a number sets `Manual`.
pub auto_kerning: Option<f32>,
/// The anti-aliasing method.
pub anti_alias: Option<TextAntiAlias>,
/// The Set Font Height Reference value.
pub font_height: Option<FontHeightReference>,
}
impl CharacterValues {
@@ -366,6 +552,15 @@ impl CharacterValues {
opentype: self.opentype.iter().copied().filter(|tag| other.opentype.contains(tag)).collect(),
language: agree(&self.language, &other.language),
axes: agree(&self.axes, &other.axes),
rotation: agree(&self.rotation, &other.rotation),
aki_left: agree(&self.aki_left, &other.aki_left),
aki_right: agree(&self.aki_right, &other.aki_right),
tsume: agree(&self.tsume, &other.tsume),
diacritic_x: agree(&self.diacritic_x, &other.diacritic_x),
diacritic_y: agree(&self.diacritic_y, &other.diacritic_y),
auto_kerning: agree(&self.auto_kerning, &other.auto_kerning),
anti_alias: agree(&self.anti_alias, &other.anti_alias),
font_height: agree(&self.font_height, &other.font_height),
}
}
}
@@ -416,6 +611,22 @@ pub enum CharacterChange {
Language(String),
/// The variable-font axis values, by axis tag.
Axes(Vec<([u8; 4], f32)>),
/// Rotation in degrees.
Rotation(f32),
/// Anti-aliasing.
AntiAlias(TextAntiAlias),
/// Set Font Height Reference.
FontHeight(FontHeightReference),
/// Insert Aki Left, thousandths of an em.
AkiLeft(f32),
/// Insert Aki Right, thousandths of an em.
AkiRight(f32),
/// Tsume, percent.
Tsume(f32),
/// Horizontal diacritic position, thousandths of an em.
DiacriticX(f32),
/// Vertical diacritic position, thousandths of an em.
DiacriticY(f32),
}
/// What the Character controls did this pass.
@@ -436,6 +647,9 @@ pub struct CharacterControlsOutput {
/// The colour swatch was clicked: the app opens its colour picker for this request (key [`COLOR_KEY`]) and sets
/// the colour. Set for the one pass of the click.
pub requests: HostRequests,
/// The family `FontPicker`'s id this pass, which `FrameOutput::ended_previews` names when the controls stop
/// showing with a preview.
pub picker: Option<egui::Id>,
}
impl Outcome for CharacterControlsOutput {
@@ -493,6 +707,16 @@ pub struct CharacterControls<'a> {
#[cfg(feature = "font-picker")]
#[prop]
axes: Option<FaceAxes<'a>>,
/// How `axes` shows: the sliders under the style row, or `AxesButton` under it.
#[cfg(feature = "font-picker")]
#[prop]
axes_layout: AxesLayout,
/// The row groups shown.
#[prop]
rows: CharacterRows,
/// The methods the Anti-aliasing select offers (with `CharacterRows::ANTI_ALIAS`).
#[prop]
anti_alias_methods: &'a [TextAntiAlias],
}
impl<'a> CharacterControls<'a> {
@@ -510,6 +734,10 @@ impl<'a> CharacterControls<'a> {
picker: None,
#[cfg(feature = "font-picker")]
axes: None,
#[cfg(feature = "font-picker")]
axes_layout: AxesLayout::default(),
rows: CharacterRows::default(),
anti_alias_methods: &TextAntiAlias::BAR,
}
}
@@ -518,6 +746,9 @@ impl<'a> CharacterControls<'a> {
let values = self.values;
let (families, styles, languages) = (self.families, self.styles, self.languages);
let (unit, superscript) = (self.unit, self.superscript);
let _ = (self.rows, self.anti_alias_methods); // P3(type-w3): ty.X23, ty.X27
#[cfg(feature = "font-picker")]
let _ = (self.axes_layout,); // P3(type-w3): ty.X26
#[cfg(feature = "font-picker")]
let mut picker = self.picker;
#[cfg(feature = "font-picker")]
@@ -708,7 +939,7 @@ impl<'a> CharacterControls<'a> {
edits.extend(select_row(ui, &words.language, hidden_side(), mixed(values.language.clone()), entries, CharacterChange::Language));
}
});
CharacterControlsOutput { response: shown.output, edits, preview_family, rested_family, requests }
CharacterControlsOutput { response: shown.output, edits, preview_family, rested_family, requests, picker: None }
}
}
+33 -1
View File
@@ -43,6 +43,19 @@ craft_ui::words! {
}
}
/// Which direction toggles the Paragraph controls show.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DirectionRow {
/// Automatic, Left to Right and Right to Left.
#[default]
Automatic,
/// Left to Right and Right to Left only.
Explicit,
/// No direction row.
Hidden,
}
/// The range of the indent fields, points.
pub(super) const INDENT_RANGE: RangeInclusive<f64> = -1296.0..=1296.0;
/// The range of the space fields, points.
@@ -191,16 +204,35 @@ pub struct ParagraphControls<'a> {
/// Shows the Hyphenate check box. Default true.
#[prop]
hyphenate: bool,
/// Which direction toggles the direction row shows.
#[prop]
direction_row: DirectionRow,
}
impl<'a> ParagraphControls<'a> {
/// Controls named `label` for the paragraph attributes `values`.
pub fn new(label: impl Into<Label>, values: &'a ParagraphValues) -> Self {
ParagraphControls { label: label.into(), values, unit: DocUnit::points(), point_text: false, vertical: false, hyphenate: true }
ParagraphControls {
label: label.into(),
values,
unit: DocUnit::points(),
point_text: false,
vertical: false,
hyphenate: true,
direction_row: DirectionRow::default(),
}
}
/// Draws the host's rows after the alignment and direction rows, before the indents, and returns the changes the
/// user made.
pub fn show_with(self, ui: &mut Ui, between: impl FnOnce(&mut Ui)) -> ParagraphControlsOutput {
let _ = (self, ui, between);
todo!("ty.X38")
}
/// Shows the controls and returns the changes the user made.
pub fn show(self, ui: &mut Ui) -> ParagraphControlsOutput {
let _ = (self.direction_row,); // P3(type-w3): ty.X37
let values = self.values;
let point_text = self.point_text;
let vertical = self.vertical;
+2 -1
View File
@@ -10,7 +10,7 @@ mod bar;
mod dialog;
pub use bar::{FindBar, FindBarOutput, FindBarState, FindStep};
pub use dialog::{FindReplaceDialog, FindRequest, FindTab};
pub use dialog::{FindCheck, FindReplaceDialog, FindRequest, FindTab, ReplaceButtons};
use crate::find::{FindError, MAX_COUNT, MAX_PATTERN, RegexError, WildcardError};
@@ -44,6 +44,7 @@ craft_ui::words! {
special: "find.special" = "Special";
find_next: "find.findNext" = "Find Next";
replace: "find.replace" = "Replace";
replace_find: "find.replaceFind" = "Replace & Find";
replace_more: "find.replaceMore" = "Replace…";
replace_all: "find.replaceAll" = "Replace All";
replaced: template "find.replaced" = "All done. We made {n} replacements.";
+100 -4
View File
@@ -14,7 +14,8 @@ use craft_ui::runtime::env::{Env, Label};
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::tabs::{Tab, TabKind, TabStrip};
use craft_ui::text::TextField;
use egui::Ui;
use egui::{Context, Ui};
use serde_json::Value;
use super::FindLabels;
use crate::find::FindOptions;
@@ -32,6 +33,37 @@ pub enum FindTab {
GoTo,
}
/// A check box the host adds to the search options (Search Backwards, Check Hidden Layers).
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct FindCheck {
/// The key the host reads the check's value by.
pub key: String,
/// The check box's label.
pub label: Label,
/// Whether the check is on.
pub on: bool,
}
impl FindCheck {
/// A check box `key` named `label`, `on` or off.
pub fn new(key: impl Into<String>, label: impl Into<Label>, on: bool) -> Self {
let _ = (key.into(), label.into(), on);
todo!("ty.X84")
}
}
/// How the Replace tab arranges its buttons.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ReplaceButtons {
/// One Replace that replaces and finds the next.
#[default]
Combined,
/// Replace (replaces only) and Replace & Find.
Separate,
}
/// A request the dialog makes while open; the app runs it and reports back with [`FindReplaceDialog::set_message`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
@@ -44,7 +76,7 @@ pub enum FindRequest {
/// How the Find what text is read.
options: FindOptions,
},
/// Replace the current match, then find the next.
/// Replace the current match, then find the next when `find_next`.
#[non_exhaustive]
Replace {
/// The Find what text.
@@ -53,6 +85,8 @@ pub enum FindRequest {
with: String,
/// How the Find what text is read.
options: FindOptions,
/// `true`: replace the current match, then find the next; `false`: replace only.
find_next: bool,
},
/// Replace every match.
#[non_exhaustive]
@@ -92,7 +126,14 @@ impl FindRequest {
/// Replace the current match of `query` with `with`.
pub fn replace(query: impl Into<String>, with: impl Into<String>, options: FindOptions) -> Self {
FindRequest::Replace { query: query.into(), with: with.into(), options }
// P3(type-w5): ty.X91
FindRequest::Replace { query: query.into(), with: with.into(), options, find_next: true }
}
/// Replace the current match of `query` with `with` and stop there.
pub fn replace_only(query: impl Into<String>, with: impl Into<String>, options: FindOptions) -> Self {
let _ = (query.into(), with.into(), options);
todo!("ty.X93")
}
/// Replace every match of `query` with `with`.
@@ -155,6 +196,15 @@ pub struct FindReplaceDialog {
insert: Option<(Field, String)>,
go_to_kind: usize,
go_to_target: String,
/// The host's check boxes, drawn after the layout's own options.
#[allow(dead_code)] // P3(type-w5): ty.X85
checks: Vec<FindCheck>,
/// The arrangement of the Replace buttons.
#[allow(dead_code)] // P3(type-w5): ty.X88
replace_buttons: ReplaceButtons,
/// Whether a match is current; the Replace buttons are enabled only while it is.
#[allow(dead_code)] // P3(type-w5): ty.X90
matched: bool,
}
impl FindReplaceDialog {
@@ -174,6 +224,9 @@ impl FindReplaceDialog {
insert: None,
go_to_kind: 0,
go_to_target: String::new(),
checks: Vec::new(),
replace_buttons: ReplaceButtons::default(),
matched: true,
}
}
@@ -199,6 +252,39 @@ impl FindReplaceDialog {
self
}
/// The host's check boxes, drawn after the layout's own options, in order, in both layouts.
#[must_use]
pub fn checks(self, checks: Vec<FindCheck>) -> Self {
let _ = checks;
todo!("ty.X85")
}
/// The current value of the host check `key`.
pub fn checked(&self, key: &str) -> Option<bool> {
let _ = key;
todo!("ty.X86")
}
/// The arrangement of the Replace buttons on the Replace tab, both layouts.
#[must_use]
pub fn replace_buttons(self, buttons: ReplaceButtons) -> Self {
let _ = buttons;
todo!("ty.X88")
}
/// Opens with `with` in Replace with (the host's last search).
#[must_use]
pub fn replace_with(self, with: impl Into<String>) -> Self {
let _ = with.into();
todo!("ty.X89")
}
/// Whether a match is current; the Replace buttons are enabled only while it is. Starts `true`.
pub fn set_matched(&mut self, matched: bool) {
let _ = matched;
todo!("ty.X90")
}
/// The request the user made since the last call, if any.
pub fn take_request(&mut self) -> Option<FindRequest> {
self.request.take()
@@ -372,13 +458,23 @@ impl StackDialog for FindReplaceDialog {
match which {
Press::ShowReplace => self.tab = FindTab::Replace,
Press::Highlight(on) => self.request = Some(FindRequest::Highlight { query, options, on: *on }),
Press::Replace if !query.is_empty() => self.request = Some(FindRequest::Replace { query, with, options }),
// P3(type-w5): ty.X91
Press::Replace if !query.is_empty() => self.request = Some(FindRequest::Replace { query, with, options, find_next: true }),
Press::ReplaceAll if !query.is_empty() => self.request = Some(FindRequest::ReplaceAll { query, with, options }),
Press::Replace | Press::ReplaceAll => {}
}
}
(picked == Some(close_at) || shown.output.closed.is_some()).then_some(DialogResult::Ok(()))
}
fn json_fields(&self) -> Option<Value> {
todo!("ty.X95")
}
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("ty.X95")
}
}
/// The Special menu: the `^` codes of Find what, or of Replace with.
+34 -14
View File
@@ -32,7 +32,8 @@ mod run;
mod stories;
use geometry::{Geometry, Shapes};
use items::{COLUMN, Item, SELECTOR, STRIP};
pub use items::RulerItem;
use items::{COLUMN, SELECTOR, STRIP};
craft_ui::words! {
/// The ruler's AccessKit names and readout (Word's).
@@ -206,13 +207,23 @@ pub struct ColumnDrag {
pub border: ColumnBorder,
}
/// The dragged item and its position from the paragraph's start edge, in points.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct RulerDrag {
/// The dragged item.
pub item: RulerItem,
/// Its position from the paragraph's start edge, in points.
pub position: f32,
}
/// What the ruler did this pass.
#[non_exhaustive]
pub struct TextRulerOutput {
/// A placed, moved or cleared stop or a moved indent marker, as the whole new values.
pub edit: EditResponse<RulerValues>,
/// The stop the user clicked (the Tabs panel's position field edits it).
pub picked: Option<usize>,
/// The stop or marker the user pressed (the Tabs panel's position field edits it).
pub picked: Option<RulerItem>,
/// A double-click on a stop (Word opens the Tabs dialog).
pub open_tabs_dialog: bool,
/// A table column border dragged ([`TextRuler::columns`]).
@@ -237,7 +248,7 @@ impl Outcome for TextRulerOutput {
/// What the ruler reports besides the edit.
#[derive(Clone, Debug, Default)]
pub(super) struct Report {
pub(super) picked: Option<usize>,
pub(super) picked: Option<RulerItem>,
pub(super) open_tabs_dialog: bool,
pub(super) column: Option<ColumnDrag>,
pub(super) kind: Option<TabAlign>,
@@ -345,6 +356,15 @@ pub struct TextRuler<'a> {
report: Report,
}
impl TextRuler<'_> {
/// The running drag of the ruler whose id is `ruler`, read outside its pass; `None` while no drag runs and while
/// the dragged stop is off the ruler.
pub fn dragging(ctx: &egui::Context, ruler: egui::Id) -> Option<RulerDrag> {
let _ = (ctx, ruler);
todo!("ty.X59")
}
}
impl<'a> TextRuler<'a> {
/// The ruler named `label` over `value`, for a column `width` points wide.
pub fn new(label: impl Into<craft_ui::runtime::env::Label>, value: Bind<'a, RulerValues>, width: f32) -> Self {
@@ -396,13 +416,13 @@ impl<'a> TextRuler<'a> {
}
}
fn item_name<'w>(words: &'w TextRulerWords, item: Item, values: &RulerValues) -> &'w str {
fn item_name<'w>(words: &'w TextRulerWords, item: RulerItem, values: &RulerValues) -> &'w str {
match item {
Item::FirstLine => words.first_line_indent.as_str(),
Item::Hanging => words.hanging_indent.as_str(),
Item::LeftBox => words.left_indent.as_str(),
Item::Right => words.right_indent.as_str(),
Item::Stop(at) => Self::tab_name(words, values.stops.get(at).map(|stop| stop.align).unwrap_or_default()),
RulerItem::FirstLine => words.first_line_indent.as_str(),
RulerItem::Hanging => words.hanging_indent.as_str(),
RulerItem::LeftBox => words.left_indent.as_str(),
RulerItem::Right => words.right_indent.as_str(),
RulerItem::Stop(at) => Self::tab_name(words, values.stops.get(at).map(|stop| stop.align).unwrap_or_default()),
}
}
}
@@ -469,7 +489,7 @@ impl Component for TextRuler<'_> {
let values = cx.value().cloned().unwrap_or_default();
let handle = HitPriority::new(HitLevel::Handle, 0);
cx.part(STRIP, layout.g.strip).sense(Sense::CLICK | Sense::DRAG).pointer_only("the Tabs dialog sets a stop by number");
for item in Item::all(&values) {
for item in RulerItem::all(&values) {
let part = cx
.part(item.part(), layout.shapes.rect(&layout.g, item, &values))
.sense(Sense::DRAG | Sense::CLICK)
@@ -479,7 +499,7 @@ impl Component for TextRuler<'_> {
.nudges()
.focus_shape(FocusShape::Rect)
.value_part();
if matches!(item, Item::Stop(at) if self.selected == Some(at)) {
if matches!(item, RulerItem::Stop(at) if self.selected == Some(at)) {
part.selected().flags(Flags::SELECTED);
}
}
@@ -514,12 +534,12 @@ impl Component for TextRuler<'_> {
let text = run::ruler_text(self.unit, &numbers);
let step = f64::from(run::snap_step(&text, self.unit));
let range = 0.0..=f64::from(self.width);
for item in Item::all(&values) {
for item in RulerItem::all(&values) {
let at = f64::from(item.position(&values, self.width));
let shown = text.format_value(&numbers, at, 0.0);
let node = access.node(item.part(), Role::SLIDER);
let kind = Self::item_name(&words, item, &values);
node.name = Name::Text(if matches!(item, Item::Stop(_)) {
node.name = Name::Text(if matches!(item, RulerItem::Stop(_)) {
words.stop.fill(&[("kind", kind), ("position", shown.as_str())])
} else {
kind.to_owned()
+7 -7
View File
@@ -2,7 +2,7 @@
use super::RulerValues;
use super::TabAlign;
use super::items::Item;
use super::items::RulerItem;
use egui::{Rect, pos2, vec2};
/// Where the column sits on the strip: positions are points from the column's start edge, which
@@ -97,14 +97,14 @@ impl Shapes {
}
/// The box the item occupies on the strip.
pub(super) fn rect(&self, g: &Geometry, item: Item, values: &RulerValues) -> Rect {
pub(super) fn rect(&self, g: &Geometry, item: RulerItem, values: &RulerValues) -> Rect {
let x = g.x(item.position(values, g.width));
match item {
Item::FirstLine => self.first_line(g.strip, x),
Item::Hanging => self.hanging(g.strip, x),
Item::LeftBox => self.left_box(g.strip, x),
Item::Right => self.right(g.strip, x),
Item::Stop(_) => self.stop(g.strip, x),
RulerItem::FirstLine => self.first_line(g.strip, x),
RulerItem::Hanging => self.hanging(g.strip, x),
RulerItem::LeftBox => self.left_box(g.strip, x),
RulerItem::Right => self.right(g.strip, x),
RulerItem::Stop(_) => self.stop(g.strip, x),
}
}
}
+31 -28
View File
@@ -22,44 +22,47 @@ pub(super) const SELECTOR: PartKey = PartKey::new("selector");
pub(super) const STRIP: PartKey = PartKey::new("strip");
/// A marker or stop on the ruler.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Item {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RulerItem {
/// The first-line indent marker.
FirstLine,
/// The triangle under the first-line one: moves the left indent, the first line stays.
Hanging,
/// The box under the hanging triangle: moves first line and left indent together.
LeftBox,
/// The right indent marker.
Right,
/// The stop at this index of [`RulerValues::stops`].
Stop(usize),
}
impl Item {
impl RulerItem {
/// Every item in the order Page Down visits them: the markers, then the stops.
pub(super) fn all(values: &RulerValues) -> Vec<Item> {
let markers = [Item::FirstLine, Item::Hanging, Item::LeftBox, Item::Right];
markers.into_iter().chain((0..values.stops.len()).map(Item::Stop)).collect()
pub(super) fn all(values: &RulerValues) -> Vec<RulerItem> {
let markers = [RulerItem::FirstLine, RulerItem::Hanging, RulerItem::LeftBox, RulerItem::Right];
markers.into_iter().chain((0..values.stops.len()).map(RulerItem::Stop)).collect()
}
/// The part of the item.
pub(super) fn part(self) -> PartRef {
match self {
Item::FirstLine => FIRST.into(),
Item::Hanging => HANGING.into(),
Item::LeftBox => LEFT.into(),
Item::Right => RIGHT.into(),
Item::Stop(at) => STOP.at(at as u64),
RulerItem::FirstLine => FIRST.into(),
RulerItem::Hanging => HANGING.into(),
RulerItem::LeftBox => LEFT.into(),
RulerItem::Right => RIGHT.into(),
RulerItem::Stop(at) => STOP.at(at as u64),
}
}
/// The item a part belongs to.
pub(super) fn of_part(part: PartRef) -> Option<Item> {
pub(super) fn of_part(part: PartRef) -> Option<RulerItem> {
match part.key {
key if key == FIRST => Some(Item::FirstLine),
key if key == HANGING => Some(Item::Hanging),
key if key == LEFT => Some(Item::LeftBox),
key if key == RIGHT => Some(Item::Right),
key if key == STOP => part.index.map(|at| Item::Stop(at as usize)),
key if key == FIRST => Some(RulerItem::FirstLine),
key if key == HANGING => Some(RulerItem::Hanging),
key if key == LEFT => Some(RulerItem::LeftBox),
key if key == RIGHT => Some(RulerItem::Right),
key if key == STOP => part.index.map(|at| RulerItem::Stop(at as usize)),
_ => None,
}
}
@@ -67,10 +70,10 @@ impl Item {
/// Where the item sits, points from the column's start edge.
pub(super) fn position(self, values: &RulerValues, width: f32) -> f32 {
match self {
Item::FirstLine => values.left_indent + values.first_line_indent,
Item::Hanging | Item::LeftBox => values.left_indent,
Item::Right => width - values.right_indent,
Item::Stop(at) => values.stops.get(at).map_or(0.0, |stop| stop.position),
RulerItem::FirstLine => values.left_indent + values.first_line_indent,
RulerItem::Hanging | RulerItem::LeftBox => values.left_indent,
RulerItem::Right => width - values.right_indent,
RulerItem::Stop(at) => values.stops.get(at).map_or(0.0, |stop| stop.position),
}
}
}
@@ -97,24 +100,24 @@ pub(super) fn without(values: &RulerValues, at: usize) -> RulerValues {
/// `values` with `item` moved to `to` points (kept within the column), and where the item is
/// afterwards (a stop moved past another has a new index).
pub(super) fn moved(values: &RulerValues, item: Item, to: f32, width: f32) -> (RulerValues, Item) {
pub(super) fn moved(values: &RulerValues, item: RulerItem, to: f32, width: f32) -> (RulerValues, RulerItem) {
if !to.is_finite() {
return (values.clone(), item);
}
let to = to.clamp(0.0, width.max(0.0));
let mut next = values.clone();
match item {
Item::FirstLine => next.first_line_indent = to - values.left_indent,
Item::LeftBox => next.left_indent = to,
Item::Hanging => {
RulerItem::FirstLine => next.first_line_indent = to - values.left_indent,
RulerItem::LeftBox => next.left_indent = to,
RulerItem::Hanging => {
next.left_indent = to;
next.first_line_indent = values.left_indent + values.first_line_indent - to;
}
Item::Right => next.right_indent = (width - to).clamp(0.0, (width - values.left_indent).max(0.0)),
Item::Stop(at) => {
RulerItem::Right => next.right_indent = (width - to).clamp(0.0, (width - values.left_indent).max(0.0)),
RulerItem::Stop(at) => {
let Some(stop) = values.stops.get(at).copied() else { return (next, item) };
let (placed, now) = place(&without(values, at), TabStop { position: to, ..stop });
return (placed, Item::Stop(now));
return (placed, RulerItem::Stop(now));
}
}
(next, item)
+12 -12
View File
@@ -1,7 +1,7 @@
//! The ruler's drawing.
use super::geometry::glyph;
use super::items::Item;
use super::items::RulerItem;
use super::run::{Held, rule, ruler_text};
use super::{TextRuler, TextRulerStyle};
use craft_ui::canvas::{RulerTick, Rulers};
@@ -23,7 +23,7 @@ impl TextRuler<'_> {
draw.fill(&rect(g.strip), style.margin);
draw.fill(&rect(g.column()), style.fill);
let items = Item::all(&values);
let items = RulerItem::all(&values);
let column_boxes: Vec<Rect> = self.columns.iter().map(|at| shapes.column_marker(g.strip, g.x(*at))).collect();
let keep_clear: Vec<Rect> = items.iter().map(|item| shapes.rect(&g, *item, &values)).chain(column_boxes.iter().copied()).collect();
self.paint_ticks(ui, cx, &keep_clear);
@@ -31,8 +31,8 @@ impl TextRuler<'_> {
let draw = ui.draw();
let base = g.strip.max.y;
for (at, stop) in values.stops.iter().enumerate() {
let off = held.off && held.now == Some(Item::Stop(at));
let line = if off { style.marker_off } else { cx.resolve_part(Item::Stop(at).part(), &style.marker) };
let off = held.off && held.now == Some(RulerItem::Stop(at));
let line = if off { style.marker_off } else { cx.resolve_part(RulerItem::Stop(at).part(), &style.marker) };
let (segments, dot) = glyph(&shapes, g.x(stop.position), base, stop.align, g.right_to_left);
for [a, b] in segments {
draw.stroke(&path(a, b), StrokeWidth::Thin, line);
@@ -63,23 +63,23 @@ impl TextRuler<'_> {
draw.text(boxed, &run);
}
}
let x = |item: Item| g.x(item.position(&values, g.width));
let line = |item: Item| cx.resolve_part(item.part(), &style.marker);
let triangle = |a: Pos2, b: Pos2, c: Pos2, item: Item| {
let x = |item: RulerItem| g.x(item.position(&values, g.width));
let line = |item: RulerItem| cx.resolve_part(item.part(), &style.marker);
let triangle = |a: Pos2, b: Pos2, c: Pos2, item: RulerItem| {
let shape = PaintShape::Polygon(vec![a, b, c]);
draw.fill(&shape, style.marker_fill);
draw.stroke(&shape, StrokeWidth::Thin, line(item));
};
let (first, left, right) = (x(Item::FirstLine), x(Item::LeftBox), x(Item::Right));
let (first, left, right) = (x(RulerItem::FirstLine), x(RulerItem::LeftBox), x(RulerItem::Right));
let top = shapes.first_line(g.strip, first);
triangle(top.left_top(), top.right_top(), pos2(first, top.max.y), Item::FirstLine);
triangle(top.left_top(), top.right_top(), pos2(first, top.max.y), RulerItem::FirstLine);
let hanging = shapes.hanging(g.strip, left);
triangle(hanging.left_bottom(), hanging.right_bottom(), pos2(left, hanging.min.y), Item::Hanging);
triangle(hanging.left_bottom(), hanging.right_bottom(), pos2(left, hanging.min.y), RulerItem::Hanging);
let boxed = rect(shapes.left_box(g.strip, left));
draw.fill(&boxed, style.marker_fill);
draw.stroke(&boxed, StrokeWidth::Thin, line(Item::LeftBox));
draw.stroke(&boxed, StrokeWidth::Thin, line(RulerItem::LeftBox));
let end = shapes.right(g.strip, right);
triangle(end.left_bottom(), end.right_bottom(), pos2(right, end.min.y), Item::Right);
triangle(end.left_bottom(), end.right_bottom(), pos2(right, end.min.y), RulerItem::Right);
if let Some(kind) = self.kind {
let corner = layout.corner;
+19 -17
View File
@@ -1,7 +1,7 @@
//! One pass of the ruler's input: the gestures on the items, the strip and the column borders, keys and the
//! screen reader's requests.
use super::items::{COLUMN, Item, STRIP, moved, place, without};
use super::items::{COLUMN, RulerItem, STRIP, moved, place, without};
use super::{ColumnBorder, ColumnDrag, RulerValues, SAME_POSITION, TabLeader, TabStop, TextRuler, dropped_off, snap_stop};
use crate::ui::length::{DocUnit, shown};
use craft_behavior::{CancelReason, GesturePhase, Granularity, Intent, NavMove, PointerButton, PressPhase, RulerUnits, Ticks};
@@ -19,11 +19,11 @@ pub(super) struct Held {
/// The values when the gesture began.
anchor: Option<RulerValues>,
/// The item grabbed (a stop by its index when the gesture began).
from: Option<Item>,
from: Option<RulerItem>,
/// A new stop is being placed, not an existing one moved.
placing: bool,
/// Where the item is now (a stop's index follows it through the sorted stops).
pub(super) now: Option<Item>,
pub(super) now: Option<RulerItem>,
/// The pointer is far enough off the ruler to clear the stop on release.
pub(super) off: bool,
/// The borders of the table when a column border drag began.
@@ -110,7 +110,7 @@ impl TextRuler<'_> {
held.anchor = None;
}
for item in Item::all(&values) {
for item in RulerItem::all(&values) {
self.run_item(cx, &layout.g, step, &mut held, &text, item);
}
self.run_strip(cx, &layout.g, step, &mut held, &text, &values);
@@ -127,14 +127,15 @@ impl TextRuler<'_> {
}
/// The pointer on one marker or stop.
fn run_item(&mut self, cx: &mut Cx<'_, Self>, g: &super::Geometry, step: f32, held: &mut Held, text: &RulerText, item: Item) {
fn run_item(&mut self, cx: &mut Cx<'_, Self>, g: &super::Geometry, step: f32, held: &mut Held, text: &RulerText, item: RulerItem) {
let part = item.part();
// A stop set in this pass has no part until the next one.
let Some(press) = cx.part_if_declared(part).map(|declared| declared.press) else { return };
match press.phase {
PressPhase::Down { start, .. } if start.button == PointerButton::Primary => {
if let Item::Stop(at) = item {
self.report.picked = Some(at);
if let RulerItem::Stop(at) = item {
// P3(type-w5): ty.X57
self.report.picked = Some(RulerItem::Stop(at));
if start.clicks >= 2 {
self.report.open_tabs_dialog = true;
}
@@ -157,7 +158,7 @@ impl TextRuler<'_> {
PressPhase::Release { start, click: false, pos, .. } if start.button == PointerButton::Primary && held.from == Some(item) => {
self.drag_item(cx, g, step, held, text, start.origin, pos, press.mods.alt);
if held.off
&& let (Some(anchor), Some(Item::Stop(grab))) = (held.anchor.clone(), held.from)
&& let (Some(anchor), Some(RulerItem::Stop(grab))) = (held.anchor.clone(), held.from)
{
cx.propose(without(&anchor, grab));
}
@@ -192,7 +193,7 @@ impl TextRuler<'_> {
let start = from.position(&anchor, g.width);
let target = snap_stop(start + (pos.x - origin.x) / g.scale * g.sign(), step, g.width, free);
let (value, now) = moved(&anchor, from, target, g.width);
held.off = matches!(from, Item::Stop(_)) && dropped_off(pos.y, g.strip);
held.off = matches!(from, RulerItem::Stop(_)) && dropped_off(pos.y, g.strip);
if !held.off {
held.now = Some(now);
cx.propose(value.clone());
@@ -201,7 +202,7 @@ impl TextRuler<'_> {
}
/// The position of the dragged item at the pointer.
fn show_position(&self, cx: &Cx<'_, Self>, text: &RulerText, at: Pos2, item: Item, values: &RulerValues, width: f32) {
fn show_position(&self, cx: &Cx<'_, Self>, text: &RulerText, at: Pos2, item: RulerItem, values: &RulerValues, width: f32) {
let words = cx.words::<super::TextRulerWords>();
let name = Self::item_name(&words, item, values).to_owned();
let value = text.format_value(&cx.env.units(), f64::from(item.position(values, width)), 0.0);
@@ -237,7 +238,8 @@ impl TextRuler<'_> {
PressPhase::Release { start, click: true, pos, .. } if start.button == PointerButton::Primary && g.column().contains(pos) => {
let (value, at) = place(values, stop_at(pos.x, press.mods.alt));
cx.set(value);
self.report.picked = Some(at);
// P3(type-w5): ty.X57
self.report.picked = Some(RulerItem::Stop(at));
}
_ => {}
}
@@ -248,9 +250,9 @@ impl TextRuler<'_> {
held.off = dropped_off(pos.y, g.strip);
if !held.off {
let (value, at) = place(&anchor, *stop);
held.now = Some(Item::Stop(at));
held.now = Some(RulerItem::Stop(at));
cx.propose(value.clone());
self.show_position(cx, text, pos, Item::Stop(at), &value, g.width);
self.show_position(cx, text, pos, RulerItem::Stop(at), &value, g.width);
}
}
@@ -306,7 +308,7 @@ impl TextRuler<'_> {
return;
}
let values = cx.value().cloned().unwrap_or_default();
for item in Item::all(&values) {
for item in RulerItem::all(&values) {
if let Some(to) = cx.intents().take_set_value_at(item.part()) {
let (value, now) = moved(&values, item, to as f32, g.width);
cx.set(value);
@@ -330,7 +332,7 @@ impl TextRuler<'_> {
}
return;
}
let Some(item) = Item::of_part(part) else { return };
let Some(item) = RulerItem::of_part(part) else { return };
let by = take_steps(cx, g, step);
if by != 0.0 {
let (value, now) = moved(&values, item, item.position(&values, g.width) + by, g.width);
@@ -340,11 +342,11 @@ impl TextRuler<'_> {
let forward = cx.intents().take_exact(&Intent::delete(true, Granularity::Unit));
let backward = cx.intents().take_exact(&Intent::delete(false, Granularity::Unit));
if (forward || backward)
&& let Item::Stop(at) = item
&& let RulerItem::Stop(at) = item
{
cx.set(without(&values, at));
let left = values.stops.len().saturating_sub(1);
let next = left.checked_sub(1).map(|last| Item::Stop(at.saturating_sub(1).min(last))).unwrap_or(Item::LeftBox);
let next = left.checked_sub(1).map(|last| RulerItem::Stop(at.saturating_sub(1).min(last))).unwrap_or(RulerItem::LeftBox);
cx.focus_part(next.part());
}
let _ = held;
+21 -1
View File
@@ -103,6 +103,10 @@ pub struct SpellingItem {
pub word: String,
/// At most [`SUGGESTION_COUNT`], best first.
pub suggestions: Vec<String>,
/// The sentence's text before the word; empty with `after` for the word alone.
pub before: String,
/// The sentence's text after the word.
pub after: String,
}
/// A button the app acts on. Ignore is the dialog's own (it moves to the next item).
@@ -130,6 +134,8 @@ pub enum SpellingAction {
},
/// Add `word` to the user's dictionary ([`SpellingSettings`]).
Add(String),
/// Ignore reports the item it skipped; the dialog still moves to the next item itself.
Ignore(SpellingItem),
/// Find the misspellings again: Ignore All added a word to [`CheckSpellingDialog::ignored`],
/// or Check All Layers changed.
Relist,
@@ -138,7 +144,14 @@ pub enum SpellingAction {
impl SpellingItem {
/// The misspelling `word` at `range` of the text object `object`, with the `suggestions` best first.
pub fn new(object: u64, range: Range<usize>, word: impl Into<String>, suggestions: Vec<String>) -> Self {
SpellingItem { object, range, word: word.into(), suggestions }
SpellingItem { object, range, word: word.into(), suggestions, before: String::new(), after: String::new() }
}
/// Sets the sentence's text before and after the word.
#[must_use]
pub fn context(self, before: impl Into<String>, after: impl Into<String>) -> Self {
let _ = (before.into(), after.into());
todo!("ty.X97")
}
}
@@ -208,6 +221,13 @@ impl CheckSpellingDialog {
self.action.take()
}
/// Replaces the list and shows its first item (Change To from its first suggestion): a host that walks its text
/// itself hands the dialog the words from its current place.
pub fn restart(&mut self, items: Vec<SpellingItem>) {
let _ = items;
todo!("ty.X100")
}
/// The misspellings found again after an action. The dialog keeps its position in the list (after Change, Ignore
/// All and Add those words are gone, so the same position is the next misspelling; earlier ones skipped with
/// Ignore stay skipped), except after Check All Layers changed, when it starts from the first. Change To gets the
+9 -2
View File
@@ -122,6 +122,8 @@ pub enum TextStyleAction {
New {
/// Whether to start from the selected type's attributes.
from_selection: bool,
/// Whether Alt was held on the New footer button: the host asks for the new style's name.
ask_name: bool,
},
/// Duplicate the selected row's style.
Duplicate(u64),
@@ -187,7 +189,7 @@ impl Facts {
TextStyleCommand::Redefine => {
(self.target && self.current.is_some_and(|id| id != 0 || self.paragraph)).then_some(TextStyleAction::Redefine)
}
TextStyleCommand::New => Some(TextStyleAction::New { from_selection: self.target }),
TextStyleCommand::New => Some(TextStyleAction::New { from_selection: self.target, ask_name: false }),
TextStyleCommand::Duplicate if several => Some(TextStyleAction::DuplicateHighlighted),
TextStyleCommand::Delete if several => Some(TextStyleAction::DeleteHighlighted),
TextStyleCommand::Duplicate => editable.map(TextStyleAction::Duplicate),
@@ -254,6 +256,9 @@ pub struct TextStylesPanel<'a> {
/// The list's text with no rows, passed to the collection's `empty` prop.
#[prop(into)]
empty: Option<Label>,
/// Scrolls the row of this id into view in this pass.
#[prop]
reveal: Option<u64>,
}
impl TextStylesPanel<'_> {
@@ -290,6 +295,7 @@ impl<'a> TextStylesPanel<'a> {
text_selected: true,
highlighting: false,
empty: None,
reveal: None,
}
}
@@ -302,7 +308,8 @@ impl<'a> TextStylesPanel<'a> {
/// Shows the panel and returns what the user asked for.
pub fn show(self, ui: &mut Ui) -> TextStylesPanelOutput {
let TextStylesPanel { label, kind, rows, mut selection, current, overridden, target, text_selected, highlighting, empty } = self;
let TextStylesPanel { label, kind, rows, mut selection, current, overridden, target, text_selected, highlighting, empty, reveal } = self;
let _ = reveal; // P3(type-w5): ty.X63
let words = Env::of(ui).words::<TextStylesWords>();
let paragraph = kind == TextStyleKind::Paragraph;
let action = Cell::new(None::<TextStyleAction>);