feat(gui): one tab per open company, each a window on that company alone (D-78)
The viewer was a window on one company: App mixed what is one company's (loader, books, page, filters, receipts, dock, menus) with what is the app's (the color scheme). Two companies in two tabs need those apart, or a filter set in one tab shows in the other. - company.rs: CompanyView owns everything per company, including its own loader, its own handle to the Owner (the process-wide set_owner stays the program's default, each view takes a handle when made and a test can give a view another), its own dock and so its agent process. - app.rs: App holds the per-app state, the views and which is in front. A view not in front still reads its loader every frame and takes the agent's books.show for its own page, so showing it later is current at once and the loader's channel never piles up Books behind it. - Every egui id a view makes is scoped by the view's own id (push_id around the view; the owner dialogs' and the palette's modals, the pages' split widths, the sidebar's footer memo and links memo take it too; the projects' figure cache is keyed by the books). Otherwise egui's memory (a scrolled sidebar) carries from one tab into the next. - data.rs: dropping a Loader wakes its thread at once and the thread stops, so a closed tab lets go of its watcher and its viewer presence now and not at the thread's next look (up to 3 s); Loader::watch tells a test the thread has ended. - tabs.rs: the tab bar. One tab per company (the books' name, else their id), the front one marked by a heavier name, an accent bar and "selected" to assistive technology, not colour alone; a close control on each (middle click too); "+" lists the data root's companies not open; overflow scrolls with a step control at each end. It runs beside the sidebar, not above it: above it the owner's 1479x519 window makes the sidebar's links scroll (sidenav.rs), with a bar of 36, 28 or 24 points alike, so the sidebar keeps the window's whole height. - lib.rs/app.rs: a company named on the command line is the only tab; otherwise the companies open at the last close come back, in order, with the same one in front and each one's page and report period; a company that is gone is skipped, none left opens the data root's first. The old per-app keys keep their names; open_companies, active_company and company.<id>.* are new. The window's title names the company in front. - scheme_menu.rs: the scheme button and its state moved out of App as they are (one scheme for the window). A new tab's dock opens closed with the front tab's agent chosen, so opening a company never starts an agent nobody asked for. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
526c27233e
commit
48cf9e3a03
11 files changed
+3362
-1893
No files matched your search
+499
-1843
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -39,24 +39,63 @@ pub struct Loader {
|
||||
/// Set when this is dropped: the loader's thread then ends, letting go
|
||||
/// of the books (and the viewer's presence on them).
|
||||
gone: Arc<std::sync::atomic::AtomicBool>,
|
||||
/// Wakes the thread at once when this is dropped, so it ends now and
|
||||
/// not at its next look.
|
||||
wake: Sender<()>,
|
||||
/// Set by the thread as it ends.
|
||||
ended: Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
/// Says whether a loader's thread has ended, after the loader is gone.
|
||||
#[derive(Clone)]
|
||||
pub struct LoaderWatch(Arc<std::sync::atomic::AtomicBool>);
|
||||
|
||||
impl LoaderWatch {
|
||||
/// Whether the thread has ended: its watcher, its hold on the books
|
||||
/// and its viewer presence are released.
|
||||
pub fn ended(&self) -> bool {
|
||||
self.0.load(std::sync::atomic::Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the flag when the loader's thread ends, however it ends.
|
||||
struct Ends(Arc<std::sync::atomic::AtomicBool>);
|
||||
|
||||
impl Drop for Ends {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Loader {
|
||||
fn drop(&mut self) {
|
||||
self.gone.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
let _ = self.wake.send(());
|
||||
}
|
||||
}
|
||||
|
||||
impl Loader {
|
||||
pub fn spawn(source: Source, ctx: egui::Context) -> Loader {
|
||||
let (tx, rx) = channel();
|
||||
let (wake, events) = channel();
|
||||
let gone = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let ended = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let stop = gone.clone();
|
||||
let ends = Ends(ended.clone());
|
||||
let wake_to_watcher = wake.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("books-loader".into())
|
||||
.spawn(move || run(source, ctx, tx, &stop))
|
||||
.spawn(move || {
|
||||
let _ends = ends;
|
||||
run(source, ctx, tx, &stop, wake_to_watcher, events)
|
||||
})
|
||||
.expect("spawn loader");
|
||||
Loader { rx, gone }
|
||||
Loader {
|
||||
rx,
|
||||
gone,
|
||||
wake,
|
||||
ended,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every update since the last call, in order (books before the
|
||||
@@ -69,6 +108,16 @@ impl Loader {
|
||||
pub fn wait(&self, timeout: Duration) -> Option<Update> {
|
||||
self.rx.recv_timeout(timeout).ok()
|
||||
}
|
||||
|
||||
/// Whether the thread has ended (it ends once this is dropped).
|
||||
pub fn finished(&self) -> bool {
|
||||
self.ended.load(std::sync::atomic::Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// A handle that outlives the loader and says when its thread ended.
|
||||
pub fn watch(&self) -> LoaderWatch {
|
||||
LoaderWatch(self.ended.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Load once, synchronously (tests and one-shot tools).
|
||||
@@ -123,6 +172,8 @@ fn run(
|
||||
ctx: egui::Context,
|
||||
tx: Sender<Update>,
|
||||
gone: &std::sync::atomic::AtomicBool,
|
||||
ev_tx: Sender<()>,
|
||||
ev_rx: Receiver<()>,
|
||||
) {
|
||||
let gone = || gone.load(std::sync::atomic::Ordering::SeqCst);
|
||||
let send = |u: Update| {
|
||||
@@ -180,7 +231,6 @@ fn run(
|
||||
};
|
||||
check_show(&send);
|
||||
|
||||
let (ev_tx, ev_rx) = channel();
|
||||
let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
|
||||
if res.is_ok() {
|
||||
let _ = ev_tx.send(());
|
||||
@@ -225,6 +275,10 @@ fn run(
|
||||
std::thread::sleep(Duration::from_secs(3));
|
||||
}
|
||||
}
|
||||
// Dropped meanwhile (the wake-up is the drop): end now.
|
||||
if gone() {
|
||||
return;
|
||||
}
|
||||
let before = snap.journal_seq();
|
||||
let grew = match snap.refresh() {
|
||||
Ok(n) => n > 0,
|
||||
|
||||
@@ -466,6 +466,15 @@ impl Default for Dock {
|
||||
}
|
||||
|
||||
impl Dock {
|
||||
/// A closed dock with `agent` chosen: another company's tab opening
|
||||
/// beside one whose dock is in use.
|
||||
pub fn closed_with(agent: Agent) -> Dock {
|
||||
Dock {
|
||||
agent,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The dock as kept: the `agent` key and the `open` flag.
|
||||
pub fn restored(get: impl Fn(&str) -> Option<String>) -> Dock {
|
||||
Dock {
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod app;
|
||||
pub mod attention;
|
||||
pub mod books;
|
||||
pub mod charts;
|
||||
pub mod company;
|
||||
pub mod data;
|
||||
pub mod demo;
|
||||
pub mod dock;
|
||||
@@ -19,14 +20,17 @@ pub mod pages;
|
||||
pub mod palette;
|
||||
mod prefs;
|
||||
mod receipts;
|
||||
mod scheme_menu;
|
||||
mod schemes;
|
||||
mod tabs;
|
||||
#[cfg(test)]
|
||||
mod test_support;
|
||||
mod theme;
|
||||
pub mod welcome;
|
||||
mod widgets;
|
||||
|
||||
pub use app::App;
|
||||
pub use app::{App, Start};
|
||||
pub use company::CompanyView;
|
||||
pub use data::Source;
|
||||
|
||||
use std::path::PathBuf;
|
||||
@@ -52,10 +56,12 @@ impl std::error::Error for Exit {}
|
||||
/// window closes. An unknown argument returns [`Exit`] (code 2).
|
||||
///
|
||||
/// `ledger-gui [--root PATH] [--book ID] [--today YYYY-MM-DD] [--demo]`:
|
||||
/// a book of the data root (plan 3.6), the only books it opens (D-44):
|
||||
/// books of the data root (plan 3.6), the only books it opens (D-44):
|
||||
/// `--root`, else the root `wanderbooks setup` made, never the current
|
||||
/// directory or a settings file; `--book` names one, else the root's only
|
||||
/// one (or the first, by id). With no books yet, and an owner to set them
|
||||
/// directory or a settings file; `--book` names one, which is then the
|
||||
/// only tab; else the companies that were open when the window last
|
||||
/// closed, each in a tab, in their order (the root's first, by id, if
|
||||
/// none of them is there any more). With no books yet, and an owner to set them
|
||||
/// up (`wanderbooks gui`), it opens the first-run page (welcome.rs) instead
|
||||
/// of ending. `--demo` builds a demo company in a temp directory and opens
|
||||
/// that.
|
||||
@@ -100,11 +106,21 @@ pub fn run(
|
||||
}
|
||||
// The books to show, or a first run (no books yet, and the program gave
|
||||
// the viewer an owner to set them up: plan P11b), or the reason not.
|
||||
// A company named (`--book`, the demo) is the only tab; otherwise the
|
||||
// companies that were open last time come back (app.rs INVARIANT 3),
|
||||
// the data root's first if none does.
|
||||
let mut first_run = None;
|
||||
let data_dir = match data_dir {
|
||||
Some(d) => Some(d),
|
||||
let start = match data_dir {
|
||||
Some(d) => Some(Start::Only(Source { data_dir: d, today })),
|
||||
None => match book_in_root(root.as_deref(), book.as_deref()) {
|
||||
Ok(d) => Some(d),
|
||||
Ok(d) if book.is_some() => Some(Start::Only(Source { data_dir: d, today })),
|
||||
Ok(d) => match ledger_store::root::Root::find(root.as_deref()) {
|
||||
Ok(r) => Some(Start::Restore {
|
||||
root: r.path().to_path_buf(),
|
||||
fallback: Source { data_dir: d, today },
|
||||
}),
|
||||
Err(_) => Some(Start::Only(Source { data_dir: d, today })),
|
||||
},
|
||||
Err(why) => match owner::current() {
|
||||
// Named books that aren't there are a mistake, not a first run.
|
||||
Some(owner) if book.is_none() => {
|
||||
@@ -135,8 +151,8 @@ pub fn run(
|
||||
"wanderbooks",
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
Ok(Box::new(match (data_dir, first_run) {
|
||||
(Some(data_dir), _) => App::new(cc, Source { data_dir, today }),
|
||||
Ok(Box::new(match (start, first_run) {
|
||||
(Some(start), _) => App::start(cc, start),
|
||||
(None, state) => App::first_run(cc, root, today, state.unwrap_or_default()),
|
||||
}))
|
||||
}),
|
||||
|
||||
@@ -204,6 +204,11 @@ pub trait Owner: Send + Sync {
|
||||
}
|
||||
}
|
||||
|
||||
/// The owner the program gave the viewer, for every company's view that
|
||||
/// isn't given one of its own. It is the program's (one per process, as
|
||||
/// the program is one), not a company's: each view takes a handle to it
|
||||
/// when it is made, and holds that (`CompanyView::with_owner` gives a view
|
||||
/// another).
|
||||
static OWNER: OnceLock<Arc<dyn Owner>> = OnceLock::new();
|
||||
|
||||
/// Give the viewer its owner (once, at start; INVARIANT 4).
|
||||
@@ -213,10 +218,6 @@ pub fn set_owner(owner: Arc<dyn Owner>) {
|
||||
|
||||
/// The viewer's owner, if the program gave it one.
|
||||
pub fn current() -> Option<Arc<dyn Owner>> {
|
||||
owner()
|
||||
}
|
||||
|
||||
fn owner() -> Option<Arc<dyn Owner>> {
|
||||
OWNER.get().cloned()
|
||||
}
|
||||
|
||||
@@ -307,6 +308,9 @@ struct RestoreForm {
|
||||
/// The menu's state: a dialog, the job under way, and the last outcome.
|
||||
#[derive(Default)]
|
||||
pub struct OwnerMenu {
|
||||
/// The view that owns it: its dialogs' ids are scoped by it, so two
|
||||
/// views' dialogs never share egui state.
|
||||
scope: Option<egui::Id>,
|
||||
/// The books last shown (by identity) and their id: found once for
|
||||
/// each load, not every frame.
|
||||
book: Option<(usize, Option<String>)>,
|
||||
@@ -325,6 +329,14 @@ pub struct OwnerMenu {
|
||||
const UPDATE_LOOK: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
impl OwnerMenu {
|
||||
/// A menu whose ids belong to the view `scope`.
|
||||
pub fn scoped(scope: egui::Id) -> Self {
|
||||
Self {
|
||||
scope: Some(scope),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The id of the books shown, if they are books of a data root: found
|
||||
/// once for each load.
|
||||
fn book_of(&mut self, books: &Arc<Books>) -> Option<String> {
|
||||
@@ -355,8 +367,8 @@ impl OwnerMenu {
|
||||
/// The standing notices above the page: an update waiting for the
|
||||
/// owner's accept, and a format upgrade the books wait for, whose
|
||||
/// go-ahead is asked for once each open (INVARIANT 5).
|
||||
pub fn notice(&mut self, ui: &mut Ui, books: &Arc<Books>) {
|
||||
let Some(owner) = owner() else {
|
||||
pub fn notice(&mut self, ui: &mut Ui, owner: Option<Arc<dyn Owner>>, books: &Arc<Books>) {
|
||||
let Some(owner) = owner else {
|
||||
return;
|
||||
};
|
||||
let Some(book) = self.book_of(books) else {
|
||||
@@ -447,8 +459,14 @@ impl OwnerMenu {
|
||||
}
|
||||
|
||||
/// The menu button and a note of the last outcome; its dialogs.
|
||||
pub fn ui(&mut self, ui: &mut Ui, books: &Arc<Books>, compact: bool) {
|
||||
let Some(owner) = owner() else {
|
||||
pub fn ui(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
owner: Option<Arc<dyn Owner>>,
|
||||
books: &Arc<Books>,
|
||||
compact: bool,
|
||||
) {
|
||||
let Some(owner) = owner else {
|
||||
return;
|
||||
};
|
||||
let Some(book) = self.book_of(books) else {
|
||||
@@ -636,11 +654,18 @@ impl OwnerMenu {
|
||||
}
|
||||
}
|
||||
if !close {
|
||||
upgrade_dialog(ctx, form, owner, book, &mut close);
|
||||
upgrade_dialog(
|
||||
ctx,
|
||||
self.scope.unwrap_or(egui::Id::NULL),
|
||||
form,
|
||||
owner,
|
||||
book,
|
||||
&mut close,
|
||||
);
|
||||
}
|
||||
}
|
||||
Dialog::Close => {
|
||||
egui::Modal::new(egui::Id::new("owner-close")).show(ctx, |ui| {
|
||||
egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-close")).show(ctx, |ui| {
|
||||
ui.heading("Close the books?");
|
||||
ui.label("Agents' sessions and everything else holding them let go. They open again when something holds them.");
|
||||
ui.horizontal(|ui| {
|
||||
@@ -656,30 +681,31 @@ impl OwnerMenu {
|
||||
});
|
||||
}
|
||||
Dialog::NewBooks { id, currency } => {
|
||||
egui::Modal::new(egui::Id::new("owner-new-books")).show(ctx, |ui| {
|
||||
ui.heading("New books");
|
||||
ui.label("Their id: lowercase letters, digits and hyphens.");
|
||||
ui.text_edit_singleline(id);
|
||||
ui.label("Their base currency (fixed for good):");
|
||||
ui.text_edit_singleline(currency);
|
||||
ui.horizontal(|ui| {
|
||||
let ready = !id.trim().is_empty() && !currency.trim().is_empty();
|
||||
if ui
|
||||
.add_enabled(ready, egui::Button::new("Make them"))
|
||||
.clicked()
|
||||
{
|
||||
let (o, i, c) = (owner.clone(), id.clone(), currency.clone());
|
||||
run = Some((
|
||||
"New books".into(),
|
||||
Box::new(move || o.new_books(&i, &c).map(|l| vec![l])),
|
||||
));
|
||||
close = true;
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
close = true;
|
||||
}
|
||||
egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-new-books"))
|
||||
.show(ctx, |ui| {
|
||||
ui.heading("New books");
|
||||
ui.label("Their id: lowercase letters, digits and hyphens.");
|
||||
ui.text_edit_singleline(id);
|
||||
ui.label("Their base currency (fixed for good):");
|
||||
ui.text_edit_singleline(currency);
|
||||
ui.horizontal(|ui| {
|
||||
let ready = !id.trim().is_empty() && !currency.trim().is_empty();
|
||||
if ui
|
||||
.add_enabled(ready, egui::Button::new("Make them"))
|
||||
.clicked()
|
||||
{
|
||||
let (o, i, c) = (owner.clone(), id.clone(), currency.clone());
|
||||
run = Some((
|
||||
"New books".into(),
|
||||
Box::new(move || o.new_books(&i, &c).map(|l| vec![l])),
|
||||
));
|
||||
close = true;
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
close = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
Dialog::Restore(form) => {
|
||||
if let Some((rx, asked)) = &form.planning
|
||||
@@ -699,7 +725,7 @@ impl OwnerMenu {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
egui::Modal::new(egui::Id::new("owner-restore")).show(ctx, |ui| {
|
||||
egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-restore")).show(ctx, |ui| {
|
||||
ui.set_max_width(520.0);
|
||||
ui.heading("Restore books");
|
||||
ui.label("The backup: its repository's address, or its folder (the books' .git folder in your backup folder).");
|
||||
@@ -794,13 +820,14 @@ impl OwnerMenu {
|
||||
/// passphrase, and the go-ahead or not now.
|
||||
fn upgrade_dialog(
|
||||
ctx: &egui::Context,
|
||||
scope: egui::Id,
|
||||
form: &mut UpgradeForm,
|
||||
owner: &Arc<dyn Owner>,
|
||||
book: &str,
|
||||
close: &mut bool,
|
||||
) {
|
||||
let p = crate::theme::pal(ctx);
|
||||
egui::Modal::new(egui::Id::new("owner-upgrade")).show(ctx, |ui| {
|
||||
egui::Modal::new(scope.with("owner-upgrade")).show(ctx, |ui| {
|
||||
ui.set_max_width(520.0);
|
||||
ui.heading("Upgrade these books' format?");
|
||||
ui.add_space(4.0);
|
||||
|
||||
@@ -166,7 +166,9 @@ pub fn split<T: ?Sized>(
|
||||
ui.allocate_rect(rect, egui::Sense::hover());
|
||||
return;
|
||||
}
|
||||
let key = egui::Id::new(("split", id));
|
||||
// Scoped by the page's ui, which is its company's: another company's
|
||||
// tab keeps its own width.
|
||||
let key = ui.id().with(("split", id));
|
||||
let mut detail_w: f32 = ui
|
||||
.ctx()
|
||||
.data_mut(|d| d.get_persisted(key))
|
||||
|
||||
@@ -748,7 +748,9 @@ pub fn figures(
|
||||
fiscal: bool,
|
||||
) -> std::sync::Arc<PageFigures> {
|
||||
type Stamp = (chrono::DateTime<chrono::Utc>, String, NaiveDate, bool);
|
||||
let key = egui::Id::new(("project_figures", id));
|
||||
// Of these books: another company's project of the same number has
|
||||
// its own figures.
|
||||
let key = egui::Id::new(("project_figures", &b.data_dir, id));
|
||||
let stamp: Stamp = (b.loaded_at, b.head.clone(), b.today, fiscal);
|
||||
if let Some((was, figs)) = ctx.data(|d| d.get_temp::<(Stamp, std::sync::Arc<PageFigures>)>(key))
|
||||
&& was == stamp
|
||||
|
||||
@@ -13,6 +13,9 @@ use egui_phosphor::regular as icon;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Palette {
|
||||
/// The view that owns it: its modal's id is scoped by it, so two
|
||||
/// views' palettes never share egui state.
|
||||
scope: Option<egui::Id>,
|
||||
open: bool,
|
||||
query: String,
|
||||
selected: usize,
|
||||
@@ -29,6 +32,13 @@ pub struct Item {
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
/// A palette whose ids belong to the view `scope`.
|
||||
pub fn scoped(scope: egui::Id) -> Self {
|
||||
Self {
|
||||
scope: Some(scope),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
pub fn open(&mut self) {
|
||||
self.open = true;
|
||||
self.query.clear();
|
||||
@@ -66,7 +76,7 @@ impl Palette {
|
||||
self.open = false;
|
||||
return Some(it.route.clone());
|
||||
}
|
||||
let modal = egui::Modal::new(egui::Id::new("palette"))
|
||||
let modal = egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("palette"))
|
||||
.frame(
|
||||
egui::Frame::new()
|
||||
.fill(p.surface)
|
||||
|
||||
@@ -0,0 +1,369 @@
|
||||
//! The color scheme button and its menu (app-wide: one scheme for the
|
||||
//! whole window, whatever company's tab is shown).
|
||||
|
||||
use crate::schemes::{self, Filter, Scheme};
|
||||
use crate::theme::{self, pal};
|
||||
use egui::{Align, CornerRadius, Layout, RichText, Sense, Stroke, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
/// The height of a family's row in the color scheme menu, for laying the
|
||||
/// families out in columns.
|
||||
const FAMILY_ROW: f32 = 34.0;
|
||||
|
||||
/// How long the pointer rests on a scheme's row (or off every row) before
|
||||
/// that scheme (or the one in force) is worn, seconds.
|
||||
const PREVIEW_AFTER: f64 = 0.05;
|
||||
|
||||
/// The width of a variant's row in a family's flyout: room for its colors
|
||||
/// and the longest name.
|
||||
const SCHEME_ROW_WIDTH: f32 = 200.0;
|
||||
|
||||
/// Where the viewer keeps its color scheme ("Family/Variant").
|
||||
const SCHEME_KEY: &str = "scheme";
|
||||
/// Where it keeps its scheme menu's filter.
|
||||
const FILTER_KEY: &str = "scheme_filter";
|
||||
|
||||
/// One variant in the color scheme menu: a strip of its colors and its
|
||||
/// name, the whole row one button, selected when it is the one in force.
|
||||
fn scheme_row(ui: &mut Ui, scheme: &Scheme, current: bool) -> egui::Response {
|
||||
let p = pal(ui.ctx());
|
||||
let (rect, response) = ui.allocate_exact_size(vec2(SCHEME_ROW_WIDTH, 28.0), Sense::click());
|
||||
response.widget_info(|| {
|
||||
egui::WidgetInfo::selected(
|
||||
egui::WidgetType::SelectableLabel,
|
||||
true,
|
||||
current,
|
||||
scheme.name,
|
||||
)
|
||||
});
|
||||
if ui.is_rect_visible(rect) {
|
||||
let painter = ui.painter();
|
||||
let fill = if current {
|
||||
Some(p.selected)
|
||||
} else if response.hovered() {
|
||||
Some(p.hover)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(fill) = fill {
|
||||
painter.rect_filled(rect, CornerRadius::same(6), fill);
|
||||
}
|
||||
let strip = egui::Rect::from_min_size(
|
||||
egui::pos2(rect.left() + 8.0, rect.center().y - 7.0),
|
||||
vec2(50.0, 14.0),
|
||||
);
|
||||
let w = strip.width() / 5.0;
|
||||
for (i, c) in scheme.swatch().into_iter().enumerate() {
|
||||
let r = egui::Rect::from_min_size(
|
||||
strip.min + vec2(w * i as f32, 0.0),
|
||||
vec2(w, strip.height()),
|
||||
);
|
||||
painter.rect_filled(r, 0.0, c);
|
||||
}
|
||||
painter.rect_stroke(
|
||||
strip,
|
||||
3.0,
|
||||
Stroke::new(1.0, p.border),
|
||||
egui::StrokeKind::Outside,
|
||||
);
|
||||
painter.text(
|
||||
egui::pos2(strip.right() + 10.0, rect.center().y),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
scheme.name,
|
||||
theme::regular(14.0),
|
||||
p.text,
|
||||
);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// The scheme and menu filter kept from last time (`get` reads the
|
||||
/// viewer's preferences): the scheme kept; before schemes, the light or
|
||||
/// dark choice kept as "dark"; else the viewer's own for the system's
|
||||
/// mode (schemes INVARIANT 4).
|
||||
fn restored(get: impl Fn(&str) -> Option<String>, system_dark: bool) -> (&'static Scheme, Filter) {
|
||||
let dark = get("dark").map_or(system_dark, |v| v == "true");
|
||||
let scheme = get(SCHEME_KEY).map_or_else(|| schemes::own(dark), |k| Scheme::from_key(&k, dark));
|
||||
let filter = get(FILTER_KEY)
|
||||
.and_then(|f| Filter::from_name(&f))
|
||||
.unwrap_or_default();
|
||||
(scheme, filter)
|
||||
}
|
||||
|
||||
/// The color scheme in force, the one worn (a hovered one previewed), and
|
||||
/// the menu's filter: the app's, shared by every tab.
|
||||
pub struct SchemeMenu {
|
||||
/// The color scheme in force (schemes.rs).
|
||||
scheme: &'static Scheme,
|
||||
/// The scheme being worn: the one in force, or one previewed while
|
||||
/// its row in the menu is hovered.
|
||||
shown: &'static Scheme,
|
||||
/// The scheme the pointer asks for, and since when: worn once it has
|
||||
/// asked for PREVIEW_AFTER.
|
||||
wanted: Option<(&'static Scheme, f64)>,
|
||||
/// Which schemes its menu shows.
|
||||
filter: Filter,
|
||||
}
|
||||
|
||||
impl SchemeMenu {
|
||||
pub fn new(scheme: &'static Scheme) -> Self {
|
||||
Self {
|
||||
scheme,
|
||||
shown: scheme,
|
||||
wanted: None,
|
||||
filter: Filter::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The scheme and filter kept from last time (`get` reads the
|
||||
/// viewer's preferences; the system's mode decides without them).
|
||||
pub fn restored(get: impl Fn(&str) -> Option<String>, system_dark: bool) -> Self {
|
||||
let (scheme, filter) = restored(get, system_dark);
|
||||
let mut me = Self::new(scheme);
|
||||
me.filter = filter;
|
||||
me
|
||||
}
|
||||
|
||||
/// Keep the preferences (the keys they have always had).
|
||||
pub fn keep(&self, set: &mut dyn FnMut(&str, String)) {
|
||||
set(SCHEME_KEY, self.scheme.key());
|
||||
set(FILTER_KEY, self.filter.name().to_string());
|
||||
set("dark", self.scheme.dark.to_string());
|
||||
}
|
||||
|
||||
/// The scheme in force.
|
||||
pub fn in_force(&self) -> &'static Scheme {
|
||||
self.scheme
|
||||
}
|
||||
|
||||
/// Whether the scheme in force is a dark one.
|
||||
pub fn dark(&self) -> bool {
|
||||
self.scheme.dark
|
||||
}
|
||||
|
||||
/// Wear the color scheme kept as `key` ("Family/Variant"; tests).
|
||||
pub fn set_scheme(&mut self, ctx: &egui::Context, key: &str) {
|
||||
self.choose(ctx, Scheme::from_key(key, self.scheme.dark));
|
||||
}
|
||||
|
||||
/// The color scheme in force, as kept ("Family/Variant").
|
||||
pub fn scheme_key(&self) -> String {
|
||||
self.scheme.key()
|
||||
}
|
||||
|
||||
/// The scheme being worn ("Family/Variant"): a previewed one while
|
||||
/// its row is hovered (tests).
|
||||
pub fn shown_scheme_key(&self) -> String {
|
||||
self.shown.key()
|
||||
}
|
||||
|
||||
fn choose(&mut self, ctx: &egui::Context, scheme: &'static Scheme) {
|
||||
self.scheme = scheme;
|
||||
self.wear(ctx, scheme);
|
||||
}
|
||||
|
||||
/// Wear `scheme`, in force or previewed.
|
||||
fn wear(&mut self, ctx: &egui::Context, scheme: &'static Scheme) {
|
||||
self.shown = scheme;
|
||||
self.wanted = None;
|
||||
theme::apply_scheme(ctx, scheme);
|
||||
}
|
||||
|
||||
/// The preview (owner, 2026-10-19: "when we hover over a scheme for
|
||||
/// some time switch to it live; when we switch out of it go to either
|
||||
/// the new thing we're hovering or back to the current one"). While
|
||||
/// the menu is open, the scheme whose row is hovered, else the one in
|
||||
/// force, is worn once the pointer has asked for it PREVIEW_AFTER
|
||||
/// without change; the menu closed, the one in force is worn at once.
|
||||
/// A preview is never kept: only a click chooses.
|
||||
fn preview(&mut self, ctx: &egui::Context, open: bool, hovered: Option<&'static Scheme>) {
|
||||
let want = match (open, hovered) {
|
||||
(true, Some(s)) => s,
|
||||
_ => self.scheme,
|
||||
};
|
||||
if std::ptr::eq(want, self.shown) {
|
||||
self.wanted = None;
|
||||
return;
|
||||
}
|
||||
if !open {
|
||||
self.wear(ctx, want);
|
||||
return;
|
||||
}
|
||||
let now = ctx.input(|i| i.time);
|
||||
match self.wanted {
|
||||
Some((s, since)) if std::ptr::eq(s, want) => {
|
||||
let waited = now - since;
|
||||
if waited >= PREVIEW_AFTER {
|
||||
self.wear(ctx, want);
|
||||
} else {
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(
|
||||
PREVIEW_AFTER - waited,
|
||||
));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.wanted = Some((want, now));
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(PREVIEW_AFTER));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The color scheme button and its menu: a filter (all, light, dark),
|
||||
/// then each family with a flyout of its variants. `compact`: the
|
||||
/// narrow rail's icon alone.
|
||||
pub fn menu(&mut self, ui: &mut Ui, compact: bool) {
|
||||
let p = pal(ui.ctx());
|
||||
let text = if compact {
|
||||
RichText::new(icon::PALETTE).size(16.0).color(p.muted)
|
||||
} else {
|
||||
RichText::new(format!("{} {}", icon::PALETTE, self.scheme.label()))
|
||||
.font(theme::regular(12.5))
|
||||
.color(p.muted)
|
||||
};
|
||||
let mut button = egui::Button::new(text).frame(false);
|
||||
if compact {
|
||||
button = button.min_size(vec2(32.0, ui.spacing().interact_size.y + 4.0));
|
||||
}
|
||||
// Open while the filter changes; closed when a scheme is chosen.
|
||||
let config = egui::containers::menu::MenuConfig::new()
|
||||
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside);
|
||||
let mut chosen = None;
|
||||
let mut hovered = None;
|
||||
let (response, open) = egui::containers::menu::MenuButton::from_button(button)
|
||||
.config(config)
|
||||
.ui(ui, |ui| {
|
||||
ui.set_min_width(200.0);
|
||||
ui.horizontal(|ui| {
|
||||
for f in [Filter::All, Filter::Light, Filter::Dark] {
|
||||
ui.selectable_value(&mut self.filter, f, f.name());
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
// Every family on screen at once, in as many columns as
|
||||
// the window's height needs: nothing hides below a scroll.
|
||||
let families = schemes::families(self.filter);
|
||||
let rows = (((ui.ctx().content_rect().height() - 160.0) / FAMILY_ROW).floor()
|
||||
as usize)
|
||||
.clamp(6, families.len().max(6));
|
||||
let font = theme::regular(14.0);
|
||||
let check = ui
|
||||
.painter()
|
||||
.layout_no_wrap(icon::CHECK.into(), font.clone(), p.accent)
|
||||
.size()
|
||||
.x;
|
||||
ui.horizontal_top(|ui| {
|
||||
for column in families.chunks(rows) {
|
||||
// Each family's button as wide as its column, its
|
||||
// flyout opening beside the column.
|
||||
ui.allocate_ui_with_layout(
|
||||
vec2(170.0, 0.0),
|
||||
Layout::top_down_justified(Align::LEFT),
|
||||
|ui| {
|
||||
ui.set_width(170.0);
|
||||
for (family, variants) in column {
|
||||
let here = *family == self.scheme.family
|
||||
&& self.filter.shows(self.scheme);
|
||||
// Only the family in force is checked; the
|
||||
// others are indented by the check's width,
|
||||
// so names line up and a screen reader hears
|
||||
// the check only where it is.
|
||||
let mut label = egui::text::LayoutJob::default();
|
||||
if here {
|
||||
label.append(
|
||||
icon::CHECK,
|
||||
0.0,
|
||||
egui::TextFormat::simple(font.clone(), p.accent),
|
||||
);
|
||||
}
|
||||
let indent = if here { 8.0 } else { check + 8.0 };
|
||||
label.append(
|
||||
family,
|
||||
indent,
|
||||
egui::TextFormat::simple(font.clone(), p.text),
|
||||
);
|
||||
ui.menu_button(label, |ui| {
|
||||
for v in variants {
|
||||
let row =
|
||||
scheme_row(ui, v, std::ptr::eq(*v, self.scheme));
|
||||
if row.hovered() {
|
||||
hovered = Some(*v);
|
||||
}
|
||||
if row.clicked() {
|
||||
chosen = Some(*v);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
response.on_hover_text(format!("Color scheme: {}", self.scheme.label()));
|
||||
match chosen {
|
||||
Some(v) => self.choose(ui.ctx(), v),
|
||||
None => self.preview(ui.ctx(), open.is_some(), hovered),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn kept(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
|
||||
let map: HashMap<String, String> = pairs
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect();
|
||||
move |k| map.get(k).cloned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kept_scheme_and_filter_come_back() {
|
||||
let (s, f) = restored(
|
||||
kept(&[
|
||||
("scheme", "Ayu/Mirage"),
|
||||
("scheme_filter", "Dark"),
|
||||
("dark", "false"),
|
||||
]),
|
||||
false,
|
||||
);
|
||||
assert_eq!(s.key(), "Ayu/Mirage", "the scheme wins over the old choice");
|
||||
assert_eq!(f, Filter::Dark);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn before_schemes_the_light_or_dark_choice_is_kept() {
|
||||
let (s, f) = restored(kept(&[("dark", "true")]), false);
|
||||
assert!(std::ptr::eq(s, schemes::own(true)));
|
||||
assert_eq!(f, Filter::All);
|
||||
let (s, _) = restored(kept(&[("dark", "false")]), true);
|
||||
assert!(std::ptr::eq(s, schemes::own(false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_nothing_kept_the_systems_mode_decides() {
|
||||
for dark in [false, true] {
|
||||
let (s, f) = restored(kept(&[]), dark);
|
||||
assert!(std::ptr::eq(s, schemes::own(dark)));
|
||||
assert_eq!(f, Filter::All);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lost_scheme_or_filter_falls_back() {
|
||||
let (s, f) = restored(
|
||||
kept(&[
|
||||
("scheme", "Gone/Away"),
|
||||
("scheme_filter", "Sepia"),
|
||||
("dark", "true"),
|
||||
]),
|
||||
false,
|
||||
);
|
||||
assert!(std::ptr::eq(s, schemes::own(true)));
|
||||
assert_eq!(f, Filter::All);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
//! The tab bar along the top of the window: one tab per open company, a
|
||||
//! close control on each, and a "+" that lists the companies of the data
|
||||
//! root that are not open. It runs from the sidebar's right edge to the
|
||||
//! window's right edge: the sidebar keeps the window's whole height, which
|
||||
//! the owner's 1479x519 window needs (`tests/sidenav.rs`: with the bar
|
||||
//! above the sidebar the links scroll there, even with a bar of 24
|
||||
//! points); with no company open there is no sidebar and it runs the whole
|
||||
//! width.
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: a person has several companies open at once, each in its own
|
||||
//! tab, and moves between them, opens and closes them, without
|
||||
//! any one disturbing another.
|
||||
//! SOURCE: plan/p15-app-and-relay.md 3.2 and 3.3 (a tab per open
|
||||
//! company); D-78 (one top-level tab per open company: a
|
||||
//! company is reachable exactly while it has a tab).
|
||||
//! INVARIANTS:
|
||||
//! 1. One tab per open company, in the order opened, showing the
|
||||
//! company's name (the id of its books until the name is read). The
|
||||
//! bar is there with one company open, and with none.
|
||||
//! 2. The tab shown is marked by more than colour: a heavier name, a
|
||||
//! bar in the accent colour along its top edge, and "selected" to
|
||||
//! assistive technology.
|
||||
//! 3. Each tab has its own close control, labelled for assistive
|
||||
//! technology with the company's name; a middle click on a tab
|
||||
//! closes it as well.
|
||||
//! 4. "+" lists only companies of the data root that are not open
|
||||
//! (a company can't be opened twice), and says so when there are
|
||||
//! none.
|
||||
//! 5. Tabs never overlap or leave the bar: they shrink to a least
|
||||
//! width, then the strip scrolls, with a step control at each end
|
||||
//! that is clipped; the tab shown is scrolled into view when it
|
||||
//! changes.
|
||||
//! 6. This only says what was asked (show, close, open); the app does
|
||||
//! it.
|
||||
//! ```
|
||||
|
||||
use crate::theme::{self, pal};
|
||||
use egui::{
|
||||
Align, CornerRadius, Frame, Layout, Margin, RichText, Sense, Stroke, Ui, UiBuilder, vec2,
|
||||
};
|
||||
use egui_phosphor::regular as icon;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The bar's height.
|
||||
pub const BAR_H: f32 = 36.0;
|
||||
/// A tab's widest and least widths (a name is cut with an ellipsis to fit).
|
||||
const TAB_MAX: f32 = 220.0;
|
||||
const TAB_MIN: f32 = 120.0;
|
||||
/// The close control's size.
|
||||
const CLOSE: f32 = 20.0;
|
||||
/// How long a reading of the data root's companies is kept while "+" is
|
||||
/// open.
|
||||
const LIST_KEPT: Duration = Duration::from_millis(750);
|
||||
|
||||
/// What a tab shows of its company.
|
||||
pub struct Tab {
|
||||
/// The company's name, else the id of its books.
|
||||
pub title: String,
|
||||
/// More about it, on hover.
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
/// What a person asked of the bar.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum TabAction {
|
||||
/// Show tab `n`.
|
||||
Show(usize),
|
||||
/// Close tab `n`.
|
||||
Close(usize),
|
||||
/// Open the company of the data root with this id.
|
||||
Open(String),
|
||||
}
|
||||
|
||||
/// The bar's memory: whether to scroll the shown tab into view, and the
|
||||
/// data root's companies as last read for "+".
|
||||
#[derive(Default)]
|
||||
pub struct TabBar {
|
||||
reveal: bool,
|
||||
listed: Option<(Instant, Vec<String>)>,
|
||||
}
|
||||
|
||||
impl TabBar {
|
||||
/// The shown tab changed (or a tab was added): scroll it into view.
|
||||
pub fn reveal(&mut self) {
|
||||
self.reveal = true;
|
||||
}
|
||||
|
||||
/// The bar. `shown` is the tab in front, if there is one; `others`
|
||||
/// reads the ids of the root's companies that are not open (called
|
||||
/// now and then while "+" is open, never otherwise).
|
||||
pub fn show(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
tabs: &[Tab],
|
||||
shown: Option<usize>,
|
||||
others: &dyn Fn() -> Vec<String>,
|
||||
) -> Option<TabAction> {
|
||||
let p = pal(ui.ctx());
|
||||
let mut action = None;
|
||||
let mut reveal = std::mem::take(&mut self.reveal);
|
||||
egui::Panel::top("company_tabs")
|
||||
.exact_size(BAR_H)
|
||||
.resizable(false)
|
||||
.frame(
|
||||
Frame::new()
|
||||
.fill(p.sidebar)
|
||||
.inner_margin(Margin::symmetric(8, 0))
|
||||
.stroke(Stroke::new(1.0, p.border)),
|
||||
)
|
||||
.show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(2.0, 0.0);
|
||||
let bar = ui.max_rect();
|
||||
// The "+" at the right end, always whole; the tabs get the
|
||||
// rest.
|
||||
let plus_w = 30.0;
|
||||
let strip_w = (ui.available_width() - plus_w - 6.0).max(0.0);
|
||||
let strip = egui::Rect::from_min_size(bar.min, vec2(strip_w, bar.height()));
|
||||
let mut strip_ui = ui.new_child(
|
||||
UiBuilder::new()
|
||||
.max_rect(strip)
|
||||
.layout(Layout::left_to_right(Align::Max)),
|
||||
);
|
||||
strip_ui.set_clip_rect(strip);
|
||||
self.strip(&mut strip_ui, tabs, shown, &mut reveal, &mut action);
|
||||
let plus = egui::Rect::from_min_size(
|
||||
egui::pos2(strip.right() + 6.0, bar.top()),
|
||||
vec2(plus_w, bar.height()),
|
||||
);
|
||||
let mut plus_ui = ui.new_child(
|
||||
UiBuilder::new()
|
||||
.max_rect(plus)
|
||||
.layout(Layout::left_to_right(Align::Center)),
|
||||
);
|
||||
self.plus(&mut plus_ui, others, &mut action);
|
||||
ui.allocate_rect(bar, Sense::hover());
|
||||
});
|
||||
if reveal {
|
||||
// The tab wasn't there to scroll to yet: try again next frame.
|
||||
self.reveal = true;
|
||||
}
|
||||
action
|
||||
}
|
||||
|
||||
/// The tabs, scrolling sideways when they don't fit.
|
||||
fn strip(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
tabs: &[Tab],
|
||||
shown: Option<usize>,
|
||||
reveal: &mut bool,
|
||||
action: &mut Option<TabAction>,
|
||||
) {
|
||||
let p = pal(ui.ctx());
|
||||
let room = ui.available_width();
|
||||
let n = tabs.len().max(1) as f32;
|
||||
let each = ((room - (n - 1.0) * 2.0) / n).clamp(TAB_MIN, TAB_MAX);
|
||||
let overflows = each * n + (n - 1.0) * 2.0 > room + 0.5;
|
||||
// A step control at each end while the tabs overflow.
|
||||
let step_w = if overflows { 22.0 } else { 0.0 };
|
||||
let area_id = ui.id().with("tab_scroll");
|
||||
let mut step = 0.0_f32;
|
||||
if overflows {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(step_w, 26.0), Sense::click());
|
||||
step_button(ui, r, &resp, icon::CARET_LEFT, "Earlier tabs");
|
||||
if resp.clicked() {
|
||||
step = -each;
|
||||
}
|
||||
}
|
||||
let view_w = room - 2.0 * step_w;
|
||||
let mut state = egui::scroll_area::State::load(ui.ctx(), area_id).unwrap_or_default();
|
||||
if step != 0.0 {
|
||||
state.offset.x = (state.offset.x + step).max(0.0);
|
||||
state.store(ui.ctx(), area_id);
|
||||
}
|
||||
let out = egui::ScrollArea::horizontal()
|
||||
.id_salt("tab_scroll")
|
||||
.max_width(view_w.max(0.0))
|
||||
.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden)
|
||||
.show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
ui.horizontal_top(|ui| {
|
||||
for (i, tab) in tabs.iter().enumerate() {
|
||||
let here = shown == Some(i);
|
||||
let r = one_tab(ui, i, tab, here, each, &p, action);
|
||||
if here && *reveal {
|
||||
r.scroll_to_me(Some(Align::Center));
|
||||
*reveal = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if overflows {
|
||||
let offset = out.state.offset.x;
|
||||
let max = (out.content_size.x - out.inner_rect.width()).max(0.0);
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(step_w, 26.0), Sense::click());
|
||||
step_button(ui, r, &resp, icon::CARET_RIGHT, "Later tabs");
|
||||
if resp.clicked() {
|
||||
let mut s = out.state;
|
||||
s.offset.x = (offset + each).min(max);
|
||||
s.store(ui.ctx(), out.id);
|
||||
}
|
||||
}
|
||||
if tabs.is_empty() {
|
||||
*reveal = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// The "+" and its list.
|
||||
fn plus(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
others: &dyn Fn() -> Vec<String>,
|
||||
action: &mut Option<TabAction>,
|
||||
) {
|
||||
let p = pal(ui.ctx());
|
||||
let button = egui::Button::new(RichText::new(icon::PLUS).size(16.0).color(p.muted))
|
||||
.frame(false)
|
||||
.min_size(vec2(28.0, 28.0));
|
||||
let (response, open) =
|
||||
egui::containers::menu::MenuButton::from_button(button).ui(ui, |ui| {
|
||||
ui.set_min_width(200.0);
|
||||
let stale = self
|
||||
.listed
|
||||
.as_ref()
|
||||
.is_none_or(|(at, _)| at.elapsed() > LIST_KEPT);
|
||||
if stale {
|
||||
self.listed = Some((Instant::now(), others()));
|
||||
}
|
||||
ui.ctx().request_repaint_after(LIST_KEPT);
|
||||
let list = self
|
||||
.listed
|
||||
.as_ref()
|
||||
.map(|(_, l)| l.as_slice())
|
||||
.unwrap_or(&[]);
|
||||
if list.is_empty() {
|
||||
ui.label(
|
||||
RichText::new("Every company here is open.")
|
||||
.font(theme::regular(13.0))
|
||||
.color(p.muted),
|
||||
);
|
||||
} else {
|
||||
ui.label(
|
||||
RichText::new("Open a company")
|
||||
.font(theme::regular(12.0))
|
||||
.color(p.muted),
|
||||
);
|
||||
for id in list {
|
||||
if ui.button(id).clicked() {
|
||||
*action = Some(TabAction::Open(id.clone()));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
// Forget the list once it is closed, so it is read afresh.
|
||||
if open.is_none() {
|
||||
self.listed = None;
|
||||
}
|
||||
response.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Open another company")
|
||||
});
|
||||
response.on_hover_text("Open another company");
|
||||
}
|
||||
}
|
||||
|
||||
/// A step control at an end of the strip.
|
||||
fn step_button(ui: &Ui, r: egui::Rect, resp: &egui::Response, glyph: &str, label: &'static str) {
|
||||
let p = pal(ui.ctx());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label));
|
||||
if resp.hovered() {
|
||||
ui.painter().rect_filled(r, CornerRadius::same(6), p.hover);
|
||||
}
|
||||
ui.painter().text(
|
||||
r.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
glyph,
|
||||
egui::FontId::proportional(13.0),
|
||||
p.muted,
|
||||
);
|
||||
}
|
||||
|
||||
/// One tab, `width` wide.
|
||||
fn one_tab(
|
||||
ui: &mut Ui,
|
||||
i: usize,
|
||||
tab: &Tab,
|
||||
here: bool,
|
||||
width: f32,
|
||||
p: &theme::Palette,
|
||||
action: &mut Option<TabAction>,
|
||||
) -> egui::Response {
|
||||
let height = BAR_H - 6.0;
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(width, height), Sense::click());
|
||||
// The tab's own id for its close control: tabs are told apart by
|
||||
// their place, and two tabs never share one.
|
||||
let close_rect = egui::Rect::from_center_size(
|
||||
egui::pos2(rect.right() - 6.0 - CLOSE / 2.0, rect.center().y),
|
||||
vec2(CLOSE, CLOSE),
|
||||
);
|
||||
let close = ui.interact(close_rect, resp.id.with("close"), Sense::click());
|
||||
resp.widget_info(|| {
|
||||
egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, here, &tab.title)
|
||||
});
|
||||
close.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(
|
||||
egui::WidgetType::Button,
|
||||
true,
|
||||
format!("Close {}", tab.title),
|
||||
)
|
||||
});
|
||||
if ui.is_rect_visible(rect) {
|
||||
let painter = ui.painter();
|
||||
let top = CornerRadius {
|
||||
nw: 8,
|
||||
ne: 8,
|
||||
sw: 0,
|
||||
se: 0,
|
||||
};
|
||||
let fill = if here {
|
||||
Some(p.bg)
|
||||
} else if resp.hovered() || close.hovered() {
|
||||
Some(p.hover)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(fill) = fill {
|
||||
painter.rect_filled(rect, top, fill);
|
||||
}
|
||||
if here {
|
||||
// A bar along the top edge and the page's own fill: the tab
|
||||
// in front is part of the page below it.
|
||||
painter.rect_filled(
|
||||
egui::Rect::from_min_size(rect.min, vec2(rect.width(), 3.0)),
|
||||
CornerRadius {
|
||||
nw: 8,
|
||||
ne: 8,
|
||||
sw: 0,
|
||||
se: 0,
|
||||
},
|
||||
p.accent,
|
||||
);
|
||||
painter.rect_filled(
|
||||
egui::Rect::from_min_max(
|
||||
egui::pos2(rect.left(), rect.bottom() - 1.0),
|
||||
egui::pos2(rect.right(), rect.bottom() + 1.0),
|
||||
),
|
||||
0.0,
|
||||
p.bg,
|
||||
);
|
||||
}
|
||||
let font = if here {
|
||||
theme::semibold(13.0)
|
||||
} else {
|
||||
theme::regular(13.0)
|
||||
};
|
||||
let text_w = rect.width() - 14.0 - CLOSE - 10.0;
|
||||
let mut job = egui::text::LayoutJob::single_section(
|
||||
tab.title.clone(),
|
||||
egui::TextFormat::simple(font, if here { p.text } else { p.muted }),
|
||||
);
|
||||
job.wrap.max_width = text_w.max(10.0);
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.break_anywhere = true;
|
||||
job.wrap.overflow_character = Some('…');
|
||||
let galley = painter.layout_job(job);
|
||||
painter.galley(
|
||||
egui::pos2(
|
||||
rect.left() + 14.0,
|
||||
rect.center().y - galley.size().y / 2.0 + 1.0,
|
||||
),
|
||||
galley,
|
||||
p.text,
|
||||
);
|
||||
if close.hovered() {
|
||||
painter.rect_filled(close_rect, CornerRadius::same(5), p.selected);
|
||||
}
|
||||
painter.text(
|
||||
close_rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icon::X,
|
||||
egui::FontId::proportional(12.0),
|
||||
if close.hovered() { p.text } else { p.muted },
|
||||
);
|
||||
}
|
||||
let resp = resp.on_hover_text(&tab.detail);
|
||||
// The close control sits over the tab and is the one under the pointer
|
||||
// there: a click on it is its own, never the tab's.
|
||||
if close
|
||||
.on_hover_text(format!("Close {}", tab.title))
|
||||
.clicked()
|
||||
|| resp.middle_clicked()
|
||||
{
|
||||
*action = Some(TabAction::Close(i));
|
||||
} else if resp.clicked() {
|
||||
*action = Some(TabAction::Show(i));
|
||||
}
|
||||
resp
|
||||
}
|
||||
Reference in new issue
Block a user