S047: the app outlives its window; close to tray reopens through run_native_ext with one context

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-27 07:08:05 -06:00
commit 2488f1282c
4 changed files with 198 additions and 97 deletions

View file

@ -22,6 +22,8 @@ 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.
@ -260,50 +262,99 @@ impl App {
/// What the tray and the notifications ask for, and what they are told.
fn shell(&mut self, ui: &Ui) {
let Some(shell) = &mut self.shell else { return };
let ctx = ui.ctx();
if ctx.input(|i| i.viewport().close_requested()) && shell.hides_on_close(&self.settings) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
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,
};
use crate::shell::Do;
for what in shell.tick(&self.settings, shot.as_deref()) {
let show = |ctx: &Context| {
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
};
match what {
Do::Show => show(ctx),
Do::Add => {
show(ctx);
self.main.adding.ask(crate::views::add::Request::default());
}
Do::PauseAll => self.run(ui, Action::PauseAll),
Do::ResumeAll => self.run(ui, Action::ResumeAll),
Do::Mode(m) => crate::views::modes::Change::Mode(m).apply(&mut self.settings),
Do::Quit => {
if let Some(shell) = &mut self.shell {
shell.quitting = true;
}
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
Do::Open(file) => {
crate::views::main::open_outside(&file.to_string_lossy());
}
Do::Folder(file) => {
crate::views::main::reveal_outside(&file);
}
Do::SignIn(url, id) => {
show(ctx);
self.main.wish = Some(Wish::SignIn(url, vec![id]));
}
Do::Retry(id) => self.main.bridge.send(medlar_core::manager::Command::Resume(id)),
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() {}
}
}
@ -397,13 +448,7 @@ impl App {
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 => {
// Quitting closes for real, even with close to tray on.
if let Some(shell) = &mut self.shell {
shell.quitting = true;
}
ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
}
Action::Quit => self.quit(ui.ctx()),
other => {
let anywhere = matches!(other, Action::ResumeAll | Action::PauseAll);
if self.screen.is_some() && !anywhere {
@ -416,13 +461,14 @@ impl App {
}
}
/// The app and which of its screens the window shows.
struct Window {
app: App,
/// 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 {
impl eframe::App for Window<'_> {
fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) {
(self.show)(&mut self.app, ui);
}
@ -431,10 +477,9 @@ impl eframe::App for Window {
self.app.theme.surface.to_normalized_gamma_f32()
}
/// Saves where the downloads are.
/// Writes the settings; the downloads are saved when the app quits.
fn on_exit(&mut self, _: Option<&eframe::glow::Context>) {
self.app.finish();
self.app.main.bridge.close();
}
/// Only the window's place and size are remembered.
@ -494,6 +539,62 @@ fn open(engine: bool, show: fn(&mut App, &mut Ui), mut args: Vec<String>) -> Exi
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);
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)
@ -502,43 +603,13 @@ fn open(engine: bool, show: fn(&mut App, &mut Ui), mut args: Vec<String>) -> Exi
if let Some(rgba) = icons::app_rgba(128) {
viewport = viewport.with_icon(Arc::new(egui::IconData { rgba, width: 128, height: 128 }));
}
let options = eframe::NativeOptions {
eframe::NativeOptions {
viewport,
persist_window: true,
persistence_path: Some(paths.data.join("window.ron")),
run_and_return: true,
..Default::default()
};
let make = move |cc: &eframe::CreationContext| {
let mut app = App::new(&cc.egui_ctx, settings, Sources::detect());
if engine {
if app.settings.desktop_colors.is_none() {
app.first = Some(FirstRun::default());
}
app.paths = Some(paths.clone());
crate::instance::wake_with(&cc.egui_ctx);
app.inbox = Inbox::new(later.take(), args.clone());
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, settings: app.settings.clone(), bus: Bus::System };
app.main.bridge = Bridge::open(opening, &cc.egui_ctx);
let shell = crate::shell::Shell::start(&cc.egui_ctx, &app.settings);
if minimised && shell.tray.is_some() {
cc.egui_ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
}
app.shell = Some(shell);
}
Ok(Box::new(Window { app, show }) as Box<dyn eframe::App>)
};
let made = eframe::run_native(APP_ID, options, Box::new(make));
if let Err(e) = made {
eprintln!("{}", tr!("app.no_window", why = e));
return ExitCode::FAILURE;
}
ExitCode::SUCCESS
}
fn damage_words(damage: &Damage) -> String {

View file

@ -1,5 +1,6 @@
//! What the window shares with the desktop: tray, notifications, launcher progress and autostart.
//! One `Shell` per window; each part is left out when the desktop has no host for it.
//! One `Shell` per run; it outlives the window, so that closing to the tray works where windows cannot hide (Wayland).
//! Each part is left out when the desktop has no host for it.
use crate::launcher::Launcher;
use crate::notify::{Notifier, Watcher};
@ -58,11 +59,9 @@ impl Shell {
}
}
/// Whether closing the window hides it instead.
/// Whether closing the window leaves Medlar running in the tray instead of quitting.
pub fn hides_on_close(&self, settings: &Settings) -> bool {
// Wayland can't hide a window, so a cancelled close would leave it stuck: close quits there until S047.
let can_hide = std::env::var_os("WAYLAND_DISPLAY").is_none();
!self.quitting && can_hide && settings.close_to_tray && self.tray.is_some()
hides(self.quitting, settings.close_to_tray, self.tray.is_some())
}
/// Once per frame: what was asked comes back, what changed goes out.
@ -97,3 +96,22 @@ impl Shell {
self.rx.try_iter().collect()
}
}
/// Closing hides to the tray only when the user wants it, a tray host shows the icon, and no quit was asked for.
pub fn hides(quitting: bool, close_to_tray: bool, host: bool) -> bool {
!quitting && close_to_tray && host
}
#[cfg(test)]
mod tests {
use super::hides;
#[test]
fn close_hides_only_with_tray_on_a_host_and_no_quit() {
assert!(hides(false, true, true));
assert!(!hides(false, false, true), "close to tray off quits");
assert!(!hides(false, true, false), "no tray host quits");
assert!(!hides(true, true, true), "Quit and Ctrl+Q quit");
assert!(!hides(true, false, false));
}
}

View file

@ -18,6 +18,7 @@ use medlar_core::tr;
use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::Receiver;
use tokio::sync::mpsc::UnboundedReceiver;
@ -42,8 +43,17 @@ pub struct Inbox {
attention: bool,
}
/// Set by `raise`, so that a run without a window opens one.
static RAISED: AtomicBool = AtomicBool::new(false);
/// Whether something asked for the window since the last call.
pub fn take_raised() -> bool {
RAISED.swap(false, Ordering::Relaxed)
}
/// Brings the window forward, also from the tray. Where focus is refused (Wayland), it asks for attention.
pub fn raise(ctx: &Context) {
RAISED.store(true, Ordering::Relaxed);
ctx.send_viewport_cmd(ViewportCommand::Visible(true));
ctx.send_viewport_cmd(ViewportCommand::Minimized(false));
ctx.send_viewport_cmd(ViewportCommand::Focus);

View file

@ -240,6 +240,18 @@ impl Main {
}
}
/// Resumes every paused download, or pauses every one that runs or waits. Also without a window.
pub fn all(&self, resume: bool) {
let Data::Ready(shot, _) = self.bridge.data() else { return };
for v in shot.iter() {
match v.state() {
State::Paused if resume => self.bridge.send(Command::Resume(v.id())),
State::Running | State::Checking | State::Queued | State::Waiting if !resume => self.bridge.send(Command::Pause(v.id())),
_ => {}
}
}
}
/// Does an action by name; what this screen has no part in comes back.
pub fn run(&mut self, ui: &Ui, action: Action) -> Option<Action> {
match action {
@ -247,17 +259,7 @@ impl Main {
Action::Find => self.asked.push(Order::Find),
Action::Rail => self.toggle_rail(ui.ctx().content_rect().width()),
Action::View => self.list.form = if self.list.form == Form::Cards { Form::Compact } else { Form::Cards },
Action::ResumeAll | Action::PauseAll => {
let Data::Ready(shot, _) = self.bridge.data() else { return None };
let resume = action == Action::ResumeAll;
for v in shot.iter() {
match v.state() {
State::Paused if resume => self.bridge.send(Command::Resume(v.id())),
State::Running | State::Checking | State::Queued | State::Waiting if !resume => self.bridge.send(Command::Pause(v.id())),
_ => {}
}
}
}
Action::ResumeAll | Action::PauseAll => self.all(action == Action::ResumeAll),
a if a.entry().group == Where::List => {
let order = self.list.perform(ui, a);
self.asked.extend(order);