Skip to content

Commit

Permalink
Clean up and refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
matthunz committed Sep 28, 2023
1 parent 6f42789 commit 16d19b9
Show file tree
Hide file tree
Showing 10 changed files with 67 additions and 60 deletions.
4 changes: 2 additions & 2 deletions examples/animation.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use skia_safe::Color4f;
use taffy::prelude::Size;
use viewbuilder::{Context, Element, Renderer, Window};
use viewbuilder::{Context, Element, Error, Renderer, Window};

#[tokio::main]
async fn main() {
async fn main() -> Result<(), Error> {
let mut cx = Context::new(());
let animated = Element::new()
.size(Size::from_points(100., 100.))
Expand Down
4 changes: 1 addition & 3 deletions examples/counter.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use skia_safe::Color4f;
use taffy::prelude::Rect;
use taffy::style::{FlexDirection, LengthPercentage};
use viewbuilder::window::Error;
use viewbuilder::NodeKey;
use viewbuilder::{Context, Element};
use viewbuilder::{Context, Element, Error, NodeKey};

fn button(
cx: &mut Context<i32>,
Expand Down
2 changes: 1 addition & 1 deletion examples/hello.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use taffy::style::{AlignItems, JustifyContent};
use viewbuilder::{window::Error, Context, Element, NodeKey};
use viewbuilder::{Context, Element, Error, NodeKey};

fn app(cx: &mut Context) -> NodeKey {
Element::new()
Expand Down
9 changes: 3 additions & 6 deletions examples/multi_window.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::error::Error;
use taffy::style::{AlignItems, JustifyContent};
use viewbuilder::{Context, Element, NodeKey, Renderer, Window};
use viewbuilder::{Context, Element, Error, NodeKey, Renderer, Window};

fn app(cx: &mut Context) -> NodeKey {
Element::new()
Expand All @@ -10,7 +9,7 @@ fn app(cx: &mut Context) -> NodeKey {
.build(cx)
}

fn main() -> Result<(), Box<dyn Error>> {
fn main() -> Result<(), Error> {
let mut renderer = Renderer::new();
let mut cx = Context::new(());

Expand All @@ -24,7 +23,5 @@ fn main() -> Result<(), Box<dyn Error>> {
let cx_key = renderer.context(cx);
renderer.insert_window(a, cx_key);
renderer.insert_window(b, cx_key);

renderer.run();
Ok(())
renderer.run()
}
2 changes: 1 addition & 1 deletion examples/scroll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use taffy::{
prelude::Rect,
style::{FlexDirection, LengthPercentage},
};
use viewbuilder::{node::Overflow, window::Error, Context, Element, NodeKey};
use viewbuilder::{node::Overflow, Context, Element, Error, NodeKey};

fn app(cx: &mut Context) -> NodeKey {
let mut elem = Element::new();
Expand Down
3 changes: 1 addition & 2 deletions src/element/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use std::marker::PhantomData;

use crate::{
event,
node::{NodeData, Overflow},
Context, Node, NodeKey,
};
use skia_safe::Color4f;
use std::marker::PhantomData;
use taffy::{
prelude::{Rect, Size},
style::{AlignItems, Dimension, FlexDirection, JustifyContent, LengthPercentage},
Expand Down
39 changes: 29 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,33 +19,53 @@
//! ```
//!

pub mod node;
pub use node::Node;

pub mod tree;
pub use tree::{NodeRef, Tree};
use thiserror::Error;

mod context;
pub use context::Context;

pub mod element;
pub use element::Element;

pub mod event;
pub use event::Event;

pub mod node;
pub use node::Node;

pub mod render;
pub use render::Renderer;

pub mod event;
pub use event::Event;
pub mod tree;
pub use tree::{NodeRef, Tree};

pub mod window;
use window::Error;
pub use window::Window;

slotmap::new_key_type! {
/// Key to access a node in a tree.
pub struct NodeKey;
}

#[derive(Error, Debug)]
pub enum Error {
/// OpenGL error.
#[error("GL")]
Gl(#[from] glutin::error::Error),

/// OpenGL display error.
#[error("Display")]
Display(Box<dyn std::error::Error>),

/// Skia surface rendering error.
#[error("Surface")]
Surface,

/// Windowing error.
#[error("Window")]
Window,
}

/// Run the user interface tree.
///
/// This will create a new window and render the tree,
Expand All @@ -59,6 +79,5 @@ pub fn run<T: 'static>(state: T, f: impl FnOnce(&mut Context<T>) -> NodeKey) ->

let window = Window::builder().build(&renderer, root)?;
renderer.insert_window(window, cx_key);
renderer.run();
Ok(())
renderer.run()
}
16 changes: 12 additions & 4 deletions src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ impl<T> Renderer<T> {
}
}

pub fn run(mut self) {
pub fn run(mut self) -> ! {
let mut previous_frame_start = Instant::now();
let proxy = self.event_loop.create_proxy();

Expand All @@ -168,8 +168,16 @@ impl<T> Renderer<T> {
Event::WindowEvent { window_id, event } => {
let window_cx = self.windows.get_mut(&window_id).unwrap();
let cx = &mut self.contexts[window_cx.context_key];
if let Some(cf) = window_cx.window.handle(cx, window_cx.window.root, event) {
*control_flow = cf;

match window_cx.window.handle(cx, window_cx.window.root, event) {
Ok(cell) => {
if let Some(cf) = cell {
*control_flow = cf;
}
}
Err(_error) => {
*control_flow = ControlFlow::Exit;
}
}
}
Event::RedrawRequested(_) => {
Expand Down Expand Up @@ -199,6 +207,6 @@ impl<T> Renderer<T> {
}

*control_flow = ControlFlow::WaitUntil(previous_frame_start + frame_duration)
});
})
}
}
17 changes: 7 additions & 10 deletions src/window/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use glutin_winit::DisplayBuilder;
use kurbo::Size;
use raw_window_handle::HasRawWindowHandle;
use skia_safe::gpu::gl::FramebufferInfo;

use std::{borrow::Cow, ffi::CString, num::NonZeroU32};
use winit::window::WindowBuilder;

Expand Down Expand Up @@ -67,7 +66,7 @@ impl Builder {
})
.unwrap()
})
.unwrap();
.map_err(|error| Error::Display(error))?;
let window = window.ok_or(Error::Window)?;
let raw_window_handle = window.raw_window_handle();

Expand All @@ -81,16 +80,16 @@ impl Builder {
let fallback_context_attributes = ContextAttributesBuilder::new()
.with_context_api(ContextApi::Gles(None))
.build(Some(raw_window_handle));

let not_current_gl_context = unsafe {
gl_config
.display()
.create_context(&gl_config, &context_attributes)
.unwrap_or_else(|_| {
.or_else(|_| {
gl_config
.display()
.create_context(&gl_config, &fallback_context_attributes)
.expect("failed to create context")
})
})?
};

let (width, height): (u32, u32) = window.inner_size().into();
Expand All @@ -105,7 +104,6 @@ impl Builder {
.display()
.create_window_surface(&gl_config, &attrs)?
};

let gl_context = not_current_gl_context.make_current(&gl_surface)?;

gl::load_with(|s| {
Expand All @@ -121,10 +119,10 @@ impl Builder {
.display()
.get_proc_address(CString::new(name).unwrap().as_c_str())
})
.ok_or(Error::Skia)?;
.ok_or(Error::Surface)?;

let mut gr_context =
skia_safe::gpu::DirectContext::new_gl(Some(interface), None).ok_or(Error::Skia)?;
skia_safe::gpu::DirectContext::new_gl(Some(interface), None).ok_or(Error::Surface)?;

let fb_info = {
let mut fboid: GLint = 0;
Expand All @@ -144,8 +142,7 @@ impl Builder {

let num_samples = gl_config.num_samples() as usize;
let stencil_size = gl_config.stencil_size() as usize;

let surface = create_surface(&window, fb_info, &mut gr_context, num_samples, stencil_size);
let surface = create_surface(&window, fb_info, &mut gr_context, num_samples, stencil_size)?;

Ok(Window {
surface,
Expand Down
31 changes: 10 additions & 21 deletions src/window/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
event::{self},
node::{NodeData, Overflow},
Context, NodeKey,
Context, Error, NodeKey,
};
use glutin::{
context::PossiblyCurrentContext,
Expand All @@ -14,7 +14,6 @@ use skia_safe::{
Color, ColorType, Surface,
};
use std::num::NonZeroU32;
use thiserror::Error;
use winit::{
event::{ElementState, KeyboardInput, MouseScrollDelta, VirtualKeyCode, WindowEvent},
event_loop::ControlFlow,
Expand All @@ -23,16 +22,6 @@ use winit::{
mod builder;
use self::builder::Builder;

#[derive(Error, Debug)]
pub enum Error {
#[error("GL")]
Gl(#[from] glutin::error::Error),
#[error("Skia")]
Skia,
#[error("Window")]
Window,
}

// Guarantee the drop order inside the FnMut closure. `Window` _must_ be dropped after
// `DirectContext`.
//
Expand Down Expand Up @@ -83,10 +72,10 @@ impl Window {
tree: &mut Context<T>,
root: NodeKey,
event: WindowEvent,
) -> Option<ControlFlow> {
) -> Result<Option<ControlFlow>, Error> {
match event {
WindowEvent::CloseRequested => {
return Some(ControlFlow::Exit);
return Ok(Some(ControlFlow::Exit));
}
WindowEvent::Resized(physical_size) => {
// Create a new render surface
Expand All @@ -96,7 +85,7 @@ impl Window {
&mut self.gr_context,
self.num_samples,
self.stencil_size,
);
)?;

// Resize the gl surface
let (width, height): (u32, u32) = physical_size.into();
Expand All @@ -117,7 +106,7 @@ impl Window {
} => {
if modifiers.logo() {
if let Some(VirtualKeyCode::Q) = virtual_keycode {
return Some(ControlFlow::Exit);
return Ok(Some(ControlFlow::Exit));
}
}

Expand Down Expand Up @@ -236,7 +225,7 @@ impl Window {
_ => (),
}

None
Ok(None)
}
}

Expand All @@ -246,11 +235,11 @@ fn create_surface(
gr_context: &mut skia_safe::gpu::DirectContext,
num_samples: usize,
stencil_size: usize,
) -> Surface {
) -> Result<Surface, Error> {
let size = window.inner_size();
let size = (
size.width.try_into().expect("Could not convert width"),
size.height.try_into().expect("Could not convert height"),
size.width.try_into().unwrap(),
size.height.try_into().unwrap(),
);
let backend_render_target =
BackendRenderTarget::new_gl(size, num_samples, stencil_size, fb_info);
Expand All @@ -263,5 +252,5 @@ fn create_surface(
None,
None,
)
.expect("Could not create skia surface")
.ok_or_else(|| Error::Surface)
}

0 comments on commit 16d19b9

Please sign in to comment.