Skip to content

Instantly share code, notes, and snippets.

@ratmice
Last active January 7, 2022 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ratmice/4757246e77a42c3228474834dca043be to your computer and use it in GitHub Desktop.
Save ratmice/4757246e77a42c3228474834dca043be to your computer and use it in GitHub Desktop.
map in a druid list widget
// Requires druid features = ["im"]
// And I *think* druid from git.
use im;
use druid::{self, lens, Data,
widget::{Flex, List, Scroll, Widget, WidgetExt, Slider, ListIter}};
#[derive(Clone, Data, Debug)]
struct AppState {
state: im::HashMap<String, f64>,
}
fn subwidget() -> impl Widget<f64> {
Slider::new().with_range(0.0, 11.0).with_step(1.0)
}
impl ListIter<f64> for AppState
{
fn for_each(&self, mut cb: impl FnMut(&f64, usize)) {
for (i, (k, v)) in self.state.iter().enumerate() {
let (_, v) = (k.to_owned(), v.to_owned());
cb(&v, i);
}
}
fn for_each_mut(&mut self, mut cb: impl FnMut(&mut f64, usize)) {
let state = &mut self.state;
for (i, (_k, v)) in state.iter_mut().enumerate() {
let mut ret = v.clone();
cb(&mut ret, i);
if !v.same(&ret) {
*v = ret;
}
}
}
fn data_len(&self) -> usize {
self.state.len()
}
}
fn top_level_widget() -> impl Widget<AppState> {
let mut row = Flex::row();
let list = List::new(move || subwidget());
row.add_flex_child(
Scroll::new(list).vertical().lens(lens::Identity),
1.0
);
Flex::column().with_child(row)
}
fn main() {
let mut state = im::HashMap::new();
state.insert("foo".to_string(), 8.0);
state.insert("bar".to_string(), 1.0);
let window = druid::WindowDesc::new(top_level_widget())
.title(druid::LocalizedString::new("hashmap appstate").with_placeholder("hashmap appstate"));
let launcher = druid::AppLauncher::with_window(window);
launcher.launch(AppState { state }).expect("launch failed");
println!("Hello, world!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment