S018: new tab backgrounds (shapes, blobs, constellation, waves, dot grid) reacting to the cursor, image/GIF layer, Customize panel, heavier clock, delayed repaints honoured
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
17a0cfcdcd
commit
0ed5b34404
24 changed files with 1452 additions and 177 deletions
|
|
@ -68,6 +68,7 @@ Never modify: `~/Documents/Apps/Nacre` (the original Python Nacre, reference onl
|
|||
| `tools/smoke.sh <script> [outdir]` | smoke run on a hidden Xvfb display with a throwaway home and software GL; outdir (default `target/smoke/<name>-<time>`) gets `nacre.log`, `selftest.log`, `<shot>.png`, `<status>.json`, `home/`; exits non-zero on crash, panic or no `status done`. Scripts in `tests/smoke/` (`launch.txt` offline, `https.txt` needs internet, `restore.txt` with `SMOKE_HOME=<launch outdir>/home`, `chrome.txt` chrome and every flyout dark and light, offline); header documents env vars and commands. `SMOKE_VISIBLE=1` shows the run on the user's screen (DP-1, real GPU, niri tiles the window so shots are narrower); use it whenever the user is watching (D-009). Read the PNGs | now (S003) |
|
||||
| `nacre://gallery` + `SMOKE_SIZE=1400x2800 tools/smoke.sh tests/smoke/gallery.txt` | every design token and widget, dark and light (+ new tab and settings shots); read the PNGs | now (S015) |
|
||||
| `SMOKE_SIZE=1400x1200 tools/smoke.sh tests/smoke/newtab.txt` | new tab page dark/light, nothing playing and a video playing, weather failed state, tall/narrow/phone widths (offline); `tests/smoke/newtab-weather.txt` shoots the real weather card (needs internet); read the PNGs | now (S017) |
|
||||
| `SMOKE_SIZE=1400x900 tools/smoke.sh tests/smoke/backgrounds.txt` | every new tab background with the pointer, Customize panel dark/light, image + blur, GIF frames; `perf-*-a/b.json` `frames` (median/max draw ms, `drawn` count) per background at Lots/Fast, hidden tab, still, Motion off. Selftest `pointer x y`, `customize`; `@PAGESDIR@` = path of tests/smoke/pages | now (S018) |
|
||||
| `python tools/icons.py` | rebuilds the icon font subset and `src/ui/icons.rs` from `tools/icons.txt` (needs fontTools and Arch's ttf-material-symbols-variable) | now (S015) |
|
||||
| appimagetool, wine + Inno Setup, VM "Windows 10" | packaging and Windows checks | see the user's global CLAUDE.md "Building" |
|
||||
|
||||
|
|
|
|||
|
|
@ -13,13 +13,13 @@ Animated, cursor-reactive backgrounds (None, Shapes, Blobs, Constellation with l
|
|||
- `src/ui/pages/newtab.rs` (background and settings parts)
|
||||
|
||||
## Steps
|
||||
- [ ] Constellation: add lines between near particles (the setting calls it "particles"; keep the key, rename the label)
|
||||
- [ ] Cursor reaction for every background; Amount and Speed; Motion setting scales or freezes them
|
||||
- [ ] Image/GIF layer with Dim and Blur sliders under the animated layer; GIF frames animate
|
||||
- [ ] Customize panel sliding in from the right over the live page: BACKGROUND, IMAGE OR GIF, ELEMENTS (up/down + switch per element), DETAILS (24-hour, seconds, name, weather place with suggestions, units)
|
||||
- [ ] Check CPU use with each background at Lots/Fast stays reasonable (log frame time); idle when the tab is hidden
|
||||
- [ ] Smoke shots of each background and the open panel; check by eye
|
||||
- [ ] PROGRESS entry, INDEX line, commit `S018: …` and push
|
||||
- [x] Constellation: add lines between near particles (the setting calls it "particles"; keep the key, rename the label)
|
||||
- [x] Cursor reaction for every background; Amount and Speed; Motion setting scales or freezes them
|
||||
- [x] Image/GIF layer with Dim and Blur sliders under the animated layer; GIF frames animate
|
||||
- [x] Customize panel sliding in from the right over the live page: BACKGROUND, IMAGE OR GIF, ELEMENTS (up/down + switch per element), DETAILS (24-hour, seconds, name, weather place with suggestions, units)
|
||||
- [x] Check CPU use with each background at Lots/Fast stays reasonable (log frame time); idle when the tab is hidden
|
||||
- [x] Smoke shots of each background and the open panel; check by eye
|
||||
- [x] PROGRESS entry, INDEX line, commit `S018: …` and push
|
||||
|
||||
## End criteria
|
||||
- Screenshot per background + panel listed in PROGRESS.
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ Tracker: https://claude.ai/artifact/9AD7fPfwJ4ASFzVTJGKU4h
|
|||
- [x] [S015 — Material You foundation](04%20UI%20redesign/S015-material-foundation.md) · Opus high
|
||||
- [x] [S016 — Chrome and menus redesign](04%20UI%20redesign/S016-ui-chrome.md) · Opus medium
|
||||
- [x] [S017 — New tab page: elements](04%20UI%20redesign/S017-ntp-elements.md) · Opus medium
|
||||
- [ ] [S018 — New tab page: backgrounds and Customize](04%20UI%20redesign/S018-ntp-backgrounds.md) · Opus medium
|
||||
- [x] [S018 — New tab page: backgrounds and Customize](04%20UI%20redesign/S018-ntp-backgrounds.md) · Opus medium
|
||||
- [ ] [S019 — Settings pages redesign](04%20UI%20redesign/S019-ui-settings.md) · Opus medium
|
||||
- [ ] [S020 — Other pages and dialogs redesign](04%20UI%20redesign/S020-ui-pages.md) · Sonnet high
|
||||
- [ ] [S021 — Phase 4 review with the user](04%20UI%20redesign/S021-phase4-review.md) · Sonnet medium · 🧑
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -12,3 +12,4 @@
|
|||
- D-008 — 2026-11-11 — One painter per window, shared by all its tabs (not one per tab). Picture-in-picture reloads the page in a dedicated web view and seeks the video (page state is lost). — Per-tab painters cost ~56 MB + 6 threads each (15 tabs: 1128 MB vs 341 MB) with equal frame time; the 4 GB target PC. The user chose it (option B in S005). — S005, any plan touching painters or PiP
|
||||
- D-009 — 2026-11-11 — Material You colours come from the `material-colors` crate pinned at `=0.4.2` (MCU port: HCT, tonal palettes, all scheme variants), not an own port. Icons are Material Symbols Outlined, cut to the names in `tools/icons.txt` by `tools/icons.py` (55 KB, FILL and wght axes kept). — 0.5.0 needs Rust 1.97 and the project allows 1.88; the crate matches MCU's reference colours (theme tests). The user's old Nacre used Material Symbols too. — S015–S020: add an icon by editing tools/icons.txt and running the tool
|
||||
- D-009 — 2026-11-11 — Smoke runs open visibly on the user's screen (`SMOKE_VISIBLE=1 tools/smoke.sh …`, niri monitor DP-1, real GPU) while the user wants to watch; hidden Xvfb (D-005) stays the default and the fallback when no Wayland session is there. Visible runs still use a throwaway home/runtime dir and share only the Wayland socket. — The user asked to see what the sessions test. Bonus: real-GPU coverage. Shots are narrower (niri tiling), so don't compare pixel sizes with Xvfb shots. — every plan that runs smoke scripts
|
||||
- D-010 — 2026-11-11 — egui's delayed repaints are honoured (repaint observer → `BrowserWindow::redraw_at` → `about_to_wait`) instead of every request redrawing at once; animations that want frames ask with `request_repaint` (every frame) or `request_repaint_after` (paced). The new tab page's settings sub-page is no longer linked from General; Customize on the page replaces it (the sub-page stays for editing shortcuts, opened by "Add shortcut"). — The NTP clock alone kept the window at the display rate; the user's reference has Customize on the page. — S019–S021 and anything that animates
|
||||
|
|
|
|||
|
|
@ -179,7 +179,7 @@ pills `FULL`, small egui widgets `S` (`theme::corner`).
|
|||
|
||||
**Type.** Outfit (OFL, `assets/fonts/Outfit[wght].ttf`, one variable font) at `theme::Weight` Thin 200, Light 300,
|
||||
Regular 400 (egui's Proportional), Medium 500, SemiBold 600; `theme::font(size, weight)`. Sizes `SMALL` 12, `BODY` 14,
|
||||
`TITLE` 18, `HEADLINE` 24, `DISPLAY` 64, `DISPLAY_LARGE` 96 (new tab clock: Thin, primary), `DISPLAY_SMALL` 40 (figures in cards). egui text styles: Small/Body/Button/Heading(24
|
||||
`TITLE` 18, `HEADLINE` 24, `DISPLAY` 64, `DISPLAY_LARGE` 96 (new tab clock: SemiBold, primary), `DISPLAY_SMALL` 40 (figures in cards). egui text styles: Small/Body/Button/Heading(24
|
||||
Medium)/Monospace 13. Outfit is Latin only: every family falls back to Material Symbols, then egui's Ubuntu-Light
|
||||
(Cyrillic, Greek). No CJK font is bundled.
|
||||
|
||||
|
|
@ -238,8 +238,9 @@ change). Elements come in `Settings::ntp.elements` order; `blocks()` groups card
|
|||
rows on a 3-column grid (2 below 720 pt, 1 below 480 pt), Now playing spanning two columns; a short row is centred.
|
||||
Rows: Now playing/Weather 224 pt (Now playing below 440 pt wide puts its artwork above, +136 pt), other cards 176 pt;
|
||||
cards are `surface_container`, radius `L`, title = 18 pt icon + Body Medium in `primary`. Clock: `DISPLAY_LARGE` 96
|
||||
(`DISPLAY` 64 under 560 pt) Thin `primary`, every digit in a cell as wide as the widest digit (no shifting), AM/PM
|
||||
Headline Regular on the digits' baseline; date `util::format_long_date`. Shortcuts: 56 pt circles in 88 pt cells,
|
||||
(`DISPLAY` 64 under 560 pt) SemiBold `primary` (the user asked for heavier digits in S018), colons `primary` at 45 %,
|
||||
every digit in a cell as wide as the widest digit (no shifting), AM/PM Title Medium `on_surface_variant` with its top
|
||||
on the digits' top; date `util::format_long_date`. Shortcuts: 56 pt circles in 88 pt cells,
|
||||
favicon of an open tab on that site else the first letter; dashed `outline` circle for Add; right-click opens/removes.
|
||||
Search pill 640×56, `surface_container_high`, `primary` ring while focused, 40 pt `primary` go button. Media art,
|
||||
visualizer ring (56 radial bars starting just outside the cookie's scallops, bands mirrored left/right, turning with the cookie at one turn a minute; short `outline_variant` ticks when still), seek bar, play button and titles
|
||||
|
|
@ -247,6 +248,27 @@ are shared with the media flyout: `menus::media_art`, `seek_bar`, `play_button`,
|
|||
`newtab::Weather` (Open-Meteo current + daily, `Shared::weather` = `Option<Result<Weather, String>>`), fetched when
|
||||
shown and missing, older than 30 min, or for another place/unit (after the place stays unchanged for 1 s).
|
||||
|
||||
**New tab backdrop and Customize** (S018, `src/ui/pages/backdrop.rs`, `customize.rs`). Under the elements: the image or
|
||||
GIF (`ntp.bg_image`, decoded on a thread, GIF frames with their delays, cover-fit, Blur = shrink + small gaussian +
|
||||
linear stretch in 2 px steps, Dim = `surface_container_lowest` at `bg_dim`), then one animated layer: Shapes (flowers,
|
||||
clover outline, rounded triangles/squares, pills, soft blobs in primary/tertiary/secondary/inverse_primary tints),
|
||||
Blobs (wobbling `*_container` circles), Constellation (`particles`: dots, lines under 150 pt, the cursor links dots
|
||||
within 200 pt), Waves (sines that swell and bend near the cursor), Dot grid (faint ripple; dots swell and turn
|
||||
`primary` within 210 pt of the cursor). Amount scales the count per megapixel (×0.55/1/1.8), Speed the clock
|
||||
(×0.45/1/2), the Motion setting divides it, Motion off or `perf::still` freezes it (the cursor still reacts). The
|
||||
cursor is smoothed by `DEFAULT` springs and fades in/out; the panel hides it. 60 fps via `request_repaint_after`.
|
||||
Customize: a `surface_container_high` panel 400 pt wide (margin `GAP_S`) on an `Order::Middle` Area, sliding from the
|
||||
right (`DEFAULT` spring); opened by the tonal "Customize" pill at the bottom right (and "Set place"), closed by its
|
||||
×, or Escape. Rows 48 pt (icon, label, control right); filter chips for the background; an M3 Expressive slider
|
||||
(16 pt track, bar handle with a gap); Weather place suggestions from Open-Meteo geocoding (`Command::SuggestPlaces`,
|
||||
`Shared::places`, after 350 ms of no typing), picking one stores its coordinates. Selftest: `customize [close]`,
|
||||
`pointer <x> <y> | off`.
|
||||
|
||||
**Redraw scheduling** (S018). egui's "repaint after N" is honoured: a repaint observer on each window's context
|
||||
records the earliest wanted time, `App::draw` redraws at once only for immediate requests and otherwise sets
|
||||
`BrowserWindow::redraw_at`, which `about_to_wait` wakes for. Hidden windows (`WindowEvent::Occluded`) skip scheduled
|
||||
frames. Before S018 any delayed request redrew immediately, so the new tab page ran at the display rate.
|
||||
|
||||
**Floating surfaces** (`src/ui/menus.rs`). `menus::floating(ctx, id, pos, pivot, open, |ui| ..)` draws a
|
||||
`menus::surface` (surface_container_high, radius `L`, popup shadow) that grows from its pivot corner (scale 0.9 to
|
||||
1, `DEFAULT`) and fades in (`EFFECT`); with `open` false it shrinks and fades without input, then returns None.
|
||||
|
|
|
|||
|
|
@ -100,6 +100,20 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
|
|||
- Not done/seen: hover/press on shortcuts and cards, the stacked phone media card below the fold (no scroll command),
|
||||
shuffle against a real player (YouTube Music, Spotify), real-GPU check.
|
||||
|
||||
## S018 — New tab backgrounds and Customize (2026-11-11)
|
||||
- Done: `ui/pages/backdrop.rs` (image/GIF with Dim/Blur; Shapes with every kind the user listed, Blobs, Constellation
|
||||
with lines, Waves, Dot grid; all react to the cursor; Amount/Speed/Motion scale, still freezes) and `customize.rs`
|
||||
(panel sliding in from the right: background chips, Amount, Speed, cursor, Upload/Change/Remove, Dim/Blur sliders,
|
||||
element order + switches, 24-hour, seconds, name, Weather place with Open-Meteo suggestions, units). General no
|
||||
longer links the NTP sub-page; redraws honour egui's delay (D-010). Clock SemiBold, soft colons, AM/PM on top (user).
|
||||
- Shots (target/smoke/s018-c, visible, ~772 pt wide): bg-none, bg-shapes(-lots/-light), bg-blobs, bg-constellation
|
||||
(-lots), bg-waves, bg-dots(-lots/-nopointer), panel-dark/light, image-dark, image-blur, gif-a/b (frames differ), gif-dots.
|
||||
- Lots/Fast median/max draw ms, fps: Shapes 1.38/13.8, 60; Blobs 1.31/7.7, 59; Constellation 1.29/2.3, 60; Waves
|
||||
1.38/2.0, 60; Dot grid 1.41/2.1, 60. CPU ~10 % of a core animating, 0-1 % idle; None/hidden tab/Motion off 2-3 fps.
|
||||
- Verified: 50 unit tests; backgrounds, newtab, chrome smoke exit 0.
|
||||
- Not seen: place suggestions (network + typing; parse tested only), Upload dialog, slider drag, Escape; pointer
|
||||
shots partly follow the user's real mouse in visible runs. Shortcut editing still lives in the old sub-page.
|
||||
|
||||
## Later
|
||||
- Reader mode, split view, translate, real gamepad rumble (D-002: not planned for now).
|
||||
- Packaging and first release (D-001: plan when the user asks).
|
||||
|
|
|
|||
|
|
@ -163,6 +163,8 @@ pub enum Command {
|
|||
SpellReplace { word: String, by: String },
|
||||
Suggest(String),
|
||||
Weather,
|
||||
/// Places matching a name, for the Weather place field.
|
||||
SuggestPlaces(String),
|
||||
FetchArt(String),
|
||||
FetchSource(String),
|
||||
ToggleRemoteDebugging,
|
||||
|
|
@ -768,6 +770,7 @@ impl App {
|
|||
},
|
||||
Command::Suggest(query) => self.fetch_suggestions(query),
|
||||
Command::Weather => self.fetch_weather(),
|
||||
Command::SuggestPlaces(name) => self.suggest_places(name),
|
||||
Command::FetchSource(url) => {
|
||||
if self.shared.sources.borrow().contains_key(&url) {
|
||||
return;
|
||||
|
|
@ -1963,6 +1966,16 @@ impl App {
|
|||
});
|
||||
}
|
||||
|
||||
fn suggest_places(&mut self, name: String) {
|
||||
let url = format!("https://geocoding-api.open-meteo.com/v1/search?count=5&name={}", util::encode_query(&name));
|
||||
self.spawn("places", move || crate::net::fetch::get_json(&url, Duration::from_secs(6)), move |app, result| {
|
||||
// A failed lookup shows no suggestions; the field still takes what was typed.
|
||||
let places = result.map(|json| crate::ui::pages::customize::Place::from_open_meteo(&json)).unwrap_or_default();
|
||||
*app.shared.places.borrow_mut() = (name, places);
|
||||
app.redraw_all();
|
||||
});
|
||||
}
|
||||
|
||||
fn fetch_weather(&mut self) {
|
||||
let (city, loc, units) = {
|
||||
let s = self.shared.settings.borrow();
|
||||
|
|
|
|||
49
src/app.rs
49
src/app.rs
|
|
@ -118,6 +118,8 @@ pub struct Shared {
|
|||
pub http_allowed: RefCell<Vec<String>>,
|
||||
/// Address-bar search suggestions for the last query: (query, suggestions).
|
||||
pub suggestions: RefCell<(String, Vec<String>)>,
|
||||
/// Weather place suggestions for the last name typed in the Customize panel: (name, places).
|
||||
pub places: RefCell<(String, Vec<crate::ui::pages::customize::Place>)>,
|
||||
/// Seed for privacy-mode noise; new every run.
|
||||
pub seed: String,
|
||||
pub started: Instant,
|
||||
|
|
@ -267,6 +269,7 @@ impl App {
|
|||
system_dark: RefCell::new(true),
|
||||
http_allowed: RefCell::new(Vec::new()),
|
||||
suggestions: RefCell::new((String::new(), Vec::new())),
|
||||
places: RefCell::new((String::new(), Vec::new())),
|
||||
seed: util::random_hex(8),
|
||||
started: Instant::now(),
|
||||
media_now: RefCell::new(None),
|
||||
|
|
@ -1610,6 +1613,10 @@ impl App {
|
|||
let Some(win) = self.windows.get_mut(&window) else { return };
|
||||
let started = Instant::now();
|
||||
win.needs_redraw = false;
|
||||
win.redraw_at = None;
|
||||
if let Ok(mut wanted) = win.repaint_wanted.lock() {
|
||||
*wanted = None;
|
||||
}
|
||||
win.sync_webviews();
|
||||
win.paint_page();
|
||||
let page_rect_before = win.page_rect;
|
||||
|
|
@ -1627,15 +1634,22 @@ impl App {
|
|||
win.frame_times.pop_front();
|
||||
}
|
||||
win.frame_times.push_back(started.elapsed().as_secs_f32() * 1000.0);
|
||||
win.frames_drawn += 1;
|
||||
// The page area moved or changed size: resize the web view and draw again.
|
||||
if win.page_rect != page_rect_before {
|
||||
win.needs_redraw = true;
|
||||
win.window.request_redraw();
|
||||
}
|
||||
// egui asks for another frame while it animates.
|
||||
let repaint = win.egui.egui_ctx.has_requested_repaint();
|
||||
if repaint {
|
||||
win.window.request_redraw();
|
||||
// egui asks for another frame while it animates, now or after a delay (a clock ticking, a background at
|
||||
// 60 fps); a delayed one waits in `redraw_at` for `about_to_wait`.
|
||||
let wanted = win.repaint_wanted.lock().ok().and_then(|mut w| w.take());
|
||||
if win.egui.egui_ctx.has_requested_repaint() {
|
||||
let at = wanted.unwrap_or_else(Instant::now);
|
||||
if at <= Instant::now() + Duration::from_millis(2) {
|
||||
win.window.request_redraw();
|
||||
} else {
|
||||
win.redraw_at = Some(at);
|
||||
}
|
||||
}
|
||||
for command in commands {
|
||||
self.run_in(window, command);
|
||||
|
|
@ -1725,6 +1739,14 @@ impl ApplicationHandler<AppEvent> for App {
|
|||
WindowEvent::RedrawRequested => {
|
||||
self.draw(window_id);
|
||||
},
|
||||
WindowEvent::Occluded(hidden) => {
|
||||
if let Some(win) = self.windows.get_mut(&window_id) {
|
||||
win.occluded = *hidden;
|
||||
if !*hidden {
|
||||
win.window.request_redraw();
|
||||
}
|
||||
}
|
||||
},
|
||||
WindowEvent::CloseRequested => {
|
||||
self.close_window(window_id);
|
||||
},
|
||||
|
|
@ -1779,7 +1801,24 @@ impl ApplicationHandler<AppEvent> for App {
|
|||
// Wake regularly for timers (session save, toasts, media position, gamepads).
|
||||
let animating = self.windows.values().any(|w| w.tabs.iter().any(|t| t.animating));
|
||||
let interval = if self.gilrs.is_some() && !self.gamepads.is_empty() || animating { 16 } else { 250 };
|
||||
event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(interval)));
|
||||
let mut wake = Instant::now() + Duration::from_millis(interval);
|
||||
// Frames egui asked for after a delay, or from another thread since the last frame; none while hidden.
|
||||
let now = Instant::now();
|
||||
for w in self.windows.values_mut() {
|
||||
if let Some(at) = w.repaint_wanted.lock().ok().and_then(|mut wanted| wanted.take()) {
|
||||
w.redraw_at = Some(w.redraw_at.map_or(at, |t| t.min(at)));
|
||||
}
|
||||
match w.redraw_at {
|
||||
Some(_) if w.occluded => {},
|
||||
Some(at) if at <= now + Duration::from_millis(1) => {
|
||||
w.redraw_at = None;
|
||||
w.window.request_redraw();
|
||||
},
|
||||
Some(at) => wake = wake.min(at),
|
||||
None => {},
|
||||
}
|
||||
}
|
||||
event_loop.set_control_flow(ControlFlow::WaitUntil(wake));
|
||||
if animating {
|
||||
for (id, w) in &self.windows {
|
||||
if w.tabs.get(w.active).is_some_and(|t| t.animating) {
|
||||
|
|
|
|||
|
|
@ -18,6 +18,8 @@
|
|||
//! find <text>, download <url>, navigate <typed text>, mute, pin
|
||||
//! js <script> run JavaScript in the current tab; the result goes to the log
|
||||
//! click <x> <y> click in the page at CSS-ish pixel x,y (from the page's top left)
|
||||
//! pointer <x> <y> | off move the interface's pointer to x,y in the page area (new tab backgrounds follow it)
|
||||
//! customize [close] open (or close) the new tab page's Customize panel
|
||||
//! log <text> write a line to the log
|
||||
//! quit
|
||||
|
||||
|
|
@ -277,6 +279,25 @@ impl App {
|
|||
}
|
||||
self.redraw(window);
|
||||
},
|
||||
"customize" => {
|
||||
if let Some(win) = self.windows.get_mut(&window) {
|
||||
win.ui.pages.ntp_customize = rest != "close";
|
||||
}
|
||||
self.redraw(window);
|
||||
},
|
||||
"pointer" => {
|
||||
// Move egui's pointer to x,y in the page area (logical px from its top left), or take it away with
|
||||
// `pointer off`; the new tab page backgrounds follow it.
|
||||
let mut parts = rest.split_whitespace().filter_map(|p| p.parse::<f32>().ok());
|
||||
if let Some(win) = self.windows.get_mut(&window) {
|
||||
let event = match (parts.next(), parts.next(), win.page_rect) {
|
||||
(Some(x), Some(y), Some(rect)) => egui::Event::PointerMoved(rect.min + egui::vec2(x, y)),
|
||||
_ => egui::Event::PointerGone,
|
||||
};
|
||||
win.egui.egui_winit.egui_input_mut().events.push(event);
|
||||
}
|
||||
self.redraw(window);
|
||||
},
|
||||
"log" => self.selftest_log(rest),
|
||||
"quit" => self.quit(),
|
||||
_ => self.selftest_log(&format!("unknown line: {line}")),
|
||||
|
|
@ -317,7 +338,7 @@ impl App {
|
|||
let frames = self.windows.get(&window).map(|w| {
|
||||
let mut times: Vec<f32> = w.frame_times.iter().copied().collect();
|
||||
times.sort_by(f32::total_cmp);
|
||||
serde_json::json!({"count": times.len(), "median_ms": times.get(times.len() / 2), "max_ms": times.last()})
|
||||
serde_json::json!({"count": times.len(), "median_ms": times.get(times.len() / 2), "max_ms": times.last(), "drawn": w.frames_drawn})
|
||||
});
|
||||
serde_json::json!({
|
||||
"windows": self.windows.len(),
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ choices!(RpcBrowsing { Off = "Off", Site = "Site name", Title = "Page title" });
|
|||
choices!(RpcBrowseType { Watch = "Watching", Listen = "Listening" });
|
||||
choices!(RpcDisplay { Details = "Details", Name = "Name", State = "State" });
|
||||
choices!(PermissionDefault { Ask = "Ask", Allow = "Allow", Block = "Block" });
|
||||
choices!(NtpBackground { Shapes = "Shapes", Off = "None", Blobs = "Blobs", Particles = "Particles", Waves = "Waves", Dots = "Dots" });
|
||||
choices!(NtpBackground { Shapes = "Shapes", Off = "None", Blobs = "Blobs", Particles = "Constellation", Waves = "Waves", Dots = "Dot grid" });
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(default)]
|
||||
|
|
|
|||
|
|
@ -156,6 +156,12 @@ pub const WEB: &str = "\u{e051}";
|
|||
pub const CONTENT_CUT: &str = "\u{e14e}";
|
||||
pub const CONTENT_PASTE: &str = "\u{e14f}";
|
||||
pub const SELECT_ALL: &str = "\u{e162}";
|
||||
pub const BLUR_MEDIUM: &str = "\u{e84c}";
|
||||
pub const MOUSE: &str = "\u{e323}";
|
||||
pub const WAVING_HAND: &str = "\u{e766}";
|
||||
pub const GRAIN: &str = "\u{e3ea}";
|
||||
pub const GIF_BOX: &str = "\u{e7a3}";
|
||||
pub const BRIGHTNESS_6: &str = "\u{e3ab}";
|
||||
|
||||
/// Every icon with its name, for the gallery.
|
||||
pub const ALL: &[(&str, &str)] = &[
|
||||
|
|
@ -314,4 +320,10 @@ pub const ALL: &[(&str, &str)] = &[
|
|||
("content_cut", CONTENT_CUT),
|
||||
("content_paste", CONTENT_PASTE),
|
||||
("select_all", SELECT_ALL),
|
||||
("blur_medium", BLUR_MEDIUM),
|
||||
("mouse", MOUSE),
|
||||
("waving_hand", WAVING_HAND),
|
||||
("grain", GRAIN),
|
||||
("gif_box", GIF_BOX),
|
||||
("brightness_6", BRIGHTNESS_6),
|
||||
];
|
||||
|
|
|
|||
|
|
@ -86,8 +86,8 @@ pub struct WindowUi {
|
|||
pub dragging_tab: Option<(u64, f32)>,
|
||||
pub qr_texture: Option<(String, egui::TextureHandle)>,
|
||||
pub art_texture: Option<(String, egui::TextureHandle)>,
|
||||
/// New tab background image (its own slot, so it doesn't fight the artwork for `art_texture`).
|
||||
pub ntp_bg_texture: Option<(String, egui::TextureHandle)>,
|
||||
/// New tab background image or GIF (its own slot, so it doesn't fight the artwork for `art_texture`).
|
||||
pub ntp_backdrop: Option<pages::backdrop::Backdrop>,
|
||||
/// Visualizer bars shown in the media flyout.
|
||||
pub levels: Vec<f32>,
|
||||
pub last_level_poll: f64,
|
||||
|
|
|
|||
586
src/ui/pages/backdrop.rs
Normal file
586
src/ui/pages/backdrop.rs
Normal file
|
|
@ -0,0 +1,586 @@
|
|||
//! What the new tab page draws behind its elements (docs/UI-BRIEF.md "Background"): an image or GIF, dimmed and
|
||||
//! softened, under one animated layer: Shapes, Blobs, Constellation, Waves or Dot grid. Every layer reacts to the
|
||||
//! cursor; Amount, Speed and the Motion setting scale it, and a still setting (or Motion off) freezes it.
|
||||
|
||||
use std::f32::consts::{PI, TAU};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
|
||||
use egui::{Color32, Id, Mesh, Painter, Pos2, Rect, Shape, Stroke, Ui, Vec2, pos2, vec2};
|
||||
|
||||
use super::super::Frame;
|
||||
use crate::store::settings::{Ntp, NtpBackground as B};
|
||||
use crate::theme::{self, Palette};
|
||||
|
||||
/// Frames a second the animated layers ask for.
|
||||
const FPS: f32 = 60.0;
|
||||
/// GIF frames together may take this many pixels (about 160 MB as RGBA), so a long GIF is scaled down.
|
||||
const GIF_PIXELS: usize = 40_000_000;
|
||||
const GIF_MAX_FRAMES: usize = 400;
|
||||
|
||||
/// The decoded image or GIF and the textures made from it at the current blur.
|
||||
pub struct Backdrop {
|
||||
path: PathBuf,
|
||||
loading: Option<Receiver<Result<Vec<(image::RgbaImage, f32)>, String>>>,
|
||||
/// Frames at full size with their delay in seconds (0 for a still image).
|
||||
base: Vec<(image::RgbaImage, f32)>,
|
||||
textures: Vec<egui::TextureHandle>,
|
||||
/// Blur the textures were made with; NaN until they exist.
|
||||
blur: f32,
|
||||
pub failed: bool,
|
||||
}
|
||||
|
||||
impl Backdrop {
|
||||
pub fn is_gif(&self) -> bool {
|
||||
self.base.len() > 1
|
||||
}
|
||||
}
|
||||
|
||||
/// Amount: how many things a layer draws, as a factor.
|
||||
fn amount(ntp: &Ntp) -> f32 {
|
||||
match ntp.bg_density.as_str() {
|
||||
"low" => 0.55,
|
||||
"high" => 1.8,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn speed(ntp: &Ntp) -> f32 {
|
||||
match ntp.bg_speed.as_str() {
|
||||
"slow" => 0.45,
|
||||
"fast" => 2.0,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A stable pseudo-random number in 0..1 per element and purpose.
|
||||
fn rnd(i: usize, k: u32) -> f32 {
|
||||
let mut x = (i as u32).wrapping_mul(2_654_435_761) ^ k.wrapping_mul(40_503).wrapping_add(0x9e37_79b9);
|
||||
x ^= x >> 13;
|
||||
x = x.wrapping_mul(0x5bd1_e995);
|
||||
x ^= x >> 15;
|
||||
(x % 10_000) as f32 / 10_000.0
|
||||
}
|
||||
|
||||
/// The cursor as the layers see it: a smoothed position and how present it is (0..1, fades in and out).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Cursor {
|
||||
pos: Pos2,
|
||||
amount: f32,
|
||||
}
|
||||
|
||||
impl Cursor {
|
||||
/// 1 at the cursor falling smoothly to 0 at `radius`.
|
||||
fn falloff(&self, p: Pos2, radius: f32) -> f32 {
|
||||
let d = (p - self.pos).length() / radius;
|
||||
if d >= 1.0 { 0.0 } else { (1.0 - d * d).powi(2) * self.amount }
|
||||
}
|
||||
|
||||
/// How far a thing at `p` is pushed away from the cursor.
|
||||
fn push(&self, p: Pos2, radius: f32, strength: f32) -> Vec2 {
|
||||
let d = p - self.pos;
|
||||
let len = d.length().max(0.001);
|
||||
d / len * strength * self.falloff(p, radius)
|
||||
}
|
||||
}
|
||||
|
||||
fn cursor(ui: &Ui, area: Rect, blocked: Option<Rect>, on: bool) -> Option<Cursor> {
|
||||
let ctx = ui.ctx();
|
||||
let id = Id::new("ntp-bg-cursor");
|
||||
let raw = ui.input(|i| i.pointer.hover_pos()).filter(|p| on && area.contains(*p) && !blocked.is_some_and(|b| b.contains(*p)));
|
||||
let amount = theme::effect(ctx, id.with("in"), raw.is_some());
|
||||
let last = ui.data(|d| d.get_temp::<Pos2>(id));
|
||||
let target = raw.or(last)?;
|
||||
if raw.is_some() && (last.is_none() || amount < 0.02) {
|
||||
// Coming in: start where the pointer is instead of sliding over from where it left.
|
||||
theme::spring_jump(ctx, id.with("x"), target.x);
|
||||
theme::spring_jump(ctx, id.with("y"), target.y);
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(id, target));
|
||||
if amount <= 0.001 {
|
||||
return None;
|
||||
}
|
||||
let pos = pos2(theme::spring(ctx, id.with("x"), target.x, theme::DEFAULT), theme::spring(ctx, id.with("y"), target.y, theme::DEFAULT));
|
||||
Some(Cursor { pos, amount })
|
||||
}
|
||||
|
||||
/// Draws the image and the animated layer over `area`. `blocked` (the Customize panel) hides the cursor from them.
|
||||
pub fn draw(ui: &mut Ui, f: &mut Frame, ntp: &Ntp, area: Rect, blocked: Option<Rect>) {
|
||||
let palette = theme::palette(ui.ctx());
|
||||
let motion = theme::tokens(ui.ctx()).motion;
|
||||
let still = motion <= 0.0 || crate::perf::still(&f.shared.settings.borrow());
|
||||
image_layer(ui, f, ntp, area, &palette, still);
|
||||
if ntp.bg == B::Off {
|
||||
return;
|
||||
}
|
||||
// Time runs at Speed (and the Motion setting's pace) and stops when still; keeping it in memory instead of
|
||||
// multiplying the clock lets Speed change without things jumping.
|
||||
let id = Id::new("ntp-bg-time");
|
||||
let dt = ui.input(|i| i.stable_dt).min(0.1) as f64;
|
||||
let rate = if still { 0.0 } else { speed(ntp) / motion.max(0.1) } as f64;
|
||||
let t = ui.data_mut(|d| {
|
||||
let t = d.get_temp_mut_or(id, 0.0f64);
|
||||
*t += dt * rate;
|
||||
*t
|
||||
}) as f32;
|
||||
let cursor = cursor(ui, area, blocked, ntp.bg_mouse);
|
||||
let painter = ui.painter_at(area);
|
||||
let aa = 1.0 / ui.ctx().pixels_per_point();
|
||||
let n = amount(ntp);
|
||||
match ntp.bg {
|
||||
B::Shapes => shapes(&painter, area, &palette, t, n, cursor, aa),
|
||||
B::Blobs => blobs(&painter, area, &palette, t, n, cursor, aa),
|
||||
B::Particles => constellation(&painter, area, &palette, t, n, cursor),
|
||||
B::Waves => waves(&painter, area, &palette, t, n, cursor),
|
||||
B::Dots => dots(&painter, area, &palette, t, n, cursor),
|
||||
B::Off => {},
|
||||
}
|
||||
if !still {
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f32(1.0 / FPS));
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a drifting thing is: its seed spot moved by its velocity, wrapping round a margin outside `area` so it
|
||||
/// leaves on one side before it comes back on the other.
|
||||
fn drift(area: Rect, i: usize, t: f32, margin: f32, speed: f32) -> Pos2 {
|
||||
let angle = rnd(i, 3) * TAU;
|
||||
let v = Vec2::angled(angle) * speed * (0.5 + rnd(i, 4));
|
||||
let w = area.width() + 2.0 * margin;
|
||||
let h = area.height() + 2.0 * margin;
|
||||
pos2(area.left() - margin + (rnd(i, 1) * w + v.x * t).rem_euclid(w), area.top() - margin + (rnd(i, 2) * h + v.y * t).rem_euclid(h))
|
||||
}
|
||||
|
||||
/// How many things fit in `area` at `per_megapixel` for the default amount.
|
||||
fn count(area: Rect, per_megapixel: f32, n: f32) -> usize {
|
||||
(area.area() / 1.0e6 * per_megapixel * n).round().clamp(3.0, 400.0) as usize
|
||||
}
|
||||
|
||||
/// Fills a shape that is star-shaped around `center` (every shape here is), with a soft one-pixel edge: a fan
|
||||
/// from the centre plus a ring that fades out, since egui's own fill assumes a convex shape.
|
||||
fn fill(painter: &Painter, center: Pos2, points: &[Pos2], color: Color32, aa: f32) {
|
||||
let n = points.len();
|
||||
if n < 3 {
|
||||
return;
|
||||
}
|
||||
let mut mesh = Mesh::default();
|
||||
mesh.colored_vertex(center, color);
|
||||
for i in 0..n {
|
||||
let along = points[(i + 1) % n] - points[(i + n - 1) % n];
|
||||
let mut normal = vec2(along.y, -along.x).normalized();
|
||||
if normal.dot(points[i] - center) < 0.0 {
|
||||
normal = -normal;
|
||||
}
|
||||
mesh.colored_vertex(points[i] - normal * aa * 0.5, color);
|
||||
mesh.colored_vertex(points[i] + normal * aa * 0.5, Color32::TRANSPARENT);
|
||||
}
|
||||
for i in 0..n {
|
||||
let j = (i + 1) % n;
|
||||
let (a, a_out, b, b_out) = (1 + 2 * i as u32, 2 + 2 * i as u32, 1 + 2 * j as u32, 2 + 2 * j as u32);
|
||||
mesh.add_triangle(0, a, b);
|
||||
mesh.add_triangle(a, a_out, b);
|
||||
mesh.add_triangle(a_out, b_out, b);
|
||||
}
|
||||
painter.add(mesh);
|
||||
}
|
||||
|
||||
/// A regular polygon with rounded corners (`round` 0 sharp .. 1 as round as the sides allow).
|
||||
fn rounded_polygon(center: Pos2, radius: f32, sides: u32, round: f32, rotation: f32) -> Vec<Pos2> {
|
||||
let n = sides as usize;
|
||||
let corners: Vec<Pos2> = (0..n).map(|k| center + Vec2::angled(rotation + k as f32 * TAU / n as f32) * radius).collect();
|
||||
let interior = PI - TAU / n as f32;
|
||||
let side = (corners[1] - corners[0]).length();
|
||||
// The arc may use at most half of each side.
|
||||
let corner_radius = round * side * 0.5 * (interior / 2.0).tan();
|
||||
let tangent = corner_radius / (interior / 2.0).tan();
|
||||
let mut out = Vec::with_capacity(n * 9);
|
||||
for k in 0..n {
|
||||
let v = corners[k];
|
||||
let to_prev = (corners[(k + n - 1) % n] - v).normalized();
|
||||
let to_next = (corners[(k + 1) % n] - v).normalized();
|
||||
let arc_center = v + (to_prev + to_next).normalized() * corner_radius / (interior / 2.0).sin();
|
||||
let start = (v + to_prev * tangent - arc_center).angle();
|
||||
let mut end = (v + to_next * tangent - arc_center).angle();
|
||||
// Go round the short way.
|
||||
while end - start > PI {
|
||||
end -= TAU;
|
||||
}
|
||||
while start - end > PI {
|
||||
end += TAU;
|
||||
}
|
||||
for s in 0..=8 {
|
||||
out.push(arc_center + Vec2::angled(egui::lerp(start..=end, s as f32 / 8.0)) * corner_radius);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A pill `length` long (end to end) and `width` thick, turned by `rotation`.
|
||||
fn capsule(center: Pos2, length: f32, width: f32, rotation: f32) -> Vec<Pos2> {
|
||||
let r = width / 2.0;
|
||||
let half = (length / 2.0 - r).max(0.0);
|
||||
let turn = Vec2::angled(rotation);
|
||||
let rotate = |v: Vec2| vec2(v.x * turn.x - v.y * turn.y, v.x * turn.y + v.y * turn.x);
|
||||
let mut out = Vec::with_capacity(34);
|
||||
for (end, from) in [(half, -PI / 2.0), (-half, PI / 2.0)] {
|
||||
for s in 0..=16 {
|
||||
let a = from + PI * s as f32 / 16.0;
|
||||
out.push(center + rotate(vec2(end + a.cos() * r, a.sin() * r)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A soft round blob whose edge wobbles slowly.
|
||||
fn blob(center: Pos2, radius: f32, t: f32, seed: f32) -> Vec<Pos2> {
|
||||
(0..72)
|
||||
.map(|k| {
|
||||
let a = k as f32 / 72.0 * TAU;
|
||||
let wobble = 1.0 + 0.07 * (3.0 * a + t * 0.5 + seed * 9.0).sin() + 0.04 * (5.0 * a - t * 0.35 + seed * 5.0).sin();
|
||||
center + Vec2::angled(a) * radius * wobble
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Accent tints for things that come in several colours.
|
||||
fn tints(p: &Palette) -> [Color32; 4] {
|
||||
[p.primary, p.tertiary, p.secondary, p.inverse_primary]
|
||||
}
|
||||
|
||||
/// Flowers, a clover outline, rounded triangles and squares, pills and soft blobs, drifting and turning in the
|
||||
/// accent's tints; the cursor pushes them aside and gives them a turn.
|
||||
fn shapes(painter: &Painter, area: Rect, p: &Palette, t: f32, n: f32, cursor: Option<Cursor>, aa: f32) {
|
||||
let tints = tints(p);
|
||||
let scale = (area.width().min(area.height()) / 900.0).clamp(0.6, 1.4);
|
||||
for i in 0..count(area, 30.0, n) {
|
||||
// Kinds by weight: flowers and rounded shapes most, a clover and a soft blob now and then.
|
||||
let kind = [0, 0, 2, 2, 3, 3, 4, 4, 1, 5][i % 10];
|
||||
let size = scale * match kind {
|
||||
1 => 70.0 + rnd(i, 5) * 40.0,
|
||||
5 => 90.0 + rnd(i, 5) * 80.0,
|
||||
_ => 22.0 + rnd(i, 5) * 34.0,
|
||||
};
|
||||
let mut pos = drift(area, i, t, size * 1.5, 14.0);
|
||||
let spin_dir = if rnd(i, 7) < 0.5 { -1.0 } else { 1.0 };
|
||||
let mut rotation = rnd(i, 6) * TAU + t * 0.12 * spin_dir * (0.4 + rnd(i, 8));
|
||||
if let Some(c) = cursor {
|
||||
pos += c.push(pos, 200.0 * scale, 70.0 * scale);
|
||||
rotation += c.falloff(pos, 240.0 * scale) * 0.8 * spin_dir;
|
||||
}
|
||||
let tint = tints[i % tints.len()];
|
||||
let outline = rnd(i, 9) < 0.35;
|
||||
let stroke = Stroke::new(2.0, tint.gamma_multiply(0.5));
|
||||
let solid = tint.gamma_multiply(0.28);
|
||||
let points = match kind {
|
||||
0 => crate::ui::paint::cookie_points(pos, size, 6 + (rnd(i, 10) * 4.0) as u32, 0.24, rotation),
|
||||
1 => crate::ui::paint::cookie_points(pos, size, 4, 0.42, rotation),
|
||||
2 => rounded_polygon(pos, size, 3, 0.55, rotation),
|
||||
3 => rounded_polygon(pos, size * 0.85, 4, 0.45, rotation),
|
||||
4 => capsule(pos, size * 2.2, size * 0.8, rotation),
|
||||
_ => blob(pos, size, t, rnd(i, 11)),
|
||||
};
|
||||
match kind {
|
||||
// The clover is only ever drawn as an outline, the soft blob only ever filled, faintly.
|
||||
1 => {
|
||||
painter.add(Shape::closed_line(points, stroke));
|
||||
},
|
||||
5 => fill(painter, pos, &points, tint.gamma_multiply(0.07), aa),
|
||||
0 | 4 => fill(painter, pos, &points, solid, aa),
|
||||
_ if outline => {
|
||||
painter.add(Shape::closed_line(points, stroke));
|
||||
},
|
||||
_ => fill(painter, pos, &points, solid, aa),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Large soft circles that wobble and float slowly, moving out of the cursor's way.
|
||||
fn blobs(painter: &Painter, area: Rect, p: &Palette, t: f32, n: f32, cursor: Option<Cursor>, aa: f32) {
|
||||
let tints = [p.secondary_container, p.primary_container, p.tertiary_container];
|
||||
let scale = (area.width().min(area.height()) / 900.0).clamp(0.6, 1.5);
|
||||
for i in 0..count(area, 14.0, n) {
|
||||
let radius = scale * (40.0 + rnd(i, 5).powi(2) * 130.0);
|
||||
let mut pos = drift(area, i, t, radius * 1.2, 9.0);
|
||||
let mut grow = 1.0;
|
||||
if let Some(c) = cursor {
|
||||
pos += c.push(pos, radius + 180.0, 90.0);
|
||||
grow += 0.08 * c.falloff(pos, radius + 120.0);
|
||||
}
|
||||
fill(painter, pos, &blob(pos, radius * grow, t, rnd(i, 6)), tints[i % tints.len()].gamma_multiply(0.6), aa);
|
||||
}
|
||||
}
|
||||
|
||||
/// Dots joined by thin lines when they come close; the cursor is a star of its own that draws lines to the dots
|
||||
/// near it and pulls them in a little.
|
||||
fn constellation(painter: &Painter, area: Rect, p: &Palette, t: f32, n: f32, cursor: Option<Cursor>) {
|
||||
let link = 150.0;
|
||||
let reach = 200.0;
|
||||
let points: Vec<(Pos2, f32)> = (0..count(area, 95.0, n))
|
||||
.map(|i| {
|
||||
let mut pos = drift(area, i, t, link, 12.0);
|
||||
if let Some(c) = cursor {
|
||||
pos -= c.push(pos, reach, 22.0);
|
||||
}
|
||||
(pos, 1.2 + rnd(i, 5) * 1.6)
|
||||
})
|
||||
.collect();
|
||||
for (i, (a, _)) in points.iter().enumerate() {
|
||||
for (b, _) in &points[i + 1..] {
|
||||
let d = (*a - *b).length();
|
||||
if d < link {
|
||||
let strength = (1.0 - d / link).powi(2);
|
||||
painter.line_segment([*a, *b], Stroke::new(1.0, p.primary.gamma_multiply(0.35 * strength)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(c) = cursor {
|
||||
for (pos, _) in &points {
|
||||
let near = c.falloff(*pos, reach);
|
||||
if near > 0.0 {
|
||||
painter.line_segment([c.pos, *pos], Stroke::new(1.0, p.primary.gamma_multiply(0.6 * near)));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (pos, r) in &points {
|
||||
painter.circle_filled(*pos, *r, p.primary.gamma_multiply(0.75));
|
||||
}
|
||||
}
|
||||
|
||||
/// Sine lines across the page that swell and bend away where the cursor is.
|
||||
fn waves(painter: &Painter, area: Rect, p: &Palette, t: f32, n: f32, cursor: Option<Cursor>) {
|
||||
let lines = (6.0 * n).round().clamp(3.0, 12.0) as usize;
|
||||
for line in 0..lines {
|
||||
let base = area.top() + area.height() * (line as f32 + 0.5) / lines as f32;
|
||||
let wavelength = 170.0 + rnd(line, 1) * 120.0;
|
||||
let amplitude = 12.0 + rnd(line, 2) * 14.0;
|
||||
let pace = 0.8 + rnd(line, 3) * 0.6;
|
||||
let phase = rnd(line, 4) * TAU;
|
||||
let points: Vec<Pos2> = (0..=(area.width() / 6.0).ceil() as usize)
|
||||
.map(|k| {
|
||||
let x = area.left() + k as f32 * 6.0;
|
||||
let angle = TAU * (x - area.left()) / wavelength + t * pace + phase;
|
||||
let mut y = base + amplitude * angle.sin() + amplitude * 0.35 * (angle * 0.43 - t * pace * 0.6).sin();
|
||||
if let Some(c) = cursor {
|
||||
let dx = x - c.pos.x;
|
||||
let dy = base - c.pos.y;
|
||||
let near = (-(dx * dx) / (2.0 * 150.0 * 150.0) - (dy * dy) / (2.0 * 170.0 * 170.0)).exp() * c.amount;
|
||||
y += near * (amplitude * 1.6 * angle.sin() + dy.signum() * 26.0);
|
||||
}
|
||||
pos2(x, y)
|
||||
})
|
||||
.collect();
|
||||
let alpha = if line % 2 == 0 { 0.55 } else { 0.32 };
|
||||
painter.add(Shape::line(points, Stroke::new(2.0, p.primary.gamma_multiply(alpha))));
|
||||
}
|
||||
}
|
||||
|
||||
/// A grid of faint dots with a slow ripple running over it; round the cursor the dots swell and light up in
|
||||
/// rings.
|
||||
fn dots(painter: &Painter, area: Rect, p: &Palette, t: f32, n: f32, cursor: Option<Cursor>) {
|
||||
let step = (26.0 / n.sqrt()).clamp(16.0, 40.0);
|
||||
let reach = 210.0;
|
||||
let columns = (area.width() / step).floor().max(1.0);
|
||||
let rows = (area.height() / step).floor().max(1.0);
|
||||
let origin = area.center() - vec2((columns - 1.0) * step, (rows - 1.0) * step) / 2.0;
|
||||
for row in 0..rows as usize {
|
||||
for column in 0..columns as usize {
|
||||
let pos = origin + vec2(column as f32 * step, row as f32 * step);
|
||||
let ripple = 0.5 + 0.5 * ((pos.x + pos.y) * 0.01 - t * 1.1).sin();
|
||||
let mut swell = 0.0;
|
||||
if let Some(c) = cursor {
|
||||
let near = c.falloff(pos, reach);
|
||||
if near > 0.0 {
|
||||
let d = (pos - c.pos).length();
|
||||
swell = (near * (0.7 + 0.3 * (d * 0.07 - t * 3.0).sin())).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
let radius = 0.9 + 0.5 * ripple + 3.4 * swell;
|
||||
let alpha = egui::lerp((0.14 + 0.1 * ripple)..=0.95, swell);
|
||||
painter.circle_filled(pos, radius, theme::layer(p.on_surface_variant, p.primary, swell).gamma_multiply(alpha));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The image or GIF, cut to cover the area, softened by Blur and dimmed toward the page colour by Dim.
|
||||
fn image_layer(ui: &mut Ui, f: &mut Frame, ntp: &Ntp, area: Rect, p: &Palette, still: bool) {
|
||||
if ntp.bg_image.is_empty() {
|
||||
f.ui.ntp_backdrop = None;
|
||||
return;
|
||||
}
|
||||
let path = f.shared.paths.data.join(&ntp.bg_image);
|
||||
if f.ui.ntp_backdrop.as_ref().is_none_or(|b| b.path != path) {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let from = path.clone();
|
||||
let ctx = ui.ctx().clone();
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(decode(&from));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
f.ui.ntp_backdrop = Some(Backdrop { path, loading: Some(rx), base: Vec::new(), textures: Vec::new(), blur: f32::NAN, failed: false });
|
||||
}
|
||||
let Some(backdrop) = f.ui.ntp_backdrop.as_mut() else { return };
|
||||
if let Some(rx) = &backdrop.loading {
|
||||
match rx.try_recv() {
|
||||
Ok(Ok(frames)) => {
|
||||
backdrop.base = frames;
|
||||
backdrop.loading = None;
|
||||
},
|
||||
Ok(Err(error)) => {
|
||||
log::warn!("new tab background {}: {error}", backdrop.path.display());
|
||||
backdrop.failed = true;
|
||||
backdrop.loading = None;
|
||||
},
|
||||
Err(TryRecvError::Empty) => {},
|
||||
Err(TryRecvError::Disconnected) => backdrop.loading = None,
|
||||
}
|
||||
}
|
||||
// Blur in steps of 2 px, so dragging the slider remakes the textures a few times rather than every frame.
|
||||
let blur = (ntp.bg_blur / 2.0).round() * 2.0;
|
||||
if !backdrop.base.is_empty() && backdrop.blur != blur {
|
||||
backdrop.textures = backdrop.base.iter().enumerate().map(|(i, (img, _))| ui.ctx().load_texture(format!("ntp-bg-{i}"), soften(img, blur), egui::TextureOptions::LINEAR)).collect();
|
||||
backdrop.blur = blur;
|
||||
}
|
||||
if backdrop.textures.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Which GIF frame shows now, and when the next one is due.
|
||||
let mut index = 0;
|
||||
if backdrop.textures.len() > 1 && !still {
|
||||
let total: f32 = backdrop.base.iter().map(|(_, d)| d).sum();
|
||||
let mut at = (ui.input(|i| i.time) as f32).rem_euclid(total.max(0.01));
|
||||
for (i, (_, delay)) in backdrop.base.iter().enumerate() {
|
||||
if at < *delay {
|
||||
index = i;
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f32((delay - at).max(0.005)));
|
||||
break;
|
||||
}
|
||||
at -= delay;
|
||||
}
|
||||
}
|
||||
let texture = &backdrop.textures[index];
|
||||
let size = texture.size_vec2();
|
||||
// Cover: fill the area, cutting what sticks out on one axis.
|
||||
let (aw, ah) = (area.width() / size.x, area.height() / size.y);
|
||||
let uv = if aw > ah {
|
||||
let h = ah / aw;
|
||||
Rect::from_min_max(pos2(0.0, (1.0 - h) / 2.0), pos2(1.0, (1.0 + h) / 2.0))
|
||||
} else {
|
||||
let w = aw / ah;
|
||||
Rect::from_min_max(pos2((1.0 - w) / 2.0, 0.0), pos2((1.0 + w) / 2.0, 1.0))
|
||||
};
|
||||
ui.painter().image(texture.id(), area, uv, Color32::WHITE);
|
||||
ui.painter().rect_filled(area, 0.0, p.surface_container_lowest.gamma_multiply(ntp.bg_dim.clamp(0.0, 1.0)));
|
||||
}
|
||||
|
||||
/// Reads an image, or every frame of an animated GIF with its delay in seconds.
|
||||
fn decode(path: &Path) -> Result<Vec<(image::RgbaImage, f32)>, String> {
|
||||
use image::AnimationDecoder as _;
|
||||
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
|
||||
if bytes.starts_with(b"GIF8") {
|
||||
let decoder = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(&bytes)).map_err(|e| e.to_string())?;
|
||||
let frames: Vec<image::Frame> = decoder.into_frames().take(GIF_MAX_FRAMES).collect::<Result<_, _>>().map_err(|e| e.to_string())?;
|
||||
if frames.len() > 1 {
|
||||
let budget = (GIF_PIXELS / frames.len()).min(1920 * 1080);
|
||||
return Ok(frames
|
||||
.into_iter()
|
||||
.map(|frame| {
|
||||
let (num, den) = frame.delay().numer_denom_ms();
|
||||
let ms = num as f32 / den.max(1) as f32;
|
||||
// Like browsers: a delay under 20 ms means "as the format's default", 100 ms.
|
||||
let delay = if ms < 20.0 { 0.1 } else { ms / 1000.0 };
|
||||
(fit(frame.into_buffer(), budget), delay)
|
||||
})
|
||||
.collect());
|
||||
}
|
||||
}
|
||||
let img = image::load_from_memory(&bytes).map_err(|e| e.to_string())?;
|
||||
Ok(vec![(fit(img.to_rgba8(), 1920 * 1080), 0.0)])
|
||||
}
|
||||
|
||||
/// Scales an image down to at most `pixels` pixels.
|
||||
fn fit(img: image::RgbaImage, pixels: usize) -> image::RgbaImage {
|
||||
let have = img.width() as usize * img.height() as usize;
|
||||
if have <= pixels {
|
||||
return img;
|
||||
}
|
||||
let k = (pixels as f32 / have as f32).sqrt();
|
||||
image::imageops::resize(&img, ((img.width() as f32 * k) as u32).max(1), ((img.height() as f32 * k) as u32).max(1), image::imageops::FilterType::Triangle)
|
||||
}
|
||||
|
||||
/// Blurs by shrinking the image until a pixel covers about half the blur radius (as seen on a page about 1600 px
|
||||
/// wide), smoothing that, and letting the linear filter stretch it back. Fast enough to follow the slider.
|
||||
fn soften(img: &image::RgbaImage, blur: f32) -> egui::ColorImage {
|
||||
let out = if blur < 1.0 {
|
||||
img.clone()
|
||||
} else {
|
||||
let width = (3200.0 / blur).min(img.width() as f32).max(8.0);
|
||||
let k = width / img.width() as f32;
|
||||
let small = image::imageops::resize(img, width as u32, ((img.height() as f32 * k) as u32).max(8), image::imageops::FilterType::Triangle);
|
||||
image::imageops::blur(&small, 1.2)
|
||||
};
|
||||
egui::ColorImage::from_rgba_unmultiplied([out.width() as usize, out.height() as usize], out.as_raw())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rounded_polygon_stays_inside_its_circle() {
|
||||
let c = pos2(100.0, 100.0);
|
||||
for sides in [3, 4] {
|
||||
for round in [0.0, 0.5, 1.0] {
|
||||
let pts = rounded_polygon(c, 50.0, sides, round, 0.3);
|
||||
assert_eq!(pts.len(), sides as usize * 9);
|
||||
assert!(pts.iter().all(|p| (*p - c).length() <= 50.01), "{sides} sides, round {round}");
|
||||
}
|
||||
}
|
||||
// Sharp corners reach the circle; rounded ones don't.
|
||||
let sharp = rounded_polygon(c, 50.0, 4, 0.0, 0.0);
|
||||
assert!(sharp.iter().any(|p| ((*p - c).length() - 50.0).abs() < 0.01));
|
||||
assert!(rounded_polygon(c, 50.0, 4, 1.0, 0.0).iter().all(|p| (*p - c).length() < 49.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capsule_has_its_length_and_width() {
|
||||
let pts = capsule(Pos2::ZERO, 100.0, 20.0, 0.0);
|
||||
let xs = pts.iter().map(|p| p.x);
|
||||
let ys = pts.iter().map(|p| p.y);
|
||||
let (min_x, max_x) = xs.fold((f32::MAX, f32::MIN), |(a, b), x| (a.min(x), b.max(x)));
|
||||
let (min_y, max_y) = ys.fold((f32::MAX, f32::MIN), |(a, b), y| (a.min(y), b.max(y)));
|
||||
assert!((max_x - min_x - 100.0).abs() < 0.1 && (max_y - min_y - 20.0).abs() < 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drift_stays_in_the_margin_and_cursor_pushes_away() {
|
||||
let area = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
|
||||
for i in 0..50 {
|
||||
let p = drift(area, i, 1234.5, 40.0, 14.0);
|
||||
assert!(area.expand(40.0).contains(p));
|
||||
}
|
||||
let c = Cursor { pos: pos2(100.0, 100.0), amount: 1.0 };
|
||||
let push = c.push(pos2(150.0, 100.0), 200.0, 70.0);
|
||||
assert!(push.x > 0.0 && push.y.abs() < 0.001);
|
||||
assert_eq!(c.push(pos2(400.0, 100.0), 200.0, 70.0), Vec2::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gif_frames_and_delays() {
|
||||
use image::codecs::gif::GifEncoder;
|
||||
let dir = std::env::temp_dir().join(format!("nacre-backdrop-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("two.gif");
|
||||
{
|
||||
let file = std::fs::File::create(&path).unwrap();
|
||||
let mut encoder = GifEncoder::new(file);
|
||||
for (shade, ms) in [(0u8, 50u32), (255, 5)] {
|
||||
let buffer = image::RgbaImage::from_pixel(4, 3, image::Rgba([shade, shade, shade, 255]));
|
||||
encoder.encode_frame(image::Frame::from_parts(buffer, 0, 0, image::Delay::from_numer_denom_ms(ms, 1))).unwrap();
|
||||
}
|
||||
}
|
||||
let frames = decode(&path).unwrap();
|
||||
assert_eq!(frames.len(), 2);
|
||||
assert_eq!((frames[0].0.width(), frames[0].0.height()), (4, 3));
|
||||
assert!((frames[0].1 - 0.05).abs() < 0.001 && (frames[1].1 - 0.1).abs() < 0.001);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
536
src/ui/pages/customize.rs
Normal file
536
src/ui/pages/customize.rs
Normal file
|
|
@ -0,0 +1,536 @@
|
|||
//! The new tab page's Customize panel (docs/UI-BRIEF.md "Customize panel"): a rounded panel that slides in from the
|
||||
//! right over the page, which stays live behind it, with Background, Image or GIF, Elements and Details.
|
||||
|
||||
use egui::{Align2, Id, Rect, RichText, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2};
|
||||
|
||||
use super::super::Frame;
|
||||
use super::super::menus::one_line;
|
||||
use super::super::widgets::{ButtonKind, button, focus_ring, icon, icon_button, interaction, segmented, switch};
|
||||
use crate::actions::Command;
|
||||
use crate::store::settings::{Ntp, NtpBackground};
|
||||
use crate::theme::{self, Weight};
|
||||
use crate::ui::icons;
|
||||
use crate::util;
|
||||
|
||||
const WIDTH: f32 = 400.0;
|
||||
const LINE: f32 = 48.0;
|
||||
/// Wait this long after the last key before asking for place suggestions.
|
||||
const SUGGEST_AFTER: f64 = 0.35;
|
||||
|
||||
/// Each element's name and icon in the panel.
|
||||
pub fn element_name(key: &str) -> (&'static str, &'static str) {
|
||||
match key {
|
||||
"greeting" => ("Greeting", icons::WAVING_HAND),
|
||||
"clock" => ("Clock", icons::SCHEDULE),
|
||||
"shortcuts" => ("Shortcuts", icons::APPS),
|
||||
"media" => ("Now playing", icons::MUSIC_NOTE),
|
||||
"weather" => ("Weather", icons::PARTLY_CLOUDY_DAY),
|
||||
"search" => ("Search", icons::SEARCH),
|
||||
"notes" => ("Notes", icons::STICKY_NOTE_2),
|
||||
"reading" => ("Reading list", icons::CHROME_READER_MODE),
|
||||
"recent" => ("Top sites", icons::TRENDING_UP),
|
||||
_ => ("Element", icons::WEB),
|
||||
}
|
||||
}
|
||||
|
||||
fn background_icon(bg: NtpBackground) -> &'static str {
|
||||
match bg {
|
||||
NtpBackground::Off => icons::BLOCK,
|
||||
NtpBackground::Shapes => icons::SHAPES,
|
||||
NtpBackground::Blobs => icons::BUBBLE_CHART,
|
||||
NtpBackground::Particles => icons::SCATTER_PLOT,
|
||||
NtpBackground::Waves => icons::WAVES,
|
||||
NtpBackground::Dots => icons::GRAIN,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the panel is this frame (it slides), or None when it's closed and gone.
|
||||
pub fn rect(ui: &Ui, f: &Frame, page: Rect) -> Option<Rect> {
|
||||
let open = f.ui.pages.ntp_customize;
|
||||
let shown = theme::spring(ui.ctx(), Id::new("ntp-customize-slide"), if open { 1.0 } else { 0.0 }, theme::DEFAULT);
|
||||
if !open && shown < 0.005 {
|
||||
return None;
|
||||
}
|
||||
let width = WIDTH.min(page.width() - 2.0 * theme::GAP_S);
|
||||
let x = page.right() - theme::GAP_S - width + (1.0 - shown) * (width + 2.0 * theme::GAP_S);
|
||||
Some(Rect::from_min_size(pos2(x, page.top() + theme::GAP_S), vec2(width, page.height() - 2.0 * theme::GAP_S)))
|
||||
}
|
||||
|
||||
/// The round "Customize" button at the bottom right of the page; hidden while the panel is open.
|
||||
pub fn opener(ui: &mut Ui, f: &mut Frame, page: Rect) {
|
||||
let p = theme::palette(ui.ctx());
|
||||
let shown = theme::effect(ui.ctx(), Id::new("ntp-customize-opener"), !f.ui.pages.ntp_customize);
|
||||
if shown < 0.01 {
|
||||
return;
|
||||
}
|
||||
let label = "Customize";
|
||||
let galley = ui.painter().layout_no_wrap(label.to_owned(), theme::font(theme::BODY, Weight::Medium), p.on_secondary_container);
|
||||
let size = vec2(theme::GAP_L + 20.0 + theme::GAP_S + galley.size().x + theme::GAP_XL, theme::CONTROL);
|
||||
let rect = Rect::from_min_size(page.right_bottom() - size - Vec2::splat(theme::GAP_L), size);
|
||||
let response = ui.interact(rect, Id::new("ntp-customize-button"), Sense::click());
|
||||
let s = interaction(ui, &response);
|
||||
let radius = theme::CONTROL / 2.0 * (1.0 - 0.4 * s.press.clamp(0.0, 1.2));
|
||||
let painter = ui.painter().clone().with_layer_id(egui::LayerId::new(egui::Order::Middle, Id::new("ntp-customize-button-layer")));
|
||||
painter.rect_filled(rect, theme::corner_radius(radius), s.layer(p.secondary_container, p.on_secondary_container).gamma_multiply(shown));
|
||||
let content = p.on_secondary_container.gamma_multiply(shown);
|
||||
painter.text(pos2(rect.left() + theme::GAP_L + 10.0, rect.center().y), Align2::CENTER_CENTER, icons::TUNE, theme::icon_font(20.0, false), content);
|
||||
painter.galley(pos2(rect.left() + theme::GAP_L + 20.0 + theme::GAP_S, rect.center().y - galley.size().y / 2.0), galley, content);
|
||||
if s.focus {
|
||||
focus_ring(ui, rect, theme::CONTROL / 2.0, &p);
|
||||
}
|
||||
if response.on_hover_text("Change the background and what this page shows").clicked() {
|
||||
f.ui.pages.ntp_customize = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the panel at `rect` (from `rect()`) on its own layer above the page.
|
||||
pub fn panel(ui: &mut Ui, f: &mut Frame, page: Rect, rect: Rect) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let p = theme::palette(&ctx);
|
||||
if f.ui.pages.ntp_customize && ctx.input(|i| i.key_pressed(egui::Key::Escape)) && ctx.memory(|m| m.focused().is_none()) {
|
||||
f.ui.pages.ntp_customize = false;
|
||||
}
|
||||
let radius = theme::radius(&ctx, theme::L);
|
||||
egui::Area::new(Id::new("ntp-customize"))
|
||||
.order(egui::Order::Middle)
|
||||
.fixed_pos(rect.min)
|
||||
.default_size(rect.size())
|
||||
.constrain(false)
|
||||
.show(&ctx, |ui| {
|
||||
ui.set_clip_rect(page);
|
||||
crate::ui::paint::shadow(ui.painter(), rect, radius, p.dark);
|
||||
ui.painter().rect_filled(rect, theme::corner_radius(radius), p.surface_container_high);
|
||||
// Swallow clicks on the panel's empty parts so they don't reach the page under it.
|
||||
ui.interact(rect, Id::new("ntp-customize-back"), Sense::click());
|
||||
let inner = rect.shrink2(vec2(theme::GAP_L, theme::GAP_M));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner));
|
||||
child.set_clip_rect(rect.intersect(page));
|
||||
let ui = &mut child;
|
||||
ui.spacing_mut().item_spacing = Vec2::ZERO;
|
||||
ui.horizontal(|ui| {
|
||||
ui.set_min_height(theme::CONTROL);
|
||||
ui.label(RichText::new("Customize").font(theme::font(theme::HEADLINE, Weight::Regular)).color(p.on_surface));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if icon_button(ui, icons::CLOSE, "Close").clicked() {
|
||||
f.ui.pages.ntp_customize = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(theme::GAP_S);
|
||||
let mut ntp = f.shared.settings.borrow().ntp.clone();
|
||||
let before = ntp.clone();
|
||||
egui::ScrollArea::vertical().id_salt("ntp-customize-scroll").auto_shrink([false, false]).show(ui, |ui| {
|
||||
ui.set_width(inner.width());
|
||||
ui.spacing_mut().item_spacing = Vec2::ZERO;
|
||||
background_section(ui, &mut ntp);
|
||||
image_section(ui, f, &mut ntp);
|
||||
elements_section(ui, &mut ntp);
|
||||
details_section(ui, f, &mut ntp);
|
||||
ui.add_space(theme::GAP_L);
|
||||
});
|
||||
if ntp != before {
|
||||
f.shared.settings.borrow_mut().ntp = ntp;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A section title in the accent colour.
|
||||
fn heading(ui: &mut Ui, title: &str) {
|
||||
let p = theme::palette(ui.ctx());
|
||||
ui.add_space(theme::GAP_L);
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::hover());
|
||||
ui.painter().text(pos2(rect.left() + theme::GAP_XS, rect.center().y), Align2::LEFT_CENTER, title, theme::font(theme::BODY, Weight::Medium), p.primary);
|
||||
ui.add_space(theme::GAP_XS);
|
||||
}
|
||||
|
||||
/// One line of the panel: icon, label, and the control at the right.
|
||||
fn line<R>(ui: &mut Ui, glyph: &str, label: &str, control: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
let p = theme::palette(ui.ctx());
|
||||
let width = ui.available_width();
|
||||
ui.allocate_ui_with_layout(vec2(width, LINE), egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.set_min_size(vec2(width, LINE));
|
||||
let enabled = ui.is_enabled();
|
||||
let content = |c: egui::Color32| if enabled { c } else { c.gamma_multiply(theme::DISABLED_CONTENT) };
|
||||
let (r, _) = ui.allocate_exact_size(vec2(32.0, LINE), Sense::hover());
|
||||
icon(ui, pos2(r.left() + 12.0, r.center().y), glyph, theme::ICON, false, content(p.on_surface_variant));
|
||||
let label = one_line(ui, label, theme::font(theme::BODY, Weight::Regular), content(p.on_surface), width * 0.45);
|
||||
ui.label(label);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), control).inner
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
/// A filter chip: icon and label in an outlined pill; the selected one is filled.
|
||||
fn chip(ui: &mut Ui, glyph: &str, label: &str, selected: bool) -> egui::Response {
|
||||
let p = theme::palette(ui.ctx());
|
||||
let font = theme::font(theme::BODY, Weight::Medium);
|
||||
let galley = ui.painter().layout_no_wrap(label.to_owned(), font, p.on_surface);
|
||||
let size = vec2(theme::GAP_M + 18.0 + theme::GAP_S + galley.size().x + theme::GAP_L, theme::CONTROL_SMALL + 4.0);
|
||||
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
|
||||
let s = interaction(ui, &response);
|
||||
let on = theme::effect(ui.ctx(), response.id.with("on"), selected);
|
||||
let radius = theme::radius(ui.ctx(), theme::S);
|
||||
let container = theme::layer(p.surface_container_high, p.secondary_container, on);
|
||||
let content = theme::layer(p.on_surface_variant, p.on_secondary_container, on);
|
||||
ui.painter().rect_filled(rect, theme::corner_radius(radius), s.layer(container, content));
|
||||
if on < 0.99 {
|
||||
ui.painter().rect_stroke(rect, theme::corner_radius(radius), Stroke::new(1.0, p.outline_variant.gamma_multiply(1.0 - on)), StrokeKind::Inside);
|
||||
}
|
||||
icon(ui, pos2(rect.left() + theme::GAP_M + 9.0, rect.center().y), glyph, 18.0, on > 0.5, content);
|
||||
ui.painter().galley(pos2(rect.left() + theme::GAP_M + 18.0 + theme::GAP_S, rect.center().y - galley.size().y / 2.0), galley, content);
|
||||
if s.focus {
|
||||
focus_ring(ui, rect, radius, &p);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// An M3 Expressive slider: a thick track, the active part in the accent, a bar for a handle with a gap round
|
||||
/// it. Drag or click to set; arrow keys step by a twentieth. Returns true when the value changed.
|
||||
fn slider(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive<f32>, width: f32, tooltip: &str) -> bool {
|
||||
let p = theme::palette(ui.ctx());
|
||||
let (rect, response) = ui.allocate_exact_size(vec2(width, theme::CONTROL), Sense::click_and_drag());
|
||||
let (lo, hi) = (*range.start(), *range.end());
|
||||
let mut fraction = ((*value - lo) / (hi - lo)).clamp(0.0, 1.0);
|
||||
let before = fraction;
|
||||
let track = rect.shrink2(vec2(2.0, 0.0));
|
||||
if (response.dragged() || response.clicked())
|
||||
&& let Some(at) = response.interact_pointer_pos()
|
||||
{
|
||||
fraction = ((at.x - track.left()) / track.width()).clamp(0.0, 1.0);
|
||||
}
|
||||
if response.has_focus() {
|
||||
let step = ui.input(|i| i.key_pressed(egui::Key::ArrowRight) as i32 - i.key_pressed(egui::Key::ArrowLeft) as i32);
|
||||
fraction = (fraction + step as f32 * 0.05).clamp(0.0, 1.0);
|
||||
}
|
||||
let changed = fraction != before;
|
||||
if changed {
|
||||
*value = lo + fraction * (hi - lo);
|
||||
}
|
||||
let s = interaction(ui, &response);
|
||||
let enabled = s.enabled;
|
||||
let dim = |c: egui::Color32, k: f32| if enabled { c } else { p.on_surface.gamma_multiply(k) };
|
||||
let x = track.left() + fraction * track.width();
|
||||
let thickness = 16.0;
|
||||
let gap = 6.0;
|
||||
let handle_width = 4.0 - 2.0 * s.press.clamp(0.0, 1.0);
|
||||
let r = theme::corner_radius(thickness / 2.0);
|
||||
let y = track.center().y;
|
||||
let active = Rect::from_min_max(pos2(track.left(), y - thickness / 2.0), pos2((x - gap).max(track.left()), y + thickness / 2.0));
|
||||
let rest = Rect::from_min_max(pos2((x + gap).min(track.right()), y - thickness / 2.0), pos2(track.right(), y + thickness / 2.0));
|
||||
if active.width() > 0.5 {
|
||||
ui.painter().rect_filled(active, r, dim(p.primary, theme::DISABLED_CONTENT));
|
||||
}
|
||||
if rest.width() > 0.5 {
|
||||
ui.painter().rect_filled(rest, r, dim(p.secondary_container, theme::DISABLED_CONTAINER));
|
||||
}
|
||||
let handle = Rect::from_center_size(pos2(x, y), vec2(handle_width, 36.0));
|
||||
if s.amount() > 0.0 {
|
||||
ui.painter().rect_filled(handle.expand(4.0), theme::corner_radius(6.0), p.primary.gamma_multiply(s.amount()));
|
||||
}
|
||||
ui.painter().rect_filled(handle, theme::corner_radius(2.0), dim(p.primary, theme::DISABLED_CONTENT));
|
||||
if s.focus {
|
||||
focus_ring(ui, handle.expand(4.0), 6.0, &p);
|
||||
}
|
||||
response.on_hover_text(tooltip);
|
||||
changed
|
||||
}
|
||||
|
||||
fn background_section(ui: &mut Ui, ntp: &mut Ntp) {
|
||||
heading(ui, "Background");
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(theme::GAP_S, theme::GAP_S);
|
||||
// The order of the video, None first (the enum's first variant is the default, Shapes).
|
||||
let order = [NtpBackground::Off, NtpBackground::Shapes, NtpBackground::Blobs, NtpBackground::Particles, NtpBackground::Waves, NtpBackground::Dots];
|
||||
for bg in order {
|
||||
if chip(ui, background_icon(bg), bg.label(), ntp.bg == bg).clicked() {
|
||||
ntp.bg = bg;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(theme::GAP_S);
|
||||
ui.add_enabled_ui(ntp.bg != NtpBackground::Off, |ui| {
|
||||
let mut amount = match ntp.bg_density.as_str() {
|
||||
"low" => "low",
|
||||
"high" => "high",
|
||||
_ => "medium",
|
||||
};
|
||||
if line(ui, icons::FILTER_LIST, "Amount", |ui| segmented(ui, &mut amount, &[("low", "Few"), ("medium", "Some"), ("high", "Lots")])) {
|
||||
ntp.bg_density = amount.to_owned();
|
||||
}
|
||||
let mut speed = match ntp.bg_speed.as_str() {
|
||||
"slow" => "slow",
|
||||
"fast" => "fast",
|
||||
_ => "normal",
|
||||
};
|
||||
if line(ui, icons::SPEED, "Speed", |ui| segmented(ui, &mut speed, &[("slow", "Slow"), ("normal", "Normal"), ("fast", "Fast")])) {
|
||||
ntp.bg_speed = speed.to_owned();
|
||||
}
|
||||
line(ui, icons::MOUSE, "React to the cursor", |ui| switch(ui, &mut ntp.bg_mouse));
|
||||
});
|
||||
}
|
||||
|
||||
fn image_section(ui: &mut Ui, f: &mut Frame, ntp: &mut Ntp) {
|
||||
heading(ui, "Image or GIF");
|
||||
let has = !ntp.bg_image.is_empty();
|
||||
let state = f.ui.ntp_backdrop.as_ref();
|
||||
let (glyph, what) = match state {
|
||||
_ if !has => (icons::IMAGE, "No image"),
|
||||
Some(b) if b.failed => (icons::ERROR, "Couldn't read this file"),
|
||||
Some(b) if b.is_gif() => (icons::GIF_BOX, "GIF set"),
|
||||
_ => (icons::IMAGE, "Image set"),
|
||||
};
|
||||
let mut pick = false;
|
||||
let mut remove = false;
|
||||
line(ui, glyph, what, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = theme::GAP_S;
|
||||
if has {
|
||||
remove = button(ui, ButtonKind::Text, None, "Remove").clicked();
|
||||
pick = button(ui, ButtonKind::Tonal, None, "Change").on_hover_text("Choose another image or GIF").clicked();
|
||||
} else {
|
||||
pick = button(ui, ButtonKind::Tonal, Some(icons::UPLOAD), "Upload").on_hover_text("Choose an image or GIF").clicked();
|
||||
}
|
||||
});
|
||||
if pick && let Some(path) = rfd::FileDialog::new().add_filter("Images and GIFs", &["png", "jpg", "jpeg", "webp", "gif", "bmp"]).pick_file() {
|
||||
let name = format!("ntp-bg-{}.{}", util::now(), path.extension().and_then(|e| e.to_str()).unwrap_or("png").to_lowercase());
|
||||
match std::fs::copy(&path, f.shared.paths.data.join(&name)) {
|
||||
Ok(_) => {
|
||||
forget_image(f, ntp);
|
||||
ntp.bg_image = name;
|
||||
},
|
||||
Err(error) => {
|
||||
let why = if error.kind() == std::io::ErrorKind::PermissionDenied { "you don't have permission to read it" } else { "the file couldn't be copied" };
|
||||
f.send(Command::Toast(format!("Couldn't use {}: {why}", path.file_name().map(|n| n.to_string_lossy()).unwrap_or_default())));
|
||||
},
|
||||
}
|
||||
}
|
||||
if remove {
|
||||
forget_image(f, ntp);
|
||||
}
|
||||
ui.add_enabled_ui(!ntp.bg_image.is_empty(), |ui| {
|
||||
let width = (ui.available_width() * 0.5).max(120.0);
|
||||
let tip = format!("{:.0}%", ntp.bg_dim * 100.0);
|
||||
line(ui, icons::BRIGHTNESS_6, "Dim", |ui| slider(ui, &mut ntp.bg_dim, 0.0..=0.9, width, &tip));
|
||||
let tip = format!("{:.0} px", ntp.bg_blur);
|
||||
line(ui, icons::BLUR_MEDIUM, "Blur", |ui| slider(ui, &mut ntp.bg_blur, 0.0..=40.0, width, &tip));
|
||||
});
|
||||
}
|
||||
|
||||
/// Clears the background image and deletes the copy Nacre made of it.
|
||||
fn forget_image(f: &Frame, ntp: &mut Ntp) {
|
||||
if ntp.bg_image.starts_with("ntp-bg-") && !ntp.bg_image.contains(['/', '\\']) {
|
||||
let _ = std::fs::remove_file(f.shared.paths.data.join(&ntp.bg_image));
|
||||
}
|
||||
ntp.bg_image.clear();
|
||||
}
|
||||
|
||||
fn elements_section(ui: &mut Ui, ntp: &mut Ntp) {
|
||||
heading(ui, "Elements");
|
||||
let len = ntp.elements.len();
|
||||
let mut swap = None;
|
||||
for i in 0..len {
|
||||
let (name, glyph) = element_name(&ntp.elements[i].0);
|
||||
ui.push_id(("ntp-element", i), |ui| {
|
||||
line(ui, glyph, name, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = theme::GAP_XS;
|
||||
switch(ui, &mut ntp.elements[i].1);
|
||||
ui.add_space(theme::GAP_S);
|
||||
ui.add_enabled_ui(i + 1 < len, |ui| {
|
||||
if icon_button(ui, icons::ARROW_DOWNWARD, &format!("Move {name} down")).clicked() {
|
||||
swap = Some((i, i + 1));
|
||||
}
|
||||
});
|
||||
ui.add_enabled_ui(i > 0, |ui| {
|
||||
if icon_button(ui, icons::ARROW_UPWARD, &format!("Move {name} up")).clicked() {
|
||||
swap = Some((i, i - 1));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
if let Some((a, b)) = swap {
|
||||
ntp.elements.swap(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
fn details_section(ui: &mut Ui, f: &mut Frame, ntp: &mut Ntp) {
|
||||
heading(ui, "Details");
|
||||
line(ui, icons::SCHEDULE, "24-hour clock", |ui| switch(ui, &mut ntp.clock24));
|
||||
line(ui, icons::TIMER, "Show seconds", |ui| switch(ui, &mut ntp.seconds));
|
||||
let field_width = (ui.available_width() * 0.55).max(140.0);
|
||||
line(ui, icons::PERSON, "Your name", |ui| field(ui, &mut ntp.name, "For the greeting", field_width, "ntp-name"));
|
||||
let place = line(ui, icons::PLACE, "Weather place", |ui| field(ui, &mut ntp.city, "City or town", field_width, "ntp-place"));
|
||||
if place.changed() {
|
||||
// The saved coordinates belong to the old place.
|
||||
ntp.city_loc = None;
|
||||
}
|
||||
place_suggestions(ui, f, ntp, &place);
|
||||
let mut units = match ntp.units.as_str() {
|
||||
"c" => "c",
|
||||
"f" => "f",
|
||||
_ => "auto",
|
||||
};
|
||||
if line(ui, icons::THERMOSTAT, "Units", |ui| segmented(ui, &mut units, &[("auto", "Auto"), ("c", "°C"), ("f", "°F")])) {
|
||||
ntp.units = units.to_owned();
|
||||
}
|
||||
}
|
||||
|
||||
/// A filled text field in the panel's style.
|
||||
fn field(ui: &mut Ui, text: &mut String, hint: &str, width: f32, id: &str) -> egui::Response {
|
||||
let p = theme::palette(ui.ctx());
|
||||
let font = theme::font(theme::BODY, Weight::Regular);
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(width, theme::CONTROL), Sense::hover());
|
||||
let edit_id = Id::new(id);
|
||||
let focused = ui.memory(|m| m.has_focus(edit_id));
|
||||
let radius = theme::corner_radius(theme::radius(ui.ctx(), theme::S));
|
||||
ui.painter().rect_filled(rect, radius, p.surface_container_highest);
|
||||
let ring = theme::effect(ui.ctx(), edit_id.with("focus"), focused);
|
||||
if ring > 0.0 {
|
||||
ui.painter().rect_stroke(rect, radius, Stroke::new(2.0, p.primary.gamma_multiply(ring)), StrokeKind::Inside);
|
||||
}
|
||||
let row_height = ui.fonts_mut(|fonts| fonts.row_height(&font));
|
||||
let inner = rect.shrink2(vec2(theme::GAP_XS, (theme::CONTROL - row_height) / 2.0));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner).id_salt(id));
|
||||
egui::TextEdit::singleline(text)
|
||||
.id(edit_id)
|
||||
.frame(egui::Frame::NONE)
|
||||
.margin(egui::Margin::symmetric(theme::GAP_S as i8, 0))
|
||||
.font(font.clone())
|
||||
.text_color(p.on_surface)
|
||||
.hint_text(RichText::new(hint).font(font).color(p.on_surface_variant))
|
||||
.desired_width(inner.width())
|
||||
.show(&mut child)
|
||||
.response
|
||||
.response
|
||||
}
|
||||
|
||||
/// Places matching what's typed in Weather place, from Open-Meteo, under the field while it's being edited.
|
||||
/// Picking one keeps its exact coordinates.
|
||||
fn place_suggestions(ui: &mut Ui, f: &mut Frame, ntp: &mut Ntp, field: &egui::Response) {
|
||||
let p = theme::palette(ui.ctx());
|
||||
let id = Id::new("ntp-place-suggest");
|
||||
let time = ui.input(|i| i.time);
|
||||
let query = ntp.city.trim().to_owned();
|
||||
// (typed at, list open)
|
||||
let (mut typed, mut open) = ui.data(|d| d.get_temp::<(f64, bool)>(id)).unwrap_or((0.0, false));
|
||||
if field.changed() {
|
||||
typed = time;
|
||||
open = true;
|
||||
}
|
||||
let list_rect = ui.data(|d| d.get_temp::<Rect>(id.with("rect")));
|
||||
let pointer_on_list = list_rect.is_some_and(|r| ui.rect_contains_pointer(r));
|
||||
if !field.has_focus() && !pointer_on_list {
|
||||
open = false;
|
||||
}
|
||||
if open && query.chars().count() >= 2 {
|
||||
let asked = ui.data(|d| d.get_temp::<String>(id.with("asked")));
|
||||
if time - typed < SUGGEST_AFTER {
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(SUGGEST_AFTER));
|
||||
} else if asked.as_deref() != Some(query.as_str()) {
|
||||
ui.data_mut(|d| d.insert_temp(id.with("asked"), query.clone()));
|
||||
f.send(Command::SuggestPlaces(query.clone()));
|
||||
}
|
||||
}
|
||||
let places = f.shared.places.borrow().clone();
|
||||
let mut picked = None;
|
||||
if open && places.0 == query && !places.1.is_empty() {
|
||||
let width = ui.available_width();
|
||||
let top = ui.cursor().top();
|
||||
let row = 44.0;
|
||||
let rect = Rect::from_min_size(pos2(ui.cursor().left(), top), vec2(width, row * places.1.len() as f32 + theme::GAP_S));
|
||||
ui.painter().rect_filled(rect, theme::corner_radius(theme::radius(ui.ctx(), theme::M)), p.surface_container_highest);
|
||||
ui.add_space(theme::GAP_XS);
|
||||
for (i, place) in places.1.iter().enumerate() {
|
||||
let (r, response) = ui.allocate_exact_size(vec2(width, row), Sense::click());
|
||||
let s = interaction(ui, &response);
|
||||
if s.amount() > 0.0 {
|
||||
ui.painter().rect_filled(r.shrink2(vec2(theme::GAP_XS, 0.0)), theme::corner_radius(theme::radius(ui.ctx(), theme::S)), p.on_surface.gamma_multiply(s.amount()));
|
||||
}
|
||||
icon(ui, pos2(r.left() + 20.0, r.center().y), icons::PLACE, 18.0, false, p.on_surface_variant);
|
||||
let text_width = width - 40.0 - theme::GAP_M;
|
||||
let name = one_line(ui, &place.name, theme::font(theme::BODY, Weight::Medium), p.on_surface, text_width);
|
||||
let region = one_line(ui, &place.region, theme::font(theme::SMALL, Weight::Regular), p.on_surface_variant, text_width);
|
||||
ui.painter().galley(pos2(r.left() + 40.0, r.center().y - name.size().y + 2.0), name, p.on_surface);
|
||||
ui.painter().galley(pos2(r.left() + 40.0, r.center().y + 2.0), region, p.on_surface_variant);
|
||||
if s.focus {
|
||||
focus_ring(ui, r.shrink(2.0), theme::radius(ui.ctx(), theme::S), &p);
|
||||
}
|
||||
if response.clicked() {
|
||||
picked = Some(i);
|
||||
}
|
||||
}
|
||||
ui.add_space(theme::GAP_XS);
|
||||
ui.data_mut(|d| d.insert_temp(id.with("rect"), rect));
|
||||
} else {
|
||||
ui.data_mut(|d| d.remove::<Rect>(id.with("rect")));
|
||||
}
|
||||
if let Some(i) = picked {
|
||||
let place = &places.1[i];
|
||||
ntp.city = place.label();
|
||||
ntp.city_loc = Some((place.lat, place.lon));
|
||||
open = false;
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(id, (typed, open)));
|
||||
}
|
||||
|
||||
/// A place from the geocoder.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Place {
|
||||
pub name: String,
|
||||
/// "Tennessee, United States"
|
||||
pub region: String,
|
||||
pub admin: String,
|
||||
pub lat: f64,
|
||||
pub lon: f64,
|
||||
}
|
||||
|
||||
impl Place {
|
||||
pub fn from_open_meteo(json: &serde_json::Value) -> Vec<Place> {
|
||||
let text = |r: &serde_json::Value, key: &str| r.get(key).and_then(|v| v.as_str()).unwrap_or_default().to_owned();
|
||||
json.get("results")
|
||||
.and_then(|r| r.as_array())
|
||||
.map(|results| {
|
||||
results
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let admin = text(r, "admin1");
|
||||
let region = [admin.clone(), text(r, "country")].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(", ");
|
||||
Place { name: text(r, "name"), region, admin, lat: r.get("latitude").and_then(|v| v.as_f64()).unwrap_or(0.0), lon: r.get("longitude").and_then(|v| v.as_f64()).unwrap_or(0.0) }
|
||||
})
|
||||
.filter(|p| !p.name.is_empty())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What the Weather place field and the weather card show: "Trenton, Tennessee".
|
||||
pub fn label(&self) -> String {
|
||||
if self.admin.is_empty() || self.admin == self.name { self.name.clone() } else { format!("{}, {}", self.name, self.admin) }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn places_from_open_meteo() {
|
||||
let json = serde_json::json!({ "results": [
|
||||
{ "name": "Trenton", "admin1": "Tennessee", "country": "United States", "latitude": 35.98, "longitude": -88.94 },
|
||||
{ "name": "Trenton", "admin1": "New Jersey", "country": "United States", "latitude": 40.22, "longitude": -74.76 },
|
||||
{ "name": "Monaco", "admin1": "Monaco", "country": "Monaco", "latitude": 43.7, "longitude": 7.4 },
|
||||
{ "latitude": 1.0 }
|
||||
]});
|
||||
let places = Place::from_open_meteo(&json);
|
||||
assert_eq!(places.len(), 3);
|
||||
assert_eq!((places[0].label(), places[0].region.as_str()), ("Trenton, Tennessee".to_owned(), "Tennessee, United States"));
|
||||
assert_eq!(places[2].label(), "Monaco");
|
||||
assert!(Place::from_open_meteo(&serde_json::json!({})).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_element_has_a_name() {
|
||||
for (key, _) in crate::store::settings::Ntp::default().elements {
|
||||
assert_ne!(element_name(&key).0, "Element", "{key}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,9 @@
|
|||
//! Nacre's own pages (nacre://...), drawn with egui inside the page area.
|
||||
|
||||
pub mod apps;
|
||||
pub mod backdrop;
|
||||
pub mod bookmarks;
|
||||
pub mod customize;
|
||||
pub mod devtools;
|
||||
pub mod downloads;
|
||||
pub mod gallery;
|
||||
|
|
@ -59,6 +61,8 @@ pub struct PageState {
|
|||
pub devtools_input: String,
|
||||
pub devtools_tab: usize,
|
||||
pub notes_dirty: bool,
|
||||
/// The new tab page's Customize panel is open.
|
||||
pub ntp_customize: bool,
|
||||
}
|
||||
|
||||
pub fn draw(ui: &mut Ui, f: &mut Frame, page: &Page) {
|
||||
|
|
|
|||
|
|
@ -79,10 +79,9 @@ pub fn fahrenheit(units: &str) -> bool {
|
|||
|
||||
pub fn draw(ui: &mut Ui, f: &mut Frame) {
|
||||
let ntp = f.shared.settings.borrow().ntp.clone();
|
||||
let palette = f.palette();
|
||||
background_image(ui, f, &ntp);
|
||||
let still = crate::perf::still(&f.shared.settings.borrow());
|
||||
background(ui, &ntp, &palette, still);
|
||||
let page = ui.max_rect();
|
||||
let panel = super::customize::rect(ui, f, page);
|
||||
super::backdrop::draw(ui, f, &ntp, page, panel);
|
||||
let elements: Vec<&str> = ntp.elements.iter().filter(|(_, on)| *on).map(|(k, _)| k.as_str()).collect();
|
||||
if elements.iter().any(|k| *k == "weather") {
|
||||
want_weather(ui, f, &ntp);
|
||||
|
|
@ -133,6 +132,10 @@ pub fn draw(ui: &mut Ui, f: &mut Frame) {
|
|||
}
|
||||
ui.add_space(theme::GAP_XL * 2.0);
|
||||
});
|
||||
super::customize::opener(ui, f, page);
|
||||
if let Some(panel) = panel {
|
||||
super::customize::panel(ui, f, page, panel);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the page is made of, top to bottom: single elements, and rows of cards.
|
||||
|
|
@ -220,21 +223,23 @@ fn clock_text(t: util::DateTime, h24: bool, seconds: bool) -> (String, &'static
|
|||
(text, suffix)
|
||||
}
|
||||
|
||||
/// Thin digits in the accent tint, each in a cell as wide as the widest digit so the time never shifts as it
|
||||
/// ticks; AM/PM sits on the same baseline. The date goes under it.
|
||||
/// Heavy digits in the accent tint, each in a cell as wide as the widest digit so the time never shifts as it
|
||||
/// ticks; the colons in a softer tint, and a small AM/PM at the digits' top. The date goes under it.
|
||||
fn clock(ui: &mut Ui, ntp: &crate::store::settings::Ntp, width: f32) {
|
||||
let p = theme::palette(ui.ctx());
|
||||
let now = util::now();
|
||||
let t = util::local_time(now);
|
||||
let (text, suffix) = clock_text(t, ntp.clock24, ntp.seconds);
|
||||
let size = if width >= 560.0 { theme::DISPLAY_LARGE } else { theme::DISPLAY };
|
||||
let font = theme::font(size, Weight::Thin);
|
||||
let font = theme::font(size, Weight::SemiBold);
|
||||
let colon = p.primary.gamma_multiply(0.45);
|
||||
let painter = ui.painter().clone();
|
||||
let digit = ('0'..='9').map(|c| painter.layout_no_wrap(c.to_string(), font.clone(), p.primary).size().x).fold(0.0, f32::max);
|
||||
let glyphs: Vec<_> = text.chars().map(|c| painter.layout_no_wrap(c.to_string(), font.clone(), p.primary)).collect();
|
||||
let glyphs: Vec<_> = text.chars().map(|c| painter.layout_no_wrap(c.to_string(), font.clone(), if c == ':' { colon } else { p.primary })).collect();
|
||||
let cells: Vec<f32> = text.chars().zip(&glyphs).map(|(c, g)| if c.is_ascii_digit() { digit } else { g.size().x }).collect();
|
||||
let suffix_galley = (!suffix.is_empty()).then(|| painter.layout_no_wrap(suffix.to_owned(), theme::font(theme::HEADLINE, Weight::Regular), p.primary));
|
||||
let suffix_width = suffix_galley.as_ref().map(|g| g.size().x + theme::GAP_S).unwrap_or(0.0);
|
||||
let small = theme::TITLE;
|
||||
let suffix_galley = (!suffix.is_empty()).then(|| painter.layout_no_wrap(suffix.to_owned(), theme::font(small, Weight::Medium), p.on_surface_variant));
|
||||
let suffix_width = suffix_galley.as_ref().map(|g| g.size().x + theme::GAP_XS).unwrap_or(0.0);
|
||||
let height = glyphs.first().map(|g| g.size().y).unwrap_or(size);
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(width, height), Sense::hover());
|
||||
let total: f32 = cells.iter().sum::<f32>() + suffix_width;
|
||||
|
|
@ -244,8 +249,10 @@ fn clock(ui: &mut Ui, ntp: &crate::store::settings::Ntp, width: f32) {
|
|||
x += cell;
|
||||
}
|
||||
if let (Some(g), Some(first)) = (suffix_galley, glyphs.first()) {
|
||||
let y = rect.top() + baseline(first) - baseline(&g);
|
||||
painter.galley(pos2(x + theme::GAP_S, y), g, p.primary);
|
||||
// Line the tops of the letters up with the tops of the digits (Outfit's cap height is 0.7 em).
|
||||
let digits_top = rect.top() + baseline(first) - 0.7 * size;
|
||||
let y = digits_top - (baseline(&g) - 0.7 * small);
|
||||
painter.galley(pos2(x + theme::GAP_XS, y), g, p.on_surface_variant);
|
||||
}
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.label(RichText::new(util::format_long_date(t)).font(theme::font(theme::BODY, Weight::Medium)).color(p.on_surface_variant));
|
||||
|
|
@ -638,7 +645,7 @@ fn weather_card(ui: &mut Ui, f: &mut Frame, ntp: &crate::store::settings::Ntp, r
|
|||
message(ui, "Add a place to see its weather here.");
|
||||
ui.add_space(theme::GAP_S);
|
||||
if button(ui, ButtonKind::Tonal, Some(icons::PLACE), "Set place").clicked() {
|
||||
f.send(Command::ShowPage(crate::tabs::Page::Settings("newtab".into())));
|
||||
f.ui.pages.ntp_customize = true;
|
||||
}
|
||||
},
|
||||
Some(Ok(w)) if w.place == ntp.city => {
|
||||
|
|
@ -665,7 +672,7 @@ fn weather_card(ui: &mut Ui, f: &mut Frame, ntp: &crate::store::settings::Ntp, r
|
|||
ui.label(one_line(ui, &format!("{} {}", icons::PLACE, w.place), small, p.on_surface_variant, inner.width()));
|
||||
},
|
||||
Some(Err(error)) => {
|
||||
let text = if error.contains("no place") { format!("No place called {place} was found. Check the name in settings.") } else { "Couldn't reach the weather service. Check your connection.".to_owned() };
|
||||
let text = if error.contains("no place") { format!("No place called {place} was found. Check the name in Customize.") } else { "Couldn't reach the weather service. Check your connection.".to_owned() };
|
||||
message(ui, &text);
|
||||
ui.add_space(theme::GAP_S);
|
||||
if button(ui, ButtonKind::Text, Some(icons::REFRESH), "Try again").clicked() {
|
||||
|
|
@ -796,144 +803,6 @@ fn top_sites_card(ui: &mut Ui, f: &mut Frame, rect: Rect) {
|
|||
});
|
||||
}
|
||||
|
||||
/// The background image, dimmed and softened by the settings.
|
||||
fn background_image(ui: &mut Ui, f: &mut Frame, ntp: &crate::store::settings::Ntp) {
|
||||
if ntp.bg_image.is_empty() {
|
||||
return;
|
||||
}
|
||||
let path = f.shared.paths.data.join(&ntp.bg_image);
|
||||
let key = format!("ntp-bg:{}:{:.0}", path.display(), ntp.bg_blur);
|
||||
let texture = match &f.ui.ntp_bg_texture {
|
||||
Some((k, t)) if *k == key => Some(t.clone()),
|
||||
_ => image::open(&path).ok().map(|img| {
|
||||
let img = img.thumbnail(1920, 1080);
|
||||
// Blur on a small copy: fast, and the linear filter smooths it when scaled up.
|
||||
let img = if ntp.bg_blur > 0.5 { img.thumbnail(640, 360).blur(ntp.bg_blur.min(40.0)) } else { img };
|
||||
let img = img.to_rgba8();
|
||||
let color = egui::ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], img.as_raw());
|
||||
let t = ui.ctx().load_texture(key.clone(), color, egui::TextureOptions::LINEAR);
|
||||
f.ui.ntp_bg_texture = Some((key.clone(), t.clone()));
|
||||
t
|
||||
}),
|
||||
};
|
||||
if let Some(texture) = texture {
|
||||
let rect = ui.max_rect();
|
||||
ui.painter().image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
ui.painter().rect_filled(rect, 0.0, Color32::from_black_alpha((ntp.bg_dim.clamp(0.0, 1.0) * 255.0) as u8));
|
||||
}
|
||||
}
|
||||
|
||||
/// The animated background behind the new tab page.
|
||||
fn background(ui: &mut Ui, ntp: &crate::store::settings::Ntp, palette: &crate::theme::Palette, still: bool) {
|
||||
use crate::store::settings::NtpBackground as B;
|
||||
if ntp.bg == B::Off {
|
||||
return;
|
||||
}
|
||||
let rect = ui.max_rect();
|
||||
let painter = ui.painter_at(rect);
|
||||
let time = if still { 0.0 } else { ui.input(|i| i.time) };
|
||||
let speed = match ntp.bg_speed.as_str() {
|
||||
"slow" => 0.5,
|
||||
"fast" => 1.8,
|
||||
_ => 1.0,
|
||||
};
|
||||
let count = match ntp.bg_density.as_str() {
|
||||
"low" => 12,
|
||||
"high" => 48,
|
||||
_ => 26,
|
||||
};
|
||||
let t = time * speed;
|
||||
let mouse = if ntp.bg_mouse { ui.input(|i| i.pointer.hover_pos()) } else { None };
|
||||
let accent = palette.accent;
|
||||
let soft = palette.accent_soft;
|
||||
// A stable pseudo-random number per element.
|
||||
let rnd = |i: usize, k: u32| -> f32 {
|
||||
let mut x = (i as u32).wrapping_mul(2_654_435_761) ^ k.wrapping_mul(40_503);
|
||||
x ^= x >> 13;
|
||||
x = x.wrapping_mul(0x5bd1_e995);
|
||||
x ^= x >> 15;
|
||||
(x % 10_000) as f32 / 10_000.0
|
||||
};
|
||||
let wrap = |v: f32, len: f32| v.rem_euclid(len);
|
||||
match ntp.bg {
|
||||
B::Shapes | B::Blobs | B::Particles => {
|
||||
for i in 0..count {
|
||||
let (sx, sy) = (rnd(i, 1), rnd(i, 2));
|
||||
let drift = (rnd(i, 3) - 0.5) * 30.0;
|
||||
let x = rect.left() + wrap(sx * rect.width() + (t as f32) * drift, rect.width());
|
||||
let y = rect.top() + wrap(sy * rect.height() + (t as f32) * (8.0 + rnd(i, 4) * 12.0), rect.height());
|
||||
let mut pos = egui::pos2(x, y);
|
||||
if let Some(m) = mouse {
|
||||
let d = pos - m;
|
||||
let dist = d.length();
|
||||
if dist < 120.0 && dist > 0.1 {
|
||||
pos += d / dist * (120.0 - dist) * 0.4;
|
||||
}
|
||||
}
|
||||
match ntp.bg {
|
||||
B::Blobs => {
|
||||
let r = 60.0 + rnd(i, 5) * 120.0;
|
||||
painter.circle_filled(pos, r, soft.gamma_multiply(0.18));
|
||||
},
|
||||
B::Particles => {
|
||||
painter.circle_filled(pos, 1.5 + rnd(i, 5) * 2.0, accent.gamma_multiply(0.5));
|
||||
},
|
||||
_ => {
|
||||
let size = 10.0 + rnd(i, 5) * 26.0;
|
||||
let color = if i % 2 == 0 { accent.gamma_multiply(0.22) } else { soft.gamma_multiply(0.35) };
|
||||
if i % 3 == 0 {
|
||||
painter.circle_stroke(pos, size / 2.0, egui::Stroke::new(2.0, color));
|
||||
} else {
|
||||
let angle = (t as f32) * 0.3 + rnd(i, 6) * 6.0;
|
||||
let corners: Vec<egui::Pos2> = (0..4).map(|k| pos + egui::Vec2::angled(angle + k as f32 * std::f32::consts::FRAC_PI_2) * size / 1.6).collect();
|
||||
painter.add(egui::Shape::convex_polygon(corners, color, egui::Stroke::NONE));
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
B::Waves => {
|
||||
for line in 0..5 {
|
||||
let base = rect.top() + rect.height() * (0.45 + line as f32 * 0.1);
|
||||
let points: Vec<egui::Pos2> = (0..=60)
|
||||
.map(|k| {
|
||||
let x = rect.left() + rect.width() * k as f32 / 60.0;
|
||||
let y = base + ((k as f32 * 0.25) + (t as f32) * (0.6 + line as f32 * 0.15)).sin() * (18.0 + line as f32 * 6.0);
|
||||
egui::pos2(x, y)
|
||||
})
|
||||
.collect();
|
||||
painter.add(egui::Shape::line(points, egui::Stroke::new(2.0, accent.gamma_multiply(0.15 + line as f32 * 0.05))));
|
||||
}
|
||||
},
|
||||
B::Dots => {
|
||||
let step = match ntp.bg_density.as_str() {
|
||||
"low" => 56.0,
|
||||
"high" => 28.0,
|
||||
_ => 40.0,
|
||||
};
|
||||
let mut y = rect.top() + step / 2.0;
|
||||
let mut row = 0;
|
||||
while y < rect.bottom() {
|
||||
let mut x = rect.left() + step / 2.0;
|
||||
let mut col = 0;
|
||||
while x < rect.right() {
|
||||
let pulse = (((row + col) as f32) * 0.4 + (t as f32) * 1.5).sin() * 0.5 + 0.5;
|
||||
let near = mouse.map(|m| (1.0 - (egui::pos2(x, y) - m).length() / 160.0).max(0.0)).unwrap_or(0.0);
|
||||
painter.circle_filled(egui::pos2(x, y), 1.5 + pulse * 1.5 + near * 3.0, accent.gamma_multiply(0.15 + near * 0.5));
|
||||
x += step;
|
||||
col += 1;
|
||||
}
|
||||
y += step;
|
||||
row += 1;
|
||||
}
|
||||
},
|
||||
B::Off => {},
|
||||
}
|
||||
if !still {
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_millis(33));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
|||
|
|
@ -176,9 +176,6 @@ fn general(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
|
|||
if row(ui, "Import from another browser", "Bookmarks, history and settings from Chrome, Firefox, Edge, Brave…", |ui| ui.button(icons::CHEVRON_RIGHT).clicked()) {
|
||||
open(f, "import");
|
||||
}
|
||||
if row(ui, "New tab page", &format!("{} shortcuts on the new tab page", s.ntp.shortcuts.len()), |ui| ui.button(icons::CHEVRON_RIGHT).clicked()) {
|
||||
open(f, "newtab");
|
||||
}
|
||||
switch_row(ui, "Custom title bar", "Frameless window with Nacre's own controls (restart to apply)", &mut s.ui.custom_title_bar);
|
||||
switch_row(ui, "Floating content card", "Rounded page with a margin around it", &mut s.ui.floating_card);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -64,6 +64,14 @@ pub struct BrowserWindow {
|
|||
pub shot_request: Option<std::path::PathBuf>,
|
||||
/// How long the last frames took to draw, in ms (self-test status).
|
||||
pub frame_times: std::collections::VecDeque<f32>,
|
||||
/// Frames drawn since the window opened (self-test status).
|
||||
pub frames_drawn: u64,
|
||||
/// When egui wants the next frame (it asked for a repaint after a delay); see `repaint_wanted`.
|
||||
pub redraw_at: Option<Instant>,
|
||||
/// The earliest time egui asked to repaint since this was last taken, from any thread.
|
||||
pub repaint_wanted: std::sync::Arc<std::sync::Mutex<Option<Instant>>>,
|
||||
/// Hidden (minimised or covered, as the compositor tells it): scheduled frames wait.
|
||||
pub occluded: bool,
|
||||
}
|
||||
|
||||
/// Choose the winit window attributes for a kind of window.
|
||||
|
|
@ -101,6 +109,14 @@ impl BrowserWindow {
|
|||
let _ = rendering.make_current();
|
||||
let egui = egui_glow::EguiGlow::new(event_loop, rendering.glow_gl_api(), None, Some(window.scale_factor() as f32), true);
|
||||
egui.egui_ctx.set_fonts(crate::ui::fonts());
|
||||
let repaint_wanted = std::sync::Arc::new(std::sync::Mutex::new(None::<Instant>));
|
||||
let wanted = repaint_wanted.clone();
|
||||
egui.egui_ctx.set_repaint_observer(move |info| {
|
||||
let at = Instant::now() + info.delay.min(std::time::Duration::from_secs(3600));
|
||||
if let Ok(mut slot) = wanted.lock() {
|
||||
*slot = Some(slot.map_or(at, |t| t.min(at)));
|
||||
}
|
||||
});
|
||||
let page_context = Rc::new(rendering.offscreen_context(size));
|
||||
let id = window.id();
|
||||
Ok(BrowserWindow {
|
||||
|
|
@ -128,6 +144,10 @@ impl BrowserWindow {
|
|||
focused: true,
|
||||
shot_request: None,
|
||||
frame_times: Default::default(),
|
||||
frames_drawn: 0,
|
||||
redraw_at: None,
|
||||
repaint_wanted,
|
||||
occluded: false,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
133
tests/smoke/backgrounds.txt
Normal file
133
tests/smoke/backgrounds.txt
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
# New tab backgrounds and the Customize panel (S018), offline. Each background with the pointer on the page (dark),
|
||||
# a frame-time status at Lots/Fast per background, the panel open (dark and light, scrolled), and the image and
|
||||
# GIF layers with Dim and Blur. Run: SMOKE_SIZE=1400x900 tools/smoke.sh tests/smoke/backgrounds.txt; read the PNGs.
|
||||
# Frame times: <name>.json "frames" (median_ms/max_ms = draw time, drawn = frames so far; two statuses 4 s apart
|
||||
# give the frame rate).
|
||||
wait 3
|
||||
resize 1400 900
|
||||
set /theme/mode "dark"
|
||||
set /ntp/name "Sam"
|
||||
page nacre://newtab
|
||||
wait 1
|
||||
set /ntp/bg_density "medium"
|
||||
set /ntp/bg_speed "normal"
|
||||
set /ntp/bg "off"
|
||||
pointer 300 400
|
||||
wait 1
|
||||
shot bg-none
|
||||
status bg-none-a
|
||||
wait 4
|
||||
status bg-none-b
|
||||
set /ntp/bg "shapes"
|
||||
wait 2
|
||||
shot bg-shapes
|
||||
set /ntp/bg "blobs"
|
||||
pointer 900 300
|
||||
wait 2
|
||||
shot bg-blobs
|
||||
set /ntp/bg "particles"
|
||||
pointer 250 350
|
||||
wait 2
|
||||
shot bg-constellation
|
||||
set /ntp/bg "waves"
|
||||
pointer 640 260
|
||||
wait 2
|
||||
shot bg-waves
|
||||
set /ntp/bg "dots"
|
||||
pointer 220 420
|
||||
wait 2
|
||||
shot bg-dots
|
||||
pointer off
|
||||
wait 2
|
||||
shot bg-dots-nopointer
|
||||
# Frame time at Lots and Fast, pointer on the page.
|
||||
set /ntp/bg_density "high"
|
||||
set /ntp/bg_speed "fast"
|
||||
pointer 500 400
|
||||
set /ntp/bg "shapes"
|
||||
wait 2
|
||||
status perf-shapes-a
|
||||
wait 4
|
||||
status perf-shapes-b
|
||||
shot bg-shapes-lots
|
||||
set /ntp/bg "blobs"
|
||||
wait 2
|
||||
status perf-blobs-a
|
||||
wait 4
|
||||
status perf-blobs-b
|
||||
set /ntp/bg "particles"
|
||||
wait 2
|
||||
status perf-constellation-a
|
||||
wait 4
|
||||
status perf-constellation-b
|
||||
shot bg-constellation-lots
|
||||
set /ntp/bg "waves"
|
||||
wait 2
|
||||
status perf-waves-a
|
||||
wait 4
|
||||
status perf-waves-b
|
||||
set /ntp/bg "dots"
|
||||
wait 2
|
||||
status perf-dots-a
|
||||
wait 4
|
||||
status perf-dots-b
|
||||
shot bg-dots-lots
|
||||
# Idle: a background tab, then the new tab with a still background.
|
||||
newtab @PAGES@/hello.html
|
||||
waitload 30
|
||||
wait 2
|
||||
status hidden-a
|
||||
wait 4
|
||||
status hidden-b
|
||||
cmd close_tab
|
||||
page nacre://newtab
|
||||
set /perf/still_ntp true
|
||||
wait 2
|
||||
status still-a
|
||||
wait 4
|
||||
status still-b
|
||||
set /perf/still_ntp false
|
||||
set /ui/motion "off"
|
||||
wait 2
|
||||
status motionoff-a
|
||||
wait 4
|
||||
status motionoff-b
|
||||
set /ui/motion "normal"
|
||||
# The panel.
|
||||
set /ntp/bg_density "medium"
|
||||
set /ntp/bg_speed "normal"
|
||||
set /ntp/bg "blobs"
|
||||
customize
|
||||
wait 2
|
||||
shot panel-dark
|
||||
set /theme/mode "light"
|
||||
wait 1
|
||||
shot panel-light
|
||||
set /theme/mode "dark"
|
||||
# Image, then GIF, under the animated layer.
|
||||
set /ntp/bg_image "@PAGESDIR@/backdrop.jpg"
|
||||
set /ntp/bg_dim 0.3
|
||||
wait 2
|
||||
shot image-dark
|
||||
set /ntp/bg_blur 16
|
||||
wait 1
|
||||
shot image-blur
|
||||
customize close
|
||||
set /ntp/bg "off"
|
||||
set /ntp/bg_blur 0
|
||||
set /ntp/bg_image "@PAGESDIR@/backdrop.gif"
|
||||
wait 2
|
||||
shot gif-a
|
||||
wait 0.25
|
||||
shot gif-b
|
||||
set /ntp/bg "dots"
|
||||
pointer 600 450
|
||||
wait 1
|
||||
shot gif-dots
|
||||
set /theme/mode "light"
|
||||
set /ntp/bg_image ""
|
||||
set /ntp/bg "shapes"
|
||||
wait 1
|
||||
shot bg-shapes-light
|
||||
status done
|
||||
quit
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue