mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-24 19:41:51 +01:00
Contract stubs: craft-print, craft-review, craft-automation, craft-color-ui, craft-dialogs
This commit is contained in:
34 files changed
+1335
-83
No files matched your search
@@ -21,7 +21,7 @@ default = []
|
||||
# The egui parts: the Actions panel, the control channel's server side (screenshots, synthetic
|
||||
# input) and `ui` stories. Without it the crate has no egui: `ControlOptions`, `ControlClient`,
|
||||
# `Params` and the recorded actions' model and files.
|
||||
ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui"]
|
||||
ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-host"] # P3(pdf-shell-w2): WF-W17
|
||||
# The Actions panel's and the Agents page's stories and mock, and the integration binary `tests/it`.
|
||||
screen-testing = ["ui", "agents", "craft-ui/testing"]
|
||||
# Agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file an
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//! `ui.inspect`: the reported widgets of a window's access tree, and the lookup of the one node a click or a focus
|
||||
//! names.
|
||||
|
||||
use craft_ui::runtime::egui::access::{AccessTree, Declared, NodeKey};
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use egui::ViewportId;
|
||||
use serde_json::Value;
|
||||
|
||||
/// The node a method names: its id or its label.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum NodeTarget {
|
||||
/// The node's id.
|
||||
Id(u64),
|
||||
/// The node's label, matched case-insensitively.
|
||||
Label(String),
|
||||
}
|
||||
|
||||
impl NodeTarget {
|
||||
/// The node `params` name (`id` or `label`), or none when they name none.
|
||||
pub fn from_params(params: &Value) -> Result<Option<NodeTarget>, String> {
|
||||
let _ = params;
|
||||
todo!("SH-C15")
|
||||
}
|
||||
}
|
||||
|
||||
/// The one reported, enabled node of `tree` that declares `action` and that `target` names; an error names none,
|
||||
/// several, disabled or undeclared.
|
||||
pub fn resolve(tree: &AccessTree, target: &NodeTarget, action: Declared) -> Result<NodeKey, String> {
|
||||
let _ = (tree, target, action);
|
||||
todo!("SH-C15")
|
||||
}
|
||||
|
||||
/// `inspect {query?, role?, focused?, limit?=500}`: the reply `{widgets, count, truncated}` over the reported nodes
|
||||
/// of `viewport`'s access tree, in tree order.
|
||||
pub fn inspect(host: &WindowHost, viewport: ViewportId, params: &Value) -> Result<Value, String> {
|
||||
let _ = (host, viewport, params);
|
||||
todo!("SH-C15")
|
||||
}
|
||||
@@ -20,7 +20,7 @@ use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotRequest, screenshot_reply};
|
||||
use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotParams, ScreenshotRequest, screenshot_reply};
|
||||
use crate::synthetic::TARGET_CHANGED;
|
||||
|
||||
/// A reply: the JSON object the transport writes as one line.
|
||||
@@ -119,6 +119,8 @@ pub enum Reply {
|
||||
token: u64,
|
||||
/// File to write the PNG to, or `None` to inline it.
|
||||
path: Option<String>,
|
||||
/// The part of the window to capture, in points; `None` captures the whole window.
|
||||
region: Option<egui::Rect>,
|
||||
/// The viewport to capture.
|
||||
viewport: egui::ViewportId,
|
||||
},
|
||||
@@ -132,8 +134,8 @@ pub enum Reply {
|
||||
impl Reply {
|
||||
/// A `ui.screenshot` reply for `token` of `viewport`, writing the PNG to `path` or inlining it
|
||||
/// when `None`.
|
||||
pub fn screenshot(token: u64, path: Option<String>, viewport: egui::ViewportId) -> Self {
|
||||
Self::Screenshot { token, path, viewport }
|
||||
pub fn screenshot(token: u64, params: ScreenshotParams, viewport: egui::ViewportId) -> Self {
|
||||
Self::Screenshot { token, path: params.path, region: params.region, viewport }
|
||||
}
|
||||
|
||||
/// `Done` with the [`result_reply`] of a method's result.
|
||||
@@ -197,7 +199,8 @@ impl ControlChannel {
|
||||
}
|
||||
Reply::AfterInput => self.input_waiters.push(reply),
|
||||
Reply::AfterJob(job) => self.job_waiters.push((job, reply)),
|
||||
Reply::Screenshot { token, path, viewport } => {
|
||||
Reply::Screenshot { token, path, region: _, viewport } => {
|
||||
// P3(pdf-shell-w2): SH-C18 (the request carries the region)
|
||||
if let Err((reply, e)) = self.captures.admit(ScreenshotRequest { token, path, viewport, reply, document, settle_ms }, motion::now()) {
|
||||
let _ = reply.send(json!({"ok": false, "error": e}));
|
||||
}
|
||||
@@ -265,7 +268,7 @@ impl ControlChannel {
|
||||
pub fn finish_captures(&mut self, finished: Vec<Finished>, write: &mut crate::screenshot::PngWriter<'_>) {
|
||||
for f in finished {
|
||||
let reply = match f.result {
|
||||
Ok(image) => screenshot_reply(f.token, image, f.path.as_deref(), write),
|
||||
Ok(image) => screenshot_reply(f.token, image, None, f.path.as_deref(), write), // P3(pdf-shell-w2): SH-C18 (`None` until the request carries the region)
|
||||
Err(e) => json!({"ok": false, "error": e}),
|
||||
};
|
||||
if let Some(tx) = f.reply {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
//! `ui.dock.apply`: one dock action applied to the app's workspace, and the workspace's `ui.inspect` listing.
|
||||
|
||||
use std::hash::Hash;
|
||||
|
||||
use craft_behavior::dock::Workspace;
|
||||
use craft_ui::docking::DockPanels;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
|
||||
/// `ui.dock.apply {action}`: deserializes one dock action and applies it to `workspace` with the permissions `panels`
|
||||
/// gives, as the dock area does. It returns `Ok({applied: [...]})`, the panels the action closed, in group order; an
|
||||
/// error is the dock error's text. `None` for any other method.
|
||||
pub fn dock_method<P: Clone + Eq + Hash + Serialize + DeserializeOwned>(
|
||||
workspace: &mut Workspace<P>,
|
||||
panels: &dyn DockPanels<P>,
|
||||
locked: bool,
|
||||
method: &str,
|
||||
params: &Value,
|
||||
) -> Option<Result<Value, String>> {
|
||||
let _ = (workspace, panels, locked, method, params);
|
||||
todo!("CH-C22")
|
||||
}
|
||||
|
||||
/// The `dock` field of the app's one `ui.inspect`: the workspace as JSON.
|
||||
pub fn inspect<P: Serialize>(workspace: &Workspace<P>) -> Value {
|
||||
let _ = workspace;
|
||||
todo!("CH-C22")
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! `ui.pick`: answers the next file picker of a running app.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// `None` for any method other than `ui.pick`. `ui.pick` takes exactly one of `{files: [path, ..]}`, `{folder: path}`,
|
||||
/// `{save: path}` or `{cancel: true}` and answers through `Files::answer_next` with `Picked::Paths` or `Cancelled`.
|
||||
pub fn pick_method(files: &dyn craft_host::Files, method: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
let _ = (files, method, params);
|
||||
todo!("WF-W17")
|
||||
}
|
||||
@@ -21,12 +21,18 @@ pub mod agents;
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod ui;
|
||||
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod access; // P3(pdf-shell-w2): SH-C15
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod args;
|
||||
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
|
||||
pub mod control;
|
||||
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
|
||||
pub mod dialogs;
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod dock; // P3(pdf-shell-w2): CH-C22
|
||||
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
|
||||
pub mod files; // P3(pdf-shell-w2): WF-W17
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod profiler;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -39,6 +45,8 @@ pub mod security;
|
||||
pub mod synthetic;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod trace;
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod window; // P3(pdf-shell-w2): CH-C23
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod client;
|
||||
|
||||
@@ -23,6 +23,7 @@ use std::time::{Duration, Instant};
|
||||
use base64::Engine as _;
|
||||
use craft_ui::runtime::windows::{ScreenshotFacts, ScreenshotSlot, WindowHost};
|
||||
use egui::{ColorImage, ViewportId};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::control::ControlResponse;
|
||||
|
||||
@@ -678,6 +679,24 @@ pub fn encode_png(width: usize, height: usize, rgba: &[u8]) -> Result<Vec<u8>, S
|
||||
/// authorized workspace. `Err` is the reply's error text.
|
||||
pub type PngWriter<'a> = dyn FnMut(&str, &[u8]) -> Result<(), String> + 'a;
|
||||
|
||||
/// A validated `ui.screenshot`: where the PNG goes and which part of the window it shows.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ScreenshotParams {
|
||||
/// File to write the PNG to, or `None` to inline it.
|
||||
pub path: Option<String>,
|
||||
/// The part of the window to capture as `[x0, y0, x1, y1]` in points, finite and ordered; `None` captures the
|
||||
/// whole window.
|
||||
pub region: Option<egui::Rect>,
|
||||
}
|
||||
|
||||
impl ScreenshotParams {
|
||||
/// `{path?, region?}`, no other fields.
|
||||
pub fn from_params(params: &Value) -> Result<ScreenshotParams, String> {
|
||||
let _ = params;
|
||||
todo!("SH-C18")
|
||||
}
|
||||
}
|
||||
|
||||
/// The reply for a finished image:
|
||||
/// - an image over [`MAX_IMAGE_BYTES`] as RGBA (or whose size overflows):
|
||||
/// `{"ok": false, "error": "screenshot {token} failed: the image exceeds the {MAX_IMAGE_BYTES / 1 MiB} MiB encode budget"}`;
|
||||
@@ -689,7 +708,14 @@ pub type PngWriter<'a> = dyn FnMut(&str, &[u8]) -> Result<(), String> + 'a;
|
||||
/// - an encode or write error `e`: `{"ok": false, "error": e}`.
|
||||
///
|
||||
/// Flatten the pixels to RGBA and drop the image before encoding, so the two copies don't overlap.
|
||||
pub fn screenshot_reply(token: u64, image: Arc<ColorImage>, path: Option<&str>, write: &mut PngWriter<'_>) -> ControlResponse {
|
||||
pub fn screenshot_reply(
|
||||
token: u64,
|
||||
image: Arc<ColorImage>,
|
||||
region: Option<egui::Rect>,
|
||||
path: Option<&str>,
|
||||
write: &mut PngWriter<'_>,
|
||||
) -> ControlResponse {
|
||||
let _ = region; // P3(pdf-shell-w2): SH-C18 (the writer crops the image to it)
|
||||
let [w, h] = image.size;
|
||||
let Some(bytes) = w.checked_mul(h).and_then(|n| n.checked_mul(4)).filter(|&n| n <= MAX_IMAGE_BYTES) else {
|
||||
return serde_json::json!({
|
||||
|
||||
@@ -24,6 +24,7 @@ use craft_ui::runtime::windows::{Released, WindowHost};
|
||||
use egui::{Pos2, Vec2, ViewportId, pos2, vec2};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::access::NodeTarget;
|
||||
use crate::protocol::{BUTTONS, KEY_MODIFIERS, Params};
|
||||
|
||||
/// Most clicks one `ui.click` may ask for (`count`).
|
||||
@@ -117,12 +118,42 @@ fn key(p: &Params<'_>) -> Result<Option<Key>, String> {
|
||||
p.choice("key", "key", &[])?.map(|name| Key::parse(name).ok_or_else(|| format!("unknown key `{name}`"))).transpose()
|
||||
}
|
||||
|
||||
/// Where a `ui.click` goes.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ClickTarget {
|
||||
/// A position.
|
||||
At(At),
|
||||
/// A node of the access tree.
|
||||
Node(NodeTarget),
|
||||
}
|
||||
|
||||
/// A validated `ui.focus`: moves the focus to a node of the access tree.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Focus {
|
||||
/// The node that takes the focus.
|
||||
pub target: NodeTarget,
|
||||
}
|
||||
|
||||
impl Focus {
|
||||
/// `{id | label}`: the node to focus.
|
||||
pub fn from_params(params: &Value) -> Result<Focus, String> {
|
||||
let _ = params;
|
||||
todo!("SH-C16")
|
||||
}
|
||||
|
||||
/// Sends the focus request for the node to `viewport`.
|
||||
pub fn inject(&self, host: &WindowHost, viewport: ViewportId) -> Result<(), String> {
|
||||
let _ = (host, viewport);
|
||||
todo!("SH-C16")
|
||||
}
|
||||
}
|
||||
|
||||
/// A validated `ui.click`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Click {
|
||||
/// Target position.
|
||||
pub at: At,
|
||||
/// Where the click goes: a position or a node of the access tree.
|
||||
pub target: ClickTarget,
|
||||
/// The button pressed.
|
||||
pub button: PointerButton,
|
||||
/// Number of clicks (2 is a double click).
|
||||
@@ -145,7 +176,7 @@ impl Click {
|
||||
return Err(format!("`count` must be at most {MAX_CLICKS} (got {count})"));
|
||||
}
|
||||
Ok(Self {
|
||||
at: At::from_params(&p)?,
|
||||
target: ClickTarget::At(At::from_params(&p)?), // P3(pdf-shell-w2): SH-C16
|
||||
button: button(&p)?.unwrap_or(PointerButton::Primary),
|
||||
count,
|
||||
mods: p.modifiers(&KEY_MODIFIERS)?,
|
||||
@@ -156,7 +187,8 @@ 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);
|
||||
let ClickTarget::At(at) = &self.target else { todo!("SH-C16") }; // P3(pdf-shell-w2): SH-C16
|
||||
host.inject_click(viewport, at.resolve(map)?, self.button, count, self.mods, self.hold);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
//! `ui.window`: window commands through the framework's one window-command path.
|
||||
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use egui::ViewportId;
|
||||
use serde_json::Value;
|
||||
|
||||
/// `ui.window {maximized: bool}` sends `WindowAction::SetMaximized` through `WindowHost::act` and returns `Ok({})`, or
|
||||
/// `Err` when `act` returns false (no window commands, as on wasm). `None` for any other method. It keeps no state.
|
||||
pub fn window_method(host: &WindowHost, viewport: ViewportId, method: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
let _ = (host, viewport, method, params);
|
||||
todo!("CH-C23")
|
||||
}
|
||||
@@ -496,7 +496,12 @@ impl Component for SwatchPair<'_> {
|
||||
match shown.color.same() {
|
||||
Some(color) if shown.ring => paint_ring(&draw, at, *color, style),
|
||||
color => {
|
||||
draw.swatch_well(at, style.radius, color.copied());
|
||||
// P3(pdf-comments-w5): CM-C25 (`swatch_well` takes a `WellFill`)
|
||||
draw.swatch_well(
|
||||
at,
|
||||
style.radius,
|
||||
color.copied().map_or(craft_ui::primitives::WellFill::Mixed, craft_ui::primitives::WellFill::Color),
|
||||
);
|
||||
draw.stroke(&PaintShape::Rect(at, style.radius), StrokeWidth::Thin, style.mark);
|
||||
draw.stroke(&outline(at, style), StrokeWidth::Thin, style.edge);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use craft_ui::choice::SwatchTable;
|
||||
use craft_ui::contract::{Bind, Held, NoValue, Outcome, Pattern, ShowContainer as _};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use egui::{Response, Ui};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -23,6 +24,10 @@ pub struct SwatchPaletteOutput {
|
||||
/// The pick of this pass as one `Set` of the swatch's colour; `None` when nothing was picked. The palette has
|
||||
/// already written it to its binding.
|
||||
pub edit: Option<EditEvent<Srgba>>,
|
||||
/// The request of the Other… row for the host's colour picker, when it was pressed this pass.
|
||||
pub pick_color: Option<ColorRequest>,
|
||||
/// Every swatch click of this pass, also a click on the colour already bound, which files no `edit`.
|
||||
pub picked: Option<Srgba>,
|
||||
}
|
||||
|
||||
impl Outcome for SwatchPaletteOutput {
|
||||
@@ -47,19 +52,55 @@ impl Outcome for SwatchPaletteOutput {
|
||||
#[derive(Pattern)]
|
||||
pub struct SwatchPalette<'a> {
|
||||
label: Label,
|
||||
color: Bind<'a, Srgba>,
|
||||
color: PaletteColor<'a>,
|
||||
swatches: &'a [(Label, Srgba)],
|
||||
}
|
||||
|
||||
/// What a palette binds: a colour, or a colour that may be none.
|
||||
enum PaletteColor<'a> {
|
||||
Color(Bind<'a, Srgba>),
|
||||
Optional(Bind<'a, Mixed<Option<Srgba>>>),
|
||||
}
|
||||
|
||||
impl<'a> SwatchPalette<'a> {
|
||||
/// A palette named `label` of `swatches`, each a name and a colour, choosing the colour bound to `color`.
|
||||
pub fn new(label: impl Into<Label>, color: Bind<'a, Srgba>, swatches: &'a [(Label, Srgba)]) -> Self {
|
||||
SwatchPalette { label: label.into(), color, swatches }
|
||||
SwatchPalette { label: label.into(), color: PaletteColor::Color(color), swatches }
|
||||
}
|
||||
|
||||
/// A palette over a colour that may be none, bound as `Mixed::Same(None)`: no swatch is selected for `Same(None)`
|
||||
/// or `Mixed`, and a pick writes `Mixed::Same(Some(colour))`.
|
||||
pub fn optional(label: impl Into<Label>, color: Bind<'a, Mixed<Option<Srgba>>>, swatches: &'a [(Label, Srgba)]) -> Self {
|
||||
SwatchPalette { label: label.into(), color: PaletteColor::Optional(color), swatches }
|
||||
}
|
||||
|
||||
/// An Other… row, keyed `key` and named `label`, that asks the host's colour picker.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w5): CM-C26
|
||||
pub fn other(self, key: impl Into<String>, label: impl Into<Label>) -> Self {
|
||||
let _ = (key.into(), label.into());
|
||||
todo!("CM-C26")
|
||||
}
|
||||
|
||||
/// A row of recent `colors` under `caption`.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w5): CM-C26
|
||||
pub fn recent(self, caption: impl Into<Label>, colors: &'a [Srgba]) -> Self {
|
||||
let _ = (caption.into(), colors);
|
||||
todo!("CM-C26")
|
||||
}
|
||||
|
||||
/// Shows the palette.
|
||||
pub fn show(self, ui: &mut Ui) -> SwatchPaletteOutput {
|
||||
let SwatchPalette { label, color, swatches } = self;
|
||||
// P3(pdf-comments-w5): CM-C26 (the optional binding)
|
||||
let color = match color {
|
||||
PaletteColor::Color(color) => color,
|
||||
PaletteColor::Optional(optional) => {
|
||||
let _ = optional;
|
||||
todo!("CM-C26")
|
||||
}
|
||||
};
|
||||
let mut held = Held::new(color);
|
||||
let name = label.clone();
|
||||
let mut shown = Stack::new().show(ui, |ui, cx| {
|
||||
@@ -82,6 +123,6 @@ impl<'a> SwatchPalette<'a> {
|
||||
Some(EditEvent::set(Mixed::Same(before), after, Arc::from(name.as_str()), None))
|
||||
})
|
||||
.flatten();
|
||||
SwatchPaletteOutput { response: shown.output, edit }
|
||||
SwatchPaletteOutput { response: shown.output, edit, pick_color: None, picked: None }
|
||||
}
|
||||
}
|
||||
@@ -200,6 +200,9 @@ struct Inner {
|
||||
last_folder: HashMap<String, PathBuf>,
|
||||
/// A panel is on screen or queued (mirrored from the panels each pump).
|
||||
panel_busy: bool,
|
||||
/// The answers `Files::answer_next` gave, which the panels answer the next requests with.
|
||||
#[allow(dead_code)] // P3(pdf-workflows-w4): WF-W16
|
||||
forced: VecDeque<Answer>,
|
||||
}
|
||||
|
||||
impl FileService {
|
||||
@@ -213,6 +216,7 @@ impl FileService {
|
||||
answered: VecDeque::new(),
|
||||
last_folder: HashMap::new(),
|
||||
panel_busy: false,
|
||||
forced: VecDeque::new(),
|
||||
}));
|
||||
let (to_panels, requests) = std::sync::mpsc::channel();
|
||||
let panels = FilePanels {
|
||||
@@ -541,6 +545,13 @@ impl Files for FileService {
|
||||
inner.answered.remove(at).map(|a| a.picked)
|
||||
}
|
||||
|
||||
/// Answers the next pick with `picked` instead of showing a panel, through the settling a native answer passes.
|
||||
/// `Picked::Contents` has no `Answer` form: it is `Err(FileError::Unsupported)`.
|
||||
fn answer_next(&self, picked: Picked) -> Result<(), FileError> {
|
||||
let _ = picked;
|
||||
todo!("WF-W16")
|
||||
}
|
||||
|
||||
// A ticket still pending leaves `pending`, so the answer the panel gives later is dropped by `finish`.
|
||||
fn forget(&self, id: PickId) {
|
||||
let mut inner = lock(&self.inner);
|
||||
|
||||
@@ -11,7 +11,9 @@ use craft_ui::contract::{
|
||||
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, FormDialog, HostRequests, Param, ParamRows, set_color_field, set_param_field};
|
||||
use craft_ui::patterns::form_dialogs::{
|
||||
DialogFields, FieldValue, FormDialog, HostRequests, PagerStep, PanePager, Param, ParamRows, set_color_field, set_param_field,
|
||||
};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::focus::{ActivateKeys, KeepKeys, KeyUse};
|
||||
use craft_ui::runtime::overlay::CloseReason;
|
||||
@@ -19,9 +21,9 @@ use craft_ui::runtime::requests::HostAnswer;
|
||||
use craft_ui::sections::{DialogRole, FooterButton, Section};
|
||||
use craft_ui::style::{ComponentStyle, Corners, RuleKind, StyleCx, SurfaceKind};
|
||||
use egui::load::SizedTexture;
|
||||
use egui::{Pos2, Rect, Response, Ui, Vec2, pos2, vec2};
|
||||
use egui::{Pos2, Rect, Response, TextureId, Ui, Vec2, pos2, vec2};
|
||||
|
||||
use super::panel::{MOST_COPIES, PrintPanel};
|
||||
use super::panel::{DriverControls, MOST_COPIES, PrintPanel};
|
||||
use super::{Duplex, Printer, Settings, State};
|
||||
|
||||
craft_ui::words! {
|
||||
@@ -62,6 +64,64 @@ pub struct PrintMarks {
|
||||
pub labels: bool,
|
||||
}
|
||||
|
||||
/// How the print dialog is arranged.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum PrintLayout {
|
||||
/// The preview at the start edge, the printer panel and the sections at the end edge.
|
||||
#[default]
|
||||
Image,
|
||||
/// Printer Setup and the app's sections in a scrolling column, then the sheet preview, its pager, the readout and
|
||||
/// the notes at the end edge; no Done button.
|
||||
Document,
|
||||
}
|
||||
|
||||
/// What the sheet preview shows on the paper.
|
||||
#[derive(Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum SheetContent {
|
||||
/// One image box holding a picture; the box can be dragged.
|
||||
Image {
|
||||
/// The image box on the paper.
|
||||
image: egui::Rect,
|
||||
/// The picture of the document.
|
||||
picture: SizedTexture,
|
||||
},
|
||||
/// The pages placed on the sheet, clipped to the paper.
|
||||
Pages(Vec<SheetPage>),
|
||||
/// A message centred in the preview, with no paper.
|
||||
Message(Label),
|
||||
}
|
||||
|
||||
/// One page placed on a sheet.
|
||||
#[derive(Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct SheetPage {
|
||||
/// The page's corners on the paper, in paper points.
|
||||
pub corners: [Pos2; 4],
|
||||
/// The page's picture; none draws a muted stand-in with `number` centred.
|
||||
pub picture: Option<TextureId>,
|
||||
/// The part of the picture to draw.
|
||||
pub uv: egui::Rect,
|
||||
/// The page's number, shown on the stand-in.
|
||||
pub number: String,
|
||||
}
|
||||
|
||||
impl SheetPage {
|
||||
/// A page at `corners` with no picture, numbered `number`.
|
||||
pub fn new(corners: [Pos2; 4], number: impl Into<String>) -> Self {
|
||||
SheetPage { corners, picture: None, uv: Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), number: number.into() }
|
||||
}
|
||||
|
||||
/// The page's picture `id` and the part `uv` of it to draw.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P6
|
||||
pub fn picture(self, id: TextureId, uv: egui::Rect) -> Self {
|
||||
let _ = (id, uv);
|
||||
todo!("PO-P6")
|
||||
}
|
||||
}
|
||||
|
||||
/// What the app's layout says for this pass, in points.
|
||||
#[derive(Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
@@ -78,13 +138,71 @@ pub struct PrintSheet {
|
||||
pub marks: PrintMarks,
|
||||
/// The readout under the preview.
|
||||
pub readout: Label,
|
||||
/// What the sheet shows on the paper.
|
||||
pub content: SheetContent,
|
||||
/// The borders drawn around the pages, in paper points.
|
||||
pub borders: Vec<egui::Rect>,
|
||||
/// The cut lines, in paper points.
|
||||
pub cuts: Vec<[Pos2; 2]>,
|
||||
/// The notes under the readout.
|
||||
pub notes: Vec<Label>,
|
||||
}
|
||||
|
||||
impl PrintSheet {
|
||||
/// A sheet of `paper` with the image box `image` holding `picture`, `readout` under the preview, no printable area
|
||||
/// and no marks.
|
||||
pub fn new(paper: egui::Vec2, image: egui::Rect, picture: SizedTexture, readout: Label) -> Self {
|
||||
PrintSheet { paper, printable: None, image, picture, marks: PrintMarks::default(), readout }
|
||||
let content = SheetContent::Image { image, picture };
|
||||
PrintSheet {
|
||||
paper,
|
||||
printable: None,
|
||||
image,
|
||||
picture,
|
||||
marks: PrintMarks::default(),
|
||||
readout,
|
||||
content,
|
||||
borders: Vec::new(),
|
||||
cuts: Vec::new(),
|
||||
notes: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A sheet of `paper` holding `pages`, with `readout` under the preview.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P6
|
||||
pub fn pages(paper: Vec2, pages: Vec<SheetPage>, readout: Label) -> Self {
|
||||
let _ = (paper, pages, readout);
|
||||
todo!("PO-P6")
|
||||
}
|
||||
|
||||
/// A preview showing `message` instead of a sheet, with `readout` under it.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P6
|
||||
pub fn message(paper: Vec2, message: Label, readout: Label) -> Self {
|
||||
let _ = (paper, message, readout);
|
||||
todo!("PO-P6")
|
||||
}
|
||||
|
||||
/// The borders drawn around the pages.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P6
|
||||
pub fn borders(self, borders: Vec<egui::Rect>) -> Self {
|
||||
let _ = borders;
|
||||
todo!("PO-P6")
|
||||
}
|
||||
|
||||
/// The cut lines.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P6
|
||||
pub fn cuts(self, cuts: Vec<[Pos2; 2]>) -> Self {
|
||||
let _ = cuts;
|
||||
todo!("PO-P6")
|
||||
}
|
||||
|
||||
/// The notes under the readout.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P6
|
||||
pub fn notes(self, notes: Vec<Label>) -> Self {
|
||||
let _ = notes;
|
||||
todo!("PO-P6")
|
||||
}
|
||||
|
||||
/// The printable area of the paper.
|
||||
@@ -117,6 +235,22 @@ impl PrintSection {
|
||||
pub fn new(title: impl Into<Label>, params: Vec<Param>) -> Self {
|
||||
Self { title: title.into(), params }
|
||||
}
|
||||
|
||||
/// Collapses the section when `open` is false, through `Section::initially_open`.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P7
|
||||
pub fn folded(self, open: bool) -> Self {
|
||||
let _ = open;
|
||||
todo!("PO-P7")
|
||||
}
|
||||
|
||||
/// A title-row button; a press is filed as `HostRequests::request_action(id)`.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P7
|
||||
pub fn button(self, id: impl Into<String>, label: impl Into<Label>, enabled: bool) -> Self {
|
||||
let _ = (id.into(), label.into(), enabled);
|
||||
todo!("PO-P7")
|
||||
}
|
||||
}
|
||||
|
||||
/// How a print dialog finished.
|
||||
@@ -378,6 +512,18 @@ pub struct PrintDialog<'a> {
|
||||
/// The host's answers to the dialog's requests.
|
||||
#[prop]
|
||||
answers: Vec<HostAnswer>,
|
||||
/// How the dialog is arranged.
|
||||
#[prop]
|
||||
layout: PrintLayout,
|
||||
/// The printer-driver controls the panel offers.
|
||||
#[prop]
|
||||
driver: DriverControls,
|
||||
/// The layout sets two-sided printing: the Two-sided row is left out.
|
||||
#[prop]
|
||||
duplex_by_layout: bool,
|
||||
/// The pager under the sheet preview in the `Document` layout.
|
||||
#[prop]
|
||||
preview_pager: Option<PanePager>,
|
||||
}
|
||||
|
||||
/// What [`PrintDialog::show`] returns.
|
||||
@@ -397,6 +543,8 @@ pub struct PrintDialogOutput {
|
||||
pub refresh: bool,
|
||||
/// The dialog's requests of the host.
|
||||
pub requests: HostRequests,
|
||||
/// The pager press made this pass.
|
||||
pub preview_step: Option<PagerStep>,
|
||||
}
|
||||
|
||||
impl Outcome for PrintDialogOutput {
|
||||
@@ -422,13 +570,33 @@ impl<'a> PrintDialog<'a> {
|
||||
discovering: false,
|
||||
ready: false,
|
||||
answers: Vec::new(),
|
||||
layout: PrintLayout::Image,
|
||||
driver: DriverControls::None,
|
||||
duplex_by_layout: false,
|
||||
preview_pager: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the dialog. The body reports the drag events and the Refresh press of its last run only, so a measuring run
|
||||
/// adds none; a second pass of a frame has no new input and reports none.
|
||||
pub fn show(self, ui: &mut Ui) -> PrintDialogOutput {
|
||||
let PrintDialog { mut settings, printers, fields, sheet, sections, opened, busy, discovering, ready, answers } = self;
|
||||
let PrintDialog {
|
||||
mut settings,
|
||||
printers,
|
||||
fields,
|
||||
sheet,
|
||||
sections,
|
||||
opened,
|
||||
busy,
|
||||
discovering,
|
||||
ready,
|
||||
answers,
|
||||
layout,
|
||||
driver,
|
||||
duplex_by_layout,
|
||||
preview_pager,
|
||||
} = self;
|
||||
let _ = (layout, driver, duplex_by_layout, preview_pager); // P3(pdf-print-ocr-w1): PO-P5
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<PrintDialogWords>();
|
||||
let mut form = FormDialog::new(words.title.clone(), fields)
|
||||
@@ -483,7 +651,7 @@ impl<'a> PrintDialog<'a> {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
PrintDialogOutput { response: shown.response, closed: shown.closed, finish, moved, refresh, requests: shown.requests }
|
||||
PrintDialogOutput { response: shown.response, closed: shown.closed, finish, moved, refresh, requests: shown.requests, preview_step: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -578,6 +746,92 @@ impl HostedPrint {
|
||||
&mut self.requests
|
||||
}
|
||||
|
||||
/// The dialog's arrangement.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn layout(self, layout: PrintLayout) -> Self {
|
||||
let _ = layout;
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// Replaces the app's sections.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn set_sections(&mut self, sections: Vec<PrintSection>) {
|
||||
let _ = sections;
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// The printer state.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn state(&self) -> &State {
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// The printer state, for the app to change.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn state_mut(&mut self) -> &mut State {
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// The printer-driver controls the panel offers.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn set_driver(&mut self, driver: DriverControls) {
|
||||
let _ = driver;
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// Whether the layout sets two-sided printing, leaving out the Two-sided row.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn set_duplex_by_layout(&mut self, on: bool) {
|
||||
let _ = on;
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// The pager under the sheet preview in the `Document` layout.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn set_preview_pager(&mut self, pager: Option<PanePager>) {
|
||||
let _ = pager;
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// The pager press since the last call.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn take_preview_step(&mut self) -> Option<PagerStep> {
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// The id of the section button pressed since the last call.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn take_action(&mut self) -> Option<String> {
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// The dialog holds OK until the app answers it with `answer_ok`.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn held_ok(self) -> Self {
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// Holds OK until the app answers it with `answer_ok`.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn hold_ok(&mut self) {
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// The held OK's answer when OK was pressed, once.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn take_ok(&mut self) -> Option<PrintAnswer> {
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// Answers the held OK: `Ok` closes the dialog, `Err` keeps it open and shows the refusal.
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
|
||||
pub fn answer_ok(&mut self, answer: Result<(), Label>) {
|
||||
let _ = answer;
|
||||
todo!("PO-P8")
|
||||
}
|
||||
|
||||
/// The answer of the dialog as it stands.
|
||||
fn answer(&self, finish: PrintFinish) -> PrintAnswer {
|
||||
PrintAnswer { finish, settings: self.state.settings.clone(), fields: self.fields.clone() }
|
||||
@@ -668,6 +922,7 @@ impl StackDialog for HostedPrint {
|
||||
map.insert("copies".to_owned(), settings.copies.into());
|
||||
map.insert("duplex".to_owned(), duplex_json(settings.duplex));
|
||||
map.insert("grayscale".to_owned(), settings.grayscale.into());
|
||||
map.insert("collate".to_owned(), settings.collate.into());
|
||||
if let Some(form) = &self.json_form {
|
||||
form(&self.fields, &mut map);
|
||||
}
|
||||
@@ -688,6 +943,7 @@ impl StackDialog for HostedPrint {
|
||||
}
|
||||
"duplex" => self.state.settings.duplex = duplex_from_json(&value).ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?,
|
||||
"grayscale" => self.state.settings.grayscale = value.as_bool().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?,
|
||||
"collate" => self.state.settings.collate = value.as_bool().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?,
|
||||
_ => {
|
||||
let section =
|
||||
self.sections.iter().find(|section| section.params.iter().any(|param| param.key == field || param.unit_key() == Some(field)));
|
||||
|
||||
@@ -6,8 +6,11 @@ mod panel;
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
pub use dialog::{HostedPrint, PrintAnswer, PrintDialog, PrintDialogOutput, PrintDialogWords, PrintFinish, PrintMarks, PrintSection, PrintSheet};
|
||||
pub use panel::{PrintPanel, PrintPanelOutput, PrintWords};
|
||||
pub use dialog::{
|
||||
HostedPrint, PrintAnswer, PrintDialog, PrintDialogOutput, PrintDialogWords, PrintFinish, PrintLayout, PrintMarks, PrintSection, PrintSheet,
|
||||
SheetContent, SheetPage,
|
||||
};
|
||||
pub use panel::{Destinations, DriverControls, PrintPanel, PrintPanelOutput, PrintWords};
|
||||
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::runtime::frame::request_repaint_after;
|
||||
@@ -29,12 +32,14 @@ pub struct Printer {
|
||||
pub label: String,
|
||||
/// Whether it is the system's default printer.
|
||||
pub default: bool,
|
||||
/// The note shown when the printer's own dialog decides copies, collate, two-sided and colour.
|
||||
pub own_dialog: Option<String>,
|
||||
}
|
||||
|
||||
impl Printer {
|
||||
/// A printer queue named `name`, with no label, not the default.
|
||||
pub fn new(name: impl Into<String>) -> Self {
|
||||
Printer { name: name.into(), label: String::new(), default: false }
|
||||
Printer { name: name.into(), label: String::new(), default: false, own_dialog: None }
|
||||
}
|
||||
|
||||
/// The text the dialog shows for the printer.
|
||||
@@ -50,6 +55,15 @@ impl Printer {
|
||||
self.default = default;
|
||||
self
|
||||
}
|
||||
|
||||
/// Marks the printer's own dialog as deciding copies, collate, two-sided and colour; the panel disables those
|
||||
/// controls and shows `note` under them while the printer is chosen.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P3
|
||||
pub fn own_dialog(self, note: impl Into<String>) -> Self {
|
||||
let _ = note;
|
||||
todo!("PO-P3")
|
||||
}
|
||||
}
|
||||
|
||||
/// The text the dialog shows for each of `printers`, in order: its label, or its name when it has
|
||||
@@ -110,6 +124,16 @@ pub enum Duplex {
|
||||
ShortEdge,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
/// Where a print job goes.
|
||||
pub enum Destination {
|
||||
/// The printer with this name.
|
||||
Printer(String),
|
||||
/// Save as PDF.
|
||||
File,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
/// What the user chose for one print job.
|
||||
@@ -122,11 +146,15 @@ pub struct Settings {
|
||||
pub duplex: Option<Duplex>,
|
||||
/// Print in grayscale.
|
||||
pub grayscale: bool,
|
||||
/// Where the job goes.
|
||||
pub destination: Destination,
|
||||
/// Collate the copies.
|
||||
pub collate: bool,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self { printer: String::new(), copies: 1, duplex: None, grayscale: false }
|
||||
Self { printer: String::new(), copies: 1, duplex: None, grayscale: false, destination: Destination::Printer(String::new()), collate: true }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! `PrintPanel`: the printer, copies, two-sided and grayscale choices of one print job.
|
||||
|
||||
use super::{Duplex, Printer, Settings, shown_names};
|
||||
use super::{Destination, Duplex, Printer, Settings, shown_names};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, Entry, Held, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
@@ -34,9 +34,38 @@ craft_ui::words! {
|
||||
portrait: "printPanel.portrait" = "Portrait";
|
||||
landscape: "printPanel.landscape" = "Landscape";
|
||||
page_in_driver: "printPanel.pageInDriver" = "set in Print Settings…";
|
||||
collate: "printPanel.collate" = "Collate";
|
||||
properties: "printPanel.properties" = "Properties…";
|
||||
save_as_pdf: "printPanel.saveAsPdf" = "Save as PDF";
|
||||
default_mark: "printPanel.defaultMark" = "(default)";
|
||||
finding: "printPanel.finding" = "Finding printers…";
|
||||
}
|
||||
}
|
||||
|
||||
/// Which printer-driver controls the panel offers.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum DriverControls {
|
||||
/// None.
|
||||
#[default]
|
||||
None,
|
||||
/// Properties… after Refresh; its press is `settings_clicked`.
|
||||
Properties,
|
||||
/// Print Settings…, Portrait and Landscape and the page line.
|
||||
Page,
|
||||
}
|
||||
|
||||
/// Which destinations the printer list offers.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Destinations {
|
||||
/// The printers only.
|
||||
#[default]
|
||||
Printers,
|
||||
/// The printers, then Save as PDF at the end of the list.
|
||||
PrintersAndFile,
|
||||
}
|
||||
|
||||
/// What the print panel reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
@@ -46,7 +75,7 @@ pub struct PrintPanelOutput {
|
||||
/// The Refresh button was pressed this pass: the caller starts printer discovery again.
|
||||
pub refresh: bool,
|
||||
/// A printer was chosen this pass: its name. The caller takes the paper from the new printer's driver.
|
||||
pub printer_chosen: Option<String>,
|
||||
pub printer_chosen: Option<Destination>,
|
||||
/// Print Settings… was pressed this pass: the caller opens the driver's own dialog.
|
||||
pub settings_clicked: bool,
|
||||
/// Portrait (`false`) or Landscape (`true`) was pressed this pass: the caller turns the driver settings.
|
||||
@@ -83,7 +112,13 @@ pub struct PrintPanel<'a> {
|
||||
/// The driver controls (Print Settings…, Portrait and Landscape, the page line) are shown: the caller can ask a
|
||||
/// printer driver for its page.
|
||||
#[prop]
|
||||
driver: bool,
|
||||
driver: DriverControls,
|
||||
/// Which destinations the list offers.
|
||||
#[prop]
|
||||
destinations: Destinations,
|
||||
/// The layout sets two-sided printing: the Two-sided row is left out.
|
||||
#[prop]
|
||||
duplex_by_layout: bool,
|
||||
/// The driver's paper in points, as the caller last took it.
|
||||
#[prop(quantity = "paper size the printer driver reports, in points")]
|
||||
page: Option<egui::Vec2>,
|
||||
@@ -95,12 +130,24 @@ pub struct PrintPanel<'a> {
|
||||
impl<'a> PrintPanel<'a> {
|
||||
/// The panel over `settings`, offering `printers`.
|
||||
pub fn new(settings: Bind<'a, Settings>, printers: &'a [Printer]) -> Self {
|
||||
PrintPanel { settings, printers, discovering: false, busy: false, driver: false, page: None, page_error: None }
|
||||
PrintPanel {
|
||||
settings,
|
||||
printers,
|
||||
discovering: false,
|
||||
busy: false,
|
||||
driver: DriverControls::None,
|
||||
destinations: Destinations::Printers,
|
||||
duplex_by_layout: false,
|
||||
page: None,
|
||||
page_error: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the panel.
|
||||
pub fn show(self, ui: &mut Ui) -> PrintPanelOutput {
|
||||
let PrintPanel { settings, printers, discovering, busy, driver, page, page_error } = self;
|
||||
let PrintPanel { settings, printers, discovering, busy, driver, destinations, duplex_by_layout, page, page_error } = self;
|
||||
let _ = (destinations, duplex_by_layout); // P3(pdf-print-ocr-w1): PO-P4
|
||||
let driver = driver == DriverControls::Page; // P3(pdf-print-ocr-w1): PO-P4
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<PrintWords>();
|
||||
let queues: Vec<Entry<String>> =
|
||||
@@ -127,7 +174,7 @@ impl<'a> PrintPanel<'a> {
|
||||
.show(ui);
|
||||
if let Some(name) = picked.value() {
|
||||
if *name != now.printer {
|
||||
printer_chosen = Some(name.clone());
|
||||
printer_chosen = Some(Destination::Printer(name.clone())); // P3(pdf-print-ocr-w1): PO-P4
|
||||
}
|
||||
now.printer.clone_from(name);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,8 @@ pub enum AnnotationKind {
|
||||
Attach,
|
||||
#[allow(missing_docs)]
|
||||
Highlight,
|
||||
/// A highlight drawn freehand.
|
||||
FreehandHighlight,
|
||||
#[allow(missing_docs)]
|
||||
Underline,
|
||||
#[allow(missing_docs)]
|
||||
@@ -154,6 +156,88 @@ pub struct Annotation {
|
||||
pub text: String,
|
||||
/// A locked annotation shows no handles.
|
||||
pub locked: bool,
|
||||
/// The width over height a corner resize keeps; `None` for a flat box.
|
||||
#[serde(default)]
|
||||
pub aspect: Option<f64>,
|
||||
/// Whether the host lets the annotation be reshaped.
|
||||
#[serde(default)]
|
||||
pub handle_rule: HandleRule,
|
||||
}
|
||||
|
||||
/// A named option for an annotation the host cannot reshape: under `FixedPoints` and `NoResize` the overlay shows no
|
||||
/// handle that would do nothing; the body still moves and selects.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub enum HandleRule {
|
||||
/// The kind's own rule decides.
|
||||
#[default]
|
||||
Free,
|
||||
/// The host keeps the points (dimension lines and polygons): no point handles and no box handles.
|
||||
FixedPoints,
|
||||
/// The host cannot resize the box (a callout with no readable box): no handles.
|
||||
NoResize,
|
||||
}
|
||||
|
||||
/// The knee of a callout stays at least this far from its box, in page units.
|
||||
pub const CALLOUT_KNEE_GAP: f64 = 12.0;
|
||||
|
||||
/// A move of at most this many page units is a slip, not a move.
|
||||
pub const SLIP_MOVE: f64 = 2.0;
|
||||
|
||||
/// A resize of at most this many page units is a slip, not a resize.
|
||||
pub const SLIP_RESIZE: f64 = 4.0;
|
||||
|
||||
/// The smallest side of a shape the tool keeps, in page units.
|
||||
pub const MIN_SHAPE: f64 = 2.0;
|
||||
|
||||
/// The Shift rule of a point drag, held from the neighbouring point.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ShiftLock {
|
||||
/// The segment snaps to 45 degree steps.
|
||||
#[default]
|
||||
Angle45,
|
||||
/// The segment stays level or plumb.
|
||||
LevelOrPlumb,
|
||||
}
|
||||
|
||||
/// `points` with the callout's point `i` moved to `to`: the knee (`i == 1`) moves along its knee line only and never
|
||||
/// nearer the box than [`CALLOUT_KNEE_GAP`]; every other point moves freely through [`reshaped`].
|
||||
#[allow(dead_code)] // P3(pdf-comments-w1): CM-C2
|
||||
pub fn callout_reshaped(rect: Rect, points: &[Point], i: usize, to: Point, lock: Option<ShiftLock>) -> Vec<Point> {
|
||||
let _ = (rect, points, i, to, lock);
|
||||
todo!("CM-C2")
|
||||
}
|
||||
|
||||
/// The width over height a corner resize of `annotation` keeps from `from` (with Shift); `None` for a flat box.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w1): CM-C3
|
||||
pub fn corner_aspect(annotation: &Annotation, from: Rect, shift: bool) -> Option<f64> {
|
||||
let _ = (annotation, from, shift);
|
||||
todo!("CM-C3")
|
||||
}
|
||||
|
||||
/// The box of `annotation`'s marker on `page`, clamped to the page; `None` when it has none.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w1): CM-C6
|
||||
pub fn marker_rect(annotation: &Annotation, page: Rect, icon_side: f64) -> Option<Rect> {
|
||||
let _ = (annotation, page, icon_side);
|
||||
todo!("CM-C6")
|
||||
}
|
||||
|
||||
/// The annotation the comment part, the hover outline and the marker hit at `at`, within `tolerance` page units.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w1): CM-C6
|
||||
pub fn pick_at(annotations: &[Annotation], at: Point, tolerance: f64, icon_side: f64, markers: &[(AnnotationId, Rect)]) -> Option<AnnotationId> {
|
||||
let _ = (annotations, at, tolerance, icon_side, markers);
|
||||
todo!("CM-C6")
|
||||
}
|
||||
|
||||
impl Annotation {
|
||||
/// The annotation as the in-flight `edit` leaves it, for the overlay's live paint.
|
||||
#[cfg(feature = "ui")]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w1): CM-C4
|
||||
pub fn edited(&self, edit: &AnnotationEdit) -> Option<Annotation> {
|
||||
let _ = edit;
|
||||
todo!("CM-C4")
|
||||
}
|
||||
}
|
||||
|
||||
impl Annotation {
|
||||
@@ -308,14 +392,13 @@ pub fn resized(rect: Rect, handle: (i8, i8), delta: Vec2, aspect: Option<f64>) -
|
||||
r.abs()
|
||||
}
|
||||
|
||||
/// `points` with point `i` moved to `to`; with `shift` the segment from its neighbour snaps to
|
||||
/// 45° steps.
|
||||
/// `points` with point `i` moved to `to`; with `lock` the segment from its neighbour is held to the rule.
|
||||
// pdfcraft: crates/ui-egui/src/tools/comments/geometry.rs:37 `reshaped`.
|
||||
pub fn reshaped(points: &[Point], i: usize, to: Point, shift: bool) -> Vec<Point> {
|
||||
pub fn reshaped(points: &[Point], i: usize, to: Point, lock: Option<ShiftLock>) -> Vec<Point> {
|
||||
let mut out = points.to_vec();
|
||||
let anchor = if i == 0 { points.get(1) } else { points.get(i - 1) };
|
||||
let to = match anchor {
|
||||
Some(&a) if shift => turn_to_45(a, to),
|
||||
Some(&a) if lock.is_some() => turn_to_45(a, to), // P3(pdf-comments-w1): CM-C5 (`LevelOrPlumb` is the writer's)
|
||||
_ => to,
|
||||
};
|
||||
if let Some(p) = out.get_mut(i) {
|
||||
@@ -368,4 +451,33 @@ pub enum AnnotationEdit {
|
||||
Selection(craft_behavior::SelectionChange<AnnotationId>),
|
||||
/// A double-click on a note or text box: the app opens its text for editing.
|
||||
Open(AnnotationId),
|
||||
/// A click or drag placement of a new annotation.
|
||||
Place(Placement),
|
||||
/// The Eraser erased along `path` with `radius` through these annotations.
|
||||
EraseAlong {
|
||||
/// The annotations the eraser reached.
|
||||
ids: Vec<AnnotationId>,
|
||||
/// The eraser's path, in page units.
|
||||
path: Vec<Point>,
|
||||
/// The eraser's radius, in page units.
|
||||
radius: f64,
|
||||
},
|
||||
}
|
||||
|
||||
/// Where a click or drag placed a new annotation: a Note, Attach or Caret at `at`; a TextBox with `size`; a Callout
|
||||
/// with its tip at `from` and its box at `at`.
|
||||
#[cfg(feature = "ui")]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Placement {
|
||||
/// The kind placed.
|
||||
pub kind: AnnotationKind,
|
||||
/// The page index.
|
||||
pub page: usize,
|
||||
/// The click point, or the box's corner.
|
||||
pub at: Point,
|
||||
/// The box's size, when the placement dragged one.
|
||||
pub size: Option<Vec2>,
|
||||
/// A callout's tip.
|
||||
pub from: Option<Point>,
|
||||
}
|
||||
@@ -21,6 +21,8 @@ fn annotation(id: u64, kind: AnnotationKind, rect: Rect) -> Annotation {
|
||||
stroke_width: 2.0,
|
||||
text: String::new(),
|
||||
locked: false,
|
||||
aspect: None, // P3(pdf-comments-w1): CM-C3
|
||||
handle_rule: crate::annotate::HandleRule::default(), // P3(pdf-comments-w1): CM-C30
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -86,6 +86,17 @@ impl ReviewStatus {
|
||||
[ReviewStatus::None, ReviewStatus::Accepted, ReviewStatus::Rejected, ReviewStatus::Cancelled, ReviewStatus::Completed];
|
||||
}
|
||||
|
||||
/// One reviewer's latest status on a thread.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ReviewerStatus {
|
||||
/// The reviewer's name.
|
||||
pub reviewer: String,
|
||||
/// The status the reviewer set.
|
||||
pub status: ReviewStatus,
|
||||
/// The text of the status reply.
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// An emoji reaction and who gave it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Reaction {
|
||||
@@ -128,6 +139,8 @@ pub struct CommentThread {
|
||||
pub messages: Vec<CommentMessage>,
|
||||
/// The thread's review status.
|
||||
pub status: ReviewStatus,
|
||||
/// Each reviewer's latest status, oldest first.
|
||||
pub statuses: Vec<ReviewerStatus>,
|
||||
/// Acrobat's per-comment checkmark.
|
||||
pub marked: bool,
|
||||
/// A locked thread can't be edited.
|
||||
@@ -141,6 +154,12 @@ impl CommentThread {
|
||||
pub fn replies(&self) -> usize {
|
||||
self.messages.len().saturating_sub(1)
|
||||
}
|
||||
|
||||
/// The latest status set by anyone; [`ReviewStatus::None`] when no reviewer set one.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w4): CM-C19
|
||||
pub fn status(&self) -> ReviewStatus {
|
||||
todo!("CM-C19")
|
||||
}
|
||||
}
|
||||
|
||||
/// What the panel hides (PdfCraft's Filter comments menu): a thread shows unless its type,
|
||||
@@ -197,12 +216,24 @@ pub enum CommentSort {
|
||||
Color,
|
||||
}
|
||||
|
||||
/// How threads on one page are ordered under the Page sort.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum PageOrder {
|
||||
/// By position on the page.
|
||||
#[default]
|
||||
Position,
|
||||
/// In document order.
|
||||
Document,
|
||||
}
|
||||
|
||||
/// The order of `threads` by `sort`, as indices: page then position on the page (top to bottom),
|
||||
/// author A–Z, newest first, kind (by `kind_name`, the reader's name of a kind), colour; ties keep
|
||||
/// document order. A plain comment sorts before every kind.
|
||||
// pdfcraft: crates/ui-egui/src/panels/comments_panel.rs:115 `show` (sorting),
|
||||
// `tools/comments/state.rs:297` `SortBy`.
|
||||
pub fn sort_threads(threads: &[CommentThread], sort: CommentSort, kind_name: impl Fn(AnnotationKind) -> String) -> Vec<usize> {
|
||||
pub fn sort_threads(threads: &[CommentThread], sort: CommentSort, page_order: PageOrder, kind_name: impl Fn(AnnotationKind) -> String) -> Vec<usize> {
|
||||
let _ = page_order; // P3(pdf-comments-w4): CM-C20
|
||||
let mut order: Vec<usize> = (0..threads.len()).collect();
|
||||
fn first(thread: &CommentThread) -> Option<&CommentMessage> {
|
||||
thread.messages.first()
|
||||
|
||||
@@ -10,6 +10,18 @@ pub const MAX_IMAGE_BYTES: usize = 4 << 20;
|
||||
/// JPEG decodes to about 48 MB; the limit keeps the decode job bounded).
|
||||
pub const MAX_IMAGE_SIDE: u32 = 8192;
|
||||
|
||||
/// The longest side a saved signature image keeps, in pixels.
|
||||
pub const MAX_SAVED_SIDE: u32 = 4096;
|
||||
|
||||
/// The most pixels a saved signature image keeps.
|
||||
pub const MAX_SAVED_PIXELS: u64 = 4 << 20;
|
||||
|
||||
/// The lightness (0 to 255) from which [`SignatureImage::remove_white_background`] treats a pixel as paper.
|
||||
pub const PAPER_CUTOFF: u8 = 245;
|
||||
|
||||
/// The width of the feathered edge below [`PAPER_CUTOFF`].
|
||||
pub const PAPER_FEATHER: u8 = 35;
|
||||
|
||||
/// The longest typed signature, in characters (PdfCraft `pdfcraft_fonts::MAX_SIGNATURE_CHARS`,
|
||||
/// `crates/fonts/src/script.rs:17`).
|
||||
pub const MAX_SIGNATURE_CHARS: usize = 256;
|
||||
@@ -72,6 +84,13 @@ impl SignatureImage {
|
||||
&self.rgba
|
||||
}
|
||||
|
||||
/// The image with paper white made transparent, with a feathered edge of `feather` below `cutoff`.
|
||||
#[allow(dead_code)] // P3(pdf-forms-w1): FM-PF4
|
||||
pub fn remove_white_background(&self, cutoff: u8, feather: u8) -> SignatureImage {
|
||||
let _ = (cutoff, feather);
|
||||
todo!("FM-PF4")
|
||||
}
|
||||
|
||||
/// The content key computed by [`new`](Self::new); equal images have equal keys.
|
||||
pub fn key(&self) -> u64 {
|
||||
self.key
|
||||
|
||||
@@ -7,7 +7,11 @@ mod tool;
|
||||
mod toolbar;
|
||||
mod words;
|
||||
|
||||
pub use overlay::{AnnotationOverlay, AnnotationOverlayStyle};
|
||||
pub use tool::{AnnotateTool, DEFAULT_COLOR, DEFAULT_STROKE_WIDTH, HIGHLIGHT_COLOR, NEW_ANNOTATION_FORM, TextQuads};
|
||||
pub use crate::annotate::ShiftLock;
|
||||
pub use overlay::{AnnotationOverlay, AnnotationOverlayStyle, BodyPaint};
|
||||
pub use tool::{
|
||||
AnnotateTool, DEFAULT_COLOR, DEFAULT_STROKE_WIDTH, DrawOptions, EmptyPress, EraseMode, FarNudge, HIGHLIGHT_COLOR, HandlesWhileDrawing,
|
||||
InkStrokes, MarkupPress, NEW_ANNOTATION_FORM, OpenOn, SelectOptions, TextQuads, ToggleMods,
|
||||
};
|
||||
pub use toolbar::{AnnotationToolbar, AnnotationToolbarOutput};
|
||||
pub use words::{AnnotateCommand, AnnotateWords, PALETTE};
|
||||
pub use words::{AnnotateCommand, AnnotateIcons, AnnotateWords, PALETTE};
|
||||
@@ -11,7 +11,7 @@ use egui::{CornerRadius, Pos2, Response};
|
||||
use kurbo::{Point, Rect};
|
||||
|
||||
use super::tool::{color32, corners};
|
||||
use crate::annotate::{Annotation, AnnotationHandle, AnnotationId, AnnotationKind, handles};
|
||||
use crate::annotate::{Annotation, AnnotationEdit, AnnotationHandle, AnnotationId, AnnotationKind, handles};
|
||||
|
||||
/// The ellipse inscribed in `rect`, as a closed run of page points.
|
||||
pub(super) fn ellipse_points(rect: Rect) -> Vec<Point> {
|
||||
@@ -98,6 +98,7 @@ fn paint_annotation(draw: &Draw<'_>, a: &Annotation, to_screen: &impl Fn(Point)
|
||||
draw.data_fill(&PaintShape::Rect(r, CornerRadius::ZERO), color);
|
||||
}
|
||||
}
|
||||
K::FreehandHighlight => todo!("CM-C1"),
|
||||
K::Underline | K::StrikeOut | K::Squiggly | K::ReplaceText => {
|
||||
for r in quads() {
|
||||
let y = if matches!(a.kind, K::StrikeOut | K::ReplaceText) { r.center().y } else { r.bottom() };
|
||||
@@ -188,12 +189,27 @@ pub struct AnnotationOverlay<'a> {
|
||||
common: Common,
|
||||
annotations: &'a [Annotation],
|
||||
selected: &'a [AnnotationId],
|
||||
/// Which bodies the overlay paints; the host paints the rest with the page.
|
||||
#[prop]
|
||||
bodies: BodyPaint<'a>,
|
||||
/// The in-flight edit, painted live.
|
||||
#[prop]
|
||||
live: Option<&'a AnnotationEdit>,
|
||||
}
|
||||
|
||||
/// Which bodies the overlay paints.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum BodyPaint<'a> {
|
||||
/// Every body.
|
||||
All,
|
||||
/// Only these annotations' bodies.
|
||||
Only(&'a [AnnotationId]),
|
||||
}
|
||||
|
||||
impl<'a> AnnotationOverlay<'a> {
|
||||
/// An overlay named `label` for `annotations`, with `selected` drawing handles.
|
||||
pub fn new(label: impl Into<Label>, annotations: &'a [Annotation], selected: &'a [AnnotationId]) -> Self {
|
||||
AnnotationOverlay { common: Common::new(), annotations, selected }.label(label)
|
||||
AnnotationOverlay { common: Common::new(), annotations, selected, bodies: BodyPaint::All, live: None }.label(label)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,6 +243,7 @@ impl Component for AnnotationOverlay<'_> {
|
||||
let painter = ui.content_painter(cx);
|
||||
let draw = ui.draw();
|
||||
let hairline = 1.0 / cx.response.ctx.pixels_per_point();
|
||||
let _ = (self.bodies, self.live); // P3(pdf-comments-w1): CM-C7, CM-C8
|
||||
for a in self.annotations {
|
||||
paint_annotation(&draw, a, &to_screen, (cx.style.text_size, cx.style.icon_side), hairline);
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ fn annotation(id: u64, kind: AnnotationKind, rect: Rect) -> Annotation {
|
||||
stroke_width: 2.0,
|
||||
text: String::new(),
|
||||
locked: false,
|
||||
aspect: None, // P3(pdf-comments-w1): CM-C3
|
||||
handle_rule: crate::annotate::HandleRule::default(), // P3(pdf-comments-w1): CM-C30
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,8 @@ use std::sync::Arc;
|
||||
use super::AnnotateWords;
|
||||
use super::overlay::ellipse_points;
|
||||
use crate::annotate::{
|
||||
Annotation, AnnotationEdit, AnnotationHandle, AnnotationHit, AnnotationId, AnnotationKind, AnnotationTool, hit, reshaped, resized,
|
||||
Annotation, AnnotationEdit, AnnotationHandle, AnnotationHit, AnnotationId, AnnotationKind, AnnotationTool, HandleRule, ShiftLock, hit, reshaped,
|
||||
resized,
|
||||
};
|
||||
|
||||
/// The page text between two page points as quads (four corners each).
|
||||
@@ -267,6 +268,203 @@ impl AnnotateTool {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a press on empty page does.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum EmptyPress {
|
||||
/// A selection rectangle.
|
||||
#[default]
|
||||
Marquee,
|
||||
/// The press is ignored (`ToolAction::Ignored`).
|
||||
PassThrough,
|
||||
}
|
||||
|
||||
/// The modifiers that toggle a selection.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ToggleMods {
|
||||
/// Shift.
|
||||
#[default]
|
||||
Shift,
|
||||
/// Shift or Command.
|
||||
ShiftOrCommand,
|
||||
}
|
||||
|
||||
/// What opens a note or text box.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum OpenOn {
|
||||
/// A double click on a note or text box.
|
||||
#[default]
|
||||
NotesAndTextBoxes,
|
||||
/// A double click on any annotation.
|
||||
Every,
|
||||
}
|
||||
|
||||
/// The modifiers that nudge a selection by the far step.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum FarNudge {
|
||||
/// Shift.
|
||||
#[default]
|
||||
Shift,
|
||||
/// Shift or Command.
|
||||
ShiftOrCommand,
|
||||
}
|
||||
|
||||
/// What a press on a handle does while a shape is being drawn.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum HandlesWhileDrawing {
|
||||
/// The press continues the drawing.
|
||||
#[default]
|
||||
Draw,
|
||||
/// The press edits through the handle.
|
||||
Edit,
|
||||
}
|
||||
|
||||
/// What a press on a text markup does.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum MarkupPress {
|
||||
/// The press selects the markup.
|
||||
#[default]
|
||||
Select,
|
||||
/// Only a click reports (`ToolAction::Ignored` otherwise).
|
||||
ClickOnly,
|
||||
}
|
||||
|
||||
/// The tool's named selection options; `Default` is today's behaviour.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct SelectOptions {
|
||||
/// What a press on empty page does.
|
||||
pub empty_press: EmptyPress,
|
||||
/// The modifiers that toggle a selection.
|
||||
pub toggle: ToggleMods,
|
||||
/// What opens a note or text box.
|
||||
pub open: OpenOn,
|
||||
/// The Shift rule of a point drag.
|
||||
pub shift_lock: ShiftLock,
|
||||
/// The modifiers that nudge by the far step.
|
||||
pub far_nudge: FarNudge,
|
||||
/// What a press on a handle does while drawing.
|
||||
pub handles_while_drawing: HandlesWhileDrawing,
|
||||
/// What a press on a text markup does.
|
||||
pub markup_press: MarkupPress,
|
||||
}
|
||||
|
||||
/// Whether ink strokes gather into one annotation per session or one per stroke.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum InkStrokes {
|
||||
/// One annotation per session.
|
||||
#[default]
|
||||
Session,
|
||||
/// One annotation per stroke.
|
||||
PerStroke,
|
||||
}
|
||||
|
||||
/// What the eraser removes.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum EraseMode {
|
||||
/// Whole strokes.
|
||||
#[default]
|
||||
Strokes,
|
||||
/// Along its path (`EraseAlong`).
|
||||
Path,
|
||||
}
|
||||
|
||||
/// The tool's named drawing options.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct DrawOptions {
|
||||
/// How ink strokes gather.
|
||||
pub ink: InkStrokes,
|
||||
/// What the eraser removes.
|
||||
pub erase: EraseMode,
|
||||
/// The eraser's radius, in screen points.
|
||||
pub eraser_radius: f32,
|
||||
}
|
||||
|
||||
impl Default for AnnotateTool {
|
||||
fn default() -> Self {
|
||||
Self::new(AnnotationTool::Select, 0)
|
||||
}
|
||||
}
|
||||
|
||||
impl AnnotateTool {
|
||||
/// A click on a comment part handed from the page: selects (with the toggle modifiers of [`SelectOptions`]) and, on
|
||||
/// the open count, opens.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w2): CM-C9
|
||||
pub fn click(&mut self, id: AnnotationId, mods: Mods, clicks: u32, words: &AnnotateWords) {
|
||||
let _ = (id, mods, clicks, words);
|
||||
todo!("CM-C9")
|
||||
}
|
||||
|
||||
/// The cursor over page point `at`, with the page-unit `tolerance` and `icon_side` the tool's reading holds.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w2): CM-C10
|
||||
pub fn cursor_at(&self, at: Point, tolerance: f64, icon_side: f64) -> Cursor {
|
||||
let _ = (at, tolerance, icon_side);
|
||||
todo!("CM-C10")
|
||||
}
|
||||
|
||||
/// The edit the gesture in flight would report, for the host's live paint.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w2): CM-C11
|
||||
pub fn in_flight(&self) -> Option<AnnotationEdit> {
|
||||
todo!("CM-C11")
|
||||
}
|
||||
|
||||
/// The points of the shape being drawn.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w2): CM-C11
|
||||
pub fn drawing(&self) -> &[Point] {
|
||||
todo!("CM-C11")
|
||||
}
|
||||
|
||||
/// Ends the shape being drawn.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w2): CM-C11
|
||||
pub fn finish_drawing(&mut self) {
|
||||
todo!("CM-C11")
|
||||
}
|
||||
|
||||
/// Takes back the last point of the shape being drawn; whether there was one.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w2): CM-C11
|
||||
pub fn undo_point(&mut self) -> bool {
|
||||
todo!("CM-C11")
|
||||
}
|
||||
|
||||
/// Drops the shape being drawn.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w2): CM-C11
|
||||
pub fn cancel_drawing(&mut self) {
|
||||
todo!("CM-C11")
|
||||
}
|
||||
|
||||
/// Snaps a caret to the page text through `snap`: the snapped point and its size.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w2): CM-C11
|
||||
pub fn caret_snap(self, snap: impl Fn(Point) -> Option<(Point, f64)> + Send + 'static) -> Self {
|
||||
let _ = snap;
|
||||
todo!("CM-C11")
|
||||
}
|
||||
|
||||
/// The tool's selection options.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w2): CM-C12
|
||||
pub fn select_options(self, options: SelectOptions) -> Self {
|
||||
let _ = options;
|
||||
todo!("CM-C12")
|
||||
}
|
||||
|
||||
/// The tool's drawing options.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w2): CM-C14
|
||||
pub fn draw_options(self, options: DrawOptions) -> Self {
|
||||
let _ = options;
|
||||
todo!("CM-C14")
|
||||
}
|
||||
}
|
||||
|
||||
/// The kinds the "New Annotation..." form places.
|
||||
const FORM_KINDS: [AnnotationKind; 8] = [
|
||||
AnnotationKind::Rectangle,
|
||||
@@ -334,6 +532,8 @@ impl AnnotateTool {
|
||||
stroke_width: self.width,
|
||||
text: String::new(),
|
||||
locked: false,
|
||||
aspect: None,
|
||||
handle_rule: HandleRule::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -490,7 +690,9 @@ fn edit_value(change: &Change, origin: Point, at: Point, mods: Mods) -> Annotati
|
||||
let aspect = (mods.shift && from.height() > 0.0).then(|| from.width() / from.height());
|
||||
AnnotationEdit::Resize { id: *target, rect: resized(*from, *handle, at - origin, aspect) }
|
||||
}
|
||||
Change::Reshape { target, index, from } => AnnotationEdit::Reshape { id: *target, points: reshaped(from, *index, at, mods.shift) },
|
||||
Change::Reshape { target, index, from } => {
|
||||
AnnotationEdit::Reshape { id: *target, points: reshaped(from, *index, at, mods.shift.then_some(ShiftLock::Angle45)) }
|
||||
} // P3(pdf-comments-w2): CM-C5
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
//! The toolbar's words and the annotation commands.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use craft_ui::runtime::commands::CommandState;
|
||||
|
||||
use crate::annotate::{AnnotationGroup, AnnotationKind, AnnotationTool};
|
||||
|
||||
/// The colours the toolbar offers, Acrobat's quick colours for comments: yellow, orange, red, pink, purple, blue,
|
||||
@@ -37,6 +41,7 @@ craft_ui::words! {
|
||||
kind_callout: "annotate.kindCallout" = "Callout";
|
||||
kind_attach: "annotate.kindAttach" = "Attachment";
|
||||
kind_highlight: "annotate.kindHighlight" = "Highlight";
|
||||
kind_freehand_highlight: "annotate.kindFreehandHighlight" = "Freehand highlight";
|
||||
kind_underline: "annotate.kindUnderline" = "Underline";
|
||||
kind_strike_out: "annotate.kindStrikeOut" = "Strikethrough";
|
||||
kind_squiggly: "annotate.kindSquiggly" = "Squiggly";
|
||||
@@ -92,6 +97,7 @@ impl AnnotateWords {
|
||||
K::Callout => self.kind_callout.as_str(),
|
||||
K::Attach => self.kind_attach.as_str(),
|
||||
K::Highlight => self.kind_highlight.as_str(),
|
||||
K::FreehandHighlight => self.kind_freehand_highlight.as_str(),
|
||||
K::Underline => self.kind_underline.as_str(),
|
||||
K::StrikeOut => self.kind_strike_out.as_str(),
|
||||
K::Squiggly => self.kind_squiggly.as_str(),
|
||||
@@ -159,6 +165,9 @@ pub enum AnnotateCommand {
|
||||
/// Highlight page text.
|
||||
#[command(label = "Highlight", icon = "brush")]
|
||||
Highlight,
|
||||
/// Highlight freehand.
|
||||
#[command(label = "Freehand highlight", icon = "brush")]
|
||||
FreehandHighlight,
|
||||
/// Underline page text.
|
||||
#[command(label = "Underline", icon = "text_underline")]
|
||||
Underline,
|
||||
@@ -219,6 +228,7 @@ impl AnnotateCommand {
|
||||
K::Callout => AnnotateCommand::Callout,
|
||||
K::Attach => AnnotateCommand::Attach,
|
||||
K::Highlight => AnnotateCommand::Highlight,
|
||||
K::FreehandHighlight => AnnotateCommand::FreehandHighlight,
|
||||
K::Underline => AnnotateCommand::Underline,
|
||||
K::StrikeOut => AnnotateCommand::StrikeOut,
|
||||
K::Squiggly => AnnotateCommand::Squiggly,
|
||||
@@ -235,4 +245,42 @@ impl AnnotateCommand {
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The command's state with the icon `icons` names for it: `CommandState::new()` with `icon` set when `icons` has
|
||||
/// one.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w1): CM-C31
|
||||
pub fn state(self, icons: &AnnotateIcons) -> CommandState {
|
||||
let _ = icons;
|
||||
todo!("CM-C31")
|
||||
}
|
||||
}
|
||||
|
||||
/// The icon an app gives each annotate command, by catalogue name or by the name of a registered app set; a command
|
||||
/// the set does not name keeps its framework icon.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct AnnotateIcons {
|
||||
icons: Vec<(AnnotateCommand, Cow<'static, str>)>,
|
||||
}
|
||||
|
||||
impl AnnotateIcons {
|
||||
/// A set that names no icon.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// The set with `icon` for `command`.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w1): CM-C31
|
||||
pub fn with(self, command: AnnotateCommand, icon: impl Into<Cow<'static, str>>) -> Self {
|
||||
let _ = (command, icon.into());
|
||||
todo!("CM-C31")
|
||||
}
|
||||
|
||||
/// The icon the set names for `command`, if any.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w1): CM-C31
|
||||
pub fn icon(&self, command: AnnotateCommand) -> Option<&str> {
|
||||
let _ = (command, &self.icons);
|
||||
todo!("CM-C31")
|
||||
}
|
||||
}
|
||||
@@ -19,12 +19,15 @@ mod stories;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use craft_behavior::Selection;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use craft_behavior::{Selection, Value};
|
||||
use craft_i18n::{DateStyle, DateTime, TimeZone};
|
||||
use craft_ui::contract::{Bind, CollectionEvent, NoValue, Outcome, Pattern, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, CollectionEvent, Entry, NoValue, Outcome, Pattern, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::notices::{Notice, NoticeLayout};
|
||||
use craft_ui::primitives::SubmitKey;
|
||||
use craft_ui::runtime::env::{AgeStyle, Env, EnvView, Label};
|
||||
use craft_ui::style::TypeRole;
|
||||
use craft_ui::text::TextField;
|
||||
@@ -32,7 +35,7 @@ use egui::{Pos2, Response, Ui};
|
||||
|
||||
use super::annotate::{AnnotateWords, PALETTE};
|
||||
use crate::annotate::AnnotationKind;
|
||||
use crate::comments::{CommentFilter, CommentSort, CommentThread, ReviewStatus, ThreadId, matches, sort_threads};
|
||||
use crate::comments::{CommentFilter, CommentSort, CommentThread, PageOrder, ReviewStatus, ThreadId, matches, sort_threads};
|
||||
|
||||
use list::{CardEvent, CardKey, CommentList, RowEntry, Rows};
|
||||
use menus::{card_menu, filter_menu, pages_menu, sort_menu};
|
||||
@@ -112,8 +115,12 @@ pub struct CommentsPanelState {
|
||||
pub filter: CommentFilter,
|
||||
/// The pages whose group is folded under the Page sort.
|
||||
pub collapsed_pages: Vec<usize>,
|
||||
/// The selected thread, if any.
|
||||
pub selected: Option<ThreadId>,
|
||||
/// The selected threads.
|
||||
pub selected: Selection<ThreadId>,
|
||||
/// The search box is open.
|
||||
pub search_open: bool,
|
||||
/// The thread the next `show` reveals, once.
|
||||
revealing: Option<ThreadId>,
|
||||
/// The message being edited inline: (thread, message index, text).
|
||||
pub editing: Option<(ThreadId, usize, String)>,
|
||||
/// The selected card's reply draft.
|
||||
@@ -132,11 +139,9 @@ struct Line {
|
||||
impl CommentsPanelState {
|
||||
/// Selects `thread` as a click on its card does, and unfolds its page group: for a comment
|
||||
/// the app selected elsewhere (on the page, or just added), whose card must be drawn.
|
||||
pub fn reveal(&mut self, thread: &CommentThread) {
|
||||
select_thread(self, thread.id);
|
||||
if let Some(page) = thread.anchor.page() {
|
||||
self.collapsed_pages.retain(|&folded| folded != page);
|
||||
}
|
||||
pub fn reveal(&mut self, thread: ThreadId) {
|
||||
select_thread(self, thread);
|
||||
self.revealing = Some(thread); // P3(pdf-comments-w4): CM-C21 (`show` unfolds the page group and takes it)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,7 +198,7 @@ pub enum CommentEdit {
|
||||
marked: bool,
|
||||
},
|
||||
/// A card was selected: the app selects the annotation on the page and scrolls to it.
|
||||
Select(ThreadId),
|
||||
Select(Vec<ThreadId>),
|
||||
/// Copy text of message `index`; the app puts it on the clipboard.
|
||||
#[non_exhaustive]
|
||||
CopyText {
|
||||
@@ -266,20 +271,80 @@ pub(crate) fn age_text(env: &EnvView<'_>, then: i64, now: i64) -> String {
|
||||
/// ```
|
||||
#[must_use = "show the panel with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct CommentsPanel<'a> {
|
||||
#[pattern(probe(CommentsPanel<'static, NoHostRow>))]
|
||||
pub struct CommentsPanel<'a, H: Value = NoHostRow> {
|
||||
label: Label,
|
||||
threads: &'a [CommentThread],
|
||||
state: &'a mut CommentsPanelState,
|
||||
read_only: bool,
|
||||
now: i64,
|
||||
page_label: Option<Box<dyn Fn(usize) -> String + 'a>>,
|
||||
host_rows: PhantomData<H>,
|
||||
}
|
||||
|
||||
/// The host row type of a panel whose cards' menus take no host rows: it has no value.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum NoHostRow {}
|
||||
|
||||
/// Who draws the panel's header.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum CommentsHeader {
|
||||
/// The panel draws its own header.
|
||||
#[default]
|
||||
Own,
|
||||
/// The host draws the header, placing [`comments_more_menu`] and [`comments_filter_menu`].
|
||||
Hosted,
|
||||
}
|
||||
|
||||
impl<'a> CommentsPanel<'a> {
|
||||
/// The panel named `label` over `threads`. The edits carry only the text; the app signs new
|
||||
/// comments with its own identity.
|
||||
pub fn new(label: impl Into<Label>, threads: &'a [CommentThread], state: &'a mut CommentsPanelState) -> Self {
|
||||
CommentsPanel { label: label.into(), threads, state, read_only: false, now: 0, page_label: None }
|
||||
CommentsPanel { label: label.into(), threads, state, read_only: false, now: 0, page_label: None, host_rows: PhantomData }
|
||||
}
|
||||
|
||||
/// The rows a card's menu appends behind a separator, from the thread and the card's message index; a row the
|
||||
/// user picks is reported as `CommentsPanelOutput::host`.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w4): CM-C22
|
||||
pub fn card_rows<H: Value>(self, rows: impl Fn(&CommentThread, usize) -> Vec<Entry<H>> + 'a) -> CommentsPanel<'a, H> {
|
||||
let _ = rows;
|
||||
todo!("CM-C22")
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, H: Value> CommentsPanel<'a, H> {
|
||||
/// Who draws the header.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w4): CM-C22
|
||||
pub fn header(self, header: CommentsHeader) -> Self {
|
||||
let _ = header;
|
||||
todo!("CM-C22")
|
||||
}
|
||||
|
||||
/// How threads on one page are ordered under the Page sort.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w4): CM-C22
|
||||
pub fn page_order(self, order: PageOrder) -> Self {
|
||||
let _ = order;
|
||||
todo!("CM-C22")
|
||||
}
|
||||
|
||||
/// The key that submits the reply box; an inline editor keeps `CommandEnter`.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w4): CM-C22
|
||||
pub fn reply_submit(self, key: SubmitKey) -> Self {
|
||||
let _ = key;
|
||||
todo!("CM-C22")
|
||||
}
|
||||
|
||||
/// How a click selects cards.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w4): CM-C22
|
||||
pub fn select_mode(self, mode: SelectMode) -> Self {
|
||||
let _ = mode;
|
||||
todo!("CM-C22")
|
||||
}
|
||||
|
||||
/// No posting or editing (a document that forbids comments).
|
||||
@@ -305,14 +370,37 @@ impl<'a> CommentsPanel<'a> {
|
||||
/// What the Comments panel did this pass.
|
||||
#[must_use]
|
||||
#[non_exhaustive]
|
||||
pub struct CommentsPanelOutput {
|
||||
pub struct CommentsPanelOutput<H = NoHostRow> {
|
||||
/// The panel's response.
|
||||
pub response: Response,
|
||||
/// This pass's edits, in order.
|
||||
pub edits: Vec<CommentEdit>,
|
||||
/// The host row picked in a card's menu: the thread, the card's message index and the row.
|
||||
pub host: Option<(ThreadId, usize, H)>,
|
||||
}
|
||||
|
||||
impl Outcome for CommentsPanelOutput {
|
||||
/// The panel's More menu: Collapse all pages, Expand all pages and the host's `host_rows`; the row picked. The
|
||||
/// `Own` header calls the same function.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w4): CM-C23
|
||||
pub fn comments_more_menu<H: Value>(
|
||||
ui: &mut Ui,
|
||||
opener: &Response,
|
||||
threads: &[CommentThread],
|
||||
state: &mut CommentsPanelState,
|
||||
host_rows: &[Entry<H>],
|
||||
) -> Option<H> {
|
||||
let _ = (ui, opener, threads, state, host_rows);
|
||||
todo!("CM-C23")
|
||||
}
|
||||
|
||||
/// The panel's filter menu over `threads`; the `Own` header calls the same function.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w4): CM-C23
|
||||
pub fn comments_filter_menu(ui: &mut Ui, opener: &Response, threads: &[CommentThread], state: &mut CommentsPanelState) {
|
||||
let _ = (ui, opener, threads, state);
|
||||
todo!("CM-C23")
|
||||
}
|
||||
|
||||
impl<H: Value> Outcome for CommentsPanelOutput<H> {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
@@ -352,9 +440,9 @@ fn toggle<T: PartialEq>(list: &mut Vec<T>, value: T) {
|
||||
|
||||
/// Makes `thread` the selected one; false when it already was.
|
||||
fn select_thread(state: &mut CommentsPanelState, thread: ThreadId) -> bool {
|
||||
let changed = state.selected != Some(thread);
|
||||
let changed = state.selected.lead != Some(thread); // P3(pdf-comments-w4): CM-C21
|
||||
if changed {
|
||||
state.selected = Some(thread);
|
||||
state.selected = Selection::single(thread);
|
||||
state.reply.clear();
|
||||
state.editing = None;
|
||||
}
|
||||
@@ -403,10 +491,10 @@ fn group_of(
|
||||
}
|
||||
}
|
||||
|
||||
impl CommentsPanel<'_> {
|
||||
impl<H: Value> CommentsPanel<'_, H> {
|
||||
/// Shows the panel and reports what the user did.
|
||||
pub fn show(self, ui: &mut Ui) -> CommentsPanelOutput {
|
||||
let CommentsPanel { label, threads, state, read_only, now, page_label } = self;
|
||||
pub fn show(self, ui: &mut Ui) -> CommentsPanelOutput<H> {
|
||||
let CommentsPanel { label, threads, state, read_only, now, page_label, host_rows: _ } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<CommentsWords>();
|
||||
let kinds = env.words::<AnnotateWords>();
|
||||
@@ -443,7 +531,7 @@ impl CommentsPanel<'_> {
|
||||
}
|
||||
let query = state.search.trim().to_owned();
|
||||
let kind_of = |kind: AnnotationKind| kind_name(&words, &kinds, Some(kind));
|
||||
let shown: Vec<&CommentThread> = sort_threads(threads, state.sort, kind_of)
|
||||
let shown: Vec<&CommentThread> = sort_threads(threads, state.sort, PageOrder::default(), kind_of) // P3(pdf-comments-w4): CM-C20
|
||||
.into_iter()
|
||||
.map(|i| &threads[i])
|
||||
.filter(|thread| state.filter.shows(thread))
|
||||
@@ -494,8 +582,8 @@ impl CommentsPanel<'_> {
|
||||
}
|
||||
}
|
||||
let source = Rows { entries };
|
||||
let mut selection = state.selected.map_or_else(Selection::default, |thread| Selection::single(CardKey::Thread(thread)));
|
||||
let selected = state.selected;
|
||||
let selected = state.selected.lead; // P3(pdf-comments-w4): CM-C21
|
||||
let mut selection = selected.map_or_else(Selection::default, |thread| Selection::single(CardKey::Thread(thread)));
|
||||
let reply: &str = &state.reply;
|
||||
let editing = state.editing.as_ref().map(|(thread, index, text)| (*thread, *index, text.as_str()));
|
||||
let mut openers = Vec::new();
|
||||
@@ -557,9 +645,9 @@ impl CommentsPanel<'_> {
|
||||
if let Some(CardKey::Thread(thread)) = selection.items.first().copied()
|
||||
&& select_thread(state, thread)
|
||||
{
|
||||
edits.push(CommentEdit::Select(thread));
|
||||
edits.push(CommentEdit::Select(vec![thread])); // P3(pdf-comments-w4): CM-C21
|
||||
}
|
||||
if let Some(thread) = state.selected.and_then(|selected| threads.iter().find(|thread| thread.id == selected)) {
|
||||
if let Some(thread) = state.selected.lead.and_then(|selected| threads.iter().find(|thread| thread.id == selected)) {
|
||||
let editable = !read_only && !thread.locked;
|
||||
for (index, button) in &buttons {
|
||||
if let Some(action) = card_menu(ui, &words, button, *index, thread, editable) {
|
||||
@@ -571,7 +659,7 @@ impl CommentsPanel<'_> {
|
||||
};
|
||||
let shown = Stack::new().fill().show(ui, body);
|
||||
let response = shown.inner.unwrap_or(shown.output);
|
||||
CommentsPanelOutput { response, edits }
|
||||
CommentsPanelOutput { response, edits, host: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -598,7 +686,7 @@ fn apply(event: CardEvent, state: &mut CommentsPanelState, edits: &mut Vec<Comme
|
||||
CardEvent::ReplyText(text) => state.reply = text,
|
||||
CardEvent::ReplyPost => {
|
||||
let text = state.reply.trim().to_owned();
|
||||
if let (Some(thread), false) = (state.selected, text.is_empty()) {
|
||||
if let (Some(thread), false) = (state.selected.lead, text.is_empty()) {
|
||||
edits.push(CommentEdit::Reply { thread, text });
|
||||
state.reply.clear();
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ fn thread(id: u64, page: usize, text: &str, replies: usize) -> CommentThread {
|
||||
color: Some([255, 200, 0]),
|
||||
messages,
|
||||
status: if id == 1 { ReviewStatus::Accepted } else { ReviewStatus::None },
|
||||
statuses: Vec::new(), // P3(pdf-comments-w4): CM-C19
|
||||
marked: id == 3,
|
||||
locked: false,
|
||||
resolved: false,
|
||||
@@ -44,7 +45,8 @@ fn threads() -> Vec<CommentThread> {
|
||||
#[story(CommentsPanel<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn comments_panel_two_pages_one_selected(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let threads = threads();
|
||||
let state = data.value("state", CommentsPanelState { selected: Some(ThreadId(2)), ..CommentsPanelState::default() });
|
||||
// P3(pdf-comments-w4): CM-C21
|
||||
let state = data.value("state", CommentsPanelState { selected: craft_behavior::Selection::single(ThreadId(2)), ..CommentsPanelState::default() });
|
||||
CommentsPanel::new("Comments", &threads, state).now(NOW).show(ui).into()
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,10 @@ pub mod vote;
|
||||
pub use annotate::{AnnotateTool, AnnotateWords, AnnotationOverlay, AnnotationToolbar, AnnotationToolbarOutput, PALETTE};
|
||||
pub use avatar::{Avatar, AvatarOutput, paint_avatar};
|
||||
pub use chat::{ChatWords, CursorChatBox, CursorChatBoxOutput, ReviewCommand, paint_chat_bubble};
|
||||
pub use comments::{CommentEdit, CommentsPanel, CommentsPanelOutput, CommentsPanelState, CommentsWords};
|
||||
pub use comments::{
|
||||
CommentEdit, CommentsHeader, CommentsPanel, CommentsPanelOutput, CommentsPanelState, CommentsWords, NoHostRow, comments_filter_menu,
|
||||
comments_more_menu,
|
||||
};
|
||||
pub use join::{JoinField, JoinFieldOutput, JoinWords};
|
||||
pub use presence::{
|
||||
FollowCommand, FollowFrame, FollowFrameOutput, PeopleBar, PeopleBarOutput, PresenceWords, RemoteCursor, RemoteCursors, paint_pointer,
|
||||
@@ -34,8 +37,9 @@ pub use presence::{
|
||||
pub use revisions::{RevisionsPanel, RevisionsPanelOutput, RevisionsWords};
|
||||
pub use signature::{SignaturePadDialog, SignaturePadResult, SignatureSettings, SignatureWords, paint_signature};
|
||||
pub use thread::{
|
||||
CommentComposer, CommentComposerOutput, CommentPin, CommentPins, CommentPinsOutput, PinCluster, PinMove, REACTIONS, ThreadPopover,
|
||||
ThreadPopoverOutput, ThreadWords, cluster, insert_mention, mention_matches, mention_query,
|
||||
CommentComposer, CommentComposerOutput, CommentPin, CommentPins, CommentPinsOutput, ComposerClose, ComposerDraft, NOTE_POPUP_LIMITS, NoteDrafts,
|
||||
NotePopup, NotePopupMessage, NotePopupOutput, PinCluster, PinMove, REACTIONS, ThreadPopover, ThreadPopoverOutput, ThreadWords, cluster,
|
||||
insert_mention, mention_matches, mention_query,
|
||||
};
|
||||
pub use versions::{VersionAction, VersionHistoryPanel, VersionHistoryPanelOutput, VersionPreviewBanner, VersionPreviewBannerOutput, VersionsWords};
|
||||
pub use vote::{VotePill, VotePillOutput, VoteWords};
|
||||
@@ -19,6 +19,7 @@ use craft_ui::fonts::FontRef;
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::notices::{Notice, NoticeLayout};
|
||||
use craft_ui::primitives::{DocRun, DocText, Draw, HAlign, PaintShape, StrokeWidth, TextureCache};
|
||||
use craft_ui::runtime::drag::OsFile;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::runtime::focus::{ActivateKeys, EditSet, KeyUse};
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
@@ -65,6 +66,8 @@ craft_ui::words! {
|
||||
cancel: "signature.cancel" = "Cancel";
|
||||
image_failed: "signature.imageFailed" = "That image could not be read.";
|
||||
image_too_large: "signature.imageTooLarge" = "That image is too large: up to 4 MiB and 8192 × 8192 pixels.";
|
||||
drop_image: "signature.dropImage" = "Drop an image here";
|
||||
drop_photo: "signature.dropPhoto" = "Drop a photo of a signature here";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,13 +143,13 @@ fn paint_typed(ctx: &egui::Context, draw: &Draw<'_>, rect: Rect, label: &str, co
|
||||
let tall = rect.height() * TYPED_HEIGHT_SHARE;
|
||||
let width = rect.width() * TYPED_WIDTH_SHARE;
|
||||
// A name too wide at the height's size shrinks to the width, so it stays on one line.
|
||||
let wide = DocText::new(&[DocRun::new(label.to_owned(), FontRef::proportional(), tall, color)])
|
||||
let wide = DocText::new(&[DocRun::new(label.to_owned(), FontRef::signature(), tall, color)])
|
||||
.layout(ctx, &Env::of_root(ctx).tokens, craft_i18n::Direction::Ltr)
|
||||
.size()
|
||||
.x;
|
||||
let size = if wide > width { tall * width / wide } else { tall };
|
||||
let room = Vec2::new(width, size);
|
||||
let run = [DocRun::new(label.to_owned(), FontRef::proportional(), size, color)];
|
||||
let run = [DocRun::new(label.to_owned(), FontRef::signature(), size, color)];
|
||||
let mut text = DocText::new(&run);
|
||||
text.align = HAlign::Center;
|
||||
draw.doc(Rect::from_center_size(rect.center(), room), &text);
|
||||
@@ -395,7 +398,9 @@ fn pop_stroke(strokes: &mut Vec<Vec<[f32; 2]>>) -> bool {
|
||||
}
|
||||
|
||||
/// The Scan tab's content, the app's.
|
||||
pub type ScanTab = Box<dyn FnMut(&mut egui::Ui, &mut SignatureDraft) + Send>;
|
||||
///
|
||||
/// It is handed the file dropped on the tab this pass.
|
||||
pub type ScanTab = Box<dyn FnMut(&mut egui::Ui, &mut SignatureDraft, Option<OsFile>) + Send>;
|
||||
|
||||
/// Acrobat's signature pad on the dialog host: "Create signature" or "Change initials" with the tabs Type (a field over
|
||||
/// the pad that shows the typed signature), Draw (a pad of strokes, Undo), Image (Browse… a PNG or JPEG up to
|
||||
@@ -433,7 +438,7 @@ impl SignaturePadDialog {
|
||||
|
||||
/// The Scan tab's content: it fills `draft.image`.
|
||||
#[must_use]
|
||||
pub fn scan(mut self, tab: impl FnMut(&mut egui::Ui, &mut SignatureDraft) + Send + 'static) -> Self {
|
||||
pub fn scan(mut self, tab: impl FnMut(&mut egui::Ui, &mut SignatureDraft, Option<OsFile>) + Send + 'static) -> Self {
|
||||
self.scan = Some(Box::new(tab));
|
||||
self
|
||||
}
|
||||
@@ -554,7 +559,7 @@ impl StackDialog for SignaturePadDialog {
|
||||
}
|
||||
SignatureTab::Scan => {
|
||||
if let Some(tab) = scan.as_mut() {
|
||||
tab(ui, draft);
|
||||
tab(ui, draft, None); // P3(pdf-forms-w1): FM-PF3 (the writer hands over the dropped file)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,14 +6,16 @@
|
||||
//! ```
|
||||
|
||||
mod mention;
|
||||
mod note_popup;
|
||||
mod pins;
|
||||
mod popover;
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
pub use mention::{insert_mention, mention_matches, mention_query};
|
||||
pub use note_popup::{NOTE_POPUP_LIMITS, NoteDrafts, NotePopup, NotePopupMessage, NotePopupOutput};
|
||||
pub use pins::{CommentPin, CommentPins, CommentPinsOutput, PinCluster, PinMove, cluster};
|
||||
pub use popover::{CommentComposer, CommentComposerOutput, REACTIONS, ThreadPopover, ThreadPopoverOutput};
|
||||
pub use popover::{CommentComposer, CommentComposerOutput, ComposerClose, ComposerDraft, REACTIONS, ThreadPopover, ThreadPopoverOutput};
|
||||
|
||||
craft_ui::words! {
|
||||
/// The thread popover's and composer's words, English by default.
|
||||
@@ -36,5 +38,6 @@ craft_ui::words! {
|
||||
pin: template "thread.pin" = "Comment by {author}";
|
||||
pin_text: template "thread.pinText" = "Comment by {author}: {words}";
|
||||
cluster: template "thread.cluster" = "{n} comments";
|
||||
note_title: "thread.noteTitle" = "Note";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! The note pop-up: a modeless window over a note's messages that keeps its size on screen at every zoom.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use craft_ui::contract::SizeLimits;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use egui::{Response, Ui, vec2};
|
||||
|
||||
/// One message of a note pop-up.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct NotePopupMessage<'a> {
|
||||
/// The message's id.
|
||||
pub id: u64,
|
||||
/// The message's title line.
|
||||
pub title: &'a str,
|
||||
/// The author's name.
|
||||
pub author: &'a str,
|
||||
/// The message text.
|
||||
pub text: &'a str,
|
||||
/// Unix seconds of the last edit or of the creation; a message with no date shows none.
|
||||
pub modified: Option<i64>,
|
||||
/// How deep a reply sits; 0 is the comment.
|
||||
pub depth: usize,
|
||||
/// Whether the message can be edited.
|
||||
pub editable: bool,
|
||||
}
|
||||
|
||||
/// The pop-ups' reply drafts, one per note.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct NoteDrafts {
|
||||
#[allow(dead_code)] // P3(pdf-comments-w3): CM-C17
|
||||
drafts: HashMap<u64, String>,
|
||||
}
|
||||
|
||||
/// The smallest size of a note pop-up, in points; it has no largest size.
|
||||
pub const NOTE_POPUP_LIMITS: SizeLimits = SizeLimits::at_least(vec2(160.0, 96.0));
|
||||
|
||||
/// What a note pop-up did this pass.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct NotePopupOutput {
|
||||
/// The pop-up's response.
|
||||
pub response: Response,
|
||||
/// The window's new rectangle, reported when a move or resize commits.
|
||||
pub placed: Option<egui::Rect>,
|
||||
}
|
||||
|
||||
/// A modeless note pop-up window over a note's messages. It keeps its size on screen at every zoom, so it takes no
|
||||
/// zoom scale; a move or resize is reported as [`NotePopupOutput::placed`].
|
||||
#[must_use = "show the pop-up with `show`"]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w3): CM-C18
|
||||
pub struct NotePopup<'a> {
|
||||
id: u64,
|
||||
label: Label,
|
||||
rect: egui::Rect,
|
||||
messages: &'a [NotePopupMessage<'a>],
|
||||
drafts: &'a mut NoteDrafts,
|
||||
}
|
||||
|
||||
impl<'a> NotePopup<'a> {
|
||||
/// The pop-up `id` named `label` at `rect` over `messages`, keeping its reply drafts in `drafts`.
|
||||
pub fn new(id: u64, label: impl Into<Label>, rect: egui::Rect, messages: &'a [NotePopupMessage<'a>], drafts: &'a mut NoteDrafts) -> Self {
|
||||
NotePopup { id, label: label.into(), rect, messages, drafts }
|
||||
}
|
||||
|
||||
/// The note's colour, straight RGB.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w3): CM-C18
|
||||
pub fn color(self, color: Option<[u8; 3]>) -> Self {
|
||||
let _ = color;
|
||||
todo!("CM-C18")
|
||||
}
|
||||
|
||||
/// Whether the note shows its checkmark.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w3): CM-C18
|
||||
pub fn mark(self, mark: bool) -> Self {
|
||||
let _ = mark;
|
||||
todo!("CM-C18")
|
||||
}
|
||||
|
||||
/// Whether the note is the selected one.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w3): CM-C18
|
||||
pub fn selected(self, selected: bool) -> Self {
|
||||
let _ = selected;
|
||||
todo!("CM-C18")
|
||||
}
|
||||
|
||||
/// The current time in Unix seconds, which the ages count from.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w3): CM-C18
|
||||
pub fn now(self, unix_seconds: i64) -> Self {
|
||||
let _ = unix_seconds;
|
||||
todo!("CM-C18")
|
||||
}
|
||||
|
||||
/// Whether the document allows commenting: replying and editing.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w3): CM-C18
|
||||
pub fn allowed(self, allowed: bool) -> Self {
|
||||
let _ = allowed;
|
||||
todo!("CM-C18")
|
||||
}
|
||||
|
||||
/// Shows the pop-up.
|
||||
#[allow(dead_code)] // P3(pdf-comments-w3): CM-C18
|
||||
pub fn show(self, ui: &mut Ui) -> NotePopupOutput {
|
||||
let _ = ui;
|
||||
todo!("CM-C18")
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::menu::{Menu, MenuItem};
|
||||
use craft_ui::popover::Popover;
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::focus::Initial;
|
||||
use craft_ui::style::TypeRole;
|
||||
use craft_ui::text::TextField;
|
||||
@@ -248,6 +248,54 @@ impl<'a> CommentComposer<'a> {
|
||||
pub fn new(anchor: Option<Pos2>, draft: &'a mut String) -> Self {
|
||||
CommentComposer { anchor, draft }
|
||||
}
|
||||
|
||||
/// A header of `title` and the `author` above the field.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w3): CM-C16
|
||||
pub fn header(self, title: impl Into<Label>, author: &'a str) -> Self {
|
||||
let _ = (title.into(), author);
|
||||
todo!("CM-C16")
|
||||
}
|
||||
|
||||
/// The rule the post applies to the draft.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w3): CM-C16
|
||||
pub fn draft_kind(self, kind: ComposerDraft) -> Self {
|
||||
let _ = kind;
|
||||
todo!("CM-C16")
|
||||
}
|
||||
|
||||
/// When the composer closes.
|
||||
#[must_use]
|
||||
#[allow(dead_code)] // P3(pdf-comments-w3): CM-C16
|
||||
pub fn close(self, close: ComposerClose) -> Self {
|
||||
let _ = close;
|
||||
todo!("CM-C16")
|
||||
}
|
||||
}
|
||||
|
||||
/// The rule a composer applies to its draft at the post.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ComposerDraft {
|
||||
/// A new comment: trailing whitespace trimmed; Post needs text.
|
||||
#[default]
|
||||
New,
|
||||
/// An edit: trailing whitespace trimmed; empty text clears the comment.
|
||||
Edit,
|
||||
/// An edit posted as typed (a typewriter comment); empty text clears the comment.
|
||||
EditVerbatim,
|
||||
}
|
||||
|
||||
/// When a composer closes.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ComposerClose {
|
||||
/// On a press outside, as well as Post and Cancel.
|
||||
#[default]
|
||||
OnOutsidePress,
|
||||
/// Only on Post or Cancel.
|
||||
OnPostOrCancel,
|
||||
}
|
||||
|
||||
/// What the composer did this pass.
|
||||
|
||||
@@ -27,6 +27,7 @@ fn thread() -> CommentThread {
|
||||
color: None,
|
||||
messages: vec![message("Ana", "Check @Bo before we ship.", NOW - 7_200), message("Bo", "On it.", NOW - 600)],
|
||||
status: ReviewStatus::None,
|
||||
statuses: Vec::new(), // P3(pdf-comments-w3): CM-C19
|
||||
marked: false,
|
||||
locked: false,
|
||||
resolved: false,
|
||||
|
||||
@@ -34,6 +34,8 @@ fn annotation(id: u64, kind: AnnotationKind, rect: Rect) -> Annotation {
|
||||
stroke_width: 1.0,
|
||||
text: String::new(),
|
||||
locked: false,
|
||||
aspect: None, // P3(pdf-comments-w2): CM-C3
|
||||
handle_rule: craft_review::annotate::HandleRule::default(), // P3(pdf-comments-w2): CM-C30
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ fn thread(id: u64, text: &str) -> CommentThread {
|
||||
color: None,
|
||||
messages: vec![CommentMessage { author: "Ana".into(), created: 0, modified: None, text: text.into(), reactions: Vec::new(), read: true }],
|
||||
status: ReviewStatus::None,
|
||||
statuses: Vec::new(), // P3(pdf-comments-w4): CM-C19
|
||||
marked: false,
|
||||
locked: false,
|
||||
resolved: false,
|
||||
@@ -26,7 +27,10 @@ fn thread(id: u64, text: &str) -> CommentThread {
|
||||
/// where Cmd+Enter posts the reply to that card's thread.
|
||||
#[trial]
|
||||
fn enter_posts_a_comment_and_enter_on_a_card_opens_its_reply_box() {
|
||||
let state = Rc::new(RefCell::new(CommentsPanelState { selected: Some(ThreadId(2)), ..CommentsPanelState::default() }));
|
||||
// P3(pdf-comments-w4): CM-C21
|
||||
let mut initial = CommentsPanelState::default();
|
||||
initial.selected = craft_behavior::Selection::single(ThreadId(2));
|
||||
let state = Rc::new(RefCell::new(initial));
|
||||
let edits = Rc::new(RefCell::new(Vec::new()));
|
||||
let (shown_state, shown_edits) = (state.clone(), edits.clone());
|
||||
let threads = vec![thread(1, "The margin is too narrow."), thread(2, "Use the brand colour.")];
|
||||
@@ -47,7 +51,7 @@ fn enter_posts_a_comment_and_enter_on_a_card_opens_its_reply_box() {
|
||||
fixture.key(Key::Tab, Modifiers::NONE).settle();
|
||||
fixture.key(Key::Enter, Modifiers::NONE).settle();
|
||||
fixture.type_text("Thanks").key(Key::Enter, Modifiers::COMMAND).settle();
|
||||
let selected = state.borrow().selected.expect("a card is selected");
|
||||
let selected = state.borrow().selected.lead.expect("a card is selected"); // P3(pdf-comments-w4): CM-C21
|
||||
assert!(
|
||||
edits.borrow().iter().any(|edit| matches!(edit, CommentEdit::Reply { thread, text, .. } if *thread == selected && text == "Thanks")),
|
||||
"Enter on the card put the focus in its reply box, where Cmd+Enter posts: {:?}",
|
||||
|
||||
Reference in new issue
Block a user