Created
August 13, 2020 12:48
-
-
Save Gab-km/654d1edfb268b7f459c43103c9d768d4 to your computer and use it in GitHub Desktop.
OrbTkの使い方(修正版)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use orbtk::prelude::*; | |
use std::cell::Cell; | |
// `Rust のマルチプラットフォーム UI ライブラリ OrbTk の使い方 - A Memorandum<https://blog1.mammb.com/entry/2019/12/16/090000>` | |
// で紹介されている、Rust用クロスプラットフォームUIツールキット `OrbTk<https://github.com/redox-os/orbtk>` | |
// が興味深かったので写経したところ、上記記事では OrbTk のバージョンは 0.3.1-alpha1 でしたが、 | |
// 現時点(2020/08/13)では v0.3.1-alpha4 まで上がっており、そのまま書くだけでは動かないところが | |
// あったので、「イベント処理」のサンプルに v0.3.1-alpha4 なりの修正を入れて書き直してみました。 | |
static ID_INPUT: &'static str = "input"; | |
#[derive(Debug, Copy, Clone)] | |
enum Action { | |
Increment, | |
} | |
#[derive(Default, AsAny)] | |
pub struct MainViewState { | |
input: Entity, | |
count: Cell<usize>, | |
action: Cell<Option<Action>>, | |
} | |
impl MainViewState { | |
fn action(&self, action: impl Into<Option<Action>>) { | |
self.action.set(action.into()); | |
} | |
} | |
impl State for MainViewState { | |
fn init(&mut self, _: &mut Registry, ctx: &mut Context) { | |
self.input = ctx | |
.entity_of_child(ID_INPUT) | |
.expect("MainViewState.init: input child could not be found."); | |
} | |
fn update(&mut self, _: &mut Registry, ctx: &mut Context<'_>) { | |
if let Some(action) = self.action.get() { | |
match action { | |
Action::Increment => { | |
let result = self.count.get() + 1; | |
self.count.set(result); | |
ctx.get_widget(self.input) | |
.set("text", String16::from(result.to_string())); | |
} | |
} | |
self.action.set(None); | |
} | |
} | |
} | |
impl Template for MainView { | |
fn template(self, id: Entity, ctx: &mut BuildContext) -> Self { | |
self.name("MainView").child( | |
Stack::new() | |
.child( | |
TextBlock::new() | |
.margin((0.0, 0.0, 0.0, 8.0)) | |
.text("Stack vertical") | |
.id(ID_INPUT) | |
.build(ctx), | |
) | |
.child( | |
Button::new() | |
.text("center") | |
.h_align("center") | |
.on_click(move |states, _| -> bool { | |
state(id, states).action(Action::Increment); | |
true | |
}) | |
.build(ctx), | |
) | |
.build(ctx), | |
) | |
} | |
} | |
widget!(MainView<MainViewState> { | |
counter: usize | |
}); | |
fn main() { | |
Application::new() | |
.window(|ctx| { | |
Window::new() | |
.title("OrbTk - event example") | |
.position((100.0, 100.0)) | |
.size(300.0, 300.0) | |
.child(MainView::new().build(ctx)) | |
.build(ctx) | |
}) | |
.run(); | |
} | |
fn state<'a>(id: Entity, states: &'a mut StatesContext) -> &'a mut MainViewState { | |
states.get_mut(id) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment