mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-26 04:58:07 +00:00
pdf-chrome-w9: net change of 3 commits
- pdf-chrome-w9: written from its sheet - pdf-chrome-w9: repair 1 - pdf-chrome-w9: review fixes (review-1)
This commit is contained in:
@@ -0,0 +1,195 @@
|
||||
//! The app's command catalog and its per-frame state: one [`CommandDef`] for every registry command and
|
||||
//! menu-only id, and one [`CommandState`] row per command, so the menus, the palette and the shortcuts read one
|
||||
//! enabled, checked and hint rule.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use craft::ui::runtime::commands::{AppCatalog, Binding, CommandDef, CommandDefError, CommandGate, CommandInput, CommandKind, CommandRef, CommandState, Scope};
|
||||
use pdfcraft_engine::commands::{self as engine, CommandSpec};
|
||||
|
||||
use crate::menus::{self, CUT, DELETE, DOCUMENT, EXTRA, NO_RECENT, PANEL, PANELS, PASTE, SELECT_ALL};
|
||||
use craft::pages::PageDisplay;
|
||||
use crate::theme::ModeChoice;
|
||||
use crate::{Mode, PdfCraftApp, QuickTool};
|
||||
|
||||
/// Commands only the catalog knows: id, English label and icon. Their handlers are the board's.
|
||||
const CATALOG_ONLY: &[(&str, &str, &str)] = &[
|
||||
("app.theme", "Switch theme", "moon"),
|
||||
("home.unpin_tool", "Unpin tool", "pin-off"),
|
||||
("form.calculation_order.back", "Back to Prepare a form", "chevron-left"),
|
||||
("tools.expand", "Expand tools", "chevrons-up-down"),
|
||||
("tools.collapse", "Collapse tools", "chevrons-down-up"),
|
||||
("tools.all", "All tools", "layout-grid"),
|
||||
("view.dock_side", "Move the side panel to the other side", "arrow-left-right"),
|
||||
("view.fit_toggle", "Toggle fit", "scan"),
|
||||
("bookmark.paste", "Paste bookmarks", "clipboard-paste"),
|
||||
("bookmark.expand_all", "Expand all bookmarks", "chevrons-down"),
|
||||
("bookmark.collapse_all", "Collapse all bookmarks", "chevrons-up"),
|
||||
("bookmark.expand_level", "Expand top-level bookmarks", "chevron-down"),
|
||||
("layers.reset_visibility", "Reset to Initial Visibility", "layers"),
|
||||
(PANEL, "Side panel", "panel-right"),
|
||||
(DOCUMENT, "Switch to document", "file"),
|
||||
("tool.group", "Tool group", "wrench"),
|
||||
];
|
||||
|
||||
/// Commands whose chords and rows are the framework's clipboard commands.
|
||||
const FRAMEWORK_EDIT: &[&str] = &["edit.copy", "edit.paste"];
|
||||
|
||||
static CATALOG_WIN: OnceLock<Option<AppCatalog>> = OnceLock::new();
|
||||
static CATALOG_MAC: OnceLock<Option<AppCatalog>> = OnceLock::new();
|
||||
|
||||
/// What a command is to the keymap: a toggle or a radio choice for the ones that carry a checked state.
|
||||
fn kind_of(id: &str) -> CommandKind {
|
||||
match id {
|
||||
"view.layout.single" | "view.layout.two_up" => CommandKind::Radio { group: Some("layout".into()) },
|
||||
"view.theme.system" | "view.theme.light" | "view.theme.dark" => CommandKind::Radio { group: Some("theme".into()) },
|
||||
PANEL => CommandKind::Radio { group: Some("panel".into()) },
|
||||
"view.continuous" | "view.page_gaps" | "view.layout.cover" | "view.full_screen" | "view.read_mode" | "view.side_panel" | "view.tools_pane"
|
||||
| "view.split" => CommandKind::Toggle,
|
||||
_ => CommandKind::Command,
|
||||
}
|
||||
}
|
||||
|
||||
/// The catalog's rows, for the chords of macOS (`mac`) or of the other platforms. A row an earlier one already
|
||||
/// has the id of is left out, so the catalog never refuses two defs of one id.
|
||||
pub(crate) fn catalog(mac: bool) -> Result<AppCatalog, CommandDefError> {
|
||||
let mut defs: Vec<CommandDef> = Vec::new();
|
||||
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
|
||||
let mut push = |def: CommandDef, shortcut: Option<craft::menu::Chord>| {
|
||||
if !seen.insert(def.command.id.clone()) {
|
||||
return;
|
||||
}
|
||||
let def = if def.kind == CommandKind::Command { def.with_kind(kind_of(&def.command.id)) } else { def };
|
||||
defs.push(match shortcut {
|
||||
Some(chord) => def.with_default(Binding::new(chord)),
|
||||
None => def,
|
||||
});
|
||||
};
|
||||
for spec in engine::COMMANDS.iter().filter(|s| !FRAMEWORK_EDIT.contains(&s.id)) {
|
||||
let mut def = CommandDef::new(CommandRef::new(spec.id), spec.label, Scope::app());
|
||||
if !spec.icon.is_empty() {
|
||||
def = def.with_icon(spec.icon);
|
||||
}
|
||||
push(def, spec.shortcut_for(mac).and_then(menus::chord));
|
||||
}
|
||||
for (id, label, shortcut) in EXTRA.iter().filter(|(id, ..)| !FRAMEWORK_EDIT.contains(id)) {
|
||||
push(CommandDef::new(CommandRef::new(*id), *label, Scope::app()), shortcut.and_then(menus::chord));
|
||||
}
|
||||
for (id, label, icon) in CATALOG_ONLY {
|
||||
push(CommandDef::new(CommandRef::new(*id), *label, Scope::app()).with_icon(*icon), None);
|
||||
}
|
||||
// The rows are static, so the catalog never changes generation.
|
||||
AppCatalog::new(defs, 0)
|
||||
}
|
||||
|
||||
/// The catalog for this platform's chords, built once.
|
||||
fn shared_catalog(mac: bool) -> Option<AppCatalog> {
|
||||
let cell = if mac { &CATALOG_MAC } else { &CATALOG_WIN };
|
||||
cell.get_or_init(|| catalog(mac).ok()).clone()
|
||||
}
|
||||
|
||||
/// The command state for this frame: the gate, the catalog and a state row for every command.
|
||||
pub(crate) fn command_input(app: &PdfCraftApp, ctx: &egui::Context) -> CommandInput {
|
||||
let gated = menus::gated(app);
|
||||
let mut input = CommandInput::new().gate(CommandGate::new(move |_| !gated));
|
||||
if let Some(catalog) = shared_catalog(super::mac_shortcuts(ctx)) {
|
||||
input = input.catalog(catalog);
|
||||
}
|
||||
let mut commands: Vec<CommandRef> = engine::COMMANDS.iter().map(|s| CommandRef::new(s.id)).collect();
|
||||
commands.extend(EXTRA.iter().map(|(id, ..)| CommandRef::new(*id)));
|
||||
commands.extend((0..app.recent.len()).map(|index| CommandRef::with_params("file.open_recent", serde_json::json!({ "index": index }))));
|
||||
commands.extend((0..app.views.len()).map(|index| CommandRef::with_params(DOCUMENT, serde_json::json!({ "index": index }))));
|
||||
commands.extend(PANELS.iter().map(|(_, name, _)| CommandRef::with_params(PANEL, serde_json::json!({ "panel": name }))));
|
||||
for command in commands {
|
||||
let state = state_of(app, ctx, &command, gated);
|
||||
input = input.state(command, state);
|
||||
}
|
||||
input
|
||||
}
|
||||
|
||||
fn state_of(app: &PdfCraftApp, ctx: &egui::Context, command: &CommandRef, gated: bool) -> CommandState {
|
||||
let enabled = enabled(app, ctx, command);
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(checked) = checked(app, command) {
|
||||
state = state.checked(checked);
|
||||
}
|
||||
if !enabled
|
||||
&& !gated
|
||||
&& let Some(spec) = engine::command(&command.id)
|
||||
{
|
||||
state = state.hint(app.disabled_reason(spec));
|
||||
}
|
||||
if menus::panel(command).is_some_and(|panel| has_content(app, panel)) {
|
||||
state = state.marked(true);
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
/// Whether a side panel has something to show in the active document.
|
||||
fn has_content(app: &PdfCraftApp, panel: crate::RightPanel) -> bool {
|
||||
let Some((_, id)) = app.active_ids() else { return false };
|
||||
let Some(doc) = app.session.get(id) else { return false };
|
||||
match panel {
|
||||
crate::RightPanel::Bookmarks => !doc.info.outline.is_empty(),
|
||||
crate::RightPanel::Layers => !doc.info.layers.is_empty(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a command can run now.
|
||||
fn enabled(app: &PdfCraftApp, ctx: &egui::Context, command: &CommandRef) -> bool {
|
||||
let view = app.active.and_then(|i| app.views.get(i));
|
||||
let organize = view.is_some_and(|v| v.organize);
|
||||
let has_doc = view.is_some();
|
||||
let enabled_id = |id: &str| engine::command(id).is_some_and(|s: &CommandSpec| app.command_enabled(s));
|
||||
let index = menus::param_index(command);
|
||||
// Edit rows stay on while a text field has the keyboard.
|
||||
let text = menus::text_editing(ctx) && matches!(command.id.as_str(), "edit.undo" | "edit.redo" | "edit.copy" | CUT | PASTE | SELECT_ALL);
|
||||
// Objects selected together in Edit a PDF are what Copy and Cut take, and Paste brings back
|
||||
// objects copied there.
|
||||
let edit_objects = app.quick_tool == QuickTool::EditText && !organize;
|
||||
let doc = app.active_ids().and_then(|(_, id)| app.session.get(id));
|
||||
text || match command.id.as_str() {
|
||||
NO_RECENT => false,
|
||||
"file.open_recent" => index.is_none_or(|i| i < app.recent.len()),
|
||||
"file.clear_recent" => !app.recent.is_empty(),
|
||||
DOCUMENT => index.is_some_and(|i| i < app.views.len()),
|
||||
// macOS ⌘W closes the window when no document is open (#869).
|
||||
"file.close" if !has_doc && super::mac_shortcuts(ctx) && !cfg!(target_arch = "wasm32") => true,
|
||||
"edit.copy" if organize => enabled_id("page.copy"),
|
||||
"edit.copy" if view.is_some_and(|v| v.picked_image.is_some()) => doc.is_some_and(|d| d.allows_copying()),
|
||||
"edit.copy" | CUT if edit_objects && view.is_some_and(|v| v.objects.count() > 0) => {
|
||||
doc.is_some_and(|d| d.allows_copying() && (command.id != CUT || d.allows_modification()))
|
||||
}
|
||||
PASTE if edit_objects && app.object_clipboard.is_some() => doc.is_some_and(pdfcraft_engine::Document::allows_modification),
|
||||
CUT => organize && enabled_id("page.cut"),
|
||||
PASTE => organize && app.page_clipboard.is_some() && enabled_id("page.paste"),
|
||||
SELECT_ALL | DELETE => has_doc,
|
||||
id if id.starts_with("view.zoom.") || id.starts_with("view.rotate.") => has_doc,
|
||||
PANEL => menus::panel(command).is_some(),
|
||||
id => enabled_id(id),
|
||||
}
|
||||
}
|
||||
|
||||
/// The checked or selected state of a toggle or radio command; `None` for any other.
|
||||
fn checked(app: &PdfCraftApp, command: &CommandRef) -> Option<bool> {
|
||||
let view = app.active.and_then(|i| app.views.get(i)).map(|v| &v.view);
|
||||
Some(match command.id.as_str() {
|
||||
"view.layout.single" => view.is_some_and(|v| v.display == PageDisplay::Single),
|
||||
"view.layout.two_up" => view.is_some_and(|v| v.display == PageDisplay::TwoUp),
|
||||
"view.continuous" => view.is_some_and(|v| v.continuous),
|
||||
"view.page_gaps" => view.is_some_and(|v| v.page_gaps),
|
||||
"view.layout.cover" => view.is_some_and(|v| v.cover),
|
||||
"view.full_screen" => app.full_screen,
|
||||
"view.read_mode" => app.mode == Mode::Read,
|
||||
// PLAN: assumed `right()` and `left_open()` read from the dock (pdf-hub-w1)
|
||||
"view.side_panel" => app.right().is_some(),
|
||||
"view.tools_pane" => app.left_open(),
|
||||
"view.split" => app.panes.split.is_some(),
|
||||
"view.theme.system" => app.theme_preference == ModeChoice::System,
|
||||
"view.theme.light" => app.theme_preference == ModeChoice::Light,
|
||||
"view.theme.dark" => app.theme_preference == ModeChoice::Dark,
|
||||
PANEL => menus::panel(command).is_some_and(|p| app.right() == Some(p)),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -1,258 +0,0 @@
|
||||
//! ⌘K command palette: every registered command (with its shortcut) and every tool in the
|
||||
//! catalogue, with a fuzzy-ish substring match.
|
||||
|
||||
use egui::{Align2, CornerRadius, Rect, Sense, Stroke, vec2};
|
||||
use pdfcraft_engine::catalog::{Availability, TOOL_GROUPS};
|
||||
|
||||
use crate::theme::{self, Tokens};
|
||||
use crate::{PdfCraftApp, icons};
|
||||
|
||||
struct Hit {
|
||||
/// The tool panel to open (tools and catalogue items); `None` for plain commands.
|
||||
group: Option<&'static str>,
|
||||
label: String,
|
||||
detail: String,
|
||||
icon: &'static str,
|
||||
command: Option<&'static str>,
|
||||
ready: bool,
|
||||
}
|
||||
|
||||
/// Where `needle` (folded with [`pdfcraft_render::text::fold_case`]) matches `hay`, for ranking.
|
||||
fn score(hay: &str, needle: &str) -> Option<usize> {
|
||||
score_for_direction(hay, needle, crate::i18n::current().rtl())
|
||||
}
|
||||
|
||||
/// Rank logical text, accepting reordered query words for right-to-left locales.
|
||||
fn score_for_direction(hay: &str, needle: &str, rtl: bool) -> Option<usize> {
|
||||
if needle.is_empty() {
|
||||
return Some(0);
|
||||
}
|
||||
let h = pdfcraft_render::text::fold_case(hay);
|
||||
if let Some(p) = h.find(needle) {
|
||||
return Some(p);
|
||||
}
|
||||
// Match the all-tools search: RTL queries may name the same words in another order.
|
||||
if rtl && needle.contains(char::is_whitespace) {
|
||||
let first = needle.split_whitespace().try_fold(usize::MAX, |first, word| h.find(word).map(|at| first.min(at)));
|
||||
if let Some(first) = first {
|
||||
return Some(first);
|
||||
}
|
||||
}
|
||||
// Subsequence match as a fallback.
|
||||
let mut it = h.chars();
|
||||
needle.chars().all(|c| it.any(|x| x == c)).then_some(100)
|
||||
}
|
||||
|
||||
/// Draw the command palette and dispatch the chosen command or tool group.
|
||||
pub fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {
|
||||
let palette_rect_id = egui::Id::unique("palette_rect");
|
||||
if !app.palette_open {
|
||||
return;
|
||||
}
|
||||
let t = Tokens::get(ctx);
|
||||
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
app.palette_open = false;
|
||||
return;
|
||||
}
|
||||
let q = pdfcraft_render::text::fold_case(app.palette_query.trim());
|
||||
let mut hits: Vec<(usize, Hit)> = Vec::new();
|
||||
let active = app.active_ids().map(|(_, id)| id);
|
||||
for spec in pdfcraft_engine::commands::COMMANDS {
|
||||
let label = pdfcraft_engine::commands::current_label(spec, &app.session, active);
|
||||
let translated = crate::i18n::command_label(&label);
|
||||
if let Some(s) = score(&translated, &q).or_else(|| score(&label, &q)).or_else(|| score(spec.id, &q).map(|s| s + 50)) {
|
||||
hits.push((
|
||||
s,
|
||||
Hit {
|
||||
group: None,
|
||||
label: translated,
|
||||
detail: spec
|
||||
.shortcut_for(crate::commands::mac_shortcuts(ctx))
|
||||
.map(|k| crate::commands::shortcut_label(ctx, k))
|
||||
.unwrap_or_else(|| tl!(spec.menu.unwrap_or("Command")).to_string()),
|
||||
icon: spec.icon,
|
||||
command: Some(spec.id),
|
||||
ready: app.command_enabled(spec),
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
for g in TOOL_GROUPS {
|
||||
if let Some(s) = score(tl!(g.label), &q).or_else(|| score(g.label, &q)) {
|
||||
hits.push((
|
||||
s,
|
||||
Hit {
|
||||
group: Some(g.id),
|
||||
label: tl!(g.label).to_string(),
|
||||
detail: tl!("Tool").into(),
|
||||
icon: g.icon,
|
||||
command: None,
|
||||
ready: g.availability == Availability::Ready,
|
||||
},
|
||||
));
|
||||
}
|
||||
for sec in g.sections {
|
||||
for i in sec.items {
|
||||
if pdfcraft_engine::commands::command(i.command).is_some() {
|
||||
continue; // listed above as a command
|
||||
}
|
||||
if let Some(s) = score(tl!(i.label), &q).or_else(|| score(i.label, &q)).or_else(|| score(i.command, &q).map(|s| s + 50)) {
|
||||
hits.push((
|
||||
s + 1,
|
||||
Hit {
|
||||
group: Some(g.id),
|
||||
label: tl!(i.label).to_string(),
|
||||
detail: tl!(g.label).into(),
|
||||
icon: i.icon,
|
||||
command: Some(i.command),
|
||||
ready: i.availability == Availability::Ready,
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hits.sort_by_key(|(s, h)| (*s, !h.ready));
|
||||
hits.truncate(12);
|
||||
let (down, up) = ctx.input(|i| (i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::ArrowUp)));
|
||||
let selected = ctx.data_mut(|data| {
|
||||
let id = egui::Id::unique("palette_selected");
|
||||
let query_id = egui::Id::unique("palette_selected_query");
|
||||
let previous_query = data.get_temp::<String>(query_id);
|
||||
let selected =
|
||||
if previous_query.as_deref() == Some(&q) { data.get_temp::<usize>(id).unwrap_or(0) } else { 0 }.min(hits.len().saturating_sub(1));
|
||||
data.insert_temp(query_id, q.clone());
|
||||
let selected = if down {
|
||||
selected.saturating_add(1).min(hits.len().saturating_sub(1))
|
||||
} else if up {
|
||||
selected.saturating_sub(1)
|
||||
} else {
|
||||
selected
|
||||
};
|
||||
data.insert_temp(id, selected);
|
||||
selected
|
||||
});
|
||||
|
||||
let screen = ctx.content_rect();
|
||||
|
||||
let previous_rect = ctx.data(|data| data.get_temp::<Rect>(palette_rect_id));
|
||||
|
||||
let outside_click = ctx.input(|input| {
|
||||
input.pointer.button_pressed(egui::PointerButton::Primary)
|
||||
&& input.pointer.interact_pos().is_some_and(|pos| previous_rect.is_some_and(|rect| !rect.contains(pos)))
|
||||
});
|
||||
|
||||
if outside_click {
|
||||
app.palette_open = false;
|
||||
app.palette_query.clear();
|
||||
return;
|
||||
}
|
||||
let mut chosen: Option<(Option<&'static str>, Option<&'static str>)> = None;
|
||||
let area_response = egui::Area::new(egui::Id::unique("palette"))
|
||||
.order(egui::Order::Foreground)
|
||||
.pivot(Align2::CENTER_TOP)
|
||||
.fixed_pos(egui::pos2(screen.center().x, screen.top() + 96.0))
|
||||
.show(ctx, |ui| {
|
||||
egui::Frame::popup(ui.style()).corner_radius(CornerRadius::same(12)).inner_margin(egui::Margin::same(10)).show(ui, |ui| {
|
||||
ui.set_width(560.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(icons::image("search", 18.0, t.text_muted));
|
||||
let r = ui
|
||||
.add(
|
||||
egui::TextEdit::singleline(&mut app.palette_query)
|
||||
.hint_text(tl!("Search tools and commands…"))
|
||||
.frame(egui::Frame::NONE)
|
||||
.font(theme::regular(15.0))
|
||||
.desired_width(f32::INFINITY),
|
||||
)
|
||||
.accessible_name(tl!("Search tools and commands"));
|
||||
// Enter runs the selected hit while the field is focused or relinquishing focus.
|
||||
if (r.has_focus() || r.lost_focus())
|
||||
&& ui.input(|i| i.key_pressed(egui::Key::Enter))
|
||||
&& let Some((_, h)) = hits.get(selected)
|
||||
{
|
||||
chosen = Some((h.command, h.group));
|
||||
}
|
||||
// Re-requesting existing focus interrupts native IME composition.
|
||||
if !r.has_focus() {
|
||||
r.request_focus();
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
for (index, (_, h)) in hits.iter().enumerate() {
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());
|
||||
let press = theme::Press::track(ui, &resp);
|
||||
press.wash(ui, rect, 6, index == selected);
|
||||
let body = rect.translate(press.offset());
|
||||
icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 9.0), vec2(18.0, 18.0)), h.icon, 17.0, t.icon);
|
||||
// Display is translated; matching above already considered both languages.
|
||||
let shown = crate::i18n::command_label(&h.label);
|
||||
let shown_detail = tl!(&h.detail).to_string();
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, h.ready, &shown));
|
||||
let fg = if h.ready { t.text } else { t.text_faint };
|
||||
let detail_font = theme::regular(12.0);
|
||||
let detail_max = (rect.width() * 0.42).clamp(0.0, 220.0);
|
||||
let detail = crate::widgets::fit_line(&shown_detail, detail_max, |s| crate::widgets::text_width(ui, s, &detail_font));
|
||||
let detail_w = crate::widgets::text_width(ui, &detail, &detail_font);
|
||||
ui.painter().text(body.right_center() - vec2(10.0, 0.0), Align2::RIGHT_CENTER, detail, detail_font, t.text_faint);
|
||||
crate::widgets::paint_left(
|
||||
ui,
|
||||
body.left_center() + vec2(36.0, 0.0),
|
||||
&shown,
|
||||
theme::regular(13.5),
|
||||
fg,
|
||||
(rect.width() - 36.0 - detail_w - 24.0).max(0.0),
|
||||
);
|
||||
if theme::hand(resp).clicked() {
|
||||
chosen = Some((h.command, h.group));
|
||||
}
|
||||
}
|
||||
if hits.is_empty() {
|
||||
ui.label(egui::RichText::new(tl!("No matching tools")).color(t.text_muted));
|
||||
}
|
||||
ui.add_space(2.0);
|
||||
let _ = Stroke::NONE;
|
||||
});
|
||||
});
|
||||
|
||||
ctx.data_mut(|data| {
|
||||
data.insert_temp(palette_rect_id, area_response.response.rect);
|
||||
});
|
||||
|
||||
if let Some((command, group)) = chosen {
|
||||
app.palette_open = false;
|
||||
app.palette_query.clear();
|
||||
if let Some(g) = group {
|
||||
app.select_tool(g);
|
||||
}
|
||||
if let Some(c) = command {
|
||||
app.run_command(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod search {
|
||||
use super::{score, score_for_direction};
|
||||
use pdfcraft_render::text::fold_case;
|
||||
|
||||
/// Word-order tolerance is RTL-only and still requires every requested word.
|
||||
#[test]
|
||||
fn rtl_palette_queries_accept_reordered_words_without_reversing_text() {
|
||||
let label = "تنظيم الصفحات";
|
||||
assert_eq!(score_for_direction(label, &fold_case("الصفحات تنظيم"), true), Some(0));
|
||||
assert_eq!(score_for_direction(label, &fold_case("تنظيم الصفحات"), true), Some(0));
|
||||
assert_eq!(score_for_direction(label, &fold_case("الصفحات مفقود"), true), None);
|
||||
assert_eq!(score_for_direction(label, &fold_case("الصفحات تنظيم"), false), None);
|
||||
assert_eq!(score_for_direction("Organize Pages", &fold_case("Pages Organize"), false), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_match_in_any_case_with_turkish_i() {
|
||||
assert_eq!(score("İçe aktar", &fold_case("içe")), Some(0));
|
||||
assert_eq!(score("Yazdır", &fold_case("YAZDIR")), Some(0));
|
||||
assert_eq!(score("Insert Pages", &fold_case("ınsert")), Some(0));
|
||||
assert_eq!(score("Print", &fold_case("print")), Some(0));
|
||||
assert_eq!(score("Print", &fold_case("zz")), None);
|
||||
}
|
||||
}
|
||||
+78
-309
@@ -4,18 +4,17 @@
|
||||
//! Items run registry commands (`pdfcraft_engine::commands`) by id, with the registry's label and
|
||||
//! shortcut, so a menu click and its shortcut run the same command. A few items have menu-only
|
||||
//! ids: the zoom keys the document view handles itself, the side panel choices, the clipboard
|
||||
//! keys, the recent files and the open documents. [`PdfCraftApp::run_menu_command`] runs every
|
||||
//! one of them, once per click, whichever bar it came from.
|
||||
//! keys, the recent files and the open documents. Each is a command of the app's catalog
|
||||
//! (`commands::catalog`), fired once per click, whichever bar it came from.
|
||||
|
||||
use craft_keymap::{Key, Mods};
|
||||
use craft_menu::{
|
||||
Builtin, Chord, CommandRef, Document, Gate, Item, ItemRole, ItemState, Labeled, LayoutOptions, Menu, MenuBar, MenuRole, Node, Target,
|
||||
use craft::keymap::{Key, Mods};
|
||||
use craft::ui::runtime::commands::{FireSource, fire, resolve};
|
||||
use craft::menu::{
|
||||
Chord, CommandRef, Document, Gate, Item, ItemRole, ItemState, Labeled, Layout, LayoutOptions, Menu, MenuBar, MenuRole, Node, Target,
|
||||
};
|
||||
use pdfcraft_engine::catalog::{Availability, TOOL_GROUPS};
|
||||
use pdfcraft_engine::commands::{self, Shortcut};
|
||||
|
||||
use crate::canvas::{Fit, PageLayout};
|
||||
use crate::theme::ThemePreference;
|
||||
use crate::{PdfCraftApp, RightPanel};
|
||||
|
||||
pub(super) mod tab_context;
|
||||
@@ -23,11 +22,6 @@ pub(super) mod tab_context;
|
||||
/// The app's name in the menus the layouts write (About, Hide, Quit).
|
||||
pub(crate) const APP_NAME: &str = "PdfCraft";
|
||||
|
||||
/// The top bar's width after the menus: the mode tabs, the search box and the buttons.
|
||||
const ROW_AFTER_MENUS: f32 = 720.0;
|
||||
/// The narrowest the menu bar gets: one "Menu" title.
|
||||
const MIN_MENUS_WIDTH: f32 = 80.0;
|
||||
|
||||
/// Menu-only commands. The registry's commands keep their own ids.
|
||||
pub(crate) const CUT: &str = "edit.cut";
|
||||
pub(crate) const PASTE: &str = "edit.paste";
|
||||
@@ -47,25 +41,19 @@ const ZOOM_OUT: &str = "view.zoom.out";
|
||||
const ROTATE_CW: &str = "view.rotate.cw";
|
||||
const ROTATE_CCW: &str = "view.rotate.ccw";
|
||||
|
||||
/// The menu-only items: id, English label and the shortcut shown (the keys stay with the view).
|
||||
const EXTRA: &[(&str, &str, Option<Shortcut>)] = &[
|
||||
/// The menu-only items: id, English label and the shortcut shown (the keys stay with the view). The
|
||||
/// zoom and rotate ids are registry commands; only Fit to height has no registry row.
|
||||
pub(crate) const EXTRA: &[(&str, &str, Option<Shortcut>)] = &[
|
||||
(CUT, "Cut", Some(Shortcut::cmd("X"))),
|
||||
(PASTE, "Paste", Some(Shortcut::cmd("V"))),
|
||||
(DELETE, "Delete", Some(Shortcut { command: false, shift: false, mac_ctrl: false, key: "Delete" })),
|
||||
(SELECT_ALL, "Select all", Some(crate::commands::SELECT_ALL)),
|
||||
(NO_RECENT, "No recent files", None),
|
||||
(ACTUAL_SIZE, "Actual size", Some(crate::commands::ACTUAL_SIZE)),
|
||||
(PAGE_LEVEL, "Zoom to page level", Some(crate::commands::PAGE_LEVEL)),
|
||||
(FIT_WIDTH, "Fit to width", Some(crate::commands::FIT_WIDTH)),
|
||||
(FIT_HEIGHT, "Fit to height", None),
|
||||
(ZOOM_IN, "Zoom in", Some(crate::commands::ZOOM_IN)),
|
||||
(ZOOM_OUT, "Zoom out", Some(crate::commands::ZOOM_OUT)),
|
||||
(ROTATE_CW, "Rotate view clockwise", Some(crate::commands::ROTATE_CW)),
|
||||
(ROTATE_CCW, "Rotate view counterclockwise", Some(crate::commands::ROTATE_CCW)),
|
||||
];
|
||||
|
||||
/// View ▸ Side panels: the panel, its id in [`PANEL`] commands and its English label.
|
||||
const PANELS: &[(RightPanel, &str, &str)] = &[
|
||||
pub(crate) const PANELS: &[(RightPanel, &str, &str)] = &[
|
||||
(RightPanel::Comments, "comments", "Comments"),
|
||||
(RightPanel::Bookmarks, "bookmarks", "Bookmarks"),
|
||||
(RightPanel::Pages, "pages", "Pages"),
|
||||
@@ -256,30 +244,36 @@ fn english(labeled: Labeled<'_>) -> Option<String> {
|
||||
match labeled {
|
||||
Labeled::Command(command) => english_label(command),
|
||||
Labeled::Title(shown) => TITLES.iter().find(|t| tl!(t) == shown).map(|t| (*t).to_owned()),
|
||||
// `Labeled` is non-exhaustive: a kind of label the bar adds later has no English name here.
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn translate(english: &'static str) -> String {
|
||||
// craft_menu's bar writes "⋯" (U+22EF, MIDLINE HORIZONTAL ELLIPSIS) itself, for the menu of
|
||||
// titles that don't fit: a sentinel to translate, not an English phrase, and the only one of
|
||||
// its four reserved labels no font this app ships or falls back to has a glyph for.
|
||||
// MissingGlyphPolicy::Panic (egui 0.37) crashes on it. The ordinary ellipsis every other
|
||||
// truncated label in this app already uses is in the bundled faces.
|
||||
if english == "\u{22ef}" {
|
||||
return "…".to_owned();
|
||||
}
|
||||
tl!(english).to_owned()
|
||||
}
|
||||
|
||||
/// The layouts' own labels (About, Quit, Window…) through the app's translations.
|
||||
pub(crate) fn layout_options() -> LayoutOptions<'static> {
|
||||
LayoutOptions { label: &translate, ..LayoutOptions::new(APP_NAME) }
|
||||
LayoutOptions::new(APP_NAME).label(&translate)
|
||||
}
|
||||
|
||||
/// Whether a dialog, a prompt or the command palette holds the window: the one gate over commands
|
||||
/// and the menus.
|
||||
pub(crate) fn gated(app: &PdfCraftApp) -> bool {
|
||||
app.modal_open() || app.palette_open
|
||||
}
|
||||
|
||||
/// Whether a text field has the keyboard: the one signal behind the Edit rows' state and the native
|
||||
/// menu's gate.
|
||||
pub(crate) fn text_editing(ctx: &egui::Context) -> bool {
|
||||
ctx.egui_wants_keyboard_input()
|
||||
}
|
||||
|
||||
impl PdfCraftApp {
|
||||
/// The app's menus for this frame, before the platform layout: every item's label, shortcut,
|
||||
/// enabled and checked state as the app is now. A modal dialog doesn't grey anything here;
|
||||
/// that is the [`Gate`]'s job ([`PdfCraftApp::menu_gate`]).
|
||||
/// enabled and checked state follow the item's command (`commands::catalog::command_input`). A
|
||||
/// modal dialog doesn't grey anything here; that is the command gate's job ([`gated`]).
|
||||
pub fn menu_bar(&self, ctx: &egui::Context) -> MenuBar {
|
||||
let mac = crate::commands::mac_shortcuts(ctx);
|
||||
let mut used: Vec<&str> = Vec::new();
|
||||
@@ -366,26 +360,22 @@ impl PdfCraftApp {
|
||||
view.push(Node::Separator);
|
||||
view.push(Node::submenu(tl!("Tools"), self.tools_menu(&used, mac)));
|
||||
view.extend(list(&["view.palette"], &mut used));
|
||||
let mut bar = MenuBar {
|
||||
menus: vec![
|
||||
Menu::new(tl!("File"), craft_menu::tidy(file)).role(MenuRole::File),
|
||||
Menu::new(tl!("Edit"), craft_menu::tidy(edit)).role(MenuRole::Edit),
|
||||
Menu::new(tl!("View"), craft_menu::tidy(view)).role(MenuRole::View),
|
||||
Menu::new(tl!("Sign"), craft_menu::tidy(sign)),
|
||||
Menu::new(tl!("Window"), window).role(MenuRole::Window),
|
||||
Menu::new(tl!("Help"), craft_menu::tidy(help)).role(MenuRole::Help),
|
||||
],
|
||||
documents: self.menu_documents(),
|
||||
};
|
||||
let mut bar = MenuBar::new(vec![
|
||||
Menu::new(tl!("File"), craft::menu::tidy(file)).role(MenuRole::File),
|
||||
Menu::new(tl!("Edit"), craft::menu::tidy(edit)).role(MenuRole::Edit),
|
||||
Menu::new(tl!("View"), craft::menu::tidy(view)).role(MenuRole::View),
|
||||
Menu::new(tl!("Sign"), craft::menu::tidy(sign)),
|
||||
Menu::new(tl!("Window"), window).role(MenuRole::Window),
|
||||
Menu::new(tl!("Help"), craft::menu::tidy(help)).role(MenuRole::Help),
|
||||
])
|
||||
.documents(self.menu_documents());
|
||||
bar.tag_item(&CommandRef::new("help.about"), ItemRole::About);
|
||||
bar.tag_item(&CommandRef::new("app.preferences"), ItemRole::Settings);
|
||||
craft_menu::apply_state(&mut bar, |command| self.menu_state(ctx, command));
|
||||
bar
|
||||
}
|
||||
|
||||
/// One item: a registry command with its live label (Undo names the edit) and shortcut, or a
|
||||
/// menu-only one. Radio and check items get their kind here, their state from
|
||||
/// [`PdfCraftApp::menu_state`].
|
||||
/// menu-only one. Radio items get their kind here, their state from the command.
|
||||
fn menu_item(&self, id: &'static str, label: Option<&str>, mac: bool) -> Node {
|
||||
let (english, shortcut) = match commands::command(id) {
|
||||
Some(spec) => {
|
||||
@@ -463,145 +453,25 @@ impl PdfCraftApp {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What may run from the menus now: a dialog, a prompt or the command palette holds the
|
||||
/// window. Edit's text items stay with a focused text field (craft-menu's gate).
|
||||
pub fn menu_gate(&self, ctx: &egui::Context) -> Gate {
|
||||
Gate { modal: self.modal_open() || self.palette_open, recording_shortcut: false, text_editing: ctx.text_edit_focused() }
|
||||
}
|
||||
|
||||
/// Whether a menu item's command can run now, and its checked or selected state.
|
||||
pub fn menu_state(&self, ctx: &egui::Context, command: &CommandRef) -> ItemState {
|
||||
let view = self.active.and_then(|i| self.views.get(i));
|
||||
let organize = view.is_some_and(|v| v.organize);
|
||||
let has_doc = view.is_some();
|
||||
let enabled_id = |id: &str| commands::command(id).is_some_and(|s| self.command_enabled(s));
|
||||
let index = param_index(command);
|
||||
let text = ctx.text_edit_focused() && matches!(command.id.as_str(), "edit.undo" | "edit.redo" | "edit.copy" | CUT | PASTE | SELECT_ALL);
|
||||
// Objects selected together in Edit a PDF are what Copy and Cut take, and Paste brings
|
||||
// back objects copied there.
|
||||
let edit_objects = self.quick_tool == crate::QuickTool::EditText && !organize;
|
||||
let doc = self.active_ids().and_then(|(_, id)| self.session.get(id));
|
||||
let enabled = text
|
||||
|| match command.id.as_str() {
|
||||
NO_RECENT => false,
|
||||
"file.open_recent" => index.is_none_or(|i| i < self.recent.len()),
|
||||
"file.clear_recent" => !self.recent.is_empty(),
|
||||
DOCUMENT => index.is_some_and(|i| i < self.views.len()),
|
||||
// macOS ⌘W closes the window when no document is open (#869).
|
||||
"file.close" if !has_doc && crate::commands::mac_shortcuts(ctx) && !cfg!(target_arch = "wasm32") => true,
|
||||
"edit.copy" if organize => enabled_id("page.copy"),
|
||||
"edit.copy" if view.is_some_and(|v| v.picked_image.is_some()) => {
|
||||
self.active_ids().and_then(|(_, id)| self.session.get(id)).is_some_and(|d| d.allows_copying())
|
||||
}
|
||||
"edit.copy" | CUT if edit_objects && view.is_some_and(|v| v.objects.count() > 0) => {
|
||||
doc.is_some_and(|d| d.allows_copying() && (command.id != CUT || d.allows_modification()))
|
||||
}
|
||||
PASTE if edit_objects && self.object_clipboard.is_some() => doc.is_some_and(pdfcraft_engine::Document::allows_modification),
|
||||
CUT => organize && enabled_id("page.cut"),
|
||||
PASTE => organize && self.page_clipboard.is_some() && enabled_id("page.paste"),
|
||||
SELECT_ALL | DELETE => has_doc,
|
||||
ACTUAL_SIZE | PAGE_LEVEL | FIT_WIDTH | FIT_HEIGHT | ZOOM_IN | ZOOM_OUT | ROTATE_CW | ROTATE_CCW => has_doc,
|
||||
PANEL => panel(command).is_some(),
|
||||
id => enabled_id(id),
|
||||
};
|
||||
let checked = match command.id.as_str() {
|
||||
"view.layout.single" => Some(view.is_some_and(|v| v.layout == PageLayout::Single)),
|
||||
"view.layout.two_up" => Some(view.is_some_and(|v| v.layout == PageLayout::TwoUp)),
|
||||
"view.continuous" => Some(view.is_some_and(|v| v.continuous())),
|
||||
"view.page_gaps" => Some(view.is_some_and(|v| v.show_page_gaps)),
|
||||
"view.layout.cover" => Some(view.is_some_and(|v| v.cover)),
|
||||
"view.full_screen" => Some(self.full_screen),
|
||||
"view.read_mode" => Some(self.mode == crate::Mode::Read),
|
||||
"view.side_panel" => Some(self.right.is_some()),
|
||||
"view.tools_pane" => Some(self.left_open),
|
||||
"view.split" => Some(self.panes.split.is_some()),
|
||||
"view.theme.system" => Some(self.theme_preference == ThemePreference::System),
|
||||
"view.theme.light" => Some(self.theme_preference == ThemePreference::Light),
|
||||
"view.theme.dark" => Some(self.theme_preference == ThemePreference::Dark),
|
||||
PANEL => Some(panel(command).is_some_and(|p| self.right == Some(p))),
|
||||
_ => None,
|
||||
};
|
||||
ItemState { enabled, checked }
|
||||
}
|
||||
|
||||
/// Run a command chosen in either menu bar. Registry commands go through
|
||||
/// [`PdfCraftApp::dispatch_command`], as their shortcuts do; the clipboard items act as
|
||||
/// their keys would (⌘C is a Copy event, Delete a key press), so every place that handles the
|
||||
/// key handles the click. A command that can't run now (a dialog opened since the menu was
|
||||
/// drawn) does nothing.
|
||||
pub fn run_menu_command(&mut self, ctx: &egui::Context, command: &CommandRef) {
|
||||
// Both menu bars run Quit and Minimize themselves; Hide and Hide Others are AppKit's.
|
||||
if Builtin::of(command).is_some() {
|
||||
return;
|
||||
}
|
||||
if !self.menu_gate(ctx).allows_command(command) || !self.menu_state(ctx, command).enabled {
|
||||
return;
|
||||
}
|
||||
let index = param_index(command);
|
||||
let key = |key: egui::Key, modifiers: egui::Modifiers| {
|
||||
[true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers })
|
||||
};
|
||||
match command.id.as_str() {
|
||||
"file.open_recent" if index.is_some() => {
|
||||
if let Some(path) = index.and_then(|i| self.recent.get(i)).map(|r| r.path.clone()) {
|
||||
self.open_recent(&path);
|
||||
}
|
||||
}
|
||||
DOCUMENT => {
|
||||
if let Some(i) = index.filter(|&i| i < self.views.len()) {
|
||||
self.active = Some(i);
|
||||
}
|
||||
}
|
||||
"edit.copy" => self.menu_input.push(egui::Event::Copy),
|
||||
CUT => self.menu_input.push(egui::Event::Cut),
|
||||
PASTE => self.menu_pastes = self.menu_pastes.saturating_add(1),
|
||||
SELECT_ALL => self.menu_input.extend(key(egui::Key::A, egui::Modifiers::COMMAND)),
|
||||
DELETE => self.menu_input.extend(key(egui::Key::Delete, egui::Modifiers::NONE)),
|
||||
PANEL => self.choose_right_panel(panel(command)),
|
||||
ACTUAL_SIZE | PAGE_LEVEL | FIT_WIDTH | FIT_HEIGHT | ZOOM_IN | ZOOM_OUT | ROTATE_CW | ROTATE_CCW => {
|
||||
let Some(v) = self.active.and_then(|i| self.views.get_mut(i)) else { return };
|
||||
match command.id.as_str() {
|
||||
ACTUAL_SIZE => v.set_zoom(1.0),
|
||||
PAGE_LEVEL => v.fit = Fit::Page,
|
||||
FIT_WIDTH => v.fit = Fit::Width,
|
||||
FIT_HEIGHT => {
|
||||
v.fit = Fit::Height;
|
||||
v.goto = Some((v.current, 0.0));
|
||||
}
|
||||
ZOOM_IN => v.zoom_step(true),
|
||||
ZOOM_OUT => v.zoom_step(false),
|
||||
ROTATE_CW => v.rotate_view(true),
|
||||
_ => v.rotate_view(false),
|
||||
}
|
||||
}
|
||||
id => {
|
||||
if let Some(spec) = commands::command(id) {
|
||||
self.dispatch_command(ctx, spec.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.request_repaint();
|
||||
/// The native macOS bar's layout with the state AppKit shows: each item's enabled and checked
|
||||
/// state is its command's, read from the board. The one reader of command state for the native
|
||||
/// bar.
|
||||
pub(crate) fn native_bar(&self, ctx: &egui::Context) -> Layout {
|
||||
let mut layout = craft::menu::mac_layout(&self.menu_bar(ctx), &layout_options());
|
||||
craft::menu::apply_state(&mut layout.bar, |command| {
|
||||
let resolved = resolve(ctx, command.clone());
|
||||
ItemState::default().enabled(resolved.enabled).checked(resolved.checked)
|
||||
});
|
||||
layout
|
||||
}
|
||||
|
||||
/// The menu bar drawn in the window (Windows, Linux, the web, and macOS when the native one
|
||||
/// couldn't be installed), where the top bar starts. Runs the commands chosen.
|
||||
pub(crate) fn menu_bar_ui(&mut self, ui: &mut egui::Ui) {
|
||||
/// couldn't be installed), where the top bar starts. A chosen command fires through the board.
|
||||
pub(crate) fn menu_bar_ui(&self, ui: &mut egui::Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let bar = craft_menu::layout(&self.menu_bar(&ctx), Target::current(), &layout_options()).bar;
|
||||
let gate = self.menu_gate(&ctx);
|
||||
// The mode tabs, search and buttons follow the bar in the same row: it takes its titles'
|
||||
// width, less when the row is short, where the menus that don't fit move into its "⋯".
|
||||
let fit = (ui.available_width() - ROW_AFTER_MENUS).max(MIN_MENUS_WIDTH);
|
||||
let chosen = craft_menu::MenuBarUi::new(&bar)
|
||||
.gate(gate)
|
||||
.label(&translate)
|
||||
.english(&english)
|
||||
.id(egui::Id::unique("pdfcraft-menu-bar"))
|
||||
.shrink_to_fit(fit)
|
||||
.show(ui);
|
||||
for command in chosen {
|
||||
self.run_menu_command(&ctx, &command);
|
||||
}
|
||||
let bar = craft::menu::layout(&self.menu_bar(&ctx), Target::current(), &layout_options()).bar;
|
||||
let modal = gated(self);
|
||||
craft::menu::MenuBarUi::new(&bar).keyboard(!modal).english(&english).show(ui);
|
||||
}
|
||||
|
||||
/// Install the native menu bar (macOS), once, from the eframe app creator. `false` when
|
||||
@@ -609,55 +479,49 @@ impl PdfCraftApp {
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn install_native_menu(&mut self, ctx: &egui::Context) -> bool {
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_pref(&self.language));
|
||||
let bar = craft_menu::mac_layout(&self.menu_bar(ctx), &layout_options()).bar;
|
||||
let bar = self.native_bar(ctx).bar;
|
||||
// The Window menu lists the open documents itself, so AppKit's window list stays off.
|
||||
self.native_menu = craft_menu::mac::install_with(ctx, &bar, craft_menu::mac::MacOptions::default().window_list(false));
|
||||
self.native_menu = craft::menu::mac::install_with(ctx, &bar, craft::menu::mac::MacOptions::default().window_list(false));
|
||||
self.native_menu.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// The native menu's clicks since the last frame, run like in-window ones.
|
||||
pub(crate) fn native_menu_clicks(&mut self, ctx: &egui::Context) {
|
||||
let gate = self.menu_gate(ctx);
|
||||
let Some(native) = self.native_menu.as_mut() else { return };
|
||||
native.set_gate(gate);
|
||||
for command in native.take_clicks(ctx) {
|
||||
self.run_menu_command(ctx, &command);
|
||||
}
|
||||
/// The native menu's per-frame turn: its gate, its clicks fired as commands, then its bar brought in
|
||||
/// step with the app, last, after this frame's changes.
|
||||
pub(crate) fn frame(app: &mut PdfCraftApp, ctx: &egui::Context) {
|
||||
if app.native_menu.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
/// Bring the native menu in step with the app, after this frame's changes.
|
||||
pub(crate) fn sync_native_menu(&mut self, ctx: &egui::Context) {
|
||||
if self.native_menu.is_none() {
|
||||
return;
|
||||
}
|
||||
let layout = craft_menu::mac_layout(&self.menu_bar(ctx), &layout_options());
|
||||
let gate = self.menu_gate(ctx);
|
||||
if let Some(native) = self.native_menu.as_mut() {
|
||||
native.set_gate(gate);
|
||||
for clash in native.sync(layout) {
|
||||
log::info!("menu shortcut {:?} kept by {} over {} ({})", clash.shortcut, clash.command.id, clash.system, clash.resolution);
|
||||
}
|
||||
let gate = Gate::default().modal(gated(app)).text_editing(text_editing(ctx));
|
||||
let clicks = app.native_menu.as_mut().map(|native| {
|
||||
native.set_gate(gate);
|
||||
native.take_clicks(ctx)
|
||||
});
|
||||
for command in clicks.unwrap_or_default() {
|
||||
fire(ctx, command, FireSource::Menu);
|
||||
}
|
||||
let layout = app.native_bar(ctx);
|
||||
if let Some(native) = app.native_menu.as_mut() {
|
||||
for clash in native.sync(layout) {
|
||||
log::info!("menu shortcut {:?} kept by {} over {} ({})", clash.shortcut, clash.command.id, clash.system, clash.resolution);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A command's `{"index": n}` parameter.
|
||||
fn param_index(command: &CommandRef) -> Option<usize> {
|
||||
pub(crate) fn param_index(command: &CommandRef) -> Option<usize> {
|
||||
command.params.get("index").and_then(serde_json::Value::as_u64).and_then(|i| usize::try_from(i).ok())
|
||||
}
|
||||
|
||||
/// The side panel a [`PANEL`] command names.
|
||||
fn panel(command: &CommandRef) -> Option<RightPanel> {
|
||||
pub(crate) fn panel(command: &CommandRef) -> Option<RightPanel> {
|
||||
let name = command.params.get("panel").and_then(serde_json::Value::as_str)?;
|
||||
PANELS.iter().find(|(_, n, _)| *n == name).map(|(p, ..)| *p)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_menu::{Backend, Dispatch, Event, ItemKind, NativeMenu};
|
||||
use craft::menu::Builtin;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -673,29 +537,13 @@ mod tests {
|
||||
}
|
||||
|
||||
fn linux(app: &PdfCraftApp, ctx: &egui::Context) -> MenuBar {
|
||||
craft_menu::layout(&app.menu_bar(ctx), Target::Linux, &layout_options()).bar
|
||||
craft::menu::layout(&app.menu_bar(ctx), Target::Linux, &layout_options()).bar
|
||||
}
|
||||
|
||||
fn item<'b>(bar: &'b MenuBar, command: &CommandRef) -> &'b Item {
|
||||
bar.find(command).unwrap_or_else(|| panic!("{} is in the menus", command.key()))
|
||||
}
|
||||
|
||||
/// The bar's own overflow-menu sentinel is not rendered as typed: no font this app ships or
|
||||
/// falls back to has U+22EF, and egui 0.37's `MissingGlyphPolicy::Panic` crashes on it when
|
||||
/// the menu bar is narrow enough to need it. The editing tests that narrow the window while a
|
||||
/// paragraph is open reproduce this end to end. The other three reserved labels are plain
|
||||
/// ASCII, so untranslated is safe for them.
|
||||
#[test]
|
||||
fn the_overflow_menu_sentinel_is_not_passed_through_untranslated() {
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let translated = translate("⋯");
|
||||
assert_ne!(translated, "⋯", "no installed font has this glyph");
|
||||
assert_eq!(translated, "…", "the ordinary ellipsis the rest of the app already uses");
|
||||
for label in ["Menu", "Scroll menu up", "Scroll menu down"] {
|
||||
assert_eq!(translate(label), label, "plain ASCII reserved labels need no substitution");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_menu_command_is_listed_once_with_its_shortcut() {
|
||||
let (app, ctx) = app(&["a.pdf"]);
|
||||
@@ -724,45 +572,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_and_radio_items_follow_the_app() {
|
||||
let (mut app, ctx) = app(&["a.pdf"]);
|
||||
let kind = |app: &PdfCraftApp, id: &str| item(&linux(app, &ctx), &CommandRef::new(id)).kind;
|
||||
assert_eq!(kind(&app, "view.layout.single"), ItemKind::Radio(true));
|
||||
assert_eq!(kind(&app, "view.layout.two_up"), ItemKind::Radio(false));
|
||||
let continuous = app.views[0].continuous();
|
||||
assert_eq!(kind(&app, "view.continuous"), ItemKind::Check(continuous));
|
||||
app.run_menu_command(&ctx, &CommandRef::new("view.layout.two_up"));
|
||||
app.run_menu_command(&ctx, &CommandRef::new("view.continuous"));
|
||||
assert_eq!(kind(&app, "view.layout.single"), ItemKind::Radio(false));
|
||||
assert_eq!(kind(&app, "view.layout.two_up"), ItemKind::Radio(true));
|
||||
assert_eq!(kind(&app, "view.continuous"), ItemKind::Check(!continuous));
|
||||
let left = app.left_open;
|
||||
assert_eq!(kind(&app, "view.tools_pane"), ItemKind::Check(left));
|
||||
app.run_menu_command(&ctx, &CommandRef::new("view.tools_pane"));
|
||||
assert_eq!(kind(&app, "view.tools_pane"), ItemKind::Check(!left));
|
||||
let bookmarks = CommandRef::with_params(PANEL, serde_json::json!({ "panel": "bookmarks" }));
|
||||
app.run_menu_command(&ctx, &bookmarks);
|
||||
assert_eq!(app.right, Some(RightPanel::Bookmarks));
|
||||
assert_eq!(item(&linux(&app, &ctx), &bookmarks).kind, ItemKind::Radio(true));
|
||||
assert_eq!(kind(&app, "view.side_panel"), ItemKind::Check(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_greys_document_commands_and_drops_their_clicks() {
|
||||
let (mut app, ctx) = app(&["a.pdf"]);
|
||||
let rotate = CommandRef::new("page.rotate");
|
||||
assert!(app.menu_gate(&ctx).allows_command(&rotate));
|
||||
app.dialog = Some(crate::Dialog::About);
|
||||
assert!(!app.menu_gate(&ctx).allows_command(&rotate), "the gate greys the menus under a dialog");
|
||||
let doc = app.views[0].id;
|
||||
let before = app.session.get(doc).unwrap().info.pages[0].rotation;
|
||||
app.run_menu_command(&ctx, &rotate);
|
||||
assert_eq!(app.session.get(doc).unwrap().info.pages[0].rotation, before, "a click that arrives anyway does nothing");
|
||||
// Quit still asks the window to close, which asks about unsaved changes.
|
||||
assert!(app.menu_gate(&ctx).allows_command(&Builtin::Quit.command()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_files_and_open_documents_are_listed_once_each() {
|
||||
let (mut app, ctx) = app(&["a.pdf", "b.pdf"]);
|
||||
@@ -781,53 +590,13 @@ mod tests {
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(documents, ["a.pdf", "b.pdf"], "each open document once, in tab order");
|
||||
app.run_menu_command(&ctx, &CommandRef::with_params(DOCUMENT, serde_json::json!({ "index": 0 })));
|
||||
assert_eq!(app.active, Some(0));
|
||||
// The macOS layout lists them once too.
|
||||
let mac = craft_menu::mac_layout(&app.menu_bar(&ctx), &layout_options()).bar;
|
||||
let mac = craft::menu::mac_layout(&app.menu_bar(&ctx), &layout_options()).bar;
|
||||
let listed = mac.items().iter().filter(|it| it.command.id == DOCUMENT).count();
|
||||
assert_eq!(listed, 2);
|
||||
app.recent.clear();
|
||||
let bar = linux(&app, &ctx);
|
||||
assert!(!item(&bar, &CommandRef::new(NO_RECENT)).enabled, "an empty list shows a greyed placeholder");
|
||||
assert!(bar.find(&CommandRef::new(NO_RECENT)).is_some(), "an empty list shows a placeholder");
|
||||
assert!(bar.find(&CommandRef::new("file.clear_recent")).is_none());
|
||||
}
|
||||
|
||||
/// A native backend that reports what the test queues, through the driver's dispatch as the
|
||||
/// macOS backend does.
|
||||
#[derive(Clone, Default)]
|
||||
struct FakeMenu(Rc<RefCell<(Option<Dispatch>, Vec<Event>)>>);
|
||||
|
||||
impl FakeMenu {
|
||||
fn click(&self, command: &CommandRef) {
|
||||
let mut state = self.0.borrow_mut();
|
||||
let event = state.0.as_ref().map(|d| d.chosen(command, None, false, None));
|
||||
state.1.extend(event);
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for FakeMenu {
|
||||
fn sync(&mut self, _bar: &MenuBar) {}
|
||||
fn drain(&mut self) -> Vec<Event> {
|
||||
std::mem::take(&mut self.0.borrow_mut().1)
|
||||
}
|
||||
fn attach(&mut self, dispatch: Dispatch) {
|
||||
self.0.borrow_mut().0 = Some(dispatch);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_native_menu_click_runs_its_command_once() {
|
||||
let (mut app, ctx) = app(&["a.pdf"]);
|
||||
let fake = FakeMenu::default();
|
||||
app.native_menu = Some(NativeMenu::new(Box::new(fake.clone())));
|
||||
let doc = app.views[0].id;
|
||||
let before = app.session.get(doc).unwrap().info.pages[0].rotation;
|
||||
fake.click(&CommandRef::new("page.rotate"));
|
||||
let mut raw = egui::RawInput::default();
|
||||
app.prepare_raw_input(&ctx, &mut raw);
|
||||
app.native_menu_clicks(&ctx);
|
||||
app.native_menu_clicks(&ctx);
|
||||
assert_eq!(app.session.get(doc).unwrap().info.pages[0].rotation, (before + 90) % 360, "rotated once");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,17 @@
|
||||
//! input in the frames the platform delivers it in ([`input`]), and the skip for tests whose text
|
||||
//! the interface fonts cannot draw ([`skip_without_glyphs`]).
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use egui::FontId;
|
||||
use egui::epaint::text::{Fonts, TextOptions};
|
||||
use egui_kittest::Harness;
|
||||
use pdfcraft_ui_egui::{PdfCraftApp, i18n, theme};
|
||||
use craft::ui::runtime::commands::{FireSource, fire};
|
||||
use craft::ui::runtime::env::WindowKey;
|
||||
use craft::ui::runtime::toast;
|
||||
use craft::host::{Host, Wake};
|
||||
use craft::keymap::CommandRef;
|
||||
use pdfcraft_ui_egui::{AppServices, FileIntake, FileWatch, PdfCraftApp, i18n};
|
||||
|
||||
pub mod fixtures;
|
||||
pub mod input;
|
||||
@@ -44,14 +50,74 @@ pub fn wait_until(h: &mut Harness<'static, PdfCraftApp>, what: &str, ready: impl
|
||||
let held = step_until(h, |h| ready(h.state()));
|
||||
assert!(
|
||||
held,
|
||||
"timed out waiting for {what}: views={}, active={:?}, password={:?}, toast={:?}",
|
||||
"timed out waiting for {what}: views={}, active={:?}, password={:?}",
|
||||
h.state().views.len(),
|
||||
h.state().active,
|
||||
h.state().password_prompt.as_ref().map(|p| (&p.name, &p.error)),
|
||||
h.state().toast
|
||||
);
|
||||
}
|
||||
|
||||
/// Fire `command` as a menu row does, through the board, and run a frame. For a command with
|
||||
/// parameters (`window.document`), pass a `CommandRef` with them.
|
||||
pub fn fire_menu(h: &mut Harness<'static, PdfCraftApp>, command: impl Into<CommandRef>) {
|
||||
fire(&h.ctx, command.into(), FireSource::Menu);
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// The text of the first notice card the main window shows, if any.
|
||||
pub fn shown_notice(h: &mut Harness<'static, PdfCraftApp>) -> Option<String> {
|
||||
toast::cards(&h.ctx, &WindowKey::main()).first().map(|card| card.toast.message.as_str().to_owned())
|
||||
}
|
||||
|
||||
/// An app built over `host`, with no wake, an inline file watch and a test file intake: the one way a
|
||||
/// test gives the app a host, so jobs and picked files run when the test steps.
|
||||
pub fn host_harness(host: Arc<Host>, clipboard: RecordingClipboard) -> Harness<'static, PdfCraftApp> {
|
||||
// PLAN: assumed `AppServices::new(wake, clipboard, recovery_dir, update_source, intake, watch)`,
|
||||
// `FileIntake::for_tests()`, `FileWatch::inline()` and `PdfCraftApp::with_host(Arc<Host>, AppServices)` (pdf-hub-w1, L-207)
|
||||
let services = AppServices::new(Wake::none(), Box::new(clipboard), None, None, FileIntake::for_tests(), FileWatch::inline());
|
||||
let app = PdfCraftApp::with_host(host, services);
|
||||
Harness::new_ui_state(|ui, app: &mut PdfCraftApp| app.ui(ui), app)
|
||||
}
|
||||
|
||||
/// A clipboard backend the tests share: what the app copies is read back through the clone the test keeps.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct RecordingClipboard {
|
||||
text: Arc<Mutex<Option<String>>>,
|
||||
}
|
||||
|
||||
impl RecordingClipboard {
|
||||
/// The text the app last copied.
|
||||
pub fn copied(&self) -> Option<String> {
|
||||
self.text.lock().ok().and_then(|text| text.clone())
|
||||
}
|
||||
}
|
||||
|
||||
// PLAN: assumed `ClipboardBackend` with `get_text` and `set_text` (craft::platform::clipboard)
|
||||
impl craft::platform::clipboard::ClipboardBackend for RecordingClipboard {
|
||||
fn get_text(&self) -> Option<String> {
|
||||
self.copied()
|
||||
}
|
||||
|
||||
fn set_text(&self, text: &str) {
|
||||
if let Ok(mut held) = self.text.lock() {
|
||||
*held = Some(text.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Step `frames` frames and return every URL the app asked the platform to open, in order.
|
||||
pub fn step_collecting_urls(h: &mut Harness<'static, PdfCraftApp>, frames: usize) -> Vec<String> {
|
||||
let mut urls = Vec::new();
|
||||
for _ in 0..frames {
|
||||
h.step();
|
||||
urls.extend(h.output().platform_output.commands.iter().filter_map(|command| match command {
|
||||
egui::OutputCommand::OpenUrl(open) => Some(open.url.clone()),
|
||||
_ => None,
|
||||
}));
|
||||
}
|
||||
urls
|
||||
}
|
||||
|
||||
/// Open the in-window menu bar's `title` menu (File, Edit, View…).
|
||||
pub fn open_menu(h: &mut Harness<'static, PdfCraftApp>, title: &str) {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
@@ -83,9 +149,7 @@ pub fn outside_menus<'h>(h: &'h Harness<'static, PdfCraftApp>, label: &str) -> e
|
||||
/// panic on a missing glyph, and Japanese, Chinese and Thai faces come only from the optional
|
||||
/// craft-fonts build input or a face installed on this machine. Prints the skip line.
|
||||
///
|
||||
/// The fonts are those the app installs for `language` and for the default CJK preference: a
|
||||
/// switch to Chinese installs its fonts for the next frame, so the first frame in Chinese draws
|
||||
/// with the fonts of the language before it.
|
||||
/// The fonts are the interface stack of `language`, which already holds the language's faces.
|
||||
///
|
||||
/// A build that requires craft-fonts (`CRAFT_FONTS_REQUIRED=1`, as the CI gate sets) never skips:
|
||||
/// a missing glyph there is a failure.
|
||||
@@ -96,13 +160,11 @@ pub fn skip_without_glyphs(name: &str, language: &str, text: &str) -> bool {
|
||||
let catalogs: Vec<&str> = i18n::Lang::from_code(language).into_iter().flat_map(i18n::Lang::catalog_texts).collect();
|
||||
let translations = catalogs.iter().flat_map(|c| c.lines()).filter(|l| !l.starts_with('#')).filter_map(|l| l.split('\t').nth(2));
|
||||
let chars: BTreeSet<char> = std::iter::once(text).chain(translations).flat_map(str::chars).filter(|c| !c.is_control()).collect();
|
||||
let cjk = theme::CjkPreference::for_language(language);
|
||||
let missing = [theme::CjkPreference::Default, cjk].into_iter().find_map(|cjk| {
|
||||
let defs = theme::installed_font_definitions(cjk);
|
||||
let families: Vec<FontId> = defs.families.keys().map(|f| FontId::new(13.0, f.clone())).collect();
|
||||
let mut fonts = Fonts::new(TextOptions::default(), defs);
|
||||
chars.iter().copied().find(|c| families.iter().any(|id| !fonts.has_glyphs(id, &c.to_string())))
|
||||
});
|
||||
// PLAN: assumed `fonts::ui_fonts(language)` (pdf-shell-w10); `fonts` must be `pub mod` for tests.
|
||||
let defs: egui::FontDefinitions = pdfcraft_ui_egui::fonts::ui_fonts(language).stack().flat_definitions();
|
||||
let families: Vec<FontId> = defs.families.keys().map(|f| FontId::new(13.0, f.clone())).collect();
|
||||
let mut fonts = Fonts::new(TextOptions::default(), defs);
|
||||
let missing = chars.iter().copied().find(|c| families.iter().any(|id| !fonts.has_glyphs(id, &c.to_string())));
|
||||
let Some(missing) = missing else {
|
||||
return false;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user