initial commit

This commit is contained in:
2025-11-10 21:59:01 -05:00
commit ff8c41e0e7
8 changed files with 4203 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/target

3624
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

11
Cargo.toml Normal file
View File

@@ -0,0 +1,11 @@
[package]
name = "openworm"
version = "0.1.0"
edition = "2024"
[dependencies]
arboard = { version = "3.6.1", features = ["wayland-data-control"] }
pollster = "0.4.0"
ui = { path = "../ui" }
wgpu = "27.0.1"
winit = "0.30.12"

37
src/app.rs Normal file
View File

@@ -0,0 +1,37 @@
use winit::{
application::ApplicationHandler,
event::WindowEvent,
event_loop::{ActiveEventLoop, EventLoop},
window::{Window, WindowId},
};
use super::Client;
#[derive(Default)]
pub struct App {
client: Option<Client>,
}
impl App {
pub fn run() {
let event_loop = EventLoop::new().unwrap();
event_loop.run_app(&mut App::default()).unwrap();
}
}
impl ApplicationHandler for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.client.is_none() {
let window = event_loop
.create_window(Window::default_attributes())
.unwrap();
let client = Client::new(window.into());
self.client = Some(client);
}
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
let client = self.client.as_mut().unwrap();
client.event(event, event_loop);
}
}

BIN
src/assets/sungals.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

79
src/input.rs Normal file
View File

@@ -0,0 +1,79 @@
use ui::{
core::{CursorState, Modifiers},
layout::Vec2,
};
use winit::{
event::{MouseButton, MouseScrollDelta, WindowEvent},
keyboard::{Key, NamedKey},
};
use super::Client;
#[derive(Default)]
pub struct Input {
cursor: CursorState,
pub modifiers: Modifiers,
}
impl Input {
pub fn event(&mut self, event: &WindowEvent) -> bool {
match event {
WindowEvent::CursorMoved { position, .. } => {
self.cursor.pos = Vec2::new(position.x as f32, position.y as f32);
self.cursor.exists = true;
}
WindowEvent::MouseInput { state, button, .. } => {
let buttons = &mut self.cursor.buttons;
let pressed = state.is_pressed();
match button {
MouseButton::Left => buttons.left.update(pressed),
MouseButton::Right => buttons.right.update(pressed),
MouseButton::Middle => buttons.middle.update(pressed),
_ => (),
}
}
WindowEvent::MouseWheel { delta, .. } => {
let delta = match *delta {
MouseScrollDelta::LineDelta(x, y) => Vec2::new(x, y),
MouseScrollDelta::PixelDelta(pos) => Vec2::new(pos.x as f32, pos.y as f32),
};
self.cursor.scroll_delta = delta;
}
WindowEvent::CursorLeft { .. } => {
self.cursor.exists = false;
self.modifiers.clear();
}
WindowEvent::KeyboardInput { event, .. } => {
if let Key::Named(named) = event.logical_key {
let pressed = event.state.is_pressed();
match named {
NamedKey::Control => {
self.modifiers.control = pressed;
}
NamedKey::Shift => {
self.modifiers.shift = pressed;
}
_ => (),
}
}
}
_ => return false,
}
true
}
pub fn end_frame(&mut self) {
self.cursor.end_frame();
}
}
impl Client {
pub fn window_size(&self) -> Vec2 {
let size = self.renderer.window().inner_size();
(size.width, size.height).into()
}
pub fn cursor_state(&self) -> &CursorState {
&self.input.cursor
}
}

300
src/main.rs Normal file
View File

@@ -0,0 +1,300 @@
use std::sync::Arc;
use app::App;
use arboard::Clipboard;
use input::Input;
use render::Renderer;
use ui::prelude::*;
use text_lib::Family;
use winit::{event::WindowEvent, event_loop::ActiveEventLoop, window::Window};
mod app;
mod input;
mod render;
pub fn main() {
App::run();
}
pub struct Client {
renderer: Renderer,
input: Input,
ui: Ui,
info: WidgetId<Text>,
focus: Option<WidgetId<TextEdit>>,
clipboard: Clipboard,
}
#[derive(Eq, PartialEq, Hash, Clone)]
struct Submit;
impl DefaultEvent for Submit {
type Data = ();
}
impl Client {
pub fn new(window: Arc<Window>) -> Self {
let renderer = Renderer::new(window);
let mut ui = Ui::new();
let rrect = rect(Color::WHITE).radius(20);
let pad_test = (
rrect.color(Color::BLUE),
(
rrect.color(Color::RED).sized(100).center(),
(
rrect.color(Color::ORANGE),
rrect.color(Color::LIME).pad(10.0),
)
.span(Dir::RIGHT, ratio(1)),
rrect.color(Color::YELLOW),
)
.span(Dir::RIGHT, [2, 2, 1])
.pad(10),
)
.span(Dir::RIGHT, [1, 3])
.add_static(&mut ui);
let span_test = (
rrect.color(Color::GREEN),
rrect.color(Color::ORANGE),
rrect.color(Color::CYAN),
rrect.color(Color::BLUE),
rrect.color(Color::MAGENTA),
rrect.color(Color::RED),
)
.span(
Dir::LEFT,
[
fixed(100),
ratio(1),
ratio(1),
relative(0.5),
fixed(100),
fixed(100),
],
)
.add_static(&mut ui);
let span_add = Span::empty(Dir::RIGHT).add_static(&mut ui);
let add_button = rect(Color::LIME)
.radius(30)
.on(CursorSense::click(), move |ctx: &mut Client, _| {
let child = ctx
.ui
.add(image(include_bytes!("assets/sungals.png")).center())
.any();
ctx.ui[span_add].children.push((child, sized()));
})
.sized(150)
.align(Align::BotRight);
let del_button = rect(Color::RED)
.radius(30)
.on(CursorSense::click(), move |ctx: &mut Client, _| {
ctx.ui[span_add].children.pop();
})
.sized(150)
.align(Align::BotLeft);
let span_add_test = (span_add, add_button, del_button)
.stack()
.add_static(&mut ui);
let main = pad_test.pad(10).add_static(&mut ui);
let btext = |content| text(content).size(30);
let text_test = (
btext("this is a").align(Align::Left),
btext("teeeeeeeest").align(Align::Right),
btext("okkk\nokkkkkk!").align(Align::Left),
btext("hmm"),
btext("a"),
(
btext("'").family(Family::Monospace).align(Align::Top),
btext("'").family(Family::Monospace),
btext(":gamer mode").family(Family::Monospace),
rect(Color::CYAN).sized(10).center(),
rect(Color::RED).sized(100).center(),
rect(Color::PURPLE).sized(50).align(Align::Top),
)
.span(Dir::RIGHT, sized())
.center(),
text("pretty cool right?").size(50),
)
.span(Dir::DOWN, sized())
.add_static(&mut ui);
let texts = Span::empty(Dir::DOWN).add_static(&mut ui);
let msg_area = (Rect::new(Color::SKY), texts.scroll().masked()).stack();
let add_text = text("add")
.editable()
.text_align(Align::Left)
.size(30)
.id_on(CursorSense::click(), |id, client: &mut Client, ctx| {
client.ui.text(id).select(ctx.cursor, ctx.size);
client.focus = Some(id.clone());
})
.id_on(Submit, move |id, client: &mut Client, _| {
let content = client.ui.text(id).take();
let text = text(content)
.editable()
.size(30)
.text_align(Align::Left)
.wrap(true)
.id_on(CursorSense::click(), |id, client: &mut Client, ctx| {
client.ui.text(id).select(ctx.cursor, ctx.size);
client.focus = Some(id.clone());
});
let msg_box = (rect(Color::WHITE.darker(0.5)), text)
.stack()
.size(StackSize::Child(1))
.add(&mut client.ui);
client.ui[texts].children.push((msg_box.any(), sized()));
})
.add(&mut ui);
let text_edit_scroll = (
msg_area,
(
Rect::new(Color::WHITE.darker(0.9)),
(
add_text.clone(),
Rect::new(Color::GREEN)
.on(CursorSense::click(), move |client: &mut Client, _| {
client.run_event(&add_text, Submit, ());
})
.sized(40),
)
.span(Dir::RIGHT, [ratio(1), sized()])
.pad(10),
)
.stack()
.size(StackSize::Child(1))
.offset_layer(1)
.align(Align::Bot),
)
.span(Dir::DOWN, [ratio(1), sized()])
.add_static(&mut ui);
let switch_button = |color, to, label| {
let rect = rect(color)
.id_on(CursorSense::click(), move |id, ui: &mut Ui, _| {
ui[main].inner.set_static(to);
ui[id].color = color.darker(0.3);
})
.edit_on(
CursorSense::HoverStart | CursorSense::unclick(),
move |r, _| {
r.color = color.brighter(0.2);
},
)
.edit_on(CursorSense::HoverEnd, move |r, _| {
r.color = color;
});
(rect, text(label).size(30)).stack()
};
let tabs = (
switch_button(Color::RED, pad_test.any(), "pad"),
switch_button(Color::GREEN, span_test.any(), "span"),
switch_button(Color::BLUE, span_add_test.any(), "image span"),
switch_button(Color::MAGENTA, text_test.any(), "text layout"),
switch_button(
Color::YELLOW.mul_rgb(0.5),
text_edit_scroll.any(),
"text edit scroll",
),
)
.span(Dir::RIGHT, ratio(1));
let info = text("").add(&mut ui);
let info_sect = info.clone().pad(10).align(Align::Right);
(
(tabs, main).span(Dir::DOWN, [fixed(40), ratio(1)]),
info_sect,
)
.stack()
.set_root(&mut ui);
Self {
renderer,
input: Input::default(),
ui,
info,
focus: None,
clipboard: Clipboard::new().unwrap(),
}
}
pub fn event(&mut self, event: WindowEvent, event_loop: &ActiveEventLoop) {
let input_changed = self.input.event(&event);
let cursor_state = self.cursor_state().clone();
if let Some(focus) = &self.focus
&& cursor_state.buttons.left.is_start()
{
self.ui.text(focus).deselect();
self.focus = None;
}
if input_changed {
let window_size = self.window_size();
self.run_sensors(&cursor_state, window_size);
self.ui.run_sensors(&cursor_state, window_size);
}
match event {
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::RedrawRequested => {
self.ui.update();
self.renderer.update(&mut self.ui);
self.renderer.draw()
}
WindowEvent::Resized(size) => {
self.ui.resize((size.width, size.height));
self.renderer.resize(&size)
}
WindowEvent::KeyboardInput { event, .. } => {
if let Some(sel) = &self.focus
&& event.state.is_pressed()
{
let mut text = self.ui.text(sel);
match text.apply_event(&event, &self.input.modifiers) {
TextInputResult::Unfocus => {
self.focus = None;
}
TextInputResult::Submit => {
self.run_event(&sel.clone(), Submit, ());
}
TextInputResult::Paste => {
if let Ok(t) = self.clipboard.get_text() {
text.insert(&t);
}
}
TextInputResult::Unused | TextInputResult::Used => (),
}
}
}
_ => (),
}
let new = format!(
"widgets: {}\nactive:{}\nviews: {}",
self.ui.num_widgets(),
self.ui.active_widgets(),
self.renderer.ui.view_count()
);
if new != *self.ui[&self.info].content {
*self.ui[&self.info].content = new;
}
if self.ui.needs_redraw() {
self.renderer.window().request_redraw();
}
self.input.end_frame();
}
}
impl UiCtx for Client {
fn ui(&mut self) -> &mut Ui {
&mut self.ui
}
}

151
src/render/mod.rs Normal file
View File

@@ -0,0 +1,151 @@
use pollster::FutureExt;
use std::sync::Arc;
use ui::{
layout::Ui,
render::{UiLimits, UiRenderer},
};
use wgpu::{util::StagingBelt, *};
use winit::{dpi::PhysicalSize, window::Window};
pub const CLEAR_COLOR: Color = Color::BLACK;
pub struct Renderer {
window: Arc<Window>,
surface: Surface<'static>,
device: Device,
queue: Queue,
config: SurfaceConfiguration,
encoder: CommandEncoder,
staging_belt: StagingBelt,
pub ui: UiRenderer,
}
impl Renderer {
pub fn update(&mut self, updates: &mut Ui) {
self.ui.update(&self.device, &self.queue, updates);
}
pub fn draw(&mut self) {
let output = self.surface.get_current_texture().unwrap();
let view = output
.texture
.create_view(&TextureViewDescriptor::default());
let mut encoder = std::mem::replace(&mut self.encoder, Self::create_encoder(&self.device));
{
let render_pass = &mut encoder.begin_render_pass(&RenderPassDescriptor {
color_attachments: &[Some(RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: Operations {
load: LoadOp::Clear(CLEAR_COLOR),
store: StoreOp::Store,
},
depth_slice: None,
})],
..Default::default()
});
self.ui.draw(render_pass);
}
self.queue.submit(std::iter::once(encoder.finish()));
self.staging_belt.finish();
output.present();
self.staging_belt.recall();
}
pub fn resize(&mut self, size: &PhysicalSize<u32>) {
self.config.width = size.width;
self.config.height = size.height;
self.surface.configure(&self.device, &self.config);
self.ui.resize(size, &self.queue);
}
fn create_encoder(device: &Device) -> CommandEncoder {
device.create_command_encoder(&CommandEncoderDescriptor {
label: Some("Render Encoder"),
})
}
pub fn new(window: Arc<Window>) -> Self {
let size = window.inner_size();
let instance = Instance::new(&InstanceDescriptor {
backends: Backends::PRIMARY,
..Default::default()
});
let surface = instance
.create_surface(window.clone())
.expect("Could not create window surface!");
let adapter = instance
.request_adapter(&RequestAdapterOptions {
power_preference: PowerPreference::default(),
compatible_surface: Some(&surface),
force_fallback_adapter: false,
})
.block_on()
.expect("Could not get adapter!");
let ui_limits = UiLimits::default();
let (device, queue) = adapter
.request_device(&DeviceDescriptor {
required_features: Features::TEXTURE_BINDING_ARRAY
| Features::PARTIALLY_BOUND_BINDING_ARRAY
| Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING,
required_limits: Limits {
max_binding_array_elements_per_shader_stage: ui_limits
.max_binding_array_elements_per_shader_stage(),
max_binding_array_sampler_elements_per_shader_stage: ui_limits
.max_binding_array_sampler_elements_per_shader_stage(),
..Default::default()
},
..Default::default()
})
.block_on()
.expect("Could not get device!");
let surface_caps = surface.get_capabilities(&adapter);
let surface_format = surface_caps
.formats
.iter()
.copied()
.find(|f| f.is_srgb())
.unwrap_or(surface_caps.formats[0]);
let config = SurfaceConfiguration {
usage: TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
width: size.width,
height: size.height,
present_mode: PresentMode::AutoVsync,
alpha_mode: surface_caps.alpha_modes[0],
desired_maximum_frame_latency: 2,
view_formats: vec![],
};
surface.configure(&device, &config);
let staging_belt = StagingBelt::new(4096 * 4);
let encoder = Self::create_encoder(&device);
let shape_pipeline = UiRenderer::new(&device, &queue, &config, ui_limits);
Self {
surface,
device,
queue,
config,
encoder,
staging_belt,
ui: shape_pipeline,
window,
}
}
pub fn window(&self) -> &Window {
self.window.as_ref()
}
}