Skip to content

Instantly share code, notes, and snippets.

@samsartor
Last active June 11, 2017 01:19
Show Gist options
  • Save samsartor/a553e1b65de02f76c5748dc13eebbd74 to your computer and use it in GitHub Desktop.
Save samsartor/a553e1b65de02f76c5748dc13eebbd74 to your computer and use it in GitHub Desktop.
A theoretical boxflight double-button example
pub fn main() {
let mut ctx = Context::new();
let mut rng = thread_rng();
ctx.add_element(ButtonsModel {
color_a: random_color(&mut rng),
color_b: random_color(&mut rng),
});
ctx.launch();
}
enum ButtonsMessage {
ChangeColor {
button: usize,
to: [f32; 3],
ids: IdSource::new(),
},
NoOp,
}
// so we don't have to ButtonsMessage::ChangeColor { ... }
use ButtonsMessage::*;
impl Message for ButtonsMessage {
fn noop() -> Self { NoOp }
}
// our model
struct ButtonsModel {
color_a: [f32; 3],
color_b: [f32; 3],
ids: IdSource,
}
// generate a random color
fn random_color<R: Rng>(&mut rng) -> [f32; 3] {
[rng.next_f32(), rng.next_f32(), rng.next_f32()]
}
// create a button of a given color `color`, that changes the color of #`other`
fn make_button(other: usize, color: [f32; 3], id: ElementId) -> objects::Button {
let rng = thread_rng(); // new rng
objects::Button { // make button view
// allows for in-progress animations to carry over
element_id: id,
// send change color event
on_press: ChangeColor { button: other, to: random_color(&mut rng) },
style: styles::NiceButton { // our own styler, from some other module
primary_color: color,
Default::default(),
},
Default::default() // all other events/params empty
}
}
impl Model<ButtonsMessage> for ButtonsModel {
// on message
fn message(&mut self, event: ButtonsMessage, cont: Controller) {
match event {
ChangeColor { button: 0, to } => { self.color_a = to; cont.invalidate(); },
ChangeColor { button: 1, to } => { self.color_b = to; cont.invalidate(); },
_ => (),
}
}
// builds the view
fn view(&self) -> View {
let mut conn = layouts::Connected::new();
// the root element is a button that changes the color of #1
let root = conn.root(make_button(1, self.color_a, self.ids.by_int(0)));
// 0.2cm below that is a button that changes the color of #0
conn.below(root, make_button(0, self.color_b, self.ids.by_hash("another way to id")), 0.2);
// export the item
conn.build()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment