Medlar/crates/app/src/app.rs
astar76 989935833f Start in the tray waits for the desktop's tray at login
Autostart ran Medlar before the shell's StatusNotifierWatcher was up, so the
tray failed, the window opened and closing it quit. A --minimised start now
spawns the tray with assume_sni_available, and the icon shows once the
watcher appears.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-05 00:40:10 -06:00

617 lines
24 KiB
Rust

//! The window: settings, theme and motion of a frame, and what is drawn in it.
use crate::desktop::{Desktop, Sources, Watch};
use crate::motion;
use crate::theme::Theme;
use crate::bridge::{Bridge, Data, Opening};
use crate::keys::{self, Action, Group};
use crate::ui::{dialog, gallery, menu};
use crate::views::firstrun::FirstRun;
use crate::views::incoming::{Inbox, of_arg};
use crate::views::main::{Main, Reply, Wish, open_outside};
use crate::views::palette::{Palette, Pick};
use crate::views::settings::rows::{self, Page};
use crate::views::settings::{Cx, SignIn, View};
use crate::{fonts, icons, tokens};
use eframe::egui::{self, Context, Ui, ViewportBuilder};
use medlar_core::net_state::Bus;
use medlar_core::paths::Paths;
use medlar_core::settings::{Damage, Settings};
use medlar_core::strings::{self, Catalogue};
use medlar_core::{logging, tr};
use std::io;
use std::process::ExitCode;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, RecvTimeoutError, sync_channel};
use crate::shell::Do;
use std::thread::JoinHandle;
/// Also the name of the desktop file, and what Wayland compositors match rules against.
pub const APP_ID: &str = "medlar";
pub struct App {
pub settings: Settings,
pub theme: Theme,
/// The daily screen. Without an engine until it gets one.
pub main: Main,
/// The settings screen, while it is open.
pub screen: Option<Box<View>>,
pub palette: Palette,
/// Until it is through.
pub first: Option<FirstRun>,
/// Where settings are kept. Without it they are not.
pub paths: Option<Paths>,
sign_in: Option<SignIn>,
/// The browser port and what came in through it or a second start.
pub inbox: Inbox,
/// The desktop's colours, if it has any.
pub desktop: Desktop,
sources: Sources,
watch: Watch,
clip: Option<crate::clipboard::Watch>,
target: crate::views::target::Target,
/// Tray, notifications and the launcher; only with an engine.
shell: Option<crate::shell::Shell>,
/// What `theme` was made from; a change in settings rebuilds it.
themed: Settings,
/// What the engine and the shortcuts know.
applied: Settings,
/// When changed settings are written.
save_at: Option<f64>,
saving: Option<JoinHandle<io::Result<()>>>,
}
/// Seconds without a change before the settings are written.
const SAVE_AFTER: f64 = 0.4;
impl App {
pub fn new(ctx: &Context, settings: Settings, sources: Sources) -> App {
fonts::install(ctx);
let desktop = sources.read();
let theme = Theme::build(&settings, desktop);
theme.apply(ctx, settings.motion);
keys::set(&settings);
crate::ui::wave::set_one_bar(settings.bar == medlar_core::settings::BarStyle::One);
let watch = Watch::start(sources.clone(), ctx);
App {
themed: settings.clone(),
applied: settings.clone(),
settings,
theme,
main: Main::default(),
screen: None,
palette: Palette::default(),
first: None,
paths: None,
sign_in: None,
inbox: Inbox::default(),
desktop,
sources,
watch,
clip: None,
target: Default::default(),
shell: None,
save_at: None,
saving: None,
}
}
fn follow_theme(&mut self, ctx: &Context) {
let desktop = self.watch.take();
if desktop {
self.desktop = self.sources.read();
}
if desktop || self.themed != self.settings {
self.themed = self.settings.clone();
self.theme = Theme::build(&self.settings, self.desktop);
self.theme.apply(ctx, self.settings.motion);
}
}
/// Changed settings count at once; they are written a moment later, beside the window.
fn follow_settings(&mut self, ctx: &Context) {
let now = ctx.input(|i| i.time);
if self.applied != self.settings {
keys::set(&self.settings);
crate::ui::wave::set_one_bar(self.settings.bar == medlar_core::settings::BarStyle::One);
self.main.bridge.apply(&self.settings);
if let Some(paths) = self.paths.as_ref().filter(|_| self.applied.language != self.settings.language) {
strings::set(Catalogue::load(&paths.languages(), &self.settings.language).0);
}
self.applied = self.settings.clone();
self.save_at = Some(now + SAVE_AFTER);
// With the new colours and words.
ctx.request_repaint();
}
match self.save_at {
Some(at) if now >= at => self.save(Some(ctx.clone())),
Some(at) => ctx.request_repaint_after_secs((at - now) as f32),
None => {}
}
if self.saving.as_ref().is_some_and(|s| s.is_finished()) {
self.saved();
}
}
fn save(&mut self, ctx: Option<Context>) {
self.saved();
self.save_at = None;
let Some(path) = self.paths.as_ref().map(Paths::settings) else { return };
let settings = self.settings.clone();
self.saving = Some(std::thread::spawn(move || {
let done = settings.save(&path);
if let Some(ctx) = ctx {
ctx.request_repaint();
}
done
}));
}
/// Waits for the last write, which takes no time once it `is_finished`.
fn saved(&mut self) {
if let Some(Ok(Err(e))) = self.saving.take().map(JoinHandle::join) {
log::warn!("settings: {e}");
let why = match e.kind() {
io::ErrorKind::PermissionDenied => tr!("backup.not_allowed"),
io::ErrorKind::StorageFull => tr!("settings.full"),
_ => tr!("backup.disk"),
};
self.main.toasts.error(tr!("settings.not_saved", why = why), None);
}
}
/// Writes what is not written yet, and waits for it.
pub fn finish(&mut self) {
if self.save_at.is_some() {
self.save(None);
}
self.saved();
}
/// Runs one frame around `draw`: theme and springs before it, the next frame after it only if something moves.
pub fn frame(&mut self, ui: &mut Ui, draw: impl FnOnce(&mut App, &mut Ui)) {
self.follow_theme(ui.ctx());
motion::begin_frame(ui.input(|i| i.stable_dt), self.settings.motion);
ui.painter().rect_filled(ui.ctx().content_rect(), 0.0, self.theme.surface);
draw(self, ui);
self.follow_settings(ui.ctx());
if motion::busy() {
ui.ctx().request_repaint();
}
}
/// One frame of the whole window.
pub fn show(&mut self, ui: &mut Ui) {
self.frame(ui, App::view);
}
fn view(&mut self, ui: &mut Ui) {
let t = self.theme.clone();
if let Some(first) = &mut self.first {
if first.show(ui, &t, &mut self.settings, self.desktop) {
self.first = None;
motion::keep_alive();
}
let bottom = ui.ctx().content_rect().bottom();
return self.main.messages(ui, &t, bottom);
}
self.keys(ui);
match self.screen.take() {
Some(mut screen) => {
if self.settings_screen(ui, &t, &mut screen) {
screen.close(&self.settings, &self.main.bridge);
motion::keep_alive();
} else {
self.screen = Some(screen);
}
}
None => {
self.main.show(ui, &t, &self.settings);
let window = ui.ctx().content_rect();
let at = egui::pos2(window.right() - crate::tokens::space::L, window.bottom() - self.main.floor() - crate::tokens::space::L);
let on = self.settings.mode == medlar_core::settings::Mode::Snail;
if crate::ui::snail::button(ui.ctx(), &t, at, on, &keys::label(Action::Snail)) {
self.run(ui, Action::Snail);
}
if let Some(change) = self.main.change.take() {
change.apply(&mut self.settings);
}
}
}
if self.first.is_none() {
self.shell(ui);
self.inbox.tick(ui.ctx(), &self.settings, &mut self.main);
self.extras(ui.ctx(), &t);
}
let bridge = &self.main.bridge;
if let Some(ask) = &mut self.sign_in {
ask.show(ui, &t, &mut self.settings, bridge);
}
if self.palette.is_open() {
let shot = match self.main.bridge.data() {
Data::Ready(shot, _) => Some(shot),
_ => None,
};
let some = !self.main.list.selected.is_empty();
match self.palette.show(ui, &t, shot.as_deref(), some) {
Some(Pick::Action(a)) => self.run(ui, a),
Some(Pick::Download(id)) => {
self.close_settings();
self.main.list.go_to(id);
}
Some(Pick::Page(page)) => self.open_settings(page),
Some(Pick::Setting(id, page)) => {
self.open_settings(page);
if let (Some(screen), Some(row)) = (&mut self.screen, rows::all().find(|r| r.id == id)) {
screen.go_to(ui, &row);
}
}
None => {}
}
}
match self.main.wish.take() {
Some(Wish::Settings) => self.open_settings(Page::Look),
Some(Wish::Network) => self.open_settings(Page::Network),
Some(Wish::SignIn(url, ids)) => self.sign_in = SignIn::new(&url, ids),
None => {}
}
if let Some(Reply::Settings(before)) = self.main.answer.take() {
self.settings = *before;
}
}
/// What the tray and the notifications ask for, and what they are told.
fn shell(&mut self, ui: &Ui) {
let ctx = ui.ctx();
for what in self.shell_tick() {
match self.act(what) {
Some(Do::Show) => {
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
}
Some(Do::Quit) => self.quit(ctx),
_ => {}
}
motion::keep_alive();
}
}
/// Tells the tray, the notifications and the launcher what changed; what they asked for comes back.
fn shell_tick(&mut self) -> Vec<Do> {
let Some(shell) = &mut self.shell else { return vec![] };
let shot = match self.main.bridge.data() {
Data::Ready(shot, _) => Some(shot),
_ => None,
};
shell.tick(&self.settings, shot.as_deref())
}
/// Does what needs no window. What needs one comes back as `Show`, and `Quit` comes back as it is.
fn act(&mut self, what: Do) -> Option<Do> {
match what {
Do::Show | Do::Quit => return Some(what),
Do::Add => {
self.main.adding.ask(crate::views::add::Request::default());
return Some(Do::Show);
}
Do::SignIn(url, id) => {
self.main.wish = Some(Wish::SignIn(url, vec![id]));
return Some(Do::Show);
}
Do::PauseAll => self.main.all(false),
Do::ResumeAll => self.main.all(true),
Do::Mode(m) => crate::views::modes::Change::Mode(m).apply(&mut self.settings),
Do::Open(file) => {
open_outside(&file.to_string_lossy());
}
Do::Folder(file) => {
crate::views::main::reveal_outside(&file);
}
Do::Retry(id) => self.main.bridge.send(medlar_core::manager::Command::Resume(id)),
}
None
}
/// Closes for real, even with close to tray on.
fn quit(&mut self, ctx: &Context) {
if let Some(shell) = &mut self.shell {
shell.quitting = true;
}
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
/// Whether the window that just closed leaves Medlar in the tray.
fn hides(&self) -> bool {
self.first.is_none() && self.shell.as_ref().is_some_and(|s| s.hides_on_close(&self.settings))
}
/// Runs without a window until one is wanted (true) or Quit is chosen (false). The engine, the port, the tray and
/// the notifications keep going; `wake` hears every repaint request, so nothing is polled while nothing happens.
fn hidden(&mut self, ctx: &Context, wake: &Receiver<()>) -> bool {
crate::views::incoming::take_raised();
loop {
for what in self.shell_tick() {
match self.act(what) {
Some(Do::Show) => return true,
Some(Do::Quit) => return false,
_ => {}
}
}
self.inbox.tick(ctx, &self.settings, &mut self.main);
if crate::views::incoming::take_raised() || self.main.wish.is_some() {
return true;
}
if self.applied != self.settings {
self.main.bridge.apply(&self.settings);
self.applied = self.settings.clone();
self.save(None);
}
if self.saving.as_ref().is_some_and(|s| s.is_finished()) {
self.saved();
}
// Requests for later repaints are not heard: a slow look round covers them.
if wake.recv_timeout(std::time::Duration::from_secs(2)).is_err_and(|e| e == RecvTimeoutError::Disconnected) {
return false;
}
while wake.try_recv().is_ok() {}
}
}
/// The clipboard watcher, the drop target and the full-window drop state.
fn extras(&mut self, ctx: &Context, t: &Theme) {
use crate::bridge::Data;
use crate::views::add::Request;
if self.settings.clipboard != "off" && self.clip.is_none() {
self.clip = Some(crate::clipboard::Watch::start(ctx.clone()));
}
let shot = match self.main.bridge.data() {
Data::Ready(shot, _) => Some(shot),
_ => None,
};
if let Some(clip) = &self.clip {
let mut links = clip.tick(&self.settings.clipboard, &self.settings.clip_types, &self.settings.clip_skip);
if let Some(shot) = shot.as_ref().filter(|_| !links.is_empty()) {
let known = medlar_core::duplicate::Known::new(shot.iter().map(|v| &*v.task));
links.retain(|l| known.find(&medlar_core::duplicate::New { url: l, ..Default::default() }).is_none());
if !links.is_empty() && self.settings.clipboard == "add" {
let request = Request { text: links.join("\n"), literal: true, ..Request::default() };
let mut add = crate::views::add::Add::new(request, &self.settings);
add.read_text();
let (tasks, secrets) = add.tasks();
self.main.toasts.info("content_paste", tr!("clip.added", n = tasks.len()));
self.main.bridge.add(tasks, secrets);
} else if !links.is_empty() {
crate::views::incoming::raise(ctx);
self.main.adding.ask(Request { text: links.join("\n"), literal: true, ..Request::default() });
}
}
}
let speed = shot.as_ref().map_or(0.0, |s| s.iter().map(|v| v.speed).sum());
self.target.show(ctx, t, &mut self.settings, &mut self.main, speed);
if self.screen.is_none() {
crate::drop::overlay(ctx, t);
}
}
fn settings_screen(&mut self, ui: &mut Ui, t: &Theme, screen: &mut View) -> bool {
let main = &mut self.main;
let mut cx = Cx { t, s: &mut self.settings, desktop: self.desktop, bridge: &main.bridge, toasts: &mut main.toasts, paths: self.paths.as_ref() };
let close = screen.show(ui, &mut cx);
let bottom = ui.ctx().content_rect().bottom();
main.messages(ui, t, bottom);
close
}
pub fn open_settings(&mut self, page: Page) {
match &mut self.screen {
Some(screen) => screen.go(page),
None => self.screen = Some(Box::new(View::open(&self.settings, page))),
}
motion::keep_alive();
}
fn close_settings(&mut self) {
if let Some(mut screen) = self.screen.take() {
screen.close(&self.settings, &self.main.bridge);
}
motion::keep_alive();
}
/// The shortcuts that count anywhere.
fn keys(&mut self, ui: &Ui) {
let recording = self.screen.as_ref().is_some_and(|s| s.recording());
if self.palette.is_open() && keys::pressed(ui, Action::Palette) {
return self.palette.toggle();
}
if recording || dialog::any_open(ui.ctx()) || menu::any_open(ui.ctx()) || self.main.list.dragging() {
return;
}
for e in keys::ALL.iter().filter(|e| e.group == Group::App) {
// The settings have a search of their own.
let theirs = e.action == Action::Find && self.screen.is_some();
if !theirs && keys::pressed(ui, e.action) {
self.run(ui, e.action);
}
}
}
/// Does an action by name.
pub fn run(&mut self, ui: &Ui, action: Action) {
match action {
Action::Palette => self.palette.toggle(),
Action::Settings if self.screen.is_some() => self.close_settings(),
Action::Settings => self.open_settings(Page::Look),
Action::Network => self.open_settings(Page::Network),
Action::Snail => {
self.settings.toggle_snail();
let on = self.settings.mode == medlar_core::settings::Mode::Snail;
self.main.toasts.info("slow_motion_video", if on { tr!("snail.on") } else { tr!("snail.off") });
}
Action::Quit => self.quit(ui.ctx()),
other => {
let anywhere = matches!(other, Action::ResumeAll | Action::PauseAll);
if self.screen.is_some() && !anywhere {
self.close_settings();
}
self.main.run(ui, other);
}
}
motion::keep_alive();
}
}
/// The app and which of its screens the window shows. The app outlives the window: closing to the tray ends the
/// window, not the app.
struct Window<'a> {
app: &'a mut App,
show: fn(&mut App, &mut Ui),
}
impl eframe::App for Window<'_> {
fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) {
(self.show)(&mut self.app, ui);
}
fn clear_color(&self, _: &egui::Visuals) -> [f32; 4] {
self.app.theme.surface.to_normalized_gamma_f32()
}
/// Writes the settings; the downloads are saved when the app quits.
fn on_exit(&mut self, _: Option<&eframe::glow::Context>) {
self.app.finish();
}
/// Only the window's place and size are remembered.
fn persist_egui_memory(&self) -> bool {
false
}
}
/// Opens the window and returns when it is closed.
pub fn run() -> ExitCode {
run_with(vec![])
}
/// Whether the arguments are for a window: links of the `medlar:` scheme and link lists, as a desktop hands them over.
pub fn wants(args: &[String]) -> bool {
!args.is_empty() && args.iter().all(|a| a == MINIMISED || of_arg(a).is_some())
}
/// Starts in the tray when there is one (what autostart passes).
pub const MINIMISED: &str = "--minimised";
/// Opens the window with something to add, or hands it to the Medlar that runs and returns.
pub fn run_with(args: Vec<String>) -> ExitCode {
open(true, App::show, args)
}
/// Opens a window with every control instead (`--gallery`).
pub fn run_gallery() -> ExitCode {
open(false, |app, ui| app.frame(ui, gallery::show), vec![])
}
/// `engine`: with the downloads, else only the window.
fn open(engine: bool, show: fn(&mut App, &mut Ui), mut args: Vec<String>) -> ExitCode {
let minimised = args.iter().any(|a| a == MINIMISED);
args.retain(|a| a != MINIMISED);
let paths = Paths::detect();
if let Err(e) = paths.create() {
eprintln!("{}: {e}", paths.config.display());
}
let mut later = None;
if engine {
match crate::instance::claim(&paths.data, &args) {
crate::instance::Claim::Handed => return ExitCode::SUCCESS,
crate::instance::Claim::First(rx) => later = Some(rx),
crate::instance::Claim::Alone => {}
}
}
let (settings, damage) = Settings::load(&paths.settings());
if let Err(e) = logging::init(&paths.log(), log::LevelFilter::Info) {
eprintln!("{}: {e}", paths.log().display());
}
if let Some(damage) = &damage {
log::warn!("settings: {damage:?}");
}
let (catalogue, problem) = Catalogue::load(&paths.languages(), &settings.language);
if let Some(problem) = problem {
log::warn!("language: {problem}");
}
strings::set(catalogue);
// One context for every window, so that what holds it (engine, tray, port, second starts) wakes the next one too.
let ctx = Context::default();
ctx.set_embed_viewports(false);
ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::new(2).unwrap_or(std::num::NonZeroUsize::MIN));
let (tx, wake) = sync_channel(1);
ctx.set_repaint_observer(move |_| {
let _ = tx.try_send(());
});
let mut app = App::new(&ctx, settings, Sources::detect());
let mut window = true;
if engine {
if app.settings.desktop_colors.is_none() {
app.first = Some(FirstRun::default());
}
app.paths = Some(paths.clone());
crate::instance::wake_with(&ctx);
app.inbox = Inbox::new(later.take(), args);
app.main.outside = open_outside;
app.main.reveal = crate::views::main::reveal_outside;
app.main.remember(paths.data.join("view.json"));
if let Some(damage) = damage {
app.main.toasts.error(damage_words(&damage), None);
}
let opening = Opening { paths: paths.clone(), settings: app.settings.clone(), bus: Bus::System };
app.main.bridge = Bridge::open(opening, &ctx);
let shell = crate::shell::Shell::start(&ctx, &app.settings, minimised);
window = !(minimised && shell.tray.is_some() && app.first.is_none());
app.shell = Some(shell);
}
let mut code = ExitCode::SUCCESS;
loop {
if window {
let this = &mut app;
let make: eframe::AppCreator<'_> = Box::new(move |_| Ok(Box::new(Window { app: this, show })));
if let Err(e) = eframe::run_native_ext(APP_ID, options(&paths), Some(ctx.clone()), make) {
eprintln!("{}", tr!("app.no_window", why = e));
code = ExitCode::FAILURE;
break;
}
if !app.hides() {
break;
}
log::info!("window closed; running in the tray");
}
window = app.hidden(&ctx, &wake);
if !window {
break;
}
}
app.finish();
app.main.bridge.close();
code
}
/// A new window, where the last one was.
fn options(paths: &Paths) -> eframe::NativeOptions {
let mut viewport = ViewportBuilder::default()
.with_title("Medlar")
.with_app_id(APP_ID)
.with_inner_size(tokens::size::WINDOW)
.with_min_inner_size(tokens::size::WINDOW_MIN);
if let Some(rgba) = icons::app_rgba(128) {
viewport = viewport.with_icon(Arc::new(egui::IconData { rgba, width: 128, height: 128 }));
}
eframe::NativeOptions {
viewport,
persist_window: true,
persistence_path: Some(paths.data.join("window.ron")),
run_and_return: true,
..Default::default()
}
}
fn damage_words(damage: &Damage) -> String {
if damage.keys.is_empty() { tr!("settings.damaged_all") } else { tr!("settings.damaged", keys = damage.keys.join(", ")) }
}