Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions apps/rustgis/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -789,12 +789,13 @@ fn main() -> eframe::Result {
Ok(_) => Some("the settings folder can't lock files, so a second copy of RustGIS couldn't be told apart".into()),
Err(no) => Some(no.why.clone()),
};
// The keys the macOS menu bar keeps, before the stored shortcuts load: the keymap leaves them
// out and the shortcut editor refuses them.
// The macOS menu's keys, before stored shortcuts load: consumed keys stay out of the keymap;
// a forwarded key may keep its own command, and the editor refuses other commands on it.
#[cfg(target_os = "macos")]
let app = {
let mut app = app;
app.ui.reserved_shortcuts = menu::reserved();
app.ui.forwarded_shortcuts = menu::forwarded();
app
};
let mut app = app.with_services(services);
Expand Down
35 changes: 31 additions & 4 deletions apps/rustgis/src/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub enum Action {
Cut,
Copy,
Paste,
/// Selects all of a focused text field (⌘A, as egui reads it).
/// Presses ⌘A: a focused text field or select.all takes it.
SelectAll,
/// Closes the window: the save prompt asks first.
CloseWindow,
Expand Down Expand Up @@ -427,7 +427,8 @@ pub fn clipboard_text() -> Option<String> {
}

/// The key combinations the menu bar keeps: its items' fixed ones and macOS's own (Hide, Hide
/// Others, Minimize). A shortcut on one would never reach the app.
/// Others, Minimize). A shortcut on one would never reach the app, except the menu's own
/// commands whose keys it forwards ([`forwarded`]).
pub fn reserved() -> Vec<KeyboardShortcut> {
let cmd = |m: Modifiers, key: Key| KeyboardShortcut::new(Modifiers::COMMAND | m, key);
let mut keys: Vec<KeyboardShortcut> = MENUS
Expand All @@ -442,6 +443,22 @@ pub fn reserved() -> Vec<KeyboardShortcut> {
keys
}

/// Fixed menu keys sent back as key events: they may keep their own command in the keymap,
/// while a focused text field still takes them first. Other commands cannot take these keys.
pub fn forwarded() -> Vec<(KeyboardShortcut, &'static str)> {
MENUS
.iter()
.flat_map(|(_, rows)| rows.iter())
.filter_map(|row| match *row {
Item(_, SelectAll, Some((key, shift))) => Some((
KeyboardShortcut::new(if shift { Modifiers::COMMAND | Modifiers::SHIFT } else { Modifiers::COMMAND }, key),
"select.all",
)),
_ => None,
})
.collect()
}

/// Whether a native panel (a file dialog) has the keys rather than the app's window.
fn panel_has_keys() -> bool {
use objc2::MainThreadMarker;
Expand Down Expand Up @@ -496,10 +513,14 @@ mod tests {
use rustgis_engine::{Project, Session};

/// Every item runs a command that exists, with parameters that parse; a fixed shortcut isn't
/// one the keymap gives another command; every shortcut shown has ⌘ and a key code.
/// one the keymap gives another command (Select All forwards its own); every shortcut shown
/// has ⌘ and a key code.
#[test]
fn items_name_commands_that_exist() {
let mut app = RustGisApp::new(Session::new(Project::default()));
app.ui.reserved_shortcuts = reserved();
app.ui.forwarded_shortcuts = forwarded();
let mut app = app.with_services(Default::default());
// Those that open a native file dialog, quit or go online aren't run here.
const NOT_RUN: &[&str] = &["ui.open", "ui.save", "ui.saveAs", "ui.addData", "ui.quit", "ui.checkUpdate"];
let mut seen = 0;
Expand Down Expand Up @@ -530,7 +551,13 @@ mod tests {
if let Some((key, shift)) = fixed {
let k = KeyboardShortcut::new(if shift { Modifiers::COMMAND | Modifiers::SHIFT } else { Modifiers::COMMAND }, key);
let taken = app.shortcut_command(k);
assert!(taken.is_none(), "{label}: the keymap gives {key:?} to {taken:?}");
if action == SelectAll {
// The menu forwards ⌘A as a key event: the text field or select.all takes
// it, just as when typed. This binding is intentional, not a collision.
assert_eq!(taken.as_deref(), Some("select.all"), "{label}: its forwarded key");
} else {
assert!(taken.is_none(), "{label}: the keymap gives {key:?} to {taken:?}");
}
}
}
}
Expand Down
15 changes: 14 additions & 1 deletion crates/engine/src/tests/layout_report_text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,23 @@ fn a_report_image_says_the_text_of_its_first_page_alone() {
assert_eq!(reported(&mut s, "png"), [of_page(&s, 0, id)]);
}

/// The one-digit/two-digit wrap boundary uses the built-in face in a fresh process: installed
/// fonts can fit both in the box, which would test font discovery rather than page expansion.
#[test]
fn a_report_measures_each_layout_page_with_its_own_page_number() {
if std::env::var_os("RUSTGIS_REPORT_PAGE_NUMBER_CHILD").is_none() {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::layout_report_text::a_report_measures_each_layout_page_with_its_own_page_number", "--nocapture"])
.env("RUSTGIS_REPORT_PAGE_NUMBER_CHILD", "1")
.env("RUSTGIS_BUILTIN_FONTS", "1")
.output()
.unwrap();
assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"), "the test didn't run in the child process");
return;
}
let mut s = sheet();
// One line while the page number has one digit; two from page 10.
// Two lines, both drawn, while the page number has one digit; a third, cut off, from page 10.
let id = text(&mut s, 0, &["{page}"; 8].join(" "), 18.0, 6.0);
s.run("layout.update", &json!({"element": id, "wrap": true, "size": 10})).unwrap();
report(&mut s, &["Sheet"]);
Expand Down
12 changes: 9 additions & 3 deletions crates/render/src/layout/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5972,7 +5972,7 @@ const PINNED_LEGEND_MEASURES: [u64; 18] = [
0x0de9_b39c_7273_61da, // 14: no-data rows, two columns
0x6de4_4bc0_7e82_51cc, // 15: across the right edge
0xbf3a_eef4_592a_7206, // 16: shorter than its title
0x7249_b531_f330_3a30, // 17: nothing to list
0x4ad5_1f0c_6756_5855, // 17: nothing to list, zero heights canonicalized
0x18ef_3e69_73a3_50c9, // 18: what the frame draws, no-data asked
];

Expand Down Expand Up @@ -6025,8 +6025,14 @@ fn legends_draw_as_before() {
};
let sizes =
legend_sizes_with_no_data_mm(&mut maps[0], scale, *all_classes, *hide_other, (*show_no_data, *text_size), (exclude, labels));
// The first three only: these are the column counts main measures.
said.push_str(&format!("{:?}\n", sizes.map(|s| [s[0], s[1], s[2]])));
// The first three only: these are the column counts main measures. Adding positive zero
// canonicalizes signed zero, which empty sums/maxima can give different signs on different
// architectures, without rounding any other dimension or changing the drawing pins.
let sizes = sizes.map(|s| [s[0], s[1], s[2]].map(|(w, h)| (w + 0.0, h + 0.0)));
if page == 17 {
assert_eq!(sizes, Some([(0.0, 0.0); 3]), "the empty legend has no rows");
}
said.push_str(&format!("{sizes:?}\n"));
measured.push((format!("page {page}"), fnv_bytes(said.as_bytes())));
}
let mut wrong = crate::layout::pin_mismatches("drawing", &drawn, &PINNED_LEGEND_PIXELS);
Expand Down
9 changes: 7 additions & 2 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -995,8 +995,12 @@ pub struct UiState {
/// (#2390): on unless turned off.
pub sharp_tiles: bool,
/// Key combinations the native menu bar keeps for itself (macOS: Quit, Close Window, Hide…):
/// a shortcut on one would never reach the app, so the shortcut editor refuses them.
/// a shortcut on one would never reach the app, so the shortcut editor refuses them, except
/// their own commands in `forwarded_shortcuts`.
pub reserved_shortcuts: Vec<egui::KeyboardShortcut>,
/// Native menu keys forwarded to the app: only their own command may use the chord. A
/// focused text field still takes the event before the command, as when the key is typed.
pub forwarded_shortcuts: Vec<(egui::KeyboardShortcut, &'static str)>,
/// Files whose layers are being listed or chosen, the first one shown.
pub choosing: Vec<layerchooser::Chooser>,
/// The project last opened or saved on this computer, for Start With › Last Project.
Expand Down Expand Up @@ -1284,6 +1288,7 @@ impl Default for UiState {
download_grids: false,
sharp_tiles: true,
reserved_shortcuts: Vec::new(),
forwarded_shortcuts: Vec::new(),
choosing: Vec::new(),
last_project: None,
start_projection: String::new(),
Expand Down Expand Up @@ -1987,14 +1992,14 @@ impl RustGisApp {
rustgis_engine::render::rustgis_tiles::earthdata::set_secret_store(services.secrets.clone());
rustgis_engine::render::rustgis_tiles::copernicus::set_secret_store(services.secrets.clone());
self.services = services;
shortcutui::load(&mut self);
sourcespane::load_connections(&mut self);
autosave::load(&mut self);
if let Some(lang) = self.services.load_pref.as_ref().and_then(|load| load("language")) {
self.ui.language = lang;
}
// Theme readers and startup notices keep translated text, so select the language before reading.
i18n::set_current(self.chosen_lang());
shortcutui::load(&mut self);
// After the language, so a notice about the saved value is in it.
threadsui::load(&mut self);
// A stored value that is neither `auto` nor a known worldview means `auto`; `china`, as
Expand Down
55 changes: 43 additions & 12 deletions crates/ui-egui/src/shortcutfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ fn import_bindings<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<
pub(crate) struct Preview {
pub text: String,
pub summary: Value,
pub skipped: Vec<Chord>,
}

/// Route picker and dropped shortcut bytes without allocating a base64 copy of oversized input.
Expand Down Expand Up @@ -87,8 +88,9 @@ fn input(p: &Value) -> Result<String, String> {
String::from_utf8(bytes).map_err(|e| e.to_string())
}

/// Validate every record before exposing a preview or changing the live map.
fn merge(app: &RustGisApp, text: &str) -> Result<(Keymap, Value), String> {
/// Validate every record before exposing a preview or changing the live map, then apply only
/// bindings the native menu permits. A skipped assignment cannot displace a current binding.
fn merge(app: &RustGisApp, text: &str) -> Result<(Keymap, Value, Vec<Chord>), String> {
if text.len() > MAX_FILE_BYTES {
return Err(tl!("Shortcut file exceeds the size limit.").into());
}
Expand All @@ -101,20 +103,45 @@ fn merge(app: &RustGisApp, text: &str) -> Result<(Keymap, Value), String> {
return Err(tl!("Unsupported shortcut file version.").into());
}
let changes = serde_json::to_string(&doc.bindings).map_err(|e| e.to_string())?;
let mut merged = app.ui.keymap.clone();
if !merged.apply_preferences(&changes) {
return Err(tl!("Shortcut file contains invalid or reserved bindings.").into());
{
let mut checked = app.ui.keymap.clone();
if !checked.apply_preferences(&changes) {
return Err(tl!("Shortcut file contains invalid or reserved bindings.").into());
}
}
if merged.preferences(&Keymap::new(&app.session.registry)).is_none() {
return Err(tl!("Too many shortcut changes to save.").into());
// Validation above includes every record, even those this platform will leave out.
let mut skipped = Vec::new();
for change in &doc.bindings {
let chord = Chord::parse(&change.keys).ok_or(tl!("Invalid shortcut key."))?;
if !change.remove && shortcutui::reserved(app, chord, &change.command) {
skipped.push(chord);
}
}
let mut kept = Vec::new();
let mut assigned = std::collections::HashSet::new();
for change in &doc.bindings {
let chord = Chord::parse(&change.keys).ok_or(tl!("Invalid shortcut key."))?;
if !change.remove {
assigned.insert(chord);
// A rejected rebind must not remove its displaced default. After an accepted assignment,
// a removal is explicit and stays in the file's order.
let blocked = if change.remove {
skipped.contains(&chord) && !assigned.contains(&chord)
} else {
shortcutui::reserved(app, chord, &change.command)
};
if !blocked {
if !change.remove {
assigned.insert(chord);
}
kept.push(change);
}
}
let mut merged = app.ui.keymap.clone();
if !merged.apply_preferences(&serde_json::to_string(&kept).map_err(|e| e.to_string())?) {
return Err(tl!("Shortcut file contains invalid or reserved bindings.").into());
}
if merged.preferences(&Keymap::new(&app.session.registry)).is_none() {
return Err(tl!("Too many shortcut changes to save.").into());
}
let unknown = assigned
.iter()
.filter_map(|&chord| merged.command_for(chord))
Expand All @@ -130,7 +157,7 @@ fn merge(app: &RustGisApp, text: &str) -> Result<(Keymap, Value), String> {
.is_some_and(|new| app.ui.keymap.command_for(chord).is_some_and(|old| !old.runs(&new.command, &new.params)))
})
.count();
Ok((merged, json!({"bindings":doc.bindings.len(), "conflicts":conflicts, "unknown_commands":unknown})))
Ok((merged, json!({"bindings":kept.len(), "conflicts":conflicts, "unknown_commands":unknown, "skipped":skipped.len()}), skipped))
}

/// Include UI actions outside Command Search when recognizing portable command ids.
Expand Down Expand Up @@ -182,16 +209,17 @@ pub fn run(app: &mut RustGisApp, id: &str, p: &Value) -> Result<Value, String> {
return Ok(Value::Null);
}
let text = input(p)?;
let (merged, summary) = merge(app, &text)?;
let (merged, summary, skipped) = merge(app, &text)?;
if p.get("confirm").and_then(Value::as_bool).unwrap_or(false) {
if app.ui.shortcut_preferences_blocked {
return Err(tl!("Reset unreadable saved shortcuts before importing.").into());
}
app.ui.keymap = merged;
shortcutui::save(app);
app.ui.shortcut_editor.import = None;
shortcutui::report_skipped(app, &skipped);
} else {
app.ui.shortcut_editor.import = Some(Preview { text, summary: summary.clone() });
app.ui.shortcut_editor.import = Some(Preview { text, summary: summary.clone(), skipped });
app.ui.shortcut_editor.open = true;
}
Ok(summary)
Expand Down Expand Up @@ -245,6 +273,9 @@ pub fn run(app: &mut RustGisApp, id: &str, p: &Value) -> Result<Value, String> {
}
}
}
if next.bindings.iter().any(|b| shortcutui::reserved(app, b.chord, &b.command)) {
return Err(tl!("Invalid or reserved shortcut key.").into());
}
if next.preferences(&defaults).is_none() {
return Err(tl!("Too many shortcut changes to save.").into());
}
Expand Down
Loading
Loading