mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 23:24:24 +00:00
Contract stubs: stage 1 (font-catalog, i18n, keymap, platform, behavior, window)
This commit is contained in:
@@ -140,6 +140,13 @@ impl CanvasView {
|
||||
self.zoom * self.sx()
|
||||
}
|
||||
|
||||
/// The screen size of the box that holds document rect `r` at the view's zoom, rotation,
|
||||
/// aspect and flip: the bounding box of [`CanvasView::quad`].
|
||||
pub fn extent(&self, r: Rect) -> ScreenVec {
|
||||
let _ = r;
|
||||
todo!("cw.C51")
|
||||
}
|
||||
|
||||
/// The screen corners of document rect `r`, in order round it: (x0, y0), (x1, y0), (x1, y1),
|
||||
/// (x0, y1).
|
||||
pub fn quad(&self, r: Rect) -> [Pos2; 4] {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! [`ZoomLadder::clamp`], so no control can pull the zoom into a narrower range of its own.
|
||||
|
||||
use super::view::CanvasView;
|
||||
use emath::Pos2;
|
||||
use emath::{Pos2, Rect as ScreenRect, Vec2 as ScreenVec};
|
||||
use kurbo::{Point, Rect, Size, Vec2};
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
@@ -160,6 +160,13 @@ fn fit_rect_up_to(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_poin
|
||||
view.center = rect.center();
|
||||
}
|
||||
|
||||
/// The window-canvas size at which the zoomed document fits: the canvas size less the view's
|
||||
/// rect size plus the screen extent of the whole document.
|
||||
pub fn wrapped_canvas(view: &CanvasView, document: Size, canvas: ScreenRect) -> ScreenVec {
|
||||
let _ = (view, document, canvas);
|
||||
todo!("cw.C72")
|
||||
}
|
||||
|
||||
/// Fill Screen: centre the document and zoom until it covers `view.rect`; one axis may extend
|
||||
/// past the canvas.
|
||||
pub fn fill(view: &mut CanvasView, size: Size, pixels_per_point: f32) {
|
||||
|
||||
@@ -11,6 +11,18 @@ use std::sync::Arc;
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct NotAValue;
|
||||
|
||||
/// What a parse learned beside the value.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct ParseNote {
|
||||
/// The tag of the unit the text named.
|
||||
pub unit: Option<u32>,
|
||||
/// The number read before the codec held it to its range.
|
||||
pub held: Option<f64>,
|
||||
/// The text held more than the codec reads; the value is what came before the cut.
|
||||
pub cut: bool,
|
||||
}
|
||||
|
||||
/// Where the caret goes when the part takes focus.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
@@ -35,9 +47,9 @@ pub trait Codec {
|
||||
/// The value of `text`; `start` is the value when editing began, for relative input.
|
||||
fn parse(&self, text: &str, start: &Self::Value) -> Result<Self::Value, NotAValue>;
|
||||
|
||||
/// The value of `text` and the tag of the unit it named (`Reader::read_tagged`); the default names none.
|
||||
fn parse_tagged(&self, text: &str, start: &Self::Value) -> Result<(Self::Value, Option<u32>), NotAValue> {
|
||||
self.parse(text, start).map(|value| (value, None))
|
||||
/// The value of `text` and what the parse learned beside it (`Reader::read_tagged`); the default notes nothing.
|
||||
fn parse_tagged(&self, text: &str, start: &Self::Value) -> Result<(Self::Value, ParseNote), NotAValue> {
|
||||
self.parse(text, start).map(|value| (value, ParseNote::default()))
|
||||
}
|
||||
|
||||
/// Whether `text` applies as soon as it is typed rather than on commit.
|
||||
@@ -79,7 +91,7 @@ impl<C: Codec + ?Sized> Codec for &C {
|
||||
(**self).parse(text, start)
|
||||
}
|
||||
|
||||
fn parse_tagged(&self, text: &str, start: &Self::Value) -> Result<(Self::Value, Option<u32>), NotAValue> {
|
||||
fn parse_tagged(&self, text: &str, start: &Self::Value) -> Result<(Self::Value, ParseNote), NotAValue> {
|
||||
(**self).parse_tagged(text, start)
|
||||
}
|
||||
|
||||
@@ -144,6 +156,8 @@ pub struct NumberCodec {
|
||||
/// Every decimal place is written, trailing zeros included.
|
||||
fixed: bool,
|
||||
custom: Option<Custom>,
|
||||
/// Typing rules of a zoom field ([`NumberCodec::zoom_typing`]).
|
||||
zoom: bool,
|
||||
}
|
||||
|
||||
impl fmt::Debug for NumberCodec {
|
||||
@@ -152,6 +166,7 @@ impl fmt::Debug for NumberCodec {
|
||||
.field("reader", &self.reader)
|
||||
.field("decimals", &self.decimals)
|
||||
.field("fixed", &self.fixed)
|
||||
.field("zoom", &self.zoom)
|
||||
.field("custom", &self.custom.is_some())
|
||||
.finish()
|
||||
}
|
||||
@@ -164,7 +179,7 @@ impl PartialEq for NumberCodec {
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||||
_ => false,
|
||||
};
|
||||
self.reader == other.reader && self.decimals == other.decimals && self.fixed == other.fixed && same_custom
|
||||
self.reader == other.reader && self.decimals == other.decimals && self.fixed == other.fixed && self.zoom == other.zoom && same_custom
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,7 +213,7 @@ const NUMBER_SAMPLE: &str = "0000.00";
|
||||
impl NumberCodec {
|
||||
/// A codec reading with `reader` and writing at most `decimals` decimal places.
|
||||
pub fn new(reader: Reader, decimals: usize) -> Self {
|
||||
NumberCodec { reader, decimals, fixed: false, custom: None }
|
||||
NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false }
|
||||
}
|
||||
|
||||
/// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown
|
||||
@@ -208,6 +223,13 @@ impl NumberCodec {
|
||||
self
|
||||
}
|
||||
|
||||
/// The same codec with the typing rules of a zoom field: digits, `/` and the decimal separator, `a/b` as the
|
||||
/// percentage `a ÷ b × 100`, and a second separator cutting the text.
|
||||
pub fn zoom_typing(self) -> Self {
|
||||
let _ = self;
|
||||
todo!("cw.C55")
|
||||
}
|
||||
|
||||
/// The same codec writing at most `decimals` decimal places.
|
||||
pub fn at_most(mut self, decimals: usize) -> Self {
|
||||
self.decimals = self.decimals.min(decimals);
|
||||
@@ -274,13 +296,15 @@ impl Codec for NumberCodec {
|
||||
}
|
||||
|
||||
/// The tag is that of the unit the text named; `None` when it named no tagged unit or a custom parser read it.
|
||||
fn parse_tagged(&self, text: &str, start: &Option<f64>) -> Result<(Option<f64>, Option<u32>), NotAValue> {
|
||||
fn parse_tagged(&self, text: &str, start: &Option<f64>) -> Result<(Option<f64>, ParseNote), NotAValue> {
|
||||
if text.trim().is_empty() {
|
||||
return Ok((None, None));
|
||||
return Ok((None, ParseNote::default()));
|
||||
}
|
||||
match self.reader.read_tagged(text, *start) {
|
||||
Ok((number, tag)) => Ok((Some(number), tag)),
|
||||
Err(rejected) => self.custom.as_ref().and_then(|parse| parse(text.trim())).map(|number| (Some(number), None)).ok_or(rejected),
|
||||
Ok((number, tag)) => Ok((Some(number), ParseNote { unit: tag, ..ParseNote::default() })), // P3(canvas-widgets-w11): cw.N1
|
||||
Err(rejected) => {
|
||||
self.custom.as_ref().and_then(|parse| parse(text.trim())).map(|number| (Some(number), ParseNote::default())).ok_or(rejected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,30 @@ pub enum CursorBadge {
|
||||
Scissors,
|
||||
/// A circle: the pen's point that closes a path.
|
||||
Close,
|
||||
/// An arrow: a move mark.
|
||||
Move,
|
||||
/// An arrowhead mark.
|
||||
Arrow,
|
||||
/// The colour-sampler ring with four ticks.
|
||||
Target,
|
||||
/// A continue mark.
|
||||
Continue,
|
||||
/// A count mark: add, move or delete.
|
||||
Count(CountMark),
|
||||
/// The corner-radius mark.
|
||||
Corner,
|
||||
}
|
||||
|
||||
/// The kind of a [`CursorBadge::Count`] mark.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum CountMark {
|
||||
/// A point is added.
|
||||
Add,
|
||||
/// A point is moved.
|
||||
Move,
|
||||
/// A point is deleted.
|
||||
Delete,
|
||||
}
|
||||
|
||||
/// A cursor the overlay host paints. Geometry is in screen points around the pointer (a tool scales its brush
|
||||
@@ -159,6 +183,34 @@ pub enum PaintedCursor {
|
||||
/// The screen direction of the edge the arrows run along.
|
||||
dir: Vec2,
|
||||
},
|
||||
/// The type tool's pointer: an I-beam, over a path when `path`.
|
||||
#[non_exhaustive]
|
||||
TypeOn {
|
||||
/// The text goes on a path.
|
||||
path: bool,
|
||||
},
|
||||
/// A locator mark.
|
||||
Locator,
|
||||
/// An arrow with its tip on the hotspot: solid, or hollow when `hollow`.
|
||||
#[non_exhaustive]
|
||||
Arrow {
|
||||
/// The arrow is drawn hollow.
|
||||
hollow: bool,
|
||||
},
|
||||
/// An I-beam across a path with a filled triangle toward each grabbable side.
|
||||
#[non_exhaustive]
|
||||
PathText {
|
||||
/// The start of the path can be grabbed.
|
||||
start: bool,
|
||||
/// The end of the path can be grabbed.
|
||||
end: bool,
|
||||
},
|
||||
/// A crosshair with the tool's icon below and right of it.
|
||||
#[non_exhaustive]
|
||||
CrosshairTool {
|
||||
/// The icon.
|
||||
icon: IconId,
|
||||
},
|
||||
/// No cursor at all.
|
||||
Hidden,
|
||||
}
|
||||
@@ -213,6 +265,26 @@ impl PaintedCursor {
|
||||
PaintedCursor::Skew { dir }
|
||||
}
|
||||
|
||||
/// The type tool's pointer, over a path when `path`.
|
||||
pub const fn type_on(path: bool) -> Self {
|
||||
PaintedCursor::TypeOn { path }
|
||||
}
|
||||
|
||||
/// An arrow with its tip on the hotspot, hollow when `hollow`.
|
||||
pub const fn arrow(hollow: bool) -> Self {
|
||||
PaintedCursor::Arrow { hollow }
|
||||
}
|
||||
|
||||
/// An I-beam across the path with a triangle toward each grabbable side.
|
||||
pub const fn path_text(start: bool, end: bool) -> Self {
|
||||
PaintedCursor::PathText { start, end }
|
||||
}
|
||||
|
||||
/// A crosshair with the tool's icon at (+10, +10).
|
||||
pub const fn crosshair_tool(icon: IconId) -> Self {
|
||||
PaintedCursor::CrosshairTool { icon }
|
||||
}
|
||||
|
||||
/// A system cursor with a mark.
|
||||
pub const fn badged(base: CursorIcon, badge: CursorBadge) -> Self {
|
||||
PaintedCursor::Badged { base, badge }
|
||||
|
||||
@@ -33,6 +33,10 @@ pub struct Workspace<P> {
|
||||
/// Closed panels, and panels the application does not register now, with where each one
|
||||
/// goes back.
|
||||
pub hidden: Vec<(P, Location<P>)>,
|
||||
/// Floating panels with the docked location each one left, so Dock Panel can return it. Saved with the
|
||||
/// workspace.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub floated: Vec<(P, Location<P>)>,
|
||||
/// Counts the replacements of this live workspace. Not saved, and not part of equality.
|
||||
#[serde(skip)]
|
||||
revision: u64,
|
||||
@@ -40,7 +44,7 @@ pub struct Workspace<P> {
|
||||
|
||||
impl<P: PartialEq> PartialEq for Workspace<P> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.version == other.version && self.layout == other.layout && self.hidden == other.hidden
|
||||
self.version == other.version && self.layout == other.layout && self.hidden == other.hidden && self.floated == other.floated
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +68,7 @@ impl<P> Workspace<P> {
|
||||
|
||||
/// A workspace of `layout`, with no hidden panels.
|
||||
pub fn new(layout: Layout<P>) -> Self {
|
||||
Self { version: Self::VERSION, layout, hidden: Vec::new(), revision: 0 }
|
||||
Self { version: Self::VERSION, layout, hidden: Vec::new(), floated: Vec::new(), revision: 0 }
|
||||
}
|
||||
|
||||
/// The revision of this live workspace: it changes with every [`replace`](Self::replace) and nothing else.
|
||||
|
||||
@@ -24,6 +24,27 @@ pub struct CropBox {
|
||||
pub angle: f64,
|
||||
}
|
||||
|
||||
/// What a resize holds about the frame's proportions.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum AspectHold {
|
||||
/// No proportion held.
|
||||
Free,
|
||||
/// The set ratio, width over height.
|
||||
Ratio(f64),
|
||||
/// The box's own ratio, the corner following the diagonal (Shift on a corner with no set ratio).
|
||||
Diagonal,
|
||||
}
|
||||
|
||||
impl AspectHold {
|
||||
/// The ratio the current resize reads; `Diagonal` holds none until tl.T41 is written.
|
||||
fn ratio(self) -> Option<f64> {
|
||||
match self {
|
||||
AspectHold::Ratio(r) => Some(r),
|
||||
AspectHold::Free | AspectHold::Diagonal => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CropBox {
|
||||
/// The frame `rect` turned `angle` degrees about its centre.
|
||||
pub const fn new(rect: Rect, angle: f64) -> Self {
|
||||
@@ -137,7 +158,8 @@ impl CropBox {
|
||||
/// the page (or the centre with `alt`), `ratio` (width over height) held. A part that is not a corner or an
|
||||
/// edge leaves the frame as it is.
|
||||
#[must_use]
|
||||
pub fn resized(&self, part: BoxPart, by: Vec2, ratio: Option<f64>, alt: bool) -> Self {
|
||||
pub fn resized(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Self {
|
||||
let ratio = hold.ratio(); // P3(tools-w15): tl.T41
|
||||
match part_handle(part) {
|
||||
Some((hx, hy)) => resized_turned(self, hx, hy, by, ratio, alt),
|
||||
None => *self,
|
||||
@@ -148,7 +170,8 @@ impl CropBox {
|
||||
/// frame about its centre, so the handle stays under the pointer while the frame stays centred on screen. The
|
||||
/// opposite edge stays put on the image (the centre with `alt`), so the frame's centre moves by the difference
|
||||
/// and the view follows it. `None` when the result is not finite or `part` is not a corner or an edge.
|
||||
pub fn resized_centred(&self, part: BoxPart, by: Vec2, ratio: Option<f64>, alt: bool) -> Option<Self> {
|
||||
pub fn resized_centred(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Option<Self> {
|
||||
let ratio = hold.ratio(); // P3(tools-w15): tl.T41
|
||||
let (hx, hy) = part_handle(part)?;
|
||||
let r = self.rect.abs();
|
||||
let (w0, h0) = (r.width(), r.height());
|
||||
|
||||
@@ -36,6 +36,14 @@ pub fn round_to_direction(angle: f64, directions: Directions) -> f64 {
|
||||
(angle / step).round() * step
|
||||
}
|
||||
|
||||
/// Shift's polygon vertex: `point` moved to the nearest of eight directions from `from`; an axis keeps the
|
||||
/// segment's length, a diagonal keeps the shorter offset on both axes. `point` itself for a zero-length or
|
||||
/// non-finite offset.
|
||||
pub fn polygon_step(from: Point, point: Point) -> Point {
|
||||
let _ = (from, point);
|
||||
todo!("cw.C23")
|
||||
}
|
||||
|
||||
/// `point` turned about `from` to the nearest multiple of 45°, keeping its distance: the one ⇧ rule for a line, a
|
||||
/// handle or a segment drawn from a fixed point. `point` itself when it is on `from` or not finite.
|
||||
pub fn turn_to_45(from: Point, point: Point) -> Point {
|
||||
|
||||
@@ -10,15 +10,17 @@ pub mod geom;
|
||||
pub mod lock;
|
||||
pub mod marquee;
|
||||
pub mod move_gesture;
|
||||
pub mod outside;
|
||||
pub mod quad;
|
||||
pub mod selection_op;
|
||||
pub mod snap;
|
||||
|
||||
pub use crop::{CropBox, CropGuide, GuideShow, crop_view, crop_view_about, hit_rect, screen_step};
|
||||
pub use crop::{AspectHold, CropBox, CropGuide, GuideShow, crop_view, crop_view_about, hit_rect, screen_step};
|
||||
pub use draft::{DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft};
|
||||
pub use lock::{Directions, LOCK_HYSTERESIS_DEGREES, lock_direction, round_to_direction, turn_to_45};
|
||||
pub use lock::{Directions, LOCK_HYSTERESIS_DEGREES, lock_direction, polygon_step, round_to_direction, turn_to_45};
|
||||
pub use marquee::{Constraint, MarqueeGesture, MarqueeRect, fixed_size_pixels, marquee_pixels, square_pixels};
|
||||
pub use move_gesture::{ConstrainStyle, MoveGesture, MoveValue, StrokeLock};
|
||||
pub use outside::outside_pieces;
|
||||
pub use quad::{BoxAllow, BoxDrag, BoxPart, BoxRules, BoxState, Homography, Parts, SKEW_LIMIT, ScaleRule, TransformMode, drag};
|
||||
pub use selection_op::SelectionOperation;
|
||||
pub use snap::{SNAP_PX, SnapGesture, SnapKind, SnapLine, SnapOptions, SnapTarget, SnapTargets, across_axis, coordinate_across, motion_across};
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
//! The canvas outside a convex hole, as convex pieces.
|
||||
|
||||
use kurbo::Point;
|
||||
|
||||
/// Convex pieces that cover the canvas quad outside the convex `hole` exactly once: the canvas clipped by each
|
||||
/// hole edge's outer half-plane in turn. Empty for a hole with fewer than three finite points or no area; the whole
|
||||
/// canvas for a hole outside it.
|
||||
pub fn outside_pieces(canvas: [Point; 4], hole: &[Point]) -> Vec<Vec<Point>> {
|
||||
let _ = (canvas, hole);
|
||||
todo!("tl.T42")
|
||||
}
|
||||
@@ -97,6 +97,9 @@ pub enum ScaleRule {
|
||||
/// PhotoCraft's Use Legacy Free Transform, DesignCraft and VectorCraft: corners stretch freely
|
||||
/// and ⇧ keeps the proportions; edges stretch their one axis.
|
||||
Free,
|
||||
/// A shape or path bounds box: a corner scales by the projection of the drag on the anchor-corner diagonal,
|
||||
/// keeping the proportions; an edge stretches its one axis.
|
||||
Shape,
|
||||
}
|
||||
|
||||
/// What the box's content allows. PhotoCraft: editable type refuses distort and perspective
|
||||
@@ -185,11 +188,20 @@ pub struct BoxRules {
|
||||
/// The angle ⇧ snaps a rotation to, in degrees (PhotoCraft 15; DesignCraft and VectorCraft
|
||||
/// 45).
|
||||
pub rotate_step: f64,
|
||||
/// The smallest side a scale drag leaves, in document units.
|
||||
pub min_side: f64,
|
||||
}
|
||||
|
||||
impl Default for BoxRules {
|
||||
fn default() -> Self {
|
||||
BoxRules { mode: TransformMode::Free, scale: ScaleRule::Proportional, aspect_linked: true, allow: BoxAllow::default(), rotate_step: 15.0 }
|
||||
BoxRules {
|
||||
mode: TransformMode::Free,
|
||||
scale: ScaleRule::Proportional,
|
||||
aspect_linked: true,
|
||||
allow: BoxAllow::default(),
|
||||
rotate_step: 15.0,
|
||||
min_side: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,6 +230,12 @@ impl BoxRules {
|
||||
self
|
||||
}
|
||||
|
||||
/// The rules with `side` as the minimum side of a scaled box, in document units.
|
||||
pub fn with_min_side(self, side: f64) -> BoxRules {
|
||||
let _ = side;
|
||||
todo!("tl.T2")
|
||||
}
|
||||
|
||||
/// The mode drags follow: a mode the content refuses scales as Free Transform does.
|
||||
pub fn effective_mode(&self) -> TransformMode {
|
||||
let refused = match self.mode {
|
||||
@@ -613,6 +631,12 @@ fn unturn(c: Vec2, angle: f64) -> Vec2 {
|
||||
}
|
||||
|
||||
impl BoxState {
|
||||
/// The pivot through the inverse homography, in `rect`'s coordinates; least squares for a flat box.
|
||||
pub fn origin_of_pivot(&self, rect: Rect) -> Point {
|
||||
let _ = rect;
|
||||
todo!("tl.T3")
|
||||
}
|
||||
|
||||
/// A box with the corners `quad`, clockwise from the top left, and the reference point `pivot`.
|
||||
pub const fn new(quad: [Point; 4], pivot: Point) -> Self {
|
||||
BoxState { quad, pivot }
|
||||
@@ -822,6 +846,13 @@ impl BoxState {
|
||||
pub struct Homography([f64; 9]);
|
||||
|
||||
impl Homography {
|
||||
/// [`Homography::apply`] for a point on the front side of the horizon, the side most of `within`'s corners lie
|
||||
/// on; `None` for a point behind it.
|
||||
pub fn apply_in_front(&self, p: Point, within: Rect) -> Option<Point> {
|
||||
let _ = (p, within);
|
||||
todo!("tl.T4")
|
||||
}
|
||||
|
||||
/// The map with these rows of (x, y, w) coefficients, applied to (x, y, 1).
|
||||
pub fn from_rows(rows: [[f64; 3]; 3]) -> Homography {
|
||||
let [[a, b, c], [d, e, f], [g, h, i]] = rows;
|
||||
|
||||
@@ -38,6 +38,13 @@ pub enum SnapKind {
|
||||
Selection,
|
||||
}
|
||||
|
||||
impl SnapKind {
|
||||
/// Whether the target's lines draw in the smart-guide colour: `LayerEdge`, `LayerCenter` and `Center`.
|
||||
pub const fn is_smart(self) -> bool {
|
||||
matches!(self, SnapKind::LayerEdge | SnapKind::LayerCenter | SnapKind::Center)
|
||||
}
|
||||
}
|
||||
|
||||
impl SnapGesture {
|
||||
/// A moving rectangle that was `at_press` when the gesture began.
|
||||
pub const fn rect(at_press: Rect) -> Self {
|
||||
|
||||
@@ -68,7 +68,7 @@ pub use canvas::{CanvasView, RulerUnits, Ticks, ViewHistory, ViewPlace, ZoomLadd
|
||||
/// The f64 geometry crate the canvas view and its callers share.
|
||||
pub use kurbo;
|
||||
|
||||
pub use codec::{Caret, Codec, NotAValue, NumberCodec, PlainText, decimals_for_step};
|
||||
pub use codec::{Caret, Codec, NotAValue, NumberCodec, ParseNote, PlainText, decimals_for_step};
|
||||
pub use columns::{ColumnKey, ColumnWidth, GridSection, GridView, sub_row_cells};
|
||||
pub use command::{CommandFlags, pick_instance, resolve_flags};
|
||||
pub use cursor::{Cursor, CursorBadge, CursorIcon, CursorPriority, IconId, PaintedCursor};
|
||||
@@ -112,7 +112,7 @@ pub use sizing::{ControlMetrics, Metrics, Proposal};
|
||||
pub use typing::{EditRun, Ended, EscapeRule, Escaped, Typed, TypingRun};
|
||||
pub use value::{Applied, CancelReason, EditEvent, EditEvents, EditPolicy, Gesture, GestureId, GesturePhase, Mixed, Validity, Value};
|
||||
pub use value_drag::{DragWarp, ValueDrag, wrap_value};
|
||||
pub use wheel::{Wheel, WheelFocus, WheelNotch, WheelPhase, WheelRoom, WheelTaker, WheelUnit};
|
||||
pub use wheel::{GESTURE_GAP, Wheel, WheelFocus, WheelGesture, WheelNotch, WheelPhase, WheelRoom, WheelTaker, WheelUnit};
|
||||
|
||||
#[cfg(test)]
|
||||
extern crate self as craft_behavior;
|
||||
|
||||
@@ -198,8 +198,16 @@ impl TypeAhead {
|
||||
}
|
||||
|
||||
/// The entry a prefix picks: the first match from the position after `from` (from `from` itself when the
|
||||
/// prefix is one repeated letter, so repeating a letter cycles), wrapping at the end.
|
||||
pub fn pick<'a>(prefix: &str, from: Option<usize>, len: usize, label: impl Fn(usize) -> std::borrow::Cow<'a, str>) -> Option<usize> {
|
||||
/// prefix is one repeated letter, so repeating a letter cycles), wrapping at the end. `fold` folds the prefix and
|
||||
/// each label before they are compared.
|
||||
pub fn pick<'a>(
|
||||
prefix: &str,
|
||||
from: Option<usize>,
|
||||
len: usize,
|
||||
label: impl Fn(usize) -> std::borrow::Cow<'a, str>,
|
||||
fold: impl Fn(&str) -> String,
|
||||
) -> Option<usize> {
|
||||
let _ = &fold; // P3(canvas-widgets-w12): cw.C64
|
||||
if len == 0 || prefix.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -192,6 +192,12 @@ fn fit(size: [f32; 2], room: [f32; 2], min: [f32; 2]) -> [f32; 2] {
|
||||
std::array::from_fn(|i| size[i].min(room[i]).max(min[i].min(room[i])).max(1.0))
|
||||
}
|
||||
|
||||
/// `size` at least `min` and at most the monitor's usable area less `frame`; the cap wins over the minimum.
|
||||
pub fn capped(size: Vec2, monitor: &Monitor, frame: Vec2, min: Vec2) -> Vec2 {
|
||||
let _ = (size, monitor, frame, min);
|
||||
todo!("cw.C54")
|
||||
}
|
||||
|
||||
fn in_points(v: f32) -> bool {
|
||||
v.is_finite() && (1.0..=MAX_POINTS).contains(&v)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! `TypingRun<C>`: the draft, rejected text, commit, cancel, escape rule and limits of a text part (18.2).
|
||||
|
||||
use crate::codec::{Codec, NotAValue};
|
||||
use crate::codec::{Codec, NotAValue, ParseNote};
|
||||
use crate::value::GestureId;
|
||||
|
||||
/// The state a [`TypingRun`] keeps per text part.
|
||||
@@ -135,8 +135,9 @@ impl<C: Codec> TypingRun<C> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The draft is now `text`: characters the codec refuses and characters past the limit drop out.
|
||||
pub fn edit(&self, run: &mut EditRun<C::Value>, start: &C::Value, text: &str) -> Typed<C::Value> {
|
||||
/// The draft is now `text`: characters the codec refuses and characters past the limit drop out. The `bool`
|
||||
/// is whether the codec's `filter` dropped a character of this edit; characters past the limit do not set it.
|
||||
pub fn edit(&self, run: &mut EditRun<C::Value>, start: &C::Value, text: &str) -> (Typed<C::Value>, bool) {
|
||||
if !run.is_open() {
|
||||
run.start = start.clone();
|
||||
}
|
||||
@@ -155,7 +156,13 @@ impl<C: Codec> TypingRun<C> {
|
||||
_ => Typed::Draft,
|
||||
};
|
||||
run.draft = Some(draft);
|
||||
typed
|
||||
(typed, false) // P3(canvas-widgets-w11): cw.N2
|
||||
}
|
||||
|
||||
/// Replaces the draft with the codec's normal form of the value it reads; whether it read one.
|
||||
pub fn rewrite(&self, run: &mut EditRun<C::Value>) -> bool {
|
||||
let _ = run;
|
||||
todo!("cw.N2")
|
||||
}
|
||||
|
||||
/// Commits the draft: a value closes the run, a draft that is no value keeps it open.
|
||||
@@ -163,19 +170,20 @@ impl<C: Codec> TypingRun<C> {
|
||||
self.commit_tagged(run).0
|
||||
}
|
||||
|
||||
/// [`commit`](Self::commit), with the tag of the unit the committed text named (`Codec::parse_tagged`).
|
||||
pub fn commit_tagged(&self, run: &mut EditRun<C::Value>) -> (Ended<C::Value>, Option<u32>) {
|
||||
let Some(draft) = run.draft.as_deref() else { return (Ended::Idle, None) };
|
||||
/// [`commit`](Self::commit), with the note of the committed text (`Codec::parse_tagged`); the default note for a
|
||||
/// rejected or idle run.
|
||||
pub fn commit_tagged(&self, run: &mut EditRun<C::Value>) -> (Ended<C::Value>, ParseNote) {
|
||||
let Some(draft) = run.draft.as_deref() else { return (Ended::Idle, ParseNote::default()) };
|
||||
match self.codec.parse_tagged(draft, &run.start) {
|
||||
Ok((value, tag)) => {
|
||||
Ok((value, note)) => {
|
||||
run.draft = None;
|
||||
run.error = None;
|
||||
(Ended::Commit(value), tag)
|
||||
(Ended::Commit(value), note)
|
||||
}
|
||||
Err(error) => {
|
||||
run.error = Some(error);
|
||||
run.rejected = Some((draft.to_owned(), run.start.clone()));
|
||||
(Ended::Rejected, None)
|
||||
(Ended::Rejected, ParseNote::default())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -213,11 +221,11 @@ mod tests {
|
||||
fn a_number_run_applies_on_commit_rejects_bad_text_and_restores_on_escape() {
|
||||
let typing = TypingRun::new(NumberCodec::default());
|
||||
let mut run = EditRun::new(Some(1.0));
|
||||
assert_eq!(typing.edit(&mut run, &Some(1.0), "2+x"), Typed::Draft);
|
||||
assert_eq!(typing.edit(&mut run, &Some(1.0), "2+x").0, Typed::Draft);
|
||||
assert_eq!(run.error, Some(NotAValue));
|
||||
assert_eq!(typing.commit(&mut run), Ended::Rejected, "the run stays open on a refused commit");
|
||||
assert!(run.is_open() && run.rejected.is_some());
|
||||
assert_eq!(typing.edit(&mut run, &Some(1.0), "2+3"), Typed::Draft, "a number applies on commit");
|
||||
assert_eq!(typing.edit(&mut run, &Some(1.0), "2+3").0, Typed::Draft, "a number applies on commit");
|
||||
assert_eq!(typing.commit(&mut run), Ended::Commit(Some(5.0)));
|
||||
assert_eq!(typing.commit(&mut run), Ended::Idle);
|
||||
typing.edit(&mut run, &Some(5.0), "9");
|
||||
|
||||
@@ -52,12 +52,18 @@ pub struct Wheel {
|
||||
/// The vertical scroll came from over a zoom zone (`Sense::WHEEL_ZOOMS_VIEW`): the taker zooms its view by it,
|
||||
/// about `at`, instead of scrolling.
|
||||
pub zooms: bool,
|
||||
/// Zoom factor of a two-finger touch; 1 for none. `zoom` is the trackpad pinch only.
|
||||
pub touch_zoom: f32,
|
||||
/// Rotation in radians, clockwise on screen (egui's `Event::Rotate`).
|
||||
pub rotation: f32,
|
||||
/// Rotation of a two-finger touch, in radians.
|
||||
pub touch_rotation: f32,
|
||||
}
|
||||
|
||||
impl Wheel {
|
||||
/// A scroll of `scroll` points with no zoom.
|
||||
pub const fn new(scroll: Vec2, mods: Mods, unit: WheelUnit, phase: WheelPhase) -> Self {
|
||||
Wheel { scroll, zoom: 1.0, mods, unit, phase, at: None, zooms: false }
|
||||
Wheel { scroll, zoom: 1.0, mods, unit, phase, at: None, zooms: false, touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0 }
|
||||
}
|
||||
|
||||
/// The same gesture with zoom factor `zoom`.
|
||||
@@ -66,6 +72,24 @@ impl Wheel {
|
||||
self
|
||||
}
|
||||
|
||||
/// The same gesture with the two-finger touch zoom factor `zoom`.
|
||||
pub const fn touch_zoom(mut self, zoom: f32) -> Self {
|
||||
self.touch_zoom = zoom;
|
||||
self
|
||||
}
|
||||
|
||||
/// The same gesture with rotation `radians`, clockwise on screen.
|
||||
pub const fn rotation(mut self, radians: f32) -> Self {
|
||||
self.rotation = radians;
|
||||
self
|
||||
}
|
||||
|
||||
/// The same gesture with the two-finger touch rotation `radians`.
|
||||
pub const fn touch_rotation(mut self, radians: f32) -> Self {
|
||||
self.touch_rotation = radians;
|
||||
self
|
||||
}
|
||||
|
||||
/// The same gesture with the pointer at `at`.
|
||||
pub const fn at(mut self, at: Pos2) -> Self {
|
||||
self.at = Some(at);
|
||||
@@ -73,6 +97,35 @@ impl Wheel {
|
||||
}
|
||||
}
|
||||
|
||||
/// The seconds between wheel events that still belong to one gesture.
|
||||
pub const GESTURE_GAP: f64 = 0.3;
|
||||
|
||||
/// A wheel gesture: events closer than [`GESTURE_GAP`] seconds, or inside one device phase. `owner` is `None` while
|
||||
/// no taker took it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct WheelGesture<O> {
|
||||
/// The taker the gesture started on.
|
||||
pub owner: Option<O>,
|
||||
/// The time of the gesture's last event, in seconds.
|
||||
pub last: f64,
|
||||
}
|
||||
|
||||
impl<O> Default for WheelGesture<O> {
|
||||
fn default() -> Self {
|
||||
WheelGesture { owner: None, last: f64::NEG_INFINITY }
|
||||
}
|
||||
}
|
||||
|
||||
impl<O: Copy> WheelGesture<O> {
|
||||
/// Closes the gesture once `now - last` reaches [`GESTURE_GAP`], or at once after a device end, and returns the
|
||||
/// owner it had.
|
||||
pub fn end(&mut self, now: f64) -> Option<O> {
|
||||
let _ = now;
|
||||
todo!("fx.F17")
|
||||
}
|
||||
}
|
||||
|
||||
/// A component that takes wheel input, as registered last pass.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
@@ -292,7 +345,16 @@ fn for_field(wheel: &Wheel) -> bool {
|
||||
/// `armed`. Shift turns a vertical wheel sideways when its vertical owner is a scroll region. When the innermost open
|
||||
/// taker under `at` for the vertical share is a zoom zone, the share goes to the innermost open zoom taker enclosing it,
|
||||
/// with `Wheel::zooms` set; without one the zone is passed over. Shares of one owner merge.
|
||||
pub fn split<O: Copy + PartialEq>(takers: &[WheelTaker<O>], at: Pos2, wheel: Wheel, focus: WheelFocus<O>, armed: Option<O>) -> Vec<(O, Wheel)> {
|
||||
pub fn split<O: Copy + PartialEq>(
|
||||
takers: &[WheelTaker<O>],
|
||||
at: Pos2,
|
||||
wheel: Wheel,
|
||||
focus: WheelFocus<O>,
|
||||
armed: Option<O>,
|
||||
gesture: &mut WheelGesture<O>,
|
||||
now: f64,
|
||||
) -> Vec<(O, Wheel)> {
|
||||
let _ = (&gesture, now); // P3(canvas-widgets-w4): fx.F18
|
||||
let field = focus.taker.filter(|focused| takers.iter().any(|taker| taker.field && taker.owner == *focused));
|
||||
if (field.is_some() || focus.app_field) && wheel.scroll != Vec2::ZERO && for_field(&wheel) {
|
||||
let mut shares = if wheel.zoom == 1.0 { Vec::new() } else { split_at(takers, at, Wheel { scroll: Vec2::ZERO, ..wheel }, focus.taker, armed) };
|
||||
@@ -371,7 +433,8 @@ mod tests {
|
||||
let outer = WheelTaker::new(1u8, rect(200.0)).vertical(true).scrolls(true).room(WheelRoom::new(Vec2::splat(50.0), Vec2::splat(50.0)));
|
||||
let inner = WheelTaker::new(2u8, rect(100.0)).vertical(true).scrolls(true).room(WheelRoom::new(Vec2::ZERO, Vec2::splat(30.0)));
|
||||
let at = pos2(10.0, 10.0);
|
||||
let owner = |y| split(&[outer, inner], at, wheel(0.0, y), WheelFocus::new(None), None).first().map(|(o, _)| *o);
|
||||
let owner =
|
||||
|y| split(&[outer, inner], at, wheel(0.0, y), WheelFocus::new(None), None, &mut WheelGesture::default(), 0.0).first().map(|(o, _)| *o);
|
||||
assert_eq!(owner(7.0), Some(1), "no room toward positive: the outer takes it");
|
||||
assert_eq!(owner(-7.0), Some(2), "room toward negative: the inner keeps it");
|
||||
}
|
||||
@@ -381,8 +444,9 @@ mod tests {
|
||||
let canvas = WheelTaker::new(1u8, rect(300.0)).horizontal(true).vertical(true).zoom(true);
|
||||
let field = WheelTaker::new(2u8, Rect::from_min_size(pos2(400.0, 0.0), Vec2::splat(20.0))).vertical(true).gated(true).field(true);
|
||||
let at = pos2(10.0, 10.0);
|
||||
let owners =
|
||||
|wheel: Wheel, focus: WheelFocus<u8>| split(&[canvas, field], at, wheel, focus, None).iter().map(|(o, _)| *o).collect::<Vec<_>>();
|
||||
let owners = |wheel: Wheel, focus: WheelFocus<u8>| {
|
||||
split(&[canvas, field], at, wheel, focus, None, &mut WheelGesture::default(), 0.0).iter().map(|(o, _)| *o).collect::<Vec<_>>()
|
||||
};
|
||||
let focused = WheelFocus::new(Some(2));
|
||||
assert_eq!(owners(wheel(0.0, 5.0), WheelFocus::new(None)), [1], "no focus: the canvas under the pointer");
|
||||
assert_eq!(owners(wheel(0.0, 5.0), focused), [2], "the focused field, away from the pointer");
|
||||
@@ -401,12 +465,12 @@ mod tests {
|
||||
let view = WheelTaker::new(2u8, rect(200.0)).horizontal(true).zoom(true);
|
||||
let zone = WheelTaker::new(3u8, rect(100.0)).zooms_view(true);
|
||||
let at = pos2(10.0, 10.0);
|
||||
let shares = split(&[region, view, zone], at, wheel(0.0, 5.0), WheelFocus::new(None), None);
|
||||
let shares = split(&[region, view, zone], at, wheel(0.0, 5.0), WheelFocus::new(None), None, &mut WheelGesture::default(), 0.0);
|
||||
assert_eq!(shares.len(), 1);
|
||||
assert_eq!((shares[0].0, shares[0].1.scroll.y, shares[0].1.zooms), (2, 5.0, true), "the view zooms by the vertical share");
|
||||
let shares = split(&[region, zone], at, wheel(0.0, 5.0), WheelFocus::new(None), None);
|
||||
let shares = split(&[region, zone], at, wheel(0.0, 5.0), WheelFocus::new(None), None, &mut WheelGesture::default(), 0.0);
|
||||
assert_eq!(shares.iter().map(|(o, w)| (*o, w.zooms)).collect::<Vec<_>>(), [(1, false)], "no zoom taker: the zone is passed over");
|
||||
let shares = split(&[region, view, zone], at, wheel(4.0, 0.0), WheelFocus::new(None), None);
|
||||
let shares = split(&[region, view, zone], at, wheel(4.0, 0.0), WheelFocus::new(None), None, &mut WheelGesture::default(), 0.0);
|
||||
assert_eq!(shares.iter().map(|(o, w)| (*o, w.zooms)).collect::<Vec<_>>(), [(2, false)], "the horizontal share passes the zone");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
//! The crop frame's geometry: resizing and fitting into the canvas.
|
||||
|
||||
use craft_behavior::geometry::{BoxPart, CropBox};
|
||||
use craft_behavior::geometry::{AspectHold, BoxPart, CropBox};
|
||||
use kurbo::{Point, Rect, Size, Vec2};
|
||||
|
||||
#[test]
|
||||
fn handles_resize_with_shift_alt_and_a_ratio() {
|
||||
let d = Vec2::new;
|
||||
let resize = |r: Rect, part: BoxPart, by: Vec2, ratio: Option<f64>, alt: bool| CropBox::upright(r).resized(part, by, ratio, alt).rect;
|
||||
let resize = |r: Rect, part: BoxPart, by: Vec2, ratio: Option<f64>, alt: bool| {
|
||||
CropBox::upright(r).resized(part, by, ratio.map_or(AspectHold::Free, AspectHold::Ratio), alt).rect
|
||||
}; // P3(tools-w15): tl.T41
|
||||
let r = Rect::new(20.0, 20.0, 100.0, 60.0);
|
||||
assert_eq!(resize(r, BoxPart::Edge(1), d(20.0, 10.0), None, false), Rect::new(20.0, 20.0, 120.0, 60.0));
|
||||
assert_eq!(resize(r, BoxPart::Corner(2), d(40.0, 10.0), None, false), Rect::new(20.0, 20.0, 140.0, 70.0));
|
||||
|
||||
@@ -31,7 +31,7 @@ pub mod system;
|
||||
pub use catalog::{Catalog, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch};
|
||||
pub use env::{FontEnv, Os, font_dirs, font_store_dir, office_font_dirs};
|
||||
pub use fontconfig::fontconfig_dirs;
|
||||
pub use scan::{FaceInfo, LocalizedName, Source, is_font_file, style_italic, style_weight, style_width};
|
||||
pub use scan::{FaceInfo, LocalizedName, Outlines, Source, is_font_file, style_italic, style_weight, style_width};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -32,6 +32,31 @@ pub struct LocalizedName {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// The kind of outlines a face draws: the first of its outline tables found.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum Outlines {
|
||||
/// `glyf` table.
|
||||
TrueType,
|
||||
/// `CFF ` table.
|
||||
Cff,
|
||||
/// `CFF2` table.
|
||||
Cff2,
|
||||
/// `VARC` table (composite variable glyphs).
|
||||
Composite,
|
||||
}
|
||||
|
||||
impl Outlines {
|
||||
/// The outlines of a face that has the tables `has` reports, in the order of the outline
|
||||
/// tables: `glyf`, `CFF `, `CFF2`, `VARC`. `None` when it has none: a face with none (outlines
|
||||
/// in Apple's `hvgl` table, bitmaps only) draws nothing and is left out.
|
||||
pub(crate) fn of(has: impl Fn(&[u8; 4]) -> bool) -> Option<Self> {
|
||||
[(b"glyf", Self::TrueType), (b"CFF ", Self::Cff), (b"CFF2", Self::Cff2), (b"VARC", Self::Composite)]
|
||||
.into_iter()
|
||||
.find_map(|(tag, kind)| has(tag).then_some(kind))
|
||||
}
|
||||
}
|
||||
|
||||
/// One face of an installed or added font: one face of a file, or one named instance of a
|
||||
/// variable font.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -65,6 +90,8 @@ pub struct FaceInfo {
|
||||
pub variations: Vec<([u8; 4], f32)>,
|
||||
/// The face has variation axes.
|
||||
pub variable: bool,
|
||||
/// The kind of outlines the face draws.
|
||||
pub outlines: Outlines,
|
||||
/// The OS/2 `fsType` embedding permissions (0 without an OS/2 table).
|
||||
pub fs_type: u16,
|
||||
/// The OS/2 code page bits (`ulCodePageRange1`, `ulCodePageRange2`).
|
||||
@@ -106,9 +133,6 @@ const MAX_INSTANCES: usize = 512;
|
||||
pub(crate) const MAX_FACES: u32 = 256;
|
||||
/// The largest table the scan reads.
|
||||
const MAX_TABLE: u32 = 1 << 20;
|
||||
/// Tables holding outlines a renderer draws. A face with none of them (outlines in Apple's `hvgl`
|
||||
/// table, bitmaps only) draws nothing and is left out.
|
||||
const OUTLINE_TABLES: [&[u8; 4]; 4] = [b"glyf", b"CFF ", b"CFF2", b"VARC"];
|
||||
|
||||
pub(crate) fn norm(s: &str) -> String {
|
||||
s.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect()
|
||||
@@ -220,7 +244,7 @@ fn sort_dedup(v: &mut Vec<String>) {
|
||||
|
||||
/// The faces `font` (face `index` of its file) offers: the face itself, then the named instances
|
||||
/// of a variable font. Empty when it has no family name.
|
||||
pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, index: u32, path: Option<&Path>, source: Source) -> Vec<Face> {
|
||||
pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, outlines: Outlines, index: u32, path: Option<&Path>, source: Source) -> Vec<Face> {
|
||||
let Some(family) = name(font, &[StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME]) else { return vec![] };
|
||||
let style = name(font, &[StringId::TYPOGRAPHIC_SUBFAMILY_NAME, StringId::SUBFAMILY_NAME]).unwrap_or_else(|| "Regular".into());
|
||||
let typo_family = localized(font, StringId::TYPOGRAPHIC_FAMILY_NAME);
|
||||
@@ -301,6 +325,7 @@ pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, index: u32, path: Option<&P
|
||||
italic: selection_italic || style_italic(&style),
|
||||
variations: vec![],
|
||||
variable: !axes.is_empty(),
|
||||
outlines,
|
||||
fs_type,
|
||||
code_pages,
|
||||
path: path.map(Path::to_path_buf),
|
||||
@@ -391,8 +416,8 @@ pub(crate) fn face_count(data: &[u8]) -> u32 {
|
||||
pub(crate) fn data_faces(data: &[u8], max_faces: u32, path: Option<&Path>, source: Source) -> Vec<Face> {
|
||||
(0..face_count(data).min(max_faces))
|
||||
.filter_map(|i| Some((i, skrifa::FontRef::from_index(data, i).ok()?)))
|
||||
.filter(|(_, f)| OUTLINE_TABLES.iter().any(|t| f.table_data(skrifa::Tag::new(t)).is_some()))
|
||||
.flat_map(|(i, f)| font_faces(&f, i, path, source))
|
||||
.filter_map(|(i, f)| Some((i, Outlines::of(|t| f.table_data(skrifa::Tag::new(t)).is_some())?, f)))
|
||||
.flat_map(|(i, outlines, f)| font_faces(&f, outlines, i, path, source))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -447,9 +472,7 @@ fn reader_faces(mut file: impl std::io::Read + std::io::Seek, max_faces: u32, ma
|
||||
let tables = usize::from(u16::from_be_bytes(dir.get(4..6)?.try_into().ok()?));
|
||||
let records = read_at(u64::from(start) + 12, tables * 16)?;
|
||||
let records: Vec<&[u8]> = records.as_chunks::<16>().0.iter().map(|r| r.as_slice()).collect();
|
||||
if !records.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) {
|
||||
return None;
|
||||
}
|
||||
let outlines = Outlines::of(|t| records.iter().any(|r| r.starts_with(t)))?;
|
||||
let mut table = |tag: &[u8; 4]| -> Option<Vec<u8>> {
|
||||
let rec = records.iter().find(|r| r.starts_with(tag))?;
|
||||
let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?);
|
||||
@@ -467,7 +490,7 @@ fn reader_faces(mut file: impl std::io::Read + std::io::Seek, max_faces: u32, ma
|
||||
}
|
||||
let refs: Vec<(&[u8; 4], &[u8])> = tables.iter().map(|(t, d)| (*t, d.as_slice())).collect();
|
||||
let font = sfnt_of(&refs)?;
|
||||
Some(font_faces(&skrifa::FontRef::new(&font).ok()?, index, Some(path), source))
|
||||
Some(font_faces(&skrifa::FontRef::new(&font).ok()?, outlines, index, Some(path), source))
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
|
||||
@@ -45,6 +45,11 @@ impl Folder {
|
||||
Folder { accents: true, ..self }
|
||||
}
|
||||
|
||||
/// Whether the locale is Turkic (`tr`, `az`): `I` folds to `ı` and `İ` to `i`.
|
||||
pub fn turkic(&self) -> bool {
|
||||
self.turkic
|
||||
}
|
||||
|
||||
/// `s` folded, with the map back to `s`.
|
||||
pub fn fold(&self, s: &str) -> Folded {
|
||||
let nfkd = DecomposingNormalizerBorrowed::new_nfkd();
|
||||
|
||||
@@ -2,17 +2,20 @@
|
||||
//!
|
||||
//! A label's `&` marker, written in its words row (`&File`), names the letter. Without one the letter is the
|
||||
//! label's first letter not yet used in the level, so a translated label needs no extra work. Letters are ASCII
|
||||
//! letters and digits, the keys the keyboard reports as such, and upper case.
|
||||
//! letters and digits, the keys the keyboard reports as such, and upper case in the folder's language.
|
||||
|
||||
use craft_i18n::Folder;
|
||||
|
||||
/// The label without its `&` marker, and the letter the first marker names. `&&` is a literal ampersand, a
|
||||
/// marker before something other than an ASCII letter or digit names no letter, and later markers are dropped.
|
||||
pub fn marked(label: &str) -> (String, Option<char>) {
|
||||
let (text, mark) = marked_at(label);
|
||||
pub fn marked(label: &str, folder: &Folder) -> (String, Option<char>) {
|
||||
let (text, mark) = marked_at(label, folder);
|
||||
(text, mark.map(|(letter, _)| letter))
|
||||
}
|
||||
|
||||
/// [`marked`] with the character index of the marked letter in the returned text.
|
||||
pub fn marked_at(label: &str) -> (String, Option<(char, usize)>) {
|
||||
pub fn marked_at(label: &str, folder: &Folder) -> (String, Option<(char, usize)>) {
|
||||
let _ = folder; // P3(top-w2): tp.T9
|
||||
let mut text = String::with_capacity(label.len());
|
||||
let mut mark = None;
|
||||
let mut at = 0;
|
||||
@@ -37,8 +40,8 @@ pub fn marked_at(label: &str) -> (String, Option<(char, usize)>) {
|
||||
/// without its markers. A `&` marker wins; a label whose marked letter an earlier label holds, and a label without a
|
||||
/// marker, takes the first letter or digit of its text not yet used, trying the first character of each word before
|
||||
/// the others.
|
||||
pub fn assign(labels: &[&str]) -> Vec<Option<(char, usize)>> {
|
||||
let parsed: Vec<(String, Option<(char, usize)>)> = labels.iter().map(|label| marked_at(label)).collect();
|
||||
pub fn assign(labels: &[&str], folder: &Folder) -> Vec<Option<(char, usize)>> {
|
||||
let parsed: Vec<(String, Option<(char, usize)>)> = labels.iter().map(|label| marked_at(label, folder)).collect();
|
||||
let mut used: Vec<char> = Vec::new();
|
||||
let mut out: Vec<Option<(char, usize)>> = Vec::with_capacity(parsed.len());
|
||||
for (_, mark) in &parsed {
|
||||
|
||||
@@ -115,11 +115,17 @@ fn run(stop: &AtomicBool, scale: f32) -> Result<Capture, ScreenError> {
|
||||
backend::capture(stop, scale)
|
||||
}
|
||||
|
||||
#[cfg(not(all(unix, not(target_os = "macos"), not(target_arch = "wasm32"))))]
|
||||
#[cfg(not(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), target_arch = "wasm32")))]
|
||||
fn run(stop: &AtomicBool, _scale: f32) -> Result<Capture, ScreenError> {
|
||||
backend::capture(stop).map(Capture::Images)
|
||||
}
|
||||
|
||||
/// The browser's EyeDropper: the one colour the user picks, as [`Capture::Color`].
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn run(_stop: &AtomicBool, _scale: f32) -> Result<Capture, ScreenError> {
|
||||
todo!("dl.K78")
|
||||
}
|
||||
|
||||
/// The scale a monitor image gets: the app's native pixels per point, or 1 when it has none.
|
||||
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
|
||||
fn usable_scale(scale: f32) -> f32 {
|
||||
@@ -545,7 +551,7 @@ mod backend {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), target_os = "macos", windows)))]
|
||||
#[cfg(not(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), target_os = "macos", windows, target_arch = "wasm32")))]
|
||||
mod backend {
|
||||
use super::{AtomicBool, ScreenError, ScreenImage};
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
mod work_area;
|
||||
|
||||
#[cfg(feature = "ui")]
|
||||
pub use work_area::{TASKBAR, fits};
|
||||
pub use work_area::{TASKBAR, WindowState, fits, visible_part};
|
||||
|
||||
pub use craft_host::target::{Backend, DesktopKind};
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! egui doesn't expose the monitor's work area (the screen less the taskbar, Dock or panel), only
|
||||
//! the monitor's size. [`TASKBAR`] is the room kept free at the monitor's bottom edge.
|
||||
|
||||
use egui::Vec2;
|
||||
use egui::{Rect, Vec2, ViewportInfo};
|
||||
|
||||
/// Room kept free at the monitor's bottom edge for a taskbar or Dock egui can't see (the Windows
|
||||
/// taskbar is 40–48 pt tall; a bottom Dock about as much).
|
||||
@@ -16,3 +16,29 @@ pub const TASKBAR: f32 = 48.0;
|
||||
pub fn fits(outer: Vec2, monitor: Vec2) -> bool {
|
||||
outer.x <= monitor.x + 0.5 && outer.y <= monitor.y - TASKBAR + 0.5
|
||||
}
|
||||
|
||||
/// How the window is shown.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum WindowState {
|
||||
/// Neither maximized nor full screen.
|
||||
Normal,
|
||||
/// Maximized.
|
||||
Maximized,
|
||||
/// Full screen.
|
||||
FullScreen,
|
||||
}
|
||||
|
||||
impl WindowState {
|
||||
/// The state `info` reports.
|
||||
pub fn of(info: &ViewportInfo) -> Self {
|
||||
let _ = info;
|
||||
todo!("tp.T12")
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of `content` that is visible on a monitor of size `monitor` for a window in `state` with inner rect
|
||||
/// `inner`; the whole of `content` when the monitor or the position is unknown.
|
||||
pub fn visible_part(content: Rect, monitor: Option<Vec2>, inner: Option<Rect>, state: WindowState) -> Rect {
|
||||
let _ = (content, monitor, inner, state);
|
||||
todo!("tp.T12")
|
||||
}
|
||||
|
||||
@@ -102,6 +102,16 @@ impl Prefix {
|
||||
pub fn var_name(self) -> String {
|
||||
format!("{}_TITLEBAR", self.0)
|
||||
}
|
||||
|
||||
/// The environment variable that picks the caption style: `<PREFIX>_CAPTION_STYLE`.
|
||||
pub fn caption_style_var(self) -> String {
|
||||
format!("{}_CAPTION_STYLE", self.0)
|
||||
}
|
||||
|
||||
/// The environment variable that picks the caption layout: `<PREFIX>_CAPTION_LAYOUT`.
|
||||
pub fn caption_layout_var(self) -> String {
|
||||
format!("{}_CAPTION_LAYOUT", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Who draws the window frame. Superseded by [`policy::Frame`]; kept for apps that have not moved.
|
||||
|
||||
@@ -33,11 +33,20 @@ use other as imp;
|
||||
|
||||
pub use imp::{hide_app, hide_other_apps, install_app_menu, system_title};
|
||||
|
||||
/// Called when an item is chosen: the item's `id` and, when a key-down chose it, the modifiers
|
||||
/// held. The platform calls it between frames from the event that chose the item, on the main
|
||||
/// Called when an item is chosen: the item's `id` and how it was chosen ([`Chosen`]). The platform calls it between frames from the event that chose the item, on the main
|
||||
/// thread. An id the app does not know belongs to a platform item (Services, Zoom, …), which the
|
||||
/// platform already handled.
|
||||
pub type Handler = Arc<dyn Fn(&str, Option<Held>) + Send + Sync>;
|
||||
pub type Handler = Arc<dyn Fn(&str, Chosen) + Send + Sync>;
|
||||
|
||||
/// How a menu item was chosen: by a key equivalent or a click, and the modifiers held then.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Chosen {
|
||||
/// A key-down chose the item.
|
||||
pub key_down: bool,
|
||||
/// The modifiers held when it was chosen.
|
||||
pub held: Held,
|
||||
}
|
||||
|
||||
/// The modifier keys held with a key-down.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
|
||||
@@ -29,7 +29,7 @@ use objc2::{MainThreadMarker, sel};
|
||||
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSEventType};
|
||||
use objc2_foundation::{NSBundle, NSLocale, NSObjectProtocol, NSString};
|
||||
|
||||
use super::{Bar, Handler, Held, Item, Menu, MenuKind, Node, Options, Platform, Shortcut};
|
||||
use super::{Bar, Chosen, Handler, Held, Item, Menu, MenuKind, Node, Options, Platform, Shortcut};
|
||||
|
||||
/// Set by [`Installed::install`]: there is one full menu bar per process.
|
||||
static INSTALLED: AtomicBool = AtomicBool::new(false);
|
||||
@@ -70,7 +70,10 @@ fn handle_event(e: MenuEvent) {
|
||||
// A copy, so nothing is locked while the app's handler runs.
|
||||
let handler = lock(&ROUTE).clone();
|
||||
if let Some(handler) = handler {
|
||||
handler(e.id.as_ref(), held);
|
||||
let mut chosen = Chosen::default(); // P3(top-w1): tp.T6
|
||||
chosen.key_down = held.is_some();
|
||||
chosen.held = held.unwrap_or_default();
|
||||
handler(e.id.as_ref(), chosen);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -135,7 +135,7 @@ pub struct Decision {
|
||||
/// the desktop's own. A browser draws no frame code ([`Frame::Native`]). A tool window's frame is
|
||||
/// [`tool_frame`], whatever `pref` and `env` say.
|
||||
pub fn decide(os: Os, runtime: Runtime, backend: Backend, desktop: &Desktop, kind: WindowKind, pref: TitleBarPref, env: Option<&str>) -> Decision {
|
||||
decide_with(&Inputs { os, runtime, backend, desktop, kind, pref, env }, &layout::default_layout)
|
||||
decide_with(&Inputs { os, runtime, backend, desktop, kind, pref, env, caption_style: None, caption_layout: None }, &layout::default_layout)
|
||||
}
|
||||
|
||||
/// What a decision reads.
|
||||
@@ -147,12 +147,17 @@ struct Inputs<'a> {
|
||||
kind: WindowKind,
|
||||
pref: TitleBarPref,
|
||||
env: Option<&'a str>,
|
||||
/// The caption family override (`<PREFIX>_CAPTION_STYLE`).
|
||||
caption_style: Option<&'a str>,
|
||||
/// The caption layout override (`<PREFIX>_CAPTION_LAYOUT`).
|
||||
caption_layout: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// `layout` supplies the caption layout for a desktop kind; it is called only when the frame comes
|
||||
/// out integrated.
|
||||
fn decide_with(inputs: &Inputs<'_>, layout: &dyn Fn(DesktopKind) -> Layout) -> Decision {
|
||||
let Inputs { os, runtime, backend, desktop, kind, pref, env } = *inputs;
|
||||
let Inputs { os, runtime, backend, desktop, kind, pref, env, caption_style, caption_layout } = *inputs;
|
||||
let _ = (caption_style, caption_layout); // P3(panels-w2): pn.C11
|
||||
let overridden = crate::parse_override(env);
|
||||
if kind == WindowKind::Tool {
|
||||
return Decision { frame: tool_frame(os, runtime), overridden, desktop: desktop.clone() };
|
||||
@@ -233,7 +238,7 @@ pub fn decide_for_kind(prefix: Prefix, backend: Backend, kind: WindowKind, pref:
|
||||
let env = std::env::var(prefix.var_name()).or_else(|_| std::env::var(Prefix::default().var_name())).ok();
|
||||
let desktop =
|
||||
if os == Os::Linux { Desktop::detect(backend) } else { Desktop { kind: DesktopKind::Other, ssd: None, gtk_theme: None, icon_theme: None } };
|
||||
let inputs = Inputs { os, runtime, backend, desktop: &desktop, kind, pref, env: env.as_deref() };
|
||||
let inputs = Inputs { os, runtime, backend, desktop: &desktop, kind, pref, env: env.as_deref(), caption_style: None, caption_layout: None }; // P3(panels-w2): pn.C11
|
||||
decide_with(&inputs, &|kind| desktop_layout(os, kind))
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user