Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Xilem Python integration sketch #2185

Draft
wants to merge 10 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[target.x86_64-apple-darwin]
rustflags = [
"-C", "link-arg=-undefined",
"-C", "link-arg=dynamic_lookup",
]

[target.aarch64-apple-darwin]
rustflags = [
"-C", "link-arg=-undefined",
"-C", "link-arg=dynamic_lookup",
]
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ members = [
"druid/examples/web",
"druid/examples/hello_web",
"druid/examples/value_formatting",
"idiopath",
]
default-members = [
"druid",
Expand Down
12 changes: 12 additions & 0 deletions idiopath/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "idiopath"
version = "0.1.0"
authors = ["Raph Levien <raph@google.com>"]
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
pyo3 = { version = "0.16.3", features = ["extension-module"] }
"druid-shell" = { path = "../druid-shell" }
77 changes: 77 additions & 0 deletions idiopath/README.md
Original file line number Diff line number Diff line change
@@ -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<u32, (), Element = impl Widget> {
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<u32, (), Element = impl Widget> {
Button::new(format!("count: {}", count), |data| *data += 1)
}

fn app_logic(data: &mut AppData) -> impl View<AppData, (), Element = impl Widget> {
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<AppData, (), Element = impl Widget> {
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
21 changes: 21 additions & 0 deletions idiopath/run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import foo

class MyApp:
def __init__(self):
self.count = 0

def run(self, data):
return foo.column(
foo.button(f'count: {self.count}', self.handle_click),
foo.button("reset", self.reset)
)

def handle_click(self, data):
self.count += 1

def reset(self, data):
self.count = 0

my_app = MyApp()

foo.ui('this data is threaded down', my_app.run)
91 changes: 91 additions & 0 deletions idiopath/src/app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// 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, piet::Piet};

use crate::{
event::Event,
id::{Id, IdPath},
view::View,
widget::{RawEvent, Widget},
};

pub struct App<T, V: View<T, ()>, F: FnMut(&mut T) -> V>
where
V::Element: Widget,
{
data: T,
app_logic: F,
view: V,
id: Id,
state: V::State,
element: V::Element,
events: Vec<Event>,
id_path: IdPath,
}

impl<T, V: View<T, ()>, F: FnMut(&mut T) -> V> App<T, V, F>
where
V::Element: Widget,
{
pub fn new(mut data: T, mut app_logic: F) -> Self {
let mut id_path = IdPath::default();
let view = (app_logic)(&mut data);
let (id, state, element) = view.build(&mut id_path);
assert!(id_path.is_empty(), "id path imbalance on build");
App {
data,
app_logic,
view,
id,
state,
element,
events: Vec::new(),
id_path,
}
}

pub fn paint(&mut self, piet: &mut Piet) {
self.element.layout();
self.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.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
.event(id_path, &mut self.state, event.body, &mut self.data);
}
// Re-rendering should be more lazy.
let view = (self.app_logic)(&mut self.data);
view.rebuild(
&mut self.id_path,
&self.view,
&mut self.id,
&mut self.state,
&mut self.element,
);
assert!(self.id_path.is_empty(), "id path imbalance on rebuild");
self.view = view;
}
}
22 changes: 22 additions & 0 deletions idiopath/src/event.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// 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<dyn Any>,
}
34 changes: 34 additions & 0 deletions idiopath/src/id.rs
Original file line number Diff line number Diff line change
@@ -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<Id>;

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()
}
}
Loading