Skip to content

Commit

Permalink
Moving to dynamic dispatch, adding callback, adding traits crate, rem…
Browse files Browse the repository at this point in the history
…oving sync provider

(im sorry)
  • Loading branch information
kokoISnoTarget committed Sep 13, 2024
1 parent 98bad27 commit 5f6bd08
Show file tree
Hide file tree
Showing 19 changed files with 275 additions and 318 deletions.
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# members = ["packages/dom"]
# members = ["packages/blitz", "packages/dom", "packages/dioxus-blitz"]
# exclude = ["packages/blitz", "packages/dioxus-blitz"]
members = ["packages/blitz", "packages/dom", "packages/dioxus-blitz", "packages/net"]
members = ["packages/blitz", "packages/dom", "packages/dioxus-blitz", "packages/net", "packages/traits"]
resolver = "2"

[workspace.dependencies]
Expand Down Expand Up @@ -55,7 +55,8 @@ incremental = false
# mozbuild = "0.1.0"
blitz = { path = "./packages/blitz" }
blitz-dom = { path = "./packages/dom" }
blitz-net = { path = "./packages/net", features = ["blocking"]}
blitz-net = { path = "./packages/net" }
blitz-traits = { path = "./packages/traits" }
comrak = { version = "0.21.0", default-features = false, features = ["syntect"] }
png = { version = "0.17" }
dioxus-blitz = { path = "./packages/dioxus-blitz" }
Expand Down
32 changes: 26 additions & 6 deletions examples/screenshot.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
//! Load first CLI argument as a url. Fallback to google.com if no CLI argument is provided.

use blitz::render_to_buffer;
use blitz_dom::util::Resource;
use blitz_dom::{HtmlDocument, Viewport};
use blitz_net::SyncProvider;
use blitz_net::{MpscCallback, Provider};
use blitz_traits::net::{SharedCallback, SharedProvider};
use reqwest::Url;
use std::sync::Arc;
use std::{
fs::File,
io::Write,
path::{Path, PathBuf},
time::Instant,
};
use tokio::runtime::Handle;

const USER_AGENT: &str = "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/81.0";

Expand Down Expand Up @@ -47,20 +51,36 @@ async fn main() {
.and_then(|arg| arg.parse().ok())
.unwrap_or(1200);

let net = SyncProvider::new();
let (mut recv, callback) = MpscCallback::new();
let net = Arc::new(Provider::new(
Handle::current(),
Arc::new(callback) as SharedCallback<Resource>,
));

timer.time("Setup document prerequsits");

// Create HtmlDocument
let mut document = HtmlDocument::from_html(&html, Some(url.clone()), Vec::new(), &net);
let mut document = HtmlDocument::from_html(
&html,
Some(url.clone()),
Vec::new(),
Arc::clone(&net) as SharedProvider<Resource>,
);

timer.time("Parsed document");

document
.as_mut()
.set_viewport(Viewport::new(width * scale, height * scale, scale as f32));

for resource in net.0.into_inner().drain(..) {
document.as_mut().load_resource(resource)
while let Some(res) = recv.recv().await {
document.as_mut().load_resource(res);
if net.is_empty() {
break;
}
}

timer.time("Created document (+ fetched assets)");
timer.time("Fetched assets");

// Compute style, layout, etc for HtmlDocument
document.as_mut().resolve();
Expand Down
3 changes: 2 additions & 1 deletion packages/dioxus-blitz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ style = { workspace = true }
tracing = { workspace = true, optional = true }
blitz = { path = "../blitz" }
blitz-dom = { path = "../dom" }
blitz-net = { path = "../net", features = ["non_blocking"] }
blitz-net = { path = "../net" }
blitz-traits = { path = "../traits" }
html-escape = "0.2.13"
url = { version = "2.5.0", features = ["serde"] }
ureq = "2.9"
Expand Down
75 changes: 60 additions & 15 deletions packages/dioxus-blitz/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,24 +22,28 @@ mod menu;
mod accessibility;

use crate::application::Application;
pub use crate::documents::DioxusDocument;
pub use crate::waker::BlitzEvent;
use crate::waker::BlitzWindowEvent;
use crate::window::View;
pub use crate::window::WindowConfig;
use blitz_dom::util::Resource;
use blitz_dom::{DocumentLike, HtmlDocument};
use blitz_net::AsyncProvider;
use blitz_net::Provider;
use blitz_traits::net::SharedCallback;
use dioxus::prelude::{ComponentFunction, Element, VirtualDom};
use std::sync::Arc;
use std::ops::DerefMut;
use std::sync::{Arc, Mutex};
use tokio::runtime::Runtime;
use url::Url;
use winit::event_loop::EventLoopProxy;
use winit::window::WindowId;
use winit::{
dpi::LogicalSize,
event_loop::{ControlFlow, EventLoop},
window::Window,
};

pub use crate::documents::DioxusDocument;
pub use crate::waker::BlitzEvent;
pub use crate::window::WindowConfig;

pub mod exports {
pub use dioxus;
}
Expand Down Expand Up @@ -116,17 +120,18 @@ pub fn launch_static_html_cfg(html: &str, cfg: Config) {
.unwrap();

let _guard = rt.enter();
let net = AsyncProvider::new(&rt);

let document = HtmlDocument::from_html(html, cfg.base_url, cfg.stylesheets, &net);
launch_with_document(document, rt, Some(Arc::new(net)));
let net_callback = Arc::new(Callback::new());
let net = Provider::new(
rt.handle().clone(),
Arc::clone(&net_callback) as SharedCallback<Resource>,
);

let document = HtmlDocument::from_html(html, cfg.base_url, cfg.stylesheets, Arc::new(net));
launch_with_document(document, rt, Some(net_callback));
}

fn launch_with_document(
doc: impl DocumentLike,
rt: Runtime,
net: Option<Arc<AsyncProvider<Resource>>>,
) {
fn launch_with_document(doc: impl DocumentLike, rt: Runtime, net_callback: Option<Arc<Callback>>) {
let mut window_attrs = Window::default_attributes();
if !cfg!(all(target_os = "android", target_os = "ios")) {
window_attrs.inner_size = Some(
Expand All @@ -137,7 +142,7 @@ fn launch_with_document(
.into(),
);
}
let window = WindowConfig::new(doc, net);
let window = WindowConfig::new(doc, net_callback);

launch_with_window(window, rt)
}
Expand Down Expand Up @@ -197,3 +202,43 @@ pub fn set_android_app(app: android_activity::AndroidApp) {
pub fn current_android_app(app: android_activity::AndroidApp) -> AndroidApp {
ANDROID_APP.get().unwrap().clone()
}

pub struct Callback(Mutex<CallbackInner>);
enum CallbackInner {
Window(WindowId, EventLoopProxy<BlitzEvent>),
Queue(Vec<Resource>),
}
impl Callback {
fn new() -> Self {
Self(Mutex::new(CallbackInner::Queue(Vec::new())))
}
fn init(self: Arc<Self>, window_id: WindowId, proxy: &EventLoopProxy<BlitzEvent>) {
let old = std::mem::replace(
self.0.lock().unwrap().deref_mut(),
CallbackInner::Window(window_id, proxy.clone()),
);
match old {
CallbackInner::Window(..) => {}
CallbackInner::Queue(mut queue) => queue
.drain(..)
.for_each(|res| Self::send_event(&window_id, proxy, res)),
}
}
fn send_event(window_id: &WindowId, proxy: &EventLoopProxy<BlitzEvent>, data: Resource) {
proxy
.send_event(BlitzEvent::Window {
window_id: *window_id,
data: BlitzWindowEvent::ResourceLoad(data),
})
.unwrap()
}
}
impl blitz_traits::net::Callback for Callback {
type Data = Resource;
fn call(self: Arc<Self>, data: Self::Data) {
match self.0.lock().unwrap().deref_mut() {
CallbackInner::Window(wid, proxy) => Self::send_event(wid, proxy, data),
CallbackInner::Queue(queue) => queue.push(data),
}
}
}
18 changes: 8 additions & 10 deletions packages/dioxus-blitz/src/window.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::accessibility::AccessibilityState;
use crate::stylo_to_winit;
use crate::waker::{create_waker, BlitzEvent, BlitzWindowEvent};
use crate::{stylo_to_winit, Callback};
use blitz::{Devtools, Renderer};
use blitz_dom::events::{EventData, RendererEvent};
use blitz_dom::{DocumentLike, Viewport};
Expand All @@ -9,8 +9,6 @@ use winit::keyboard::PhysicalKey;
#[allow(unused)]
use wgpu::rwh::HasWindowHandle;

use blitz_dom::util::Resource;
use blitz_net::AsyncProvider;
use std::sync::Arc;
use std::task::Waker;
use winit::event::{ElementState, MouseButton};
Expand All @@ -24,27 +22,27 @@ use crate::menu::init_menu;
pub struct WindowConfig<Doc: DocumentLike> {
doc: Doc,
attributes: WindowAttributes,
net: Option<Arc<AsyncProvider<Resource>>>,
callback: Option<Arc<Callback>>,
}

impl<Doc: DocumentLike> WindowConfig<Doc> {
pub fn new(doc: Doc, net: Option<Arc<AsyncProvider<Resource>>>) -> Self {
pub fn new(doc: Doc, callback: Option<Arc<Callback>>) -> Self {
WindowConfig {
doc,
attributes: Window::default_attributes(),
net,
callback,
}
}

pub fn with_attributes(
doc: Doc,
attributes: WindowAttributes,
net: Option<Arc<AsyncProvider<Resource>>>,
callback: Option<Arc<Callback>>,
) -> Self {
WindowConfig {
doc,
attributes,
net,
callback,
}
}
}
Expand Down Expand Up @@ -87,8 +85,8 @@ impl<Doc: DocumentLike> View<Doc> {
) -> Self {
let winit_window = Arc::from(event_loop.create_window(config.attributes).unwrap());

if let Some(net) = config.net {
net.resolve(proxy.clone(), winit_window.id());
if let Some(callback) = config.callback {
callback.init(winit_window.id(), proxy);
}

// TODO: make this conditional on text input focus
Expand Down
2 changes: 1 addition & 1 deletion packages/dom/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ default = ["tracing"]
tracing = ["dep:tracing"]

[dependencies]
blitz-net = { path = "../net" }
blitz-traits = { path = "../traits" }
style = { workspace = true, features = ["servo"] }
selectors = { workspace = true }
style_config = { workspace = true }
Expand Down
2 changes: 1 addition & 1 deletion packages/dom/src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,7 @@ impl Document {
self.stylist.remove_stylesheet(old, &self.guard.read())
}

// TODO: Nodes could potentially get reused so ordering by node_id might be wrong.
let insertion_point = self
.nodes_to_stylesheet
.range((Bound::Excluded(node_id), Bound::Unbounded))
Expand All @@ -573,7 +574,6 @@ impl Document {
match resource {
Resource::Css(node_id, css) => {
self.append_or_insert_stylesheet(css, node_id);
self.resolve();
}
Resource::Image(node_id, image) => {
let node = self.get_node_mut(node_id).unwrap();
Expand Down
6 changes: 3 additions & 3 deletions packages/dom/src/html_document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{Document, DocumentHtmlParser, DocumentLike, Viewport};

use crate::util::Resource;
use crate::DEFAULT_CSS;
use blitz_net::NetProvider;
use blitz_traits::net::SharedProvider;

pub struct HtmlDocument {
inner: Document,
Expand Down Expand Up @@ -33,11 +33,11 @@ impl DocumentLike for HtmlDocument {
}

impl HtmlDocument {
pub fn from_html<N: NetProvider<Resource>>(
pub fn from_html(
html: &str,
base_url: Option<String>,
stylesheets: Vec<String>,
net: N,
net: SharedProvider<Resource>,
) -> Self {
// Spin up the virtualdom and include the default stylesheet
let viewport = Viewport::new(0, 0, 1.0);
Expand Down
Loading

0 comments on commit 5f6bd08

Please sign in to comment.