Struct kas_core::event::EventState
source · pub struct EventState { /* private fields */ }
Expand description
Event manager state
This struct encapsulates window-specific event-handling state and handling.
Most operations are only available via a EventMgr
handle, though some
are available on this struct.
Besides event handling, this struct also configures widgets.
Some methods are intended only for usage by KAS shells and are hidden from
documentation unless the internal_doc
feature is enabled. Only winit
events are currently supported; changes will be required to generalise this.
Implementations§
source§impl EventState
impl EventState
Public API
sourcepub fn window_has_focus(&self) -> bool
pub fn window_has_focus(&self) -> bool
True when the window has focus
sourcepub fn show_accel_labels(&self) -> bool
pub fn show_accel_labels(&self) -> bool
True when accelerator key labels should be shown
(True when Alt is held and no widget has character focus.)
This is a fast check.
sourcepub fn has_char_focus(&self, w_id: &WidgetId) -> (bool, bool)
pub fn has_char_focus(&self, w_id: &WidgetId) -> (bool, bool)
Get whether this widget has (char_focus, sel_focus)
char_focus
: implies this widget receives keyboard inputsel_focus
: implies this widget is allowed to select things
Note that char_focus
implies sel_focus
.
Get whether this widget has keyboard navigation focus
sourcepub fn is_hovered(&self, w_id: &WidgetId) -> bool
pub fn is_hovered(&self, w_id: &WidgetId) -> bool
Get whether the widget is under the mouse cursor
sourcepub fn is_depressed(&self, w_id: &WidgetId) -> bool
pub fn is_depressed(&self, w_id: &WidgetId) -> bool
Check whether the given widget is visually depressed
sourcepub fn is_disabled(&self, w_id: &WidgetId) -> bool
pub fn is_disabled(&self, w_id: &WidgetId) -> bool
Check whether a widget is disabled
A widget is disabled if any ancestor is.
Examples found in repository?
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
fn nav(
mgr: &mut ConfigMgr,
widget: &mut dyn Widget,
focus: Option<&WidgetId>,
rev: bool,
) -> Option<WidgetId> {
if mgr.ev_state().is_disabled(widget.id_ref()) {
return None;
}
let mut child = focus.and_then(|id| widget.find_child_index(id));
if !rev {
if let Some(index) = child {
if let Some(id) = widget
.get_child_mut(index)
.and_then(|w| nav(mgr, w, focus, rev))
{
return Some(id);
}
} else if !widget.eq_id(focus) && widget.navigable() {
return Some(widget.id());
}
loop {
if let Some(index) = widget.nav_next(mgr, rev, child) {
if let Some(id) = widget
.get_child_mut(index)
.and_then(|w| nav(mgr, w, focus, rev))
{
return Some(id);
}
child = Some(index);
} else {
return None;
}
}
} else {
if let Some(index) = child {
if let Some(id) = widget
.get_child_mut(index)
.and_then(|w| nav(mgr, w, focus, rev))
{
return Some(id);
}
}
loop {
if let Some(index) = widget.nav_next(mgr, rev, child) {
if let Some(id) = widget
.get_child_mut(index)
.and_then(|w| nav(mgr, w, focus, rev))
{
return Some(id);
}
child = Some(index);
} else {
return if !widget.eq_id(focus) && widget.navigable() {
Some(widget.id())
} else {
None
};
}
}
}
}
sourcepub fn modifiers(&self) -> ModifiersState
pub fn modifiers(&self) -> ModifiersState
Get the current modifier state
Examples found in repository?
131 132 133 134 135 136 137 138 139 140 141 142
pub fn config_enable_pan(&self, source: PressSource) -> bool {
source.is_touch()
|| source.is_primary() && self.config.mouse_pan().is_enabled_with(self.modifiers())
}
/// Is mouse text panning enabled?
#[inline]
pub fn config_enable_mouse_text_pan(&self) -> bool {
self.config
.mouse_text_pan()
.is_enabled_with(self.modifiers())
}
More examples
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
pub fn handle(&mut self, mgr: &mut EventMgr, w_id: WidgetId, event: Event) -> TextInputAction {
use TextInputAction as Action;
match event {
Event::PressStart { source, coord, .. } if source.is_primary() => {
let (action, icon) = match source {
PressSource::Touch(touch_id) => {
self.touch_phase = TouchPhase::Start(touch_id, coord);
let delay = mgr.config().touch_select_delay();
mgr.request_update(w_id.clone(), PAYLOAD_SELECT, delay, false);
(Action::Focus, None)
}
PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan() => {
(Action::Focus, Some(CursorIcon::Grabbing))
}
PressSource::Mouse(_, repeats) => (
Action::Cursor(coord, true, !mgr.modifiers().shift(), repeats),
None,
),
};
mgr.grab_press_unique(w_id, source, coord, icon);
action
}
Event::PressMove {
source,
coord,
delta,
..
} => {
self.glide.move_delta(delta);
match source {
PressSource::Touch(touch_id) => match self.touch_phase {
TouchPhase::Start(id, start_coord) if id == touch_id => {
let delta = coord - start_coord;
if mgr.config_test_pan_thresh(delta) {
self.touch_phase = TouchPhase::Pan(id);
Action::Pan(delta)
} else {
Action::None
}
}
TouchPhase::Pan(id) if id == touch_id => Action::Pan(delta),
_ => Action::Cursor(coord, false, false, 1),
},
PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan() => {
Action::Pan(delta)
}
PressSource::Mouse(_, repeats) => Action::Cursor(coord, false, false, repeats),
}
}
Event::PressEnd { source, .. } => {
if self.glide.opt_start(mgr.config().scroll_flick_timeout())
&& (matches!(source, PressSource::Touch(id) if self.touch_phase == TouchPhase::Pan(id))
|| matches!(source, PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan()))
{
self.touch_phase = TouchPhase::None;
mgr.request_update(w_id, PAYLOAD_GLIDE, Duration::new(0, 0), true);
}
Action::None
}
Event::TimerUpdate(pl) if pl == PAYLOAD_SELECT => {
match self.touch_phase {
TouchPhase::Start(touch_id, coord) => {
self.touch_phase = TouchPhase::Cursor(touch_id);
Action::Cursor(coord, true, !mgr.modifiers().shift(), 1)
}
// Note: if the TimerUpdate were from another requester it
// should technically be Unused, but it doesn't matter
// so long as other consumers match this first.
_ => Action::None,
}
}
Event::TimerUpdate(pl) if pl == PAYLOAD_GLIDE => {
// Momentum/glide scrolling: update per arbitrary step time until movment stops.
let decay = mgr.config().scroll_flick_decay();
if let Some(delta) = self.glide.step(decay) {
let dur = Duration::from_millis(GLIDE_POLL_MS);
mgr.request_update(w_id, PAYLOAD_GLIDE, dur, true);
Action::Pan(delta)
} else {
Action::None
}
}
_ => Action::Unused,
}
}
sourcepub fn config(&self) -> &WindowConfig
pub fn config(&self) -> &WindowConfig
Access event-handling configuration
Examples found in repository?
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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
pub fn scroll_by_event(
&mut self,
mgr: &mut EventMgr,
event: Event,
id: WidgetId,
window_rect: Rect,
) -> (bool, Response) {
let mut moved = false;
match event {
Event::Command(cmd) => {
let offset = match cmd {
Command::Home => Offset::ZERO,
Command::End => self.max_offset,
cmd => {
let delta = match cmd {
Command::Left => LineDelta(-1.0, 0.0),
Command::Right => LineDelta(1.0, 0.0),
Command::Up => LineDelta(0.0, 1.0),
Command::Down => LineDelta(0.0, -1.0),
Command::PageUp => PixelDelta(Offset(0, window_rect.size.1 / 2)),
Command::PageDown => PixelDelta(Offset(0, -(window_rect.size.1 / 2))),
_ => return (false, Response::Unused),
};
let delta = match delta {
LineDelta(x, y) => mgr.config().scroll_distance((x, y)),
PixelDelta(d) => d,
};
self.offset - delta
}
};
let action = self.set_offset(offset);
if !action.is_empty() {
moved = true;
*mgr |= action;
}
mgr.set_scroll(Scroll::Rect(window_rect));
}
Event::Scroll(delta) => {
let delta = match delta {
LineDelta(x, y) => mgr.config().scroll_distance((x, y)),
PixelDelta(d) => d,
};
moved = self.scroll_by_delta(mgr, delta);
}
Event::PressStart { source, coord, .. }
if self.max_offset != Offset::ZERO && mgr.config_enable_pan(source) =>
{
let icon = Some(CursorIcon::Grabbing);
mgr.grab_press_unique(id, source, coord, icon);
}
Event::PressMove { delta, .. } => {
self.glide.move_delta(delta);
moved = self.scroll_by_delta(mgr, delta);
}
Event::PressEnd { .. } => {
if self.glide.opt_start(mgr.config().scroll_flick_timeout()) {
mgr.request_update(id, PAYLOAD_GLIDE, Duration::new(0, 0), true);
}
}
Event::TimerUpdate(pl) if pl == PAYLOAD_GLIDE => {
// Momentum/glide scrolling: update per arbitrary step time until movment stops.
let decay = mgr.config().scroll_flick_decay();
if let Some(delta) = self.glide.step(decay) {
let action = self.set_offset(self.offset - delta);
if !action.is_empty() {
*mgr |= action;
moved = true;
}
if delta == Offset::ZERO || !action.is_empty() {
// Note: when FPS > pixels/sec, delta may be zero while
// still scrolling. Glide returns None when we're done,
// but we're also done if unable to scroll further.
let dur = Duration::from_millis(GLIDE_POLL_MS);
mgr.request_update(id, PAYLOAD_GLIDE, dur, true);
mgr.set_scroll(Scroll::Scrolled);
}
}
}
_ => return (false, Response::Unused),
}
(moved, Response::Used)
}
}
#[impl_default(TouchPhase::None)]
#[derive(Clone, Debug, PartialEq)]
enum TouchPhase {
None,
Start(u64, Coord), // id, coord
Pan(u64), // id
Cursor(u64), // id
}
/// Handles text selection and panning from mouse and touch events
#[derive(Clone, Debug, Default)]
pub struct TextInput {
touch_phase: TouchPhase,
glide: Glide,
}
/// Result of [`TextInput::handle`]
pub enum TextInputAction {
/// No action (event consumed)
None,
/// Event not used
Unused,
/// Pan text using the given `delta`
Pan(Offset),
/// Keyboard focus should be requested (if not already active)
///
/// This is also the case for variant `Cursor(_, true, _, _)` (i.e. if
/// `anchor == true`).
Focus,
/// Update cursor and/or selection: `(coord, anchor, clear, repeats)`
///
/// The cursor position should be moved to `coord`.
///
/// If `anchor`, the anchor position (used for word and line selection mode)
/// should be set to the new cursor position.
///
/// If `clear`, the selection should be cleared (move selection position to
/// edit position).
///
/// If `repeats > 1`, [`SelectionHelper::expand`] should be called with
/// this parameter to enable word/line selection mode.
Cursor(Coord, bool, bool, u32),
}
impl TextInput {
/// Handle input events
///
/// Consumes the following events: `PressStart`, `PressMove`, `PressEnd`,
/// `TimerUpdate(pl)` where `pl == 1<<60 || pl == (1<<60)+1`.
/// May request press grabs and timer updates.
///
/// Implements scrolling and text selection behaviour, excluding handling of
/// [`Event::Scroll`].
pub fn handle(&mut self, mgr: &mut EventMgr, w_id: WidgetId, event: Event) -> TextInputAction {
use TextInputAction as Action;
match event {
Event::PressStart { source, coord, .. } if source.is_primary() => {
let (action, icon) = match source {
PressSource::Touch(touch_id) => {
self.touch_phase = TouchPhase::Start(touch_id, coord);
let delay = mgr.config().touch_select_delay();
mgr.request_update(w_id.clone(), PAYLOAD_SELECT, delay, false);
(Action::Focus, None)
}
PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan() => {
(Action::Focus, Some(CursorIcon::Grabbing))
}
PressSource::Mouse(_, repeats) => (
Action::Cursor(coord, true, !mgr.modifiers().shift(), repeats),
None,
),
};
mgr.grab_press_unique(w_id, source, coord, icon);
action
}
Event::PressMove {
source,
coord,
delta,
..
} => {
self.glide.move_delta(delta);
match source {
PressSource::Touch(touch_id) => match self.touch_phase {
TouchPhase::Start(id, start_coord) if id == touch_id => {
let delta = coord - start_coord;
if mgr.config_test_pan_thresh(delta) {
self.touch_phase = TouchPhase::Pan(id);
Action::Pan(delta)
} else {
Action::None
}
}
TouchPhase::Pan(id) if id == touch_id => Action::Pan(delta),
_ => Action::Cursor(coord, false, false, 1),
},
PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan() => {
Action::Pan(delta)
}
PressSource::Mouse(_, repeats) => Action::Cursor(coord, false, false, repeats),
}
}
Event::PressEnd { source, .. } => {
if self.glide.opt_start(mgr.config().scroll_flick_timeout())
&& (matches!(source, PressSource::Touch(id) if self.touch_phase == TouchPhase::Pan(id))
|| matches!(source, PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan()))
{
self.touch_phase = TouchPhase::None;
mgr.request_update(w_id, PAYLOAD_GLIDE, Duration::new(0, 0), true);
}
Action::None
}
Event::TimerUpdate(pl) if pl == PAYLOAD_SELECT => {
match self.touch_phase {
TouchPhase::Start(touch_id, coord) => {
self.touch_phase = TouchPhase::Cursor(touch_id);
Action::Cursor(coord, true, !mgr.modifiers().shift(), 1)
}
// Note: if the TimerUpdate were from another requester it
// should technically be Unused, but it doesn't matter
// so long as other consumers match this first.
_ => Action::None,
}
}
Event::TimerUpdate(pl) if pl == PAYLOAD_GLIDE => {
// Momentum/glide scrolling: update per arbitrary step time until movment stops.
let decay = mgr.config().scroll_flick_decay();
if let Some(delta) = self.glide.step(decay) {
let dur = Duration::from_millis(GLIDE_POLL_MS);
mgr.request_update(w_id, PAYLOAD_GLIDE, dur, true);
Action::Pan(delta)
} else {
Action::None
}
}
_ => Action::Unused,
}
}
sourcepub fn config_enable_pan(&self, source: PressSource) -> bool
pub fn config_enable_pan(&self, source: PressSource) -> bool
Is mouse panning enabled?
Examples found in repository?
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
pub fn scroll_by_event(
&mut self,
mgr: &mut EventMgr,
event: Event,
id: WidgetId,
window_rect: Rect,
) -> (bool, Response) {
let mut moved = false;
match event {
Event::Command(cmd) => {
let offset = match cmd {
Command::Home => Offset::ZERO,
Command::End => self.max_offset,
cmd => {
let delta = match cmd {
Command::Left => LineDelta(-1.0, 0.0),
Command::Right => LineDelta(1.0, 0.0),
Command::Up => LineDelta(0.0, 1.0),
Command::Down => LineDelta(0.0, -1.0),
Command::PageUp => PixelDelta(Offset(0, window_rect.size.1 / 2)),
Command::PageDown => PixelDelta(Offset(0, -(window_rect.size.1 / 2))),
_ => return (false, Response::Unused),
};
let delta = match delta {
LineDelta(x, y) => mgr.config().scroll_distance((x, y)),
PixelDelta(d) => d,
};
self.offset - delta
}
};
let action = self.set_offset(offset);
if !action.is_empty() {
moved = true;
*mgr |= action;
}
mgr.set_scroll(Scroll::Rect(window_rect));
}
Event::Scroll(delta) => {
let delta = match delta {
LineDelta(x, y) => mgr.config().scroll_distance((x, y)),
PixelDelta(d) => d,
};
moved = self.scroll_by_delta(mgr, delta);
}
Event::PressStart { source, coord, .. }
if self.max_offset != Offset::ZERO && mgr.config_enable_pan(source) =>
{
let icon = Some(CursorIcon::Grabbing);
mgr.grab_press_unique(id, source, coord, icon);
}
Event::PressMove { delta, .. } => {
self.glide.move_delta(delta);
moved = self.scroll_by_delta(mgr, delta);
}
Event::PressEnd { .. } => {
if self.glide.opt_start(mgr.config().scroll_flick_timeout()) {
mgr.request_update(id, PAYLOAD_GLIDE, Duration::new(0, 0), true);
}
}
Event::TimerUpdate(pl) if pl == PAYLOAD_GLIDE => {
// Momentum/glide scrolling: update per arbitrary step time until movment stops.
let decay = mgr.config().scroll_flick_decay();
if let Some(delta) = self.glide.step(decay) {
let action = self.set_offset(self.offset - delta);
if !action.is_empty() {
*mgr |= action;
moved = true;
}
if delta == Offset::ZERO || !action.is_empty() {
// Note: when FPS > pixels/sec, delta may be zero while
// still scrolling. Glide returns None when we're done,
// but we're also done if unable to scroll further.
let dur = Duration::from_millis(GLIDE_POLL_MS);
mgr.request_update(id, PAYLOAD_GLIDE, dur, true);
mgr.set_scroll(Scroll::Scrolled);
}
}
}
_ => return (false, Response::Unused),
}
(moved, Response::Used)
}
sourcepub fn config_enable_mouse_text_pan(&self) -> bool
pub fn config_enable_mouse_text_pan(&self) -> bool
Is mouse text panning enabled?
Examples found in repository?
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
pub fn handle(&mut self, mgr: &mut EventMgr, w_id: WidgetId, event: Event) -> TextInputAction {
use TextInputAction as Action;
match event {
Event::PressStart { source, coord, .. } if source.is_primary() => {
let (action, icon) = match source {
PressSource::Touch(touch_id) => {
self.touch_phase = TouchPhase::Start(touch_id, coord);
let delay = mgr.config().touch_select_delay();
mgr.request_update(w_id.clone(), PAYLOAD_SELECT, delay, false);
(Action::Focus, None)
}
PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan() => {
(Action::Focus, Some(CursorIcon::Grabbing))
}
PressSource::Mouse(_, repeats) => (
Action::Cursor(coord, true, !mgr.modifiers().shift(), repeats),
None,
),
};
mgr.grab_press_unique(w_id, source, coord, icon);
action
}
Event::PressMove {
source,
coord,
delta,
..
} => {
self.glide.move_delta(delta);
match source {
PressSource::Touch(touch_id) => match self.touch_phase {
TouchPhase::Start(id, start_coord) if id == touch_id => {
let delta = coord - start_coord;
if mgr.config_test_pan_thresh(delta) {
self.touch_phase = TouchPhase::Pan(id);
Action::Pan(delta)
} else {
Action::None
}
}
TouchPhase::Pan(id) if id == touch_id => Action::Pan(delta),
_ => Action::Cursor(coord, false, false, 1),
},
PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan() => {
Action::Pan(delta)
}
PressSource::Mouse(_, repeats) => Action::Cursor(coord, false, false, repeats),
}
}
Event::PressEnd { source, .. } => {
if self.glide.opt_start(mgr.config().scroll_flick_timeout())
&& (matches!(source, PressSource::Touch(id) if self.touch_phase == TouchPhase::Pan(id))
|| matches!(source, PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan()))
{
self.touch_phase = TouchPhase::None;
mgr.request_update(w_id, PAYLOAD_GLIDE, Duration::new(0, 0), true);
}
Action::None
}
Event::TimerUpdate(pl) if pl == PAYLOAD_SELECT => {
match self.touch_phase {
TouchPhase::Start(touch_id, coord) => {
self.touch_phase = TouchPhase::Cursor(touch_id);
Action::Cursor(coord, true, !mgr.modifiers().shift(), 1)
}
// Note: if the TimerUpdate were from another requester it
// should technically be Unused, but it doesn't matter
// so long as other consumers match this first.
_ => Action::None,
}
}
Event::TimerUpdate(pl) if pl == PAYLOAD_GLIDE => {
// Momentum/glide scrolling: update per arbitrary step time until movment stops.
let decay = mgr.config().scroll_flick_decay();
if let Some(delta) = self.glide.step(decay) {
let dur = Duration::from_millis(GLIDE_POLL_MS);
mgr.request_update(w_id, PAYLOAD_GLIDE, dur, true);
Action::Pan(delta)
} else {
Action::None
}
}
_ => Action::Unused,
}
}
sourcepub fn config_test_pan_thresh(&self, dist: Offset) -> bool
pub fn config_test_pan_thresh(&self, dist: Offset) -> bool
Test pan threshold against config, adjusted for scale factor
Returns true when dist
is large enough to switch to pan mode.
Examples found in repository?
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
pub fn handle(&mut self, mgr: &mut EventMgr, w_id: WidgetId, event: Event) -> TextInputAction {
use TextInputAction as Action;
match event {
Event::PressStart { source, coord, .. } if source.is_primary() => {
let (action, icon) = match source {
PressSource::Touch(touch_id) => {
self.touch_phase = TouchPhase::Start(touch_id, coord);
let delay = mgr.config().touch_select_delay();
mgr.request_update(w_id.clone(), PAYLOAD_SELECT, delay, false);
(Action::Focus, None)
}
PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan() => {
(Action::Focus, Some(CursorIcon::Grabbing))
}
PressSource::Mouse(_, repeats) => (
Action::Cursor(coord, true, !mgr.modifiers().shift(), repeats),
None,
),
};
mgr.grab_press_unique(w_id, source, coord, icon);
action
}
Event::PressMove {
source,
coord,
delta,
..
} => {
self.glide.move_delta(delta);
match source {
PressSource::Touch(touch_id) => match self.touch_phase {
TouchPhase::Start(id, start_coord) if id == touch_id => {
let delta = coord - start_coord;
if mgr.config_test_pan_thresh(delta) {
self.touch_phase = TouchPhase::Pan(id);
Action::Pan(delta)
} else {
Action::None
}
}
TouchPhase::Pan(id) if id == touch_id => Action::Pan(delta),
_ => Action::Cursor(coord, false, false, 1),
},
PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan() => {
Action::Pan(delta)
}
PressSource::Mouse(_, repeats) => Action::Cursor(coord, false, false, repeats),
}
}
Event::PressEnd { source, .. } => {
if self.glide.opt_start(mgr.config().scroll_flick_timeout())
&& (matches!(source, PressSource::Touch(id) if self.touch_phase == TouchPhase::Pan(id))
|| matches!(source, PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan()))
{
self.touch_phase = TouchPhase::None;
mgr.request_update(w_id, PAYLOAD_GLIDE, Duration::new(0, 0), true);
}
Action::None
}
Event::TimerUpdate(pl) if pl == PAYLOAD_SELECT => {
match self.touch_phase {
TouchPhase::Start(touch_id, coord) => {
self.touch_phase = TouchPhase::Cursor(touch_id);
Action::Cursor(coord, true, !mgr.modifiers().shift(), 1)
}
// Note: if the TimerUpdate were from another requester it
// should technically be Unused, but it doesn't matter
// so long as other consumers match this first.
_ => Action::None,
}
}
Event::TimerUpdate(pl) if pl == PAYLOAD_GLIDE => {
// Momentum/glide scrolling: update per arbitrary step time until movment stops.
let decay = mgr.config().scroll_flick_decay();
if let Some(delta) = self.glide.step(decay) {
let dur = Duration::from_millis(GLIDE_POLL_MS);
mgr.request_update(w_id, PAYLOAD_GLIDE, dur, true);
Action::Pan(delta)
} else {
Action::None
}
}
_ => Action::Unused,
}
}
sourcepub fn set_disabled(&mut self, w_id: WidgetId, state: bool)
pub fn set_disabled(&mut self, w_id: WidgetId, state: bool)
Set/unset a widget as disabled
Disabled status applies to all descendants and blocks reception of
events (Response::Unused
is returned automatically when the
recipient or any ancestor is disabled).
sourcepub fn request_update(
&mut self,
id: WidgetId,
payload: u64,
delay: Duration,
first: bool
)
pub fn request_update(
&mut self,
id: WidgetId,
payload: u64,
delay: Duration,
first: bool
)
Schedule an update
Widget updates may be used for animation and timed responses. See also
Draw::animate
for animation.
Widget w_id
will receive Event::TimerUpdate
with this payload
at
approximately time = now + delay
(or possibly a little later due to
frame-rate limiters and processing time).
Requesting an update with delay == 0
is valid, except from an
Event::TimerUpdate
handler (where it may cause an infinite loop).
If multiple updates with the same id
and payload
are requested,
these are merged (using the earliest time if first
is true).
Examples found in repository?
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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
pub fn scroll_by_event(
&mut self,
mgr: &mut EventMgr,
event: Event,
id: WidgetId,
window_rect: Rect,
) -> (bool, Response) {
let mut moved = false;
match event {
Event::Command(cmd) => {
let offset = match cmd {
Command::Home => Offset::ZERO,
Command::End => self.max_offset,
cmd => {
let delta = match cmd {
Command::Left => LineDelta(-1.0, 0.0),
Command::Right => LineDelta(1.0, 0.0),
Command::Up => LineDelta(0.0, 1.0),
Command::Down => LineDelta(0.0, -1.0),
Command::PageUp => PixelDelta(Offset(0, window_rect.size.1 / 2)),
Command::PageDown => PixelDelta(Offset(0, -(window_rect.size.1 / 2))),
_ => return (false, Response::Unused),
};
let delta = match delta {
LineDelta(x, y) => mgr.config().scroll_distance((x, y)),
PixelDelta(d) => d,
};
self.offset - delta
}
};
let action = self.set_offset(offset);
if !action.is_empty() {
moved = true;
*mgr |= action;
}
mgr.set_scroll(Scroll::Rect(window_rect));
}
Event::Scroll(delta) => {
let delta = match delta {
LineDelta(x, y) => mgr.config().scroll_distance((x, y)),
PixelDelta(d) => d,
};
moved = self.scroll_by_delta(mgr, delta);
}
Event::PressStart { source, coord, .. }
if self.max_offset != Offset::ZERO && mgr.config_enable_pan(source) =>
{
let icon = Some(CursorIcon::Grabbing);
mgr.grab_press_unique(id, source, coord, icon);
}
Event::PressMove { delta, .. } => {
self.glide.move_delta(delta);
moved = self.scroll_by_delta(mgr, delta);
}
Event::PressEnd { .. } => {
if self.glide.opt_start(mgr.config().scroll_flick_timeout()) {
mgr.request_update(id, PAYLOAD_GLIDE, Duration::new(0, 0), true);
}
}
Event::TimerUpdate(pl) if pl == PAYLOAD_GLIDE => {
// Momentum/glide scrolling: update per arbitrary step time until movment stops.
let decay = mgr.config().scroll_flick_decay();
if let Some(delta) = self.glide.step(decay) {
let action = self.set_offset(self.offset - delta);
if !action.is_empty() {
*mgr |= action;
moved = true;
}
if delta == Offset::ZERO || !action.is_empty() {
// Note: when FPS > pixels/sec, delta may be zero while
// still scrolling. Glide returns None when we're done,
// but we're also done if unable to scroll further.
let dur = Duration::from_millis(GLIDE_POLL_MS);
mgr.request_update(id, PAYLOAD_GLIDE, dur, true);
mgr.set_scroll(Scroll::Scrolled);
}
}
}
_ => return (false, Response::Unused),
}
(moved, Response::Used)
}
}
#[impl_default(TouchPhase::None)]
#[derive(Clone, Debug, PartialEq)]
enum TouchPhase {
None,
Start(u64, Coord), // id, coord
Pan(u64), // id
Cursor(u64), // id
}
/// Handles text selection and panning from mouse and touch events
#[derive(Clone, Debug, Default)]
pub struct TextInput {
touch_phase: TouchPhase,
glide: Glide,
}
/// Result of [`TextInput::handle`]
pub enum TextInputAction {
/// No action (event consumed)
None,
/// Event not used
Unused,
/// Pan text using the given `delta`
Pan(Offset),
/// Keyboard focus should be requested (if not already active)
///
/// This is also the case for variant `Cursor(_, true, _, _)` (i.e. if
/// `anchor == true`).
Focus,
/// Update cursor and/or selection: `(coord, anchor, clear, repeats)`
///
/// The cursor position should be moved to `coord`.
///
/// If `anchor`, the anchor position (used for word and line selection mode)
/// should be set to the new cursor position.
///
/// If `clear`, the selection should be cleared (move selection position to
/// edit position).
///
/// If `repeats > 1`, [`SelectionHelper::expand`] should be called with
/// this parameter to enable word/line selection mode.
Cursor(Coord, bool, bool, u32),
}
impl TextInput {
/// Handle input events
///
/// Consumes the following events: `PressStart`, `PressMove`, `PressEnd`,
/// `TimerUpdate(pl)` where `pl == 1<<60 || pl == (1<<60)+1`.
/// May request press grabs and timer updates.
///
/// Implements scrolling and text selection behaviour, excluding handling of
/// [`Event::Scroll`].
pub fn handle(&mut self, mgr: &mut EventMgr, w_id: WidgetId, event: Event) -> TextInputAction {
use TextInputAction as Action;
match event {
Event::PressStart { source, coord, .. } if source.is_primary() => {
let (action, icon) = match source {
PressSource::Touch(touch_id) => {
self.touch_phase = TouchPhase::Start(touch_id, coord);
let delay = mgr.config().touch_select_delay();
mgr.request_update(w_id.clone(), PAYLOAD_SELECT, delay, false);
(Action::Focus, None)
}
PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan() => {
(Action::Focus, Some(CursorIcon::Grabbing))
}
PressSource::Mouse(_, repeats) => (
Action::Cursor(coord, true, !mgr.modifiers().shift(), repeats),
None,
),
};
mgr.grab_press_unique(w_id, source, coord, icon);
action
}
Event::PressMove {
source,
coord,
delta,
..
} => {
self.glide.move_delta(delta);
match source {
PressSource::Touch(touch_id) => match self.touch_phase {
TouchPhase::Start(id, start_coord) if id == touch_id => {
let delta = coord - start_coord;
if mgr.config_test_pan_thresh(delta) {
self.touch_phase = TouchPhase::Pan(id);
Action::Pan(delta)
} else {
Action::None
}
}
TouchPhase::Pan(id) if id == touch_id => Action::Pan(delta),
_ => Action::Cursor(coord, false, false, 1),
},
PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan() => {
Action::Pan(delta)
}
PressSource::Mouse(_, repeats) => Action::Cursor(coord, false, false, repeats),
}
}
Event::PressEnd { source, .. } => {
if self.glide.opt_start(mgr.config().scroll_flick_timeout())
&& (matches!(source, PressSource::Touch(id) if self.touch_phase == TouchPhase::Pan(id))
|| matches!(source, PressSource::Mouse(..) if mgr.config_enable_mouse_text_pan()))
{
self.touch_phase = TouchPhase::None;
mgr.request_update(w_id, PAYLOAD_GLIDE, Duration::new(0, 0), true);
}
Action::None
}
Event::TimerUpdate(pl) if pl == PAYLOAD_SELECT => {
match self.touch_phase {
TouchPhase::Start(touch_id, coord) => {
self.touch_phase = TouchPhase::Cursor(touch_id);
Action::Cursor(coord, true, !mgr.modifiers().shift(), 1)
}
// Note: if the TimerUpdate were from another requester it
// should technically be Unused, but it doesn't matter
// so long as other consumers match this first.
_ => Action::None,
}
}
Event::TimerUpdate(pl) if pl == PAYLOAD_GLIDE => {
// Momentum/glide scrolling: update per arbitrary step time until movment stops.
let decay = mgr.config().scroll_flick_decay();
if let Some(delta) = self.glide.step(decay) {
let dur = Duration::from_millis(GLIDE_POLL_MS);
mgr.request_update(w_id, PAYLOAD_GLIDE, dur, true);
Action::Pan(delta)
} else {
Action::None
}
}
_ => Action::Unused,
}
}
sourcepub fn redraw(&mut self, _id: WidgetId)
pub fn redraw(&mut self, _id: WidgetId)
Notify that a widget must be redrawn
Note: currently, only full-window redraws are supported, thus this is
equivalent to: mgr.send_action(TkAction::REDRAW);
Examples found in repository?
More examples
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
pub fn set_disabled(&mut self, w_id: WidgetId, state: bool) {
for (i, id) in self.disabled.iter().enumerate() {
if w_id == id {
if !state {
self.redraw(w_id);
self.disabled.remove(i);
}
return;
}
}
if state {
self.send_action(TkAction::REDRAW);
self.disabled.push(w_id);
}
}
sourcepub fn send_action(&mut self, action: TkAction)
pub fn send_action(&mut self, action: TkAction)
Notify that a TkAction
action should happen
This causes the given action to happen after event handling.
Calling mgr.send_action(action)
is equivalent to *mgr |= action
.
Whenever a widget is added, removed or replaced, a reconfigure action is required. Should a widget’s size requirements change, these will only affect the UI after a reconfigure action.
Examples found in repository?
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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
fn bitor_assign(&mut self, action: TkAction) {
self.send_action(action);
}
}
impl std::ops::BitOrAssign<TkAction> for EventState {
#[inline]
fn bitor_assign(&mut self, action: TkAction) {
self.send_action(action);
}
}
/// Public API
impl EventState {
/// True when the window has focus
#[inline]
pub fn window_has_focus(&self) -> bool {
self.window_has_focus
}
/// True when accelerator key labels should be shown
///
/// (True when Alt is held and no widget has character focus.)
///
/// This is a fast check.
#[inline]
pub fn show_accel_labels(&self) -> bool {
self.modifiers.alt()
}
/// Get whether this widget has `(char_focus, sel_focus)`
///
/// - `char_focus`: implies this widget receives keyboard input
/// - `sel_focus`: implies this widget is allowed to select things
///
/// Note that `char_focus` implies `sel_focus`.
#[inline]
pub fn has_char_focus(&self, w_id: &WidgetId) -> (bool, bool) {
let sel_focus = *w_id == self.sel_focus;
(sel_focus && self.char_focus, sel_focus)
}
/// Get whether this widget has keyboard navigation focus
#[inline]
pub fn has_nav_focus(&self, w_id: &WidgetId) -> bool {
*w_id == self.nav_focus
}
/// Get whether the widget is under the mouse cursor
#[inline]
pub fn is_hovered(&self, w_id: &WidgetId) -> bool {
self.mouse_grab.is_none() && *w_id == self.hover
}
/// Check whether the given widget is visually depressed
pub fn is_depressed(&self, w_id: &WidgetId) -> bool {
for (_, id) in &self.key_depress {
if *id == w_id {
return true;
}
}
if self
.mouse_grab
.as_ref()
.map(|grab| *w_id == grab.depress)
.unwrap_or(false)
{
return true;
}
for grab in self.touch_grab.iter() {
if *w_id == grab.depress {
return true;
}
}
for popup in &self.popups {
if *w_id == popup.1.parent {
return true;
}
}
false
}
/// Check whether a widget is disabled
///
/// A widget is disabled if any ancestor is.
#[inline]
pub fn is_disabled(&self, w_id: &WidgetId) -> bool {
// TODO(opt): we should be able to use binary search here
for id in &self.disabled {
if id.is_ancestor_of(w_id) {
return true;
}
}
false
}
/// Get the current modifier state
#[inline]
pub fn modifiers(&self) -> ModifiersState {
self.modifiers
}
/// Access event-handling configuration
#[inline]
pub fn config(&self) -> &WindowConfig {
&self.config
}
/// Is mouse panning enabled?
#[inline]
pub fn config_enable_pan(&self, source: PressSource) -> bool {
source.is_touch()
|| source.is_primary() && self.config.mouse_pan().is_enabled_with(self.modifiers())
}
/// Is mouse text panning enabled?
#[inline]
pub fn config_enable_mouse_text_pan(&self) -> bool {
self.config
.mouse_text_pan()
.is_enabled_with(self.modifiers())
}
/// Test pan threshold against config, adjusted for scale factor
///
/// Returns true when `dist` is large enough to switch to pan mode.
#[inline]
pub fn config_test_pan_thresh(&self, dist: Offset) -> bool {
Vec2::conv(dist).abs().max_comp() >= self.config.pan_dist_thresh()
}
/// Set/unset a widget as disabled
///
/// Disabled status applies to all descendants and blocks reception of
/// events ([`Response::Unused`] is returned automatically when the
/// recipient or any ancestor is disabled).
pub fn set_disabled(&mut self, w_id: WidgetId, state: bool) {
for (i, id) in self.disabled.iter().enumerate() {
if w_id == id {
if !state {
self.redraw(w_id);
self.disabled.remove(i);
}
return;
}
}
if state {
self.send_action(TkAction::REDRAW);
self.disabled.push(w_id);
}
}
/// Schedule an update
///
/// Widget updates may be used for animation and timed responses. See also
/// [`Draw::animate`](crate::draw::Draw::animate) for animation.
///
/// Widget `w_id` will receive [`Event::TimerUpdate`] with this `payload` at
/// approximately `time = now + delay` (or possibly a little later due to
/// frame-rate limiters and processing time).
///
/// Requesting an update with `delay == 0` is valid, except from an
/// [`Event::TimerUpdate`] handler (where it may cause an infinite loop).
///
/// If multiple updates with the same `id` and `payload` are requested,
/// these are merged (using the earliest time if `first` is true).
pub fn request_update(&mut self, id: WidgetId, payload: u64, delay: Duration, first: bool) {
let time = Instant::now() + delay;
if let Some(row) = self
.time_updates
.iter_mut()
.find(|row| row.1 == id && row.2 == payload)
{
if (first && row.0 <= time) || (!first && row.0 >= time) {
return;
}
row.0 = time;
log::trace!(
target: "kas_core::event::manager",
"request_update: update {id} at now+{}ms",
delay.as_millis()
);
} else {
self.time_updates.push((time, id, payload));
}
self.time_updates.sort_by(|a, b| b.0.cmp(&a.0)); // reverse sort
}
/// Notify that a widget must be redrawn
///
/// Note: currently, only full-window redraws are supported, thus this is
/// equivalent to: `mgr.send_action(TkAction::REDRAW);`
#[inline]
pub fn redraw(&mut self, _id: WidgetId) {
// Theoretically, notifying by WidgetId allows selective redrawing
// (damage events). This is not yet implemented.
self.send_action(TkAction::REDRAW);
}
/// Notify that a [`TkAction`] action should happen
///
/// This causes the given action to happen after event handling.
///
/// Calling `mgr.send_action(action)` is equivalent to `*mgr |= action`.
///
/// Whenever a widget is added, removed or replaced, a reconfigure action is
/// required. Should a widget's size requirements change, these will only
/// affect the UI after a reconfigure action.
#[inline]
pub fn send_action(&mut self, action: TkAction) {
self.action |= action;
}
/// Attempts to set a fallback to receive [`Event::Command`]
///
/// In case a navigation key is pressed (see [`Command`]) but no widget has
/// navigation focus, then, if a fallback has been set, that widget will
/// receive the key via [`Event::Command`].
///
/// Only one widget can be a fallback, and the *first* to set itself wins.
/// This is primarily used to allow scroll-region widgets to
/// respond to navigation keys when no widget has focus.
pub fn register_nav_fallback(&mut self, id: WidgetId) {
if self.nav_fallback.is_none() {
log::debug!(target: "kas_core::event::manager","register_nav_fallback: id={id}");
self.nav_fallback = Some(id);
}
}
fn accel_layer_for_id(&mut self, id: &WidgetId) -> Option<&mut AccelLayer> {
let root = &WidgetId::ROOT;
for (k, v) in self.accel_layers.range_mut(root..=id).rev() {
if k.is_ancestor_of(id) {
return Some(v);
};
}
debug_assert!(false, "expected ROOT accel layer");
None
}
/// Add a new accelerator key layer
///
/// This method constructs a new "layer" for accelerator keys: any keys
/// added via [`EventState::add_accel_keys`] to a widget which is a descentant
/// of (or equal to) `id` will only be active when that layer is active.
///
/// This method should only be called by parents of a pop-up: layers over
/// the base layer are *only* activated by an open pop-up.
///
/// If `alt_bypass` is true, then this layer's accelerator keys will be
/// active even without Alt pressed (but only highlighted with Alt pressed).
pub fn new_accel_layer(&mut self, id: WidgetId, alt_bypass: bool) {
self.accel_layers.insert(id, (alt_bypass, HashMap::new()));
}
/// Enable `alt_bypass` for layer
///
/// This may be called by a child widget during configure to enable or
/// disable alt-bypass for the accel-key layer containing its accel keys.
/// This allows accelerator keys to be used as shortcuts without the Alt
/// key held. See also [`EventState::new_accel_layer`].
pub fn enable_alt_bypass(&mut self, id: &WidgetId, alt_bypass: bool) {
if let Some(layer) = self.accel_layer_for_id(id) {
layer.0 = alt_bypass;
}
}
/// Adds an accelerator key for a widget
///
/// An *accelerator key* is a shortcut key able to directly open menus,
/// activate buttons, etc. A user triggers the key by pressing `Alt+Key`,
/// or (if `alt_bypass` is enabled) by simply pressing the key.
/// The widget with this `id` then receives [`Command::Activate`].
///
/// Note that accelerator keys may be automatically derived from labels:
/// see [`crate::text::AccelString`].
///
/// Accelerator keys are added to the layer with the longest path which is
/// an ancestor of `id`. This usually means that if the widget is part of a
/// pop-up, the key is only active when that pop-up is open.
/// See [`EventState::new_accel_layer`].
///
/// This should only be called from [`Widget::configure`].
#[inline]
pub fn add_accel_keys(&mut self, id: &WidgetId, keys: &[VirtualKeyCode]) {
if let Some(layer) = self.accel_layer_for_id(id) {
for key in keys {
layer.1.entry(*key).or_insert_with(|| id.clone());
}
}
}
/// Request character-input focus
///
/// Returns true on success or when the widget already had char focus.
///
/// Character data is sent to the widget with char focus via
/// [`Event::ReceivedCharacter`] and [`Event::Command`].
///
/// Char focus implies sel focus (see [`Self::request_sel_focus`]) and
/// navigation focus.
///
/// When char focus is lost, [`Event::LostCharFocus`] is sent.
#[inline]
pub fn request_char_focus(&mut self, id: WidgetId) -> bool {
self.set_sel_focus(id, true);
true
}
/// Request selection focus
///
/// Returns true on success or when the widget already had sel focus.
///
/// To prevent multiple simultaneous selections (e.g. of text) in the UI,
/// only widgets with "selection focus" are allowed to select things.
/// Selection focus is implied by character focus. [`Event::LostSelFocus`]
/// is sent when selection focus is lost; in this case any existing
/// selection should be cleared.
///
/// Selection focus implies navigation focus.
///
/// When char focus is lost, [`Event::LostSelFocus`] is sent.
#[inline]
pub fn request_sel_focus(&mut self, id: WidgetId) -> bool {
self.set_sel_focus(id, false);
true
}
/// Set a grab's depress target
///
/// When a grab on mouse or touch input is in effect
/// ([`EventMgr::grab_press`]), the widget owning the grab may set itself
/// or any other widget as *depressed* ("pushed down"). Each grab depresses
/// at most one widget, thus setting a new depress target clears any
/// existing target. Initially a grab depresses its owner.
///
/// This effect is purely visual. A widget is depressed when one or more
/// grabs targets the widget to depress, or when a keyboard binding is used
/// to activate a widget (for the duration of the key-press).
///
/// Queues a redraw and returns `true` if the depress target changes,
/// otherwise returns `false`.
pub fn set_grab_depress(&mut self, source: PressSource, target: Option<WidgetId>) -> bool {
let mut redraw = false;
match source {
PressSource::Mouse(_, _) => {
if let Some(grab) = self.mouse_grab.as_mut() {
redraw = grab.depress != target;
grab.depress = target.clone();
}
}
PressSource::Touch(id) => {
if let Some(grab) = self.get_touch(id) {
redraw = grab.depress != target;
grab.depress = target.clone();
}
}
}
if redraw {
log::trace!(target: "kas_core::event::manager", "set_grab_depress: target={target:?}");
self.send_action(TkAction::REDRAW);
}
redraw
}
/// Returns true if `id` or any descendant has a mouse or touch grab
pub fn any_pin_on(&self, id: &WidgetId) -> bool {
if self
.mouse_grab
.as_ref()
.map(|grab| grab.start_id == id)
.unwrap_or(false)
{
return true;
}
if self.touch_grab.iter().any(|grab| grab.start_id == id) {
return true;
}
false
}
/// Get the current keyboard navigation focus, if any
///
/// This is the widget selected by navigating the UI with the Tab key.
#[inline]
pub fn nav_focus(&self) -> Option<&WidgetId> {
self.nav_focus.as_ref()
}
/// Clear keyboard navigation focus
pub fn clear_nav_focus(&mut self) {
if let Some(id) = self.nav_focus.take() {
self.send_action(TkAction::REDRAW);
self.pending.push_back(Pending::LostNavFocus(id));
}
self.clear_char_focus();
log::trace!(target: "kas_core::event::manager", "clear_nav_focus");
}
/// Set the keyboard navigation focus directly
///
/// Normally, [`Widget::navigable`] will be true for the specified
/// widget, but this is not required, e.g. a `ScrollLabel` can receive focus
/// on text selection with the mouse. (Currently such widgets will receive
/// events like any other with nav focus, but this may change.)
///
/// The target widget, if not already having navigation focus, will receive
/// [`Event::NavFocus`] with `key_focus` as the payload. This boolean should
/// be true if focussing in response to keyboard input, false if reacting to
/// mouse or touch input.
pub fn set_nav_focus(&mut self, id: WidgetId, key_focus: bool) {
if id == self.nav_focus || !self.config.nav_focus {
return;
}
self.send_action(TkAction::REDRAW);
if let Some(old_id) = self.nav_focus.take() {
self.pending.push_back(Pending::LostNavFocus(old_id));
}
self.clear_char_focus();
self.nav_focus = Some(id.clone());
log::trace!(target: "kas_core::event::manager", "set_nav_focus: {id}");
self.pending.push_back(Pending::SetNavFocus(id, key_focus));
}
/// Set the cursor icon
///
/// This is normally called when handling [`Event::MouseHover`]. In other
/// cases, calling this method may be ineffective. The cursor is
/// automatically "unset" when the widget is no longer hovered.
///
/// If a mouse grab ([`EventMgr::grab_press`]) is active, its icon takes precedence.
pub fn set_cursor_icon(&mut self, icon: CursorIcon) {
// Note: this is acted on by EventState::update
self.hover_icon = icon;
}
}
/// Public API
impl<'a> EventMgr<'a> {
/// Send an event to a widget
///
/// Sends `event` to widget `id`, where `widget` is either the target `id`
/// or any ancestor.
/// Ancestors of `id` up to and including `widget` have the usual
/// event-handling interactions: the ability to steal events and handle
/// unused events, to handle messages and to react to scroll actions.
///
/// Messages may be left on the stack after this returns and scroll state
/// may be adjusted.
///
/// When calling this method, be aware that:
///
/// - Some widgets use an inner component to handle events, thus calling
/// with the outer widget's `id` may not have the desired effect.
/// [`Layout::find_id`] and [`Self::next_nav_focus`] are able to find
/// the appropriate event-handling target.
/// (TODO: do we need another method to find this target?)
/// - Some events such as [`Event::PressMove`] contain embedded widget
/// identifiers which may affect handling of the event.
pub fn send(&mut self, widget: &mut dyn Widget, mut id: WidgetId, event: Event) -> Response {
log::trace!(target: "kas_core::event::manager", "send: id={id}: {event:?}");
// TODO(opt): we should be able to use binary search here
let mut disabled = false;
if !event.pass_when_disabled() {
for d in &self.disabled {
if d.is_ancestor_of(&id) {
id = d.clone();
disabled = true;
}
}
if disabled {
log::trace!(target: "kas_core::event::manager", "target is disabled; sending to ancestor {id}");
}
}
self.scroll = Scroll::None;
self.send_recurse(widget, id, disabled, event)
}
/// Push a message to the stack
pub fn push_msg<M: Debug + 'static>(&mut self, msg: M) {
self.push_boxed_msg(Box::new(msg));
}
/// Push a pre-boxed message to the stack
pub fn push_boxed_msg<M: Debug + 'static>(&mut self, msg: Box<M>) {
self.messages.push(Message::new(msg));
}
/// True if the message stack is non-empty
pub fn has_msg(&self) -> bool {
!self.messages.is_empty()
}
/// Try popping the last message from the stack with the given type
pub fn try_pop_msg<M: Debug + 'static>(&mut self) -> Option<M> {
self.try_pop_boxed_msg().map(|m| *m)
}
/// Try popping the last message from the stack with the given type
pub fn try_pop_boxed_msg<M: Debug + 'static>(&mut self) -> Option<Box<M>> {
if self.messages.last().map(|m| m.is::<M>()).unwrap_or(false) {
self.messages.pop().unwrap().downcast::<M>().ok()
} else {
None
}
}
/// Try observing the last message on the stack without popping
pub fn try_observe_msg<M: Debug + 'static>(&self) -> Option<&M> {
self.messages.last().and_then(|m| m.downcast_ref::<M>())
}
/// Set a scroll action
///
/// When setting [`Scroll::Rect`], use the widgets own coordinate space.
///
/// Note that calling this method has no effect on the widget itself, but
/// affects parents via their [`Widget::handle_scroll`] method.
#[inline]
pub fn set_scroll(&mut self, scroll: Scroll) {
self.scroll = scroll;
}
/// Add an overlay (pop-up)
///
/// A pop-up is a box used for things like tool-tips and menus which is
/// drawn on top of other content and has focus for input.
///
/// Depending on the host environment, the pop-up may be a special type of
/// window without borders and with precise placement, or may be a layer
/// drawn in an existing window.
///
/// The parent of a popup automatically receives mouse-motion events
/// ([`Event::PressMove`]) which may be used to navigate menus.
/// The parent automatically receives the "depressed" visual state.
///
/// It is recommended to call [`EventState::set_nav_focus`] or
/// [`EventMgr::next_nav_focus`] after this method.
///
/// A pop-up may be closed by calling [`EventMgr::close_window`] with
/// the [`WindowId`] returned by this method.
///
/// Returns `None` if window creation is not currently available (but note
/// that `Some` result does not guarantee the operation succeeded).
pub fn add_popup(&mut self, popup: crate::Popup) -> Option<WindowId> {
log::trace!(target: "kas_core::event::manager", "add_popup: {popup:?}");
let new_id = &popup.id;
while let Some((_, popup, _)) = self.popups.last() {
if popup.parent.is_ancestor_of(new_id) {
break;
}
let (wid, popup, _old_nav_focus) = self.popups.pop().unwrap();
self.shell.close_window(wid);
self.popup_removed.push((popup.parent, wid));
// Don't restore old nav focus: assume new focus will be set by new popup
}
let opt_id = self.shell.add_popup(popup.clone());
if let Some(id) = opt_id {
let nav_focus = self.nav_focus.clone();
self.popups.push((id, popup, nav_focus));
}
self.clear_nav_focus();
opt_id
}
/// Add a window
///
/// Typically an application adds at least one window before the event-loop
/// starts (see `kas_wgpu::Toolkit::add`), however this method is not
/// available to a running UI. Instead, this method may be used.
///
/// Caveat: if an error occurs opening the new window it will not be
/// reported (except via log messages).
#[inline]
pub fn add_window(&mut self, widget: Box<dyn crate::Window>) -> WindowId {
self.shell.add_window(widget)
}
/// Close a window or pop-up
///
/// In the case of a pop-up, all pop-ups created after this will also be
/// removed (on the assumption they are a descendant of the first popup).
///
/// If `restore_focus` then navigation focus will return to whichever widget
/// had focus before the popup was open. (Usually this is true excepting
/// where focus has already been changed.)
pub fn close_window(&mut self, id: WindowId, restore_focus: bool) {
if let Some(index) =
self.popups
.iter()
.enumerate()
.find_map(|(i, p)| if p.0 == id { Some(i) } else { None })
{
let mut old_nav_focus = None;
while self.popups.len() > index {
let (wid, popup, onf) = self.popups.pop().unwrap();
self.popup_removed.push((popup.parent, wid));
self.shell.close_window(wid);
old_nav_focus = onf;
}
if !restore_focus {
old_nav_focus = None
}
if let Some(id) = old_nav_focus {
self.set_nav_focus(id, true);
}
// TODO: if popup.id is an ancestor of self.nav_focus then clear
// focus if not setting (currently we cannot test this)
}
self.shell.close_window(id);
}
/// Send [`Event::Update`] to all widgets
///
/// All widgets across all windows will receive [`Event::Update`] with
/// [`UpdateId::ZERO`] and the given `payload`.
#[inline]
pub fn update_all(&mut self, payload: u64) {
self.shell.update_all(UpdateId::ZERO, payload);
}
/// Send [`Event::Update`] to all widgets
///
/// All widgets across all windows will receive [`Event::Update`] with
/// the given `id` and `payload`.
pub fn update_with_id(&mut self, id: UpdateId, payload: u64) {
log::debug!(target: "kas_core::event::manager", "update_all: id={id:?}, payload={payload}");
self.shell.update_all(id, payload);
}
/// Attempt to get clipboard contents
///
/// In case of failure, paste actions will simply fail. The implementation
/// may wish to log an appropriate warning message.
#[inline]
pub fn get_clipboard(&mut self) -> Option<String> {
self.shell.get_clipboard()
}
/// Attempt to set clipboard contents
#[inline]
pub fn set_clipboard(&mut self, content: String) {
self.shell.set_clipboard(content)
}
/// Adjust the theme
#[inline]
pub fn adjust_theme<F: FnMut(&mut dyn ThemeControl) -> TkAction>(&mut self, mut f: F) {
self.shell.adjust_theme(&mut f);
}
/// Access a [`SizeMgr`]
///
/// Warning: sizes are calculated using the window's current scale factor.
/// This may change, even without user action, since some platforms
/// always initialize windows with scale factor 1.
/// See also notes on [`Widget::configure`].
pub fn size_mgr<F: FnMut(SizeMgr) -> T, T>(&mut self, mut f: F) -> T {
let mut result = None;
self.shell.size_and_draw_shared(&mut |size, _| {
result = Some(f(SizeMgr::new(size)));
});
result.expect("ShellWindow::size_and_draw_shared impl failed to call function argument")
}
/// Access a [`ConfigMgr`]
pub fn config_mgr<F: FnMut(&mut ConfigMgr) -> T, T>(&mut self, mut f: F) -> T {
let mut result = None;
self.shell.size_and_draw_shared(&mut |size, draw_shared| {
let mut mgr = ConfigMgr::new(size, draw_shared, self.state);
result = Some(f(&mut mgr));
});
result.expect("ShellWindow::size_and_draw_shared impl failed to call function argument")
}
/// Access a [`DrawShared`]
pub fn draw_shared<F: FnMut(&mut dyn DrawShared) -> T, T>(&mut self, mut f: F) -> T {
let mut result = None;
self.shell.size_and_draw_shared(&mut |_, draw_shared| {
result = Some(f(draw_shared));
});
result.expect("ShellWindow::size_and_draw_shared impl failed to call function argument")
}
/// Grab "press" events for `source` (a mouse or finger)
///
/// When a "press" source is "grabbed", events for this source will be sent
/// to the grabbing widget. Notes:
///
/// - For mouse sources, a click-press event from another button will
/// cancel this grab; [`Event::PressEnd`] will be sent (with mode
/// [`GrabMode::Grab`]), then [`Event::PressStart`] will be sent to the
/// widget under the mouse like normal.
/// - For touch-screen sources, events are delivered until the finger is
/// removed or the touch is cancelled (e.g. by dragging off-screen).
/// - [`Self::grab_press_unique`] is a variant of this method which
/// cancels grabs of other sources by the same widget.
///
/// Each grab can optionally visually depress one widget, and initially
/// depresses the widget owning the grab (the `id` passed here). Call
/// [`EventState::set_grab_depress`] to update the grab's depress target.
/// This is cleared automatically when the grab ends.
///
/// The events sent depends on the `mode`:
///
/// - [`GrabMode::Grab`]: simple / low-level interpretation of input
/// which delivers [`Event::PressMove`] and [`Event::PressEnd`] events.
/// - All other [`GrabMode`] values: generates [`Event::Pan`] events.
/// Requesting additional grabs on the same widget from the same source
/// (i.e. multiple touches) allows generation of rotation and scale
/// factors (depending on the [`GrabMode`]).
/// Any previously existing `Pan` grabs by this widgets are replaced.
///
/// Since these events are *requested*, the widget should consume them even
/// if not required, although in practice this
/// only affects parents intercepting [`Response::Unused`] events.
pub fn grab_press(
&mut self,
id: WidgetId,
source: PressSource,
coord: Coord,
mode: GrabMode,
cursor: Option<CursorIcon>,
) {
let start_id = id.clone();
log::trace!(target: "kas_core::event::manager", "grab_press: start_id={start_id}, source={source:?}");
let mut pan_grab = (u16::MAX, 0);
match source {
PressSource::Mouse(button, repetitions) => {
if self.remove_mouse_grab().is_some() {
#[cfg(debug_assertions)]
log::error!(target: "kas_core::event::manager", "grab_press: existing mouse grab!");
}
if mode != GrabMode::Grab {
pan_grab = self.set_pan_on(id.clone(), mode, false, coord);
}
self.mouse_grab = Some(MouseGrab {
button,
repetitions,
start_id: start_id.clone(),
cur_id: Some(start_id),
depress: Some(id),
mode,
pan_grab,
coord,
delta: Offset::ZERO,
});
if let Some(icon) = cursor {
self.shell.set_cursor_icon(icon);
}
}
PressSource::Touch(touch_id) => {
if self.remove_touch(touch_id).is_some() {
#[cfg(debug_assertions)]
log::error!(target: "kas_core::event::manager", "grab_press: existing touch grab!");
}
if mode != GrabMode::Grab {
pan_grab = self.set_pan_on(id.clone(), mode, true, coord);
}
self.touch_grab.push(TouchGrab {
id: touch_id,
start_id,
depress: Some(id.clone()),
cur_id: Some(id),
last_move: coord,
coord,
mode,
pan_grab,
});
}
}
self.send_action(TkAction::REDRAW);
}
/// A variant of [`Self::grab_press`], where a unique grab is desired
///
/// This removes any existing press-grabs by widget `id`, then calls
/// [`Self::grab_press`] with `mode = GrabMode::Grab` to create a new grab.
/// Previous grabs are discarded without delivering [`Event::PressEnd`].
pub fn grab_press_unique(
&mut self,
id: WidgetId,
source: PressSource,
coord: Coord,
cursor: Option<CursorIcon>,
) {
if id == self.mouse_grab.as_ref().map(|grab| &grab.start_id) {
self.remove_mouse_grab();
}
self.touch_grab.retain(|grab| id != grab.start_id);
self.grab_press(id, source, coord, GrabMode::Grab, cursor);
}
/// Update the mouse cursor used during a grab
///
/// This only succeeds if widget `id` has an active mouse-grab (see
/// [`EventMgr::grab_press`]). The cursor will be reset when the mouse-grab
/// ends.
pub fn update_grab_cursor(&mut self, id: WidgetId, icon: CursorIcon) {
if let Some(ref grab) = self.mouse_grab {
if grab.start_id == id {
self.shell.set_cursor_icon(icon);
}
}
}
/// Advance the keyboard navigation focus
///
/// This is a shim around [`ConfigMgr::next_nav_focus`].
#[inline]
pub fn next_nav_focus(
&mut self,
widget: &mut dyn Widget,
reverse: bool,
key_focus: bool,
) -> bool {
self.config_mgr(|mgr| mgr.next_nav_focus(widget, reverse, key_focus))
}
/// Advance the keyboard navigation focus
///
/// This is similar to [`Self::next_nav_focus`], but looks for the next
/// widget from `id` which is [`Widget::navigable`].
#[inline]
pub fn next_nav_focus_from(
&mut self,
widget: &mut dyn Widget,
id: WidgetId,
key_focus: bool,
) -> bool {
if id == self.nav_focus {
return true;
} else if !self.config.nav_focus {
return false;
}
self.send_action(TkAction::REDRAW);
if let Some(old_id) = self.nav_focus.take() {
self.pending.push_back(Pending::LostNavFocus(old_id));
}
self.clear_char_focus();
if widget
.find_widget(&id)
.map(|w| w.navigable())
.unwrap_or(false)
{
log::trace!(target: "kas_core::event::manager", "set_nav_focus: {id}");
self.nav_focus = Some(id.clone());
self.pending.push_back(Pending::SetNavFocus(id, key_focus));
true
} else {
self.nav_focus = Some(id);
self.next_nav_focus(widget, false, key_focus)
}
}
More examples
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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
fn add_key_depress(&mut self, scancode: u32, id: WidgetId) {
if self.key_depress.values().any(|v| *v == id) {
return;
}
self.key_depress.insert(scancode, id);
self.send_action(TkAction::REDRAW);
}
fn end_key_event(&mut self, scancode: u32) {
// We must match scancode not vkey since the latter may have changed due to modifiers
if let Some(id) = self.key_depress.remove(&scancode) {
self.redraw(id);
}
}
fn mouse_grab(&mut self) -> Option<&mut MouseGrab> {
self.mouse_grab.as_mut()
}
#[inline]
fn get_touch(&mut self, touch_id: u64) -> Option<&mut TouchGrab> {
self.touch_grab.iter_mut().find(|grab| grab.id == touch_id)
}
// Clears touch grab and pan grab and redraws
fn remove_touch(&mut self, touch_id: u64) -> Option<TouchGrab> {
for i in 0..self.touch_grab.len() {
if self.touch_grab[i].id == touch_id {
let grab = self.touch_grab.remove(i);
log::trace!(
"remove_touch: touch_id={touch_id}, start_id={}",
grab.start_id
);
self.send_action(TkAction::REDRAW); // redraw(..)
self.remove_pan_grab(grab.pan_grab);
return Some(grab);
}
}
None
}
fn clear_char_focus(&mut self) {
if let Some(id) = self.char_focus() {
log::trace!("clear_char_focus");
// If widget has char focus, this is lost
self.char_focus = false;
self.pending.push_back(Pending::LostCharFocus(id));
}
}
// Set selection focus to `wid`; if `char_focus` also set that
fn set_sel_focus(&mut self, wid: WidgetId, char_focus: bool) {
log::trace!("set_sel_focus: wid={wid}, char_focus={char_focus}");
// The widget probably already has nav focus, but anyway:
self.set_nav_focus(wid.clone(), true);
if wid == self.sel_focus {
self.char_focus = self.char_focus || char_focus;
return;
}
if let Some(id) = self.sel_focus.clone() {
if self.char_focus {
// If widget has char focus, this is lost
self.pending.push_back(Pending::LostCharFocus(id.clone()));
}
// Selection focus is lost if another widget receives char focus
self.pending.push_back(Pending::LostSelFocus(id));
}
self.char_focus = char_focus;
self.sel_focus = Some(wid);
}
}
// NOTE: we *want* to store Box<dyn Any + Debug> entries, but Rust doesn't
// support multi-trait objects. An alternative would be to store Box<dyn Message>
// where `trait Message: Any + Debug {}`, but Rust does not support
// trait-object upcast, so we cannot downcast the result.
//
// Workaround: pre-format when the message is *pushed*.
struct Message {
any: Box<dyn Any>,
#[cfg(debug_assertions)]
fmt: String,
}
impl Message {
fn new<M: Any + Debug>(msg: Box<M>) -> Self {
#[cfg(debug_assertions)]
let fmt = format!("{}::{:?}", std::any::type_name::<M>(), &msg);
#[cfg(debug_assertions)]
log::debug!(target: "kas_core::event::manager::messages", "push_msg: {fmt}");
let any = msg;
Message {
#[cfg(debug_assertions)]
fmt,
any,
}
}
fn is<T: 'static>(&self) -> bool {
self.any.is::<T>()
}
fn downcast<T: 'static>(self) -> Result<Box<T>, Box<dyn Any>> {
self.any.downcast::<T>()
}
fn downcast_ref<T: 'static>(&self) -> Option<&T> {
self.any.downcast_ref::<T>()
}
}
impl std::fmt::Debug for Message {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
#[cfg(debug_assertions)]
let r = f.write_str(&self.fmt);
#[cfg(not(debug_assertions))]
let r = f.write_str("[use debug build to see value]");
r
}
}
/// Manager of event-handling and toolkit actions
///
/// An `EventMgr` is in fact a handle around [`EventState`] and [`ShellWindow`]
/// in order to provide a convenient user-interface during event processing.
///
/// `EventMgr` supports [`Deref`] and [`DerefMut`] with target [`EventState`].
///
/// It exposes two interfaces: one aimed at users implementing widgets and UIs
/// and one aimed at shells. The latter is hidden
/// from documentation unless the `internal_doc` feature is enabled.
#[must_use]
pub struct EventMgr<'a> {
state: &'a mut EventState,
shell: &'a mut dyn ShellWindow,
messages: Vec<Message>,
scroll: Scroll,
action: TkAction,
}
impl<'a> Deref for EventMgr<'a> {
type Target = EventState;
fn deref(&self) -> &Self::Target {
self.state
}
}
impl<'a> DerefMut for EventMgr<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.state
}
}
impl<'a> Drop for EventMgr<'a> {
fn drop(&mut self) {
for msg in self.messages.drain(..) {
log::warn!(target: "kas_core::event::manager::messages", "unhandled: {msg:?}");
}
}
}
/// Internal methods
impl<'a> EventMgr<'a> {
fn set_hover(&mut self, w_id: Option<WidgetId>) {
if self.hover != w_id {
log::trace!("set_hover: w_id={w_id:?}");
if let Some(id) = self.hover.take() {
self.pending.push_back(Pending::LostMouseHover(id));
}
self.hover = w_id.clone();
if let Some(id) = w_id {
self.pending.push_back(Pending::MouseHover(id));
}
}
}
fn start_key_event(&mut self, widget: &mut dyn Widget, vkey: VirtualKeyCode, scancode: u32) {
log::trace!(
"start_key_event: widget={}, vkey={vkey:?}, scancode={scancode}",
widget.id()
);
use VirtualKeyCode as VK;
let opt_command = self.config.shortcuts(|s| s.get(self.modifiers, vkey));
if let Some(cmd) = opt_command {
let mut targets = vec![];
let mut send = |_self: &mut Self, id: WidgetId, cmd| -> bool {
if !targets.contains(&id) {
let used = _self.send_event(widget, id.clone(), Event::Command(cmd));
if used {
_self.add_key_depress(scancode, id.clone());
}
targets.push(id);
used
} else {
false
}
};
if self.char_focus || cmd.suitable_for_sel_focus() {
if let Some(id) = self.sel_focus.clone() {
if send(self, id, cmd) {
return;
}
}
}
if !self.modifiers.alt() {
if let Some(id) = self.nav_focus.clone() {
if send(self, id, cmd) {
return;
}
}
}
if let Some(id) = self.popups.last().map(|popup| popup.1.parent.clone()) {
if send(self, id, cmd) {
return;
}
}
if let Some(id) = self.nav_fallback.clone() {
if send(self, id, cmd) {
return;
}
}
}
// Next priority goes to accelerator keys when Alt is held or alt_bypass is true
let mut target = None;
let mut n = 0;
for (i, id) in (self.popups.iter().rev())
.map(|(_, popup, _)| popup.parent.clone())
.chain(std::iter::once(widget.id()))
.enumerate()
{
if let Some(layer) = self.accel_layers.get(&id) {
// but only when Alt is held or alt-bypass is enabled:
if self.modifiers == ModifiersState::ALT
|| layer.0 && self.modifiers == ModifiersState::empty()
{
if let Some(id) = layer.1.get(&vkey).cloned() {
target = Some(id);
n = i;
break;
}
}
}
}
// If we found a key binding below the top layer, we should close everything above
if n > 0 {
let len = self.popups.len();
for i in ((len - n)..len).rev() {
let id = self.popups[i].0;
self.close_window(id, false);
}
}
if let Some(id) = target {
if widget
.find_widget(&id)
.map(|w| w.navigable())
.unwrap_or(false)
{
self.set_nav_focus(id.clone(), true);
}
self.add_key_depress(scancode, id.clone());
self.send_event(widget, id, Event::Command(Command::Activate));
} else if self.config.nav_focus && vkey == VK::Tab {
self.clear_char_focus();
let shift = self.modifiers.shift();
self.next_nav_focus(widget, shift, true);
} else if vkey == VK::Escape {
if let Some(id) = self.popups.last().map(|(id, _, _)| *id) {
self.close_window(id, true);
}
}
}
// Clears mouse grab and pan grab, resets cursor and redraws
fn remove_mouse_grab(&mut self) -> Option<MouseGrab> {
if let Some(grab) = self.mouse_grab.take() {
log::trace!("remove_mouse_grab: start_id={}", grab.start_id);
self.shell.set_cursor_icon(self.hover_icon);
self.send_action(TkAction::REDRAW); // redraw(..)
self.remove_pan_grab(grab.pan_grab);
Some(grab)
} else {
None
}
}
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
pub fn add_popup(&mut self, mgr: &mut EventMgr, id: WindowId, popup: kas::Popup) {
let index = self.popups.len();
self.popups.push((id, popup));
mgr.config_mgr(|mgr| self.resize_popup(mgr, index));
mgr.send_action(TkAction::REDRAW);
}
/// Trigger closure of a pop-up
///
/// If the given `id` refers to a pop-up, it should be closed.
pub fn remove_popup(&mut self, mgr: &mut EventMgr, id: WindowId) {
for i in 0..self.popups.len() {
if id == self.popups[i].0 {
self.popups.remove(i);
mgr.send_action(TkAction::REGION_MOVED);
return;
}
}
}
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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
pub fn with<F>(&mut self, shell: &mut dyn ShellWindow, f: F)
where
F: FnOnce(&mut EventMgr),
{
let mut mgr = EventMgr {
state: self,
shell,
messages: vec![],
scroll: Scroll::None,
action: TkAction::empty(),
};
f(&mut mgr);
let action = mgr.action;
drop(mgr);
self.send_action(action);
}
/// Update, after receiving all events
#[inline]
pub fn update(&mut self, shell: &mut dyn ShellWindow, widget: &mut dyn Widget) -> TkAction {
let old_hover_icon = self.hover_icon;
let mut mgr = EventMgr {
state: self,
shell,
messages: vec![],
scroll: Scroll::None,
action: TkAction::empty(),
};
while let Some((parent, wid)) = mgr.popup_removed.pop() {
mgr.send_event(widget, parent, Event::PopupRemoved(wid));
}
if let Some((id, event)) = mgr.mouse_grab().and_then(|g| g.flush_move()) {
mgr.send_event(widget, id, event);
}
for i in 0..mgr.touch_grab.len() {
if let Some((id, event)) = mgr.touch_grab[i].flush_move() {
mgr.send_event(widget, id, event);
}
}
for gi in 0..mgr.pan_grab.len() {
let grab = &mut mgr.pan_grab[gi];
debug_assert!(grab.mode != GrabMode::Grab);
assert!(grab.n > 0);
// Terminology: pi are old coordinates, qi are new coords
let (p1, q1) = (DVec2::conv(grab.coords[0].0), DVec2::conv(grab.coords[0].1));
grab.coords[0].0 = grab.coords[0].1;
let alpha;
let delta;
if grab.mode == GrabMode::PanOnly || grab.n == 1 {
alpha = DVec2(1.0, 0.0);
delta = q1 - p1;
} else {
// We don't use more than two touches: information would be
// redundant (although it could be averaged).
let (p2, q2) = (DVec2::conv(grab.coords[1].0), DVec2::conv(grab.coords[1].1));
grab.coords[1].0 = grab.coords[1].1;
let (pd, qd) = (p2 - p1, q2 - q1);
alpha = match grab.mode {
GrabMode::PanFull => qd.complex_div(pd),
GrabMode::PanScale => DVec2((qd.sum_square() / pd.sum_square()).sqrt(), 0.0),
GrabMode::PanRotate => {
let a = qd.complex_div(pd);
a / a.sum_square().sqrt()
}
_ => unreachable!(),
};
// Average delta from both movements:
delta = (q1 - alpha.complex_mul(p1) + q2 - alpha.complex_mul(p2)) * 0.5;
}
let id = grab.id.clone();
if alpha != DVec2(1.0, 0.0) || delta != DVec2::ZERO {
let event = Event::Pan { alpha, delta };
mgr.send_event(widget, id, event);
}
}
// Warning: infinite loops are possible here if widgets always queue a
// new pending event when evaluating one of these:
while let Some(item) = mgr.pending.pop_front() {
log::trace!(target: "kas_core::event::manager", "update: handling Pending::{item:?}");
let (id, event) = match item {
Pending::SetNavFocus(id, key_focus) => (id, Event::NavFocus(key_focus)),
Pending::MouseHover(id) => (id, Event::MouseHover),
Pending::LostNavFocus(id) => (id, Event::LostNavFocus),
Pending::LostMouseHover(id) => {
mgr.hover_icon = Default::default();
(id, Event::LostMouseHover)
}
Pending::LostCharFocus(id) => (id, Event::LostCharFocus),
Pending::LostSelFocus(id) => (id, Event::LostSelFocus),
};
mgr.send_event(widget, id, event);
}
let action = mgr.action;
drop(mgr);
if self.hover_icon != old_hover_icon && self.mouse_grab.is_none() {
shell.set_cursor_icon(self.hover_icon);
}
let action = action | self.action;
self.action = TkAction::empty();
action
}
}
/// Shell API
#[cfg_attr(not(feature = "internal_doc"), doc(hidden))]
#[cfg_attr(doc_cfg, doc(cfg(internal_doc)))]
impl<'a> EventMgr<'a> {
/// Update widgets due to timer
pub fn update_timer(&mut self, widget: &mut dyn Widget) {
let now = Instant::now();
// assumption: time_updates are sorted in reverse order
while !self.time_updates.is_empty() {
if self.time_updates.last().unwrap().0 > now {
break;
}
let update = self.time_updates.pop().unwrap();
self.send_event(widget, update.1, Event::TimerUpdate(update.2));
}
self.time_updates.sort_by(|a, b| b.0.cmp(&a.0)); // reverse sort
}
/// Update widgets with an [`UpdateId`]
pub fn update_widgets(&mut self, widget: &mut dyn Widget, id: UpdateId, payload: u64) {
if id == self.state.config.config.id() {
let (sf, dpem) = self.size_mgr(|size| (size.scale_factor(), size.dpem()));
self.state.config.update(sf, dpem);
}
let start = Instant::now();
let count = self.send_all(widget, Event::Update { id, payload });
log::debug!(
target: "kas_core::event::manager",
"update_widgets: sent Event::Update ({id:?}) to {count} widgets in {}μs",
start.elapsed().as_micros()
);
}
/// Handle a winit `WindowEvent`.
///
/// Note that some event types are not handled, since for these
/// events the shell must take direct action anyway:
/// `Resized(size)`, `RedrawRequested`, `HiDpiFactorChanged(factor)`.
#[cfg(feature = "winit")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "winit")))]
pub fn handle_winit(&mut self, widget: &mut dyn Widget, event: winit::event::WindowEvent) {
use winit::event::{ElementState, MouseScrollDelta, TouchPhase, WindowEvent::*};
match event {
CloseRequested => self.send_action(TkAction::CLOSE),
/* Not yet supported: see #98
DroppedFile(path) => ,
HoveredFile(path) => ,
HoveredFileCancelled => ,
*/
ReceivedCharacter(c) => {
if let Some(id) = self.char_focus() {
// Filter out control codes (Unicode 5.11). These may be
// generated from combinations such as Ctrl+C by some other
// layer. We use our own shortcut system instead.
if c >= '\x20' && !('\x7f'..='\u{9f}').contains(&c) {
let event = Event::ReceivedCharacter(c);
self.send_event(widget, id, event);
}
}
}
Focused(state) => {
self.window_has_focus = state;
if state {
// Required to restart theme animations
self.send_action(TkAction::REDRAW);
} else {
// Window focus lost: close all popups
while let Some(id) = self.popups.last().map(|(id, _, _)| *id) {
self.close_window(id, true);
}
}
}
KeyboardInput {
input,
is_synthetic,
..
} => {
if input.state == ElementState::Pressed && !is_synthetic {
if let Some(vkey) = input.virtual_keycode {
self.start_key_event(widget, vkey, input.scancode);
}
} else if input.state == ElementState::Released {
self.end_key_event(input.scancode);
}
}
ModifiersChanged(state) => {
if state.alt() != self.modifiers.alt() {
// This controls drawing of accelerator key indicators
self.send_action(TkAction::REDRAW);
}
self.modifiers = state;
}
CursorMoved { position, .. } => {
self.last_click_button = FAKE_MOUSE_BUTTON;
let coord = position.cast_approx();
// Update hovered widget
let cur_id = widget.find_id(coord);
let delta = coord - self.last_mouse_coord;
self.set_hover(cur_id.clone());
if let Some(grab) = self.state.mouse_grab.as_mut() {
if grab.mode == GrabMode::Grab {
grab.cur_id = cur_id;
grab.coord = coord;
grab.delta += delta;
} else if let Some(pan) =
self.state.pan_grab.get_mut(usize::conv(grab.pan_grab.0))
{
pan.coords[usize::conv(grab.pan_grab.1)].1 = coord;
}
} else if let Some(id) = self.popups.last().map(|(_, p, _)| p.parent.clone()) {
let source = PressSource::Mouse(FAKE_MOUSE_BUTTON, 0);
let event = Event::PressMove {
source,
cur_id,
coord,
delta,
};
self.send_event(widget, id, event);
} else {
// We don't forward move events without a grab
}
self.last_mouse_coord = coord;
}
// CursorEntered { .. },
CursorLeft { .. } => {
self.last_click_button = FAKE_MOUSE_BUTTON;
if self.mouse_grab().is_none() {
// If there's a mouse grab, we will continue to receive
// coordinates; if not, set a fake coordinate off the window
self.last_mouse_coord = Coord(-1, -1);
self.set_hover(None);
}
}
MouseWheel { delta, .. } => {
if let Some((id, event)) = self.mouse_grab().and_then(|g| g.flush_move()) {
self.send_event(widget, id, event);
}
self.last_click_button = FAKE_MOUSE_BUTTON;
let event = Event::Scroll(match delta {
MouseScrollDelta::LineDelta(x, y) => ScrollDelta::LineDelta(x, y),
MouseScrollDelta::PixelDelta(pos) => {
// The delta is given as a PhysicalPosition, so we need
// to convert to our vector type (Offset) here.
let coord = Coord::conv_approx(pos);
ScrollDelta::PixelDelta(coord.cast())
}
});
if let Some(id) = self.hover.clone() {
self.send_event(widget, id, event);
}
}
MouseInput { state, button, .. } => {
if let Some((id, event)) = self.mouse_grab().and_then(|g| g.flush_move()) {
self.send_event(widget, id, event);
}
let coord = self.last_mouse_coord;
if state == ElementState::Pressed {
let now = Instant::now();
if button != self.last_click_button || self.last_click_timeout < now {
self.last_click_button = button;
self.last_click_repetitions = 0;
}
self.last_click_repetitions += 1;
self.last_click_timeout = now + DOUBLE_CLICK_TIMEOUT;
}
if let Some(grab) = self.remove_mouse_grab() {
if grab.mode == GrabMode::Grab {
// Mouse grab active: send events there
// Note: any button release may end the grab (intended).
let event = Event::PressEnd {
source: PressSource::Mouse(grab.button, grab.repetitions),
end_id: self.hover.clone(),
coord,
success: state == ElementState::Released,
};
self.send_event(widget, grab.start_id, event);
}
// Pan events do not receive Start/End notifications
}
if state == ElementState::Pressed {
if let Some(start_id) = self.hover.clone() {
// No mouse grab but have a hover target
if self.config.mouse_nav_focus() {
if let Some(w) = widget.find_widget(&start_id) {
if w.navigable() {
self.set_nav_focus(w.id(), false);
}
}
}
}
let source = PressSource::Mouse(button, self.last_click_repetitions);
let event = Event::PressStart {
source,
start_id: self.hover.clone(),
coord,
};
self.send_popup_first(widget, self.hover.clone(), event);
}
}
// TouchpadPressure { pressure: f32, stage: i64, },
// AxisMotion { axis: AxisId, value: f64, },
Touch(touch) => {
let source = PressSource::Touch(touch.id);
let coord = touch.location.cast_approx();
match touch.phase {
TouchPhase::Started => {
let start_id = widget.find_id(coord);
if let Some(id) = start_id.as_ref() {
if self.config.touch_nav_focus() {
if let Some(w) = widget.find_widget(id) {
if w.navigable() {
self.set_nav_focus(w.id(), false);
}
}
}
let event = Event::PressStart {
source,
start_id: start_id.clone(),
coord,
};
self.send_popup_first(widget, start_id, event);
}
}
TouchPhase::Moved => {
let cur_id = widget.find_id(coord);
let mut redraw = false;
let mut pan_grab = None;
if let Some(grab) = self.get_touch(touch.id) {
if grab.mode == GrabMode::Grab {
// Only when 'depressed' status changes:
redraw = grab.cur_id != cur_id
&& (grab.start_id == grab.cur_id || grab.start_id == cur_id);
grab.cur_id = cur_id;
grab.coord = coord;
} else {
pan_grab = Some(grab.pan_grab);
}
}
if redraw {
self.send_action(TkAction::REDRAW);
} else if let Some(pan_grab) = pan_grab {
if usize::conv(pan_grab.1) < MAX_PAN_GRABS {
if let Some(pan) = self.pan_grab.get_mut(usize::conv(pan_grab.0)) {
pan.coords[usize::conv(pan_grab.1)].1 = coord;
}
}
}
}
ev @ (TouchPhase::Ended | TouchPhase::Cancelled) => {
if let Some(mut grab) = self.remove_touch(touch.id) {
if let Some((id, event)) = grab.flush_move() {
self.send_event(widget, id, event);
}
if grab.mode == GrabMode::Grab {
let event = Event::PressEnd {
source,
end_id: grab.cur_id.clone(),
coord,
success: ev == TouchPhase::Ended,
};
self.send_event(widget, grab.start_id, event);
}
}
}
}
}
_ => (),
}
}
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
pub fn next_nav_focus(
&mut self,
mut widget: &mut dyn Widget,
reverse: bool,
key_focus: bool,
) -> bool {
if !self.config.nav_focus {
return false;
}
if let Some(id) = self.popups.last().map(|(_, p, _)| p.id.clone()) {
if id.is_ancestor_of(widget.id_ref()) {
// do nothing
} else if let Some(w) = widget.find_widget_mut(&id) {
widget = w;
} else {
log::warn!(
target: "kas_core::event::config_mgr",
"next_nav_focus: have open pop-up which is not a child of widget",
);
return false;
}
}
// We redraw in all cases. Since this is not part of widget event
// processing, we can push directly to self.action.
self.send_action(TkAction::REDRAW);
let old_nav_focus = self.nav_focus.take();
fn nav(
mgr: &mut ConfigMgr,
widget: &mut dyn Widget,
focus: Option<&WidgetId>,
rev: bool,
) -> Option<WidgetId> {
if mgr.ev_state().is_disabled(widget.id_ref()) {
return None;
}
let mut child = focus.and_then(|id| widget.find_child_index(id));
if !rev {
if let Some(index) = child {
if let Some(id) = widget
.get_child_mut(index)
.and_then(|w| nav(mgr, w, focus, rev))
{
return Some(id);
}
} else if !widget.eq_id(focus) && widget.navigable() {
return Some(widget.id());
}
loop {
if let Some(index) = widget.nav_next(mgr, rev, child) {
if let Some(id) = widget
.get_child_mut(index)
.and_then(|w| nav(mgr, w, focus, rev))
{
return Some(id);
}
child = Some(index);
} else {
return None;
}
}
} else {
if let Some(index) = child {
if let Some(id) = widget
.get_child_mut(index)
.and_then(|w| nav(mgr, w, focus, rev))
{
return Some(id);
}
}
loop {
if let Some(index) = widget.nav_next(mgr, rev, child) {
if let Some(id) = widget
.get_child_mut(index)
.and_then(|w| nav(mgr, w, focus, rev))
{
return Some(id);
}
child = Some(index);
} else {
return if !widget.eq_id(focus) && widget.navigable() {
Some(widget.id())
} else {
None
};
}
}
}
}
// Whether to restart from the beginning on failure
let restart = old_nav_focus.is_some();
let mut opt_id = nav(self, widget, old_nav_focus.as_ref(), reverse);
if restart && opt_id.is_none() {
opt_id = nav(self, widget, None, reverse);
}
log::trace!(
target: "kas_core::event::config_mgr",
"next_nav_focus: nav_focus={opt_id:?}",
);
self.nav_focus = opt_id.clone();
if opt_id == old_nav_focus {
return opt_id.is_some();
}
if let Some(id) = old_nav_focus {
self.pending.push_back(Pending::LostNavFocus(id));
}
if let Some(id) = opt_id {
if id != self.sel_focus {
self.clear_char_focus();
}
self.pending.push_back(Pending::SetNavFocus(id, key_focus));
true
} else {
// Most likely an error occurred
self.clear_char_focus();
false
}
}
/// Advance the keyboard navigation focus
///
/// This is similar to [`Self::next_nav_focus`], but looks for the next
/// widget from `id` which is [`Widget::navigable`].
#[inline]
pub fn next_nav_focus_from(
&mut self,
widget: &mut dyn Widget,
id: WidgetId,
key_focus: bool,
) -> bool {
if id == self.nav_focus {
return true;
} else if !self.config.nav_focus {
return false;
}
self.send_action(TkAction::REDRAW);
if let Some(old_id) = self.nav_focus.take() {
self.pending.push_back(Pending::LostNavFocus(old_id));
}
self.clear_char_focus();
if widget
.find_widget(&id)
.map(|w| w.navigable())
.unwrap_or(false)
{
log::trace!(target: "kas_core::event::manager", "set_nav_focus: {id}");
self.nav_focus = Some(id.clone());
self.pending.push_back(Pending::SetNavFocus(id, key_focus));
true
} else {
self.nav_focus = Some(id);
self.next_nav_focus(widget, false, key_focus)
}
}
}
impl<'a> std::ops::BitOrAssign<TkAction> for ConfigMgr<'a> {
#[inline]
fn bitor_assign(&mut self, action: TkAction) {
self.ev.send_action(action);
}
Attempts to set a fallback to receive Event::Command
In case a navigation key is pressed (see Command
) but no widget has
navigation focus, then, if a fallback has been set, that widget will
receive the key via Event::Command
.
Only one widget can be a fallback, and the first to set itself wins. This is primarily used to allow scroll-region widgets to respond to navigation keys when no widget has focus.
sourcepub fn new_accel_layer(&mut self, id: WidgetId, alt_bypass: bool)
pub fn new_accel_layer(&mut self, id: WidgetId, alt_bypass: bool)
Add a new accelerator key layer
This method constructs a new “layer” for accelerator keys: any keys
added via EventState::add_accel_keys
to a widget which is a descentant
of (or equal to) id
will only be active when that layer is active.
This method should only be called by parents of a pop-up: layers over the base layer are only activated by an open pop-up.
If alt_bypass
is true, then this layer’s accelerator keys will be
active even without Alt pressed (but only highlighted with Alt pressed).
Examples found in repository?
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
pub fn full_configure(&mut self, shell: &mut dyn ShellWindow, widget: &mut dyn Widget) {
log::debug!(target: "kas_core::event::manager", "full_configure");
self.action.remove(TkAction::RECONFIGURE);
// These are recreated during configure:
self.accel_layers.clear();
self.nav_fallback = None;
self.new_accel_layer(WidgetId::ROOT, false);
shell.size_and_draw_shared(&mut |size, draw_shared| {
let mut mgr = ConfigMgr::new(size, draw_shared, self);
mgr.configure(WidgetId::ROOT, widget);
});
let hover = widget.find_id(self.last_mouse_coord);
self.with(shell, |mgr| mgr.set_hover(hover));
}
sourcepub fn enable_alt_bypass(&mut self, id: &WidgetId, alt_bypass: bool)
pub fn enable_alt_bypass(&mut self, id: &WidgetId, alt_bypass: bool)
Enable alt_bypass
for layer
This may be called by a child widget during configure to enable or
disable alt-bypass for the accel-key layer containing its accel keys.
This allows accelerator keys to be used as shortcuts without the Alt
key held. See also EventState::new_accel_layer
.
sourcepub fn add_accel_keys(&mut self, id: &WidgetId, keys: &[VirtualKeyCode])
pub fn add_accel_keys(&mut self, id: &WidgetId, keys: &[VirtualKeyCode])
Adds an accelerator key for a widget
An accelerator key is a shortcut key able to directly open menus,
activate buttons, etc. A user triggers the key by pressing Alt+Key
,
or (if alt_bypass
is enabled) by simply pressing the key.
The widget with this id
then receives Command::Activate
.
Note that accelerator keys may be automatically derived from labels:
see crate::text::AccelString
.
Accelerator keys are added to the layer with the longest path which is
an ancestor of id
. This usually means that if the widget is part of a
pop-up, the key is only active when that pop-up is open.
See EventState::new_accel_layer
.
This should only be called from Widget::configure
.
sourcepub fn request_char_focus(&mut self, id: WidgetId) -> bool
pub fn request_char_focus(&mut self, id: WidgetId) -> bool
Request character-input focus
Returns true on success or when the widget already had char focus.
Character data is sent to the widget with char focus via
Event::ReceivedCharacter
and Event::Command
.
Char focus implies sel focus (see Self::request_sel_focus
) and
navigation focus.
When char focus is lost, Event::LostCharFocus
is sent.
sourcepub fn request_sel_focus(&mut self, id: WidgetId) -> bool
pub fn request_sel_focus(&mut self, id: WidgetId) -> bool
Request selection focus
Returns true on success or when the widget already had sel focus.
To prevent multiple simultaneous selections (e.g. of text) in the UI,
only widgets with “selection focus” are allowed to select things.
Selection focus is implied by character focus. Event::LostSelFocus
is sent when selection focus is lost; in this case any existing
selection should be cleared.
Selection focus implies navigation focus.
When char focus is lost, Event::LostSelFocus
is sent.
sourcepub fn set_grab_depress(
&mut self,
source: PressSource,
target: Option<WidgetId>
) -> bool
pub fn set_grab_depress(
&mut self,
source: PressSource,
target: Option<WidgetId>
) -> bool
Set a grab’s depress target
When a grab on mouse or touch input is in effect
(EventMgr::grab_press
), the widget owning the grab may set itself
or any other widget as depressed (“pushed down”). Each grab depresses
at most one widget, thus setting a new depress target clears any
existing target. Initially a grab depresses its owner.
This effect is purely visual. A widget is depressed when one or more grabs targets the widget to depress, or when a keyboard binding is used to activate a widget (for the duration of the key-press).
Queues a redraw and returns true
if the depress target changes,
otherwise returns false
.
Examples found in repository?
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
pub fn on_activate<F: FnOnce(&mut EventMgr) -> Response>(
self,
mgr: &mut EventMgr,
id: WidgetId,
f: F,
) -> Response {
match self {
Event::Command(cmd) if cmd.is_activate() => f(mgr),
Event::PressStart { source, coord, .. } if source.is_primary() => {
mgr.grab_press(id, source, coord, GrabMode::Grab, None);
Response::Used
}
Event::PressMove { source, cur_id, .. } => {
let target = if id == cur_id { cur_id } else { None };
mgr.set_grab_depress(source, target);
Response::Used
}
Event::PressEnd {
end_id, success, ..
} if success && id == end_id => f(mgr),
Event::PressEnd { .. } => Response::Used,
_ => Response::Unused,
}
}
sourcepub fn any_pin_on(&self, id: &WidgetId) -> bool
pub fn any_pin_on(&self, id: &WidgetId) -> bool
Returns true if id
or any descendant has a mouse or touch grab
Get the current keyboard navigation focus, if any
This is the widget selected by navigating the UI with the Tab key.
Clear keyboard navigation focus
Examples found in repository?
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
pub fn add_popup(&mut self, popup: crate::Popup) -> Option<WindowId> {
log::trace!(target: "kas_core::event::manager", "add_popup: {popup:?}");
let new_id = &popup.id;
while let Some((_, popup, _)) = self.popups.last() {
if popup.parent.is_ancestor_of(new_id) {
break;
}
let (wid, popup, _old_nav_focus) = self.popups.pop().unwrap();
self.shell.close_window(wid);
self.popup_removed.push((popup.parent, wid));
// Don't restore old nav focus: assume new focus will be set by new popup
}
let opt_id = self.shell.add_popup(popup.clone());
if let Some(id) = opt_id {
let nav_focus = self.nav_focus.clone();
self.popups.push((id, popup, nav_focus));
}
self.clear_nav_focus();
opt_id
}
Set the keyboard navigation focus directly
Normally, Widget::navigable
will be true for the specified
widget, but this is not required, e.g. a ScrollLabel
can receive focus
on text selection with the mouse. (Currently such widgets will receive
events like any other with nav focus, but this may change.)
The target widget, if not already having navigation focus, will receive
Event::NavFocus
with key_focus
as the payload. This boolean should
be true if focussing in response to keyboard input, false if reacting to
mouse or touch input.
Examples found in repository?
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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
fn set_sel_focus(&mut self, wid: WidgetId, char_focus: bool) {
log::trace!("set_sel_focus: wid={wid}, char_focus={char_focus}");
// The widget probably already has nav focus, but anyway:
self.set_nav_focus(wid.clone(), true);
if wid == self.sel_focus {
self.char_focus = self.char_focus || char_focus;
return;
}
if let Some(id) = self.sel_focus.clone() {
if self.char_focus {
// If widget has char focus, this is lost
self.pending.push_back(Pending::LostCharFocus(id.clone()));
}
// Selection focus is lost if another widget receives char focus
self.pending.push_back(Pending::LostSelFocus(id));
}
self.char_focus = char_focus;
self.sel_focus = Some(wid);
}
}
// NOTE: we *want* to store Box<dyn Any + Debug> entries, but Rust doesn't
// support multi-trait objects. An alternative would be to store Box<dyn Message>
// where `trait Message: Any + Debug {}`, but Rust does not support
// trait-object upcast, so we cannot downcast the result.
//
// Workaround: pre-format when the message is *pushed*.
struct Message {
any: Box<dyn Any>,
#[cfg(debug_assertions)]
fmt: String,
}
impl Message {
fn new<M: Any + Debug>(msg: Box<M>) -> Self {
#[cfg(debug_assertions)]
let fmt = format!("{}::{:?}", std::any::type_name::<M>(), &msg);
#[cfg(debug_assertions)]
log::debug!(target: "kas_core::event::manager::messages", "push_msg: {fmt}");
let any = msg;
Message {
#[cfg(debug_assertions)]
fmt,
any,
}
}
fn is<T: 'static>(&self) -> bool {
self.any.is::<T>()
}
fn downcast<T: 'static>(self) -> Result<Box<T>, Box<dyn Any>> {
self.any.downcast::<T>()
}
fn downcast_ref<T: 'static>(&self) -> Option<&T> {
self.any.downcast_ref::<T>()
}
}
impl std::fmt::Debug for Message {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
#[cfg(debug_assertions)]
let r = f.write_str(&self.fmt);
#[cfg(not(debug_assertions))]
let r = f.write_str("[use debug build to see value]");
r
}
}
/// Manager of event-handling and toolkit actions
///
/// An `EventMgr` is in fact a handle around [`EventState`] and [`ShellWindow`]
/// in order to provide a convenient user-interface during event processing.
///
/// `EventMgr` supports [`Deref`] and [`DerefMut`] with target [`EventState`].
///
/// It exposes two interfaces: one aimed at users implementing widgets and UIs
/// and one aimed at shells. The latter is hidden
/// from documentation unless the `internal_doc` feature is enabled.
#[must_use]
pub struct EventMgr<'a> {
state: &'a mut EventState,
shell: &'a mut dyn ShellWindow,
messages: Vec<Message>,
scroll: Scroll,
action: TkAction,
}
impl<'a> Deref for EventMgr<'a> {
type Target = EventState;
fn deref(&self) -> &Self::Target {
self.state
}
}
impl<'a> DerefMut for EventMgr<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.state
}
}
impl<'a> Drop for EventMgr<'a> {
fn drop(&mut self) {
for msg in self.messages.drain(..) {
log::warn!(target: "kas_core::event::manager::messages", "unhandled: {msg:?}");
}
}
}
/// Internal methods
impl<'a> EventMgr<'a> {
fn set_hover(&mut self, w_id: Option<WidgetId>) {
if self.hover != w_id {
log::trace!("set_hover: w_id={w_id:?}");
if let Some(id) = self.hover.take() {
self.pending.push_back(Pending::LostMouseHover(id));
}
self.hover = w_id.clone();
if let Some(id) = w_id {
self.pending.push_back(Pending::MouseHover(id));
}
}
}
fn start_key_event(&mut self, widget: &mut dyn Widget, vkey: VirtualKeyCode, scancode: u32) {
log::trace!(
"start_key_event: widget={}, vkey={vkey:?}, scancode={scancode}",
widget.id()
);
use VirtualKeyCode as VK;
let opt_command = self.config.shortcuts(|s| s.get(self.modifiers, vkey));
if let Some(cmd) = opt_command {
let mut targets = vec![];
let mut send = |_self: &mut Self, id: WidgetId, cmd| -> bool {
if !targets.contains(&id) {
let used = _self.send_event(widget, id.clone(), Event::Command(cmd));
if used {
_self.add_key_depress(scancode, id.clone());
}
targets.push(id);
used
} else {
false
}
};
if self.char_focus || cmd.suitable_for_sel_focus() {
if let Some(id) = self.sel_focus.clone() {
if send(self, id, cmd) {
return;
}
}
}
if !self.modifiers.alt() {
if let Some(id) = self.nav_focus.clone() {
if send(self, id, cmd) {
return;
}
}
}
if let Some(id) = self.popups.last().map(|popup| popup.1.parent.clone()) {
if send(self, id, cmd) {
return;
}
}
if let Some(id) = self.nav_fallback.clone() {
if send(self, id, cmd) {
return;
}
}
}
// Next priority goes to accelerator keys when Alt is held or alt_bypass is true
let mut target = None;
let mut n = 0;
for (i, id) in (self.popups.iter().rev())
.map(|(_, popup, _)| popup.parent.clone())
.chain(std::iter::once(widget.id()))
.enumerate()
{
if let Some(layer) = self.accel_layers.get(&id) {
// but only when Alt is held or alt-bypass is enabled:
if self.modifiers == ModifiersState::ALT
|| layer.0 && self.modifiers == ModifiersState::empty()
{
if let Some(id) = layer.1.get(&vkey).cloned() {
target = Some(id);
n = i;
break;
}
}
}
}
// If we found a key binding below the top layer, we should close everything above
if n > 0 {
let len = self.popups.len();
for i in ((len - n)..len).rev() {
let id = self.popups[i].0;
self.close_window(id, false);
}
}
if let Some(id) = target {
if widget
.find_widget(&id)
.map(|w| w.navigable())
.unwrap_or(false)
{
self.set_nav_focus(id.clone(), true);
}
self.add_key_depress(scancode, id.clone());
self.send_event(widget, id, Event::Command(Command::Activate));
} else if self.config.nav_focus && vkey == VK::Tab {
self.clear_char_focus();
let shift = self.modifiers.shift();
self.next_nav_focus(widget, shift, true);
} else if vkey == VK::Escape {
if let Some(id) = self.popups.last().map(|(id, _, _)| *id) {
self.close_window(id, true);
}
}
}
More examples
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
pub fn close_window(&mut self, id: WindowId, restore_focus: bool) {
if let Some(index) =
self.popups
.iter()
.enumerate()
.find_map(|(i, p)| if p.0 == id { Some(i) } else { None })
{
let mut old_nav_focus = None;
while self.popups.len() > index {
let (wid, popup, onf) = self.popups.pop().unwrap();
self.popup_removed.push((popup.parent, wid));
self.shell.close_window(wid);
old_nav_focus = onf;
}
if !restore_focus {
old_nav_focus = None
}
if let Some(id) = old_nav_focus {
self.set_nav_focus(id, true);
}
// TODO: if popup.id is an ancestor of self.nav_focus then clear
// focus if not setting (currently we cannot test this)
}
self.shell.close_window(id);
}
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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
pub fn handle_winit(&mut self, widget: &mut dyn Widget, event: winit::event::WindowEvent) {
use winit::event::{ElementState, MouseScrollDelta, TouchPhase, WindowEvent::*};
match event {
CloseRequested => self.send_action(TkAction::CLOSE),
/* Not yet supported: see #98
DroppedFile(path) => ,
HoveredFile(path) => ,
HoveredFileCancelled => ,
*/
ReceivedCharacter(c) => {
if let Some(id) = self.char_focus() {
// Filter out control codes (Unicode 5.11). These may be
// generated from combinations such as Ctrl+C by some other
// layer. We use our own shortcut system instead.
if c >= '\x20' && !('\x7f'..='\u{9f}').contains(&c) {
let event = Event::ReceivedCharacter(c);
self.send_event(widget, id, event);
}
}
}
Focused(state) => {
self.window_has_focus = state;
if state {
// Required to restart theme animations
self.send_action(TkAction::REDRAW);
} else {
// Window focus lost: close all popups
while let Some(id) = self.popups.last().map(|(id, _, _)| *id) {
self.close_window(id, true);
}
}
}
KeyboardInput {
input,
is_synthetic,
..
} => {
if input.state == ElementState::Pressed && !is_synthetic {
if let Some(vkey) = input.virtual_keycode {
self.start_key_event(widget, vkey, input.scancode);
}
} else if input.state == ElementState::Released {
self.end_key_event(input.scancode);
}
}
ModifiersChanged(state) => {
if state.alt() != self.modifiers.alt() {
// This controls drawing of accelerator key indicators
self.send_action(TkAction::REDRAW);
}
self.modifiers = state;
}
CursorMoved { position, .. } => {
self.last_click_button = FAKE_MOUSE_BUTTON;
let coord = position.cast_approx();
// Update hovered widget
let cur_id = widget.find_id(coord);
let delta = coord - self.last_mouse_coord;
self.set_hover(cur_id.clone());
if let Some(grab) = self.state.mouse_grab.as_mut() {
if grab.mode == GrabMode::Grab {
grab.cur_id = cur_id;
grab.coord = coord;
grab.delta += delta;
} else if let Some(pan) =
self.state.pan_grab.get_mut(usize::conv(grab.pan_grab.0))
{
pan.coords[usize::conv(grab.pan_grab.1)].1 = coord;
}
} else if let Some(id) = self.popups.last().map(|(_, p, _)| p.parent.clone()) {
let source = PressSource::Mouse(FAKE_MOUSE_BUTTON, 0);
let event = Event::PressMove {
source,
cur_id,
coord,
delta,
};
self.send_event(widget, id, event);
} else {
// We don't forward move events without a grab
}
self.last_mouse_coord = coord;
}
// CursorEntered { .. },
CursorLeft { .. } => {
self.last_click_button = FAKE_MOUSE_BUTTON;
if self.mouse_grab().is_none() {
// If there's a mouse grab, we will continue to receive
// coordinates; if not, set a fake coordinate off the window
self.last_mouse_coord = Coord(-1, -1);
self.set_hover(None);
}
}
MouseWheel { delta, .. } => {
if let Some((id, event)) = self.mouse_grab().and_then(|g| g.flush_move()) {
self.send_event(widget, id, event);
}
self.last_click_button = FAKE_MOUSE_BUTTON;
let event = Event::Scroll(match delta {
MouseScrollDelta::LineDelta(x, y) => ScrollDelta::LineDelta(x, y),
MouseScrollDelta::PixelDelta(pos) => {
// The delta is given as a PhysicalPosition, so we need
// to convert to our vector type (Offset) here.
let coord = Coord::conv_approx(pos);
ScrollDelta::PixelDelta(coord.cast())
}
});
if let Some(id) = self.hover.clone() {
self.send_event(widget, id, event);
}
}
MouseInput { state, button, .. } => {
if let Some((id, event)) = self.mouse_grab().and_then(|g| g.flush_move()) {
self.send_event(widget, id, event);
}
let coord = self.last_mouse_coord;
if state == ElementState::Pressed {
let now = Instant::now();
if button != self.last_click_button || self.last_click_timeout < now {
self.last_click_button = button;
self.last_click_repetitions = 0;
}
self.last_click_repetitions += 1;
self.last_click_timeout = now + DOUBLE_CLICK_TIMEOUT;
}
if let Some(grab) = self.remove_mouse_grab() {
if grab.mode == GrabMode::Grab {
// Mouse grab active: send events there
// Note: any button release may end the grab (intended).
let event = Event::PressEnd {
source: PressSource::Mouse(grab.button, grab.repetitions),
end_id: self.hover.clone(),
coord,
success: state == ElementState::Released,
};
self.send_event(widget, grab.start_id, event);
}
// Pan events do not receive Start/End notifications
}
if state == ElementState::Pressed {
if let Some(start_id) = self.hover.clone() {
// No mouse grab but have a hover target
if self.config.mouse_nav_focus() {
if let Some(w) = widget.find_widget(&start_id) {
if w.navigable() {
self.set_nav_focus(w.id(), false);
}
}
}
}
let source = PressSource::Mouse(button, self.last_click_repetitions);
let event = Event::PressStart {
source,
start_id: self.hover.clone(),
coord,
};
self.send_popup_first(widget, self.hover.clone(), event);
}
}
// TouchpadPressure { pressure: f32, stage: i64, },
// AxisMotion { axis: AxisId, value: f64, },
Touch(touch) => {
let source = PressSource::Touch(touch.id);
let coord = touch.location.cast_approx();
match touch.phase {
TouchPhase::Started => {
let start_id = widget.find_id(coord);
if let Some(id) = start_id.as_ref() {
if self.config.touch_nav_focus() {
if let Some(w) = widget.find_widget(id) {
if w.navigable() {
self.set_nav_focus(w.id(), false);
}
}
}
let event = Event::PressStart {
source,
start_id: start_id.clone(),
coord,
};
self.send_popup_first(widget, start_id, event);
}
}
TouchPhase::Moved => {
let cur_id = widget.find_id(coord);
let mut redraw = false;
let mut pan_grab = None;
if let Some(grab) = self.get_touch(touch.id) {
if grab.mode == GrabMode::Grab {
// Only when 'depressed' status changes:
redraw = grab.cur_id != cur_id
&& (grab.start_id == grab.cur_id || grab.start_id == cur_id);
grab.cur_id = cur_id;
grab.coord = coord;
} else {
pan_grab = Some(grab.pan_grab);
}
}
if redraw {
self.send_action(TkAction::REDRAW);
} else if let Some(pan_grab) = pan_grab {
if usize::conv(pan_grab.1) < MAX_PAN_GRABS {
if let Some(pan) = self.pan_grab.get_mut(usize::conv(pan_grab.0)) {
pan.coords[usize::conv(pan_grab.1)].1 = coord;
}
}
}
}
ev @ (TouchPhase::Ended | TouchPhase::Cancelled) => {
if let Some(mut grab) = self.remove_touch(touch.id) {
if let Some((id, event)) = grab.flush_move() {
self.send_event(widget, id, event);
}
if grab.mode == GrabMode::Grab {
let event = Event::PressEnd {
source,
end_id: grab.cur_id.clone(),
coord,
success: ev == TouchPhase::Ended,
};
self.send_event(widget, grab.start_id, event);
}
}
}
}
}
_ => (),
}
}
sourcepub fn set_cursor_icon(&mut self, icon: CursorIcon)
pub fn set_cursor_icon(&mut self, icon: CursorIcon)
Set the cursor icon
This is normally called when handling Event::MouseHover
. In other
cases, calling this method may be ineffective. The cursor is
automatically “unset” when the widget is no longer hovered.
If a mouse grab (EventMgr::grab_press
) is active, its icon takes precedence.
Trait Implementations§
source§impl BitOrAssign<TkAction> for EventState
impl BitOrAssign<TkAction> for EventState
source§fn bitor_assign(&mut self, action: TkAction)
fn bitor_assign(&mut self, action: TkAction)
|=
operation. Read more