While the active tab loads, the address pill squeezes into a wavy progress bar mapping an estimate of the load (Servo reports only stages); hover, focus or typing springs it back to the field. selftest gets fakeload, hover and blur for the loading and hover shots in tests/smoke/chrome.txt. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1164 lines
56 KiB
Rust
1164 lines
56 KiB
Rust
//! The browser chrome: title bar, tab strip, toolbar with the address field, bookmarks bar,
|
|
//! the slim bar of app windows, and the picture-in-picture window. Drawn from the theme tokens
|
|
//! (docs/DESIGN.md "UI system"); flyouts and menus are in `menus`.
|
|
|
|
use egui::{Align, Align2, Color32, Id, Key, Layout, Pos2, Rect, Response, RichText, Sense, Stroke, StrokeKind, Ui, UiBuilder, Vec2, pos2, vec2};
|
|
|
|
use super::widgets::{focus_ring, glyph, icon, icon_button, icon_toggle, interaction};
|
|
use super::{Flyout, Frame, menus};
|
|
use crate::actions::{Command, Disposition};
|
|
use crate::net::VpnStatus;
|
|
use crate::store::settings::{BookmarksBar, MediaButton};
|
|
use crate::tabs::Page;
|
|
use crate::theme::{self, Palette, Weight};
|
|
use crate::ui::icons;
|
|
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,
|
|
}
|
|
|
|
/// Chrome measurements in points (docs/PROGRESS.md S016).
|
|
const STRIP: f32 = 44.0;
|
|
const TAB: f32 = 34.0;
|
|
const TAB_GAP: f32 = 4.0;
|
|
const TAB_MIN: f32 = 76.0;
|
|
const TAB_MAX: f32 = 240.0;
|
|
const PINNED: f32 = 44.0;
|
|
const TOOLBAR: f32 = 52.0;
|
|
const BOOKMARKS: f32 = 36.0;
|
|
/// Small round buttons inside a tab or the address field.
|
|
const INNER: f32 = 24.0;
|
|
|
|
/// The colour behind the chrome and around the page card.
|
|
pub fn chrome_fill(p: &Palette) -> Color32 {
|
|
p.surface_container
|
|
}
|
|
|
|
fn bar(p: &Palette) -> egui::Frame {
|
|
egui::Frame::NONE.fill(chrome_fill(p)).inner_margin(egui::Margin::symmetric(theme::GAP_S as i8, 0))
|
|
}
|
|
|
|
/// A state layer for a custom-drawn control: hover and press as one opacity.
|
|
fn state_layer(ui: &Ui, response: &Response) -> (f32, f32) {
|
|
let s = interaction(ui, response);
|
|
(s.amount(), s.press.clamp(0.0, 1.0))
|
|
}
|
|
|
|
/// A small round button drawn inside another control (tab close, mute, address field chips).
|
|
fn inner_button(ui: &Ui, center: Pos2, id: Id, glyph: &str, tooltip: &str, color: Color32) -> Response {
|
|
let rect = Rect::from_center_size(center, Vec2::splat(INNER));
|
|
let response = ui.interact(rect, id, Sense::click()).on_hover_text(tooltip);
|
|
let (amount, press) = state_layer(ui, &response);
|
|
if amount > 0.0 {
|
|
ui.painter().circle_filled(center, INNER / 2.0 - press, color.gamma_multiply(amount * 1.5));
|
|
}
|
|
icon(ui, center, glyph, 16.0, false, color);
|
|
response
|
|
}
|
|
|
|
/// A loading indicator: an arc going round. Repaints while shown.
|
|
fn spinner(ui: &Ui, center: Pos2, radius: f32, color: Color32) {
|
|
let t = ui.input(|i| i.time) as f32;
|
|
let start = t * 5.0;
|
|
let sweep = 1.2 + 0.9 * (t * 2.2).sin().abs();
|
|
let points: Vec<Pos2> = (0..=20).map(|i| start + sweep * i as f32 / 20.0).map(|a| center + radius * vec2(a.cos(), a.sin())).collect();
|
|
ui.painter().add(egui::Shape::line(points, Stroke::new(2.0, color)));
|
|
ui.ctx().request_repaint();
|
|
}
|
|
|
|
/// A count or dot on the top right of a toolbar button.
|
|
fn badge(ui: &Ui, button: Rect, text: &str, fill: Color32, content: Color32) {
|
|
let corner = button.right_top() + vec2(-6.0, 6.0);
|
|
if text.is_empty() {
|
|
ui.painter().circle(corner, 4.0, fill, Stroke::new(1.5, chrome_fill(&theme::palette(ui.ctx()))));
|
|
return;
|
|
}
|
|
let galley = ui.painter().layout_no_wrap(text.to_owned(), theme::font(theme::SMALL - 2.0, Weight::SemiBold), content);
|
|
let size = vec2((galley.size().x + 8.0).max(16.0), 16.0);
|
|
let rect = Rect::from_center_size(corner + vec2(size.x / 2.0 - 8.0, 0.0), size);
|
|
ui.painter().rect(rect, theme::corner_radius(8.0), fill, Stroke::new(1.5, chrome_fill(&theme::palette(ui.ctx()))), StrokeKind::Outside);
|
|
ui.painter().galley(rect.center() - galley.size() / 2.0, galley, content);
|
|
}
|
|
|
|
/// Our own title bar when the system's is turned off.
|
|
pub fn title_bar(root: &mut Ui, f: &mut Frame) {
|
|
let p = f.palette();
|
|
egui::Panel::top("title-bar").exact_size(36.0).frame(bar(&p)).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(theme::GAP_S);
|
|
let title = if f.incognito() { "Nacre, incognito" } else { "Nacre" };
|
|
ui.label(RichText::new(title).font(theme::font(theme::BODY, Weight::Medium)).color(p.on_surface_variant));
|
|
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
|
ui.spacing_mut().item_spacing.x = 0.0;
|
|
for (glyph, tip, command, danger) in [(icons::CLOSE, "Close", Command::WindowClose, true), (icons::CROP_SQUARE, "Maximize", Command::WindowMaximize, false), (icons::MINIMIZE, "Minimize", Command::WindowMinimize, false)] {
|
|
if window_button(ui, glyph, tip, danger, &p).clicked() {
|
|
f.send(command);
|
|
}
|
|
}
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
/// Minimize, maximize and close: wide flat targets, close turns red under the pointer.
|
|
fn window_button(ui: &mut Ui, glyph: &str, tooltip: &str, danger: bool, p: &Palette) -> Response {
|
|
let (rect, response) = ui.allocate_exact_size(vec2(44.0, 32.0), Sense::click());
|
|
let s = interaction(ui, &response);
|
|
let hover = s.hover.max(s.press.clamp(0.0, 1.0));
|
|
let (fill, content) = if danger { (p.error.gamma_multiply(hover), theme::layer(p.on_surface_variant, p.on_error, hover)) } else { (p.on_surface.gamma_multiply(s.amount()), p.on_surface_variant) };
|
|
ui.painter().rect_filled(rect, theme::corner_radius(theme::radius(ui.ctx(), theme::S)), fill);
|
|
icon(ui, rect.center(), glyph, 18.0, false, content);
|
|
response.on_hover_text(tooltip)
|
|
}
|
|
|
|
/// The tab strip: pill tabs that slide to their place, the selection pill that follows the active tab, a round
|
|
/// "+" after the last tab. Tabs drag under the pointer and the others make room.
|
|
pub fn tab_strip(root: &mut Ui, f: &mut Frame) {
|
|
let p = f.palette();
|
|
egui::Panel::top("tabs").exact_size(STRIP).frame(bar(&p)).show_separator_line(false).show(root, |ui| {
|
|
let ctx = ui.ctx().clone();
|
|
let strip = ui.max_rect();
|
|
// A resize moves every tab at once: jump instead of sliding.
|
|
let resized = ctx.data_mut(|d| {
|
|
let last = d.get_temp_mut_or_insert_with(Id::new("tab-strip-width"), || strip.width());
|
|
let changed = (*last - strip.width()).abs() > 0.5;
|
|
*last = strip.width();
|
|
changed
|
|
});
|
|
let avail = strip.width() - theme::CONTROL_SMALL - theme::GAP_S;
|
|
let widths = tab_widths(f, avail);
|
|
let total = widths.iter().sum::<f32>() + TAB_GAP * widths.len().saturating_sub(1) as f32;
|
|
let shown_total = slide(&ctx, Id::new("tab-strip-total"), total, resized);
|
|
ui.horizontal_centered(|ui| {
|
|
ui.spacing_mut().item_spacing.x = theme::GAP_S;
|
|
egui::ScrollArea::horizontal().id_salt("tab-scroll").max_width(avail).auto_shrink([true, false]).scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden).show(ui, |ui| {
|
|
let (rect, _) = ui.allocate_exact_size(vec2(shown_total.max(total), STRIP), Sense::hover());
|
|
tabs_in(ui, f, rect, &widths, resized);
|
|
});
|
|
if icon_button(ui, icons::ADD, "New tab (Ctrl+T)").clicked() {
|
|
f.send(Command::NewTab);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
/// Tab widths: pinned tabs stay small, the others share what's left between `TAB_MIN` and `TAB_MAX`.
|
|
fn tab_widths(f: &Frame, avail: f32) -> Vec<f32> {
|
|
let pinned_width = |t: &crate::tabs::Tab| if t.audible() || t.muted { PINNED + INNER } else { PINNED };
|
|
let pinned: f32 = f.tabs.iter().filter(|t| t.pinned).map(pinned_width).sum();
|
|
let unpinned = f.tabs.iter().filter(|t| !t.pinned).count();
|
|
let gaps = TAB_GAP * f.tabs.len().saturating_sub(1) as f32;
|
|
let each = if unpinned == 0 { 0.0 } else { ((avail - pinned - gaps) / unpinned as f32).clamp(TAB_MIN, TAB_MAX) };
|
|
f.tabs.iter().map(|t| if t.pinned { pinned_width(t) } else { each }).collect()
|
|
}
|
|
|
|
/// A spring for positions that jumps when `jump` (window resized).
|
|
fn slide(ctx: &egui::Context, id: Id, target: f32, jump: bool) -> f32 {
|
|
if jump {
|
|
theme::spring_jump(ctx, id, target);
|
|
}
|
|
theme::spring(ctx, id, target, theme::DEFAULT)
|
|
}
|
|
|
|
fn tabs_in(ui: &mut Ui, f: &mut Frame, rect: Rect, widths: &[f32], resized: bool) {
|
|
let ctx = ui.ctx().clone();
|
|
let p = f.palette();
|
|
let n = f.tabs.len();
|
|
let mut slots = Vec::with_capacity(n);
|
|
let mut x = 0.0;
|
|
for w in widths {
|
|
slots.push(x);
|
|
x += w + TAB_GAP;
|
|
}
|
|
// While a tab is dragged it sits under the pointer and the others shift to where it would drop.
|
|
let dragged = f.ui.dragging_tab.and_then(|(id, grab)| f.tabs.iter().position(|t| t.id == id).map(|i| (i, grab)));
|
|
let pointer = ui.input(|i| i.pointer.interact_pos());
|
|
let mut drop_index = None;
|
|
let mut targets = slots.clone();
|
|
if let (Some((d, grab)), Some(pointer)) = (dragged, pointer) {
|
|
let x = (pointer.x - rect.left() - grab).clamp(0.0, (rect.width() - widths[d]).max(0.0));
|
|
let (shifted, to) = drag_layout(&slots, widths, d, x);
|
|
targets = shifted;
|
|
drop_index = Some(to);
|
|
}
|
|
let rects: Vec<Rect> = (0..n)
|
|
.map(|i| {
|
|
let id = Id::new(("tab-x", f.tabs[i].id));
|
|
let x = if dragged.is_some_and(|(d, _)| d == i) {
|
|
theme::spring_jump(&ctx, id, targets[i]);
|
|
targets[i]
|
|
} else {
|
|
slide(&ctx, id, targets[i], resized)
|
|
};
|
|
Rect::from_min_size(pos2(rect.left() + x, rect.center().y - TAB / 2.0), vec2(widths[i], TAB))
|
|
})
|
|
.collect();
|
|
// The selection pill slides between tabs; it follows a dragged tab exactly.
|
|
if let Some(active) = rects.get(*f.active) {
|
|
let jump = resized || dragged.is_some_and(|(d, _)| d == *f.active);
|
|
let left = slide(&ctx, Id::new("tab-pill-left"), active.left(), jump);
|
|
let right = slide(&ctx, Id::new("tab-pill-right"), active.right(), jump);
|
|
let pill = Rect::from_x_y_ranges(left..=right.max(left), active.y_range());
|
|
ui.painter().rect_filled(pill, theme::corner_radius(TAB / 2.0), p.secondary_container);
|
|
}
|
|
let mut order: Vec<usize> = (0..n).collect();
|
|
if let Some((d, _)) = dragged {
|
|
order.retain(|&i| i != d);
|
|
order.push(d);
|
|
}
|
|
let mut command = None;
|
|
for i in order {
|
|
let is_dragged = dragged.is_some_and(|(d, _)| d == i);
|
|
if let Some(c) = tab(ui, f, i, rects[i], is_dragged, drop_index) {
|
|
command = Some(c);
|
|
}
|
|
}
|
|
if let Some(c) = command {
|
|
f.send(c);
|
|
}
|
|
}
|
|
|
|
/// Where every tab goes while tab `d` is dragged to `x`: the index it would drop at, and each tab's x with the
|
|
/// others shifted to make room (the dragged one at `x`).
|
|
fn drag_layout(slots: &[f32], widths: &[f32], d: usize, x: f32) -> (Vec<f32>, usize) {
|
|
let n = slots.len();
|
|
let center = x + widths[d] / 2.0;
|
|
let to = (0..n).filter(|&i| i != d && slots[i] + widths[i] / 2.0 < center).count();
|
|
let mut order: Vec<usize> = (0..n).filter(|&i| i != d).collect();
|
|
order.insert(to, d);
|
|
let mut targets = vec![0.0; n];
|
|
let mut next = 0.0;
|
|
for &i in &order {
|
|
targets[i] = next;
|
|
next += widths[i] + TAB_GAP;
|
|
}
|
|
targets[d] = x;
|
|
(targets, to)
|
|
}
|
|
|
|
/// One tab at `rect`. Returns the command it asks for.
|
|
fn tab(ui: &mut Ui, f: &mut Frame, index: usize, rect: Rect, dragged: bool, drop_index: Option<usize>) -> Option<Command> {
|
|
let p = f.palette();
|
|
let ctx = ui.ctx().clone();
|
|
let t = &f.tabs[index];
|
|
let (tab_id, pinned, muted, audible, loading) = (t.id, t.pinned, t.muted, t.audible(), t.loading());
|
|
let title = t.display_title();
|
|
let url = t.shown_url();
|
|
let favicon = t.favicon.as_ref().map(|t| t.id());
|
|
let internal = t.page.is_some();
|
|
let active = index == *f.active;
|
|
let response = ui.interact(rect, Id::new(("tab", tab_id)), Sense::click_and_drag());
|
|
let (amount, press) = state_layer(ui, &response);
|
|
let selected = theme::effect(&ctx, Id::new(("tab-on", tab_id)), active);
|
|
let content = theme::layer(p.on_surface_variant, p.on_secondary_container, selected);
|
|
let body = rect.shrink(press * 1.5);
|
|
let radius = theme::corner_radius(TAB / 2.0);
|
|
if dragged {
|
|
crate::ui::paint::shadow(ui.painter(), body, TAB / 2.0, p.dark);
|
|
ui.painter().rect_filled(body, radius, if active { p.secondary_container } else { p.surface_container_high });
|
|
}
|
|
if amount > 0.0 || dragged {
|
|
ui.painter().rect_filled(body, radius, content.gamma_multiply(amount + if dragged { theme::DRAG } else { 0.0 }));
|
|
}
|
|
let cy = rect.center().y;
|
|
let icon_center = if pinned { pos2(rect.left() + PINNED / 2.0, cy) } else { pos2(rect.left() + theme::GAP_M + 8.0, cy) };
|
|
if loading {
|
|
spinner(ui, icon_center, 7.0, p.primary);
|
|
} else if let Some(texture) = favicon {
|
|
ui.painter().image(texture, Rect::from_center_size(icon_center, Vec2::splat(16.0)), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
|
} else {
|
|
icon(ui, icon_center, if internal { icons::TAB } else { icons::PUBLIC }, 16.0, active, content);
|
|
}
|
|
let hovered = response.hovered() || ui.rect_contains_pointer(rect);
|
|
let mut right = rect.right() - theme::GAP_XS - INNER / 2.0;
|
|
let mut command = None;
|
|
if !pinned && (rect.width() >= 110.0 || active || hovered) {
|
|
if inner_button(ui, pos2(right, cy), Id::new(("tab-close", tab_id)), icons::CLOSE, "Close tab (Ctrl+W)", content).clicked() {
|
|
command = Some(Command::CloseTab(tab_id));
|
|
}
|
|
right -= INNER;
|
|
}
|
|
if audible || muted {
|
|
let center = if pinned { pos2(rect.right() - theme::GAP_XS - INNER / 2.0, cy) } else { pos2(right, cy) };
|
|
if inner_button(ui, center, Id::new(("tab-mute", tab_id)), if muted { icons::VOLUME_OFF } else { icons::VOLUME_UP }, if muted { "Unmute tab" } else { "Mute tab" }, content).clicked() {
|
|
command = Some(Command::MuteTab(tab_id));
|
|
}
|
|
right -= INNER;
|
|
}
|
|
if !pinned {
|
|
let left = icon_center.x + 8.0 + theme::GAP_S;
|
|
let width = right + INNER / 2.0 - theme::GAP_XS - left;
|
|
if width > 8.0 {
|
|
let galley = menus::one_line(ui, &title, theme::font(theme::BODY, if active { Weight::Medium } else { Weight::Regular }), content, width);
|
|
ui.painter().galley(pos2(left, cy - galley.size().y / 2.0), galley, content);
|
|
}
|
|
}
|
|
let response = response.on_hover_text(format!("{title}\n{url}"));
|
|
if command.is_some() {
|
|
return command;
|
|
}
|
|
if response.middle_clicked() {
|
|
return Some(Command::CloseTab(tab_id));
|
|
}
|
|
if response.clicked() && !active {
|
|
return Some(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()
|
|
&& let Some(pos) = response.interact_pointer_pos()
|
|
{
|
|
f.ui.dragging_tab = Some((tab_id, pos.x - rect.left()));
|
|
}
|
|
if response.drag_stopped() && dragged {
|
|
f.ui.dragging_tab = None;
|
|
if let Some(to) = drop_index.filter(|&to| to != index) {
|
|
return Some(Command::MoveTab { from: index, to });
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// Toolbar buttons right of the address field, in the order they show.
|
|
const RIGHT_BUTTONS: &[&str] = &["passwords", "history", "bookmarks", "downloads", "qr", "apps", "devtools", "pip", "screenshot", "adblock", "media", "vpn"];
|
|
|
|
pub fn toolbar(root: &mut Ui, f: &mut Frame) {
|
|
let p = f.palette();
|
|
egui::Panel::top("toolbar").exact_size(TOOLBAR).frame(bar(&p)).show_separator_line(false).show(root, |ui| {
|
|
ui.horizontal_centered(|ui| {
|
|
ui.spacing_mut().item_spacing.x = theme::GAP_XS;
|
|
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_ui(can_back, |ui| icon_button(ui, glyph("back"), "Back (Alt+Left). Right-click for history")).inner;
|
|
if r.clicked() {
|
|
f.send(Command::Back);
|
|
}
|
|
if r.secondary_clicked() {
|
|
f.ui.flyout = Some(Flyout::BackHistory(r.rect.left_bottom() + vec2(0.0, theme::GAP_XS)));
|
|
}
|
|
}
|
|
if settings.toolbar_has("forward") && ui.add_enabled_ui(can_forward, |ui| icon_button(ui, glyph("forward"), "Forward (Alt+Right)")).inner.clicked() {
|
|
f.send(Command::Forward);
|
|
}
|
|
if settings.toolbar_has("reload") {
|
|
if loading {
|
|
if icon_button(ui, icons::CLOSE, "Stop loading (Esc)").clicked() {
|
|
f.send(Command::Stop);
|
|
}
|
|
} else if icon_button(ui, glyph("reload"), "Reload (Ctrl+R). Shift-click reloads without the 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);
|
|
}
|
|
if settings.toolbar_has("incognito") && icon_button(ui, glyph("incognito"), "New incognito window (Ctrl+Shift+N)").clicked() {
|
|
f.send(Command::NewIncognito);
|
|
}
|
|
ui.add_space(theme::GAP_XS);
|
|
// Buttons on the right first, so the address field can take what's left.
|
|
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
|
ui.spacing_mut().item_spacing.x = theme::GAP_XS;
|
|
let menu = icon_toggle(ui, icons::MORE_VERT, "Menu", f.ui.flyout == Some(Flyout::Main));
|
|
if menu.clicked() {
|
|
f.ui.toggle(Flyout::Main, Some(menu.rect));
|
|
}
|
|
profile_button(ui, f);
|
|
for key in RIGHT_BUTTONS.iter().rev() {
|
|
if settings.toolbar_has(key) {
|
|
right_button(ui, f, &settings, key);
|
|
}
|
|
}
|
|
ui.add_space(theme::GAP_XS);
|
|
ui.with_layout(Layout::left_to_right(Align::Center), |ui| omnibox(ui, f));
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
/// The profile avatar: the profile's initial, or the incognito mask. Shown with more than one profile.
|
|
fn profile_button(ui: &mut Ui, f: &mut Frame) {
|
|
if f.shared.profile_count() <= 1 && !f.incognito() {
|
|
return;
|
|
}
|
|
let p = f.palette();
|
|
let (rect, response) = ui.allocate_exact_size(Vec2::splat(theme::CONTROL_SMALL), Sense::click());
|
|
let (amount, press) = state_layer(ui, &response);
|
|
let (fill, content) = if f.incognito() { (p.tertiary_container, p.on_tertiary_container) } else { (p.primary_container, p.on_primary_container) };
|
|
let radius = 13.0 - press * 2.0;
|
|
ui.painter().circle_filled(rect.center(), radius, theme::layer(fill, content, amount));
|
|
if f.incognito() {
|
|
icon(ui, rect.center(), icons::DOMINO_MASK, 18.0, true, content);
|
|
} else {
|
|
let initial = f.shared.paths.profile.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default();
|
|
ui.painter().text(rect.center(), Align2::CENTER_CENTER, initial, theme::font(theme::BODY, Weight::SemiBold), content);
|
|
}
|
|
let tip = if f.incognito() { "Incognito window: nothing is saved".to_owned() } else { format!("Profile: {}", f.shared.paths.profile) };
|
|
if response.on_hover_text(tip).clicked() {
|
|
f.ui.toggle(Flyout::Profiles, Some(rect));
|
|
}
|
|
}
|
|
|
|
fn right_button(ui: &mut Ui, f: &mut Frame, settings: &crate::store::settings::Settings, key: &str) {
|
|
let p = f.palette();
|
|
let open = |f: &Frame, flyout: &Flyout| f.ui.flyout.as_ref() == Some(flyout);
|
|
match key {
|
|
"vpn" => {
|
|
let status = f.shared.vpn_status.borrow().clone();
|
|
let (dot, tip) = match &status {
|
|
VpnStatus::Off => (None, "VPN is off".to_owned()),
|
|
VpnStatus::Connecting(why) => (Some(p.warning), format!("VPN: {why}")),
|
|
VpnStatus::On(how) => (Some(p.success), format!("VPN on: {how}")),
|
|
VpnStatus::Failed(why) => (Some(p.error), format!("VPN: {why}")),
|
|
};
|
|
let r = icon_toggle(ui, glyph("vpn"), &tip, open(f, &Flyout::Vpn));
|
|
if let Some(color) = dot {
|
|
badge(ui, r.rect, "", color, color);
|
|
}
|
|
if r.clicked() {
|
|
f.ui.toggle(Flyout::Vpn, Some(r.rect));
|
|
}
|
|
},
|
|
"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 || open(f, &Flyout::Media),
|
|
};
|
|
if show {
|
|
let r = icon_toggle(ui, if playing { icons::GRAPHIC_EQ } else { glyph("media") }, "Media", open(f, &Flyout::Media));
|
|
if r.clicked() {
|
|
f.ui.toggle(Flyout::Media, Some(r.rect));
|
|
}
|
|
}
|
|
},
|
|
"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 off = !settings.adblock.enabled || paused;
|
|
let tip = if !settings.adblock.enabled { "Ad blocker is off".to_owned() } else if paused { "Ad blocker is paused on this site".to_owned() } else { format!("Ad blocker: {blocked} blocked on this page") };
|
|
let r = icon_toggle(ui, icons::SHIELD, &tip, open(f, &Flyout::Shield));
|
|
if off {
|
|
// A slash through the shield.
|
|
let c = r.rect.center();
|
|
ui.painter().line_segment([c + vec2(-7.0, -7.0), c + vec2(7.0, 7.0)], Stroke::new(2.0, p.on_surface_variant));
|
|
} else if blocked > 0 {
|
|
badge(ui, r.rect, &if blocked > 99 { "99+".to_owned() } else { blocked.to_string() }, p.primary, p.on_primary);
|
|
}
|
|
if r.clicked() {
|
|
f.ui.toggle(Flyout::Shield, Some(r.rect));
|
|
}
|
|
},
|
|
"downloads" => {
|
|
let downloads = f.shared.downloads.borrow();
|
|
let running = downloads.active_count();
|
|
let progress = downloads.overall_progress();
|
|
drop(downloads);
|
|
let tip = match (running, progress) {
|
|
(0, _) => "Downloads (Ctrl+J)".to_owned(),
|
|
(n, Some(p)) => format!("{n} downloading, {:.0}% done (Ctrl+J)", p * 100.0),
|
|
(n, None) => format!("{n} downloading (Ctrl+J)"),
|
|
};
|
|
let r = icon_toggle(ui, glyph("downloads"), &tip, open(f, &Flyout::Downloads));
|
|
if running > 0 {
|
|
// A ring round the button fills with the overall progress, or circles while the size is unknown.
|
|
let c = r.rect.center();
|
|
let radius = theme::CONTROL_SMALL / 2.0 - 1.0;
|
|
ui.painter().circle_stroke(c, radius, Stroke::new(2.0, p.secondary_container));
|
|
match progress {
|
|
Some(fraction) => {
|
|
let fraction = theme::spring(ui.ctx(), r.id.with("progress"), fraction as f32, theme::DEFAULT).clamp(0.0, 1.0);
|
|
let start = -std::f32::consts::FRAC_PI_2;
|
|
let points: Vec<Pos2> = (0..=40).map(|i| start + fraction * std::f32::consts::TAU * i as f32 / 40.0).map(|a| c + radius * vec2(a.cos(), a.sin())).collect();
|
|
ui.painter().add(egui::Shape::line(points, Stroke::new(2.0, p.primary)));
|
|
},
|
|
None => spinner(ui, c, radius, p.primary),
|
|
}
|
|
if running > 1 {
|
|
badge(ui, r.rect, &running.to_string(), p.primary, p.on_primary);
|
|
}
|
|
}
|
|
if r.clicked() {
|
|
f.ui.toggle(Flyout::Downloads, Some(r.rect));
|
|
}
|
|
},
|
|
"apps" => {
|
|
let r = icon_toggle(ui, glyph("apps"), "Apps", open(f, &Flyout::Apps));
|
|
if r.clicked() {
|
|
f.ui.toggle(Flyout::Apps, Some(r.rect));
|
|
}
|
|
},
|
|
"qr" => {
|
|
let url = f.tab().map(|t| t.url.clone()).unwrap_or_default();
|
|
let r = icon_toggle(ui, glyph("qr"), "QR code for this page", matches!(f.ui.flyout, Some(Flyout::Qr(_))));
|
|
if r.clicked() {
|
|
f.ui.toggle(Flyout::Qr(url), Some(r.rect));
|
|
}
|
|
},
|
|
_ => {
|
|
let (tip, command) = match key {
|
|
"devtools" => ("Developer tools (F12)", Command::Action(crate::keys::Action::DevTools)),
|
|
"history" => ("History (Ctrl+H)", Command::ShowPage(Page::History)),
|
|
"passwords" => ("Passwords", Command::ShowPage(Page::Passwords)),
|
|
"bookmarks" => ("Bookmarks", Command::ShowPage(Page::Bookmarks)),
|
|
"pip" => ("Picture in picture", Command::EnterPip),
|
|
"screenshot" => ("Save as PDF or image", Command::PrintPage),
|
|
_ => return,
|
|
};
|
|
if 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)
|
|
}
|
|
}
|
|
|
|
/// How safe the current page's connection is, for the site button at the start of the address field.
|
|
#[derive(Clone, Copy, PartialEq)]
|
|
enum Security {
|
|
Internal,
|
|
Secure,
|
|
NotSecure,
|
|
Local,
|
|
}
|
|
|
|
/// The address field: a pill with the site button, the address (host stands out while not editing), zoom and
|
|
/// install chips and the star. Focus lifts it to the lightest surface with a ring.
|
|
fn omnibox(ui: &mut Ui, f: &mut Frame) {
|
|
let p = f.palette();
|
|
let ctx = ui.ctx().clone();
|
|
let Some(tab) = f.tab() else { return };
|
|
let shown = tab.shown_url();
|
|
let is_web = tab.page.is_none();
|
|
let security = if !is_web {
|
|
Security::Internal
|
|
} else if shown.starts_with("https://") {
|
|
Security::Secure
|
|
} else if shown.starts_with("http://") {
|
|
Security::NotSecure
|
|
} else {
|
|
Security::Local
|
|
};
|
|
let zoom = tab.zoom;
|
|
let bookmarked = is_web && f.shared.bookmarks.borrow().is_bookmarked(&tab.url);
|
|
let installable = is_web && shown.starts_with("http") && url::Url::parse(&shown).is_ok_and(|u| f.shared.apps.borrow().for_url(&u).is_none());
|
|
let (tab_id, loading) = (tab.id, tab.loading());
|
|
let estimate = load_estimate(tab.load_status, tab.load_started.map(|t| t.elapsed().as_secs_f32()).unwrap_or(0.0));
|
|
let id = ui.id().with("omnibox");
|
|
let (rect, background) = ui.allocate_exact_size(vec2(ui.available_width().max(160.0), theme::CONTROL), Sense::hover());
|
|
let pointer = background.hovered() || ui.rect_contains_pointer(rect);
|
|
let focus = theme::effect(&ctx, id.with("focus"), f.ui.omnibox_focused);
|
|
let hover = theme::effect(&ctx, id.with("hover"), pointer);
|
|
// While the page loads the whole pill turns into a wavy progress bar; the pointer, focus or typing bring the
|
|
// field back. After the load it fills to the end before the field comes back.
|
|
let progress_id = Id::new(("load-progress", tab_id));
|
|
let mut progress = theme::spring(&ctx, progress_id, if loading { estimate } else { 1.0 }, theme::EFFECT);
|
|
if loading && progress > estimate + 0.25 {
|
|
// A new load after a finished one starts from the left again.
|
|
theme::spring_jump(&ctx, progress_id, 0.0);
|
|
progress = 0.0;
|
|
}
|
|
let was_wave = ctx.data(|d| d.get_temp::<bool>(id.with("wave-on"))).unwrap_or(false);
|
|
let engaged = pointer || f.ui.omnibox_focused || f.ui.omnibox_edit.is_some();
|
|
let wave_on = !engaged && (loading || (was_wave && progress < 0.995));
|
|
ctx.data_mut(|d| d.insert_temp(id.with("wave-on"), wave_on));
|
|
let morph = theme::spring(&ctx, id.with("wave"), if wave_on { 1.0 } else { 0.0 }, theme::DEFAULT);
|
|
let m = morph.clamp(0.0, 1.0);
|
|
let fill = theme::layer(theme::layer(p.surface_container_highest, p.on_surface, theme::HOVER * hover * (1.0 - focus)), p.surface_container_lowest, focus);
|
|
// The pill squeezes down to the progress track (spring, may overshoot a little in height).
|
|
let squeeze = morph.clamp(0.0, 1.1);
|
|
let pill = rect.shrink2(vec2(theme::GAP_S * m, ((theme::CONTROL - WAVE_TRACK) / 2.0 * squeeze).min(theme::CONTROL / 2.0 - 1.0)));
|
|
let radius = theme::corner_radius(pill.height() / 2.0);
|
|
ui.painter().rect_filled(pill, radius, theme::layer(fill, p.secondary_container, m));
|
|
if focus > 0.0 {
|
|
ui.painter().rect_stroke(pill, radius, Stroke::new(2.0, p.primary.gamma_multiply(focus)), StrokeKind::Inside);
|
|
}
|
|
if m > 0.0 {
|
|
let mut painter = ui.painter().clone();
|
|
painter.set_opacity(m);
|
|
let phase = if wave_on { ctx.input(|i| i.time) as f32 * 5.0 } else { 0.0 };
|
|
crate::ui::paint::wavy_progress(&painter, pill, progress, 3.0 * m, phase, &p);
|
|
ctx.request_repaint();
|
|
}
|
|
let mut inner = ui.new_child(UiBuilder::new().max_rect(rect.shrink2(vec2(theme::GAP_XS, 0.0))).layout(Layout::left_to_right(Align::Center)));
|
|
inner.spacing_mut().item_spacing.x = 0.0;
|
|
inner.set_opacity(1.0 - m);
|
|
let ui = &mut inner;
|
|
// Site button: a chip that says what kind of connection this is.
|
|
let (glyph, label, color, tip) = match security {
|
|
Security::Internal => (icons::TAB, "", p.on_surface_variant, "Nacre page"),
|
|
Security::Secure => (icons::LOCK, "", p.on_surface_variant, "Connection is secure. Site information and permissions"),
|
|
Security::NotSecure => (icons::WARNING, "Not secure", p.error, "Connection is not secure: others on the network can see and change this page"),
|
|
Security::Local => (icons::INFO, "", p.on_surface_variant, "Site information"),
|
|
};
|
|
let site = chip(ui, glyph, label, color, tip, f.ui.flyout == Some(Flyout::SiteInfo));
|
|
if site.clicked() && is_web {
|
|
f.ui.toggle(Flyout::SiteInfo, Some(site.rect));
|
|
}
|
|
let right_space = INNER * (is_web as u8 + installable as u8) as f32 + if (zoom - 1.0).abs() > 0.001 { 56.0 } else { 0.0 } + theme::GAP_S;
|
|
let width = (ui.available_width() - right_space).max(80.0);
|
|
let mut text = f.ui.omnibox_edit.clone().unwrap_or_else(|| if shown == "nacre://newtab" { String::new() } else { shown.clone() });
|
|
let engine = f.shared.settings.borrow().search_engine_name();
|
|
let font = theme::font(theme::BODY, Weight::Regular);
|
|
let emphasize = !f.ui.omnibox_focused && f.ui.omnibox_edit.is_none();
|
|
let mut layouter = |ui: &Ui, buffer: &dyn egui::TextBuffer, _wrap: f32| {
|
|
let job = address_job(buffer.as_str(), emphasize, &p, font.clone());
|
|
ui.fonts_mut(|fonts| fonts.layout_job(job))
|
|
};
|
|
let output = egui::TextEdit::singleline(&mut text)
|
|
.id(id)
|
|
.frame(egui::Frame::NONE)
|
|
.margin(egui::Margin { left: theme::GAP_S as i8, right: theme::GAP_S as i8, top: 4, bottom: 0 })
|
|
.hint_text(RichText::new(format!("Search with {engine} or type an address")).color(p.on_surface_variant))
|
|
.layouter(&mut layouter)
|
|
.desired_width(width)
|
|
.show(ui);
|
|
let response = output.response;
|
|
let requested = f.ui.focus_omnibox;
|
|
if requested {
|
|
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(&ctx, id);
|
|
}
|
|
let focused = response.has_focus();
|
|
// egui keeps showing a selection after focus leaves; the address at rest shows none.
|
|
if !focused
|
|
&& !requested
|
|
&& let Some(mut state) = egui::TextEdit::load_state(&ctx, id)
|
|
&& state.cursor.char_range().is_some_and(|r| r.primary != r.secondary)
|
|
{
|
|
state.cursor.set_char_range(None);
|
|
state.store(&ctx, id);
|
|
}
|
|
if response.gained_focus() && f.ui.omnibox_edit.is_none() {
|
|
let mut state = egui::TextEdit::load_state(&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(&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();
|
|
let open = focused && editing.as_ref().is_some_and(|q| !q.trim().is_empty());
|
|
if let Some(query) = editing.as_ref().filter(|_| open) {
|
|
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, rect, open);
|
|
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;
|
|
}
|
|
// Chips at the end: zoom (click resets), install, the star.
|
|
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
|
if is_web {
|
|
let (rect, _) = ui.allocate_exact_size(vec2(INNER + theme::GAP_XS, theme::CONTROL), Sense::hover());
|
|
let tip = if bookmarked { "Edit bookmark (Ctrl+D)" } else { "Bookmark this page (Ctrl+D)" };
|
|
let star_id = Id::new("omnibox-star");
|
|
let on = theme::effect(&ctx, star_id.with("on"), bookmarked);
|
|
let star = inner_button(ui, rect.center(), star_id, "", tip, p.on_surface_variant);
|
|
// The star fills and turns to the accent when the page is bookmarked; it pops a little as it does.
|
|
let size = 18.0 * (1.0 + 0.25 * (on * std::f32::consts::PI).sin());
|
|
icon(ui, rect.center(), icons::STAR, size, bookmarked, theme::layer(p.on_surface_variant, p.primary, on));
|
|
if star.clicked() {
|
|
if bookmarked {
|
|
let url = f.tabs[*f.active].url.clone();
|
|
f.ui.toggle(Flyout::EditBookmark(url), Some(star.rect));
|
|
} else {
|
|
f.send(Command::ToggleBookmark);
|
|
}
|
|
}
|
|
}
|
|
if installable {
|
|
let (rect, _) = ui.allocate_exact_size(vec2(INNER, theme::CONTROL), Sense::hover());
|
|
if inner_button(ui, rect.center(), Id::new("omnibox-install"), icons::INSTALL_DESKTOP, "Install this site as an app", p.on_surface_variant).clicked() {
|
|
f.send(Command::InstallApp);
|
|
}
|
|
}
|
|
if (zoom - 1.0).abs() > 0.001 {
|
|
let label = format!("{:.0}%", zoom * 100.0);
|
|
if chip(ui, icons::ZOOM_IN, &label, p.on_surface_variant, "Zoom. Click to reset", false).clicked() {
|
|
f.send(Command::Zoom(0));
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
/// A small pill inside the address field: an icon and maybe a label, with a state layer.
|
|
fn chip(ui: &mut Ui, glyph: &str, label: &str, color: Color32, tooltip: &str, on: bool) -> Response {
|
|
let p = theme::palette(ui.ctx());
|
|
let galley = (!label.is_empty()).then(|| ui.painter().layout_no_wrap(label.to_owned(), theme::font(theme::SMALL, Weight::Medium), color));
|
|
let width = 32.0 + galley.as_ref().map(|g| g.size().x + theme::GAP_S).unwrap_or(0.0);
|
|
let (rect, response) = ui.allocate_exact_size(vec2(width, 32.0), Sense::click());
|
|
let (amount, press) = state_layer(ui, &response);
|
|
let selected = theme::effect(ui.ctx(), response.id.with("on"), on);
|
|
let body = rect.shrink(press);
|
|
let fill = if galley.is_some() { theme::layer(p.surface_container_highest, color, 0.12) } else { Color32::TRANSPARENT };
|
|
let fill = theme::layer(theme::layer(fill, p.secondary_container, selected), color, amount);
|
|
if fill != Color32::TRANSPARENT && (galley.is_some() || amount + selected > 0.0) {
|
|
ui.painter().rect_filled(body, theme::corner_radius(16.0), fill);
|
|
}
|
|
icon(ui, pos2(rect.left() + 16.0, rect.center().y), glyph, 18.0, false, color);
|
|
if let Some(galley) = galley {
|
|
ui.painter().galley(pos2(rect.left() + 30.0, rect.center().y - galley.size().y / 2.0), galley, color);
|
|
}
|
|
if response.has_focus() {
|
|
focus_ring(ui, rect, 16.0, &p);
|
|
}
|
|
response.on_hover_text(tooltip)
|
|
}
|
|
|
|
/// Height of the progress track the address pill squeezes into while a page loads.
|
|
const WAVE_TRACK: f32 = 4.0;
|
|
|
|
/// How far a load has got, 0..1. Servo reports only stages, so this eases towards a cap per stage: up to 0.6
|
|
/// until the head is parsed, then up to 0.92 until it completes.
|
|
fn load_estimate(status: Option<servo::LoadStatus>, seconds: f32) -> f32 {
|
|
let ease = |cap: f32, tau: f32| cap * (1.0 - (-seconds / tau).exp());
|
|
match status {
|
|
Some(servo::LoadStatus::Started) => 0.05 + ease(0.55, 1.5),
|
|
Some(servo::LoadStatus::HeadParsed) => 0.6 + ease(0.32, 2.0),
|
|
_ => 1.0,
|
|
}
|
|
}
|
|
|
|
/// The address with the host in full colour and the rest dimmed, while not editing.
|
|
fn address_job(text: &str, emphasize: bool, p: &Palette, font: egui::FontId) -> egui::text::LayoutJob {
|
|
let mut job = egui::text::LayoutJob::default();
|
|
let format = |color| egui::TextFormat::simple(font.clone(), color);
|
|
let host = emphasize.then(|| text.find("://")).flatten().map(|i| {
|
|
let start = i + 3;
|
|
let end = text[start..].find(['/', '?', '#']).map(|j| start + j).unwrap_or(text.len());
|
|
(start, end)
|
|
});
|
|
match host {
|
|
Some((start, end)) => {
|
|
job.append(&text[..start], 0.0, format(p.on_surface_variant));
|
|
job.append(&text[start..end], 0.0, format(p.on_surface));
|
|
job.append(&text[end..], 0.0, format(p.on_surface_variant));
|
|
},
|
|
None => job.append(text, 0.0, format(p.on_surface)),
|
|
}
|
|
job
|
|
}
|
|
|
|
/// Everything the address bar offers for what was typed.
|
|
fn suggestions(f: &Frame, query: &str) -> Vec<Suggestion> {
|
|
let mut out = Vec::new();
|
|
let template = f.shared.settings.borrow().search_template();
|
|
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: query.to_owned(), 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 }),
|
|
}
|
|
}
|
|
|
|
/// The suggestions under the address field: grows open from it, fades away when it closes.
|
|
fn suggestion_popup(ui: &mut Ui, f: &mut Frame, field: Rect, open: bool) {
|
|
if f.ui.omnibox_items.is_empty() {
|
|
return;
|
|
}
|
|
let items = f.ui.omnibox_items.clone();
|
|
let selected = f.ui.suggestion_index;
|
|
let engine = f.shared.settings.borrow().search_engine_name();
|
|
let mut clicked = None;
|
|
let pos = field.left_bottom() + vec2(0.0, theme::GAP_XS);
|
|
menus::floating(ui.ctx(), Id::new("omnibox-suggestions"), pos, Align2::LEFT_TOP, open, |ui| {
|
|
ui.set_width(field.width() - 2.0 * theme::GAP_S);
|
|
for (i, s) in items.iter().enumerate() {
|
|
let glyph = match s.kind {
|
|
SuggestionKind::Search | SuggestionKind::SearchSuggestion => icons::SEARCH,
|
|
SuggestionKind::Url => icons::PUBLIC,
|
|
SuggestionKind::History => icons::HISTORY,
|
|
SuggestionKind::Bookmark => icons::STAR,
|
|
SuggestionKind::Tab(_) => icons::TAB,
|
|
SuggestionKind::Page => icons::SETTINGS,
|
|
};
|
|
let detail = match s.kind {
|
|
SuggestionKind::Search => format!("Search with {engine}"),
|
|
SuggestionKind::History | SuggestionKind::Bookmark | SuggestionKind::Tab(_) => util::host_of_str(&s.url),
|
|
_ => String::new(),
|
|
};
|
|
let title = if s.title.is_empty() { &s.url } else { &s.title };
|
|
if menus::menu_item(ui, Some(glyph), title, &detail, selected == Some(i)).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) {
|
|
let p = f.palette();
|
|
egui::Panel::top("bookmarks-bar").exact_size(BOOKMARKS).frame(bar(&p)).show_separator_line(false).show(root, |ui| {
|
|
ui.horizontal_centered(|ui| {
|
|
ui.spacing_mut().item_spacing.x = theme::GAP_XS;
|
|
let items: Vec<crate::store::bookmarks::Node> = f.shared.bookmarks.borrow().bar.children.clone();
|
|
if items.is_empty() {
|
|
ui.add_space(theme::GAP_S);
|
|
icon(ui, pos2(ui.cursor().left() + 8.0, ui.max_rect().center().y), icons::STAR, 16.0, false, p.on_surface_variant);
|
|
ui.add_space(16.0 + theme::GAP_S);
|
|
ui.label(RichText::new("Bookmarks you add to the bar show up here. Click the star in the address field or press Ctrl+D").font(theme::font(theme::SMALL, Weight::Regular)).color(p.on_surface_variant));
|
|
}
|
|
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
|
if bar_chip(ui, Some(icons::BOOKMARKS), "All bookmarks", None).clicked() {
|
|
f.send(Command::ShowPage(Page::Bookmarks));
|
|
}
|
|
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
|
|
ui.set_clip_rect(ui.max_rect());
|
|
for node in items {
|
|
bookmark_item(ui, f, &node);
|
|
}
|
|
});
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
/// A bookmark on the bar: a small pill with an icon and the title.
|
|
fn bar_chip(ui: &mut Ui, glyph: Option<&str>, label: &str, trailing: Option<&str>) -> Response {
|
|
let p = theme::palette(ui.ctx());
|
|
let galley = ui.painter().layout_no_wrap(util::ellipsize(label, 24), theme::font(theme::SMALL, Weight::Medium), p.on_surface);
|
|
let lead = if glyph.is_some() { 16.0 + theme::GAP_S } else { 0.0 };
|
|
let tail = if trailing.is_some() { 16.0 + theme::GAP_XS } else { 0.0 };
|
|
let (rect, response) = ui.allocate_exact_size(vec2(theme::GAP_M * 2.0 + lead + galley.size().x + tail, 28.0), Sense::click());
|
|
let (amount, press) = state_layer(ui, &response);
|
|
if amount > 0.0 {
|
|
ui.painter().rect_filled(rect.shrink(press), theme::corner_radius(14.0), p.on_surface.gamma_multiply(amount));
|
|
}
|
|
let mut x = rect.left() + theme::GAP_M;
|
|
if let Some(glyph) = glyph {
|
|
icon(ui, pos2(x + 8.0, rect.center().y), glyph, 16.0, false, p.on_surface_variant);
|
|
x += lead;
|
|
}
|
|
let width = galley.size().x;
|
|
ui.painter().galley(pos2(x, rect.center().y - galley.size().y / 2.0), galley, p.on_surface);
|
|
if let Some(glyph) = trailing {
|
|
icon(ui, pos2(x + width + theme::GAP_XS + 8.0, rect.center().y), glyph, 16.0, false, p.on_surface_variant);
|
|
}
|
|
if response.has_focus() {
|
|
focus_ring(ui, rect, 14.0, &p);
|
|
}
|
|
response
|
|
}
|
|
|
|
fn bookmark_item(ui: &mut Ui, f: &mut Frame, node: &crate::store::bookmarks::Node) {
|
|
match &node.url {
|
|
Some(url) => {
|
|
let r = bar_chip(ui, Some(icons::PUBLIC), &node.title, None).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 => {
|
|
let r = bar_chip(ui, Some(icons::FOLDER), &node.title, Some(icons::EXPAND_MORE));
|
|
egui::Popup::menu(&r).frame(menus::surface(&f.palette(), ui.ctx())).show(|ui| {
|
|
ui.spacing_mut().item_spacing.y = 2.0;
|
|
ui.set_min_width(220.0);
|
|
folder_menu(ui, f, node);
|
|
});
|
|
},
|
|
}
|
|
}
|
|
|
|
fn folder_menu(ui: &mut Ui, f: &mut Frame, folder: &crate::store::bookmarks::Node) {
|
|
if folder.children.is_empty() {
|
|
menus::empty(ui, "This folder is empty");
|
|
}
|
|
for child in &folder.children {
|
|
match &child.url {
|
|
Some(url) => {
|
|
if menus::menu_item(ui, Some(icons::PUBLIC), &child.title, "", false).on_hover_text(url).clicked() {
|
|
f.send(Command::Open { url: url.clone(), how: Disposition::Current, from: None });
|
|
ui.close();
|
|
}
|
|
},
|
|
None => {
|
|
ui.menu_button(format!("{} {}", icons::FOLDER, util::ellipsize(&child.title, 40)), |ui| folder_menu(ui, f, child));
|
|
},
|
|
}
|
|
}
|
|
if folder.children.iter().filter(|c| c.url.is_some()).count() > 1 {
|
|
menus::divider(ui);
|
|
if menus::menu_item(ui, Some(icons::OPEN_IN_NEW), "Open all in new tabs", "", false).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) {
|
|
let p = f.palette();
|
|
egui::Panel::top("app-bar").exact_size(44.0).frame(bar(&p)).show_separator_line(false).show(root, |ui| {
|
|
ui.horizontal_centered(|ui| {
|
|
ui.spacing_mut().item_spacing.x = theme::GAP_XS;
|
|
let can_back = f.tab().is_some_and(|t| t.can_go_back());
|
|
if ui.add_enabled_ui(can_back, |ui| icon_button(ui, icons::ARROW_BACK, "Back (Alt+Left)")).inner.clicked() {
|
|
f.send(Command::Back);
|
|
}
|
|
if icon_button(ui, icons::REFRESH, "Reload (Ctrl+R)").clicked() {
|
|
f.send(Command::Reload { hard: false });
|
|
}
|
|
ui.add_space(theme::GAP_S);
|
|
let title = f.tab().map(|t| t.display_title()).unwrap_or_default();
|
|
ui.label(RichText::new(util::ellipsize(&title, 80)).font(theme::font(theme::BODY, Weight::Medium)).color(p.on_surface));
|
|
if let Some(url) = f.tab().map(|t| t.url.clone()) {
|
|
ui.label(RichText::new(util::host_of_str(&url)).font(theme::font(theme::SMALL, Weight::Regular)).color(p.on_surface_variant));
|
|
}
|
|
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
|
let menu = icon_toggle(ui, icons::MORE_VERT, "Menu", f.ui.flyout == Some(Flyout::Main));
|
|
if menu.clicked() {
|
|
f.ui.toggle(Flyout::Main, Some(menu.rect));
|
|
}
|
|
if icon_button(ui, icons::OPEN_IN_NEW, "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(icons::FAST_REWIND)).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(icons::PLAY_PAUSE)).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(icons::FAST_FORWARD)).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(icons::VOLUME_OFF)).frame(false)).on_hover_text("Mute").clicked() {
|
|
f.send(Command::PipAct { action: "mute".into(), value: 0.0 });
|
|
}
|
|
if ui.add(egui::Button::new(white(icons::PIP_EXIT)).frame(false)).on_hover_text("Back to the tab").clicked() {
|
|
f.send(Command::ExitPip);
|
|
}
|
|
});
|
|
});
|
|
});
|
|
let _ = f.pip_size;
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn dragged_tab_drops_where_its_middle_is_and_the_others_make_room() {
|
|
let widths = [100.0, 100.0, 100.0];
|
|
let slots = [0.0, 104.0, 208.0];
|
|
// The first tab dragged past the middle of the second: it drops at 1, the second moves to the front.
|
|
let (targets, to) = drag_layout(&slots, &widths, 0, 120.0);
|
|
assert_eq!(to, 1);
|
|
assert_eq!(targets, vec![120.0, 0.0, 208.0]);
|
|
// Not far enough: it stays first and nobody moves.
|
|
let (targets, to) = drag_layout(&slots, &widths, 0, 40.0);
|
|
assert_eq!(to, 0);
|
|
assert_eq!(targets, vec![40.0, 104.0, 208.0]);
|
|
// The last tab dragged to the start.
|
|
let (_, to) = drag_layout(&slots, &widths, 2, 0.0);
|
|
assert_eq!(to, 0);
|
|
}
|
|
|
|
#[test]
|
|
fn load_estimate_grows_by_stage_and_never_reaches_the_end_early() {
|
|
use servo::LoadStatus::{Complete, HeadParsed, Started};
|
|
assert!(load_estimate(Some(Started), 0.0) > 0.0);
|
|
assert!(load_estimate(Some(Started), 1.0) < load_estimate(Some(Started), 3.0));
|
|
assert!(load_estimate(Some(Started), 100.0) <= 0.6 + 1e-4);
|
|
assert!(load_estimate(Some(HeadParsed), 0.0) >= load_estimate(Some(Started), 100.0) - 1e-4);
|
|
assert!(load_estimate(Some(HeadParsed), 100.0) < 0.95);
|
|
assert_eq!(load_estimate(Some(Complete), 0.0), 1.0);
|
|
}
|
|
|
|
#[test]
|
|
fn address_shows_the_host_in_full_colour() {
|
|
let p = Palette::new(Color32::from_rgb(0x67, 0x50, 0xA4), true, "tonal_spot", 0.0);
|
|
let font = egui::FontId::proportional(14.0);
|
|
let job = address_job("https://example.org/path?q=1", true, &p, font.clone());
|
|
let parts: Vec<(&str, Color32)> = job.sections.iter().map(|s| (&job.text[s.byte_range.start.0..s.byte_range.end.0], s.format.color)).collect();
|
|
assert_eq!(parts, vec![("https://", p.on_surface_variant), ("example.org", p.on_surface), ("/path?q=1", p.on_surface_variant)]);
|
|
// While editing, or for text that isn't an address, all of it is plain.
|
|
assert_eq!(address_job("https://example.org/", false, &p, font.clone()).sections.len(), 1);
|
|
assert_eq!(address_job("cats", true, &p, font).sections.len(), 1);
|
|
}
|
|
}
|