use std::cell::{OnceCell, RefCell};
use std::path::{Path, PathBuf};
use std::rc::{Rc, Weak};
use ledgeline_core::ui_prefs::BootAppearance;
use muda::{
IsMenuItem, Menu, MenuId, MenuItem, PredefinedMenuItem, Submenu,
accelerator::{Accelerator, Code, Modifiers},
};
#[cfg(target_os = "linux")]
use tao::keyboard::{Key, ModifiersState};
use tao::{
dpi::LogicalSize,
event_loop::EventLoop,
window::{Window, WindowBuilder},
};
use url::Url;
use wry::{NewWindowResponse, PageLoadEvent, WebViewBuilder};
use crate::security::in_spa;
use crate::{AppDirs, AppIdentity, recents};
#[cfg(target_os = "macos")]
pub mod file_assoc;
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub struct GuiError(String);
pub fn spawn_server<F>(
app: &'static AppIdentity,
runtime: &tokio::runtime::Runtime,
host: &str,
port: u16,
router_for: F,
) -> tokio::sync::oneshot::Receiver<Option<u16>>
where
F: FnOnce(u16) -> Result<axum::Router, String> + Send + 'static,
{
let (port_tx, port_rx) = tokio::sync::oneshot::channel::<Option<u16>>();
let addr = format!("{host}:{port}");
runtime.spawn(async move {
let prefix = app.log_prefix;
match tokio::net::TcpListener::bind(&addr).await {
Ok(listener) => {
let bound = listener.local_addr().map(|a| a.port()).ok();
let _ = port_tx.send(bound);
let router = match bound.map(router_for) {
Some(Ok(router)) => router,
Some(Err(error)) => {
eprintln!("{prefix}: security setup failed: {error}");
return;
}
None => return,
};
if let Err(error) = axum::serve(listener, router).await {
eprintln!("{prefix}: server error: {error}");
}
}
Err(error) => {
eprintln!("{prefix}: bind error on {addr}: {error}");
let _ = port_tx.send(None);
}
}
});
port_rx
}
#[cfg(target_os = "macos")]
fn about_metadata(app: &AppIdentity, version: &str) -> muda::AboutMetadata {
muda::AboutMetadata {
name: Some(app.name.to_string()),
version: Some(version.to_string()),
..Default::default()
}
}
pub fn log_menu(app: &AppIdentity, what: &str, result: Result<(), muda::Error>) {
if let Err(error) = result {
eprintln!("{}: failed to build {what}: {error}", app.log_prefix);
}
}
#[cfg(target_os = "macos")]
pub const COMMAND_MODIFIER: Modifiers = Modifiers::META;
#[cfg(not(target_os = "macos"))]
pub const COMMAND_MODIFIER: Modifiers = Modifiers::CONTROL;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shortcut {
New,
Open,
Reload,
Back,
Forward,
Zoom(Zoom),
#[cfg(target_os = "linux")]
Quit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Zoom {
In,
Out,
Reset,
}
#[must_use]
pub const fn zoom_script(zoom: Zoom) -> &'static str {
match zoom {
Zoom::In => "window.dispatchEvent(new CustomEvent('ledgeline:zoom', {detail: 'in'}))",
Zoom::Out => "window.dispatchEvent(new CustomEvent('ledgeline:zoom', {detail: 'out'}))",
Zoom::Reset => "window.dispatchEvent(new CustomEvent('ledgeline:zoom', {detail: 'reset'}))",
}
}
#[cfg(target_os = "linux")]
pub fn stop_web_process(webview: &wry::WebView) {
use webkit2gtk::WebViewExt;
use wry::WebViewExtUnix;
webview.webview().terminate_web_process();
}
#[cfg(target_os = "linux")]
#[must_use]
pub fn linux_shortcut_for(key: &Key<'_>, modifiers: ModifiersState) -> Option<Shortcut> {
let ctrl = modifiers.control_key() && !modifiers.alt_key() && !modifiers.super_key();
let alt = modifiers.alt_key() && !modifiers.control_key() && !modifiers.super_key();
match key {
Key::Character(character) if ctrl && character.eq_ignore_ascii_case("n") => {
Some(Shortcut::New)
}
Key::Character(character) if ctrl && character.eq_ignore_ascii_case("o") => {
Some(Shortcut::Open)
}
Key::Character(character) if ctrl && character.eq_ignore_ascii_case("r") => {
Some(Shortcut::Reload)
}
Key::Character(character) if ctrl && character.eq_ignore_ascii_case("q") => {
Some(Shortcut::Quit)
}
Key::ArrowLeft if alt => Some(Shortcut::Back),
Key::ArrowRight if alt => Some(Shortcut::Forward),
_ => None,
}
}
#[cfg(target_os = "linux")]
pub fn disable_gtk_menu_bar_accel() {
use gtk::prelude::*;
if let Some(settings) = gtk::Settings::default()
&& settings.find_property("gtk-menu-bar-accel").is_some()
{
settings.set_property("gtk-menu-bar-accel", None::<String>);
}
}
#[cfg(target_os = "linux")]
pub fn set_window_chrome_visible(
app: &AppIdentity,
menu_bar: &Menu,
window: &Window,
visible: bool,
) {
use gtk::prelude::*;
use tao::platform::unix::WindowExtUnix;
if let Some(bar) = menu_bar
.clone()
.gtk_menubar_for_gtk_window(window.gtk_window())
{
bar.set_no_show_all(!visible);
}
log_menu(
app,
"menu bar visibility",
if visible {
menu_bar.show_for_gtk_window(window.gtk_window())
} else {
menu_bar.hide_for_gtk_window(window.gtk_window())
},
);
window.set_decorations(visible);
}
pub struct MenuSpec<'a> {
pub version: &'a str,
pub new_label: &'a str,
pub open_label: &'a str,
pub app_menu_items: &'a [&'a dyn IsMenuItem],
pub after_recent: &'a [&'a dyn IsMenuItem],
}
pub struct AppMenu {
pub menu_bar: Menu,
pub new: MenuItem,
pub open: MenuItem,
pub recent: Submenu,
pub reload: MenuItem,
pub back: MenuItem,
pub forward: MenuItem,
pub zoom_in: MenuItem,
pub zoom_out: MenuItem,
pub actual_size: MenuItem,
#[cfg(target_os = "linux")]
pub quit: MenuItem,
}
impl AppMenu {
#[must_use]
pub fn build(app: &AppIdentity, spec: &MenuSpec<'_>) -> Self {
build_menu(app, spec)
}
#[must_use]
pub fn shortcut_for(&self, id: &MenuId) -> Option<Shortcut> {
#[cfg(target_os = "linux")]
if id == self.quit.id() {
return Some(Shortcut::Quit);
}
if id == self.new.id() {
Some(Shortcut::New)
} else if id == self.open.id() {
Some(Shortcut::Open)
} else if id == self.reload.id() {
Some(Shortcut::Reload)
} else if id == self.back.id() {
Some(Shortcut::Back)
} else if id == self.forward.id() {
Some(Shortcut::Forward)
} else if id == self.zoom_in.id() {
Some(Shortcut::Zoom(Zoom::In))
} else if id == self.zoom_out.id() {
Some(Shortcut::Zoom(Zoom::Out))
} else if id == self.actual_size.id() {
Some(Shortcut::Zoom(Zoom::Reset))
} else {
None
}
}
}
fn build_menu(app: &AppIdentity, spec: &MenuSpec<'_>) -> AppMenu {
let menu_bar = Menu::new();
#[cfg(target_os = "macos")]
let app_menu = {
let app_menu = Submenu::new(app.name, true);
let about = PredefinedMenuItem::about(None, Some(about_metadata(app, spec.version)));
let separator = PredefinedMenuItem::separator();
let tail = [
PredefinedMenuItem::separator(),
PredefinedMenuItem::services(None),
PredefinedMenuItem::separator(),
PredefinedMenuItem::hide(None),
PredefinedMenuItem::hide_others(None),
PredefinedMenuItem::show_all(None),
PredefinedMenuItem::separator(),
PredefinedMenuItem::quit(None),
];
let mut items: Vec<&dyn IsMenuItem> = vec![&about, &separator];
items.extend_from_slice(spec.app_menu_items);
items.extend(tail.iter().map(|item| item as &dyn IsMenuItem));
log_menu(app, "app menu", app_menu.append_items(&items));
app_menu
};
#[cfg(not(target_os = "macos"))]
let _ = (spec.version, spec.app_menu_items);
let file_menu = Submenu::new("&File", true);
let new = MenuItem::with_id(
"new",
spec.new_label,
true,
Some(Accelerator::new(COMMAND_MODIFIER, Code::KeyN)),
);
let open = MenuItem::with_id(
"open",
spec.open_label,
true,
Some(Accelerator::new(COMMAND_MODIFIER, Code::KeyO)),
);
let recent = Submenu::new("Open &Recent", true);
log_menu(
app,
"file menu",
file_menu.append_items(&[&new, &open, &recent, &PredefinedMenuItem::separator()]),
);
let after_recent = file_menu
.items()
.iter()
.position(|item| item.id() == recent.id())
.map_or(0, |index| index + 1);
for (offset, item) in spec.after_recent.iter().enumerate() {
log_menu(
app,
"file menu extras",
file_menu.insert(*item, after_recent + offset),
);
}
#[cfg(not(target_os = "linux"))]
log_menu(
app,
"file menu close",
file_menu.append(&PredefinedMenuItem::close_window(Some("Close Window"))),
);
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
log_menu(
app,
"file menu quit",
file_menu.append_items(&[
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::quit(None),
]),
);
#[cfg(target_os = "linux")]
let quit = {
let quit = MenuItem::with_id(
"quit",
"&Quit",
true,
Some(Accelerator::new(COMMAND_MODIFIER, Code::KeyQ)),
);
log_menu(app, "file menu quit", file_menu.append(&quit));
quit
};
let edit_menu = Submenu::new("&Edit", true);
log_menu(
app,
"edit menu",
edit_menu.append_items(&[
&PredefinedMenuItem::undo(None),
&PredefinedMenuItem::redo(None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::cut(None),
&PredefinedMenuItem::copy(None),
&PredefinedMenuItem::paste(None),
&PredefinedMenuItem::select_all(None),
]),
);
let view_menu = Submenu::new("&View", true);
let reload = MenuItem::with_id(
"reload",
"&Reload",
true,
Some(Accelerator::new(COMMAND_MODIFIER, Code::KeyR)),
);
#[cfg(target_os = "macos")]
let (back_accel, forward_accel) = (
Accelerator::new(COMMAND_MODIFIER, Code::BracketLeft),
Accelerator::new(COMMAND_MODIFIER, Code::BracketRight),
);
#[cfg(not(target_os = "macos"))]
let (back_accel, forward_accel) = (
Accelerator::new(Modifiers::ALT, Code::ArrowLeft),
Accelerator::new(Modifiers::ALT, Code::ArrowRight),
);
let back = MenuItem::with_id("back", "&Back", true, Some(back_accel));
let forward = MenuItem::with_id("forward", "&Forward", true, Some(forward_accel));
let zoom_in = MenuItem::with_id(
"zoom-in",
"Zoom &In",
true,
Some(Accelerator::new(COMMAND_MODIFIER, Code::Equal)),
);
let zoom_out = MenuItem::with_id(
"zoom-out",
"Zoom &Out",
true,
Some(Accelerator::new(COMMAND_MODIFIER, Code::Minus)),
);
let actual_size = MenuItem::with_id(
"actual-size",
"&Actual Size",
true,
Some(Accelerator::new(COMMAND_MODIFIER, Code::Digit0)),
);
log_menu(
app,
"view menu",
view_menu.append_items(&[
&reload,
&PredefinedMenuItem::separator(),
&back,
&forward,
&PredefinedMenuItem::separator(),
&zoom_in,
&zoom_out,
&actual_size,
]),
);
#[cfg(target_os = "macos")]
log_menu(
app,
"menu bar",
menu_bar.append_items(&[&app_menu, &file_menu, &edit_menu, &view_menu]),
);
#[cfg(not(target_os = "macos"))]
log_menu(
app,
"menu bar",
menu_bar.append_items(&[&file_menu, &edit_menu, &view_menu]),
);
AppMenu {
menu_bar,
new,
open,
recent,
reload,
back,
forward,
zoom_in,
zoom_out,
actual_size,
#[cfg(target_os = "linux")]
quit,
}
}
pub struct RecentMenu {
submenu: Submenu,
map: RefCell<Vec<(MenuId, PathBuf)>>,
limit: usize,
empty_label: &'static str,
}
impl RecentMenu {
#[must_use]
pub fn new(submenu: Submenu, limit: usize, empty_label: &'static str) -> Self {
Self {
submenu,
map: RefCell::new(Vec::new()),
limit,
empty_label,
}
}
pub fn rebuild(&self, app: &AppIdentity, dirs: &AppDirs, current: Option<&Path>) {
while self.submenu.remove_at(0).is_some() {}
let recents: Vec<PathBuf> = recents::list(dirs)
.into_iter()
.filter(|path| Some(path.as_path()) != current)
.take(self.limit)
.collect();
if recents.is_empty() {
log_menu(
app,
"open-recent submenu",
self.submenu
.append(&MenuItem::new(self.empty_label, false, None)),
);
self.map.borrow_mut().clear();
return;
}
let mut new_map = Vec::with_capacity(recents.len());
for (index, path) in recents.iter().enumerate() {
let item = MenuItem::with_id(
format!("recent-{index}"),
recents::display_label(path),
true,
None,
);
new_map.push((item.id().clone(), path.clone()));
log_menu(app, "open-recent submenu", self.submenu.append(&item));
}
*self.map.borrow_mut() = new_map;
}
#[must_use]
pub fn picked(&self, id: &MenuId) -> Option<PathBuf> {
self.map
.borrow()
.iter()
.find_map(|(item, path)| (item == id).then(|| path.clone()))
}
}
#[must_use]
pub fn navigation_allowed(base: &str, candidate: &str) -> bool {
candidate == base.trim_end_matches('/') || candidate.starts_with(base)
}
pub use crate::security::{HANDOFF_PATH, plain_https, plain_mailto};
#[must_use]
pub fn handoff_target(base: &str, candidate: &str) -> Option<String> {
if !navigation_allowed(base, candidate) {
return None;
}
let url = Url::parse(candidate).ok()?;
if url.path() != HANDOFF_PATH {
return None;
}
url.query_pairs()
.find(|(key, _)| key == "url")
.map(|(_, value)| value.into_owned())
.filter(|target| !target.is_empty())
}
pub fn open_in_browser(app: &AppIdentity, url: &str) {
#[cfg(target_os = "macos")]
let program = "/usr/bin/open";
#[cfg(target_os = "linux")]
let program = "xdg-open";
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
{
eprintln!(
"{}: opening {url} is not supported on this platform",
app.log_prefix
);
return;
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
if let Err(error) = spawn_reaped(std::process::Command::new(program).arg(url)) {
eprintln!("{}: could not open {url}: {error}", app.log_prefix);
}
}
pub fn spawn_reaped(command: &mut std::process::Command) -> std::io::Result<u32> {
let mut child = command.spawn()?;
let id = child.id();
let _ = std::thread::Builder::new()
.name("reap-child".to_string())
.spawn(move || {
let _ = child.wait();
});
Ok(id)
}
#[must_use]
pub fn first_file_path(urls: &[Url]) -> Option<PathBuf> {
urls.iter().find_map(|url| url.to_file_path().ok())
}
#[must_use]
pub fn appearance_init_script(origin: &str, appearance: &BootAppearance) -> String {
let literal = |value: &str| serde_json::Value::from(value).to_string();
let cache = serde_json::to_string(appearance).unwrap_or_else(|_| "null".to_string());
format!(
"if (window.location.origin === {origin}) {{ try {{ \
if (!sessionStorage.getItem(\"ledgeline.appearance.seeded\")) {{ \
localStorage.setItem(\"ledgeline.appearance\", {cache}); \
sessionStorage.setItem(\"ledgeline.appearance.seeded\", \"1\"); }} \
}} catch (e) {{}} }}",
origin = literal(origin),
cache = literal(&cache),
)
}
#[derive(Debug)]
struct MainFrame {
origin: String,
spa_base: &'static str,
last: String,
}
impl MainFrame {
fn new(origin: String, spa_base: &'static str, start: &str) -> Result<Self, GuiError> {
if !in_spa(&origin, spa_base, start) {
return Err(GuiError(format!(
"the start page {start} is outside the app's pages ({origin}{spa_base})"
)));
}
Ok(Self {
origin,
spa_base,
last: start.to_string(),
})
}
fn committed(&mut self, page: &str) -> Option<String> {
if in_spa(&self.origin, self.spa_base, page) {
page.clone_into(&mut self.last);
None
} else {
Some(self.last.clone())
}
}
}
pub fn webview_origin(url: &str) -> Result<String, GuiError> {
Ok(Url::parse(url)
.map_err(|error| GuiError(format!("parsing the webview url: {error}")))?
.origin()
.ascii_serialization())
}
pub fn build_webview<F>(
app: &'static AppIdentity,
window: &Window,
url: &str,
start: &str,
init_scripts: Vec<String>,
open_external: F,
) -> Result<Rc<wry::WebView>, GuiError>
where
F: Fn(&str) -> bool + Clone + 'static,
{
let base = url.to_string();
let popup_base = base.clone();
let main_frame = RefCell::new(MainFrame::new(webview_origin(url)?, app.spa_base, start)?);
let handle: Rc<OnceCell<Weak<wry::WebView>>> = Rc::default();
let loader = Rc::clone(&handle);
let (navigating, new_window) = (open_external.clone(), open_external);
let mut builder = WebViewBuilder::new();
for script in init_scripts {
builder = builder.with_initialization_script(script);
}
let builder = builder
.with_url(start)
.with_navigation_handler(move |candidate| {
if let Some(target) = handoff_target(&base, &candidate) {
if !navigating(&target) {
eprintln!("{}: blocked hand-off of {target}", app.log_prefix);
}
return false;
}
let allowed = navigation_allowed(&base, &candidate);
if !allowed && !navigating(&candidate) {
eprintln!("{}: blocked navigation to {candidate}", app.log_prefix);
}
allowed
})
.with_on_page_load_handler(move |event, page| {
if !matches!(event, PageLoadEvent::Started) {
return;
}
let Some(back) = main_frame.borrow_mut().committed(&page) else {
return;
};
eprintln!(
"{}: refused {page} in the main window; back to {back}",
app.log_prefix
);
if let Some(webview) = loader.get().and_then(Weak::upgrade) {
let _ = webview.load_url(&back);
}
})
.with_new_window_req_handler(move |candidate, _features| {
if let Some(target) = handoff_target(&popup_base, &candidate) {
if !new_window(&target) {
eprintln!("{}: blocked hand-off of {target}", app.log_prefix);
}
return NewWindowResponse::Deny;
}
if !new_window(&candidate) {
eprintln!("{}: blocked new window for {candidate}", app.log_prefix);
}
NewWindowResponse::Deny
})
.with_download_started_handler(move |_url, destination| {
choose_download_destination(app, destination)
})
.with_download_completed_handler(|_url, path, success| {
if !success {
show_download_error(path.as_deref());
}
});
let builder = match perf::script(app) {
Some(script) => builder
.with_initialization_script(script)
.with_ipc_handler(|request| perf::on_message(request.body())),
None => builder,
};
#[cfg(not(target_os = "linux"))]
let webview = builder
.build(window)
.map_err(|error| GuiError(format!("creating webview: {error}")))?;
#[cfg(target_os = "linux")]
let webview = {
use tao::platform::unix::WindowExtUnix;
use wry::WebViewBuilderExtUnix;
match window.default_vbox() {
Some(vbox) => builder.build_gtk(vbox),
None => builder.build_gtk(window.gtk_window()),
}
.map_err(|error| GuiError(format!("creating webview: {error}")))?
};
let webview = Rc::new(webview);
let _ = handle.set(Rc::downgrade(&webview));
Ok(webview)
}
pub fn build_window<T>(
app: &AppIdentity,
event_loop: &EventLoop<T>,
menu: &Menu,
) -> Result<Window, GuiError> {
#[cfg(target_os = "macos")]
menu.init_for_nsapp();
let window_builder = WindowBuilder::new()
.with_title(app.name)
.with_inner_size(LogicalSize::new(1280.0, 832.0))
.with_min_inner_size(LogicalSize::new(800.0, 600.0));
#[cfg(target_os = "linux")]
let window_builder = window_builder.with_decorations(false);
let window = window_builder
.build(event_loop)
.map_err(|error| GuiError(format!("creating window: {error}")))?;
#[cfg(target_os = "windows")]
{
use tao::platform::windows::WindowExtWindows;
unsafe {
let _ = menu.init_for_hwnd(window.hwnd() as isize);
}
}
#[cfg(target_os = "linux")]
{
use tao::platform::unix::WindowExtUnix;
let _ = menu.init_for_gtk_window(window.gtk_window(), window.default_vbox());
}
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
let _ = menu;
Ok(window)
}
pub fn choose_download_destination(app: &AppIdentity, destination: &mut PathBuf) -> bool {
let suggested = destination
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
let dialog = rfd::FileDialog::new()
.set_title("Save export")
.set_file_name(suggested);
let dialog = match destination.parent() {
Some(dir) => dialog.set_directory(dir),
None => dialog,
};
let Some(chosen) = dialog.save_file() else {
return false;
};
if chosen.exists()
&& let Err(error) = std::fs::remove_file(&chosen)
{
eprintln!(
"{}: could not replace {}: {error}",
app.log_prefix,
chosen.display()
);
return false;
}
*destination = chosen;
true
}
pub fn show_download_error(path: Option<&Path>) {
let description = match path {
Some(path) => format!("Could not save {}.", path.display()),
None => "The export could not be saved.".to_string(),
};
show_error("Export failed", description);
}
pub fn show_error(title: &'static str, description: String) {
std::thread::spawn(move || {
rfd::MessageDialog::new()
.set_level(rfd::MessageLevel::Error)
.set_title(title)
.set_description(description)
.set_buttons(rfd::MessageButtons::Ok)
.show();
});
}
#[cfg(all(test, target_os = "linux"))]
mod linux_keyboard_tests {
use super::{Shortcut, linux_shortcut_for};
use tao::keyboard::{Key, ModifiersState};
const CTRL: ModifiersState = ModifiersState::CONTROL;
const ALT: ModifiersState = ModifiersState::ALT;
const SHIFT: ModifiersState = ModifiersState::SHIFT;
#[test]
fn the_bound_chords_map_to_their_actions() {
assert_eq!(
linux_shortcut_for(&Key::Character("n"), CTRL),
Some(Shortcut::New)
);
assert_eq!(
linux_shortcut_for(&Key::Character("o"), CTRL),
Some(Shortcut::Open)
);
assert_eq!(
linux_shortcut_for(&Key::Character("r"), CTRL),
Some(Shortcut::Reload)
);
assert_eq!(
linux_shortcut_for(&Key::ArrowLeft, ALT),
Some(Shortcut::Back)
);
assert_eq!(
linux_shortcut_for(&Key::ArrowRight, ALT),
Some(Shortcut::Forward)
);
assert_eq!(
linux_shortcut_for(&Key::Character("q"), CTRL),
Some(Shortcut::Quit)
);
}
#[test]
fn the_modifier_must_match_exactly() {
assert_eq!(
linux_shortcut_for(&Key::Character("o"), ModifiersState::empty()),
None
);
assert_eq!(
linux_shortcut_for(&Key::ArrowLeft, ModifiersState::empty()),
None
);
assert_eq!(linux_shortcut_for(&Key::Character("o"), ALT), None);
assert_eq!(linux_shortcut_for(&Key::ArrowLeft, CTRL), None);
assert_eq!(linux_shortcut_for(&Key::Character("o"), CTRL | ALT), None);
assert_eq!(linux_shortcut_for(&Key::ArrowLeft, ALT | CTRL), None);
assert_eq!(
linux_shortcut_for(&Key::Character("o"), CTRL | ModifiersState::SUPER),
None
);
}
#[test]
fn shift_is_folded_into_the_logical_key_rather_than_examined() {
assert_eq!(
linux_shortcut_for(&Key::Character("O"), CTRL | SHIFT),
Some(Shortcut::Open)
);
assert_eq!(
linux_shortcut_for(&Key::Character("R"), CTRL | SHIFT),
Some(Shortcut::Reload)
);
}
#[test]
fn unbound_keys_are_left_to_the_page() {
assert_eq!(linux_shortcut_for(&Key::F10, ModifiersState::empty()), None);
assert_eq!(linux_shortcut_for(&Key::Character("d"), CTRL), None);
assert_eq!(linux_shortcut_for(&Key::Character("u"), CTRL), None);
assert_eq!(
linux_shortcut_for(&Key::Escape, ModifiersState::empty()),
None
);
}
}
pub mod perf {
use std::sync::OnceLock;
use std::time::Instant;
use crate::AppIdentity;
const ENV: &str = "LEDGELINE_PERF";
static START: OnceLock<Instant> = OnceLock::new();
fn enabled() -> bool {
std::env::var_os(ENV).is_some()
}
fn elapsed_ms() -> f64 {
START.get_or_init(Instant::now).elapsed().as_secs_f64() * 1000.0
}
pub fn start() {
START.get_or_init(Instant::now);
}
pub fn stamp(label: &str) {
if enabled() {
eprintln!("PERF rust {label} {:.1}", elapsed_ms());
}
}
pub(super) fn script(app: &AppIdentity) -> Option<String> {
let path = std::env::var_os(ENV)?;
match std::fs::read_to_string(&path) {
Ok(script) => Some(script),
Err(error) => {
eprintln!(
"{}: {ENV}: cannot read {}: {error}",
app.log_prefix,
path.to_string_lossy()
);
None
}
}
}
pub(super) fn on_message(body: &str) {
eprintln!("PERF js {:.1} {body}", elapsed_ms());
if body.contains("\"ev\":\"scroll_done\"") {
std::process::exit(0);
}
}
}
#[cfg(test)]
mod tests {
use super::{
BootAppearance, HANDOFF_PATH, MainFrame, Zoom, appearance_init_script, first_file_path,
handoff_target, navigation_allowed, plain_https, webview_origin, zoom_script,
};
use std::path::PathBuf;
use url::Url;
#[cfg(unix)]
#[test]
fn spawn_reaped_leaves_no_zombie() {
fn still_there(id: u32) -> Option<bool> {
if cfg!(target_os = "linux") {
return Some(std::path::Path::new(&format!("/proc/{id}")).exists());
}
let found = std::process::Command::new("/bin/ps")
.args(["-o", "stat=", "-p", &id.to_string()])
.output()
.ok()?;
Some(!String::from_utf8_lossy(&found.stdout).trim().is_empty())
}
let id = super::spawn_reaped(&mut std::process::Command::new("true")).expect("spawns");
if still_there(std::process::id()) != Some(true) {
eprintln!("skipped: this platform can't list processes");
return;
}
let gone = (0..200).any(|_| {
if still_there(id) == Some(false) {
return true;
}
std::thread::sleep(std::time::Duration::from_millis(10));
false
});
assert!(gone, "process {id} was never reaped");
}
#[test]
fn appearance_script_seeds_the_boot_cache_once_on_our_origin() {
let appearance = BootAppearance {
light: "catppuccin-latte",
dark: "catppuccin-mocha",
scale: 125,
};
let script = appearance_init_script("http://127.0.0.1:5555", &appearance);
assert!(script.starts_with(r#"if (window.location.origin === "http://127.0.0.1:5555")"#));
assert!(script.contains(
r#"localStorage.setItem("ledgeline.appearance", "{\"light\":\"catppuccin-latte\",\"dark\":\"catppuccin-mocha\",\"scale\":125}")"#
));
assert!(script.contains(r#"sessionStorage.getItem("ledgeline.appearance.seeded")"#));
}
#[test]
fn zoom_scripts_dispatch_the_event_the_spa_listens_for() {
for (zoom, detail) in [(Zoom::In, "in"), (Zoom::Out, "out"), (Zoom::Reset, "reset")] {
let script = zoom_script(zoom);
assert!(script.starts_with("window.dispatchEvent(new CustomEvent('ledgeline:zoom'"));
assert!(
script.contains(&format!("{{detail: '{detail}'}}")),
"{script}"
);
}
}
#[test]
fn plain_https_refuses_ports_credentials_and_other_schemes() {
assert!(plain_https(" https://example.com/x ").is_some());
for refused in [
"http://example.com/",
"https://user@example.com/",
"https://user:secret@example.com/",
"https://example.com:8443/",
"file:///etc/passwd",
"javascript:alert(1)",
"not a url",
] {
assert!(plain_https(refused).is_none(), "{refused}");
}
}
#[test]
fn the_webview_origin_is_scheme_host_and_port() {
assert_eq!(
webview_origin("http://127.0.0.1:5000/").expect("parses"),
"http://127.0.0.1:5000"
);
assert!(webview_origin("not a url").is_err());
}
const BASE: &str = "http://127.0.0.1:5000/";
fn urls(raw: &[&str]) -> Vec<Url> {
raw.iter()
.map(|raw| Url::parse(raw).expect("test URL parses"))
.collect()
}
#[test]
fn navigation_is_confined_to_our_own_origin() {
assert!(navigation_allowed(BASE, "http://127.0.0.1:5000/"));
assert!(navigation_allowed(BASE, "http://127.0.0.1:5000"));
assert!(navigation_allowed(
BASE,
"http://127.0.0.1:5000/reports?tab=1"
));
assert!(!navigation_allowed(BASE, "https://evil.example/"));
assert!(!navigation_allowed(BASE, "file:///etc/passwd"));
assert!(!navigation_allowed(BASE, "http://127.0.0.1:5001/"));
assert!(!navigation_allowed(
BASE,
"http://127.0.0.1:5000@evil.example/"
));
assert!(!navigation_allowed(BASE, "http://127.0.0.1:50000/"));
assert!(!navigation_allowed(
BASE,
"http://127.0.0.1:5000.evil.example/"
));
for refused in [
"about:blank",
"about:srcdoc",
"data:text/html,<script>alert(1)</script>",
"javascript:alert(1)",
"https://127.0.0.1:5000/",
"http://localhost:5000/",
] {
assert!(!navigation_allowed(BASE, refused), "{refused}");
}
}
#[test]
fn frames_may_load_same_origin_pages_outside_the_spa() {
assert!(navigation_allowed(
BASE,
"http://127.0.0.1:5000/notes/acme.md"
));
assert!(navigation_allowed(
BASE,
"http://127.0.0.1:5000/.ledgeline-invoicer/preview?x=1"
));
}
const ORIGIN: &str = "http://127.0.0.1:5000";
#[test]
fn the_handoff_path_is_pinned() {
assert_eq!(HANDOFF_PATH, "/.ledgeline/open");
}
#[test]
fn a_same_origin_handoff_names_its_decoded_target() {
assert_eq!(
handoff_target(
BASE,
"http://127.0.0.1:5000/.ledgeline/open?url=mailto%3Aap%40example.com%3Fsubject%3DInvoice%2520108"
)
.as_deref(),
Some("mailto:ap@example.com?subject=Invoice%20108")
);
}
#[test]
fn anything_else_is_no_handoff() {
for candidate in [
"http://127.0.0.1:5001/.ledgeline/open?url=mailto%3Aa%40b.c",
"http://localhost:5000/.ledgeline/open?url=mailto%3Aa%40b.c",
"https://127.0.0.1:5000/.ledgeline/open?url=mailto%3Aa%40b.c",
"http://127.0.0.1:5000/.ledgeline/open/x?url=mailto%3Aa%40b.c",
"http://127.0.0.1:5000/.ledgeline/opener?url=mailto%3Aa%40b.c",
"http://127.0.0.1:5000/.ledgeline/open",
"http://127.0.0.1:5000/.ledgeline/open?link=mailto%3Aa%40b.c",
"http://127.0.0.1:5000/.ledgeline/open?url=",
"http://127.0.0.1:5000/notes/acme.md?url=mailto%3Aa%40b.c",
"http://127.0.0.1:5000/app/",
"mailto:a@b.c",
] {
assert_eq!(handoff_target(BASE, candidate), None, "{candidate}");
}
}
#[test]
fn the_main_frame_must_start_in_the_spa() {
assert!(MainFrame::new(ORIGIN.into(), "/app/", "http://127.0.0.1:5000/app/").is_ok());
assert!(MainFrame::new(ORIGIN.into(), "/", "http://127.0.0.1:5000/new").is_ok());
for outside in [
"http://127.0.0.1:5000/",
"http://127.0.0.1:5000/notes/acme.md",
"http://127.0.0.1:5001/app/",
"about:blank",
] {
assert!(
MainFrame::new(ORIGIN.into(), "/app/", outside).is_err(),
"{outside}"
);
}
}
#[test]
fn the_main_frame_returns_to_its_last_spa_page_from_anything_else() {
let home = "http://127.0.0.1:5000/app/";
let mut frame = MainFrame::new(ORIGIN.into(), "/app/", home).expect("starts in the SPA");
assert_eq!(frame.committed(home), None);
assert_eq!(
frame.committed("http://127.0.0.1:5000/app/invoices/7"),
None
);
for refused in [
"http://127.0.0.1:5000/customers/contracts/sow.html",
"http://127.0.0.1:5000/app/../notes/acme.md",
"http://127.0.0.1:5000/app/%2e%2e/notes/acme.md",
"http://127.0.0.1:5000/.mbr/notes",
"http://127.0.0.1:5000/api/books",
"http://127.0.0.1:5001/app/",
"http://evil.example/app/",
"about:blank",
"data:text/html,x",
"javascript:alert(1)",
] {
assert_eq!(
frame.committed(refused).as_deref(),
Some("http://127.0.0.1:5000/app/invoices/7"),
"{refused}"
);
}
assert_eq!(frame.committed("http://127.0.0.1:5000/app/customers"), None);
assert_eq!(
frame
.committed("http://127.0.0.1:5000/notes/x.md")
.as_deref(),
Some("http://127.0.0.1:5000/app/customers")
);
}
#[test]
fn a_whole_origin_spa_main_frame_refuses_only_other_origins() {
let mut frame = MainFrame::new(ORIGIN.into(), "/", "http://127.0.0.1:5000/")
.expect("starts in the SPA");
for page in [
"http://127.0.0.1:5000/reports?tab=1",
"http://127.0.0.1:5000/settings",
"http://127.0.0.1:5000/new",
] {
assert_eq!(frame.committed(page), None, "{page}");
}
assert_eq!(
frame.committed("about:blank").as_deref(),
Some("http://127.0.0.1:5000/new")
);
}
#[test]
fn document_launch_resolves_the_first_usable_file_url() {
assert_eq!(
first_file_path(&urls(&["file:///tmp/main.journal"])),
Some(PathBuf::from("/tmp/main.journal"))
);
assert_eq!(
first_file_path(&urls(&["file:///Users/me/My%20Books/main.journal"])),
Some(PathBuf::from("/Users/me/My Books/main.journal"))
);
assert_eq!(
first_file_path(&urls(&["https://example.com/main.journal"])),
None
);
assert_eq!(first_file_path(&[]), None);
assert_eq!(
first_file_path(&urls(&[
"ledgeline://open",
"file:///tmp/second.journal",
"file:///tmp/third.journal",
])),
Some(PathBuf::from("/tmp/second.journal"))
);
}
}