Nacre on Servo: first complete, reviewed, not yet built version
Everything in Rust on Servo 0.7 (trimmed: no WebXR, WebGPU, multiprocess): tabs and windows, address bar with suggestions, history, bookmarks and reading list, downloads with resume and external download managers, encrypted password vault with autofill, ad blocker (adblock-rust, 22 lists), VPN through Tor or a proxy and secure DNS via a local bridge proxy, picture in picture, Discord Rich Presence, media player and visualizer, spell check, site apps, user scripts and styles, import from other browsers, gamepads, Web Bluetooth, and every setting of the original Nacre in a plain egui interface. Not compiled yet; docs/HANDOFF.md has the first build checklist. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
e8167c3f4a
15 changed files with 265927 additions and 0 deletions
677
src/ui/chrome.rs
Normal file
677
src/ui/chrome.rs
Normal file
|
|
@ -0,0 +1,677 @@
|
|||
//! The browser chrome: title bar, tab strip, toolbar with the address bar, bookmarks bar,
|
||||
//! the slim bar of app windows, and the picture-in-picture window.
|
||||
|
||||
use egui::{Align, Color32, Key, Layout, RichText, Sense, Ui, Vec2};
|
||||
|
||||
use super::widgets::{glyph, icon_button, icon_toggle};
|
||||
use super::{Flyout, Frame};
|
||||
use crate::actions::{Command, Disposition};
|
||||
use crate::net::VpnStatus;
|
||||
use crate::store::settings::{BookmarksBar, MediaButton};
|
||||
use crate::tabs::Page;
|
||||
use crate::util;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum SuggestionKind {
|
||||
Search,
|
||||
SearchSuggestion,
|
||||
Url,
|
||||
History,
|
||||
Bookmark,
|
||||
Tab(u64),
|
||||
Page,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Suggestion {
|
||||
pub kind: SuggestionKind,
|
||||
pub title: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
/// Our own title bar when the system's is turned off.
|
||||
pub fn title_bar(root: &mut Ui, f: &mut Frame) {
|
||||
egui::Panel::top("title-bar").exact_size(30.0).show_separator_line(false).show(root, |ui| {
|
||||
let response = ui.interact(ui.max_rect(), ui.id().with("drag"), Sense::click_and_drag());
|
||||
if response.drag_started() {
|
||||
f.send(Command::WindowDrag);
|
||||
}
|
||||
if response.double_clicked() {
|
||||
f.send(Command::WindowMaximize);
|
||||
}
|
||||
ui.horizontal_centered(|ui| {
|
||||
ui.add_space(8.0);
|
||||
ui.label(RichText::new(if f.incognito() { "Nacre — incognito" } else { "Nacre" }).weak());
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
// Same size for all three, flush right.
|
||||
let size = Vec2::new(40.0, 26.0);
|
||||
if ui.add_sized(size, egui::Button::new("✕").frame(false)).on_hover_text("Close").clicked() {
|
||||
f.send(Command::WindowClose);
|
||||
}
|
||||
if ui.add_sized(size, egui::Button::new("🗖").frame(false)).on_hover_text("Maximize").clicked() {
|
||||
f.send(Command::WindowMaximize);
|
||||
}
|
||||
if ui.add_sized(size, egui::Button::new("🗕").frame(false)).on_hover_text("Minimize").clicked() {
|
||||
f.send(Command::WindowMinimize);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub fn tab_strip(root: &mut Ui, f: &mut Frame) {
|
||||
egui::Panel::top("tabs").exact_size(34.0).show_separator_line(false).show(root, |ui| {
|
||||
ui.horizontal_centered(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
let pinned = f.tabs.iter().filter(|t| t.pinned).count();
|
||||
let unpinned = f.tabs.len() - pinned;
|
||||
let avail = ui.available_width() - 40.0;
|
||||
let width = if unpinned == 0 { 0.0 } else { ((avail - pinned as f32 * 38.0) / unpinned as f32).clamp(60.0, 220.0) };
|
||||
egui::ScrollArea::horizontal().id_salt("tab-scroll").max_width(avail).auto_shrink([false, true]).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let mut drop_at: Option<(usize, usize)> = None;
|
||||
for index in 0..f.tabs.len() {
|
||||
let w = if f.tabs[index].pinned { 36.0 } else { width };
|
||||
if let Some(target) = tab_button(ui, f, index, w) {
|
||||
drop_at = Some((index, target));
|
||||
}
|
||||
}
|
||||
if let Some((from, to)) = drop_at
|
||||
&& from != to
|
||||
{
|
||||
f.send(Command::MoveTab { from, to });
|
||||
}
|
||||
});
|
||||
});
|
||||
if icon_button(ui, "➕", "New tab (Ctrl+T)").clicked() {
|
||||
f.send(Command::NewTab);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// One tab. Returns the index it was dropped at when a drag ends.
|
||||
fn tab_button(ui: &mut Ui, f: &mut Frame, index: usize, width: f32) -> Option<usize> {
|
||||
let palette = f.palette();
|
||||
let active = index == *f.active;
|
||||
let (rect, response) = ui.allocate_exact_size(Vec2::new(width, 28.0), Sense::click_and_drag());
|
||||
let tab = &f.tabs[index];
|
||||
let tab_id = tab.id;
|
||||
let fill = if active {
|
||||
palette.surface_low
|
||||
} else if response.hovered() {
|
||||
palette.surface_high
|
||||
} else {
|
||||
Color32::TRANSPARENT
|
||||
};
|
||||
ui.painter().rect_filled(rect, 6.0, fill);
|
||||
if active {
|
||||
ui.painter().line_segment([rect.left_bottom() + egui::vec2(6.0, 0.0), rect.right_bottom() - egui::vec2(6.0, 0.0)], egui::Stroke::new(2.0, palette.accent));
|
||||
}
|
||||
let mut x = rect.left() + 8.0;
|
||||
let center_y = rect.center().y;
|
||||
// Icon: spinner while loading, favicon, or a dot.
|
||||
let icon_rect = egui::Rect::from_center_size(egui::pos2(x + 8.0, center_y), Vec2::splat(16.0));
|
||||
if tab.loading() {
|
||||
ui.put(icon_rect, egui::Spinner::new().size(14.0));
|
||||
} else if let Some(texture) = &tab.favicon {
|
||||
ui.painter().image(texture.id(), icon_rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
|
||||
} else {
|
||||
let g = if tab.page.is_some() { "◆" } else { "●" };
|
||||
ui.painter().text(icon_rect.center(), egui::Align2::CENTER_CENTER, g, egui::FontId::proportional(11.0), palette.text_weak);
|
||||
}
|
||||
x += 22.0;
|
||||
let mut close_clicked = false;
|
||||
let mut mute_clicked = false;
|
||||
if !tab.pinned {
|
||||
let right = rect.right() - 6.0;
|
||||
let close_rect = egui::Rect::from_center_size(egui::pos2(right - 9.0, center_y), Vec2::splat(18.0));
|
||||
let close = ui.interact(close_rect, ui.id().with(("close", tab_id)), Sense::click());
|
||||
if close.hovered() {
|
||||
ui.painter().rect_filled(close_rect, 4.0, palette.outline);
|
||||
}
|
||||
ui.painter().text(close_rect.center(), egui::Align2::CENTER_CENTER, "✕", egui::FontId::proportional(11.0), palette.text);
|
||||
close_clicked = close.clicked();
|
||||
let mut title_right = close_rect.left() - 4.0;
|
||||
if tab.audible() || tab.muted {
|
||||
let mute_rect = egui::Rect::from_center_size(egui::pos2(title_right - 9.0, center_y), Vec2::splat(18.0));
|
||||
let mute = ui.interact(mute_rect, ui.id().with(("mute", tab_id)), Sense::click()).on_hover_text(if tab.muted { "Unmute tab" } else { "Mute tab" });
|
||||
ui.painter().text(mute_rect.center(), egui::Align2::CENTER_CENTER, if tab.muted { "🔇" } else { "🔊" }, egui::FontId::proportional(12.0), palette.text);
|
||||
mute_clicked = mute.clicked();
|
||||
title_right = mute_rect.left() - 2.0;
|
||||
}
|
||||
let title = tab.display_title();
|
||||
let max = ((title_right - x) / 6.5).max(1.0) as usize;
|
||||
let text = util::ellipsize(&title, max);
|
||||
let color = if active { palette.text } else { palette.text_weak };
|
||||
ui.painter().with_clip_rect(egui::Rect::from_min_max(egui::pos2(x, rect.top()), egui::pos2(title_right, rect.bottom()))).text(egui::pos2(x, center_y), egui::Align2::LEFT_CENTER, text, egui::FontId::proportional(13.0), color);
|
||||
}
|
||||
let title = tab.display_title();
|
||||
let response = response.on_hover_text(format!("{title}\n{}", tab.shown_url()));
|
||||
if close_clicked || response.middle_clicked() {
|
||||
f.send(Command::CloseTab(tab_id));
|
||||
return None;
|
||||
}
|
||||
if mute_clicked {
|
||||
f.send(Command::MuteTab(tab_id));
|
||||
return None;
|
||||
}
|
||||
if response.clicked() && !active {
|
||||
f.send(Command::SelectTab(index));
|
||||
}
|
||||
if response.secondary_clicked() {
|
||||
let pos = response.interact_pointer_pos().unwrap_or(rect.left_bottom());
|
||||
f.ui.flyout = Some(Flyout::TabMenu(tab_id, pos));
|
||||
}
|
||||
if response.drag_started() {
|
||||
f.ui.dragging_tab = Some((tab_id, 0.0));
|
||||
}
|
||||
if response.drag_stopped() && f.ui.dragging_tab.is_some_and(|(id, _)| id == tab_id) {
|
||||
f.ui.dragging_tab = None;
|
||||
if let Some(pos) = response.interact_pointer_pos() {
|
||||
// Index under the pointer, counting from this tab's own slot.
|
||||
let shift = ((pos.x - rect.center().x) / width).round() as isize;
|
||||
let target = (index as isize + shift).clamp(0, f.tabs.len() as isize - 1) as usize;
|
||||
return Some(target);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn toolbar(root: &mut Ui, f: &mut Frame) {
|
||||
egui::Panel::top("toolbar").exact_size(40.0).show(root, |ui| {
|
||||
ui.horizontal_centered(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
let settings = f.shared.settings.borrow().clone();
|
||||
let (can_back, can_forward, loading) = f.tab().map(|t| (t.can_go_back(), t.can_go_forward(), t.loading())).unwrap_or_default();
|
||||
if settings.toolbar_has("back") {
|
||||
let r = ui.add_enabled(can_back, egui::Button::new(RichText::new(glyph("back")).size(15.0)).min_size(Vec2::splat(28.0)).frame(false)).on_hover_text("Back (Alt+Left) · right-click for history");
|
||||
if r.clicked() {
|
||||
f.send(Command::Back);
|
||||
}
|
||||
if r.secondary_clicked() {
|
||||
f.ui.flyout = Some(Flyout::BackHistory(r.rect.left_bottom()));
|
||||
}
|
||||
}
|
||||
if settings.toolbar_has("forward") && ui.add_enabled(can_forward, egui::Button::new(RichText::new(glyph("forward")).size(15.0)).min_size(Vec2::splat(28.0)).frame(false)).on_hover_text("Forward (Alt+Right)").clicked() {
|
||||
f.send(Command::Forward);
|
||||
}
|
||||
if settings.toolbar_has("reload") {
|
||||
if loading {
|
||||
if icon_button(ui, "✕", "Stop").clicked() {
|
||||
f.send(Command::Stop);
|
||||
}
|
||||
} else if icon_button(ui, glyph("reload"), "Reload (Ctrl+R) · Shift-click: without cache").clicked() {
|
||||
let hard = ui.input(|i| i.modifiers.shift);
|
||||
f.send(Command::Reload { hard });
|
||||
}
|
||||
}
|
||||
if settings.toolbar_has("home") && icon_button(ui, glyph("home"), "Home page").clicked() {
|
||||
f.send(Command::Home);
|
||||
}
|
||||
// Buttons on the right first, so the address bar can take what's left.
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
let menu = icon_button(ui, "☰", "Menu");
|
||||
if menu.clicked() {
|
||||
f.ui.toggle(Flyout::Main, Some(menu.rect));
|
||||
}
|
||||
right_buttons(ui, f, &settings);
|
||||
ui.with_layout(Layout::left_to_right(Align::Center), |ui| omnibox(ui, f));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn right_buttons(ui: &mut Ui, f: &mut Frame, settings: &crate::store::settings::Settings) {
|
||||
let palette = f.palette();
|
||||
if f.shared.profile_count() > 1 || f.incognito() {
|
||||
let label = if f.incognito() { "🕶".to_owned() } else { f.shared.paths.profile.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default() };
|
||||
let r = ui.add(egui::Button::new(label).min_size(Vec2::splat(28.0))).on_hover_text(format!("Profile: {}", f.shared.paths.profile));
|
||||
if r.clicked() {
|
||||
f.ui.toggle(Flyout::Profiles, Some(r.rect));
|
||||
}
|
||||
}
|
||||
if settings.toolbar_has("vpn") {
|
||||
let status = f.shared.vpn_status.borrow().clone();
|
||||
let (text, tip) = match &status {
|
||||
VpnStatus::Off => (RichText::new(glyph("vpn")), "VPN: off".to_owned()),
|
||||
VpnStatus::Connecting(why) => (RichText::new(glyph("vpn")).color(palette.warning), format!("VPN: {why}")),
|
||||
VpnStatus::On(how) => (RichText::new(glyph("vpn")).color(palette.success), format!("VPN on: {how}")),
|
||||
VpnStatus::Failed(why) => (RichText::new(glyph("vpn")).color(palette.error), format!("VPN: {why}")),
|
||||
};
|
||||
let r = ui.add(egui::Button::new(text.size(15.0)).min_size(Vec2::splat(28.0)).frame(false)).on_hover_text(tip);
|
||||
if r.clicked() {
|
||||
f.ui.toggle(Flyout::Vpn, Some(r.rect));
|
||||
}
|
||||
}
|
||||
if settings.toolbar_has("media") {
|
||||
let playing = f.tabs.iter().any(|t| t.audible()) || f.shared.media_anywhere();
|
||||
let show = match settings.media.button {
|
||||
MediaButton::Always => true,
|
||||
MediaButton::Never => false,
|
||||
MediaButton::Auto => playing || f.ui.flyout == Some(Flyout::Media),
|
||||
};
|
||||
if show {
|
||||
let r = icon_toggle(ui, glyph("media"), "Media playing", f.ui.flyout == Some(Flyout::Media));
|
||||
if r.clicked() {
|
||||
f.ui.toggle(Flyout::Media, Some(r.rect));
|
||||
}
|
||||
}
|
||||
}
|
||||
if settings.toolbar_has("adblock") {
|
||||
let blocked = f.tab().map(|t| t.blocked).unwrap_or(0);
|
||||
let paused = f.tab().is_some_and(|t| settings.adblock_paused_on(&t.host()));
|
||||
let label = if !settings.adblock.enabled || paused { RichText::new("🛡").weak() } else if blocked > 0 { RichText::new(format!("🛡{blocked}")) } else { RichText::new("🛡") };
|
||||
let r = ui.add(egui::Button::new(label.size(14.0)).min_size(Vec2::splat(28.0)).frame(false)).on_hover_text(format!("Ad blocker · {blocked} blocked on this page"));
|
||||
if r.clicked() {
|
||||
f.ui.toggle(Flyout::Shield, Some(r.rect));
|
||||
}
|
||||
}
|
||||
if settings.toolbar_has("downloads") {
|
||||
let downloads = f.shared.downloads.borrow();
|
||||
let running = downloads.active_count();
|
||||
let progress = downloads.overall_progress();
|
||||
drop(downloads);
|
||||
let label = match (running, progress) {
|
||||
(0, _) => RichText::new(glyph("downloads")),
|
||||
(_, Some(p)) => RichText::new(format!("⬇{:.0}%", p * 100.0)).color(palette.accent),
|
||||
(n, None) => RichText::new(format!("⬇{n}")).color(palette.accent),
|
||||
};
|
||||
let r = ui.add(egui::Button::new(label.size(14.0)).min_size(Vec2::splat(28.0)).frame(false)).on_hover_text("Downloads (Ctrl+J)");
|
||||
if r.clicked() {
|
||||
f.ui.toggle(Flyout::Downloads, Some(r.rect));
|
||||
}
|
||||
}
|
||||
for (key, tip, command) in [
|
||||
("devtools", "Developer tools (F12)", Command::Action(crate::keys::Action::DevTools)),
|
||||
("qr", "QR code for this page", Command::QrCode),
|
||||
("history", "History (Ctrl+H)", Command::ShowPage(Page::History)),
|
||||
("passwords", "Passwords", Command::ShowPage(Page::Passwords)),
|
||||
("bookmarks", "Bookmarks", Command::ShowPage(Page::Bookmarks)),
|
||||
("apps", "Apps", Command::ShowPage(Page::Apps)),
|
||||
("pip", "Picture in picture", Command::EnterPip),
|
||||
("screenshot", "Save as PDF or image", Command::PrintPage),
|
||||
("incognito", "New incognito window (Ctrl+Shift+N)", Command::NewIncognito),
|
||||
] {
|
||||
if settings.toolbar_has(key) && icon_button(ui, glyph(key), tip).clicked() {
|
||||
f.send(command);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::app::Shared {
|
||||
pub fn profile_count(&self) -> usize {
|
||||
self.paths.profile_list().profiles.len()
|
||||
}
|
||||
|
||||
/// Whether any tab in any window is playing media (the media button shows in every window).
|
||||
pub fn media_anywhere(&self) -> bool {
|
||||
self.media_now.borrow().as_ref().is_some_and(|m| !m.state.paused)
|
||||
}
|
||||
}
|
||||
|
||||
fn omnibox(ui: &mut Ui, f: &mut Frame) {
|
||||
let palette = f.palette();
|
||||
let Some(tab) = f.tab() else { return };
|
||||
let shown = tab.shown_url();
|
||||
let is_web = tab.page.is_none();
|
||||
let secure = shown.starts_with("https://");
|
||||
let zoom = tab.zoom;
|
||||
let host = tab.host();
|
||||
let bookmarked = is_web && f.shared.bookmarks.borrow().is_bookmarked(&tab.url);
|
||||
let installable = is_web && shown.starts_with("http") && f.shared.apps.borrow().for_url(&url::Url::parse(&shown).unwrap_or_else(|_| url::Url::parse("about:blank").expect("valid"))).is_none();
|
||||
// Site info button.
|
||||
let lock = if !is_web { "◆" } else if secure { "🔒" } else if shown.starts_with("http://") { "⚠" } else { "ℹ" };
|
||||
let r = ui.add(egui::Button::new(lock).frame(false).min_size(Vec2::splat(26.0))).on_hover_text(if secure { "Connection is secure" } else if is_web { "Connection is not secure" } else { "Nacre page" });
|
||||
if r.clicked() && is_web {
|
||||
f.ui.toggle(Flyout::SiteInfo, Some(r.rect));
|
||||
}
|
||||
let right_space = 26.0 * (1.0 + (zoom != 1.0) as u8 as f32 + installable as u8 as f32) + 8.0;
|
||||
let width = (ui.available_width() - right_space).max(120.0);
|
||||
let mut text = f.ui.omnibox_edit.clone().unwrap_or_else(|| if shown == "nacre://newtab" { String::new() } else { shown.clone() });
|
||||
let id = ui.id().with("omnibox");
|
||||
let engine = f.shared.settings.borrow().search_engine_name();
|
||||
let output = egui::TextEdit::singleline(&mut text).id(id).hint_text(format!("Search with {engine} or type an address")).desired_width(width).show(ui);
|
||||
let response = output.response;
|
||||
if f.ui.focus_omnibox {
|
||||
f.ui.focus_omnibox = false;
|
||||
response.request_focus();
|
||||
// Select everything so typing replaces the address.
|
||||
let mut state = output.state;
|
||||
state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(text.chars().count()))));
|
||||
state.store(ui.ctx(), id);
|
||||
}
|
||||
let focused = response.has_focus();
|
||||
if response.gained_focus() && f.ui.omnibox_edit.is_none() {
|
||||
let mut state = egui::TextEdit::load_state(ui.ctx(), id).unwrap_or_default();
|
||||
state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(text.chars().count()))));
|
||||
state.store(ui.ctx(), id);
|
||||
}
|
||||
f.ui.omnibox_focused = focused;
|
||||
if response.changed() {
|
||||
f.ui.omnibox_edit = Some(text.clone());
|
||||
f.ui.suggestion_index = None;
|
||||
if let Some(tab) = f.tab_mut() {
|
||||
tab.draft = Some(text.clone());
|
||||
}
|
||||
f.send(Command::Suggest(text.clone()));
|
||||
}
|
||||
let editing = f.ui.omnibox_edit.clone();
|
||||
if focused && let Some(query) = editing.as_ref().filter(|q| !q.trim().is_empty()) {
|
||||
if f.ui.omnibox_query != *query || f.shared.suggestions.borrow().0 == *query && f.ui.omnibox_items.iter().all(|s| s.kind != SuggestionKind::SearchSuggestion) {
|
||||
f.ui.omnibox_items = suggestions(f, query);
|
||||
f.ui.omnibox_query = query.clone();
|
||||
}
|
||||
let count = f.ui.omnibox_items.len();
|
||||
if ui.input(|i| i.key_pressed(Key::ArrowDown)) && count > 0 {
|
||||
f.ui.suggestion_index = Some(f.ui.suggestion_index.map(|i| (i + 1).min(count - 1)).unwrap_or(0));
|
||||
}
|
||||
if ui.input(|i| i.key_pressed(Key::ArrowUp)) {
|
||||
f.ui.suggestion_index = f.ui.suggestion_index.and_then(|i| i.checked_sub(1));
|
||||
}
|
||||
suggestion_popup(ui, f, response.rect);
|
||||
}
|
||||
if response.lost_focus() {
|
||||
if ui.input(|i| i.key_pressed(Key::Enter)) {
|
||||
let chosen = f.ui.suggestion_index.and_then(|i| f.ui.omnibox_items.get(i).cloned());
|
||||
let alt = ui.input(|i| i.modifiers.alt);
|
||||
match chosen {
|
||||
Some(s) => run_suggestion(f, s, alt),
|
||||
None => {
|
||||
let typed = editing.unwrap_or(text);
|
||||
if alt {
|
||||
let template = f.shared.settings.borrow().search_template();
|
||||
if let Some(url) = util::address_to_url(&typed, &template) {
|
||||
f.send(Command::Open { url: url.to_string(), how: Disposition::NewForegroundTab, from: None });
|
||||
}
|
||||
} else {
|
||||
f.send(Command::Navigate(typed));
|
||||
}
|
||||
},
|
||||
}
|
||||
f.ui.omnibox_edit = None;
|
||||
if let Some(tab) = f.tab_mut() {
|
||||
tab.draft = None;
|
||||
}
|
||||
} else if ui.input(|i| i.key_pressed(Key::Escape)) {
|
||||
f.ui.omnibox_edit = None;
|
||||
if let Some(tab) = f.tab_mut() {
|
||||
tab.draft = None;
|
||||
}
|
||||
f.send(Command::FocusPage);
|
||||
}
|
||||
f.ui.suggestion_index = None;
|
||||
}
|
||||
if (zoom - 1.0).abs() > 0.001 && ui.add(egui::Button::new(format!("{:.0}%", zoom * 100.0)).frame(false)).on_hover_text("Zoom · click to reset").clicked() {
|
||||
f.send(Command::Zoom(0));
|
||||
}
|
||||
if installable && icon_button(ui, "⊕", "Install this site as an app").clicked() {
|
||||
f.send(Command::InstallApp);
|
||||
}
|
||||
if is_web {
|
||||
let star = ui.add(egui::Button::new(RichText::new(if bookmarked { "★" } else { "☆" }).color(if bookmarked { palette.accent } else { palette.text })).frame(false).min_size(Vec2::splat(26.0))).on_hover_text("Bookmark this page (Ctrl+D)");
|
||||
if star.clicked() {
|
||||
if bookmarked {
|
||||
f.ui.toggle(Flyout::EditBookmark(f.tabs[*f.active].url.clone()), Some(star.rect));
|
||||
} else {
|
||||
f.send(Command::ToggleBookmark);
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = host;
|
||||
}
|
||||
|
||||
/// Everything the address bar offers for what was typed.
|
||||
fn suggestions(f: &Frame, query: &str) -> Vec<Suggestion> {
|
||||
let mut out = Vec::new();
|
||||
let settings = f.shared.settings.borrow();
|
||||
let template = settings.search_template();
|
||||
let engine = settings.search_engine_name();
|
||||
drop(settings);
|
||||
let target = util::address_to_url(query, &template);
|
||||
let is_search = target.as_ref().is_none_or(|u| template.contains(u.host_str().unwrap_or("-")) && u.as_str().contains(&util::encode_query(query.trim())));
|
||||
if is_search {
|
||||
out.push(Suggestion { kind: SuggestionKind::Search, title: format!("{query} — search with {engine}"), url: template.replace("%s", &util::encode_query(query.trim())) });
|
||||
} else if let Some(url) = &target {
|
||||
out.push(Suggestion { kind: SuggestionKind::Url, title: url.to_string(), url: url.to_string() });
|
||||
}
|
||||
// Nacre's own pages by name.
|
||||
let lower = query.to_lowercase();
|
||||
for (name, page) in [("settings", Page::Settings(String::new())), ("history", Page::History), ("bookmarks", Page::Bookmarks), ("downloads", Page::Downloads), ("passwords", Page::Passwords), ("apps", Page::Apps)] {
|
||||
if lower.len() >= 3 && name.starts_with(&lower) {
|
||||
out.push(Suggestion { kind: SuggestionKind::Page, title: page.title(), url: page.url() });
|
||||
}
|
||||
}
|
||||
// Open tabs.
|
||||
for tab in f.tabs.iter().filter(|t| t.page.is_none() && t.id != f.tabs.get(*f.active).map(|a| a.id).unwrap_or(0)) {
|
||||
if tab.title.to_lowercase().contains(&lower) || tab.url.to_lowercase().contains(&lower) {
|
||||
out.push(Suggestion { kind: SuggestionKind::Tab(tab.id), title: format!("Switch to tab: {}", tab.display_title()), url: tab.url.clone() });
|
||||
if out.len() > 3 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (url, title) in f.shared.bookmarks.borrow().search(query, 3) {
|
||||
out.push(Suggestion { kind: SuggestionKind::Bookmark, title, url });
|
||||
}
|
||||
for (url, title) in f.shared.history.borrow().suggest(query, 6) {
|
||||
if !out.iter().any(|s| s.url == url) {
|
||||
out.push(Suggestion { kind: SuggestionKind::History, title, url });
|
||||
}
|
||||
}
|
||||
let (q, list) = f.shared.suggestions.borrow().clone();
|
||||
if q == query {
|
||||
for s in list.into_iter().filter(|s| s != query).take(4) {
|
||||
out.push(Suggestion { kind: SuggestionKind::SearchSuggestion, url: template.replace("%s", &util::encode_query(&s)), title: s });
|
||||
}
|
||||
}
|
||||
out.truncate(12);
|
||||
out
|
||||
}
|
||||
|
||||
fn run_suggestion(f: &mut Frame, s: Suggestion, new_tab: bool) {
|
||||
match s.kind {
|
||||
SuggestionKind::Tab(id) => {
|
||||
if let Some(i) = f.tabs.iter().position(|t| t.id == id) {
|
||||
f.send(Command::SelectTab(i));
|
||||
}
|
||||
},
|
||||
_ => f.send(Command::Open { url: s.url, how: if new_tab { Disposition::NewForegroundTab } else { Disposition::Current }, from: None }),
|
||||
}
|
||||
}
|
||||
|
||||
fn suggestion_popup(ui: &mut Ui, f: &mut Frame, below: egui::Rect) {
|
||||
if f.ui.omnibox_items.is_empty() {
|
||||
return;
|
||||
}
|
||||
let palette = f.palette();
|
||||
let items = f.ui.omnibox_items.clone();
|
||||
let selected = f.ui.suggestion_index;
|
||||
let mut clicked = None;
|
||||
egui::Area::new(egui::Id::new("omnibox-suggestions")).fixed_pos(below.left_bottom() + egui::vec2(0.0, 2.0)).order(egui::Order::Foreground).show(ui.ctx(), |ui| {
|
||||
egui::Frame::popup(ui.style()).fill(palette.surface_high).show(ui, |ui| {
|
||||
ui.set_width(below.width());
|
||||
for (i, s) in items.iter().enumerate() {
|
||||
let icon = match s.kind {
|
||||
SuggestionKind::Search | SuggestionKind::SearchSuggestion => "🔍",
|
||||
SuggestionKind::Url => "↗",
|
||||
SuggestionKind::History => "🕘",
|
||||
SuggestionKind::Bookmark => "★",
|
||||
SuggestionKind::Tab(_) => "▭",
|
||||
SuggestionKind::Page => "◆",
|
||||
};
|
||||
let detail = if matches!(s.kind, SuggestionKind::History | SuggestionKind::Bookmark | SuggestionKind::Tab(_)) { format!(" {}", util::ellipsize(&s.url, 70)) } else { String::new() };
|
||||
let text = format!("{icon} {}{detail}", util::ellipsize(if s.title.is_empty() { &s.url } else { &s.title }, 80));
|
||||
let r = ui.add_sized([below.width() - 12.0, 24.0], egui::Button::new(text).selected(selected == Some(i)).frame(selected == Some(i)));
|
||||
if r.clicked() {
|
||||
clicked = Some(s.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(s) = clicked {
|
||||
run_suggestion(f, s, false);
|
||||
f.ui.omnibox_edit = None;
|
||||
f.ui.omnibox_focused = false;
|
||||
ui.ctx().memory_mut(|m| m.stop_text_input());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bookmarks_bar_visible(f: &Frame) -> bool {
|
||||
let mode = f.shared.settings.borrow().ui.bookmarks_bar;
|
||||
match mode {
|
||||
BookmarksBar::Always => true,
|
||||
BookmarksBar::Never => false,
|
||||
BookmarksBar::NewTab => f.tab().is_some_and(|t| t.page == Some(Page::NewTab)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bookmarks_bar(root: &mut Ui, f: &mut Frame) {
|
||||
egui::Panel::top("bookmarks-bar").exact_size(28.0).show(root, |ui| {
|
||||
ui.horizontal_centered(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
let items: Vec<crate::store::bookmarks::Node> = f.shared.bookmarks.borrow().bar.children.clone();
|
||||
if items.is_empty() {
|
||||
ui.label(RichText::new("Bookmarks you add to the bar show here").weak().small());
|
||||
}
|
||||
for node in items {
|
||||
bookmark_item(ui, f, &node);
|
||||
}
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if ui.small_button("All bookmarks").clicked() {
|
||||
f.send(Command::ShowPage(Page::Bookmarks));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn bookmark_item(ui: &mut Ui, f: &mut Frame, node: &crate::store::bookmarks::Node) {
|
||||
match &node.url {
|
||||
Some(url) => {
|
||||
let r = ui.add(egui::Button::new(util::ellipsize(&node.title, 24)).frame(false)).on_hover_text(url);
|
||||
if r.clicked() {
|
||||
let new_tab = ui.input(|i| i.modifiers.command);
|
||||
f.send(Command::Open { url: url.clone(), how: if new_tab { Disposition::NewBackgroundTab } else { Disposition::Current }, from: None });
|
||||
}
|
||||
if r.middle_clicked() {
|
||||
f.send(Command::Open { url: url.clone(), how: Disposition::NewBackgroundTab, from: None });
|
||||
}
|
||||
if r.secondary_clicked() {
|
||||
f.ui.flyout = Some(Flyout::BookmarkMenu(node.id, r.rect.left_bottom()));
|
||||
}
|
||||
},
|
||||
None => {
|
||||
ui.menu_button(format!("📁 {}", util::ellipsize(&node.title, 20)), |ui| {
|
||||
folder_menu(ui, f, node);
|
||||
});
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn folder_menu(ui: &mut Ui, f: &mut Frame, folder: &crate::store::bookmarks::Node) {
|
||||
if folder.children.is_empty() {
|
||||
ui.label(RichText::new("Empty").weak());
|
||||
}
|
||||
for child in &folder.children {
|
||||
match &child.url {
|
||||
Some(url) => {
|
||||
if ui.button(util::ellipsize(&child.title, 48)).on_hover_text(url).clicked() {
|
||||
f.send(Command::Open { url: url.clone(), how: Disposition::Current, from: None });
|
||||
ui.close();
|
||||
}
|
||||
},
|
||||
None => {
|
||||
ui.menu_button(format!("📁 {}", util::ellipsize(&child.title, 40)), |ui| folder_menu(ui, f, child));
|
||||
},
|
||||
}
|
||||
}
|
||||
if folder.children.iter().filter(|c| c.url.is_some()).count() > 1 {
|
||||
ui.separator();
|
||||
if ui.button("Open all in new tabs").clicked() {
|
||||
for child in folder.children.iter().filter_map(|c| c.url.clone()) {
|
||||
f.send(Command::Open { url: child, how: Disposition::NewBackgroundTab, from: None });
|
||||
}
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// App windows: back, reload, the page title, "open in browser", and the menu.
|
||||
pub fn app_bar(root: &mut Ui, f: &mut Frame) {
|
||||
egui::Panel::top("app-bar").exact_size(32.0).show(root, |ui| {
|
||||
ui.horizontal_centered(|ui| {
|
||||
let can_back = f.tab().is_some_and(|t| t.can_go_back());
|
||||
if ui.add_enabled(can_back, egui::Button::new("⬅").frame(false)).clicked() {
|
||||
f.send(Command::Back);
|
||||
}
|
||||
if icon_button(ui, "⟳", "Reload").clicked() {
|
||||
f.send(Command::Reload { hard: false });
|
||||
}
|
||||
let title = f.tab().map(|t| t.display_title()).unwrap_or_default();
|
||||
ui.label(RichText::new(util::ellipsize(&title, 80)).strong());
|
||||
if let Some(url) = f.tab().map(|t| t.url.clone()) {
|
||||
ui.label(RichText::new(util::host_of_str(&url)).weak().small());
|
||||
}
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
let menu = icon_button(ui, "☰", "Menu");
|
||||
if menu.clicked() {
|
||||
f.ui.toggle(Flyout::Main, Some(menu.rect));
|
||||
}
|
||||
if icon_button(ui, "↗", "Open in the browser").clicked()
|
||||
&& let Some(url) = f.tab().map(|t| t.url.clone())
|
||||
{
|
||||
f.send(Command::Open { url, how: Disposition::NewForegroundTab, from: None });
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Picture in picture: the video frame and a few controls over it.
|
||||
pub fn pip_window(root: &mut Ui, f: &mut Frame) {
|
||||
let rect = root.max_rect();
|
||||
root.painter().rect_filled(rect, 0.0, Color32::BLACK);
|
||||
if let Some(texture) = f.pip_frame {
|
||||
root.painter().image(texture.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
|
||||
} else {
|
||||
root.put(egui::Rect::from_center_size(rect.center(), Vec2::splat(32.0)), egui::Spinner::new());
|
||||
}
|
||||
let hovered = root.ctx().input(|i| i.pointer.hover_pos().is_some());
|
||||
if !hovered {
|
||||
return;
|
||||
}
|
||||
let response = root.interact(rect, root.id().with("pip-surface"), Sense::click_and_drag());
|
||||
if response.drag_started() {
|
||||
f.send(Command::WindowDrag);
|
||||
}
|
||||
if response.double_clicked() {
|
||||
f.send(Command::ExitPip);
|
||||
} else if response.clicked() {
|
||||
f.send(Command::PipAct { action: "toggle".into(), value: 0.0 });
|
||||
}
|
||||
egui::Area::new(egui::Id::new("pip-controls")).anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -8.0)).show(root.ctx(), |ui| {
|
||||
egui::Frame::popup(ui.style()).fill(Color32::from_black_alpha(170)).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let white = |t: &str| RichText::new(t).color(Color32::WHITE).size(16.0);
|
||||
if ui.add(egui::Button::new(white("⏪")).frame(false)).on_hover_text("Back 10 seconds").clicked() {
|
||||
f.send(Command::PipAct { action: "skip".into(), value: -10.0 });
|
||||
}
|
||||
if ui.add(egui::Button::new(white("⏯")).frame(false)).on_hover_text("Play or pause").clicked() {
|
||||
f.send(Command::PipAct { action: "toggle".into(), value: 0.0 });
|
||||
}
|
||||
if ui.add(egui::Button::new(white("⏩")).frame(false)).on_hover_text("Forward 10 seconds").clicked() {
|
||||
f.send(Command::PipAct { action: "skip".into(), value: 10.0 });
|
||||
}
|
||||
if ui.add(egui::Button::new(white("🔇")).frame(false)).on_hover_text("Mute").clicked() {
|
||||
f.send(Command::PipAct { action: "mute".into(), value: 0.0 });
|
||||
}
|
||||
if ui.add(egui::Button::new(white("⤶")).frame(false)).on_hover_text("Back to the tab").clicked() {
|
||||
f.send(Command::ExitPip);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
let _ = f.pip_size;
|
||||
}
|
||||
415
src/ui/dialogs.rs
Normal file
415
src/ui/dialogs.rs
Normal file
|
|
@ -0,0 +1,415 @@
|
|||
//! Bars above the page (permission requests, save password, ...), the find bar, and dialogs in
|
||||
//! front of the page (alerts, sign-in, select lists, colour picker, autofill).
|
||||
|
||||
use egui::{Align2, RichText, Ui, Vec2};
|
||||
|
||||
use super::Frame;
|
||||
use crate::actions::{Command, DialogResult, PromptAnswer};
|
||||
use crate::tabs::{Dialog, Prompt};
|
||||
use crate::util;
|
||||
|
||||
pub fn prompt_bars(root: &mut Ui, f: &mut Frame) {
|
||||
let Some(tab) = f.tab() else { return };
|
||||
let Some(prompt) = tab.prompts.front() else { return };
|
||||
let tab_id = tab.id;
|
||||
let more = tab.prompts.len() - 1;
|
||||
let text = match prompt {
|
||||
Prompt::Permission { host, kind, .. } => format!("{host} wants to {}", kind.request_text()),
|
||||
Prompt::ProtocolHandler { host, scheme, .. } => format!("{host} wants to open {scheme}: links"),
|
||||
Prompt::SaveLogin { origin, username, update, .. } => {
|
||||
let who = if username.is_empty() { String::new() } else { format!(" for {username}") };
|
||||
if *update { format!("Update the saved password{who} on {}?", util::host_of_str(origin)) } else { format!("Save the password{who} on {}?", util::host_of_str(origin)) }
|
||||
},
|
||||
Prompt::HttpFallback { url } => format!("{} has no secure version. Open it over an unencrypted connection?", util::host_of(url)),
|
||||
Prompt::External { url } => format!("Open this link in another app? {}", util::ellipsize(url, 60)),
|
||||
Prompt::PopupBlocked { .. } => "A pop-up was blocked on this site".to_owned(),
|
||||
Prompt::Info { text } => text.clone(),
|
||||
};
|
||||
let kind = match prompt {
|
||||
Prompt::Permission { .. } | Prompt::ProtocolHandler { .. } => 0,
|
||||
Prompt::SaveLogin { .. } => 1,
|
||||
Prompt::HttpFallback { .. } => 2,
|
||||
Prompt::External { .. } => 3,
|
||||
Prompt::PopupBlocked { .. } => 4,
|
||||
Prompt::Info { .. } => 5,
|
||||
};
|
||||
let fill = f.palette().accent_soft;
|
||||
egui::Panel::top("prompt-bar").frame(egui::Frame::NONE.fill(fill).inner_margin(egui::Margin::symmetric(12, 6))).show(root, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(text).strong());
|
||||
if more > 0 {
|
||||
ui.label(RichText::new(format!("(+{more} more)")).weak());
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let mut answer = None;
|
||||
if ui.small_button("✕").on_hover_text("Not now").clicked() {
|
||||
answer = Some(PromptAnswer::Dismiss);
|
||||
}
|
||||
match kind {
|
||||
0 | 3 => {
|
||||
let remember_id = ui.id().with(("remember", tab_id));
|
||||
let mut remember = ui.data_mut(|d| *d.get_temp_mut_or(remember_id, true));
|
||||
if ui.button("Block").clicked() {
|
||||
answer = Some(PromptAnswer::Deny { remember });
|
||||
}
|
||||
if ui.button("Allow").clicked() {
|
||||
answer = Some(PromptAnswer::Allow { remember });
|
||||
}
|
||||
ui.checkbox(&mut remember, "Remember");
|
||||
ui.data_mut(|d| d.insert_temp(remember_id, remember));
|
||||
},
|
||||
1 => {
|
||||
if ui.button("Never for this site").clicked() {
|
||||
answer = Some(PromptAnswer::Never);
|
||||
}
|
||||
if ui.button("Save").clicked() {
|
||||
answer = Some(PromptAnswer::Yes);
|
||||
}
|
||||
},
|
||||
2 => {
|
||||
if ui.button("Always for this site").clicked() {
|
||||
answer = Some(PromptAnswer::Allow { remember: true });
|
||||
}
|
||||
if ui.button("Open anyway").clicked() {
|
||||
answer = Some(PromptAnswer::Yes);
|
||||
}
|
||||
},
|
||||
4 => {
|
||||
if ui.button("Always allow pop-ups here").clicked() {
|
||||
answer = Some(PromptAnswer::Allow { remember: true });
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
if let Some(answer) = answer {
|
||||
f.send(Command::Prompt { tab: tab_id, answer });
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub fn find_bar(root: &mut Ui, f: &mut Frame) {
|
||||
let Some(tab) = f.tab() else { return };
|
||||
if !tab.find.open {
|
||||
return;
|
||||
}
|
||||
let mut find = tab.find.clone();
|
||||
egui::Panel::top("find-bar").show(root, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Find");
|
||||
let response = ui.add(egui::TextEdit::singleline(&mut find.text).desired_width(260.0).hint_text("Find in page"));
|
||||
if find.focus {
|
||||
response.request_focus();
|
||||
find.focus = false;
|
||||
}
|
||||
let enter = response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
let shift = ui.input(|i| i.modifiers.shift);
|
||||
if response.changed() {
|
||||
f.send(Command::Find { text: find.text.clone(), forward: true, case: find.case_sensitive });
|
||||
}
|
||||
if enter {
|
||||
f.send(Command::Find { text: find.text.clone(), forward: !shift, case: find.case_sensitive });
|
||||
response.request_focus();
|
||||
}
|
||||
if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
f.send(Command::FindClose);
|
||||
}
|
||||
let label = if find.text.is_empty() { String::new() } else if find.count == 0 { "No matches".into() } else { format!("{} of {}", find.index, find.count) };
|
||||
ui.label(RichText::new(label).weak());
|
||||
if ui.small_button("⬆").on_hover_text("Previous (Shift+Enter)").clicked() {
|
||||
f.send(Command::Find { text: find.text.clone(), forward: false, case: find.case_sensitive });
|
||||
}
|
||||
if ui.small_button("⬇").on_hover_text("Next (Enter)").clicked() {
|
||||
f.send(Command::Find { text: find.text.clone(), forward: true, case: find.case_sensitive });
|
||||
}
|
||||
if ui.checkbox(&mut find.case_sensitive, "Match case").changed() {
|
||||
f.send(Command::Find { text: find.text.clone(), forward: true, case: find.case_sensitive });
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.small_button("✕").clicked() {
|
||||
f.send(Command::FindClose);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
if let Some(tab) = f.tab_mut() {
|
||||
tab.find.text = find.text;
|
||||
tab.find.case_sensitive = find.case_sensitive;
|
||||
tab.find.focus = find.focus;
|
||||
}
|
||||
}
|
||||
|
||||
/// Dialogs that belong to the page, drawn over it.
|
||||
pub fn page_dialogs(ctx: &egui::Context, f: &mut Frame) {
|
||||
let active = *f.active;
|
||||
let Some(tab) = f.tabs.get_mut(active) else { return };
|
||||
let tab_id = tab.id;
|
||||
let Some(dialog) = tab.dialog.take() else { return };
|
||||
let page = f.page_rect.unwrap_or_else(|| ctx.content_rect());
|
||||
let palette = f.palette();
|
||||
let center = page.center_top() + egui::vec2(0.0, 80.0);
|
||||
let card = |ctx: &egui::Context, id: &str, body: &mut dyn FnMut(&mut Ui)| {
|
||||
egui::Area::new(egui::Id::new((id, tab_id))).fixed_pos(center).pivot(Align2::CENTER_TOP).order(egui::Order::Foreground).show(ctx, |ui| {
|
||||
egui::Frame::popup(ui.style()).fill(palette.surface_high).inner_margin(egui::Margin::same(16)).show(ui, |ui| {
|
||||
ui.set_width(380.0);
|
||||
body(ui);
|
||||
});
|
||||
});
|
||||
};
|
||||
let mut result: Option<DialogResult> = None;
|
||||
let mut extra: Vec<Command> = Vec::new();
|
||||
match &dialog {
|
||||
Dialog::Simple(simple, origin) => {
|
||||
let value_id = egui::Id::new(("prompt-value", tab_id));
|
||||
card(ctx, "simple-dialog", &mut |ui| {
|
||||
ui.label(RichText::new(format!("{} says", util::host_of_str(origin))).weak());
|
||||
ui.add_space(4.0);
|
||||
ui.label(util::ellipsize(simple.message(), 2000));
|
||||
ui.add_space(8.0);
|
||||
let mut value: Option<String> = None;
|
||||
if let servo::SimpleDialog::Prompt(prompt) = simple {
|
||||
let mut text = ui.data_mut(|d| d.get_temp::<String>(value_id)).unwrap_or_else(|| prompt.current_value().to_owned());
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(340.0));
|
||||
r.request_focus();
|
||||
ui.data_mut(|d| d.insert_temp(value_id, text.clone()));
|
||||
value = Some(text);
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if !matches!(simple, servo::SimpleDialog::Alert(_)) && ui.button("Cancel").clicked() {
|
||||
result = Some(DialogResult::Cancel);
|
||||
}
|
||||
if ui.button("OK").clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) {
|
||||
result = Some(DialogResult::Ok(value.clone()));
|
||||
}
|
||||
});
|
||||
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
result = Some(if matches!(simple, servo::SimpleDialog::Alert(_)) { DialogResult::Ok(None) } else { DialogResult::Cancel });
|
||||
}
|
||||
});
|
||||
if result.is_some() {
|
||||
ctx.data_mut(|d| d.remove::<String>(value_id));
|
||||
}
|
||||
},
|
||||
Dialog::Auth { request, username, password } => {
|
||||
let id = egui::Id::new(("auth", tab_id));
|
||||
card(ctx, "auth-dialog", &mut |ui| {
|
||||
let host = request.url().host_str().unwrap_or("").to_owned();
|
||||
ui.label(RichText::new(if request.for_proxy() { format!("The proxy {host} needs you to sign in") } else { format!("{host} needs you to sign in") }).strong());
|
||||
let (mut u, mut p) = ui.data_mut(|d| d.get_temp::<(String, String)>(id)).unwrap_or((username.clone(), password.clone()));
|
||||
ui.add(egui::TextEdit::singleline(&mut u).hint_text("User name").desired_width(340.0));
|
||||
let pr = ui.add(egui::TextEdit::singleline(&mut p).hint_text("Password").password(true).desired_width(340.0));
|
||||
ui.data_mut(|d| d.insert_temp(id, (u.clone(), p.clone())));
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Cancel").clicked() {
|
||||
result = Some(DialogResult::Cancel);
|
||||
}
|
||||
if ui.button("Sign in").clicked() || (pr.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) {
|
||||
result = Some(DialogResult::Auth { username: u.clone(), password: p.clone() });
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
Dialog::Select(select) => {
|
||||
let rect = device_rect(ctx, f.page_rect.as_ref(), select.position());
|
||||
let multiple = select.allow_select_multiple();
|
||||
let mut chosen: Vec<usize> = select.selected_options();
|
||||
let area = egui::Area::new(egui::Id::new(("select", tab_id))).fixed_pos(rect.left_bottom()).order(egui::Order::Foreground).constrain(true).show(ctx, |ui| {
|
||||
egui::Frame::menu(ui.style()).show(ui, |ui| {
|
||||
ui.set_min_width(rect.width().max(160.0));
|
||||
egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| {
|
||||
let mut option = |ui: &mut Ui, o: &servo::SelectElementOption, indent: bool| {
|
||||
let selected = chosen.contains(&o.id);
|
||||
let label = if indent { format!(" {}", o.label) } else { o.label.clone() };
|
||||
let r = ui.add_enabled(!o.is_disabled, egui::Button::new(label).selected(selected).frame(false));
|
||||
if r.clicked() {
|
||||
if multiple {
|
||||
if selected { chosen.retain(|i| *i != o.id) } else { chosen.push(o.id) }
|
||||
} else {
|
||||
chosen = vec![o.id];
|
||||
result = Some(DialogResult::Select(chosen.clone()));
|
||||
}
|
||||
}
|
||||
};
|
||||
for entry in select.options() {
|
||||
match entry {
|
||||
servo::SelectElementOptionOrOptgroup::Option(o) => option(ui, o, false),
|
||||
servo::SelectElementOptionOrOptgroup::Optgroup { label, options } => {
|
||||
ui.label(RichText::new(label).strong());
|
||||
for o in options {
|
||||
option(ui, o, true);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
});
|
||||
if multiple && ui.button("Done").clicked() {
|
||||
result = Some(DialogResult::Select(chosen.clone()));
|
||||
}
|
||||
});
|
||||
});
|
||||
let outside = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !area.response.rect.contains(p)));
|
||||
if result.is_none() && (outside || ctx.input(|i| i.key_pressed(egui::Key::Escape))) {
|
||||
result = Some(if multiple { DialogResult::Select(chosen) } else { DialogResult::Close });
|
||||
}
|
||||
},
|
||||
Dialog::Color(picker, initial) => {
|
||||
let rect = device_rect(ctx, f.page_rect.as_ref(), picker.position());
|
||||
let id = egui::Id::new(("color", tab_id));
|
||||
let mut rgb = ctx.data_mut(|d| d.get_temp::<[u8; 3]>(id)).unwrap_or(*initial);
|
||||
egui::Area::new(id).fixed_pos(rect.left_bottom()).order(egui::Order::Foreground).constrain(true).show(ctx, |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
let mut color = egui::Color32::from_rgb(rgb[0], rgb[1], rgb[2]);
|
||||
egui::color_picker::color_picker_color32(ui, &mut color, egui::color_picker::Alpha::Opaque);
|
||||
rgb = [color.r(), color.g(), color.b()];
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Cancel").clicked() {
|
||||
result = Some(DialogResult::Color(None));
|
||||
}
|
||||
if ui.button("Choose").clicked() {
|
||||
result = Some(DialogResult::Color(Some(rgb)));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
ctx.data_mut(|d| d.insert_temp(id, rgb));
|
||||
if result.is_some() {
|
||||
ctx.data_mut(|d| d.remove::<[u8; 3]>(id));
|
||||
}
|
||||
},
|
||||
Dialog::ContextMenu(menu) => {
|
||||
super::menus::page_menu(ctx, f, tab_id, menu);
|
||||
},
|
||||
Dialog::Bluetooth(request) => {
|
||||
card(ctx, "bluetooth", &mut |ui| {
|
||||
ui.label(RichText::new("Choose a Bluetooth device").strong());
|
||||
if request.devices().is_empty() {
|
||||
ui.label(RichText::new("No devices found nearby").weak());
|
||||
}
|
||||
for (i, device) in request.devices().iter().enumerate() {
|
||||
let name = if device.name.is_empty() { device.address.clone() } else { format!("{} ({})", device.name, device.address) };
|
||||
if ui.button(name).clicked() {
|
||||
result = Some(DialogResult::Device(Some(i)));
|
||||
}
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
result = Some(DialogResult::Device(None));
|
||||
}
|
||||
});
|
||||
},
|
||||
Dialog::LeavePage(_) => {
|
||||
card(ctx, "leave", &mut |ui| {
|
||||
ui.label(RichText::new("Leave this page?").strong());
|
||||
ui.label("Changes you made may not be saved.");
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Stay").clicked() {
|
||||
result = Some(DialogResult::Leave(false));
|
||||
}
|
||||
if ui.button("Leave").clicked() {
|
||||
result = Some(DialogResult::Leave(true));
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
Dialog::Logins { x, y, items } => {
|
||||
let zoom = f.tabs.get(active).map(|t| t.zoom).unwrap_or(1.0);
|
||||
let pos = page.min + egui::vec2(x * zoom, y * zoom + 2.0);
|
||||
let locked = f.shared.vault.borrow().locked();
|
||||
let mut close = false;
|
||||
let area = egui::Area::new(egui::Id::new(("logins", tab_id))).fixed_pos(pos).order(egui::Order::Foreground).constrain(true).show(ctx, |ui| {
|
||||
egui::Frame::menu(ui.style()).show(ui, |ui| {
|
||||
ui.set_min_width(240.0);
|
||||
if locked {
|
||||
let id = egui::Id::new("vault-unlock");
|
||||
let mut pw = ui.data_mut(|d| d.get_temp::<String>(id)).unwrap_or_default();
|
||||
ui.label("Unlock saved passwords");
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut pw).password(true).hint_text("Master password"));
|
||||
if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
|
||||
match f.shared.vault.borrow_mut().unlock(&pw) {
|
||||
Ok(()) => {
|
||||
pw.clear();
|
||||
close = true;
|
||||
},
|
||||
Err(error) => {
|
||||
ui.label(RichText::new(error.to_string()).color(palette.error));
|
||||
},
|
||||
}
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(id, pw));
|
||||
return;
|
||||
}
|
||||
for (id, user) in items {
|
||||
let label = if user.is_empty() { "(no user name)".to_owned() } else { user.clone() };
|
||||
if ui.button(format!("🔑 {label}")).clicked() {
|
||||
extra.push(Command::FillLogin { tab: tab_id, id: *id });
|
||||
}
|
||||
}
|
||||
if !items.is_empty() {
|
||||
ui.separator();
|
||||
}
|
||||
let (len, symbols) = {
|
||||
let s = f.shared.settings.borrow();
|
||||
(s.vault.gen_length, s.vault.gen_symbols)
|
||||
};
|
||||
if ui.button("Use a strong password").on_hover_text("Fills a new random password; it is saved when you submit the form").clicked() {
|
||||
extra.push(Command::FillPassword { tab: tab_id, password: crate::store::vault::generate(len as usize, symbols) });
|
||||
}
|
||||
if ui.button("Manage passwords").clicked() {
|
||||
extra.push(Command::ShowPage(crate::tabs::Page::Passwords));
|
||||
close = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
let outside = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !area.response.rect.contains(p)));
|
||||
if close || outside || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
result = Some(DialogResult::Close);
|
||||
}
|
||||
},
|
||||
Dialog::Forms { kind, x, y } => {
|
||||
let zoom = f.tabs.get(active).map(|t| t.zoom).unwrap_or(1.0);
|
||||
let pos = page.min + egui::vec2(x * zoom, y * zoom + 2.0);
|
||||
let area = egui::Area::new(egui::Id::new(("forms", tab_id))).fixed_pos(pos).order(egui::Order::Foreground).constrain(true).show(ctx, |ui| {
|
||||
egui::Frame::menu(ui.style()).show(ui, |ui| {
|
||||
let vault = f.shared.vault.borrow();
|
||||
if kind == "card" {
|
||||
for c in &vault.contents.cards {
|
||||
let label = if c.nickname.is_empty() { c.masked() } else { format!("{} {}", c.nickname, c.masked()) };
|
||||
if ui.button(format!("💳 {label}")).clicked() {
|
||||
extra.push(Command::FillCard { tab: tab_id, id: c.id });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for a in &vault.contents.addresses {
|
||||
if ui.button(format!("🏠 {}, {}", a.name, a.street)).clicked() {
|
||||
extra.push(Command::FillAddress { tab: tab_id, id: a.id });
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
let outside = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !area.response.rect.contains(p)));
|
||||
if outside || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
result = Some(DialogResult::Close);
|
||||
}
|
||||
},
|
||||
}
|
||||
// Put it back; the app takes it when the result arrives.
|
||||
if let Some(tab) = f.tabs.get_mut(active) {
|
||||
if tab.dialog.is_none() {
|
||||
tab.dialog = Some(dialog);
|
||||
}
|
||||
}
|
||||
for command in extra {
|
||||
f.send(command);
|
||||
}
|
||||
if let Some(result) = result {
|
||||
f.send(Command::Dialog { tab: tab_id, result });
|
||||
}
|
||||
let _ = Vec2::ZERO;
|
||||
}
|
||||
|
||||
fn device_rect(ctx: &egui::Context, page: Option<&egui::Rect>, rect: servo::DeviceIntRect) -> egui::Rect {
|
||||
let ppp = ctx.pixels_per_point();
|
||||
let origin = page.map(|r| r.min).unwrap_or_default();
|
||||
egui::Rect::from_min_max(origin + egui::vec2(rect.min.x as f32 / ppp, rect.min.y as f32 / ppp), origin + egui::vec2(rect.max.x as f32 / ppp, rect.max.y as f32 / ppp))
|
||||
}
|
||||
914
src/ui/menus.rs
Normal file
914
src/ui/menus.rs
Normal file
|
|
@ -0,0 +1,914 @@
|
|||
//! The page's right-click menu and the flyouts that open from the toolbar.
|
||||
|
||||
use egui::{Align2, Color32, RichText, Ui, Vec2};
|
||||
|
||||
use super::widgets::{segmented, switch};
|
||||
use super::{Flyout, Frame};
|
||||
use crate::actions::{Command, Disposition, DownloadOp, MenuAction};
|
||||
use crate::keys::Action;
|
||||
use crate::net::VpnStatus;
|
||||
use crate::store::downloads::State as DlState;
|
||||
use crate::store::settings::{VpnProvider, Visualizer};
|
||||
use crate::tabs::Page;
|
||||
use crate::util;
|
||||
|
||||
/// A right-click menu on a page: Servo's own items plus Nacre's.
|
||||
pub struct PageMenu {
|
||||
menu: Option<servo::ContextMenu>,
|
||||
pub position: servo::DeviceIntRect,
|
||||
pub items: Vec<(String, MenuAction, bool)>,
|
||||
pub link: Option<String>,
|
||||
pub image: Option<String>,
|
||||
pub selection: String,
|
||||
pub word: String,
|
||||
pub editable: bool,
|
||||
pub media: Option<String>,
|
||||
}
|
||||
|
||||
impl PageMenu {
|
||||
pub fn new(menu: servo::ContextMenu, extra: Option<serde_json::Value>, page_url: &str, has_media: bool) -> PageMenu {
|
||||
let info = menu.element_info();
|
||||
let link = info.link_url.as_ref().map(|u| u.to_string());
|
||||
let image = info.image_url.as_ref().map(|u| u.to_string());
|
||||
let extra = extra.unwrap_or_default();
|
||||
let s = |k: &str| extra.get(k).and_then(|v| v.as_str()).unwrap_or("").to_owned();
|
||||
let selection = s("selection");
|
||||
let word = s("word");
|
||||
let editable = extra.get("editable").and_then(|v| v.as_bool()).unwrap_or(false) || info.flags.contains(servo::ContextMenuElementInformationFlags::EditableText);
|
||||
let media = extra.get("media").and_then(|m| m.get("src")).and_then(|v| v.as_str()).map(str::to_owned).filter(|s| !s.is_empty());
|
||||
let mut items: Vec<(String, MenuAction, bool)> = Vec::new();
|
||||
if let Some(link) = &link {
|
||||
items.push(("Open link in new tab".into(), MenuAction::OpenLink(link.clone(), Disposition::NewBackgroundTab), true));
|
||||
items.push(("Open link in new window".into(), MenuAction::OpenLink(link.clone(), Disposition::NewWindow), true));
|
||||
items.push(("Open link in incognito window".into(), MenuAction::OpenLink(link.clone(), Disposition::Incognito), true));
|
||||
items.push(("Save link as…".into(), MenuAction::SaveLink(link.clone()), true));
|
||||
items.push(("Copy link address".into(), MenuAction::CopyText(link.clone()), true));
|
||||
items.push((String::new(), MenuAction::Dismiss, false));
|
||||
}
|
||||
if let Some(image) = &image {
|
||||
items.push(("Open image in new tab".into(), MenuAction::OpenLink(image.clone(), Disposition::NewBackgroundTab), true));
|
||||
items.push(("Save image as…".into(), MenuAction::SaveLink(image.clone()), true));
|
||||
items.push(("Copy image address".into(), MenuAction::CopyText(image.clone()), true));
|
||||
items.push((String::new(), MenuAction::Dismiss, false));
|
||||
}
|
||||
if let Some(src) = &media {
|
||||
items.push(("Picture in picture".into(), MenuAction::Pip, true));
|
||||
items.push(("Loop".into(), MenuAction::LoopMedia, true));
|
||||
if src.starts_with("http") {
|
||||
items.push(("Save video or audio as…".into(), MenuAction::SaveLink(src.clone()), true));
|
||||
items.push(("Copy media address".into(), MenuAction::CopyText(src.clone()), true));
|
||||
}
|
||||
items.push((String::new(), MenuAction::Dismiss, false));
|
||||
} else if has_media && link.is_none() && image.is_none() && selection.is_empty() && !editable {
|
||||
items.push(("Picture in picture".into(), MenuAction::Pip, true));
|
||||
}
|
||||
// Servo's own items (back/forward/reload, clipboard actions).
|
||||
for item in menu.items() {
|
||||
match item {
|
||||
servo::ContextMenuItem::Item { label, action, enabled } => {
|
||||
// Nacre already offers these with its own wording above.
|
||||
if matches!(action, servo::ContextMenuAction::OpenLinkInNewWebView | servo::ContextMenuAction::CopyLink | servo::ContextMenuAction::CopyImageLink | servo::ContextMenuAction::OpenImageInNewView) {
|
||||
continue;
|
||||
}
|
||||
items.push((label.clone(), MenuAction::Servo(*action), *enabled));
|
||||
},
|
||||
servo::ContextMenuItem::Separator => items.push((String::new(), MenuAction::Dismiss, false)),
|
||||
}
|
||||
}
|
||||
if !selection.trim().is_empty() {
|
||||
let short = util::ellipsize(selection.trim(), 30);
|
||||
items.push((String::new(), MenuAction::Dismiss, false));
|
||||
items.push((format!("Search for “{short}”"), MenuAction::SearchFor(selection.trim().to_owned()), true));
|
||||
if selection.trim().starts_with("http") && !selection.contains(char::is_whitespace) {
|
||||
items.push(("Open as link".into(), MenuAction::OpenLink(selection.trim().to_owned(), Disposition::NewForegroundTab), true));
|
||||
}
|
||||
}
|
||||
if link.is_none() && image.is_none() && !editable {
|
||||
items.push((String::new(), MenuAction::Dismiss, false));
|
||||
items.push(("Save page as…".into(), MenuAction::SavePage, true));
|
||||
items.push(("QR code for this page".into(), MenuAction::QrCode, true));
|
||||
if page_url.starts_with("http") {
|
||||
items.push(("View page source".into(), MenuAction::ViewSource, true));
|
||||
}
|
||||
items.push(("Developer tools".into(), MenuAction::DevTools, true));
|
||||
}
|
||||
let position = menu.position();
|
||||
PageMenu { menu: Some(menu), position, items, link, image, selection, word, editable, media }
|
||||
}
|
||||
|
||||
pub fn control_id(&self) -> Option<servo::EmbedderControlId> {
|
||||
self.menu.as_ref().map(|m| m.id())
|
||||
}
|
||||
|
||||
pub fn select(mut self, action: servo::ContextMenuAction) {
|
||||
if let Some(menu) = self.menu.take() {
|
||||
menu.select(action);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dismiss(mut self) {
|
||||
if let Some(menu) = self.menu.take() {
|
||||
menu.dismiss();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the page menu at its position; returns the chosen action.
|
||||
pub fn page_menu(ctx: &egui::Context, f: &mut Frame, tab_id: u64, menu: &PageMenu) {
|
||||
let ppp = ctx.pixels_per_point();
|
||||
let origin = f.page_rect.map(|r| r.min).unwrap_or_default();
|
||||
let pos = origin + egui::vec2(menu.position.min.x as f32 / ppp, menu.position.min.y as f32 / ppp);
|
||||
let speller_suggestions: Vec<String> = if menu.editable && !menu.word.is_empty() {
|
||||
let speller = f.shared.speller.borrow();
|
||||
match speller.as_ref() {
|
||||
Some(s) if !s.check(&menu.word) => s.suggest(&menu.word, 5),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let misspelled = menu.editable && !menu.word.is_empty() && f.shared.speller.borrow().as_ref().is_some_and(|s| !s.check(&menu.word));
|
||||
let mut chosen = None;
|
||||
let area = egui::Area::new(egui::Id::new(("page-menu", tab_id))).fixed_pos(pos).order(egui::Order::Foreground).constrain(true).show(ctx, |ui| {
|
||||
egui::Frame::menu(ui.style()).show(ui, |ui| {
|
||||
ui.set_min_width(220.0);
|
||||
if misspelled {
|
||||
for s in &speller_suggestions {
|
||||
if ui.button(RichText::new(s).strong()).clicked() {
|
||||
chosen = Some(MenuAction::SpellReplace(menu.word.clone(), s.clone()));
|
||||
}
|
||||
}
|
||||
if speller_suggestions.is_empty() {
|
||||
ui.label(RichText::new("No suggestions").weak());
|
||||
}
|
||||
if ui.button(format!("Add “{}” to the dictionary", menu.word)).clicked() {
|
||||
chosen = Some(MenuAction::SpellAdd(menu.word.clone()));
|
||||
}
|
||||
ui.separator();
|
||||
}
|
||||
let mut last_sep = true;
|
||||
for (label, action, enabled) in &menu.items {
|
||||
if label.is_empty() {
|
||||
if !last_sep {
|
||||
ui.separator();
|
||||
last_sep = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
last_sep = false;
|
||||
if ui.add_enabled(*enabled, egui::Button::new(label).frame(false)).clicked() {
|
||||
chosen = Some(action.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
let clicked_outside = ctx.input(|i| i.pointer.any_pressed()) && !ctx.input(|i| i.pointer.interact_pos().is_some_and(|p| area.response.rect.contains(p)));
|
||||
let escape = ctx.input(|i| i.key_pressed(egui::Key::Escape));
|
||||
if let Some(action) = chosen {
|
||||
f.send(Command::Menu { tab: tab_id, action });
|
||||
} else if clicked_outside || escape {
|
||||
f.send(Command::Menu { tab: tab_id, action: MenuAction::Dismiss });
|
||||
}
|
||||
}
|
||||
|
||||
/// Show whichever flyout is open.
|
||||
pub fn flyouts(ctx: &egui::Context, f: &mut Frame) {
|
||||
let Some(flyout) = f.ui.flyout.clone() else { return };
|
||||
let anchor = f.ui.flyout_anchor;
|
||||
let (pos, pivot) = match &flyout {
|
||||
Flyout::TabMenu(_, p) | Flyout::BookmarkMenu(_, p) | Flyout::BackHistory(p) => (*p, Align2::LEFT_TOP),
|
||||
_ => match anchor {
|
||||
Some(r) => (r.right_bottom() + egui::vec2(0.0, 4.0), Align2::RIGHT_TOP),
|
||||
None => (ctx.content_rect().right_top() + egui::vec2(-8.0, 80.0), Align2::RIGHT_TOP),
|
||||
},
|
||||
};
|
||||
let palette = f.palette();
|
||||
let area = egui::Area::new(egui::Id::new("flyout")).fixed_pos(pos).pivot(pivot).order(egui::Order::Foreground).constrain(true).show(ctx, |ui| {
|
||||
egui::Frame::popup(ui.style()).fill(palette.surface_high).inner_margin(egui::Margin::same(10)).show(ui, |ui| match &flyout {
|
||||
Flyout::Main => main_menu(ui, f),
|
||||
Flyout::Downloads => downloads(ui, f),
|
||||
Flyout::Shield => shield(ui, f),
|
||||
Flyout::Vpn => vpn(ui, f),
|
||||
Flyout::Media => media(ui, f),
|
||||
Flyout::SiteInfo => site_info(ui, f),
|
||||
Flyout::Profiles => profiles(ui, f),
|
||||
Flyout::EditBookmark(url) => edit_bookmark(ui, f, url),
|
||||
Flyout::Qr(url) => qr(ui, f, url),
|
||||
Flyout::TabMenu(id, _) => tab_menu(ui, f, *id),
|
||||
Flyout::BookmarkMenu(id, _) => bookmark_menu(ui, f, *id),
|
||||
Flyout::BackHistory(_) => back_history(ui, f),
|
||||
Flyout::Apps => apps(ui, f),
|
||||
});
|
||||
});
|
||||
let rect = area.response.rect;
|
||||
let pressed_outside = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !rect.contains(p) && anchor.is_none_or(|a| !a.contains(p))));
|
||||
if pressed_outside || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn item(ui: &mut Ui, label: &str, shortcut: &str) -> bool {
|
||||
let response = ui.add(egui::Button::new(label).frame(false).min_size(Vec2::new(240.0, 22.0)).right_text(RichText::new(shortcut).weak().small()));
|
||||
response.clicked()
|
||||
}
|
||||
|
||||
fn main_menu(ui: &mut Ui, f: &mut Frame) {
|
||||
let keys = f.shared.keymap.borrow();
|
||||
let k = |a: Action| keys.label(a);
|
||||
let mut run: Option<Command> = None;
|
||||
fn pick(run: &mut Option<Command>, cond: bool, command: Command) {
|
||||
if cond {
|
||||
*run = Some(command);
|
||||
}
|
||||
}
|
||||
pick(&mut run, item(ui, "New tab", &k(Action::NewTab)), Command::NewTab);
|
||||
pick(&mut run, item(ui, "New window", &k(Action::NewWindow)), Command::NewWindow);
|
||||
pick(&mut run, item(ui, "New incognito window", &k(Action::NewIncognito)), Command::NewIncognito);
|
||||
ui.separator();
|
||||
pick(&mut run, item(ui, "History", &k(Action::History)), Command::ShowPage(Page::History));
|
||||
pick(&mut run, item(ui, "Downloads", &k(Action::Downloads)), Command::ShowPage(Page::Downloads));
|
||||
pick(&mut run, item(ui, "Bookmarks", &k(Action::BookmarksManager)), Command::ShowPage(Page::Bookmarks));
|
||||
pick(&mut run, item(ui, "Passwords and autofill", &k(Action::Passwords)), Command::ShowPage(Page::Passwords));
|
||||
pick(&mut run, item(ui, "Apps and scripts", ""), Command::ShowPage(Page::Apps));
|
||||
let closed = f.shared.session.borrow().closed.iter().take(8).map(|t| t.title.clone()).collect::<Vec<_>>();
|
||||
if !closed.is_empty() {
|
||||
ui.menu_button("Recently closed", |ui| {
|
||||
for (i, title) in closed.iter().enumerate() {
|
||||
if ui.button(util::ellipsize(title, 50)).clicked() {
|
||||
run = Some(Command::ReopenClosed(Some(i)));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Zoom");
|
||||
let zoom = f.tabs.get(*f.active).map(|t| t.zoom).unwrap_or(1.0);
|
||||
if ui.button("−").clicked() {
|
||||
run = Some(Command::Zoom(-1));
|
||||
}
|
||||
if ui.button(format!("{:.0}%", zoom * 100.0)).on_hover_text("Reset").clicked() {
|
||||
run = Some(Command::Zoom(0));
|
||||
}
|
||||
if ui.button("+").clicked() {
|
||||
run = Some(Command::Zoom(1));
|
||||
}
|
||||
if ui.button("⛶").on_hover_text("Full screen (F11)").clicked() {
|
||||
run = Some(Command::Action(Action::Fullscreen));
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
pick(&mut run, item(ui, "Find in page…", &k(Action::Find)), Command::Action(Action::Find));
|
||||
pick(&mut run, item(ui, "Save page as…", &k(Action::SavePage)), Command::SavePage);
|
||||
pick(&mut run, item(ui, "Save as PDF or image…", &k(Action::Print)), Command::PrintPage);
|
||||
pick(&mut run, item(ui, "Picture in picture", &k(Action::PictureInPicture)), Command::EnterPip);
|
||||
pick(&mut run, item(ui, "Install this site as an app", ""), Command::InstallApp);
|
||||
pick(&mut run, item(ui, "Create a desktop shortcut", ""), Command::CreateShortcut);
|
||||
pick(&mut run, item(ui, "QR code for this page", ""), Command::QrCode);
|
||||
ui.menu_button("More tools", |ui| {
|
||||
if item(ui, "Developer tools", &k(Action::DevTools)) {
|
||||
run = Some(Command::Action(Action::DevTools));
|
||||
ui.close();
|
||||
}
|
||||
if item(ui, "View page source", &k(Action::ViewSource)) {
|
||||
run = Some(Command::ViewSource);
|
||||
ui.close();
|
||||
}
|
||||
if item(ui, "Task manager", &k(Action::TaskManager)) {
|
||||
run = Some(Command::ShowPage(Page::TaskManager));
|
||||
ui.close();
|
||||
}
|
||||
if item(ui, "Delete browsing data…", &k(Action::ClearData)) {
|
||||
run = Some(Command::ShowPage(Page::ClearData));
|
||||
ui.close();
|
||||
}
|
||||
if item(ui, "Free up memory", "") {
|
||||
run = Some(Command::FreeMemory);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
pick(&mut run, item(ui, "Settings", &k(Action::Settings)), Command::ShowPage(Page::Settings(String::new())));
|
||||
pick(&mut run, item(ui, "About Nacre", ""), Command::ShowPage(Page::About));
|
||||
pick(&mut run, item(ui, "Quit", &k(Action::Quit)), Command::Quit);
|
||||
drop(keys);
|
||||
if let Some(command) = run {
|
||||
f.ui.flyout = None;
|
||||
f.send(command);
|
||||
}
|
||||
}
|
||||
|
||||
fn downloads(ui: &mut Ui, f: &mut Frame) {
|
||||
ui.set_width(360.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new("Downloads").strong());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.small_button("All downloads").clicked() {
|
||||
f.send(Command::ShowPage(Page::Downloads));
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
if ui.small_button("📂").on_hover_text("Open the downloads folder").clicked() {
|
||||
f.send(Command::Download(DownloadOp::OpenFolder));
|
||||
}
|
||||
});
|
||||
});
|
||||
// Where new downloads go.
|
||||
let mut settings = f.shared.settings.borrow_mut();
|
||||
let enabled: Vec<String> = settings.downloads.managers.clone();
|
||||
if !enabled.is_empty() {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(RichText::new("Download with").small());
|
||||
let mut manager = settings.downloads.manager.clone();
|
||||
ui.selectable_value(&mut manager, "builtin".to_owned(), "Nacre");
|
||||
for key in &enabled {
|
||||
if let Some(m) = crate::net::dlm::by_key(key) {
|
||||
ui.selectable_value(&mut manager, key.clone(), m.short);
|
||||
}
|
||||
}
|
||||
settings.downloads.manager = manager;
|
||||
});
|
||||
}
|
||||
drop(settings);
|
||||
ui.separator();
|
||||
let items: Vec<crate::store::downloads::Download> = f.shared.downloads.borrow().items.iter().take(8).cloned().collect();
|
||||
if items.is_empty() {
|
||||
ui.label(RichText::new("Nothing downloaded yet").weak());
|
||||
}
|
||||
for d in items {
|
||||
download_row(ui, f, &d);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn download_row(ui: &mut Ui, f: &mut Frame, d: &crate::store::downloads::Download) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(ui.available_width() - 90.0);
|
||||
let name = d.file_name();
|
||||
if d.state == DlState::Done {
|
||||
if ui.link(util::ellipsize(&name, 48)).clicked() {
|
||||
f.send(Command::Download(DownloadOp::Open(d.id)));
|
||||
}
|
||||
} else {
|
||||
ui.label(util::ellipsize(&name, 48));
|
||||
}
|
||||
let status = match d.state {
|
||||
DlState::Running => {
|
||||
let mut s = format!("{}/s · {}", util::format_bytes(d.speed), util::format_bytes(d.received));
|
||||
if d.total > 0 {
|
||||
s.push_str(&format!(" of {}", util::format_bytes(d.total)));
|
||||
}
|
||||
if let Some(eta) = d.eta() {
|
||||
s.push_str(&format!(" · {} left", util::format_duration(eta)));
|
||||
}
|
||||
s
|
||||
},
|
||||
DlState::Paused => format!("Paused · {}{}", util::format_bytes(d.received), if d.total > 0 { format!(" of {}", util::format_bytes(d.total)) } else { String::new() }),
|
||||
DlState::Done => format!("{} · {}", util::format_bytes(d.total.max(d.received)), util::format_ago(d.finished)),
|
||||
DlState::Failed => format!("Failed: {}", d.error),
|
||||
DlState::Cancelled => "Cancelled".into(),
|
||||
DlState::HandedOff => format!("Sent to {}", d.manager),
|
||||
};
|
||||
ui.label(RichText::new(status).small().weak());
|
||||
if matches!(d.state, DlState::Running | DlState::Paused) {
|
||||
ui.add(egui::ProgressBar::new(d.progress().unwrap_or(0.0)).desired_height(4.0));
|
||||
}
|
||||
});
|
||||
match d.state {
|
||||
DlState::Running => {
|
||||
if ui.small_button("⏸").on_hover_text("Pause").clicked() {
|
||||
f.send(Command::Download(DownloadOp::Pause(d.id)));
|
||||
}
|
||||
if ui.small_button("✕").on_hover_text("Cancel").clicked() {
|
||||
f.send(Command::Download(DownloadOp::Cancel(d.id)));
|
||||
}
|
||||
},
|
||||
DlState::Paused => {
|
||||
if ui.small_button("▶").on_hover_text("Resume").clicked() {
|
||||
f.send(Command::Download(DownloadOp::Resume(d.id)));
|
||||
}
|
||||
if ui.small_button("✕").on_hover_text("Cancel").clicked() {
|
||||
f.send(Command::Download(DownloadOp::Cancel(d.id)));
|
||||
}
|
||||
},
|
||||
DlState::Failed => {
|
||||
if ui.small_button("⟳").on_hover_text("Try again").clicked() {
|
||||
f.send(Command::Download(DownloadOp::Retry(d.id)));
|
||||
}
|
||||
},
|
||||
DlState::Done => {
|
||||
if ui.small_button("📂").on_hover_text("Show in folder").clicked() {
|
||||
f.send(Command::Download(DownloadOp::ShowInFolder(d.id)));
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
if !d.active() && ui.small_button("🗑").on_hover_text("Remove from the list").clicked() {
|
||||
f.send(Command::Download(DownloadOp::Remove(d.id)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn shield(ui: &mut Ui, f: &mut Frame) {
|
||||
ui.set_width(300.0);
|
||||
let (host, blocked, hidden) = f.tab().map(|t| (t.host(), t.blocked, t.hidden_elements)).unwrap_or_default();
|
||||
let mut settings = f.shared.settings.borrow_mut();
|
||||
ui.label(RichText::new("Ad blocker").strong());
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Block ads and trackers");
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
switch(ui, &mut settings.adblock.enabled);
|
||||
});
|
||||
});
|
||||
if !host.is_empty() {
|
||||
let mut on_here = !settings.adblock_paused_on(&host);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!("On {host}"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if switch(ui, &mut on_here) {
|
||||
if on_here {
|
||||
settings.adblock.allow.retain(|h| !util::host_matches(&host, h));
|
||||
} else {
|
||||
settings.adblock.allow.push(host.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.label(RichText::new("Changes for this site apply when the page reloads.").small().weak());
|
||||
}
|
||||
ui.separator();
|
||||
ui.label(format!("{blocked} requests blocked on this page"));
|
||||
if hidden > 0 {
|
||||
ui.label(format!("{hidden} ad leftovers hidden"));
|
||||
}
|
||||
ui.label(RichText::new(format!("{} blocked in total", settings.adblock.total)).weak());
|
||||
drop(settings);
|
||||
ui.label(RichText::new(f.shared.adblock_status.borrow().clone()).small().weak());
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Update lists").clicked() {
|
||||
f.send(Command::UpdateFilterLists);
|
||||
}
|
||||
if ui.button("Reload page").clicked() {
|
||||
f.send(Command::Reload { hard: false });
|
||||
}
|
||||
if ui.button("Settings").clicked() {
|
||||
f.send(Command::ShowPage(Page::Settings("adblock".into())));
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn vpn(ui: &mut Ui, f: &mut Frame) {
|
||||
ui.set_width(320.0);
|
||||
let status = f.shared.vpn_status.borrow().clone();
|
||||
let mut settings = f.shared.settings.borrow_mut();
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new("VPN").strong());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
switch(ui, &mut settings.vpn.enabled);
|
||||
});
|
||||
});
|
||||
ui.label(RichText::new("Covers Nacre only: pages, downloads and list updates. Other apps keep using your normal connection.").small().weak());
|
||||
ui.separator();
|
||||
segmented(ui, &mut settings.vpn.provider, VpnProvider::ALL);
|
||||
if settings.vpn.provider == VpnProvider::Custom {
|
||||
ui.add(egui::TextEdit::singleline(&mut settings.vpn.custom).hint_text("socks5://host:port or http://host:port").desired_width(290.0));
|
||||
} else {
|
||||
ui.label(RichText::new("Uses a Tor that is already running (system tor, Tor Browser) or starts the installed tor program.").small().weak());
|
||||
}
|
||||
drop(settings);
|
||||
let palette = f.palette();
|
||||
let (text, color) = match status {
|
||||
VpnStatus::Off => ("Off".to_owned(), palette.text_weak),
|
||||
VpnStatus::Connecting(why) => (why, palette.warning),
|
||||
VpnStatus::On(how) => (format!("Connected: {how}"), palette.success),
|
||||
VpnStatus::Failed(why) => (why, palette.error),
|
||||
};
|
||||
ui.label(RichText::new(text).color(color));
|
||||
}
|
||||
|
||||
fn media(ui: &mut Ui, f: &mut Frame) {
|
||||
ui.set_width(340.0);
|
||||
let Some(now) = f.shared.media_now.borrow().clone() else {
|
||||
ui.label(RichText::new("Nothing is playing").weak());
|
||||
return;
|
||||
};
|
||||
let settings = f.shared.settings.borrow().media.clone();
|
||||
let state = &now.state;
|
||||
// Artwork, spinning while it plays when that's on.
|
||||
if !state.art.is_empty() {
|
||||
let image = f.shared.art_images.borrow().get(&state.art).cloned();
|
||||
match image {
|
||||
None => f.send(Command::FetchArt(state.art.clone())),
|
||||
Some(Some(image)) => {
|
||||
let key = state.art.clone();
|
||||
let texture = match &f.ui.art_texture {
|
||||
Some((k, t)) if *k == key => t.clone(),
|
||||
_ => {
|
||||
let t = ui.ctx().load_texture(format!("art:{key}"), image, egui::TextureOptions::LINEAR);
|
||||
f.ui.art_texture = Some((key, t.clone()));
|
||||
t
|
||||
},
|
||||
};
|
||||
let spin = settings.spin && !state.paused && !crate::perf::still(&f.shared.settings.borrow());
|
||||
let angle = if spin { (ui.input(|i| i.time) * 0.3) as f32 % std::f32::consts::TAU } else { 0.0 };
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add(egui::Image::new(&texture).fit_to_exact_size(Vec2::splat(140.0)).corner_radius(70).rotate(angle, Vec2::splat(0.5)));
|
||||
});
|
||||
if spin {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
},
|
||||
Some(None) => {},
|
||||
}
|
||||
}
|
||||
ui.label(RichText::new(util::ellipsize(if state.title.is_empty() { &now.title } else { &state.title }, 60)).strong());
|
||||
let by = if state.artist.is_empty() { now.host.clone() } else { state.artist.clone() };
|
||||
ui.label(RichText::new(by).weak());
|
||||
// Visualizer.
|
||||
if settings.visualizer != Visualizer::Off && !state.paused {
|
||||
let time = ui.input(|i| i.time);
|
||||
let target = f.shared.cava.borrow().levels().unwrap_or_else(|| crate::media::simulated_levels(time));
|
||||
let dt = ui.input(|i| i.stable_dt).min(0.1);
|
||||
crate::media::ease_levels(&mut f.ui.levels, &target, dt);
|
||||
let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), 36.0), egui::Sense::hover());
|
||||
let n = f.ui.levels.len().max(1);
|
||||
let w = rect.width() / n as f32;
|
||||
for (i, level) in f.ui.levels.iter().enumerate() {
|
||||
let h = (level * rect.height()).max(2.0);
|
||||
let bar = egui::Rect::from_min_max(egui::pos2(rect.left() + i as f32 * w + 1.0, rect.bottom() - h), egui::pos2(rect.left() + (i + 1) as f32 * w - 1.0, rect.bottom()));
|
||||
ui.painter().rect_filled(bar, 2.0, f.palette().accent);
|
||||
}
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
// Position.
|
||||
if state.duration > 0.0 {
|
||||
let pos = state.position_at(now.received_ms);
|
||||
let mut value = f.ui.media_seek.unwrap_or(pos as f32);
|
||||
let response = ui.add(egui::Slider::new(&mut value, 0.0..=state.duration as f32).show_value(false));
|
||||
if response.dragged() {
|
||||
f.ui.media_seek = Some(value);
|
||||
}
|
||||
if response.drag_stopped() || response.clicked() {
|
||||
f.ui.media_seek = None;
|
||||
f.send(Command::Media { tab: now.tab, action: "seek".into(), value: value as f64 });
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(util::format_media_time(pos)).small());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(RichText::new(util::format_media_time(state.duration)).small()));
|
||||
});
|
||||
if !state.paused {
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
|
||||
}
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let big = |t: &str| RichText::new(t).size(18.0);
|
||||
if ui.button(big("⏮")).on_hover_text("Previous").clicked() {
|
||||
f.send(Command::Media { tab: now.tab, action: "prev".into(), value: 0.0 });
|
||||
}
|
||||
if ui.button(big(if state.paused { "▶" } else { "⏸" })).clicked() {
|
||||
f.send(Command::Media { tab: now.tab, action: "toggle".into(), value: 0.0 });
|
||||
}
|
||||
if ui.button(big("⏭")).on_hover_text("Next").clicked() {
|
||||
f.send(Command::Media { tab: now.tab, action: "next".into(), value: 0.0 });
|
||||
}
|
||||
if ui.button(big(if now.muted { "🔇" } else { "🔊" })).on_hover_text("Mute tab").clicked() {
|
||||
f.send(Command::MuteTab(now.tab));
|
||||
}
|
||||
if state.is_video && ui.button(big("⧉")).on_hover_text("Picture in picture").clicked() {
|
||||
if let Some(i) = f.tabs.iter().position(|t| t.id == now.tab) {
|
||||
f.send(Command::SelectTab(i));
|
||||
}
|
||||
f.send(Command::EnterPip);
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
if ui.small_button("Go to tab").clicked() {
|
||||
if let Some(i) = f.tabs.iter().position(|t| t.id == now.tab) {
|
||||
f.send(Command::SelectTab(i));
|
||||
}
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
let muted_site = f.shared.settings.borrow().site_muted(&now.host);
|
||||
if ui.small_button(if muted_site { "Unmute site" } else { "Mute site" }).clicked() {
|
||||
f.send(Command::ToggleMuteSite(now.host.clone()));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn site_info(ui: &mut Ui, f: &mut Frame) {
|
||||
ui.set_width(330.0);
|
||||
let Some(tab) = f.tab() else { return };
|
||||
let host = tab.host();
|
||||
let url = tab.url.clone();
|
||||
let secure = url.starts_with("https://");
|
||||
ui.label(RichText::new(&host).strong());
|
||||
ui.label(if secure { "🔒 The connection is secure" } else { "⚠ The connection is not secure: others on the network can see and change this page" });
|
||||
ui.separator();
|
||||
ui.label(RichText::new("Permissions").strong());
|
||||
let decisions = f.shared.permissions.borrow().for_host(&host);
|
||||
if decisions.is_empty() {
|
||||
ui.label(RichText::new("This site hasn't asked for anything.").weak().small());
|
||||
}
|
||||
for (kind, decision) in decisions {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(kind.label());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.small_button("Reset").clicked() {
|
||||
f.shared.permissions.borrow_mut().set(&host, kind, None);
|
||||
}
|
||||
let mut allow = decision == crate::store::permissions::Decision::Allow;
|
||||
if switch(ui, &mut allow) {
|
||||
f.shared.permissions.borrow_mut().set(&host, kind, Some(if allow { crate::store::permissions::Decision::Allow } else { crate::store::permissions::Decision::Block }));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
ui.separator();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button("Site settings").clicked() {
|
||||
f.send(Command::ShowPage(Page::SiteSettings(host.clone())));
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
if ui.button("Delete data for this site").clicked() {
|
||||
f.send(Command::ClearSiteData(host.clone()));
|
||||
}
|
||||
if ui.button("Install as app").clicked() {
|
||||
f.send(Command::InstallApp);
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn profiles(ui: &mut Ui, f: &mut Frame) {
|
||||
ui.set_width(240.0);
|
||||
let list = f.shared.paths.profile_list();
|
||||
ui.label(RichText::new(format!("Profile: {}", f.shared.paths.profile)).strong());
|
||||
if f.incognito() {
|
||||
ui.label(RichText::new("Incognito: nothing from this window is saved.").weak().small());
|
||||
}
|
||||
ui.separator();
|
||||
for name in list.profiles {
|
||||
if name == f.shared.paths.profile {
|
||||
continue;
|
||||
}
|
||||
if ui.button(format!("Open {name}")).clicked() {
|
||||
f.send(Command::SwitchProfile(name));
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
}
|
||||
if ui.button("Manage profiles").clicked() {
|
||||
f.send(Command::ShowPage(Page::Settings("profiles".into())));
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn edit_bookmark(ui: &mut Ui, f: &mut Frame, url: &str) {
|
||||
ui.set_width(320.0);
|
||||
let Some(node) = f.shared.bookmarks.borrow().find_url(url).cloned() else {
|
||||
f.ui.flyout = None;
|
||||
return;
|
||||
};
|
||||
ui.label(RichText::new("Bookmark added").strong());
|
||||
let id = egui::Id::new(("bookmark-title", node.id));
|
||||
let mut title = ui.data_mut(|d| d.get_temp::<String>(id)).unwrap_or_else(|| node.title.clone());
|
||||
ui.add(egui::TextEdit::singleline(&mut title).desired_width(300.0));
|
||||
ui.data_mut(|d| d.insert_temp(id, title.clone()));
|
||||
// Folder: the bar, other bookmarks, or any folder.
|
||||
let folders = folder_list(&f.shared.bookmarks.borrow());
|
||||
let current_parent = parent_of(&f.shared.bookmarks.borrow(), node.id);
|
||||
let mut parent = current_parent;
|
||||
egui::ComboBox::from_id_salt("bookmark-folder").width(300.0).selected_text(folders.iter().find(|(id, _)| *id == parent).map(|(_, n)| n.clone()).unwrap_or_default()).show_ui(ui, |ui| {
|
||||
for (id, name) in &folders {
|
||||
ui.selectable_value(&mut parent, *id, name);
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Remove").clicked() {
|
||||
f.shared.bookmarks.borrow_mut().remove(node.id);
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
if ui.button("Done").clicked() {
|
||||
let mut b = f.shared.bookmarks.borrow_mut();
|
||||
b.edit(node.id, &title, None);
|
||||
if parent != current_parent {
|
||||
b.move_to(node.id, parent, None);
|
||||
}
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// (folder id, "Bar / Sub") for every folder.
|
||||
pub fn folder_list(b: &crate::store::bookmarks::Bookmarks) -> Vec<(u64, String)> {
|
||||
fn walk(node: &crate::store::bookmarks::Node, prefix: &str, out: &mut Vec<(u64, String)>) {
|
||||
let name = if prefix.is_empty() { node.title.clone() } else { format!("{prefix} / {}", node.title) };
|
||||
out.push((node.id, name.clone()));
|
||||
for child in node.children.iter().filter(|c| c.is_folder()) {
|
||||
walk(child, &name, out);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(&b.bar, "", &mut out);
|
||||
walk(&b.other, "", &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
pub fn parent_of(b: &crate::store::bookmarks::Bookmarks, id: u64) -> u64 {
|
||||
fn find(node: &crate::store::bookmarks::Node, id: u64) -> Option<u64> {
|
||||
if node.children.iter().any(|c| c.id == id) {
|
||||
return Some(node.id);
|
||||
}
|
||||
node.children.iter().find_map(|c| find(c, id))
|
||||
}
|
||||
find(&b.bar, id).or_else(|| find(&b.other, id)).unwrap_or(crate::store::bookmarks::BAR)
|
||||
}
|
||||
|
||||
fn qr(ui: &mut Ui, f: &mut Frame, url: &str) {
|
||||
let key = format!("qr:{url}");
|
||||
let texture = match &f.ui.qr_texture {
|
||||
Some((k, t)) if *k == key => Some(t.clone()),
|
||||
_ => qr_image(url).map(|image| {
|
||||
let t = ui.ctx().load_texture(key.clone(), image, egui::TextureOptions::NEAREST);
|
||||
f.ui.qr_texture = Some((key.clone(), t.clone()));
|
||||
t
|
||||
}),
|
||||
};
|
||||
ui.label(RichText::new("Scan to open this page").strong());
|
||||
match texture {
|
||||
Some(texture) => {
|
||||
ui.add(egui::Image::new(&texture).fit_to_exact_size(Vec2::splat(220.0)));
|
||||
},
|
||||
None => {
|
||||
ui.label("This address is too long for a QR code.");
|
||||
},
|
||||
}
|
||||
ui.label(RichText::new(util::ellipsize(url, 60)).small().weak());
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Copy address").clicked() {
|
||||
ui.ctx().copy_text(url.to_owned());
|
||||
}
|
||||
if ui.button("Save as PNG").clicked()
|
||||
&& let Some(png) = qr_png(url)
|
||||
{
|
||||
std::thread::spawn(move || {
|
||||
if let Some(path) = rfd::FileDialog::new().set_file_name("qr-code.png").save_file() {
|
||||
let _ = std::fs::write(path, png);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn qr_modules(url: &str) -> Option<(usize, Vec<bool>)> {
|
||||
let code = qrcode::QrCode::new(url.as_bytes()).ok()?;
|
||||
let width = code.width();
|
||||
let dark = code.to_colors().into_iter().map(|c| c == qrcode::Color::Dark).collect();
|
||||
Some((width, dark))
|
||||
}
|
||||
|
||||
fn qr_image(url: &str) -> Option<egui::ColorImage> {
|
||||
let (width, dark) = qr_modules(url)?;
|
||||
let border = 2;
|
||||
let size = width + border * 2;
|
||||
let mut pixels = vec![Color32::WHITE; size * size];
|
||||
for y in 0..width {
|
||||
for x in 0..width {
|
||||
if dark[y * width + x] {
|
||||
pixels[(y + border) * size + x + border] = Color32::BLACK;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(egui::ColorImage::new([size, size], pixels))
|
||||
}
|
||||
|
||||
fn qr_png(url: &str) -> Option<Vec<u8>> {
|
||||
let (width, dark) = qr_modules(url)?;
|
||||
let scale = 8u32;
|
||||
let border = 4u32;
|
||||
let size = (width as u32 + border * 2) * scale;
|
||||
let image = image::RgbaImage::from_fn(size, size, |x, y| {
|
||||
let mx = (x / scale) as i64 - border as i64;
|
||||
let my = (y / scale) as i64 - border as i64;
|
||||
let on = mx >= 0 && my >= 0 && (mx as usize) < width && (my as usize) < width && dark[my as usize * width + mx as usize];
|
||||
if on { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([255, 255, 255, 255]) }
|
||||
});
|
||||
let mut png = Vec::new();
|
||||
image.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
Some(png)
|
||||
}
|
||||
|
||||
fn tab_menu(ui: &mut Ui, f: &mut Frame, id: u64) {
|
||||
let Some(tab) = f.tabs.iter().find(|t| t.id == id) else {
|
||||
f.ui.flyout = None;
|
||||
return;
|
||||
};
|
||||
let (pinned, muted) = (tab.pinned, tab.muted);
|
||||
let mut run = None;
|
||||
if item(ui, "New tab to the right", "") {
|
||||
run = Some(Command::NewTab);
|
||||
}
|
||||
if item(ui, "Reload", "") {
|
||||
run = Some(Command::ReloadTab(id));
|
||||
}
|
||||
if item(ui, "Duplicate", "") {
|
||||
run = Some(Command::DuplicateTab(id));
|
||||
}
|
||||
if item(ui, if pinned { "Unpin" } else { "Pin" }, "") {
|
||||
run = Some(Command::PinTab(id));
|
||||
}
|
||||
if item(ui, if muted { "Unmute tab" } else { "Mute tab" }, "") {
|
||||
run = Some(Command::MuteTab(id));
|
||||
}
|
||||
if item(ui, "Move to new window", "") {
|
||||
run = Some(Command::MoveTabToNewWindow(id));
|
||||
}
|
||||
ui.separator();
|
||||
if item(ui, "Close", "") {
|
||||
run = Some(Command::CloseTab(id));
|
||||
}
|
||||
if item(ui, "Close other tabs", "") {
|
||||
run = Some(Command::CloseOtherTabs(id));
|
||||
}
|
||||
if item(ui, "Close tabs to the right", "") {
|
||||
run = Some(Command::CloseTabsRight(id));
|
||||
}
|
||||
ui.separator();
|
||||
if item(ui, "Reopen closed tab", "") {
|
||||
run = Some(Command::ReopenClosed(None));
|
||||
}
|
||||
if item(ui, "Bookmark all tabs", "") {
|
||||
run = Some(Command::BookmarkAllTabs);
|
||||
}
|
||||
if let Some(command) = run {
|
||||
f.ui.flyout = None;
|
||||
f.send(command);
|
||||
}
|
||||
}
|
||||
|
||||
fn bookmark_menu(ui: &mut Ui, f: &mut Frame, id: u64) {
|
||||
let Some(node) = f.shared.bookmarks.borrow().get(id).cloned() else {
|
||||
f.ui.flyout = None;
|
||||
return;
|
||||
};
|
||||
let mut run = None;
|
||||
if let Some(url) = &node.url {
|
||||
if item(ui, "Open in new tab", "") {
|
||||
run = Some(Command::Open { url: url.clone(), how: Disposition::NewForegroundTab, from: None });
|
||||
}
|
||||
if item(ui, "Open in new window", "") {
|
||||
run = Some(Command::Open { url: url.clone(), how: Disposition::NewWindow, from: None });
|
||||
}
|
||||
if item(ui, "Open in incognito window", "") {
|
||||
run = Some(Command::Open { url: url.clone(), how: Disposition::Incognito, from: None });
|
||||
}
|
||||
if item(ui, "Copy address", "") {
|
||||
ui.ctx().copy_text(url.clone());
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
}
|
||||
if item(ui, "Edit in the bookmark manager", "") {
|
||||
run = Some(Command::ShowPage(Page::Bookmarks));
|
||||
}
|
||||
if item(ui, "Delete", "") {
|
||||
f.shared.bookmarks.borrow_mut().remove(id);
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
if let Some(command) = run {
|
||||
f.ui.flyout = None;
|
||||
f.send(command);
|
||||
}
|
||||
}
|
||||
|
||||
fn back_history(ui: &mut Ui, f: &mut Frame) {
|
||||
let Some(tab) = f.tab() else { return };
|
||||
let entries: Vec<(usize, String)> = tab.back_forward.iter().enumerate().take(tab.history_index).rev().take(15).map(|(i, u)| (i, u.to_string())).collect();
|
||||
if entries.is_empty() {
|
||||
ui.label(RichText::new("No earlier pages").weak());
|
||||
}
|
||||
for (i, url) in entries {
|
||||
let title = f.shared.history.borrow().search(&url, 1).first().map(|v| v.title.clone()).filter(|t| !t.is_empty()).unwrap_or_else(|| url.clone());
|
||||
if item(ui, &util::ellipsize(&title, 50), "") {
|
||||
f.send(Command::HistoryJump(i));
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if item(ui, "Show full history", "") {
|
||||
f.send(Command::ShowPage(Page::History));
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn apps(ui: &mut Ui, f: &mut Frame) {
|
||||
let apps = f.shared.apps.borrow().items.clone();
|
||||
if apps.is_empty() {
|
||||
ui.label(RichText::new("No apps yet. Install a site from the menu.").weak());
|
||||
}
|
||||
for app in apps {
|
||||
if item(ui, &app.name, &app.scope) {
|
||||
f.send(Command::OpenApp(app.id.clone()));
|
||||
f.ui.flyout = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
264
src/ui/mod.rs
Normal file
264
src/ui/mod.rs
Normal file
|
|
@ -0,0 +1,264 @@
|
|||
//! The browser interface, drawn with egui. Plain on purpose for now: everything works, the
|
||||
//! designed look comes later. Drawing code reads the shared stores, may edit simple things
|
||||
//! (settings, bookmarks, history) directly, and asks the app for everything else with `Command`s.
|
||||
|
||||
pub mod chrome;
|
||||
pub mod dialogs;
|
||||
pub mod menus;
|
||||
pub mod pages;
|
||||
pub mod widgets;
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use egui::{Align2, Color32, RichText};
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::actions::Command;
|
||||
use crate::app::Shared;
|
||||
use crate::hub::Hub;
|
||||
use crate::tabs::Tab;
|
||||
use crate::theme::Palette;
|
||||
use crate::window::Kind;
|
||||
|
||||
/// Small windows that open from the toolbar and menus.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Flyout {
|
||||
Main,
|
||||
Downloads,
|
||||
Shield,
|
||||
Vpn,
|
||||
Media,
|
||||
SiteInfo,
|
||||
Profiles,
|
||||
EditBookmark(String),
|
||||
Qr(String),
|
||||
TabMenu(u64, egui::Pos2),
|
||||
BookmarkMenu(u64, egui::Pos2),
|
||||
BackHistory(egui::Pos2),
|
||||
Apps,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct WindowUi {
|
||||
pub palette: Option<Palette>,
|
||||
/// Address bar text while the user edits it (None = show the page's URL).
|
||||
pub omnibox_edit: Option<String>,
|
||||
pub focus_omnibox: bool,
|
||||
pub omnibox_focused: bool,
|
||||
pub suggestion_index: Option<usize>,
|
||||
pub flyout: Option<Flyout>,
|
||||
/// Where the last flyout button was, to place the flyout under it.
|
||||
pub flyout_anchor: Option<egui::Rect>,
|
||||
pub ime_control: Option<servo::EmbedderControlId>,
|
||||
/// The web tab developer tools look at.
|
||||
pub devtools_target: Option<u64>,
|
||||
pub pages: pages::PageState,
|
||||
/// Tab being dragged in the tab strip: (tab id, grab offset x).
|
||||
pub dragging_tab: Option<(u64, f32)>,
|
||||
pub qr_texture: Option<(String, egui::TextureHandle)>,
|
||||
pub art_texture: Option<(String, egui::TextureHandle)>,
|
||||
/// Visualizer bars shown in the media flyout.
|
||||
pub levels: Vec<f32>,
|
||||
pub last_level_poll: f64,
|
||||
pub media_seek: Option<f32>,
|
||||
/// Address bar suggestions for `omnibox_query`.
|
||||
pub omnibox_query: String,
|
||||
pub omnibox_items: Vec<chrome::Suggestion>,
|
||||
}
|
||||
|
||||
impl WindowUi {
|
||||
pub fn close_popups(&mut self) {
|
||||
self.flyout = None;
|
||||
self.suggestion_index = None;
|
||||
}
|
||||
|
||||
/// A flyout is open: the first click on the page closes it instead of reaching the page.
|
||||
pub fn blocks_page(&self) -> bool {
|
||||
self.flyout.is_some()
|
||||
}
|
||||
|
||||
pub fn has_popup(&self) -> bool {
|
||||
self.flyout.is_some() || self.omnibox_focused
|
||||
}
|
||||
|
||||
pub fn palette(&self) -> Palette {
|
||||
self.palette.unwrap_or_else(|| Palette::new(Color32::from_rgb(0x67, 0x50, 0xA4), true, "tonal_spot", 0.0))
|
||||
}
|
||||
|
||||
pub fn toggle(&mut self, flyout: Flyout, anchor: Option<egui::Rect>) {
|
||||
if self.flyout.as_ref() == Some(&flyout) {
|
||||
self.flyout = None;
|
||||
} else {
|
||||
self.flyout = Some(flyout);
|
||||
self.flyout_anchor = anchor;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a frame of drawing works with.
|
||||
pub struct Frame<'a> {
|
||||
pub shared: &'a Rc<Shared>,
|
||||
pub hub: &'a Rc<Hub>,
|
||||
pub tabs: &'a mut Vec<Tab>,
|
||||
pub active: &'a mut usize,
|
||||
pub ui: &'a mut WindowUi,
|
||||
pub page_rect: &'a mut Option<egui::Rect>,
|
||||
pub kind: &'a Kind,
|
||||
pub fullscreen: bool,
|
||||
pub pip_frame: Option<&'a egui::TextureHandle>,
|
||||
pub pip_size: [u32; 2],
|
||||
pub commands: &'a mut Vec<Command>,
|
||||
pub window_id: WindowId,
|
||||
}
|
||||
|
||||
impl Frame<'_> {
|
||||
pub fn send(&mut self, command: Command) {
|
||||
self.commands.push(command);
|
||||
}
|
||||
|
||||
pub fn tab(&self) -> Option<&Tab> {
|
||||
self.tabs.get(*self.active)
|
||||
}
|
||||
|
||||
pub fn tab_mut(&mut self) -> Option<&mut Tab> {
|
||||
self.tabs.get_mut(*self.active)
|
||||
}
|
||||
|
||||
pub fn palette(&self) -> Palette {
|
||||
self.ui.palette()
|
||||
}
|
||||
|
||||
pub fn incognito(&self) -> bool {
|
||||
self.shared.incognito
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw(root: &mut egui::Ui, f: &mut Frame) {
|
||||
let ctx = root.ctx().clone();
|
||||
if let Kind::Pip { .. } = f.kind {
|
||||
chrome::pip_window(root, f);
|
||||
return;
|
||||
}
|
||||
let app_window = matches!(f.kind, Kind::App(_));
|
||||
let page_fullscreen = f.fullscreen && f.tab().is_some_and(|t| t.fullscreen);
|
||||
if !page_fullscreen {
|
||||
let custom_title = f.shared.settings.borrow().ui.custom_title_bar && *f.kind == Kind::Normal;
|
||||
if custom_title {
|
||||
chrome::title_bar(root, f);
|
||||
}
|
||||
if app_window {
|
||||
chrome::app_bar(root, f);
|
||||
} else {
|
||||
chrome::tab_strip(root, f);
|
||||
chrome::toolbar(root, f);
|
||||
if chrome::bookmarks_bar_visible(f) {
|
||||
chrome::bookmarks_bar(root, f);
|
||||
}
|
||||
}
|
||||
dialogs::prompt_bars(root, f);
|
||||
dialogs::find_bar(root, f);
|
||||
}
|
||||
let floating = f.shared.settings.borrow().ui.floating_card && !page_fullscreen && !app_window;
|
||||
let frame = egui::Frame::NONE.inner_margin(if floating { egui::Margin::symmetric(8, 6) } else { egui::Margin::ZERO });
|
||||
egui::CentralPanel::no_frame().frame(frame).show(root, |ui| page_area(ui, f, floating));
|
||||
dialogs::page_dialogs(&ctx, f);
|
||||
menus::flyouts(&ctx, f);
|
||||
toasts(&ctx, f);
|
||||
}
|
||||
|
||||
/// The page itself: a web page's framebuffer, or one of Nacre's pages.
|
||||
fn page_area(ui: &mut egui::Ui, f: &mut Frame, floating: bool) {
|
||||
let rect = ui.max_rect();
|
||||
let Some(tab) = f.tabs.get(*f.active) else {
|
||||
*f.page_rect = None;
|
||||
return;
|
||||
};
|
||||
if let Some(page) = tab.page.clone() {
|
||||
*f.page_rect = None;
|
||||
egui::Frame::NONE.fill(f.palette().surface_low).corner_radius(if floating { crate::theme::corner(&f.shared.settings.borrow()) } else { 0 }).show(ui, |ui| {
|
||||
ui.set_min_size(rect.size());
|
||||
pages::draw(ui, f, &page);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if tab.pip_size.is_some() {
|
||||
*f.page_rect = None;
|
||||
ui.centered_and_justified(|ui| {
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add_space(rect.height() * 0.35);
|
||||
ui.label(RichText::new("Playing in picture in picture").size(18.0));
|
||||
if ui.button("Bring it back").clicked() {
|
||||
let tab_id = f.tabs[*f.active].id;
|
||||
f.send(Command::ClosePip(tab_id));
|
||||
}
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
if let Some(reason) = tab.crashed.clone() {
|
||||
*f.page_rect = None;
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add_space(rect.height() * 0.25);
|
||||
ui.heading("This page crashed");
|
||||
ui.label("Something on the page broke the engine. Reloading usually fixes it.");
|
||||
ui.add_space(8.0);
|
||||
if ui.button("Reload").clicked() {
|
||||
f.send(Command::CrashReload);
|
||||
}
|
||||
ui.collapsing("Details", |ui| {
|
||||
ui.monospace(reason);
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
*f.page_rect = Some(rect);
|
||||
match tab.web.as_ref() {
|
||||
Some(web) => {
|
||||
if let Some(callback) = crate::window::page_callback(rect, &web.context) {
|
||||
ui.painter().add(callback);
|
||||
}
|
||||
// Status text (link targets) at the bottom left, like other browsers.
|
||||
if let Some(status) = tab.status_text.as_ref().filter(|s| !s.is_empty()) {
|
||||
let text = crate::util::ellipsize(status, 120);
|
||||
let galley = ui.painter().layout_no_wrap(text, egui::FontId::proportional(12.0), f.palette().text);
|
||||
let r = egui::Rect::from_min_size(rect.left_bottom() - egui::vec2(0.0, galley.size().y + 6.0), galley.size() + egui::vec2(12.0, 6.0));
|
||||
ui.painter().rect_filled(r, 4.0, f.palette().surface_high);
|
||||
ui.painter().galley(r.min + egui::vec2(6.0, 3.0), galley, f.palette().text);
|
||||
}
|
||||
},
|
||||
None => {
|
||||
ui.painter().rect_filled(rect, 0.0, f.palette().surface_low);
|
||||
ui.put(egui::Rect::from_center_size(rect.center(), egui::vec2(40.0, 40.0)), egui::Spinner::new());
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn toasts(ctx: &egui::Context, f: &mut Frame) {
|
||||
let toasts: Vec<(String, Option<(String, Command)>)> = f.shared.toasts.borrow().iter().map(|t| (t.text.clone(), t.action.clone())).collect();
|
||||
if toasts.is_empty() {
|
||||
return;
|
||||
}
|
||||
let palette = f.palette();
|
||||
egui::Area::new(egui::Id::new("toasts")).anchor(Align2::CENTER_BOTTOM, egui::vec2(0.0, -16.0)).order(egui::Order::Tooltip).show(ctx, |ui| {
|
||||
for (i, (text, action)) in toasts.iter().enumerate() {
|
||||
egui::Frame::popup(ui.style()).fill(palette.surface_high).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(text);
|
||||
if let Some((label, command)) = action
|
||||
&& ui.button(label).clicked()
|
||||
{
|
||||
f.commands.push(command.clone());
|
||||
if let Some(t) = f.shared.toasts.borrow_mut().get_mut(i) {
|
||||
t.until = std::time::Instant::now();
|
||||
}
|
||||
}
|
||||
if ui.small_button("✕").clicked()
|
||||
&& let Some(t) = f.shared.toasts.borrow_mut().get_mut(i)
|
||||
{
|
||||
t.until = std::time::Instant::now();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
132
src/ui/pages/apps.rs
Normal file
132
src/ui/pages/apps.rs
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
//! nacre://apps — sites installed as apps, and user scripts and styles (Nacre's stand-in for
|
||||
//! extensions: Servo can't run Chrome extensions).
|
||||
|
||||
use egui::{RichText, Ui};
|
||||
|
||||
use super::super::widgets::{card, page_column, switch};
|
||||
use super::super::Frame;
|
||||
use crate::actions::Command;
|
||||
use crate::store::scripts::{self, Kind};
|
||||
use crate::util;
|
||||
|
||||
const NEW_SCRIPT: &str = "// ==UserScript==\n// @name My script\n// @match https://example.com/*\n// @run-at document-end\n// ==/UserScript==\n\n";
|
||||
|
||||
pub fn draw(ui: &mut Ui, f: &mut Frame) {
|
||||
page_column(ui, "apps", 900.0, |ui| {
|
||||
ui.heading("Apps");
|
||||
ui.label(RichText::new("Sites installed as apps open in their own window and have a launcher entry.").weak());
|
||||
let apps = f.shared.apps.borrow().items.clone();
|
||||
card(ui, |ui| {
|
||||
if apps.is_empty() {
|
||||
ui.label(RichText::new("No apps yet. Open a site and choose “Install this site as an app” from the menu.").weak());
|
||||
}
|
||||
for app in apps {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(&app.name).strong());
|
||||
ui.label(RichText::new(&app.scope).weak().small());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.small_button("Remove").clicked() {
|
||||
f.send(Command::UninstallApp(app.id.clone()));
|
||||
}
|
||||
let mut launcher = app.launcher;
|
||||
if switch(ui, &mut launcher) {
|
||||
f.send(Command::SetAppLauncher { id: app.id.clone(), on: launcher });
|
||||
}
|
||||
ui.label(RichText::new("Launcher entry").small());
|
||||
if ui.button("Open").clicked() {
|
||||
f.send(Command::OpenApp(app.id.clone()));
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
}
|
||||
if f.tab().is_some_and(|t| t.page.is_none() && t.url.starts_with("http")) && ui.button("Install the current site").clicked() {
|
||||
f.send(Command::InstallApp);
|
||||
}
|
||||
});
|
||||
ui.add_space(16.0);
|
||||
ui.heading("Scripts and styles");
|
||||
ui.label(RichText::new("User scripts (.user.js) and user styles (.user.css) change sites the way extensions do. They run on matching pages from their next load. Opening a .user.js link offers to install it.").weak());
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::TextEdit::singleline(&mut f.ui.pages.script_url).hint_text("https://…/script.user.js").desired_width(420.0));
|
||||
if ui.button("Install from address").clicked() && f.ui.pages.script_url.starts_with("http") {
|
||||
let url = std::mem::take(&mut f.ui.pages.script_url);
|
||||
f.send(Command::InstallScript(url));
|
||||
}
|
||||
if ui.button("New script").clicked() {
|
||||
f.ui.pages.script_edit = Some((0, NEW_SCRIPT.to_owned()));
|
||||
}
|
||||
if ui.button("New style").clicked() {
|
||||
f.ui.pages.script_edit = Some((u64::MAX, "/* ==UserStyle==\n@name My style\n@match https://example.com/*\n==/UserStyle== */\n\n".to_owned()));
|
||||
}
|
||||
});
|
||||
if let Some((id, mut source)) = f.ui.pages.script_edit.clone() {
|
||||
card(ui, |ui| {
|
||||
ui.add(egui::TextEdit::multiline(&mut source).code_editor().desired_rows(16).desired_width(f32::INFINITY));
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Save").clicked() {
|
||||
match id {
|
||||
0 => {
|
||||
f.shared.scripts.borrow_mut().add(Kind::Script, &source, "");
|
||||
},
|
||||
u64::MAX => {
|
||||
f.shared.scripts.borrow_mut().add(Kind::Style, &source, "");
|
||||
},
|
||||
id => f.shared.scripts.borrow_mut().set_source(id, &source),
|
||||
}
|
||||
f.ui.pages.script_edit = None;
|
||||
f.send(Command::Toast("Saved. It applies on matching pages from their next load.".into()));
|
||||
f.send(Command::ReloadScripts);
|
||||
return;
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
f.ui.pages.script_edit = None;
|
||||
return;
|
||||
}
|
||||
f.ui.pages.script_edit = Some((id, source.clone()));
|
||||
});
|
||||
});
|
||||
}
|
||||
let items = f.shared.scripts.borrow().items.clone();
|
||||
card(ui, |ui| {
|
||||
if items.is_empty() {
|
||||
ui.label(RichText::new("No scripts or styles installed.").weak());
|
||||
}
|
||||
for item in items {
|
||||
let header = item.header();
|
||||
ui.horizontal(|ui| {
|
||||
let mut on = item.enabled;
|
||||
if switch(ui, &mut on) {
|
||||
f.shared.scripts.borrow_mut().set_enabled(item.id, on);
|
||||
f.send(Command::ReloadScripts);
|
||||
}
|
||||
ui.vertical(|ui| {
|
||||
ui.label(RichText::new(format!("{} {}", if item.kind == Kind::Script { "📜" } else { "🎨" }, header.name)).strong());
|
||||
let mut detail = header.matches.join(", ");
|
||||
if !header.version.is_empty() {
|
||||
detail = format!("v{} · {detail}", header.version);
|
||||
}
|
||||
ui.label(RichText::new(util::ellipsize(&detail, 100)).weak().small());
|
||||
if !header.description.is_empty() {
|
||||
ui.label(RichText::new(util::ellipsize(&header.description, 120)).small());
|
||||
}
|
||||
});
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.small_button("Delete").clicked() {
|
||||
f.shared.scripts.borrow_mut().remove(item.id);
|
||||
f.send(Command::ReloadScripts);
|
||||
}
|
||||
if ui.small_button("Edit").clicked() {
|
||||
f.ui.pages.script_edit = Some((item.id, item.source.clone()));
|
||||
}
|
||||
if !item.origin_url.is_empty() && ui.small_button("Update").on_hover_text(&item.origin_url).clicked() {
|
||||
f.send(Command::InstallScript(item.origin_url.clone()));
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
}
|
||||
});
|
||||
let _ = scripts::pattern_to_regex;
|
||||
});
|
||||
}
|
||||
176
src/ui/pages/bookmarks.rs
Normal file
176
src/ui/pages/bookmarks.rs
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
//! nacre://bookmarks — the bookmark manager: folders, editing, moving, import and export,
|
||||
//! and the reading list.
|
||||
|
||||
use egui::{RichText, Ui};
|
||||
|
||||
use super::super::menus::{folder_list, parent_of};
|
||||
use super::super::widgets::page_column;
|
||||
use super::super::Frame;
|
||||
use crate::actions::{Command, Disposition};
|
||||
use crate::store::bookmarks::{Node, BAR};
|
||||
use crate::util;
|
||||
|
||||
pub fn draw(ui: &mut Ui, f: &mut Frame) {
|
||||
page_column(ui, "bookmarks", 900.0, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.heading("Bookmarks");
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("Export").clicked() {
|
||||
f.send(Command::ExportBookmarks);
|
||||
}
|
||||
if ui.button("Import file").clicked() {
|
||||
f.send(Command::ImportBookmarksFile);
|
||||
}
|
||||
if ui.button("Import from a browser").clicked() {
|
||||
f.send(Command::ShowPage(crate::tabs::Page::Settings("import".into())));
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add(egui::TextEdit::singleline(&mut f.ui.pages.bookmarks_search).hint_text("Search bookmarks").desired_width(f32::INFINITY));
|
||||
ui.add_space(8.0);
|
||||
let query = f.ui.pages.bookmarks_search.clone();
|
||||
if !query.trim().is_empty() {
|
||||
let found = f.shared.bookmarks.borrow().search(&query, 200);
|
||||
if found.is_empty() {
|
||||
ui.label(RichText::new("Nothing matches.").weak());
|
||||
}
|
||||
for (url, title) in found {
|
||||
if ui.link(util::ellipsize(&title, 90)).on_hover_text(&url).clicked() {
|
||||
f.send(Command::Open { url, how: Disposition::Current, from: None });
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let folders = folder_list(&f.shared.bookmarks.borrow());
|
||||
let current = f.ui.pages.bookmarks_folder.unwrap_or(BAR);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (id, name) in &folders {
|
||||
if ui.selectable_label(current == *id, format!("📁 {name}")).clicked() {
|
||||
f.ui.pages.bookmarks_folder = Some(*id);
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::TextEdit::singleline(&mut f.ui.pages.new_folder).hint_text("New folder name"));
|
||||
if ui.button("Add folder here").clicked() {
|
||||
let name = std::mem::take(&mut f.ui.pages.new_folder);
|
||||
f.shared.bookmarks.borrow_mut().add_folder(current, &name);
|
||||
}
|
||||
if let Some(tab) = f.tab().filter(|t| t.page.is_none())
|
||||
&& ui.button("Add the current page here").clicked()
|
||||
{
|
||||
let (title, url) = (tab.display_title(), tab.url.clone());
|
||||
f.shared.bookmarks.borrow_mut().add(current, &title, &url);
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
let node: Option<Node> = f.shared.bookmarks.borrow().get(current).cloned();
|
||||
let Some(node) = node else { return };
|
||||
if node.children.is_empty() {
|
||||
ui.label(RichText::new("This folder is empty.").weak());
|
||||
}
|
||||
let count = node.children.len();
|
||||
for (index, child) in node.children.iter().enumerate() {
|
||||
bookmark_row(ui, f, child, current, index, count, &folders);
|
||||
}
|
||||
// Reading list.
|
||||
ui.add_space(16.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new("Reading list").strong());
|
||||
if let Some(tab) = f.tab().filter(|t| t.page.is_none())
|
||||
&& ui.small_button("Add the current page").clicked()
|
||||
{
|
||||
let (url, title) = (tab.url.clone(), tab.display_title());
|
||||
f.shared.reading.borrow_mut().add(&url, &title);
|
||||
}
|
||||
});
|
||||
let items: Vec<crate::store::bookmarks::ReadingItem> = f.shared.reading.borrow().items.clone();
|
||||
if items.is_empty() {
|
||||
ui.label(RichText::new("Pages saved for later show here.").weak());
|
||||
}
|
||||
for item in items {
|
||||
ui.horizontal(|ui| {
|
||||
let text = if item.read { RichText::new(util::ellipsize(&item.title, 80)).weak() } else { RichText::new(util::ellipsize(&item.title, 80)) };
|
||||
if ui.link(text).on_hover_text(&item.url).clicked() {
|
||||
f.shared.reading.borrow_mut().set_read(&item.url, true);
|
||||
f.send(Command::Navigate(item.url.clone()));
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.small_button("Remove").clicked() {
|
||||
f.shared.reading.borrow_mut().remove(&item.url);
|
||||
}
|
||||
if ui.small_button(if item.read { "Mark unread" } else { "Mark read" }).clicked() {
|
||||
f.shared.reading.borrow_mut().set_read(&item.url, !item.read);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn bookmark_row(ui: &mut Ui, f: &mut Frame, node: &Node, parent: u64, index: usize, count: usize, folders: &[(u64, String)]) {
|
||||
let editing = f.ui.pages.bookmark_edit.as_ref().is_some_and(|(id, ..)| *id == node.id);
|
||||
if editing {
|
||||
let (id, mut title, mut url) = f.ui.pages.bookmark_edit.clone().expect("checked");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::TextEdit::singleline(&mut title).desired_width(200.0));
|
||||
if node.url.is_some() {
|
||||
ui.add(egui::TextEdit::singleline(&mut url).desired_width(360.0));
|
||||
}
|
||||
if ui.button("Save").clicked() {
|
||||
f.shared.bookmarks.borrow_mut().edit(id, &title, node.url.as_ref().map(|_| url.as_str()));
|
||||
f.ui.pages.bookmark_edit = None;
|
||||
return;
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
f.ui.pages.bookmark_edit = None;
|
||||
return;
|
||||
}
|
||||
f.ui.pages.bookmark_edit = Some((id, title, url));
|
||||
});
|
||||
return;
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
match &node.url {
|
||||
Some(url) => {
|
||||
let r = ui.link(util::ellipsize(&node.title, 60)).on_hover_text(url);
|
||||
if r.clicked() {
|
||||
f.send(Command::Open { url: url.clone(), how: Disposition::Current, from: None });
|
||||
}
|
||||
if r.middle_clicked() {
|
||||
f.send(Command::Open { url: url.clone(), how: Disposition::NewBackgroundTab, from: None });
|
||||
}
|
||||
ui.label(RichText::new(util::host_of_str(url)).weak().small());
|
||||
},
|
||||
None => {
|
||||
if ui.link(format!("📁 {}", node.title)).clicked() {
|
||||
f.ui.pages.bookmarks_folder = Some(node.id);
|
||||
}
|
||||
ui.label(RichText::new(format!("{} items", node.children.len())).weak().small());
|
||||
},
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.small_button("Delete").clicked() {
|
||||
f.shared.bookmarks.borrow_mut().remove(node.id);
|
||||
}
|
||||
if ui.small_button("Edit").clicked() {
|
||||
f.ui.pages.bookmark_edit = Some((node.id, node.title.clone(), node.url.clone().unwrap_or_default()));
|
||||
}
|
||||
ui.menu_button("Move to", |ui| {
|
||||
for (id, name) in folders {
|
||||
if *id != node.id && *id != parent && ui.button(name).clicked() {
|
||||
f.shared.bookmarks.borrow_mut().move_to(node.id, *id, None);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
if index + 1 < count && ui.small_button("⬇").clicked() {
|
||||
f.shared.bookmarks.borrow_mut().move_to(node.id, parent, Some(index + 1));
|
||||
}
|
||||
if index > 0 && ui.small_button("⬆").clicked() {
|
||||
f.shared.bookmarks.borrow_mut().move_to(node.id, parent, Some(index - 1));
|
||||
}
|
||||
});
|
||||
});
|
||||
let _ = parent_of;
|
||||
}
|
||||
105
src/ui/pages/devtools.rs
Normal file
105
src/ui/pages/devtools.rs
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
//! nacre://devtools — a small set of developer tools for a tab: its console (with evaluation),
|
||||
//! the requests it made (and which were blocked), and the page's current HTML. Full tools are
|
||||
//! available through Firefox's remote debugging (Settings → Privacy).
|
||||
|
||||
use egui::{RichText, Ui};
|
||||
|
||||
use super::super::Frame;
|
||||
use crate::actions::Command;
|
||||
use crate::util;
|
||||
|
||||
pub fn draw(ui: &mut Ui, f: &mut Frame) {
|
||||
let target = f.ui.devtools_target.and_then(|id| f.tabs.iter().find(|t| t.id == id)).or_else(|| f.tabs.iter().find(|t| t.page.is_none()));
|
||||
let Some(target) = target else {
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add_space(40.0);
|
||||
ui.label("Open a web page in this window, then come back here.");
|
||||
});
|
||||
return;
|
||||
};
|
||||
let target_id = target.id;
|
||||
let target_title = target.display_title();
|
||||
let webview = target.webview_id();
|
||||
ui.horizontal(|ui| {
|
||||
ui.heading("Developer tools");
|
||||
ui.label(RichText::new(format!("for {}", util::ellipsize(&target_title, 60))).weak());
|
||||
egui::ComboBox::from_id_salt("devtools-target").selected_text("Other tab").show_ui(ui, |ui| {
|
||||
for tab in f.tabs.iter().filter(|t| t.page.is_none()) {
|
||||
if ui.selectable_label(tab.id == target_id, util::ellipsize(&tab.display_title(), 50)).clicked() {
|
||||
f.ui.devtools_target = Some(tab.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let remote = f.shared.settings.borrow().web.remote_debugging;
|
||||
if ui.button(if remote { "Remote debugging: on" } else { "Remote debugging: off" }).on_hover_text("Firefox → about:debugging → connect to localhost:6080 (restart to apply)").clicked() {
|
||||
f.send(Command::ToggleRemoteDebugging);
|
||||
}
|
||||
});
|
||||
});
|
||||
f.ui.devtools_target = Some(target_id);
|
||||
ui.horizontal(|ui| {
|
||||
for (i, name) in ["Console", "Network", "Elements"].iter().enumerate() {
|
||||
if ui.selectable_label(f.ui.pages.devtools_tab == i, *name).clicked() {
|
||||
f.ui.pages.devtools_tab = i;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
match f.ui.pages.devtools_tab {
|
||||
0 => {
|
||||
let palette = f.palette();
|
||||
let lines: Vec<(servo::ConsoleLogLevel, String, u64)> = f.tabs.iter().find(|t| t.id == target_id).map(|t| t.console.iter().map(|l| (l.level.clone(), l.text.clone(), l.time_ms)).collect()).unwrap_or_default();
|
||||
egui::ScrollArea::vertical().stick_to_bottom(true).max_height(ui.available_height() - 40.0).auto_shrink([false, false]).show(ui, |ui| {
|
||||
for (level, text, time) in lines {
|
||||
let color = match level {
|
||||
servo::ConsoleLogLevel::Error => palette.error,
|
||||
servo::ConsoleLogLevel::Warn => palette.warning,
|
||||
servo::ConsoleLogLevel::Debug | servo::ConsoleLogLevel::Trace => palette.text_weak,
|
||||
_ => palette.text,
|
||||
};
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(RichText::new(util::format_clock(time / 1000)).weak().monospace().small());
|
||||
ui.label(RichText::new(text).color(color).monospace());
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut f.ui.pages.devtools_input).hint_text("JavaScript to run in the page").code_editor().desired_width(ui.available_width() - 80.0));
|
||||
let run = ui.button("Run").clicked() || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)));
|
||||
if run && !f.ui.pages.devtools_input.trim().is_empty() {
|
||||
let script = std::mem::take(&mut f.ui.pages.devtools_input);
|
||||
f.send(Command::DevToolsEval(script));
|
||||
r.request_focus();
|
||||
}
|
||||
});
|
||||
},
|
||||
1 => {
|
||||
let entries: Vec<crate::hub::NetEntry> = webview.and_then(|id| f.hub.net_log.borrow().get(&id).map(|log| log.iter().cloned().collect())).unwrap_or_default();
|
||||
ui.label(RichText::new(format!("{} requests · {} blocked", entries.len(), entries.iter().filter(|e| e.blocked).count())).weak());
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
egui::Grid::new("net").num_columns(4).striped(true).show(ui, |ui| {
|
||||
for e in entries.iter().rev() {
|
||||
ui.label(RichText::new(&e.method).monospace());
|
||||
ui.label(RichText::new(&e.kind).weak());
|
||||
ui.label(if e.blocked { RichText::new("blocked").color(f.palette().error) } else { RichText::new("") });
|
||||
ui.label(RichText::new(util::ellipsize(&e.url, 120)).monospace().small()).on_hover_text(&e.url);
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
_ => {
|
||||
ui.label(RichText::new("The page's HTML as it is now (after scripts ran) shows in the console:").weak());
|
||||
if ui.button("Print document.documentElement.outerHTML").clicked() {
|
||||
f.send(Command::DevToolsEval("document.documentElement.outerHTML".into()));
|
||||
f.ui.pages.devtools_tab = 0;
|
||||
}
|
||||
if ui.button("View the original source").clicked()
|
||||
&& let Some(url) = f.tabs.iter().find(|t| t.id == target_id).map(|t| t.url.clone())
|
||||
{
|
||||
f.send(Command::Open { url: crate::tabs::Page::Source(url).url(), how: crate::actions::Disposition::NewForegroundTab, from: None });
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
43
src/ui/pages/downloads.rs
Normal file
43
src/ui/pages/downloads.rs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
//! nacre://downloads — every download, with search, and where they go.
|
||||
|
||||
use egui::{RichText, Ui};
|
||||
|
||||
use super::super::menus::download_row;
|
||||
use super::super::widgets::page_column;
|
||||
use super::super::Frame;
|
||||
use crate::actions::{Command, DownloadOp};
|
||||
|
||||
pub fn draw(ui: &mut Ui, f: &mut Frame) {
|
||||
page_column(ui, "downloads", 860.0, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.heading("Downloads");
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("Clear finished").clicked() {
|
||||
f.send(Command::Download(DownloadOp::ClearFinished));
|
||||
}
|
||||
if ui.button("📂 Open folder").clicked() {
|
||||
f.send(Command::Download(DownloadOp::OpenFolder));
|
||||
}
|
||||
if ui.button("Settings").clicked() {
|
||||
f.send(Command::ShowPage(crate::tabs::Page::Settings("downloads".into())));
|
||||
}
|
||||
});
|
||||
});
|
||||
let dir = f.shared.settings.borrow().downloads.dir.display().to_string();
|
||||
ui.label(RichText::new(format!("Saving to {dir}")).weak().small());
|
||||
ui.add(egui::TextEdit::singleline(&mut f.ui.pages.downloads_search).hint_text("Search downloads").desired_width(f32::INFINITY));
|
||||
ui.add_space(8.0);
|
||||
let query = f.ui.pages.downloads_search.to_lowercase();
|
||||
let items: Vec<crate::store::downloads::Download> = f.shared.downloads.borrow().items.iter().filter(|d| query.is_empty() || d.file_name().to_lowercase().contains(&query) || d.url.to_lowercase().contains(&query)).cloned().collect();
|
||||
if items.is_empty() {
|
||||
ui.label(RichText::new(if query.is_empty() { "Files you download show up here." } else { "Nothing matches." }).weak());
|
||||
}
|
||||
for d in items {
|
||||
super::super::widgets::card(ui, |ui| {
|
||||
download_row(ui, f, &d);
|
||||
ui.label(RichText::new(crate::util::ellipsize(&d.url, 110)).weak().small());
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
});
|
||||
}
|
||||
93
src/ui/pages/history.rs
Normal file
93
src/ui/pages/history.rs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
//! nacre://history — visits grouped by day, with search and deleting.
|
||||
|
||||
use egui::{RichText, Ui};
|
||||
|
||||
use super::super::widgets::page_column;
|
||||
use super::super::Frame;
|
||||
use crate::actions::{Command, Disposition};
|
||||
use crate::tabs::Page;
|
||||
use crate::util;
|
||||
|
||||
pub fn draw(ui: &mut Ui, f: &mut Frame) {
|
||||
page_column(ui, "history", 860.0, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.heading("History");
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("Delete browsing data…").clicked() {
|
||||
f.send(Command::ShowPage(Page::ClearData));
|
||||
}
|
||||
});
|
||||
});
|
||||
if f.incognito() {
|
||||
ui.label(RichText::new("Incognito windows don't keep history.").weak());
|
||||
}
|
||||
ui.add(egui::TextEdit::singleline(&mut f.ui.pages.history_search).hint_text("Search history").desired_width(f32::INFINITY));
|
||||
ui.add_space(8.0);
|
||||
let query = f.ui.pages.history_search.clone();
|
||||
let visits: Vec<crate::store::history::Visit> = f.shared.history.borrow().search(&query, 600).into_iter().cloned().collect();
|
||||
if visits.is_empty() {
|
||||
ui.label(RichText::new(if query.is_empty() { "Pages you visit show up here." } else { "Nothing matches." }).weak());
|
||||
}
|
||||
let mut last_day = i64::MIN;
|
||||
let mut remove: Option<(String, u64)> = None;
|
||||
let mut remove_host: Option<String> = None;
|
||||
for visit in &visits {
|
||||
let day = util::local_day(visit.time);
|
||||
if day != last_day {
|
||||
last_day = day;
|
||||
ui.add_space(10.0);
|
||||
ui.label(RichText::new(util::format_day_heading(visit.time)).strong());
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(util::format_clock(visit.time)).weak().monospace());
|
||||
let title = if visit.title.is_empty() { visit.url.clone() } else { visit.title.clone() };
|
||||
let r = ui.link(util::ellipsize(&title, 80)).on_hover_text(&visit.url);
|
||||
if r.clicked() {
|
||||
let new_tab = ui.input(|i| i.modifiers.command);
|
||||
f.send(Command::Open { url: visit.url.clone(), how: if new_tab { Disposition::NewBackgroundTab } else { Disposition::Current }, from: None });
|
||||
}
|
||||
if r.middle_clicked() {
|
||||
f.send(Command::Open { url: visit.url.clone(), how: Disposition::NewBackgroundTab, from: None });
|
||||
}
|
||||
ui.label(RichText::new(util::host_of_str(&visit.url)).weak().small());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.menu_button("⋮", |ui| {
|
||||
if ui.button("Open in new tab").clicked() {
|
||||
f.send(Command::Open { url: visit.url.clone(), how: Disposition::NewBackgroundTab, from: None });
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Copy address").clicked() {
|
||||
ui.ctx().copy_text(visit.url.clone());
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Remove from history").clicked() {
|
||||
remove = Some((visit.url.clone(), visit.time));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Remove everything from this site").clicked() {
|
||||
remove_host = Some(util::host_of_str(&visit.url));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
if let Some((url, time)) = remove {
|
||||
f.shared.history.borrow_mut().remove_visit(&url, time);
|
||||
}
|
||||
if let Some(host) = remove_host {
|
||||
f.shared.history.borrow_mut().remove_host(&host);
|
||||
}
|
||||
// Recently closed tabs, for quick reopening.
|
||||
let closed: Vec<(usize, String, String)> = f.shared.session.borrow().closed.iter().enumerate().take(10).map(|(i, t)| (i, t.title.clone(), t.url.clone())).collect();
|
||||
if !closed.is_empty() && query.is_empty() {
|
||||
ui.add_space(16.0);
|
||||
ui.label(RichText::new("Recently closed tabs").strong());
|
||||
for (i, title, url) in closed {
|
||||
if ui.link(util::ellipsize(if title.is_empty() { &url } else { &title }, 80)).clicked() {
|
||||
f.send(Command::ReopenClosed(Some(i)));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
352
src/ui/pages/misc.rs
Normal file
352
src/ui/pages/misc.rs
Normal file
|
|
@ -0,0 +1,352 @@
|
|||
//! Smaller pages: site settings, delete browsing data, about, first-run setup, task manager,
|
||||
//! page source, and errors.
|
||||
|
||||
use egui::{RichText, Ui};
|
||||
|
||||
use super::super::widgets::{card, page_column, row, segmented, switch, switch_row};
|
||||
use super::super::Frame;
|
||||
use crate::actions::Command;
|
||||
use crate::store::permissions::{Decision, Kind};
|
||||
use crate::store::settings::{ColourSource, DohProvider, ThemeMode};
|
||||
use crate::tabs::Page;
|
||||
use crate::util;
|
||||
|
||||
pub fn site_settings(ui: &mut Ui, f: &mut Frame, host: &str) {
|
||||
page_column(ui, "site-settings", 860.0, |ui| {
|
||||
if host.is_empty() {
|
||||
ui.heading("Site settings");
|
||||
ui.label(RichText::new("Sites you answered a permission request for. Defaults are in Settings → Privacy → Site settings.").weak());
|
||||
ui.add(egui::TextEdit::singleline(&mut f.ui.pages.site_search).hint_text("Search sites").desired_width(f32::INFINITY));
|
||||
let all = f.shared.permissions.borrow().all();
|
||||
let mut hosts: Vec<String> = all.iter().map(|(h, ..)| h.clone()).collect();
|
||||
hosts.dedup();
|
||||
let q = f.ui.pages.site_search.to_lowercase();
|
||||
card(ui, |ui| {
|
||||
if hosts.is_empty() {
|
||||
ui.label(RichText::new("No sites yet.").weak());
|
||||
}
|
||||
for h in hosts.iter().filter(|h| q.is_empty() || h.contains(&q)) {
|
||||
let summary: Vec<String> = all.iter().filter(|(x, ..)| x == h).map(|(_, k, d)| format!("{} {}", k.label(), if *d == Decision::Allow { "✓" } else { "✕" })).collect();
|
||||
if row(ui, h, &summary.join(" · "), |ui| ui.button("›").clicked()) {
|
||||
f.send(Command::ShowPage(Page::SiteSettings(h.clone())));
|
||||
}
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
if ui.button("‹ All sites").clicked() {
|
||||
f.send(Command::ShowPage(Page::SiteSettings(String::new())));
|
||||
}
|
||||
ui.heading(host);
|
||||
let mut s = f.shared.settings.borrow().clone();
|
||||
let before = s.clone();
|
||||
card(ui, |ui| {
|
||||
for kind in Kind::ALL {
|
||||
let current = f.shared.permissions.borrow().site_decision(host, *kind);
|
||||
let mut value: u8 = match current {
|
||||
None => 0,
|
||||
Some(Decision::Allow) => 1,
|
||||
Some(Decision::Block) => 2,
|
||||
};
|
||||
let default = s.privacy.permission_defaults.get(kind.key()).copied().unwrap_or_else(|| kind.builtin_default());
|
||||
let opts: &[(u8, &str)] = &[(0, "Default"), (1, "Allow"), (2, "Block")];
|
||||
let changed = row(ui, kind.label(), &format!("Default: {}", default.label()), |ui| segmented(ui, &mut value, opts));
|
||||
if changed {
|
||||
let decision = match value {
|
||||
1 => Some(Decision::Allow),
|
||||
2 => Some(Decision::Block),
|
||||
_ => None,
|
||||
};
|
||||
f.shared.permissions.borrow_mut().set(host, *kind, decision);
|
||||
}
|
||||
}
|
||||
});
|
||||
card(ui, |ui| {
|
||||
let mut ads = !s.adblock_paused_on(host);
|
||||
if switch_row(ui, "Block ads on this site", "", &mut ads) {
|
||||
if ads {
|
||||
s.adblock.allow.retain(|h| !util::host_matches(host, h));
|
||||
} else {
|
||||
s.adblock.allow.push(host.to_owned());
|
||||
}
|
||||
}
|
||||
let mut active = s.keeps_active(host);
|
||||
if switch_row(ui, "Always keep active", "Its tabs are never frozen or unloaded", &mut active) {
|
||||
if active {
|
||||
s.perf.keep_active.push(host.to_owned());
|
||||
} else {
|
||||
s.perf.keep_active.retain(|h| !util::host_matches(host, h));
|
||||
}
|
||||
}
|
||||
let mut muted = s.site_muted(host);
|
||||
if switch_row(ui, "Mute", "", &mut muted) {
|
||||
f.send(Command::ToggleMuteSite(host.to_owned()));
|
||||
}
|
||||
let mut http = s.privacy.https_exceptions.iter().any(|h| h == host);
|
||||
if switch_row(ui, "Allow without HTTPS", "Only matters when HTTPS-only mode is on", &mut http) {
|
||||
if http {
|
||||
s.privacy.https_exceptions.push(host.to_owned());
|
||||
} else {
|
||||
s.privacy.https_exceptions.retain(|h| h != host);
|
||||
}
|
||||
}
|
||||
if let Some(zoom) = s.web.zoom_sites.get(host).copied() {
|
||||
if row(ui, "Zoom", &format!("{:.0}%", zoom * 100.0), |ui| ui.button("Reset").clicked()) {
|
||||
s.web.zoom_sites.remove(host);
|
||||
}
|
||||
}
|
||||
if row(ui, "Cookies and site data", "Stored by this site in Nacre", |ui| ui.button("Delete").clicked()) {
|
||||
f.send(Command::ClearSiteData(host.to_owned()));
|
||||
}
|
||||
});
|
||||
if s != before {
|
||||
*f.shared.settings.borrow_mut() = s;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const RANGES: &[(&str, u64)] = &[("Last hour", 3600), ("Last 24 hours", 86_400), ("Last 7 days", 7 * 86_400), ("Last 4 weeks", 28 * 86_400), ("All time", 0)];
|
||||
const WHAT: &[(&str, &str, &str)] = &[
|
||||
("history", "Browsing history", "Pages you visited and recently closed tabs"),
|
||||
("cookies", "Cookies and site data", "Signs you out of most sites"),
|
||||
("cache", "Cached files", "Pages load a little slower the first time"),
|
||||
("downloads", "Download list", "Files stay on disk"),
|
||||
("permissions", "Site permissions", ""),
|
||||
("passwords", "Passwords", ""),
|
||||
("autofill", "Addresses and cards", ""),
|
||||
];
|
||||
|
||||
pub fn clear_data(ui: &mut Ui, f: &mut Frame) {
|
||||
if f.ui.pages.clear_what.is_empty() {
|
||||
f.ui.pages.clear_what = vec!["history".into(), "cookies".into(), "cache".into()];
|
||||
}
|
||||
page_column(ui, "clear-data", 640.0, |ui| {
|
||||
ui.heading("Delete browsing data");
|
||||
card(ui, |ui| {
|
||||
let mut range = f.ui.pages.clear_range;
|
||||
let opts: Vec<(usize, &str)> = RANGES.iter().enumerate().map(|(i, (l, _))| (i, *l)).collect();
|
||||
row(ui, "Time range", "", |ui| segmented(ui, &mut range, &opts));
|
||||
f.ui.pages.clear_range = range;
|
||||
for (key, label, desc) in WHAT {
|
||||
let mut on = f.ui.pages.clear_what.iter().any(|k| k == key);
|
||||
if switch_row(ui, label, desc, &mut on) {
|
||||
if on {
|
||||
f.ui.pages.clear_what.push((*key).to_owned());
|
||||
} else {
|
||||
f.ui.pages.clear_what.retain(|k| k != key);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.label(RichText::new("Cookies, cache, permissions and passwords are deleted whatever the time range; Servo keeps no dates for them.").weak().small());
|
||||
if ui.button(RichText::new("Delete data").strong()).clicked() {
|
||||
let seconds = RANGES[f.ui.pages.clear_range.min(RANGES.len() - 1)].1;
|
||||
let since = if seconds == 0 { 0 } else { util::now().saturating_sub(seconds) };
|
||||
f.send(Command::ClearData { since, what: f.ui.pages.clear_what.clone() });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn about(ui: &mut Ui, f: &mut Frame) {
|
||||
page_column(ui, "about", 640.0, |ui| {
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add_space(20.0);
|
||||
ui.label(RichText::new("Nacre").size(40.0).strong());
|
||||
ui.label(format!("Version {}", crate::updates::current_version()));
|
||||
ui.label(RichText::new("Servo 0.7.0 engine · written in Rust").weak());
|
||||
});
|
||||
ui.add_space(16.0);
|
||||
card(ui, |ui| {
|
||||
let status = f.shared.update_status.borrow().clone();
|
||||
if row(ui, "Updates", if status.is_empty() { "Not checked yet" } else { &status }, |ui| ui.button("Check now").clicked()) {
|
||||
f.send(Command::CheckUpdates);
|
||||
}
|
||||
if f.shared.update.borrow().is_some() && row(ui, "A new version is ready", "", |ui| ui.button("Get it").clicked()) {
|
||||
f.send(Command::OpenUpdate);
|
||||
}
|
||||
let repo = f.shared.settings.borrow().update.repo.clone();
|
||||
if !repo.is_empty() && row(ui, "Source code and releases", &repo, |ui| ui.button("Open").clicked()) {
|
||||
f.send(Command::Open { url: repo, how: crate::actions::Disposition::NewForegroundTab, from: None });
|
||||
}
|
||||
row(ui, "Licence", "Mozilla Public License 2.0 (Servo and Nacre)", |_| ());
|
||||
row(ui, "Engine limits", "No DRM video (Widevine), no Chrome extensions (use scripts and styles), no printing (save as PDF instead)", |_| ());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// First run: a few choices, then the new tab page.
|
||||
pub fn welcome(ui: &mut Ui, f: &mut Frame) {
|
||||
let mut s = f.shared.settings.borrow().clone();
|
||||
let before = s.clone();
|
||||
page_column(ui, "welcome", 640.0, |ui| {
|
||||
let step = f.ui.pages.welcome_step;
|
||||
ui.add_space(20.0);
|
||||
match step {
|
||||
0 => {
|
||||
ui.label(RichText::new("Welcome to Nacre").size(32.0).strong());
|
||||
ui.label("A few choices and you're ready. You can change all of them later in Settings.");
|
||||
let sources = f.shared.import_sources.borrow().clone();
|
||||
if !sources.is_empty() {
|
||||
ui.add_space(12.0);
|
||||
ui.label(RichText::new("Bring your bookmarks and history").strong());
|
||||
card(ui, |ui| {
|
||||
for (i, src) in sources.iter().enumerate() {
|
||||
if row(ui, &src.name(), "Bookmarks, history, home page and search engine", |ui| ui.button("Import").clicked()) {
|
||||
f.send(Command::Import { source: i, bookmarks: true, history: true, settings: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
let status = f.shared.import_status.borrow().clone();
|
||||
if !status.is_empty() {
|
||||
ui.label(RichText::new(status).weak());
|
||||
}
|
||||
}
|
||||
},
|
||||
1 => {
|
||||
ui.label(RichText::new("Search").size(26.0).strong());
|
||||
card(ui, |ui| {
|
||||
for (key, name, _, _) in s.search_engines() {
|
||||
ui.radio_value(&mut s.startup.search_engine, key, name);
|
||||
}
|
||||
});
|
||||
},
|
||||
2 => {
|
||||
ui.label(RichText::new("Look").size(26.0).strong());
|
||||
card(ui, |ui| {
|
||||
row(ui, "Mode", "", |ui| segmented(ui, &mut s.theme.mode, ThemeMode::ALL));
|
||||
row(ui, "Colours", "", |ui| segmented(ui, &mut s.theme.source, ColourSource::ALL));
|
||||
});
|
||||
},
|
||||
3 => {
|
||||
ui.label(RichText::new("Privacy").size(26.0).strong());
|
||||
card(ui, |ui| {
|
||||
switch_row(ui, "Block ads and trackers", "", &mut s.adblock.enabled);
|
||||
switch_row(ui, "HTTPS-only mode", "", &mut s.privacy.https_only);
|
||||
switch_row(ui, "Privacy mode", "Hides your browser's fingerprint", &mut s.privacy.mode);
|
||||
row(ui, "Secure DNS", "", |ui| {
|
||||
egui::ComboBox::from_id_salt("welcome-doh").selected_text(s.privacy.doh.label()).show_ui(ui, |ui| {
|
||||
for (v, l) in DohProvider::ALL {
|
||||
ui.selectable_value(&mut s.privacy.doh, *v, *l);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
_ => {
|
||||
ui.label(RichText::new("You're ready").size(32.0).strong());
|
||||
ui.label("Nacre is set up. Have a look at the new tab page and the menu ☰ for everything else.");
|
||||
},
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
ui.horizontal(|ui| {
|
||||
if step > 0 && ui.button("Back").clicked() {
|
||||
f.ui.pages.welcome_step -= 1;
|
||||
}
|
||||
if step < 4 {
|
||||
if ui.button(RichText::new("Next").strong()).clicked() {
|
||||
f.ui.pages.welcome_step += 1;
|
||||
}
|
||||
if ui.button("Skip setup").clicked() {
|
||||
s.startup.welcome_done = true;
|
||||
s.startup.import_offered = true;
|
||||
f.send(Command::Navigate("nacre://newtab".into()));
|
||||
}
|
||||
} else if ui.button(RichText::new("Start browsing").strong()).clicked() {
|
||||
s.startup.welcome_done = true;
|
||||
s.startup.import_offered = true;
|
||||
f.ui.pages.welcome_step = 0;
|
||||
f.send(Command::Navigate("nacre://newtab".into()));
|
||||
}
|
||||
});
|
||||
});
|
||||
if s != before {
|
||||
*f.shared.settings.borrow_mut() = s;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn task_manager(ui: &mut Ui, f: &mut Frame) {
|
||||
page_column(ui, "task-manager", 860.0, |ui| {
|
||||
ui.heading("Task manager");
|
||||
let (total, available) = crate::perf::system_memory();
|
||||
ui.label(format!("Nacre uses {} with {} threads · {} of {} memory free", util::format_bytes(crate::perf::own_memory()), crate::perf::own_threads(), util::format_bytes(available), util::format_bytes(total)));
|
||||
ui.label(RichText::new("Servo runs every page in Nacre's own process, so memory isn't split per tab.").weak().small());
|
||||
ui.add_space(8.0);
|
||||
let rows: Vec<(u64, String, &'static str, bool)> = f
|
||||
.tabs
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let state = if t.page.is_some() { "Nacre page" } else if t.web.is_none() { "Unloaded" } else if t.frozen { "Frozen" } else if t.audible() { "Playing" } else if t.loading() { "Loading" } else { "Running" };
|
||||
(t.id, t.display_title(), state, t.web.is_some())
|
||||
})
|
||||
.collect();
|
||||
egui::Grid::new("tasks").num_columns(3).striped(true).show(ui, |ui| {
|
||||
for (id, title, state, has_web) in rows {
|
||||
ui.label(util::ellipsize(&title, 60));
|
||||
ui.label(state);
|
||||
ui.horizontal(|ui| {
|
||||
if has_web && ui.small_button("Reload").clicked() {
|
||||
f.send(Command::ReloadTab(id));
|
||||
}
|
||||
if ui.small_button("Close").clicked() {
|
||||
f.send(Command::CloseTab(id));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
if ui.button("Unload background tabs").clicked() {
|
||||
f.send(Command::FreeMemory);
|
||||
}
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs(2));
|
||||
});
|
||||
}
|
||||
|
||||
pub fn source(ui: &mut Ui, f: &mut Frame, url: &str) {
|
||||
let source = f.shared.sources.borrow().get(url).cloned();
|
||||
match source {
|
||||
None => {
|
||||
f.send(Command::FetchSource(url.to_owned()));
|
||||
ui.spinner();
|
||||
},
|
||||
Some(None) => {
|
||||
ui.spinner();
|
||||
},
|
||||
Some(Some(Err(error))) => {
|
||||
ui.label(format!("The source couldn't be loaded: {error}"));
|
||||
if ui.button("Try again").clicked() {
|
||||
f.shared.sources.borrow_mut().remove(url);
|
||||
}
|
||||
},
|
||||
Some(Some(Ok(text))) => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(format!("Source of {}", util::ellipsize(url, 100))).strong());
|
||||
if ui.small_button("Copy").clicked() {
|
||||
ui.ctx().copy_text(text.clone());
|
||||
}
|
||||
if ui.small_button("Reload").clicked() {
|
||||
f.shared.sources.borrow_mut().remove(url);
|
||||
}
|
||||
});
|
||||
egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| {
|
||||
// Very long sources are shown in part to keep the window responsive.
|
||||
let mut shown: &str = if text.len() > 2_000_000 { &text[..text.char_indices().nth(2_000_000).map(|(i, _)| i).unwrap_or(text.len())] } else { &text };
|
||||
// A &str buffer is read-only: selectable and copyable, not editable.
|
||||
ui.add(egui::TextEdit::multiline(&mut shown).code_editor().desired_width(f32::INFINITY));
|
||||
});
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn error(ui: &mut Ui, f: &mut Frame, url: &str, why: &str) {
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add_space(80.0);
|
||||
ui.heading(crate::resources::ERROR_TITLE);
|
||||
ui.label(url);
|
||||
ui.label(RichText::new(why).weak());
|
||||
if ui.button("Try again").clicked() {
|
||||
f.send(Command::Navigate(url.to_owned()));
|
||||
}
|
||||
});
|
||||
let _ = switch;
|
||||
}
|
||||
81
src/ui/pages/mod.rs
Normal file
81
src/ui/pages/mod.rs
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
//! Nacre's own pages (nacre://...), drawn with egui inside the page area.
|
||||
|
||||
pub mod apps;
|
||||
pub mod bookmarks;
|
||||
pub mod devtools;
|
||||
pub mod downloads;
|
||||
pub mod history;
|
||||
pub mod misc;
|
||||
pub mod newtab;
|
||||
pub mod passwords;
|
||||
pub mod settings;
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use egui::Ui;
|
||||
|
||||
use super::Frame;
|
||||
use crate::tabs::Page;
|
||||
|
||||
/// What the pages remember between frames (search boxes, forms being filled in).
|
||||
#[derive(Default)]
|
||||
pub struct PageState {
|
||||
pub settings_section: String,
|
||||
pub settings_search: String,
|
||||
/// Action whose shortcut is being recorded.
|
||||
pub capture_key: Option<crate::keys::Action>,
|
||||
pub new_engine: (String, String),
|
||||
pub new_list_url: String,
|
||||
pub keep_active_input: String,
|
||||
pub new_profile: String,
|
||||
pub new_shortcut: (String, String),
|
||||
pub master: (String, String),
|
||||
pub history_search: String,
|
||||
pub bookmarks_search: String,
|
||||
pub bookmarks_folder: Option<u64>,
|
||||
pub bookmark_edit: Option<(u64, String, String)>,
|
||||
pub new_folder: String,
|
||||
pub downloads_search: String,
|
||||
pub passwords_tab: usize,
|
||||
pub passwords_search: String,
|
||||
pub revealed: HashSet<u64>,
|
||||
pub login_edit: Option<crate::store::vault::Login>,
|
||||
pub address_edit: Option<crate::store::vault::Address>,
|
||||
pub card_edit: Option<crate::store::vault::Card>,
|
||||
pub reauth: String,
|
||||
pub reauth_error: String,
|
||||
pub unlock: String,
|
||||
pub unlock_error: String,
|
||||
pub generated: String,
|
||||
pub gen_passphrase: bool,
|
||||
pub script_edit: Option<(u64, String)>,
|
||||
pub new_script: String,
|
||||
pub script_url: String,
|
||||
pub site_search: String,
|
||||
pub clear_range: usize,
|
||||
pub clear_what: Vec<String>,
|
||||
pub welcome_step: usize,
|
||||
pub devtools_input: String,
|
||||
pub devtools_tab: usize,
|
||||
pub notes_dirty: bool,
|
||||
}
|
||||
|
||||
pub fn draw(ui: &mut Ui, f: &mut Frame, page: &Page) {
|
||||
match page {
|
||||
Page::NewTab => newtab::draw(ui, f),
|
||||
Page::Settings(section) => settings::draw(ui, f, section),
|
||||
Page::History => history::draw(ui, f),
|
||||
Page::Bookmarks => bookmarks::draw(ui, f),
|
||||
Page::Downloads => downloads::draw(ui, f),
|
||||
Page::Passwords => passwords::draw(ui, f),
|
||||
Page::Apps => apps::draw(ui, f),
|
||||
Page::SiteSettings(host) => misc::site_settings(ui, f, host),
|
||||
Page::ClearData => misc::clear_data(ui, f),
|
||||
Page::About => misc::about(ui, f),
|
||||
Page::Welcome => misc::welcome(ui, f),
|
||||
Page::TaskManager => misc::task_manager(ui, f),
|
||||
Page::DevTools => devtools::draw(ui, f),
|
||||
Page::Source(url) => misc::source(ui, f, url),
|
||||
Page::Error(url, why) => misc::error(ui, f, url, why),
|
||||
}
|
||||
}
|
||||
326
src/ui/pages/newtab.rs
Normal file
326
src/ui/pages/newtab.rs
Normal file
|
|
@ -0,0 +1,326 @@
|
|||
//! The new tab page: clock, greeting, search, shortcuts, media, weather, notes, reading list and
|
||||
//! recent pages, each switchable in Settings → General → New tab.
|
||||
|
||||
use egui::{RichText, Ui, Vec2};
|
||||
|
||||
use super::super::Frame;
|
||||
use crate::actions::{Command, Disposition};
|
||||
use crate::util;
|
||||
|
||||
pub fn draw(ui: &mut Ui, f: &mut Frame) {
|
||||
let ntp = f.shared.settings.borrow().ntp.clone();
|
||||
let palette = f.palette();
|
||||
// Background image, dimmed and softened by the settings.
|
||||
if !ntp.bg_image.is_empty() {
|
||||
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.art_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.art_texture = Some((key.clone(), t.clone()));
|
||||
t
|
||||
}),
|
||||
};
|
||||
if let Some(texture) = texture {
|
||||
let rect = ui.max_rect();
|
||||
ui.painter().image(texture.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE);
|
||||
ui.painter().rect_filled(rect, 0.0, egui::Color32::from_black_alpha((ntp.bg_dim.clamp(0.0, 1.0) * 255.0) as u8));
|
||||
}
|
||||
}
|
||||
let still = crate::perf::still(&f.shared.settings.borrow());
|
||||
background(ui, &ntp, &palette, still);
|
||||
super::super::widgets::page_column(ui, "newtab", 760.0, |ui| {
|
||||
ui.add_space(40.0);
|
||||
for (element, on) in &ntp.elements {
|
||||
if !on {
|
||||
continue;
|
||||
}
|
||||
match element.as_str() {
|
||||
"clock" => {
|
||||
let now = util::now();
|
||||
let t = util::local_time(now);
|
||||
let (hour, suffix) = if ntp.clock24 { (t.hour, "") } else { (if t.hour % 12 == 0 { 12 } else { t.hour % 12 }, if t.hour < 12 { " AM" } else { " PM" }) };
|
||||
let text = if ntp.seconds { format!("{hour}:{:02}:{:02}{suffix}", t.minute, t.second) } else { format!("{hour}:{:02}{suffix}", t.minute) };
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.label(RichText::new(text).size(64.0).strong());
|
||||
ui.label(RichText::new(util::format_day_heading(now)).weak());
|
||||
});
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs(if ntp.seconds { 1 } else { 15 }));
|
||||
},
|
||||
"greeting" => {
|
||||
let hour = util::local_time(util::now()).hour;
|
||||
let part = match hour {
|
||||
5..=11 => "Good morning",
|
||||
12..=17 => "Good afternoon",
|
||||
_ => "Good evening",
|
||||
};
|
||||
let text = if ntp.name.is_empty() { part.to_owned() } else { format!("{part}, {}", ntp.name) };
|
||||
ui.vertical_centered(|ui| ui.label(RichText::new(text).size(22.0)));
|
||||
},
|
||||
"search" => {
|
||||
ui.add_space(12.0);
|
||||
let id = egui::Id::new("ntp-search");
|
||||
let mut text = ui.data_mut(|d| d.get_temp::<String>(id)).unwrap_or_default();
|
||||
let engine = f.shared.settings.borrow().search_engine_name();
|
||||
ui.vertical_centered(|ui| {
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut text).hint_text(format!("Search with {engine}")).desired_width(520.0).font(egui::TextStyle::Heading));
|
||||
if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) && !text.trim().is_empty() {
|
||||
f.send(Command::Navigate(text.clone()));
|
||||
text.clear();
|
||||
}
|
||||
});
|
||||
ui.data_mut(|d| d.insert_temp(id, text));
|
||||
ui.add_space(12.0);
|
||||
},
|
||||
"shortcuts" => {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let total = ntp.shortcuts.len().max(1) as f32;
|
||||
let width = (ui.available_width() / total.min(6.0) - 8.0).clamp(90.0, 120.0);
|
||||
for (title, url) in &ntp.shortcuts {
|
||||
let button = egui::Button::new(RichText::new(format!("{}\n{}", initial(title), util::ellipsize(title, 14)))).min_size(Vec2::new(width, 64.0));
|
||||
let r = ui.add(button).on_hover_text(url);
|
||||
if r.clicked() {
|
||||
let new_tab = ui.input(|i| i.modifiers.command);
|
||||
f.send(Command::Open { url: url.clone(), how: if new_tab { Disposition::NewBackgroundTab } else { Disposition::Current }, from: None });
|
||||
}
|
||||
if r.middle_clicked() {
|
||||
f.send(Command::Open { url: url.clone(), how: Disposition::NewBackgroundTab, from: None });
|
||||
}
|
||||
}
|
||||
if ui.add(egui::Button::new("➕\nAdd").min_size(Vec2::new(90.0, 64.0))).on_hover_text("Edit shortcuts in settings").clicked() {
|
||||
f.send(Command::ShowPage(crate::tabs::Page::Settings("newtab".into())));
|
||||
}
|
||||
});
|
||||
},
|
||||
"media" => {
|
||||
let now = f.shared.media_now.borrow().clone();
|
||||
if let Some(now) = now {
|
||||
super::super::widgets::card(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new("♫").size(22.0).color(palette.accent));
|
||||
ui.vertical(|ui| {
|
||||
ui.label(RichText::new(util::ellipsize(if now.state.title.is_empty() { &now.title } else { &now.state.title }, 60)).strong());
|
||||
ui.label(RichText::new(if now.state.artist.is_empty() { now.host.clone() } else { now.state.artist.clone() }).weak());
|
||||
});
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("⏭").clicked() {
|
||||
f.send(Command::Media { tab: now.tab, action: "next".into(), value: 0.0 });
|
||||
}
|
||||
if ui.button(if now.state.paused { "▶" } else { "⏸" }).clicked() {
|
||||
f.send(Command::Media { tab: now.tab, action: "toggle".into(), value: 0.0 });
|
||||
}
|
||||
if ui.button("⏮").clicked() {
|
||||
f.send(Command::Media { tab: now.tab, action: "prev".into(), value: 0.0 });
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
},
|
||||
"weather" => {
|
||||
let weather = f.shared.weather.borrow().clone();
|
||||
match weather {
|
||||
Some((city, temp, code)) => {
|
||||
ui.vertical_centered(|ui| ui.label(RichText::new(format!("{} {temp:.0}° · {city}", weather_glyph(code))).size(18.0)));
|
||||
},
|
||||
None if !ntp.city.is_empty() => {
|
||||
let asked = ui.data_mut(|d| std::mem::replace(d.get_temp_mut_or(egui::Id::new("weather-asked"), false), true));
|
||||
if !asked {
|
||||
f.send(Command::Weather);
|
||||
}
|
||||
},
|
||||
None => {
|
||||
ui.vertical_centered(|ui| ui.label(RichText::new("Set your city in settings to see the weather").weak().small()));
|
||||
},
|
||||
}
|
||||
},
|
||||
"notes" => {
|
||||
super::super::widgets::card(ui, |ui| {
|
||||
ui.label(RichText::new("Notes").strong());
|
||||
let mut notes = f.shared.settings.borrow().ntp.notes.clone();
|
||||
if ui.add(egui::TextEdit::multiline(&mut notes).desired_width(f32::INFINITY).desired_rows(4)).changed() {
|
||||
f.shared.settings.borrow_mut().ntp.notes = notes;
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
},
|
||||
"reading" => {
|
||||
let items: Vec<crate::store::bookmarks::ReadingItem> = f.shared.reading.borrow().items.iter().filter(|i| !i.read).take(6).cloned().collect();
|
||||
if !items.is_empty() {
|
||||
super::super::widgets::card(ui, |ui| {
|
||||
ui.label(RichText::new("Reading list").strong());
|
||||
for item in items {
|
||||
ui.horizontal(|ui| {
|
||||
if ui.link(util::ellipsize(&item.title, 70)).clicked() {
|
||||
f.shared.reading.borrow_mut().set_read(&item.url, true);
|
||||
f.send(Command::Navigate(item.url.clone()));
|
||||
}
|
||||
if ui.small_button("✓").on_hover_text("Mark as read").clicked() {
|
||||
f.shared.reading.borrow_mut().set_read(&item.url, true);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
},
|
||||
"recent" => {
|
||||
let recent: Vec<(String, String)> = f.shared.history.borrow().recent(8).iter().map(|v| (v.url.clone(), v.title.clone())).collect();
|
||||
if !recent.is_empty() {
|
||||
super::super::widgets::card(ui, |ui| {
|
||||
ui.label(RichText::new("Recent").strong());
|
||||
for (url, title) in recent {
|
||||
if ui.link(util::ellipsize(if title.is_empty() { &url } else { &title }, 80)).on_hover_text(&url).clicked() {
|
||||
f.send(Command::Navigate(url));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
ui.add_space(10.0);
|
||||
}
|
||||
ui.add_space(20.0);
|
||||
ui.vertical_centered(|ui| {
|
||||
if ui.small_button("Customize this page").clicked() {
|
||||
f.send(Command::ShowPage(crate::tabs::Page::Settings("newtab".into())));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn initial(title: &str) -> String {
|
||||
title.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_else(|| "•".into())
|
||||
}
|
||||
|
||||
/// WMO weather codes (Open-Meteo).
|
||||
fn weather_glyph(code: u32) -> &'static str {
|
||||
match code {
|
||||
0 => "☀",
|
||||
1..=3 => "⛅",
|
||||
45 | 48 => "🌫",
|
||||
51..=67 | 80..=82 => "🌧",
|
||||
71..=77 | 85 | 86 => "🌨",
|
||||
95..=99 => "⛈",
|
||||
_ => "☁",
|
||||
}
|
||||
}
|
||||
|
||||
/// 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));
|
||||
}
|
||||
}
|
||||
422
src/ui/pages/passwords.rs
Normal file
422
src/ui/pages/passwords.rs
Normal file
|
|
@ -0,0 +1,422 @@
|
|||
//! nacre://passwords — saved logins, addresses and cards, the generator, a check for weak or
|
||||
//! reused passwords, and the master password.
|
||||
|
||||
use egui::{RichText, Ui};
|
||||
|
||||
use super::super::widgets::{card, page_column};
|
||||
use super::super::Frame;
|
||||
use crate::actions::Command;
|
||||
use crate::store::vault::{self, Address, Card, Login, Mode};
|
||||
use crate::util;
|
||||
|
||||
const TABS: &[&str] = &["Passwords", "Addresses", "Cards", "Generator", "Check", "Master password"];
|
||||
|
||||
pub fn draw(ui: &mut Ui, f: &mut Frame) {
|
||||
page_column(ui, "passwords", 900.0, |ui| {
|
||||
ui.heading("Passwords and autofill");
|
||||
if f.incognito() {
|
||||
ui.label(RichText::new("Incognito windows have their own empty password store that is thrown away when they close.").weak());
|
||||
}
|
||||
if f.shared.vault.borrow().locked() {
|
||||
unlock(ui, f);
|
||||
return;
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
for (i, name) in TABS.iter().enumerate() {
|
||||
if ui.selectable_label(f.ui.pages.passwords_tab == i, *name).clicked() {
|
||||
f.ui.pages.passwords_tab = i;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
match f.ui.pages.passwords_tab {
|
||||
0 => logins(ui, f),
|
||||
1 => addresses(ui, f),
|
||||
2 => cards(ui, f),
|
||||
3 => generator(ui, f),
|
||||
4 => check(ui, f),
|
||||
_ => master(ui, f),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn unlock(ui: &mut Ui, f: &mut Frame) {
|
||||
card(ui, |ui| {
|
||||
ui.label(RichText::new("Your passwords are locked").strong());
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut f.ui.pages.unlock).password(true).hint_text("Master password"));
|
||||
let go = ui.button("Unlock").clicked() || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)));
|
||||
if go {
|
||||
let pw = std::mem::take(&mut f.ui.pages.unlock);
|
||||
match f.shared.vault.borrow_mut().unlock(&pw) {
|
||||
Ok(()) => f.ui.pages.unlock_error.clear(),
|
||||
Err(e) => f.ui.pages.unlock_error = e.to_string(),
|
||||
}
|
||||
}
|
||||
if !f.ui.pages.unlock_error.is_empty() {
|
||||
ui.label(RichText::new(&f.ui.pages.unlock_error).color(f.palette().error));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Copy a secret and wipe it from the clipboard later if it is still there.
|
||||
fn copy_secret(f: &Frame, secret: &str) {
|
||||
let seconds = f.shared.settings.borrow().vault.clipboard_clear;
|
||||
let secret = secret.to_owned();
|
||||
std::thread::spawn(move || {
|
||||
let Ok(mut clipboard) = arboard::Clipboard::new() else { return };
|
||||
if clipboard.set_text(secret.clone()).is_err() || seconds == 0 {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_secs(seconds as u64));
|
||||
if clipboard.get_text().is_ok_and(|t| t == secret) {
|
||||
let _ = clipboard.set_text(String::new());
|
||||
}
|
||||
});
|
||||
f.shared.toast(if seconds > 0 { format!("Copied; cleared from the clipboard in {seconds} s") } else { "Copied".into() });
|
||||
}
|
||||
|
||||
/// Whether passwords may be shown right now; asks for the master password if needed.
|
||||
fn may_reveal(ui: &mut Ui, f: &mut Frame) -> bool {
|
||||
let (reauth, minutes) = {
|
||||
let s = f.shared.settings.borrow();
|
||||
(s.vault.reauth, s.vault.reauth_min)
|
||||
};
|
||||
if !f.shared.vault.borrow().needs_reauth(reauth, minutes) {
|
||||
return true;
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Enter the master password to see passwords:");
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut f.ui.pages.reauth).password(true).desired_width(180.0));
|
||||
if ui.button("OK").clicked() || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) {
|
||||
let pw = std::mem::take(&mut f.ui.pages.reauth);
|
||||
if f.shared.vault.borrow_mut().check_password(&pw) {
|
||||
f.ui.pages.reauth_error.clear();
|
||||
} else {
|
||||
f.ui.pages.reauth_error = "That password is not right.".into();
|
||||
}
|
||||
}
|
||||
});
|
||||
if !f.ui.pages.reauth_error.is_empty() {
|
||||
ui.label(RichText::new(&f.ui.pages.reauth_error).color(f.palette().error));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn logins(ui: &mut Ui, f: &mut Frame) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::TextEdit::singleline(&mut f.ui.pages.passwords_search).hint_text("Search passwords").desired_width(360.0));
|
||||
if ui.button("Add").clicked() {
|
||||
f.ui.pages.login_edit = Some(Login::default());
|
||||
}
|
||||
if ui.button("Import CSV").clicked() {
|
||||
f.send(Command::ImportPasswords);
|
||||
}
|
||||
if ui.button("Export CSV").clicked() {
|
||||
f.send(Command::ExportPasswords);
|
||||
}
|
||||
});
|
||||
if let Some(mut edit) = f.ui.pages.login_edit.clone() {
|
||||
card(ui, |ui| {
|
||||
ui.label(RichText::new(if edit.id == 0 { "New password" } else { "Edit password" }).strong());
|
||||
egui::Grid::new("login-edit").num_columns(2).show(ui, |ui| {
|
||||
ui.label("Site");
|
||||
ui.add(egui::TextEdit::singleline(&mut edit.origin).hint_text("https://example.com").desired_width(360.0));
|
||||
ui.end_row();
|
||||
ui.label("User name");
|
||||
ui.add(egui::TextEdit::singleline(&mut edit.username).desired_width(360.0));
|
||||
ui.end_row();
|
||||
ui.label("Password");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::TextEdit::singleline(&mut edit.password).password(true).desired_width(280.0));
|
||||
if ui.small_button("Generate").clicked() {
|
||||
let (len, sym) = {
|
||||
let s = f.shared.settings.borrow();
|
||||
(s.vault.gen_length, s.vault.gen_symbols)
|
||||
};
|
||||
edit.password = vault::generate(len as usize, sym);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Note");
|
||||
ui.add(egui::TextEdit::singleline(&mut edit.note).desired_width(360.0));
|
||||
ui.end_row();
|
||||
});
|
||||
let (level, label) = vault::strength(&edit.password);
|
||||
ui.add(egui::ProgressBar::new(level as f32 / 4.0).text(label).desired_width(360.0));
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Save").clicked() {
|
||||
let result = if edit.id == 0 {
|
||||
f.shared.vault.borrow_mut().upsert_login(&edit.origin, &edit.username, &edit.password, &edit.note).map(|_| ())
|
||||
} else {
|
||||
edit.origin = vault::origin_of(&edit.origin);
|
||||
f.shared.vault.borrow_mut().update_login(edit.clone())
|
||||
};
|
||||
match result {
|
||||
Ok(()) => f.ui.pages.login_edit = None,
|
||||
Err(e) => f.shared.toast(e.to_string()),
|
||||
}
|
||||
return;
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
f.ui.pages.login_edit = None;
|
||||
return;
|
||||
}
|
||||
f.ui.pages.login_edit = Some(edit.clone());
|
||||
});
|
||||
});
|
||||
}
|
||||
let query = f.ui.pages.passwords_search.to_lowercase();
|
||||
let mut list: Vec<Login> = f.shared.vault.borrow().contents.logins.iter().filter(|l| query.is_empty() || l.origin.to_lowercase().contains(&query) || l.username.to_lowercase().contains(&query)).cloned().collect();
|
||||
list.sort_by(|a, b| util::host_of_str(&a.origin).cmp(&util::host_of_str(&b.origin)).then(a.username.cmp(&b.username)));
|
||||
if list.is_empty() {
|
||||
ui.label(RichText::new("Passwords you save show up here.").weak());
|
||||
}
|
||||
let can_reveal = f.ui.pages.revealed.is_empty() || may_reveal(ui, f);
|
||||
let mut delete = None;
|
||||
egui::Grid::new("logins").num_columns(4).striped(true).show(ui, |ui| {
|
||||
for login in &list {
|
||||
ui.label(util::host_of_str(&login.origin));
|
||||
ui.label(if login.username.is_empty() { "—".into() } else { login.username.clone() });
|
||||
let shown = f.ui.pages.revealed.contains(&login.id) && can_reveal;
|
||||
ui.monospace(if shown { login.password.clone() } else { "••••••••".into() });
|
||||
ui.horizontal(|ui| {
|
||||
if ui.small_button(if shown { "Hide" } else { "Show" }).clicked() {
|
||||
if shown {
|
||||
f.ui.pages.revealed.remove(&login.id);
|
||||
} else {
|
||||
f.ui.pages.revealed.insert(login.id);
|
||||
}
|
||||
}
|
||||
if ui.small_button("Copy").clicked() {
|
||||
let ok = !f.shared.vault.borrow().needs_reauth(f.shared.settings.borrow().vault.reauth, f.shared.settings.borrow().vault.reauth_min);
|
||||
if ok {
|
||||
copy_secret(f, &login.password);
|
||||
} else {
|
||||
f.ui.pages.revealed.insert(login.id);
|
||||
}
|
||||
}
|
||||
if ui.small_button("Edit").clicked() {
|
||||
f.ui.pages.login_edit = Some(login.clone());
|
||||
}
|
||||
if ui.small_button("Delete").clicked() {
|
||||
delete = Some(login.id);
|
||||
}
|
||||
if ui.small_button("Open").clicked() {
|
||||
f.send(Command::Open { url: login.origin.clone(), how: crate::actions::Disposition::NewForegroundTab, from: None });
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
if let Some(id) = delete {
|
||||
let _ = f.shared.vault.borrow_mut().delete_login(id);
|
||||
}
|
||||
let never = f.shared.vault.borrow().contents.never.clone();
|
||||
if !never.is_empty() {
|
||||
ui.add_space(12.0);
|
||||
ui.collapsing(format!("Never saved for {} sites", never.len()), |ui| {
|
||||
for origin in never {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(&origin);
|
||||
if ui.small_button("Remove").clicked() {
|
||||
let _ = f.shared.vault.borrow_mut().remove_never(&origin);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn addresses(ui: &mut Ui, f: &mut Frame) {
|
||||
if ui.button("Add address").clicked() {
|
||||
f.ui.pages.address_edit = Some(Address::default());
|
||||
}
|
||||
if let Some(mut a) = f.ui.pages.address_edit.clone() {
|
||||
card(ui, |ui| {
|
||||
egui::Grid::new("address-edit").num_columns(2).show(ui, |ui| {
|
||||
for (label, value) in [("Name", &mut a.name), ("Organization", &mut a.organization), ("Street", &mut a.street), ("City", &mut a.city), ("Region", &mut a.region), ("Postal code", &mut a.postal_code), ("Country", &mut a.country), ("Phone", &mut a.phone), ("Email", &mut a.email)] {
|
||||
ui.label(label);
|
||||
ui.add(egui::TextEdit::singleline(value).desired_width(340.0));
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Save").clicked() {
|
||||
let _ = f.shared.vault.borrow_mut().upsert_address(a.clone());
|
||||
f.ui.pages.address_edit = None;
|
||||
return;
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
f.ui.pages.address_edit = None;
|
||||
return;
|
||||
}
|
||||
f.ui.pages.address_edit = Some(a.clone());
|
||||
});
|
||||
});
|
||||
}
|
||||
let list = f.shared.vault.borrow().contents.addresses.clone();
|
||||
if list.is_empty() {
|
||||
ui.label(RichText::new("Addresses you save are offered when a form asks for one.").weak());
|
||||
}
|
||||
for a in list {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!("{} · {}, {} {}", a.name, a.street, a.postal_code, a.city));
|
||||
if ui.small_button("Edit").clicked() {
|
||||
f.ui.pages.address_edit = Some(a.clone());
|
||||
}
|
||||
if ui.small_button("Delete").clicked() {
|
||||
let _ = f.shared.vault.borrow_mut().delete_address(a.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn cards(ui: &mut Ui, f: &mut Frame) {
|
||||
if ui.button("Add card").clicked() {
|
||||
f.ui.pages.card_edit = Some(Card::default());
|
||||
}
|
||||
if let Some(mut c) = f.ui.pages.card_edit.clone() {
|
||||
card(ui, |ui| {
|
||||
egui::Grid::new("card-edit").num_columns(2).show(ui, |ui| {
|
||||
ui.label("Name on card");
|
||||
ui.add(egui::TextEdit::singleline(&mut c.name).desired_width(300.0));
|
||||
ui.end_row();
|
||||
ui.label("Number");
|
||||
ui.add(egui::TextEdit::singleline(&mut c.number).desired_width(300.0));
|
||||
ui.end_row();
|
||||
ui.label("Expires");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::DragValue::new(&mut c.exp_month).range(1..=12));
|
||||
ui.label("/");
|
||||
ui.add(egui::DragValue::new(&mut c.exp_year).range(2000..=2100));
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("Nickname");
|
||||
ui.add(egui::TextEdit::singleline(&mut c.nickname).desired_width(300.0));
|
||||
ui.end_row();
|
||||
});
|
||||
ui.label(RichText::new("The security code is never saved.").weak().small());
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Save").clicked() {
|
||||
let _ = f.shared.vault.borrow_mut().upsert_card(c.clone());
|
||||
f.ui.pages.card_edit = None;
|
||||
return;
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
f.ui.pages.card_edit = None;
|
||||
return;
|
||||
}
|
||||
f.ui.pages.card_edit = Some(c.clone());
|
||||
});
|
||||
});
|
||||
}
|
||||
let list = f.shared.vault.borrow().contents.cards.clone();
|
||||
if list.is_empty() {
|
||||
ui.label(RichText::new("Cards you save are offered when a payment form asks for one.").weak());
|
||||
}
|
||||
for c in list {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!("{} {} · {:02}/{}", if c.nickname.is_empty() { &c.name } else { &c.nickname }, c.masked(), c.exp_month, c.exp_year));
|
||||
if ui.small_button("Edit").clicked() {
|
||||
f.ui.pages.card_edit = Some(c.clone());
|
||||
}
|
||||
if ui.small_button("Delete").clicked() {
|
||||
let _ = f.shared.vault.borrow_mut().delete_card(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn generator(ui: &mut Ui, f: &mut Frame) {
|
||||
let mut s = f.shared.settings.borrow().vault.clone();
|
||||
card(ui, |ui| {
|
||||
ui.checkbox(&mut f.ui.pages.gen_passphrase, "Passphrase (words) instead of characters");
|
||||
if !f.ui.pages.gen_passphrase {
|
||||
ui.add(egui::Slider::new(&mut s.gen_length, 8..=64).text("characters"));
|
||||
ui.checkbox(&mut s.gen_symbols, "Symbols");
|
||||
}
|
||||
if ui.button("Generate").clicked() || f.ui.pages.generated.is_empty() {
|
||||
f.ui.pages.generated = if f.ui.pages.gen_passphrase { vault::passphrase(5, "-") } else { vault::generate(s.gen_length as usize, s.gen_symbols) };
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.monospace(RichText::new(&f.ui.pages.generated).size(16.0));
|
||||
if ui.button("Copy").clicked() {
|
||||
copy_secret(f, &f.ui.pages.generated.clone());
|
||||
}
|
||||
});
|
||||
let (level, label) = vault::strength(&f.ui.pages.generated);
|
||||
ui.add(egui::ProgressBar::new(level as f32 / 4.0).text(label));
|
||||
});
|
||||
if s != f.shared.settings.borrow().vault {
|
||||
f.shared.settings.borrow_mut().vault = s;
|
||||
}
|
||||
}
|
||||
|
||||
fn check(ui: &mut Ui, f: &mut Frame) {
|
||||
let issues = f.shared.vault.borrow().weak_or_reused();
|
||||
if issues.is_empty() {
|
||||
ui.label("No weak or reused passwords found.");
|
||||
return;
|
||||
}
|
||||
ui.label(format!("{} passwords could be stronger", issues.len()));
|
||||
let logins = f.shared.vault.borrow().contents.logins.clone();
|
||||
for (id, reason) in issues {
|
||||
if let Some(login) = logins.iter().find(|l| l.id == id) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!("{} · {}", util::host_of_str(&login.origin), if login.username.is_empty() { "—" } else { &login.username }));
|
||||
ui.label(RichText::new(reason).color(f.palette().warning));
|
||||
if ui.small_button("Change").clicked() {
|
||||
f.send(Command::Open { url: login.origin.clone(), how: crate::actions::Disposition::NewForegroundTab, from: None });
|
||||
}
|
||||
if ui.small_button("Edit").clicked() {
|
||||
f.ui.pages.login_edit = Some(login.clone());
|
||||
f.ui.pages.passwords_tab = 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn master(ui: &mut Ui, f: &mut Frame) {
|
||||
let mode = f.shared.vault.borrow().mode();
|
||||
card(ui, |ui| {
|
||||
match mode {
|
||||
Mode::Device => {
|
||||
ui.label("Your passwords are encrypted with a key kept in your profile folder. A master password also protects them from anyone who can read your files.");
|
||||
},
|
||||
Mode::Master => {
|
||||
ui.label("A master password protects your passwords. Nacre asks for it after it locks.");
|
||||
},
|
||||
}
|
||||
let (a, b) = &mut f.ui.pages.master;
|
||||
ui.add(egui::TextEdit::singleline(a).password(true).hint_text("New master password"));
|
||||
ui.add(egui::TextEdit::singleline(b).password(true).hint_text("Type it again"));
|
||||
let ok = !a.is_empty() && a == b;
|
||||
let level = vault::strength(a).0;
|
||||
if !a.is_empty() && level < 2 {
|
||||
ui.label(RichText::new("That master password is easy to guess.").color(f.palette().warning));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add_enabled(ok, egui::Button::new(if mode == Mode::Master { "Change master password" } else { "Set master password" })).clicked() {
|
||||
let pw = std::mem::take(&mut f.ui.pages.master.0);
|
||||
f.ui.pages.master.1.clear();
|
||||
match f.shared.vault.borrow_mut().set_master(&pw) {
|
||||
Ok(()) => f.shared.toast("Master password set"),
|
||||
Err(e) => f.shared.toast(e.to_string()),
|
||||
}
|
||||
}
|
||||
if mode == Mode::Master {
|
||||
if ui.button("Remove master password").clicked() {
|
||||
match f.shared.vault.borrow_mut().remove_master() {
|
||||
Ok(()) => f.shared.toast("Master password removed"),
|
||||
Err(e) => f.shared.toast(e.to_string()),
|
||||
}
|
||||
}
|
||||
if ui.button("Lock now").clicked() {
|
||||
f.shared.vault.borrow_mut().lock();
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.label(RichText::new("If you forget the master password, the saved passwords can't be recovered.").weak().small());
|
||||
});
|
||||
}
|
||||
1026
src/ui/pages/settings.rs
Normal file
1026
src/ui/pages/settings.rs
Normal file
File diff suppressed because it is too large
Load diff
154
src/ui/widgets.rs
Normal file
154
src/ui/widgets.rs
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
//! Small building blocks used across the interface.
|
||||
|
||||
use egui::{Response, RichText, Sense, Ui, Vec2};
|
||||
|
||||
/// A square button with a glyph and a tooltip.
|
||||
pub fn icon_button(ui: &mut Ui, glyph: &str, tooltip: &str) -> Response {
|
||||
let button = egui::Button::new(RichText::new(glyph).size(15.0)).min_size(Vec2::new(28.0, 28.0)).frame(false);
|
||||
ui.add(button).on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
/// Like `icon_button` but shows as pressed when `on`.
|
||||
pub fn icon_toggle(ui: &mut Ui, glyph: &str, tooltip: &str, on: bool) -> Response {
|
||||
let button = egui::Button::new(RichText::new(glyph).size(15.0)).min_size(Vec2::new(28.0, 28.0)).selected(on).frame(on);
|
||||
ui.add(button).on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
/// An on/off switch. Returns true when it changed.
|
||||
pub fn switch(ui: &mut Ui, on: &mut bool) -> bool {
|
||||
let size = Vec2::new(36.0, 20.0);
|
||||
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
|
||||
if response.clicked() {
|
||||
*on = !*on;
|
||||
}
|
||||
let t = ui.ctx().animate_bool_responsive(response.id, *on);
|
||||
let visuals = ui.style().interact_selectable(&response, *on);
|
||||
let radius = rect.height() / 2.0;
|
||||
let fill = if *on { ui.visuals().selection.stroke.color } else { ui.visuals().widgets.inactive.bg_fill };
|
||||
ui.painter().rect(rect, radius, fill, visuals.bg_stroke, egui::StrokeKind::Inside);
|
||||
let x = egui::lerp((rect.left() + radius)..=(rect.right() - radius), t);
|
||||
let knob = if *on { ui.visuals().panel_fill } else { ui.visuals().widgets.inactive.fg_stroke.color };
|
||||
ui.painter().circle_filled(egui::pos2(x, rect.center().y), radius * 0.72, knob);
|
||||
response.clicked()
|
||||
}
|
||||
|
||||
/// A row of buttons choosing one of `options`. Returns true when it changed.
|
||||
pub fn segmented<T: Copy + PartialEq>(ui: &mut Ui, value: &mut T, options: &[(T, &str)]) -> bool {
|
||||
let mut changed = false;
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
for (option, label) in options {
|
||||
let selected = *value == *option;
|
||||
let text = if selected { format!("✓ {label}") } else { (*label).to_owned() };
|
||||
if ui.add(egui::Button::new(text).selected(selected)).clicked() && !selected {
|
||||
*value = *option;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
changed
|
||||
}
|
||||
|
||||
/// A setting: title and description on the left, the control on the right.
|
||||
pub fn row<R>(ui: &mut Ui, title: &str, description: &str, control: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
let mut result = None;
|
||||
egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_max_width((ui.available_width() - 260.0).max(200.0));
|
||||
ui.label(RichText::new(title).strong());
|
||||
if !description.is_empty() {
|
||||
ui.label(RichText::new(description).small().weak());
|
||||
}
|
||||
});
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
result = Some(control(ui));
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
result.expect("control ran")
|
||||
}
|
||||
|
||||
/// A switch row. Returns true when it changed.
|
||||
pub fn switch_row(ui: &mut Ui, title: &str, description: &str, on: &mut bool) -> bool {
|
||||
row(ui, title, description, |ui| switch(ui, on))
|
||||
}
|
||||
|
||||
/// A row that opens something: title, description, and an arrow.
|
||||
pub fn link_row(ui: &mut Ui, title: &str, description: &str) -> bool {
|
||||
row(ui, title, description, |ui| ui.button("›").clicked())
|
||||
}
|
||||
|
||||
pub fn section(ui: &mut Ui, title: &str) {
|
||||
ui.add_space(14.0);
|
||||
ui.label(RichText::new(title).size(20.0).strong());
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
|
||||
/// A card that groups rows.
|
||||
pub fn card<R>(ui: &mut Ui, contents: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
let fill = ui.visuals().faint_bg_color;
|
||||
egui::Frame::NONE.fill(fill).corner_radius(ui.visuals().window_corner_radius).inner_margin(egui::Margin::same(4)).show(ui, contents).inner
|
||||
}
|
||||
|
||||
/// Centered page column of at most `width` points, scrolling.
|
||||
pub fn page_column<R>(ui: &mut Ui, id: &str, width: f32, contents: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
egui::ScrollArea::vertical().id_salt(id).auto_shrink([false, false]).show(ui, |ui| {
|
||||
// Margins are small integers in egui, so center with spacing instead.
|
||||
let avail = ui.available_width();
|
||||
let w = (avail - 32.0).min(width).max(200.0);
|
||||
let pad = ((avail - w) / 2.0).max(0.0);
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.add_space(pad);
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(w);
|
||||
ui.add_space(16.0);
|
||||
let r = contents(ui);
|
||||
ui.add_space(32.0);
|
||||
r
|
||||
})
|
||||
.inner
|
||||
})
|
||||
.inner
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
/// A text field with a hint; returns its response.
|
||||
pub fn text_field(ui: &mut Ui, text: &mut String, hint: &str, width: f32) -> Response {
|
||||
ui.add(egui::TextEdit::singleline(text).hint_text(hint).desired_width(width))
|
||||
}
|
||||
|
||||
/// A number field limited to `range`. Returns true when it changed.
|
||||
pub fn number(ui: &mut Ui, value: &mut u32, range: std::ops::RangeInclusive<u32>, suffix: &str) -> bool {
|
||||
ui.add(egui::DragValue::new(value).range(range).suffix(suffix)).changed()
|
||||
}
|
||||
|
||||
/// Glyph for a toolbar button key.
|
||||
pub fn glyph(key: &str) -> &'static str {
|
||||
match key {
|
||||
"back" => "⬅",
|
||||
"forward" => "➡",
|
||||
"reload" => "⟳",
|
||||
"home" => "🏠",
|
||||
"incognito" => "🕶",
|
||||
"passwords" => "🔑",
|
||||
"history" => "🕘",
|
||||
"downloads" => "⬇",
|
||||
"bookmarks" => "★",
|
||||
"qr" => "▦",
|
||||
"devtools" => "🛠",
|
||||
"adblock" => "🛡",
|
||||
"media" => "♫",
|
||||
"vpn" => "🌐",
|
||||
"apps" => "▤",
|
||||
"screenshot" => "📷",
|
||||
"pip" => "⧉",
|
||||
"zoom" => "🔍",
|
||||
"share" => "⤴",
|
||||
"reader" => "📖",
|
||||
"settings" => "⚙",
|
||||
_ => "•",
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue