diff --git a/Cargo.toml b/Cargo.toml index 4815d2d075..ee804ea7e7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ members = [ "druid/examples/web", "druid/examples/hello_web", "druid/examples/value_formatting", + "idiopath", ] default-members = [ "druid", diff --git a/druid-shell/src/backend/mac/window.rs b/druid-shell/src/backend/mac/window.rs index 836f49543f..a212412cf3 100644 --- a/druid-shell/src/backend/mac/window.rs +++ b/druid-shell/src/backend/mac/window.rs @@ -1424,6 +1424,7 @@ unsafe impl HasRawWindowHandle for WindowHandle { } unsafe impl Send for IdleHandle {} +unsafe impl Sync for IdleHandle {} impl IdleHandle { fn add_idle(&self, idle: IdleKind) { diff --git a/idiopath/Cargo.toml b/idiopath/Cargo.toml new file mode 100644 index 0000000000..08c6bcd65a --- /dev/null +++ b/idiopath/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "idiopath" +version = "0.1.0" +authors = ["Raph Levien "] +edition = "2021" + +[dependencies] +"druid-shell" = { path = "../druid-shell" } + +futures-task = "0.3" +tokio = { version = "1", features = ["full"] } diff --git a/idiopath/README.md b/idiopath/README.md new file mode 100644 index 0000000000..94c9108dc0 --- /dev/null +++ b/idiopath/README.md @@ -0,0 +1,77 @@ +# An experimental Rust architecture for reactive UI + +This repo contains an experimental architecture, implemented with a toy UI. At a very high level, it combines ideas from Flutter, SwiftUI, and Elm. Like all of these, it uses lightweight view objects, diffing them to provide minimal updates to a retained UI. Like SwiftUI, it is strongly typed. + +## Overall program flow + +Like Elm, the app logic contains *centralized state.* On each cycle (meaning, roughly, on each high-level UI interaction such as a button click), the framework calls a closure, giving it mutable access to the app state, and the return value is a *view tree.* This view tree is fairly short-lived; it is used to render the UI, possibly dispatch some events, and be used as a reference for *diffing* by the next cycle, at which point it is dropped. + +We'll use the standard counter example. Here the state is a single integer, and the view tree is a column containing two buttons. + +```rust +fn app_logic(data: &mut u32) -> impl View { + Column::new(( + Button::new(format!("count: {}", data), |data| *data += 1), + Button::new("reset", |data| *data = 0), + )) +} +``` + +These are all just vanilla data structures. The next step is diffing or reconciling against a previous version, now a standard technique. The result is an *element tree.* Each node type in the view tree has a corresponding element as an associated type. The `build` method on a view node creates the element, and the `rebuild` method diffs against the previous version (for example, if the string changes) and updates the element. There's also an associated state tree, not actually needed in this simple example, but would be used for memoization. + +The closures are the interesting part. When they're run, they take a mutable reference to the app data. + +## Components + +A major goal is to support React-like components, where modules that build UI for some fragment of the overall app state are composed together. + +```rust +struct AppData { + count: u32, +} + +fn count_button(count: u32) -> impl View { + Button::new(format!("count: {}", count), |data| *data += 1) +} + +fn app_logic(data: &mut AppData) -> impl View { + Adapt::new(|data: &mut AppData, thunk| thunk.call(&mut data.count), + count_button(data.count)) +} +``` + +This adapt node is very similar to a lens (quite familiar to existing Druid users), and is also very similar to the [Html.map] node in Elm. Note that in this case the data presented to the child component to render, and the mutable app state available in callbacks is the same, but that is not necessarily the case. + +## Memoization + +In the simplest case, the app builds the entire view tree, which is diffed against the previous tree, only to find that most of it hasn't changed. + +When a subtree is a pure function of some data, as is the case for the button above, it makes sense to *memoize.* The data is compared to the previous version, and only when it's changed is the view tree build. The signature of the memoize node is nearly identical to [Html.lazy] in Elm: + +```rust +n app_logic(data: &mut AppData) -> impl View { + Memoize::new(data.count, |count| { + Button::new(format!("count: {}", count), |data: &mut AppData| { + data.count += 1 + }) + }), +} +``` + +The current code uses a `PartialEq` bound, but in practice I think it might be much more useful to use pointer equality on `Rc` and `Arc`. + +The combination of memoization with pointer equality and an adapt node that calls [Rc::make_mut] on the parent type is actually a powerful form of change tracking, similar in scope to Adapton, self-adjusting computation, or the types of binding objects used in SwiftUI. If a piece of data is rendered in two different places, it automatically propagates the change to both of those, without having to do any explicit management of the dependency graph. + +I anticipate it will also be possible to do dirty tracking manually - the app logic can set a dirty flag when a subtree needs re-rendering. + +## Optional type erasure + +By default, view nodes are strongly typed. The type of a container includes the types of its children (through the `ViewTuple` trait), so for a large tree the type can become quite large. In addition, such types don't make for easy dynamic reconfiguration of the UI. SwiftUI has exactly this issue, and provides [AnyView] as the solution. Ours is more or less identical. + +The type erasure of View nodes is not an easy trick, as the trait has two associated types and the `rebuild` method takes the previous view as a `&Self` typed parameter. Nonetheless, it is possible. (As far as I know, Olivier Faure was the first to demonstrate this technique, in [Panoramix], but I'm happy to be further enlightened) + +[Html.lazy]: https://guide.elm-lang.org/optimization/lazy.html +[Html map]: https://package.elm-lang.org/packages/elm/html/latest/Html#map +[Rc::make_mut]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.make_mut +[AnyView]: https://developer.apple.com/documentation/swiftui/anyview +[Panoramix]: https://github.com/PoignardAzur/panoramix diff --git a/idiopath/src/app.rs b/idiopath/src/app.rs new file mode 100644 index 0000000000..8ccaa2bac1 --- /dev/null +++ b/idiopath/src/app.rs @@ -0,0 +1,139 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::{Arc, Mutex}; + +use druid_shell::{kurbo::Point, piet::Piet, WindowHandle}; + +use crate::{ + event::Event, + id::Id, + view::{Cx, View}, + widget::{RawEvent, Widget}, +}; + +pub struct App, F: FnMut(&mut T) -> V> +where + V::Element: Widget, +{ + data: T, + app_logic: F, + view: Option, + id: Option, + state: Option, + element: Option, + events: Vec, + cx: Cx, + wake_queue: WakeQueue, +} + +#[derive(Clone, Default)] +pub struct WakeQueue(Arc>>); + +impl, F: FnMut(&mut T) -> V> App +where + V::Element: Widget, +{ + pub fn new(data: T, app_logic: F) -> Self { + let wake_queue = Default::default(); + let cx = Cx::new(&wake_queue); + App { + data, + app_logic, + view: None, + id: None, + state: None, + element: None, + events: Vec::new(), + cx, + wake_queue, + } + } + + pub fn ensure_app(&mut self) { + if self.view.is_none() { + let view = (self.app_logic)(&mut self.data); + let (id, state, element) = view.build(&mut self.cx); + self.view = Some(view); + self.id = Some(id); + self.state = Some(state); + self.element = Some(element); + } + } + + pub fn connect(&mut self, window_handle: WindowHandle) { + self.cx.set_handle(window_handle.get_idle_handle()); + } + + pub fn paint(&mut self, piet: &mut Piet) { + self.ensure_app(); + let element = self.element.as_mut().unwrap(); + element.layout(); + element.paint(piet, Point::ZERO); + } + + pub fn mouse_down(&mut self, point: Point) { + self.event(RawEvent::MouseDown(point)); + } + + fn event(&mut self, event: RawEvent) { + self.ensure_app(); + let element = self.element.as_mut().unwrap(); + element.event(&event, &mut self.events); + self.run_app_logic(); + } + + pub fn run_app_logic(&mut self) { + for event in self.events.drain(..) { + let id_path = &event.id_path[1..]; + self.view.as_ref().unwrap().event( + id_path, + self.state.as_mut().unwrap(), + event.body, + &mut self.data, + ); + } + // Re-rendering should be more lazy. + let view = (self.app_logic)(&mut self.data); + view.rebuild( + &mut self.cx, + self.view.as_ref().unwrap(), + self.id.as_mut().unwrap(), + self.state.as_mut().unwrap(), + self.element.as_mut().unwrap(), + ); + assert!(self.cx.is_empty(), "id path imbalance on rebuild"); + self.view = Some(view); + } + + pub fn wake_async(&mut self) { + let events = self.wake_queue.take(); + self.events.extend(events); + self.run_app_logic(); + } +} + +impl WakeQueue { + // Returns true if the queue was empty. + pub fn push_event(&self, event: Event) -> bool { + let mut queue = self.0.lock().unwrap(); + let was_empty = queue.is_empty(); + queue.push(event); + was_empty + } + + pub fn take(&self) -> Vec { + std::mem::replace(&mut self.0.lock().unwrap(), Vec::new()) + } +} diff --git a/idiopath/src/event.rs b/idiopath/src/event.rs new file mode 100644 index 0000000000..e36a2a0727 --- /dev/null +++ b/idiopath/src/event.rs @@ -0,0 +1,33 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::any::Any; + +use crate::id::IdPath; + +pub struct Event { + pub id_path: IdPath, + pub body: Box, +} + +pub struct AsyncWake; + +impl Event { + pub fn new(id_path: IdPath, event: impl Any + Send) -> Event { + Event { + id_path, + body: Box::new(event), + } + } +} diff --git a/idiopath/src/id.rs b/idiopath/src/id.rs new file mode 100644 index 0000000000..2bf6889e7d --- /dev/null +++ b/idiopath/src/id.rs @@ -0,0 +1,34 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::num::NonZeroU64; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Hash)] +/// A stable identifier for an element. +pub struct Id(NonZeroU64); + +pub type IdPath = Vec; + +impl Id { + /// Allocate a new, unique `Id`. + pub fn next() -> Id { + use druid_shell::Counter; + static WIDGET_ID_COUNTER: Counter = Counter::new(); + Id(WIDGET_ID_COUNTER.next_nonzero()) + } + + pub fn to_raw(self) -> u64 { + self.0.into() + } +} diff --git a/idiopath/src/main.rs b/idiopath/src/main.rs new file mode 100644 index 0000000000..9f7b1ab5d6 --- /dev/null +++ b/idiopath/src/main.rs @@ -0,0 +1,199 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +mod app; +mod event; +mod id; +mod view; +mod view_tuple; +mod widget; + +use std::any::Any; +use std::time::Duration; + +use app::App; +use druid_shell::kurbo::Size; +use druid_shell::piet::{Color, RenderContext}; + +use druid_shell::{ + Application, Cursor, HotKey, IdleToken, Menu, MouseEvent, Region, SysMods, WinHandler, + WindowBuilder, WindowHandle, +}; +use view::adapt::Adapt; +use view::button::Button; +use view::column::Column; +use view::future::FutureView; +use view::memoize::Memoize; +use view::View; +use widget::Widget; + +const BG_COLOR: Color = Color::rgb8(0x27, 0x28, 0x22); + +struct MainState, F: FnMut(&mut T) -> V> +where + V::Element: Widget, +{ + size: Size, + handle: WindowHandle, + app: App, +} + +impl + 'static, F: FnMut(&mut T) -> V + 'static> WinHandler + for MainState +where + V::Element: Widget, +{ + fn connect(&mut self, handle: &WindowHandle) { + self.handle = handle.clone(); + self.app.connect(handle.clone()); + } + + fn prepare_paint(&mut self) {} + + fn paint(&mut self, piet: &mut druid_shell::piet::Piet, _: &Region) { + let rect = self.size.to_rect(); + piet.fill(rect, &BG_COLOR); + self.app.paint(piet); + } + + fn command(&mut self, id: u32) { + match id { + 0x100 => { + self.handle.close(); + Application::global().quit() + } + _ => println!("unexpected id {}", id), + } + } + + fn mouse_move(&mut self, _event: &MouseEvent) { + self.handle.set_cursor(&Cursor::Arrow); + } + + fn mouse_down(&mut self, event: &MouseEvent) { + self.app.mouse_down(event.pos); + self.handle.invalidate(); + } + + fn mouse_up(&mut self, _event: &MouseEvent) {} + + fn size(&mut self, size: Size) { + self.size = size; + } + + fn request_close(&mut self) { + self.handle.close(); + } + + fn destroy(&mut self) { + Application::global().quit() + } + + fn as_any(&mut self) -> &mut dyn Any { + self + } + + fn idle(&mut self, token: IdleToken) { + println!("idle handler was called, token = {:?}!", token); + self.app.wake_async(); + // Properly, the app should invalidate only when the appearance changes. + // But this is a quick and dirty demo! + self.handle.invalidate(); + } +} + +impl, F: FnMut(&mut T) -> V> MainState +where + V::Element: Widget, +{ + fn new(app: App) -> Self { + let state = MainState { + size: Default::default(), + handle: Default::default(), + app, + }; + state + } +} + +/* +fn app_logic(data: &mut u32) -> impl View { + let button = Button::new(format!("count: {}", data), |data| *data += 1); + let boxed: Box> = Box::new(button); + Column::new((boxed, Button::new("reset", |data| *data = 0))) +} +*/ + +#[derive(Default)] +struct AppData { + count: u32, +} + +fn count_button(count: u32) -> impl View { + Button::new(format!("count: {}", count), |data| *data += 1) +} + +fn app_logic(data: &mut AppData) -> impl View { + Column::new(( + Button::new(format!("count: {}", data.count), |data: &mut AppData| { + data.count += 1 + }), + Button::new("reset", |data: &mut AppData| data.count = 0), + Memoize::new(data.count, |count| { + Button::new(format!("count: {}", count), |data: &mut AppData| { + data.count += 1 + }) + }), + Adapt::new( + |data: &mut AppData, thunk| thunk.call(&mut data.count), + count_button(data.count), + ), + FutureView::new( + || tokio::spawn(async { + tokio::time::sleep(Duration::from_millis(1000)).await; + 42 + }), + |value| Button::new(format!("{:?}", value), |_| ()), + ), + )) +} + +#[tokio::main] +async fn main() { + //tracing_subscriber::fmt().init(); + let mut file_menu = Menu::new(); + file_menu.add_item( + 0x100, + "E&xit", + Some(&HotKey::new(SysMods::Cmd, "q")), + true, + false, + ); + let mut menubar = Menu::new(); + menubar.add_dropdown(Menu::new(), "Application", true); + menubar.add_dropdown(file_menu, "&File", true); + + let app = App::new(AppData::default(), app_logic); + let druid_app = Application::new().unwrap(); + let mut builder = WindowBuilder::new(druid_app.clone()); + let main_state = MainState::new(app); + builder.set_handler(Box::new(main_state)); + builder.set_title("Idiopath"); + builder.set_menu(menubar); + + let window = builder.build().unwrap(); + window.show(); + + druid_app.run(None); +} diff --git a/idiopath/src/view.rs b/idiopath/src/view.rs new file mode 100644 index 0000000000..1b8ec2a6d2 --- /dev/null +++ b/idiopath/src/view.rs @@ -0,0 +1,123 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod adapt; +pub mod any_view; +pub mod button; +pub mod column; +pub mod future; +pub mod memoize; +pub mod use_state; + +use std::{any::Any, sync::Arc}; + +use druid_shell::{IdleHandle, IdleToken}; +use futures_task::{ArcWake, Waker}; + +use crate::{ + app::WakeQueue, + event::{AsyncWake, Event}, + id::{Id, IdPath}, + widget::Widget, +}; + +pub trait View { + type State; + + type Element: Widget; + + fn build(&self, cx: &mut Cx) -> (Id, Self::State, Self::Element); + + fn rebuild( + &self, + cx: &mut Cx, + prev: &Self, + id: &mut Id, + state: &mut Self::State, + element: &mut Self::Element, + ); + + fn event( + &self, + id_path: &[Id], + state: &mut Self::State, + event: Box, + app_state: &mut T, + ) -> A; +} + +#[derive(Clone)] +pub struct Cx { + id_path: IdPath, + idle_handle: Option, + wake_queue: WakeQueue, +} + +struct MyWaker { + id_path: IdPath, + idle_handle: IdleHandle, + wake_queue: WakeQueue, +} + +impl ArcWake for MyWaker { + fn wake_by_ref(arc_self: &Arc) { + println!("path = {:?}", arc_self.id_path); + let event = Event::new(arc_self.id_path.clone(), AsyncWake); + if arc_self.wake_queue.push_event(event) { + // The clone shouldn't be needed; schedule_idle should be &self I think + arc_self + .idle_handle + .clone() + .schedule_idle(IdleToken::new(42)); + } + } +} + +impl Cx { + pub fn new(wake_queue: &WakeQueue) -> Self { + Cx { + id_path: Vec::new(), + idle_handle: None, + wake_queue: wake_queue.clone(), + } + } + + pub fn push(&mut self, id: Id) { + self.id_path.push(id); + } + + pub fn pop(&mut self) { + self.id_path.pop(); + } + + pub fn is_empty(&self) -> bool { + self.id_path.is_empty() + } + + pub fn id_path(&self) -> &IdPath { + &self.id_path + } + + pub(crate) fn set_handle(&mut self, idle_handle: Option) { + self.idle_handle = idle_handle; + } + + pub fn waker(&self) -> Waker { + futures_task::waker(Arc::new(MyWaker { + id_path: self.id_path.clone(), + idle_handle: self.idle_handle.as_ref().unwrap().clone(), + wake_queue: self.wake_queue.clone(), + })) + } +} diff --git a/idiopath/src/view/adapt.rs b/idiopath/src/view/adapt.rs new file mode 100644 index 0000000000..8accd4cd3a --- /dev/null +++ b/idiopath/src/view/adapt.rs @@ -0,0 +1,92 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::{any::Any, marker::PhantomData}; + +use crate::id::Id; + +use super::{Cx, View}; + +pub struct Adapt) -> A, C: View> { + f: F, + child: C, + phantom: PhantomData<(T, A, U, B)>, +} + +/// A "thunk" which dispatches an event to an adapt node's child. +/// +/// The closure passed to Adapt should call this thunk with the child's +/// app state. +pub struct AdaptThunk<'a, U, B, C: View> { + child: &'a C, + state: &'a mut C::State, + id_path: &'a [Id], + event: Box, +} + +impl) -> A, C: View> Adapt { + pub fn new(f: F, child: C) -> Self { + Adapt { + f, + child, + phantom: Default::default(), + } + } +} + +impl<'a, U, B, C: View> AdaptThunk<'a, U, B, C> { + pub fn call(self, app_state: &mut U) -> B { + self.child + .event(self.id_path, self.state, self.event, app_state) + } +} + +impl) -> A, C: View> View + for Adapt +{ + type State = C::State; + + type Element = C::Element; + + fn build(&self, cx: &mut Cx) -> (Id, Self::State, Self::Element) { + self.child.build(cx) + } + + fn rebuild( + &self, + cx: &mut Cx, + prev: &Self, + id: &mut Id, + state: &mut Self::State, + element: &mut Self::Element, + ) { + self.child.rebuild(cx, &prev.child, id, state, element); + } + + fn event( + &self, + id_path: &[Id], + state: &mut Self::State, + event: Box, + app_state: &mut T, + ) -> A { + let thunk = AdaptThunk { + child: &self.child, + state, + id_path, + event, + }; + (self.f)(app_state, thunk) + } +} diff --git a/idiopath/src/view/any_view.rs b/idiopath/src/view/any_view.rs new file mode 100644 index 0000000000..570d7492ab --- /dev/null +++ b/idiopath/src/view/any_view.rs @@ -0,0 +1,143 @@ +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::{ + any::Any, + ops::{Deref, DerefMut}, +}; + +use crate::{id::Id, widget::AnyWidget}; + +use super::{Cx, View}; + +/// A trait enabling type erasure of views. +/// +/// The name is slightly misleading as it's not any view, but only ones +/// whose element is AnyWidget. +/// +/// Making a trait which is generic over another trait bound appears to +/// be well beyond the capability of Rust's type system. If type-erased +/// views with other bounds are needed, the best approach is probably +/// duplication of the code, probably with a macro. +pub trait AnyView { + fn as_any(&self) -> &dyn Any; + + fn dyn_build(&self, cx: &mut Cx) -> (Id, Box, Box); + + fn dyn_rebuild( + &self, + cx: &mut Cx, + prev: &dyn AnyView, + id: &mut Id, + state: &mut Box, + element: &mut Box, + ); + + fn dyn_event( + &self, + id_path: &[Id], + state: &mut dyn Any, + event: Box, + app_state: &mut T, + ) -> A; +} + +impl + 'static> AnyView for V +where + V::State: 'static, + V::Element: AnyWidget + 'static, +{ + fn as_any(&self) -> &dyn Any { + self + } + + fn dyn_build(&self, cx: &mut Cx) -> (Id, Box, Box) { + let (id, state, element) = self.build(cx); + (id, Box::new(state), Box::new(element)) + } + + fn dyn_rebuild( + &self, + cx: &mut Cx, + prev: &dyn AnyView, + id: &mut Id, + state: &mut Box, + element: &mut Box, + ) { + if let Some(prev) = prev.as_any().downcast_ref() { + if let Some(state) = state.downcast_mut() { + if let Some(element) = element.deref_mut().as_any_mut().downcast_mut() { + self.rebuild(cx, prev, id, state, element); + } else { + println!("downcast of element failed in dyn_event"); + } + } else { + println!("downcast of state failed in dyn_event"); + } + } else { + let (new_id, new_state, new_element) = self.build(cx); + *id = new_id; + *state = Box::new(new_state); + *element = Box::new(new_element); + } + } + + fn dyn_event( + &self, + id_path: &[Id], + state: &mut dyn Any, + event: Box, + app_state: &mut T, + ) -> A { + if let Some(state) = state.downcast_mut() { + self.event(id_path, state, event, app_state) + } else { + // Possibly softer failure? Would require either Option return or + // Default bound on A. + panic!("downcast error in dyn_event"); + } + } +} + +impl View for Box> { + type State = Box; + + type Element = Box; + + fn build(&self, cx: &mut Cx) -> (Id, Self::State, Self::Element) { + self.deref().dyn_build(cx) + } + + fn rebuild( + &self, + cx: &mut Cx, + prev: &Self, + id: &mut Id, + state: &mut Self::State, + element: &mut Self::Element, + ) { + self.deref() + .dyn_rebuild(cx, prev.deref(), id, state, element); + } + + fn event( + &self, + id_path: &[Id], + state: &mut Self::State, + event: Box, + app_state: &mut T, + ) -> A { + self.deref() + .dyn_event(id_path, state.deref_mut(), event, app_state) + } +} diff --git a/idiopath/src/view/button.rs b/idiopath/src/view/button.rs new file mode 100644 index 0000000000..30d0d6e2a3 --- /dev/null +++ b/idiopath/src/view/button.rs @@ -0,0 +1,71 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::any::Any; + +use crate::id::Id; + +use super::{Cx, View}; + +pub struct Button { + label: String, + // consider not boxing + callback: Box A>, +} + +impl Button { + pub fn new(label: impl Into, clicked: impl Fn(&mut T) -> A + 'static) -> Self { + Button { + label: label.into(), + callback: Box::new(clicked), + } + } +} + +impl View for Button { + type State = (); + + type Element = crate::widget::button::Button; + + fn build(&self, cx: &mut Cx) -> (Id, Self::State, Self::Element) { + let id = Id::next(); + cx.push(id); + let element = crate::widget::button::Button::new(cx.id_path(), self.label.clone()); + cx.pop(); + (id, (), element) + } + + fn rebuild( + &self, + _cx: &mut Cx, + prev: &Self, + _id: &mut crate::id::Id, + _state: &mut Self::State, + element: &mut Self::Element, + ) { + if prev.label != self.label { + element.set_label(self.label.clone()); + } + } + + fn event( + &self, + _id_path: &[crate::id::Id], + _state: &mut Self::State, + _event: Box, + app_state: &mut T, + ) -> A { + (self.callback)(app_state) + } +} diff --git a/idiopath/src/view/column.rs b/idiopath/src/view/column.rs new file mode 100644 index 0000000000..310c9f6628 --- /dev/null +++ b/idiopath/src/view/column.rs @@ -0,0 +1,76 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::{any::Any, marker::PhantomData}; + +use crate::{id::Id, view_tuple::ViewTuple, widget::WidgetTuple}; + +use super::{Cx, View}; + +pub struct Column> { + children: VT, + phantom: PhantomData<(T, A)>, +} + +impl> Column +where + VT::Elements: WidgetTuple, +{ + pub fn new(children: VT) -> Self { + let phantom = Default::default(); + Column { children, phantom } + } +} + +impl> View for Column +where + VT::Elements: WidgetTuple, +{ + type State = VT::State; + + type Element = crate::widget::column::Column; + + fn build(&self, cx: &mut Cx) -> (Id, Self::State, Self::Element) { + let id = Id::next(); + cx.push(id); + let (state, elements) = self.children.build(cx); + cx.pop(); + let column = crate::widget::column::Column::new(elements); + (id, state, column) + } + + fn rebuild( + &self, + cx: &mut Cx, + prev: &Self, + id: &mut Id, + state: &mut Self::State, + element: &mut Self::Element, + ) { + cx.push(*id); + self.children + .rebuild(cx, &prev.children, state, element.children_mut()); + cx.pop(); + } + + fn event( + &self, + id_path: &[Id], + state: &mut Self::State, + event: Box, + app_state: &mut T, + ) -> A { + self.children.event(id_path, state, event, app_state) + } +} diff --git a/idiopath/src/view/future.rs b/idiopath/src/view/future.rs new file mode 100644 index 0000000000..1eebc554d8 --- /dev/null +++ b/idiopath/src/view/future.rs @@ -0,0 +1,174 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::{future::Future, marker::PhantomData, pin::Pin}; + +use futures_task::{Context, Poll, Waker}; + +use crate::id::Id; + +use super::{Cx, View}; + +pub struct FutureView< + T, + A, + FutureCB: Fn() -> F, + F: Future + Unpin, + D, + ViewCB: Fn(Option<&D>) -> V, + V: View, +> { + future_cb: FutureCB, + view_cb: ViewCB, + phantom: PhantomData<(T, A)>, +} + +pub struct FutureState + Unpin, D, V: View> { + child_id: Id, + waker: Waker, + awakened: bool, + future: PendingFuture, + view: V, + view_state: V::State, +} + +enum PendingFuture> { + Pending(F), + Ready(D), +} + +impl + Unpin> PendingFuture { + // Return true if the state changed + fn invoke(&mut self, waker: &Waker) -> bool { + if let PendingFuture::Pending(f) = self { + let mut future_cx = Context::from_waker(&waker); + match Pin::new(f).poll(&mut future_cx) { + Poll::Ready(d) => { + *self = PendingFuture::Ready(d); + true + } + Poll::Pending => false, + } + } else { + false + } + } +} + +// Note: the Default bound on A here is not quite right. A better approach I +// think would be to have an EventResult enum with A as one variant, and others +// for "id path not found" (ie async wake delivered to node that was deleted) +// and "async wake success", which would set dirty bits on Memoize etc. +impl< + T, + A: Default, + FutureCB: Fn() -> F, + F: Future + Unpin, + D, + ViewCB: Fn(Option<&D>) -> V, + V: View, + > FutureView +{ + pub fn new(future_cb: FutureCB, view_cb: ViewCB) -> Self { + FutureView { + future_cb, + view_cb, + phantom: Default::default(), + } + } +} + +impl< + T, + A: Default, + FutureCB: Fn() -> F, + F: Future + Unpin, + D, + ViewCB: Fn(Option<&D>) -> V, + V: View, + > View for FutureView +{ + type State = FutureState; + + type Element = V::Element; + + fn build(&self, cx: &mut Cx) -> (crate::id::Id, Self::State, Self::Element) { + let mut future = PendingFuture::Pending((self.future_cb)()); + let id = Id::next(); + cx.push(id); + let waker = cx.waker(); + future.invoke(&waker); + let data = match &future { + PendingFuture::Ready(d) => Some(d), + _ => None, + }; + let view = (self.view_cb)(data); + + let (child_id, view_state, element) = view.build(cx); + cx.pop(); + let state = FutureState { + child_id, + waker, + awakened: false, + future, + view, + view_state, + }; + (id, state, element) + } + + fn rebuild( + &self, + cx: &mut Cx, + _prev: &Self, + id: &mut Id, + state: &mut Self::State, + element: &mut Self::Element, + ) { + if state.awakened && state.future.invoke(&state.waker) { + let data = match &state.future { + PendingFuture::Ready(d) => Some(d), + _ => None, + }; + let view = (self.view_cb)(data); + cx.push(*id); + view.rebuild( + cx, + &state.view, + &mut state.child_id, + &mut state.view_state, + element, + ); + cx.pop(); + state.view = view; + } + } + + fn event( + &self, + id_path: &[Id], + state: &mut Self::State, + event: Box, + app_state: &mut T, + ) -> A { + if id_path.is_empty() { + state.awakened = true; + Default::default() + } else { + state + .view + .event(&id_path[1..], &mut state.view_state, event, app_state) + } + } +} diff --git a/idiopath/src/view/memoize.rs b/idiopath/src/view/memoize.rs new file mode 100644 index 0000000000..4b9f25ba2b --- /dev/null +++ b/idiopath/src/view/memoize.rs @@ -0,0 +1,77 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::any::Any; + +use crate::id::Id; + +use super::{Cx, View}; + +pub struct Memoize { + data: D, + child_cb: F, +} + +pub struct MemoizeState> { + view: V, + view_state: V::State, +} + +impl V> Memoize { + pub fn new(data: D, child_cb: F) -> Self { + Memoize { data, child_cb } + } +} + +impl, F: Fn(&D) -> V> View + for Memoize +{ + type State = MemoizeState; + + type Element = V::Element; + + fn build(&self, cx: &mut Cx) -> (Id, Self::State, Self::Element) { + let view = (self.child_cb)(&self.data); + let (id, view_state, element) = view.build(cx); + let memoize_state = MemoizeState { view, view_state }; + (id, memoize_state, element) + } + + fn rebuild( + &self, + cx: &mut Cx, + prev: &Self, + id: &mut Id, + state: &mut Self::State, + element: &mut Self::Element, + ) { + if prev.data != self.data { + let view = (self.child_cb)(&self.data); + view.rebuild(cx, &state.view, id, &mut state.view_state, element); + state.view = view; + } + } + + fn event( + &self, + id_path: &[Id], + state: &mut Self::State, + event: Box, + app_state: &mut T, + ) -> A { + state + .view + .event(id_path, &mut state.view_state, event, app_state) + } +} diff --git a/idiopath/src/view/use_state.rs b/idiopath/src/view/use_state.rs new file mode 100644 index 0000000000..c28201489b --- /dev/null +++ b/idiopath/src/view/use_state.rs @@ -0,0 +1,99 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::{any::Any, marker::PhantomData, rc::Rc}; + +use crate::id::Id; + +use super::{Cx, View}; + +/// An implementation of the "use_state" pattern familiar in reactive UI. +/// +/// This may not be the final form. In this version, the parent app data +/// is `Rc`, and the child is `(Rc, S)` where S is the local state. +/// +/// The first callback creates the initial state (it is called on build but +/// not rebuild). The second callback takes that state as an argument. It +/// is not passed the app state, but since that state is `Rc`, it would be +/// natural to clone it and capture it in a `move` closure. +pub struct UseState { + f_init: FInit, + f: F, + phantom: PhantomData<(T, A, S, V)>, +} + +pub struct UseStateState, S), A>> { + state: Option, + view: V, + view_state: V::State, +} + +impl S, F: Fn(&mut S) -> V> UseState { + pub fn new(f_init: FInit, f: F) -> Self { + let phantom = Default::default(); + UseState { f_init, f, phantom } + } +} + +impl, S), A>, FInit: Fn() -> S, F: Fn(&mut S) -> V> View, A> + for UseState +{ + type State = UseStateState; + + type Element = V::Element; + + fn build(&self, cx: &mut Cx) -> (Id, Self::State, Self::Element) { + let mut state = (self.f_init)(); + let view = (self.f)(&mut state); + let (id, view_state, element) = view.build(cx); + let my_state = UseStateState { + state: Some(state), + view, + view_state, + }; + (id, my_state, element) + } + + fn rebuild( + &self, + cx: &mut Cx, + _prev: &Self, + id: &mut Id, + state: &mut Self::State, + element: &mut Self::Element, + ) { + let view = (self.f)(state.state.as_mut().unwrap()); + view.rebuild(cx, &state.view, id, &mut state.view_state, element); + state.view = view; + } + + fn event( + &self, + id_path: &[Id], + state: &mut Self::State, + event: Box, + app_state: &mut Rc, + ) -> A { + let mut local_state = (app_state.clone(), state.state.take().unwrap()); + let a = state + .view + .event(id_path, &mut state.view_state, event, &mut local_state); + let (local_app_state, my_state) = local_state; + if !Rc::ptr_eq(app_state, &local_app_state) { + *app_state = local_app_state + } + state.state = Some(my_state); + a + } +} diff --git a/idiopath/src/view_tuple.rs b/idiopath/src/view_tuple.rs new file mode 100644 index 0000000000..3d85e98ccb --- /dev/null +++ b/idiopath/src/view_tuple.rs @@ -0,0 +1,105 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::any::Any; + +use crate::{ + id::Id, + view::{Cx, View}, +}; + +pub trait ViewTuple { + type State; + + type Elements; + + fn build(&self, cx: &mut Cx) -> (Self::State, Self::Elements); + + fn rebuild(&self, cx: &mut Cx, prev: &Self, state: &mut Self::State, els: &mut Self::Elements); + + fn event( + &self, + id_path: &[Id], + state: &mut Self::State, + event: Box, + app_state: &mut T, + ) -> A; +} + +macro_rules! impl_view_tuple { + ( $n: tt; $( $t:ident),* ; $( $s:tt ),* ) => { + impl ),* > ViewTuple for ( $( $t, )* ) { + type State = ( $( $t::State, )* [Id; $n]); + + type Elements = ( $( $t::Element, )* ); + + fn build(&self, cx: &mut Cx) -> (Self::State, Self::Elements) { + let b = ( $( self.$s.build(cx), )* ); + let state = ( $( b.$s.1, )* [ $( b.$s.0 ),* ]); + let els = ( $( b.$s.2, )* ); + (state, els) + } + + fn rebuild( + &self, + cx: &mut Cx, + prev: &Self, + state: &mut Self::State, + els: &mut Self::Elements, + ) { + $( + self.$s + .rebuild(cx, &prev.$s, &mut state.$n[$s], &mut state.$s, &mut els.$s); + )* + } + + fn event( + &self, + id_path: &[Id], + state: &mut Self::State, + event: Box, + app_state: &mut T, + ) -> A { + let hd = id_path[0]; + let tl = &id_path[1..]; + $( + if hd == state.$n[$s] { + self.$s.event(tl, &mut state.$s, event, app_state) + } else )* { + panic!("inconsistent id_path") + } + } + } + } +} + +impl_view_tuple!(1; V0; 0); +impl_view_tuple!(2; V0, V1; 0, 1); +impl_view_tuple!(3; V0, V1, V2; 0, 1, 2); +impl_view_tuple!(4; V0, V1, V2, V3; 0, 1, 2, 3); +impl_view_tuple!(5; V0, V1, V2, V3, V4; 0, 1, 2, 3, 4); +impl_view_tuple!(6; V0, V1, V2, V3, V4, V5; 0, 1, 2, 3, 4, 5); +impl_view_tuple!(7; V0, V1, V2, V3, V4, V5, V6; 0, 1, 2, 3, 4, 5, 6); +impl_view_tuple!(8; + V0, V1, V2, V3, V4, V5, V6, V7; + 0, 1, 2, 3, 4, 5, 6, 7 +); +impl_view_tuple!(9; + V0, V1, V2, V3, V4, V5, V6, V7, V8; + 0, 1, 2, 3, 4, 5, 6, 7, 8 +); +impl_view_tuple!(10; + V0, V1, V2, V3, V4, V5, V6, V7, V8, V9; + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 +); diff --git a/idiopath/src/widget.rs b/idiopath/src/widget.rs new file mode 100644 index 0000000000..45a171e010 --- /dev/null +++ b/idiopath/src/widget.rs @@ -0,0 +1,114 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod button; +pub mod column; + +use std::any::Any; +use std::ops::DerefMut; + +use druid_shell::kurbo::{Point, Size}; +use druid_shell::piet::Piet; + +use crate::event::Event; + +/// A basic widget trait. +pub trait Widget { + fn event(&mut self, event: &RawEvent, events: &mut Vec); + + fn layout(&mut self) -> Size; + + fn paint(&mut self, ctx: &mut Piet, pos: Point); +} + +// consider renaming, may get other stuff +#[derive(Default)] +pub struct Geom { + // probably want id? + size: Size, +} + +pub trait AnyWidget: Widget { + fn as_any(&self) -> &dyn Any; + + fn as_any_mut(&mut self) -> &mut dyn Any; +} + +impl AnyWidget for W { + fn as_any(&self) -> &dyn Any { + self + } + + fn as_any_mut(&mut self) -> &mut dyn Any { + self + } +} + +impl Widget for Box { + fn event(&mut self, event: &RawEvent, events: &mut Vec) { + self.deref_mut().event(event, events); + } + + fn layout(&mut self) -> Size { + self.deref_mut().layout() + } + + fn paint(&mut self, ctx: &mut Piet, pos: Point) { + self.deref_mut().paint(ctx, pos); + } +} + +#[derive(Debug)] +pub enum RawEvent { + MouseDown(Point), +} + +pub trait WidgetTuple { + fn length(&self) -> usize; + + // Follows Panoramix; rethink to reduce allocation + // Maybe SmallVec? + fn widgets_mut(&mut self) -> Vec<&mut dyn AnyWidget>; +} + +macro_rules! impl_widget_tuple { + ( $n: tt; $( $WidgetType:ident),* ; $( $index:tt ),* ) => { + impl< $( $WidgetType: AnyWidget ),* > WidgetTuple for ( $( $WidgetType, )* ) { + fn length(&self) -> usize { + $n + } + + fn widgets_mut(&mut self) -> Vec<&mut dyn AnyWidget> { + let mut v: Vec<&mut dyn AnyWidget> = Vec::with_capacity(self.length()); + $( + v.push(&mut self.$index); + )* + v + } + + } + } +} + +impl_widget_tuple!(1; W0; 0); +impl_widget_tuple!(2; W0, W1; 0, 1); +impl_widget_tuple!(3; W0, W1, W2; 0, 1, 2); +impl_widget_tuple!(4; W0, W1, W2, W3; 0, 1, 2, 3); +impl_widget_tuple!(5; W0, W1, W2, W3, W4; 0, 1, 2, 3, 4); +impl_widget_tuple!(6; W0, W1, W2, W3, W4, W5; 0, 1, 2, 3, 4, 5); +impl_widget_tuple!(7; W0, W1, W2, W3, W4, W5, W6; 0, 1, 2, 3, 4, 5, 6); +impl_widget_tuple!(8; + W0, W1, W2, W3, W4, W5, W6, W7; + 0, 1, 2, 3, 4, 5, 6, 7 +); diff --git a/idiopath/src/widget/button.rs b/idiopath/src/widget/button.rs new file mode 100644 index 0000000000..25d3d601da --- /dev/null +++ b/idiopath/src/widget/button.rs @@ -0,0 +1,62 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use druid_shell::{ + kurbo::{Point, Size}, + piet::{Color, Piet, RenderContext, Text, TextLayoutBuilder}, +}; + +use crate::{event::Event, id::IdPath}; + +use super::Widget; + +#[derive(Default)] + +pub struct Button { + id_path: IdPath, + label: String, +} + +impl Button { + pub fn new(id_path: &IdPath, label: String) -> Button { + Button { + id_path: id_path.clone(), + label, + } + } + + pub fn set_label(&mut self, label: String) { + self.label = label; + } +} + +impl Widget for Button { + fn event(&mut self, _event: &super::RawEvent, events: &mut Vec) { + events.push(Event::new(self.id_path.clone(), ())); + } + + fn layout(&mut self) -> Size { + Size::new(100., 20.) + } + + fn paint(&mut self, ctx: &mut Piet, pos: Point) { + let layout = ctx + .text() + .new_text_layout(self.label.clone()) + .text_color(Color::WHITE) + .build() + .unwrap(); + ctx.draw_text(&layout, pos); + } +} diff --git a/idiopath/src/widget/column.rs b/idiopath/src/widget/column.rs new file mode 100644 index 0000000000..258e6f5873 --- /dev/null +++ b/idiopath/src/widget/column.rs @@ -0,0 +1,75 @@ +// Copyright 2022 The Druid Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use druid_shell::{ + kurbo::{Point, Size, Vec2}, + piet::Piet, +}; + +use crate::event::Event; + +use super::{Geom, RawEvent, Widget, WidgetTuple}; + +pub struct Column { + children: W, + geoms: Vec, +} + +impl Column { + pub fn new(children: W) -> Self { + let geoms = (0..children.length()).map(|_| Geom::default()).collect(); + Column { children, geoms } + } + + pub fn children_mut(&mut self) -> &mut W { + &mut self.children + } +} + +impl Widget for Column { + fn event(&mut self, event: &super::RawEvent, events: &mut Vec) { + match event { + RawEvent::MouseDown(p) => { + let mut p = *p; + for (child, geom) in self.children.widgets_mut().into_iter().zip(&self.geoms) { + if p.y < geom.size.height { + let child_event = RawEvent::MouseDown(p); + child.event(&child_event, events); + break; + } + p.y -= geom.size.height; + } + } + } + } + + fn layout(&mut self) -> Size { + let mut size = Size::default(); + for (child, geom) in self.children.widgets_mut().into_iter().zip(&mut self.geoms) { + let child_size = child.layout(); + geom.size = child_size; + size.width = size.width.max(child_size.width); + size.height += child_size.height; + } + size + } + + fn paint(&mut self, ctx: &mut Piet, pos: Point) { + let mut child_pos = pos + Vec2::new(10.0, 0.0); + for (child, geom) in self.children.widgets_mut().into_iter().zip(&self.geoms) { + child.paint(ctx, child_pos); + child_pos.y += geom.size.height; + } + } +}