Medlar/crates/app/src/app.rs
astar76 4ac8cd9379 S033: tray, notifications, launcher progress, autostart, metainfo, test file
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 22:49:31 -06:00

532 lines
20 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::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);
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);
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);
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 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));
}
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)),
}
}
}
/// 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() {
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
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 => ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close),
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.
struct Window {
app: 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()
}
/// Saves where the downloads are.
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.
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);
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 }));
}
let options = eframe::NativeOptions {
viewport,
persist_window: true,
persistence_path: Some(paths.data.join("window.ron")),
..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 {
if damage.keys.is_empty() { tr!("settings.damaged_all") } else { tr!("settings.damaged", keys = damage.keys.join(", ")) }
}