1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
// 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 in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! Combobox
use super::{menu::MenuEntry, Column, Mark, StringLabel};
use kas::event::{Command, FocusSource, ScrollDelta};
use kas::prelude::*;
use kas::theme::{MarkStyle, TextClass};
use kas::Popup;
use std::fmt::Debug;
#[derive(Clone, Debug)]
struct IndexMsg(usize);
impl_scope! {
/// A pop-up multiple choice menu
///
/// # Messages
///
/// A combobox presents a menu with a fixed set of choices when clicked.
/// Each choice has an associated value of type `V`.
///
/// If no selection handler exists, then the choice's message is emitted
/// when selected. If a handler is specified via [`Self::with`] or
/// [`Self::with_msg`] then this message is passed to the handler and not emitted.
#[widget {
layout = button! 'frame(row! [self.label, self.mark]);
navigable = true;
hover_highlight = true;
}]
pub struct ComboBox<A, V: Clone + Debug + Eq + 'static> {
core: widget_core!(),
#[widget(&())]
label: StringLabel,
#[widget(&())]
mark: Mark,
#[widget(&())]
popup: Popup<Column<MenuEntry<V>>>,
active: usize,
opening: bool,
state_fn: Box<dyn Fn(&ConfigCx, &A) -> V>,
on_select: Option<Box<dyn Fn(&mut EventCx, V)>>,
}
impl Layout for Self {
fn nav_next(&self, _: bool, _: Option<usize>) -> Option<usize> {
// We have no child within our rect
None
}
}
impl Events for Self {
type Data = A;
fn update(&mut self, cx: &mut ConfigCx, data: &A) {
let msg = (self.state_fn)(cx, data);
if let Some(index) = self.popup
.iter()
.enumerate()
.find_map(|(i, w)| (*w == msg).then_some(i))
{
if index != self.active {
self.active = index;
cx.redraw(&self);
}
} else {
log::warn!("ComboBox::update: unknown entry {msg:?}");
};
}
fn handle_event(&mut self, cx: &mut EventCx, _: &A, event: Event) -> IsUsed {
let open_popup = |s: &mut Self, cx: &mut EventCx, source: FocusSource| {
if s.popup.open(cx, &(), s.id()) {
if let Some(w) = s.popup.get_child(s.active) {
cx.next_nav_focus(w.id(), false, source);
}
}
};
match event {
Event::Command(cmd, code) => {
if self.popup.is_open() {
let next = |cx: &mut EventCx, clr, rev| {
if clr {
cx.clear_nav_focus();
}
cx.next_nav_focus(None, rev, FocusSource::Key);
};
match cmd {
cmd if cmd.is_activate() => {
self.popup.close(cx);
if let Some(code) = code {
cx.depress_with_key(self.id(), code);
}
}
Command::Up => next(cx, false, true),
Command::Down => next(cx, false, false),
Command::Home => next(cx, true, false),
Command::End => next(cx, true, true),
_ => return Unused,
}
} else {
let last = self.len().saturating_sub(1);
let action = match cmd {
cmd if cmd.is_activate() => {
open_popup(self, cx, FocusSource::Key);
if let Some(code) = code {
cx.depress_with_key(self.id(), code);
}
Action::empty()
}
Command::Up => self.set_active(self.active.saturating_sub(1)),
Command::Down => self.set_active((self.active + 1).min(last)),
Command::Home => self.set_active(0),
Command::End => self.set_active(last),
_ => return Unused,
};
cx.action(self, action);
}
Used
}
Event::Scroll(ScrollDelta::LineDelta(_, y)) if !self.popup.is_open() => {
if y > 0.0 {
let action = self.set_active(self.active.saturating_sub(1));
cx.action(&self, action);
} else if y < 0.0 {
let last = self.len().saturating_sub(1);
let action = self.set_active((self.active + 1).min(last));
cx.action(&self, action);
}
Used
}
Event::PressStart { press } => {
if press.id.as_ref().map(|id| self.is_ancestor_of(id)).unwrap_or(false) {
if press.is_primary() {
press.grab(self.id()).with_cx(cx);
cx.set_grab_depress(*press, press.id);
self.opening = !self.popup.is_open();
}
Used
} else {
Unused
}
}
Event::CursorMove { press } | Event::PressMove { press, .. } => {
open_popup(self, cx, FocusSource::Pointer);
let cond = self.popup.rect().contains(press.coord);
let target = if cond { press.id } else { None };
cx.set_grab_depress(press.source, target.clone());
if let Some(id) = target {
cx.set_nav_focus(id, FocusSource::Pointer);
}
Used
}
Event::PressEnd { press, success } if success => {
if let Some(id) = press.id {
if self.eq_id(&id) {
if self.opening {
open_popup(self, cx, FocusSource::Pointer);
return Used;
}
} else if self.popup.is_open() && self.popup.is_ancestor_of(&id) {
cx.send_command(id, Command::Activate);
return Used;
}
}
self.popup.close(cx);
Used
}
_ => Unused,
}
}
fn handle_messages(&mut self, cx: &mut EventCx, _: &Self::Data) {
if let Some(IndexMsg(index)) = cx.try_pop() {
let action = self.set_active(index);
cx.action(&self, action);
self.popup.close(cx);
if let Some(ref f) = self.on_select {
if let Some(msg) = cx.try_pop() {
(f)(cx, msg);
}
}
}
}
}
}
impl<A, V: Clone + Debug + Eq + 'static> ComboBox<A, V> {
/// Construct a combobox
///
/// Constructs a combobox with labels derived from an iterator over string
/// types. For example:
/// ```
/// # use kas_widgets::ComboBox;
/// #[derive(Clone, Copy, Debug, PartialEq, Eq)]
/// enum Select { A, B, C }
///
/// let combobox = ComboBox::new(
/// [("A", Select::A), ("B", Select::B), ("C", Select::C)],
/// |_, selection| *selection,
/// );
/// ```
///
/// The closure `state_fn` selects the active entry from input data.
pub fn new<T, I>(iter: I, state_fn: impl Fn(&ConfigCx, &A) -> V + 'static) -> Self
where
T: Into<AccessString>,
I: IntoIterator<Item = (T, V)>,
{
let entries = iter
.into_iter()
.map(|(label, msg)| MenuEntry::new_msg(label, msg))
.collect();
Self::new_vec(entries, state_fn)
}
/// Construct a combobox with the given menu entries
///
/// A combobox presents a menu with a fixed set of choices when clicked.
///
/// The closure `state_fn` selects the active entry from input data.
pub fn new_vec(
entries: Vec<MenuEntry<V>>,
state_fn: impl Fn(&ConfigCx, &A) -> V + 'static,
) -> Self {
let label = entries.first().map(|entry| entry.get_string());
let label = StringLabel::new(label.unwrap_or_default()).with_class(TextClass::Button);
ComboBox {
core: Default::default(),
label,
mark: Mark::new(MarkStyle::Point(Direction::Down)),
popup: Popup::new(
Column::new(entries).on_messages(|cx, _, index| {
cx.push(IndexMsg(index));
false
}),
Direction::Down,
),
active: 0,
opening: false,
state_fn: Box::new(state_fn),
on_select: None,
}
}
/// Send the message generated by `f` on selection
#[must_use]
pub fn with_msg<M: Debug + 'static>(self, f: impl Fn(V) -> M + 'static) -> Self {
self.with(move |cx, m| cx.push(f(m)))
}
/// Call the handler `f` on selection
///
/// On selection of a new choice the closure `f` is called with the choice's
/// message.
#[must_use]
pub fn with<F>(mut self, f: F) -> ComboBox<A, V>
where
F: Fn(&mut EventCx, V) + 'static,
{
self.on_select = Some(Box::new(f));
self
}
/// Construct a combobox which sends a message on selection
///
/// See [`Self::new`] and [`Self::with_msg`] for documentation.
pub fn new_msg<T, I, M>(
iter: I,
state_fn: impl Fn(&ConfigCx, &A) -> V + 'static,
msg_fn: impl Fn(V) -> M + 'static,
) -> Self
where
T: Into<AccessString>,
I: IntoIterator<Item = (T, V)>,
M: Debug + 'static,
{
Self::new(iter, state_fn).with_msg(msg_fn)
}
}
impl<A, V: Clone + Debug + Eq + 'static> ComboBox<A, V> {
/// Get the index of the active choice
///
/// This index is normally less than the number of choices (`self.len()`),
/// but may not be if set programmatically or there are no choices.
#[inline]
pub fn active(&self) -> usize {
self.active
}
/// Set the active choice (inline style)
#[inline]
pub fn with_active(mut self, index: usize) -> Self {
let _ = self.set_active(index);
self
}
/// Set the active choice
pub fn set_active(&mut self, index: usize) -> Action {
if self.active != index && index < self.popup.len() {
self.active = index;
let string = if index < self.len() {
self.popup[index].get_string()
} else {
"".to_string()
};
self.label.set_string(string)
} else {
Action::empty()
}
}
/// Get the number of entries
#[inline]
pub fn len(&self) -> usize {
self.popup.len()
}
/// True if the box contains no entries
#[inline]
pub fn is_empty(&self) -> bool {
self.popup.is_empty()
}
/// Remove all choices
pub fn clear(&mut self) {
self.popup.clear()
}
/// Add a choice to the combobox, in last position
///
/// Returns the index of the new choice
//
// TODO(opt): these methods cause full-window resize. They don't need to
// resize at all if the menu is closed!
pub fn push<T: Into<AccessString>>(&mut self, cx: &mut ConfigCx, label: T, msg: V) -> usize {
let column = &mut self.popup;
column.push(cx, &(), MenuEntry::new_msg(label, msg))
}
/// Pops the last choice from the combobox
pub fn pop(&mut self, cx: &mut EventState) -> Option<()> {
self.popup.pop(cx).map(|_| ())
}
/// Add a choice at position `index`
///
/// Panics if `index > len`.
pub fn insert<T: Into<AccessString>>(
&mut self,
cx: &mut ConfigCx,
index: usize,
label: T,
msg: V,
) {
let column = &mut self.popup;
column.insert(cx, &(), index, MenuEntry::new_msg(label, msg));
}
/// Removes the choice at position `index`
///
/// Panics if `index` is out of bounds.
pub fn remove(&mut self, cx: &mut EventState, index: usize) {
self.popup.remove(cx, index);
}
/// Replace the choice at `index`
///
/// Panics if `index` is out of bounds.
pub fn replace<T: Into<AccessString>>(
&mut self,
cx: &mut ConfigCx,
index: usize,
label: T,
msg: V,
) {
self.popup
.replace(cx, &(), index, MenuEntry::new_msg(label, msg));
}
}