mirror of
https://github.com/mileswolfallen2/browser.git
synced 2026-09-08 11:23:18 +00:00
feat: initial implementation of a browser application using egui and wgpu
- Added Cargo.toml with dependencies for egui, wgpu, and other libraries. - Implemented main application logic in src/app.rs, including window management, rendering, and tab handling. - Created a new module src/servo_host.rs to manage interactions with the Servo engine and webview. - Established event handling for user inputs, including keyboard and mouse events. - Integrated a basic UI layout with a tab strip, toolbar, and status bar. - Implemented functionality for navigating URLs and managing multiple tabs.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
/target
|
||||
Generated
+10557
File diff suppressed because it is too large
Load Diff
+20
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "browser"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
egui = "0.36.1"
|
||||
egui-wgpu = "0.36.1"
|
||||
egui-winit = "0.36.1"
|
||||
env_logger = "0.11.11"
|
||||
euclid = "0.22"
|
||||
image = "0.25"
|
||||
keyboard-types = "0.8"
|
||||
log = "0.4.33"
|
||||
pollster = "0.4"
|
||||
rustls = "0.23"
|
||||
servo = "0.5.0"
|
||||
url = "2"
|
||||
wgpu = "30.0.0"
|
||||
winit = "0.30.13"
|
||||
@@ -1,2 +1,77 @@
|
||||
# browser
|
||||
idk
|
||||
|
||||
A minimal Firefox-style web browser built on [Servo](https://servo.org), the Rust web engine — **the newest actively maintained browser built on Servo**, written against the [`servo` crate](https://crates.io/crates/servo) embedding API (v0.1+, released April 2026).
|
||||
|
||||
> **Context:** [Verso](https://github.com/versotile-org/verso), the pioneering third-party Servo browser, was archived in October 2025 and is no longer maintained. Servo's own servoshell remains a demo mini-browser for testing the engine. This project picks up the embedder-side baton on the new public `servo` crates.io API — no engine fork required.
|
||||
|
||||
## What works
|
||||
|
||||
- Tab strip with create/close/switch
|
||||
- Back / forward / reload navigation with real history state
|
||||
- URL bar with address parsing and DuckDuckGo search fallback (`localhost` handled too)
|
||||
- Pages render via Servo into offscreen surfaces and composite under the native chrome
|
||||
- Mouse, scroll wheel, and keyboard input forwarded to the page
|
||||
- Live page titles, loading spinners, and hover status bar
|
||||
- `window.open()` / target=_blank opens a new tab
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────┐
|
||||
│ Chrome UI: egui 0.36 + wgpu │ tabs · toolbar · status bar
|
||||
├──────────────────────────────────────────┤
|
||||
│ Frame bridge │ WebView::paint() → read_to_image()
|
||||
├──────────────────────────────────────────┤
|
||||
│ Engine: servo 0.5 crate │ Stylo · SpiderMonkey · WebRender
|
||||
│ one WebView per tab, each with its own │
|
||||
│ OffscreenRenderingContext │
|
||||
└──────────────────────────────────────────┘
|
||||
windowing: winit · rendering: wgpu (Metal/Vulkan/DX12)
|
||||
```
|
||||
|
||||
The embedder owns everything above the engine: windowing, chrome, input routing,
|
||||
and history UI. Servo owns layout, JS, networking, and painting. The two talk through
|
||||
`WebView::notify_input_event` (down) and a `WebViewDelegate` message queue (up).
|
||||
|
||||
## Building
|
||||
|
||||
Requires a stable Rust toolchain (1.85+ recommended):
|
||||
|
||||
```sh
|
||||
cargo build --release
|
||||
cargo run --release
|
||||
```
|
||||
|
||||
First build takes a while — the servo crate compiles SpiderMonkey (C++) and the full
|
||||
WebRender pipeline. Incremental rebuilds after that are fast.
|
||||
|
||||
Tested on macOS (Apple Silicon). Windows and Linux should work in principle since all
|
||||
dependencies are cross-platform, but they haven't been exercised yet.
|
||||
|
||||
## Known limitations
|
||||
|
||||
This is an early-days project on top of an engine that is itself pre-1.0:
|
||||
|
||||
- No DRM video (Widevine), and some sites will simply not render correctly yet —
|
||||
that's Servo's web-compat surface area, not something the embedder can fix
|
||||
- Frames are composited through CPU readback, so heavy pages cost more than a
|
||||
zero-copy GPU path would (fine for basic browsing)
|
||||
- No bookmarks/history persistence, downloads, devtools, or preferences UI yet
|
||||
|
||||
## Roadmap
|
||||
|
||||
- [ ] Zero-copy frame path (share GL textures instead of readback)
|
||||
- [ ] Bookmarks and browsing history
|
||||
- [ ] Page context menus
|
||||
- [ ] Dark mode following system theme
|
||||
- [ ] Linux CI builds
|
||||
|
||||
## Credits
|
||||
|
||||
Built on the shoulders of the [Servo project](https://servo.org) (Linux Foundation Europe),
|
||||
with the chrome rendered by [egui](https://github.com/emilk/egui). Design cues from Firefox.
|
||||
See also [Verso](https://github.com/versotile-org/verso) (archived) — the pioneering Servo embedder whose contributions live on upstream.
|
||||
|
||||
## License
|
||||
|
||||
See [LICENSE](LICENSE).
|
||||
|
||||
+879
@@ -0,0 +1,879 @@
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use egui_wgpu::{Renderer, RendererOptions, ScreenDescriptor};
|
||||
use egui_winit::State as EguiWinitState;
|
||||
use keyboard_types::Modifiers;
|
||||
use servo::RenderingContext;
|
||||
use url::Url;
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
|
||||
use winit::event::{ElementState, WindowEvent};
|
||||
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy};
|
||||
use winit::raw_window_handle::{HasDisplayHandle, HasWindowHandle};
|
||||
use winit::window::{Window, WindowId};
|
||||
|
||||
use crate::servo_host::{
|
||||
self, make_keyboard_input, winit_button_action_to_servo, winit_button_to_servo, wheel_input,
|
||||
Engine, EngineMsg, EguiWaker, Tab,
|
||||
};
|
||||
use crate::UserEvent;
|
||||
|
||||
const START_PAGE: &str = "https://servo.org/";
|
||||
const CHROME_BG: egui::Color32 = egui::Color32::from_rgb(240, 240, 244);
|
||||
const CHROME_BG_DARKER: egui::Color32 = egui::Color32::from_rgb(223, 223, 230);
|
||||
const TAB_ACTIVE_BG: egui::Color32 = egui::Color32::WHITE;
|
||||
const ACCENT: egui::Color32 = egui::Color32::from_rgb(0, 97, 224);
|
||||
|
||||
pub struct BrowserApp {
|
||||
proxy: EventLoopProxy<UserEvent>,
|
||||
window: Option<Arc<Window>>,
|
||||
gpu: Option<Gpu>,
|
||||
engine: Option<Rc<Engine>>,
|
||||
tabs: Vec<Tab>,
|
||||
active: usize,
|
||||
url_edit: String,
|
||||
url_bar_focused: bool,
|
||||
content_focused: bool,
|
||||
content_rect: egui::Rect,
|
||||
last_cursor_pos: PhysicalPosition<f64>,
|
||||
modifiers: Modifiers,
|
||||
scale_factor: f64,
|
||||
pending_close: Option<usize>,
|
||||
}
|
||||
|
||||
struct Gpu {
|
||||
surface: wgpu::Surface<'static>,
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
config: wgpu::SurfaceConfiguration,
|
||||
egui_ctx: egui::Context,
|
||||
egui_winit: EguiWinitState,
|
||||
renderer: Renderer,
|
||||
}
|
||||
|
||||
impl BrowserApp {
|
||||
pub fn new(proxy: EventLoopProxy<UserEvent>) -> BrowserApp {
|
||||
BrowserApp {
|
||||
proxy,
|
||||
window: None,
|
||||
gpu: None,
|
||||
engine: None,
|
||||
tabs: Vec::new(),
|
||||
active: 0,
|
||||
url_edit: START_PAGE.to_owned(),
|
||||
url_bar_focused: false,
|
||||
content_focused: false,
|
||||
content_rect: egui::Rect::NOTHING,
|
||||
last_cursor_pos: PhysicalPosition::new(0.0, 0.0),
|
||||
modifiers: Modifiers::empty(),
|
||||
scale_factor: 1.0,
|
||||
pending_close: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn init(&mut self, event_loop: &ActiveEventLoop) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let attrs =
|
||||
Window::default_attributes()
|
||||
.with_title("Fox")
|
||||
.with_inner_size(LogicalSize::new(1360.0, 900.0));
|
||||
let window = Arc::new(event_loop.create_window(attrs)?);
|
||||
self.scale_factor = window.scale_factor();
|
||||
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
|
||||
let surface = instance.create_surface(window.clone())?;
|
||||
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::HighPerformance,
|
||||
compatible_surface: Some(&surface),
|
||||
force_fallback_adapter: false,
|
||||
..Default::default()
|
||||
}))?;
|
||||
|
||||
let caps = surface.get_capabilities(&adapter);
|
||||
let format = caps.formats[0];
|
||||
let size = window.inner_size();
|
||||
let config = wgpu::SurfaceConfiguration {
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
format,
|
||||
width: size.width.max(1),
|
||||
height: size.height.max(1),
|
||||
present_mode: wgpu::PresentMode::Fifo,
|
||||
alpha_mode: caps.alpha_modes[0],
|
||||
view_formats: vec![],
|
||||
desired_maximum_frame_latency: 2,
|
||||
color_space: wgpu::SurfaceColorSpace::Auto,
|
||||
};
|
||||
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
label: Some("fox-device"),
|
||||
required_features: wgpu::Features::empty(),
|
||||
required_limits: wgpu::Limits::default(),
|
||||
memory_hints: wgpu::MemoryHints::default(),
|
||||
..Default::default()
|
||||
}))?;
|
||||
surface.configure(&device, &config);
|
||||
|
||||
let egui_ctx = egui::Context::default();
|
||||
{
|
||||
let proxy = self.proxy.clone();
|
||||
egui_ctx.set_request_repaint_callback(move |info| {
|
||||
let _ = proxy.send_event(UserEvent::RepaintAfter(info.delay));
|
||||
});
|
||||
}
|
||||
let display_handle = event_loop
|
||||
.display_handle()
|
||||
.map_err(|e| format!("no display handle: {e:?}"))?;
|
||||
let mut egui_winit = EguiWinitState::new(
|
||||
egui_ctx.clone(),
|
||||
egui::ViewportId::ROOT,
|
||||
&display_handle,
|
||||
Some(self.scale_factor as f32),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
egui_winit.set_max_texture_side(device.limits().max_texture_dimension_2d as usize);
|
||||
let renderer = Renderer::new(&device, format, RendererOptions::default());
|
||||
|
||||
self.apply_style(&egui_ctx);
|
||||
|
||||
let window_handle = window
|
||||
.window_handle()
|
||||
.map_err(|e| format!("no window handle: {e:?}"))?;
|
||||
let window_context = Rc::new(servo::WindowRenderingContext::new(
|
||||
display_handle,
|
||||
window_handle,
|
||||
size,
|
||||
)
|
||||
.map_err(|e| format!("failed to create Servo rendering context: {e:?}"))?);
|
||||
window_context.make_current().ok();
|
||||
let waker = EguiWaker(egui_ctx.clone());
|
||||
let engine = Rc::new(Engine::new(waker, window_context));
|
||||
engine.window_context.take_window().ok();
|
||||
|
||||
let start_url = Url::parse(START_PAGE)?;
|
||||
let tab = engine.create_tab(start_url, self.scale_factor as f32);
|
||||
self.tabs.push(tab);
|
||||
self.active = 0;
|
||||
|
||||
self.gpu = Some(Gpu {
|
||||
surface,
|
||||
device,
|
||||
queue,
|
||||
config,
|
||||
egui_ctx,
|
||||
egui_winit,
|
||||
renderer,
|
||||
});
|
||||
self.window = Some(window.clone());
|
||||
|
||||
window.request_redraw();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_style(&self, ctx: &egui::Context) {
|
||||
let mut visuals = egui::Visuals::light();
|
||||
visuals.panel_fill = CHROME_BG;
|
||||
visuals.widgets.noninteractive.bg_fill = CHROME_BG;
|
||||
visuals.selection.stroke.color = ACCENT;
|
||||
ctx.set_visuals_of(egui::Theme::Light, visuals);
|
||||
}
|
||||
|
||||
fn active_tab(&self) -> Option<&Tab> {
|
||||
self.tabs.get(self.active)
|
||||
}
|
||||
|
||||
fn active_tab_mut(&mut self) -> Option<&mut Tab> {
|
||||
self.tabs.get_mut(self.active)
|
||||
}
|
||||
|
||||
fn tab_by_id_mut(&mut self, id: servo::WebViewId) -> Option<&mut Tab> {
|
||||
self.tabs.iter_mut().find(|t| t.id == id)
|
||||
}
|
||||
|
||||
fn active_id(&self) -> Option<servo::WebViewId> {
|
||||
self.tabs.get(self.active).map(|t| t.id)
|
||||
}
|
||||
|
||||
fn navigate_active(&mut self, input: &str) {
|
||||
let Some(url) = parse_location(input.trim()) else {
|
||||
return;
|
||||
};
|
||||
if let Some(tab) = self.active_tab_mut() {
|
||||
tab.webview.load(url);
|
||||
tab.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn open_new_tab(&mut self) {
|
||||
let Some(engine) = self.engine.clone() else {
|
||||
return;
|
||||
};
|
||||
let url = Url::parse(START_PAGE).expect("valid start page");
|
||||
let tab = engine.create_tab(url, self.scale_factor as f32);
|
||||
self.tabs.push(tab);
|
||||
self.active = self.tabs.len() - 1;
|
||||
self.content_focused = false;
|
||||
self.url_edit = START_PAGE.to_owned();
|
||||
}
|
||||
|
||||
fn close_tab(&mut self, index: usize) {
|
||||
if index >= self.tabs.len() {
|
||||
return;
|
||||
}
|
||||
self.tabs.remove(index);
|
||||
if self.tabs.is_empty() {
|
||||
self.open_new_tab();
|
||||
return;
|
||||
}
|
||||
if self.active >= self.tabs.len() {
|
||||
self.active = self.tabs.len() - 1;
|
||||
} else if index < self.active {
|
||||
self.active -= 1;
|
||||
}
|
||||
self.content_focused = false;
|
||||
}
|
||||
|
||||
fn drain_engine_messages(&mut self) {
|
||||
let Some(engine) = self.engine.clone() else {
|
||||
return;
|
||||
};
|
||||
let messages: Vec<EngineMsg> = engine.queue.borrow_mut().drain(..).collect();
|
||||
for msg in messages {
|
||||
match msg {
|
||||
EngineMsg::UrlChanged(id, url) => {
|
||||
let is_active = Some(id) == self.active_id();
|
||||
if let Some(tab) = self.tab_by_id_mut(id) {
|
||||
tab.url_string.clone_from(&url);
|
||||
if is_active && !self.url_bar_focused {
|
||||
self.url_edit.clone_from(&url);
|
||||
}
|
||||
}
|
||||
}
|
||||
EngineMsg::TitleChanged(id, title) => {
|
||||
let is_active = Some(id) == self.active_id();
|
||||
let display = title.unwrap_or_else(|| {
|
||||
fallback_title(&self
|
||||
.tabs
|
||||
.iter()
|
||||
.find(|t| t.id == id)
|
||||
.map(|t| t.url_string.clone())
|
||||
.unwrap_or_default())
|
||||
});
|
||||
if let Some(tab) = self.tab_by_id_mut(id) {
|
||||
tab.title.clone_from(&display);
|
||||
}
|
||||
if is_active {
|
||||
if let Some(window) = self.window.as_ref() {
|
||||
window.set_title(&format!("{display} — Fox"));
|
||||
}
|
||||
}
|
||||
}
|
||||
EngineMsg::StatusText(id, status) => {
|
||||
if let Some(tab) = self.tab_by_id_mut(id) {
|
||||
tab.status_text = status;
|
||||
}
|
||||
}
|
||||
EngineMsg::LoadStatus(id, loading) => {
|
||||
if let Some(tab) = self.tab_by_id_mut(id) {
|
||||
tab.loading = loading;
|
||||
}
|
||||
}
|
||||
EngineMsg::NewFrame(id) => {
|
||||
if let Some(tab) = self.tab_by_id_mut(id) {
|
||||
tab.dirty = true;
|
||||
}
|
||||
}
|
||||
EngineMsg::Animating(id, animating) => {
|
||||
if let Some(tab) = self.tab_by_id_mut(id) {
|
||||
tab.animating = animating;
|
||||
}
|
||||
}
|
||||
EngineMsg::Crashed(id, reason) => {
|
||||
if let Some(tab) = self.tab_by_id_mut(id) {
|
||||
tab.title = format!("Crashed: {reason}");
|
||||
tab.loading = false;
|
||||
}
|
||||
}
|
||||
EngineMsg::Closed(id) => {
|
||||
if let Some(index) = self.tabs.iter().position(|t| t.id == id) {
|
||||
self.close_tab(index);
|
||||
}
|
||||
}
|
||||
EngineMsg::NewWebView(webview) => {
|
||||
let mut tab = Tab::adopt(webview);
|
||||
tab.dirty = true;
|
||||
self.tabs.push(tab);
|
||||
self.active = self.tabs.len() - 1;
|
||||
self.url_edit.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_viewport_and_paint(&mut self) {
|
||||
let ppp = self.scale_factor as f32;
|
||||
let egui_ctx = self.gpu.as_ref().map(|g| g.egui_ctx.clone());
|
||||
let content = self.content_rect;
|
||||
|
||||
let Some(tab) = self.active_tab_mut() else {
|
||||
return;
|
||||
};
|
||||
if content.is_positive() {
|
||||
let phys_w = (content.width() * ppp).round() as u32;
|
||||
let phys_h = (content.height() * ppp).round() as u32;
|
||||
let current = tab.webview.size();
|
||||
let cur = (current.width.round() as u32, current.height.round() as u32);
|
||||
if cur != (phys_w, phys_h) && phys_w > 0 && phys_h > 0 {
|
||||
tab.webview.resize(PhysicalSize::new(phys_w, phys_h));
|
||||
tab.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !tab.dirty {
|
||||
return;
|
||||
}
|
||||
tab.webview.paint();
|
||||
|
||||
let size = tab.webview.size();
|
||||
let w = size.width.round() as i32;
|
||||
let h = size.height.round() as i32;
|
||||
if w <= 0 || h <= 0 {
|
||||
return;
|
||||
}
|
||||
let rect = euclid::Box2D::from_origin_and_size(euclid::point2(0, 0), euclid::size2(w, h));
|
||||
let rc = tab.webview.rendering_context();
|
||||
if let Some(img) = rc.read_to_image(rect) {
|
||||
let dims = [img.width() as usize, img.height() as usize];
|
||||
let pixels = img.into_raw();
|
||||
let image = egui::ColorImage::from_rgba_unmultiplied(dims, &pixels);
|
||||
match (&tab.texture, &egui_ctx) {
|
||||
(Some(texture), _) => {
|
||||
texture.clone().set(image, egui::TextureOptions::LINEAR);
|
||||
}
|
||||
(None, Some(ctx)) => {
|
||||
let name = format!("page-{:?}", tab.id);
|
||||
tab.texture = Some(ctx.load_texture(name, image, egui::TextureOptions::LINEAR));
|
||||
}
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
tab.dirty = false;
|
||||
}
|
||||
|
||||
fn build_ui(&mut self, ui: &mut egui::Ui) {
|
||||
egui::Panel::top("chrome").show(ui, |ui| {
|
||||
ui.vertical(|ui| {
|
||||
self.tab_strip(ui);
|
||||
ui.separator();
|
||||
self.toolbar(ui);
|
||||
});
|
||||
});
|
||||
|
||||
let hover_status = self
|
||||
.active_tab()
|
||||
.and_then(|t| t.status_text.clone())
|
||||
.filter(|s| !s.is_empty());
|
||||
if let Some(status) = hover_status {
|
||||
egui::Panel::bottom("statusbar")
|
||||
.frame(
|
||||
egui::Frame::new()
|
||||
.fill(CHROME_BG_DARKER)
|
||||
.inner_margin(egui::Margin::symmetric(8, 3)),
|
||||
)
|
||||
.show(ui, |ui| {
|
||||
ui.set_min_height(18.0);
|
||||
ui.label(
|
||||
egui::RichText::new(status)
|
||||
.small()
|
||||
.color(egui::Color32::from_gray(70)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
egui::CentralPanel::default()
|
||||
.frame(egui::Frame::new().fill(egui::Color32::WHITE))
|
||||
.show(ui, |ui| {
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
ui.allocate_rect(rect, egui::Sense::hover());
|
||||
self.content_rect = rect;
|
||||
let Some(texture) = self.active_tab().and_then(|t| t.texture.clone()) else {
|
||||
ui.centered_and_justified(|ui| {
|
||||
ui.label("Starting up the Servo engine…");
|
||||
});
|
||||
return;
|
||||
};
|
||||
ui.put(
|
||||
rect,
|
||||
egui::Image::new(&texture).fit_to_exact_size(rect.size()),
|
||||
);
|
||||
});
|
||||
|
||||
let busy = self
|
||||
.tabs
|
||||
.iter()
|
||||
.any(|t| t.loading || t.animating || t.dirty);
|
||||
if busy {
|
||||
ui.ctx().request_repaint_after(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
fn tab_strip(&mut self, ui: &mut egui::Ui) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
ui.add_space(4.0);
|
||||
for i in 0..self.tabs.len() {
|
||||
self.single_tab(ui, i, i == self.active);
|
||||
}
|
||||
if ui
|
||||
.add(
|
||||
egui::Button::new("+")
|
||||
.min_size(egui::vec2(26.0, 24.0))
|
||||
.corner_radius(5.0),
|
||||
)
|
||||
.on_hover_text("New tab")
|
||||
.clicked()
|
||||
{
|
||||
self.open_new_tab();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn single_tab(&mut self, ui: &mut egui::Ui, index: usize, is_active: bool) {
|
||||
let Some(tab) = self.tabs.get(index) else {
|
||||
return;
|
||||
};
|
||||
let title = truncate_title(&tab.title, 28);
|
||||
let loading = tab.loading;
|
||||
let bg = if is_active { TAB_ACTIVE_BG } else { CHROME_BG };
|
||||
|
||||
let activate = Cell::new(false);
|
||||
let close = Cell::new(false);
|
||||
|
||||
egui::Frame::new()
|
||||
.fill(bg)
|
||||
.corner_radius(egui::CornerRadius {
|
||||
nw: 7,
|
||||
ne: 7,
|
||||
sw: 0,
|
||||
se: 0,
|
||||
})
|
||||
.inner_margin(egui::Margin::symmetric(8, 3))
|
||||
.show(ui, |ui| {
|
||||
let tab_response = ui
|
||||
.horizontal(|ui| {
|
||||
if loading {
|
||||
ui.add(egui::Spinner::new().size(12.0));
|
||||
}
|
||||
let label = egui::RichText::new(&title).size(13.0);
|
||||
if ui
|
||||
.add(egui::Button::new(label).fill(egui::Color32::TRANSPARENT))
|
||||
.clicked()
|
||||
{
|
||||
activate.set(true);
|
||||
}
|
||||
if ui.small_button(egui::RichText::new("×").size(11.0)).clicked() {
|
||||
close.set(true);
|
||||
}
|
||||
})
|
||||
.response;
|
||||
if tab_response.clicked() {
|
||||
activate.set(true);
|
||||
}
|
||||
});
|
||||
|
||||
if close.get() {
|
||||
self.pending_close = Some(index);
|
||||
return;
|
||||
}
|
||||
if activate.get() && self.active != index {
|
||||
self.active = index;
|
||||
self.content_focused = false;
|
||||
if !self.url_bar_focused {
|
||||
if let Some(tab) = self.tabs.get(index) {
|
||||
self.url_edit.clone_from(&tab.url_string);
|
||||
}
|
||||
}
|
||||
if let Some(tab) = self.tabs.get_mut(index) {
|
||||
tab.dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn toolbar(&mut self, ui: &mut egui::Ui) {
|
||||
let can_back = self.active_tab().map(|t| t.webview.can_go_back()) == Some(true);
|
||||
let can_forward = self.active_tab().map(|t| t.webview.can_go_forward()) == Some(true);
|
||||
let loading = self.active_tab().map(|t| t.loading) == Some(true);
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(4.0);
|
||||
ui.add_enabled_ui(can_back, |ui| {
|
||||
if nav_button(ui, "←", "Go back").clicked() {
|
||||
if let Some(tab) = self.active_tab_mut() {
|
||||
tab.webview.go_back(1);
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_enabled_ui(can_forward, |ui| {
|
||||
if nav_button(ui, "→", "Go forward").clicked() {
|
||||
if let Some(tab) = self.active_tab_mut() {
|
||||
tab.webview.go_forward(1);
|
||||
}
|
||||
}
|
||||
});
|
||||
if nav_button(ui, if loading { "◌" } else { "↻" }, "Reload").clicked() {
|
||||
if let Some(tab) = self.active_tab_mut() {
|
||||
tab.webview.reload();
|
||||
}
|
||||
}
|
||||
|
||||
let url_field = egui::TextEdit::singleline(&mut self.url_edit)
|
||||
.hint_text("Search with DuckDuckGo or enter address")
|
||||
.desired_width(ui.available_width() - 12.0)
|
||||
.font(egui::TextStyle::Small);
|
||||
let response = ui.add(url_field);
|
||||
self.url_bar_focused = response.has_focus();
|
||||
if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
|
||||
let text = self.url_edit.clone();
|
||||
self.navigate_active(&text);
|
||||
response.request_focus();
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
});
|
||||
}
|
||||
|
||||
fn point_inside_content(&self, pos: PhysicalPosition<f64>) -> bool {
|
||||
let ppp = self.scale_factor as f32;
|
||||
let x = pos.x as f32 / ppp;
|
||||
let y = pos.y as f32 / ppp;
|
||||
self.content_rect.contains(egui::Pos2::new(x, y))
|
||||
}
|
||||
|
||||
fn content_point(&self, pos: PhysicalPosition<f64>) -> servo::DevicePoint {
|
||||
let ppp = self.scale_factor;
|
||||
servo::DevicePoint::new(
|
||||
(pos.x - self.content_rect.min.x as f64 * ppp) as f32,
|
||||
(pos.y - self.content_rect.min.y as f64 * ppp) as f32,
|
||||
)
|
||||
}
|
||||
|
||||
fn forward_pointer_move(&mut self) {
|
||||
let pos = self.last_cursor_pos;
|
||||
if !self.point_inside_content(pos) {
|
||||
return;
|
||||
}
|
||||
let origin_x = self.content_rect.min.x as f64 * self.scale_factor;
|
||||
let origin_y = self.content_rect.min.y as f64 * self.scale_factor;
|
||||
let point = servo::DevicePoint::new(
|
||||
(pos.x - origin_x) as f32,
|
||||
(pos.y - origin_y) as f32,
|
||||
);
|
||||
if let Some(tab) = self.active_tab_mut() {
|
||||
tab.webview.notify_input_event(servo::InputEvent::MouseMove(
|
||||
servo::MouseMoveEvent::new(point.into()),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn forward_mouse_click(&mut self, state: ElementState, button: winit::event::MouseButton) {
|
||||
let pos = self.last_cursor_pos;
|
||||
let inside = self.point_inside_content(pos);
|
||||
if inside {
|
||||
self.content_focused = true;
|
||||
let point = self.content_point(pos);
|
||||
if let Some(tab) = self.active_tab_mut() {
|
||||
tab.webview.focus();
|
||||
if let Some(btn) = winit_button_to_servo(button) {
|
||||
let action = winit_button_action_to_servo(state);
|
||||
tab.webview.notify_input_event(servo::InputEvent::MouseButton(
|
||||
servo::MouseButtonEvent::new(action, btn, point.into()),
|
||||
));
|
||||
}
|
||||
}
|
||||
} else if state == ElementState::Pressed {
|
||||
self.content_focused = false;
|
||||
if let Some(tab) = self.active_tab_mut() {
|
||||
tab.webview.blur();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn forward_wheel(&mut self, delta: winit::event::MouseScrollDelta) {
|
||||
if !self.point_inside_content(self.last_cursor_pos) {
|
||||
return;
|
||||
}
|
||||
let point = self.content_point(self.last_cursor_pos);
|
||||
if let Some(tab) = self.active_tab_mut() {
|
||||
if let Some(event) = wheel_input(delta, point) {
|
||||
tab.webview.notify_input_event(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn forward_keyboard(&mut self, event: &winit::event::KeyEvent) {
|
||||
if !self.content_focused || self.url_bar_focused {
|
||||
return;
|
||||
}
|
||||
let parts = servo_host::winit_key_event_to_parts(event);
|
||||
if let Some(input) = make_keyboard_input(parts, self.modifiers) {
|
||||
if let Some(tab) = self.active_tab_mut() {
|
||||
tab.webview.notify_input_event(input);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn redraw(&mut self) {
|
||||
let Some(window) = self.window.clone() else {
|
||||
return;
|
||||
};
|
||||
let Some(engine) = self.engine.clone() else {
|
||||
return;
|
||||
};
|
||||
|
||||
engine.spin();
|
||||
self.drain_engine_messages();
|
||||
if let Some(index) = self.pending_close.take() {
|
||||
self.close_tab(index);
|
||||
}
|
||||
self.sync_viewport_and_paint();
|
||||
|
||||
let (screen, raw_input, egui_ctx) = {
|
||||
let Some(gpu) = self.gpu.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let screen = ScreenDescriptor {
|
||||
size_in_pixels: [gpu.config.width, gpu.config.height],
|
||||
pixels_per_point: window.scale_factor() as f32,
|
||||
};
|
||||
let raw_input = gpu.egui_winit.take_egui_input(&window);
|
||||
(screen, raw_input, gpu.egui_ctx.clone())
|
||||
};
|
||||
|
||||
let full_output = egui_ctx.run_ui(raw_input, |ui| {
|
||||
self.build_ui(ui);
|
||||
});
|
||||
let paint_jobs = egui_ctx.tessellate(full_output.shapes, full_output.pixels_per_point);
|
||||
|
||||
let Some(gpu) = self.gpu.as_mut() else {
|
||||
return;
|
||||
};
|
||||
gpu.egui_winit
|
||||
.handle_platform_output(&window, full_output.platform_output);
|
||||
|
||||
for (id, deltas) in &full_output.textures_delta.set {
|
||||
for delta in deltas {
|
||||
gpu.renderer.update_texture(&gpu.device, &gpu.queue, *id, delta);
|
||||
}
|
||||
}
|
||||
|
||||
let surface_texture = match gpu.surface.get_current_texture() {
|
||||
wgpu::CurrentSurfaceTexture::Success(texture) => texture,
|
||||
wgpu::CurrentSurfaceTexture::Suboptimal(texture) => {
|
||||
gpu.surface.configure(&gpu.device, &gpu.config);
|
||||
texture
|
||||
}
|
||||
other => {
|
||||
log::warn!("get_current_texture: {other:?}");
|
||||
window.request_redraw();
|
||||
return;
|
||||
}
|
||||
};
|
||||
let view = surface_texture
|
||||
.texture
|
||||
.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let mut encoder = gpu
|
||||
.device
|
||||
.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
||||
|
||||
let buffers = gpu.renderer.update_buffers(
|
||||
&gpu.device,
|
||||
&gpu.queue,
|
||||
&mut encoder,
|
||||
&paint_jobs,
|
||||
&screen,
|
||||
);
|
||||
|
||||
{
|
||||
let clear = wgpu::Color {
|
||||
r: CHROME_BG.r() as f64 / 255.0,
|
||||
g: CHROME_BG.g() as f64 / 255.0,
|
||||
b: CHROME_BG.b() as f64 / 255.0,
|
||||
a: 1.0,
|
||||
};
|
||||
let pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("fox-frame"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &view,
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(clear),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
let mut pass = pass.forget_lifetime();
|
||||
gpu.renderer.render(&mut pass, &paint_jobs, &screen);
|
||||
}
|
||||
|
||||
for id in &full_output.textures_delta.free {
|
||||
gpu.renderer.free_texture(id);
|
||||
}
|
||||
|
||||
gpu.queue.submit(
|
||||
buffers
|
||||
.into_iter()
|
||||
.chain(std::iter::once(encoder.finish())),
|
||||
);
|
||||
gpu.queue.present(surface_texture);
|
||||
}
|
||||
}
|
||||
|
||||
fn nav_button(ui: &mut egui::Ui, glyph: &str, tip: &str) -> egui::Response {
|
||||
ui.add(
|
||||
egui::Button::new(egui::RichText::new(glyph).size(15.0))
|
||||
.min_size(egui::vec2(30.0, 26.0))
|
||||
.corner_radius(5.0),
|
||||
)
|
||||
.on_hover_text(tip)
|
||||
}
|
||||
|
||||
fn truncate_title(title: &str, max_chars: usize) -> String {
|
||||
if title.chars().count() <= max_chars {
|
||||
title.to_owned()
|
||||
} else {
|
||||
let cut: String = title.chars().take(max_chars.saturating_sub(1)).collect();
|
||||
format!("{cut}…")
|
||||
}
|
||||
}
|
||||
|
||||
fn fallback_title(url: &str) -> String {
|
||||
Url::parse(url)
|
||||
.ok()
|
||||
.and_then(|u| u.host_str().map(|h| h.to_owned()))
|
||||
.unwrap_or_else(|| "New Tab".to_owned())
|
||||
}
|
||||
|
||||
pub fn parse_location(input: &str) -> Option<Url> {
|
||||
let text = input.trim();
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if text.starts_with("about:") || text.contains("://") {
|
||||
return Url::parse(text).ok();
|
||||
}
|
||||
if text == "localhost" || text.starts_with("localhost:") || text.starts_with("127.0.0.1") {
|
||||
return Url::parse(&format!("http://{text}")).ok();
|
||||
}
|
||||
let looks_like_host = !text.contains(char::is_whitespace) && (text.contains('.') || text.ends_with('/'));
|
||||
if looks_like_host {
|
||||
return Url::parse(&format!("https://{text}")).ok();
|
||||
}
|
||||
Url::parse_with_params("https://duckduckgo.com/", &[("q", text)]).ok()
|
||||
}
|
||||
|
||||
impl ApplicationHandler<UserEvent> for BrowserApp {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.window.is_none() {
|
||||
if let Err(err) = self.init(event_loop) {
|
||||
log::error!("Failed to initialize: {err}");
|
||||
event_loop.exit();
|
||||
}
|
||||
}
|
||||
event_loop.set_control_flow(ControlFlow::Wait);
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) { let Some(window) = self.window.clone() else {
|
||||
return;
|
||||
};
|
||||
if window_id != window.id() {
|
||||
return;
|
||||
}
|
||||
|
||||
match &event {
|
||||
WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::RedrawRequested => self.redraw(),
|
||||
WindowEvent::Resized(size) => {
|
||||
if let Some(gpu) = self.gpu.as_mut() {
|
||||
gpu.config.width = size.width.max(1);
|
||||
gpu.config.height = size.height.max(1);
|
||||
gpu.surface.configure(&gpu.device, &gpu.config);
|
||||
}
|
||||
if let Some(tab) = self.active_tab_mut() {
|
||||
tab.dirty = true;
|
||||
}
|
||||
window.request_redraw();
|
||||
}
|
||||
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
||||
self.scale_factor = *scale_factor;
|
||||
for tab in &self.tabs {
|
||||
tab.webview
|
||||
.set_hidpi_scale_factor(euclid::Scale::new(*scale_factor as f32));
|
||||
}
|
||||
}
|
||||
WindowEvent::CursorMoved { position, .. } => {
|
||||
self.last_cursor_pos = *position;
|
||||
self.forward_pointer_move();
|
||||
}
|
||||
WindowEvent::MouseInput { state, button, .. } => {
|
||||
self.forward_mouse_click(*state, *button);
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, .. } => self.forward_wheel(*delta),
|
||||
WindowEvent::KeyboardInput {
|
||||
event: key_event,
|
||||
is_synthetic,
|
||||
..
|
||||
} => {
|
||||
if !*is_synthetic {
|
||||
self.forward_keyboard(key_event);
|
||||
}
|
||||
}
|
||||
WindowEvent::ModifiersChanged(mods) => {
|
||||
let state = mods.state();
|
||||
let mut m = Modifiers::empty();
|
||||
if state.contains(winit::keyboard::ModifiersState::SHIFT) {
|
||||
m |= Modifiers::SHIFT;
|
||||
}
|
||||
if state.contains(winit::keyboard::ModifiersState::CONTROL) {
|
||||
m |= Modifiers::CONTROL;
|
||||
}
|
||||
if state.contains(winit::keyboard::ModifiersState::ALT) {
|
||||
m |= Modifiers::ALT;
|
||||
}
|
||||
if state.contains(winit::keyboard::ModifiersState::SUPER) {
|
||||
m |= Modifiers::META;
|
||||
}
|
||||
self.modifiers = m;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if let Some(gpu) = self.gpu.as_mut() {
|
||||
let response = gpu.egui_winit.on_window_event(&window, &event);
|
||||
if response.repaint {
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
|
||||
match event {
|
||||
UserEvent::RepaintAfter(delay) => {
|
||||
event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + delay));
|
||||
if let Some(window) = self.window.as_ref() {
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
mod app;
|
||||
mod servo_host;
|
||||
|
||||
use std::error::Error;
|
||||
|
||||
use app::BrowserApp;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum UserEvent {
|
||||
RepaintAfter(std::time::Duration),
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Note: logging is initialized by `Servo::setup_logging()` — do not install
|
||||
// another logger here or it will panic with `SetLoggerError`.
|
||||
|
||||
rustls::crypto::aws_lc_rs::default_provider()
|
||||
.install_default()
|
||||
.expect("Failed to install crypto provider");
|
||||
|
||||
let event_loop = winit::event_loop::EventLoop::<UserEvent>::with_user_event()
|
||||
.build()
|
||||
.expect("Failed to create event loop");
|
||||
|
||||
let proxy = event_loop.create_proxy();
|
||||
let mut app = BrowserApp::new(proxy);
|
||||
|
||||
event_loop.run_app(&mut app)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use egui::TextureHandle;
|
||||
use keyboard_types::{Code, Key, KeyState, Location, Modifiers, NamedKey};
|
||||
use servo::{
|
||||
DevicePoint, EventLoopWaker, InputEvent, KeyboardEvent as ServoKeyboardEvent, LoadStatus,
|
||||
MouseButton, MouseButtonAction, OffscreenRenderingContext, RenderingContext, Servo,
|
||||
ServoBuilder, Theme, WebView, WebViewBuilder, WebViewId, WheelDelta, WheelEvent, WheelMode,
|
||||
WindowRenderingContext,
|
||||
};
|
||||
use url::Url;
|
||||
|
||||
pub type SharedQueue = Rc<RefCell<Vec<EngineMsg>>>;
|
||||
|
||||
pub enum EngineMsg {
|
||||
UrlChanged(WebViewId, String),
|
||||
TitleChanged(WebViewId, Option<String>),
|
||||
StatusText(WebViewId, Option<String>),
|
||||
LoadStatus(WebViewId, bool),
|
||||
NewFrame(WebViewId),
|
||||
Animating(WebViewId, bool),
|
||||
Crashed(WebViewId, String),
|
||||
Closed(WebViewId),
|
||||
NewWebView(WebView),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct EguiWaker(pub egui::Context);
|
||||
|
||||
impl EventLoopWaker for EguiWaker {
|
||||
fn clone_box(&self) -> Box<dyn EventLoopWaker> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
|
||||
fn wake(&self) {
|
||||
self.0.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BrowserDelegate {
|
||||
pub queue: SharedQueue,
|
||||
}
|
||||
|
||||
impl servo::WebViewDelegate for BrowserDelegate {
|
||||
fn notify_url_changed(&self, webview: WebView, url: Url) {
|
||||
self.queue
|
||||
.borrow_mut()
|
||||
.push(EngineMsg::UrlChanged(webview.id(), url.to_string()));
|
||||
}
|
||||
|
||||
fn notify_page_title_changed(&self, webview: WebView, title: Option<String>) {
|
||||
self.queue
|
||||
.borrow_mut()
|
||||
.push(EngineMsg::TitleChanged(webview.id(), title));
|
||||
}
|
||||
|
||||
fn notify_status_text_changed(&self, webview: WebView, status: Option<String>) {
|
||||
self.queue
|
||||
.borrow_mut()
|
||||
.push(EngineMsg::StatusText(webview.id(), status));
|
||||
}
|
||||
|
||||
fn notify_load_status_changed(&self, webview: WebView, status: LoadStatus) {
|
||||
let loading = !matches!(status, LoadStatus::Complete);
|
||||
self.queue
|
||||
.borrow_mut()
|
||||
.push(EngineMsg::LoadStatus(webview.id(), loading));
|
||||
}
|
||||
|
||||
fn notify_new_frame_ready(&self, webview: WebView) {
|
||||
self.queue
|
||||
.borrow_mut()
|
||||
.push(EngineMsg::NewFrame(webview.id()));
|
||||
}
|
||||
|
||||
fn notify_animating_changed(&self, webview: WebView, animating: bool) {
|
||||
self.queue
|
||||
.borrow_mut()
|
||||
.push(EngineMsg::Animating(webview.id(), animating));
|
||||
}
|
||||
|
||||
fn notify_crashed(&self, webview: WebView, reason: String, _backtrace: Option<String>) {
|
||||
self.queue
|
||||
.borrow_mut()
|
||||
.push(EngineMsg::Crashed(webview.id(), reason));
|
||||
}
|
||||
|
||||
fn notify_closed(&self, webview: WebView) {
|
||||
self.queue.borrow_mut().push(EngineMsg::Closed(webview.id()));
|
||||
}
|
||||
|
||||
fn request_create_new(&self, parent_webview: WebView, request: servo::CreateNewWebViewRequest) {
|
||||
let webview = request
|
||||
.builder(parent_webview.rendering_context())
|
||||
.delegate(parent_webview.delegate())
|
||||
.build();
|
||||
webview.notify_theme_change(Theme::Light);
|
||||
self.queue.borrow_mut().push(EngineMsg::NewWebView(webview));
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Engine {
|
||||
pub servo: Servo,
|
||||
pub window_context: Rc<WindowRenderingContext>,
|
||||
pub queue: SharedQueue,
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
pub fn new(waker: EguiWaker, window_context: Rc<WindowRenderingContext>) -> Engine {
|
||||
let queue: SharedQueue = Rc::new(RefCell::new(Vec::new()));
|
||||
let servo = ServoBuilder::default()
|
||||
.event_loop_waker(Box::new(waker))
|
||||
.build();
|
||||
servo.setup_logging();
|
||||
Engine {
|
||||
servo,
|
||||
window_context,
|
||||
queue,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spin(&self) {
|
||||
self.servo.spin_event_loop();
|
||||
}
|
||||
|
||||
pub fn create_tab(&self, url: Url, hidpi_scale: f32) -> Tab {
|
||||
let size = self.window_context.size();
|
||||
let offscreen: Rc<OffscreenRenderingContext> =
|
||||
Rc::new(self.window_context.offscreen_context(size));
|
||||
let delegate = Rc::new(BrowserDelegate {
|
||||
queue: self.queue.clone(),
|
||||
});
|
||||
let webview = WebViewBuilder::new(&self.servo, offscreen as Rc<dyn RenderingContext>)
|
||||
.url(url)
|
||||
.hidpi_scale_factor(euclid::Scale::new(hidpi_scale))
|
||||
.delegate(delegate)
|
||||
.build();
|
||||
webview.notify_theme_change(Theme::Light);
|
||||
Tab::new(webview)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Tab {
|
||||
pub webview: WebView,
|
||||
pub id: WebViewId,
|
||||
pub title: String,
|
||||
pub url_string: String,
|
||||
pub status_text: Option<String>,
|
||||
pub loading: bool,
|
||||
pub animating: bool,
|
||||
pub dirty: bool,
|
||||
pub texture: Option<TextureHandle>,
|
||||
}
|
||||
|
||||
impl Tab {
|
||||
fn new(webview: WebView) -> Tab {
|
||||
Tab {
|
||||
id: webview.id(),
|
||||
webview,
|
||||
title: String::from("New Tab"),
|
||||
url_string: String::new(),
|
||||
status_text: None,
|
||||
loading: true,
|
||||
animating: false,
|
||||
dirty: true,
|
||||
texture: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn adopt(webview: WebView) -> Tab {
|
||||
Tab::new(webview)
|
||||
}
|
||||
}
|
||||
|
||||
fn winit_named_key_to_kt(key: winit::keyboard::NamedKey) -> Key {
|
||||
use winit::keyboard::NamedKey as W;
|
||||
match key {
|
||||
W::Enter => Key::Named(NamedKey::Enter),
|
||||
W::Tab => Key::Named(NamedKey::Tab),
|
||||
W::Backspace => Key::Named(NamedKey::Backspace),
|
||||
W::Delete => Key::Named(NamedKey::Delete),
|
||||
W::Escape => Key::Named(NamedKey::Escape),
|
||||
W::Space => Key::Character(" ".into()),
|
||||
W::ArrowUp => Key::Named(NamedKey::ArrowUp),
|
||||
W::ArrowDown => Key::Named(NamedKey::ArrowDown),
|
||||
W::ArrowLeft => Key::Named(NamedKey::ArrowLeft),
|
||||
W::ArrowRight => Key::Named(NamedKey::ArrowRight),
|
||||
W::Home => Key::Named(NamedKey::Home),
|
||||
W::End => Key::Named(NamedKey::End),
|
||||
W::PageUp => Key::Named(NamedKey::PageUp),
|
||||
W::PageDown => Key::Named(NamedKey::PageDown),
|
||||
W::Insert => Key::Named(NamedKey::Insert),
|
||||
W::F1 => Key::Named(NamedKey::F1),
|
||||
W::F2 => Key::Named(NamedKey::F2),
|
||||
W::F3 => Key::Named(NamedKey::F3),
|
||||
W::F4 => Key::Named(NamedKey::F4),
|
||||
W::F5 => Key::Named(NamedKey::F5),
|
||||
W::F6 => Key::Named(NamedKey::F6),
|
||||
W::F7 => Key::Named(NamedKey::F7),
|
||||
W::F8 => Key::Named(NamedKey::F8),
|
||||
W::F9 => Key::Named(NamedKey::F9),
|
||||
W::F10 => Key::Named(NamedKey::F10),
|
||||
W::F11 => Key::Named(NamedKey::F11),
|
||||
W::F12 => Key::Named(NamedKey::F12),
|
||||
_ => Key::Named(NamedKey::Unidentified),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn winit_key_to_kt_key(key: &winit::keyboard::Key) -> Key {
|
||||
match key {
|
||||
winit::keyboard::Key::Character(s) => Key::Character(s.as_str().into()),
|
||||
winit::keyboard::Key::Named(n) => winit_named_key_to_kt(*n),
|
||||
_ => Key::Named(NamedKey::Unidentified),
|
||||
}
|
||||
}
|
||||
|
||||
pub struct KeyEventParts {
|
||||
pub state: KeyState,
|
||||
pub key: Key,
|
||||
pub code: Code,
|
||||
pub repeat: bool,
|
||||
}
|
||||
|
||||
pub fn winit_key_event_to_parts(event: &winit::event::KeyEvent) -> KeyEventParts {
|
||||
let state = if event.state == winit::event::ElementState::Pressed {
|
||||
KeyState::Down
|
||||
} else {
|
||||
KeyState::Up
|
||||
};
|
||||
let code = match event.physical_key {
|
||||
winit::keyboard::PhysicalKey::Code(code) => {
|
||||
// winit's `KeyCode` variants share their names with the W3C
|
||||
// `KeyboardEvent.code` values that `keyboard_types::Code` parses.
|
||||
format!("{code:?}")
|
||||
.parse::<Code>()
|
||||
.unwrap_or(Code::Unidentified)
|
||||
}
|
||||
winit::keyboard::PhysicalKey::Unidentified(_native) => Code::Unidentified,
|
||||
};
|
||||
KeyEventParts {
|
||||
state,
|
||||
key: winit_key_to_kt_key(&event.logical_key),
|
||||
code,
|
||||
repeat: event.repeat,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn make_keyboard_input(parts: KeyEventParts, modifiers: Modifiers) -> Option<InputEvent> {
|
||||
if parts.key == Key::Named(NamedKey::Unidentified) && parts.code == Code::Unidentified {
|
||||
return None;
|
||||
}
|
||||
let event = ServoKeyboardEvent::new_without_event(
|
||||
parts.state,
|
||||
parts.key,
|
||||
parts.code,
|
||||
Location::Standard,
|
||||
modifiers,
|
||||
parts.repeat,
|
||||
false,
|
||||
);
|
||||
Some(InputEvent::Keyboard(event))
|
||||
}
|
||||
|
||||
pub fn winit_button_to_servo(button: winit::event::MouseButton) -> Option<MouseButton> {
|
||||
match button {
|
||||
winit::event::MouseButton::Left => Some(MouseButton::Left),
|
||||
winit::event::MouseButton::Right => Some(MouseButton::Right),
|
||||
winit::event::MouseButton::Middle => Some(MouseButton::Middle),
|
||||
winit::event::MouseButton::Back => Some(MouseButton::Back),
|
||||
winit::event::MouseButton::Forward => Some(MouseButton::Forward),
|
||||
winit::event::MouseButton::Other(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn winit_button_action_to_servo(state: winit::event::ElementState) -> MouseButtonAction {
|
||||
match state {
|
||||
winit::event::ElementState::Pressed => MouseButtonAction::Down,
|
||||
winit::event::ElementState::Released => MouseButtonAction::Up,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wheel_input(
|
||||
delta: winit::event::MouseScrollDelta,
|
||||
point: DevicePoint,
|
||||
) -> Option<InputEvent> {
|
||||
let (x, y, mode) = match delta {
|
||||
winit::event::MouseScrollDelta::LineDelta(dx, dy) => {
|
||||
((dx * 76.0) as f64, (dy * 76.0) as f64, WheelMode::DeltaLine)
|
||||
}
|
||||
winit::event::MouseScrollDelta::PixelDelta(pos) => (pos.x, pos.y, WheelMode::DeltaPixel),
|
||||
};
|
||||
Some(InputEvent::Wheel(WheelEvent::new(
|
||||
WheelDelta { x, y, z: 0.0, mode },
|
||||
point.into(),
|
||||
)))
|
||||
}
|
||||
Reference in New Issue
Block a user