pub struct WidgetId(_);
Expand description
Widget identifier
All widgets are assigned an identifier which is unique within the window. This type may be tested for equality and order and may be iterated over as a “path” of “key” values.
Formatting a WidgetId
via Display
prints the the path, for example
#1290a4
. Here, #
represents the root; each following hexadecimal digit
represents a path component except that digits 8-f
are combined with the
following digit(s). Hence, the above path has components 1
, 2
, 90
,
a4
. To interpret these values, first subtract 8 from each digit but the
last digit, then read as base-8: [1, 2, 8, 20]
.
This type is small (64-bit) and non-zero: Option<WidgetId>
has the same
size as WidgetId
. It is also very cheap to Clone
: usually only one if
check, and in the worst case a pointer dereference and ref-count increment.
Paths up to 14 digits long (as printed) are represented internally;
beyond this limit a reference-counted stack allocation is used.
WidgetId
is neither Send
nor Sync
.
Identifiers are assigned when configured and when re-configured
(via TkAction::RECONFIGURE
or ConfigMgr::configure
).
In most cases values are persistent but this is not guaranteed (e.g.
inserting or removing a child from a List
widget will affect the
identifiers of all following children). View-widgets assign path components
based on the data key, thus possibly making identifiers persistent.
Implementations§
source§impl WidgetId
impl WidgetId
sourcepub fn is_valid(&self) -> bool
pub fn is_valid(&self) -> bool
Is the identifier valid?
Default-constructed identifiers are invalid. Comparing invalid ids is considered a logic error and thus will panic in debug builds. This method may be used to check an identifier’s validity.
sourcepub fn iter(&self) -> WidgetPathIter<'_> ⓘ
pub fn iter(&self) -> WidgetPathIter<'_> ⓘ
Iterate over path components
sourcepub fn is_ancestor_of(&self, id: &Self) -> bool
pub fn is_ancestor_of(&self, id: &Self) -> bool
Returns true if self
equals id
or if id
is a descendant of self
Examples found in repository?
More examples
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
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
}
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
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
}
}
pub fn iter_keys_after(&self, id: &Self) -> WidgetPathIter<'_> ⓘ
sourcepub fn next_key_after(&self, id: &Self) -> Option<usize>
pub fn next_key_after(&self, id: &Self) -> Option<usize>
Get first key in path of self
path after id
If the path of self
starts with the path of id
(id.is_ancestor_of(self)
) then this returns the next key in
self
’s path (if any). Otherwise, this returns None
.
sourcepub fn parent(&self) -> Option<WidgetId>
pub fn parent(&self) -> Option<WidgetId>
Get the parent widget’s identifier, if not root
Note: there is no guarantee that Self::as_u64
on the result will
match that of the original parent identifier.
sourcepub fn make_child(&self, key: usize) -> Self
pub fn make_child(&self, key: usize) -> Self
Make an identifier for the child with the given key
Note: this is not a getter method. Calling multiple times with the same
key
may or may not return the same value!
sourcepub fn as_u64(&self) -> u64
pub fn as_u64(&self) -> u64
Convert to a u64
This value should not be interpreted, except as follows:
- it is guaranteed non-zero
- it may be passed to
Self::opt_from_u64
- comparing two
u64
values generated this way will mostly work as an equality check of the sourceWidgetId
, but can return false negatives (only if each id was generated through separate calls toSelf::make_child
)
sourcepub fn opt_to_u64(id: Option<&WidgetId>) -> u64
pub fn opt_to_u64(id: Option<&WidgetId>) -> u64
Convert Option<WidgetId>
to u64
This value should not be interpreted, except as follows:
- it is zero if and only if
id == None
- it may be passed to
Self::opt_from_u64
- comparing two
u64
values generated this way will mostly work as an equality check of the sourceWidgetId
, but can return false negatives (only if each id was generated through separate calls toSelf::make_child
)
sourcepub unsafe fn opt_from_u64(n: u64) -> Option<WidgetId>
pub unsafe fn opt_from_u64(n: u64) -> Option<WidgetId>
Convert u64
to Option<WidgetId>
Returns None
if and only if n == 0
.
Safety
This may only be called with the output of Self::as_u64
,
Self::opt_from_u64
, or 0
.
This is unsafe since Self
has a heap-allocated variant. If n
looks
like a heap-allocated variant but is not the result of Self::as_u64
,
or it is but the source instance of Self
and all clones have been
destroyed, then some operations on the result of this method will
attempt to dereference an invalid pointer.
sourcepub fn iter_path(&self) -> impl Iterator<Item = usize> + '_
pub fn iter_path(&self) -> impl Iterator<Item = usize> + '_
Construct an iterator, returning indices
This represents the widget’s “path” from the root (window).
Examples found in repository?
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
fn eq(&self, rhs: &Self) -> bool {
match (self.0.get(), rhs.0.get()) {
(Variant::Invalid, _) | (_, Variant::Invalid) => panic!("WidgetId::eq: invalid id"),
(Variant::Int(x), Variant::Int(y)) => x == y,
_ => self.iter_path().eq(rhs.iter_path()),
}
}
}
impl Eq for WidgetId {}
impl PartialOrd for WidgetId {
fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
Some(self.cmp(rhs))
}
}
impl Ord for WidgetId {
fn cmp(&self, rhs: &Self) -> Ordering {
match (self.0.get(), rhs.0.get()) {
(Variant::Invalid, _) | (_, Variant::Invalid) => panic!("WidgetId::cmp: invalid id"),
(Variant::Int(x), Variant::Int(y)) => x.cmp(&y),
_ => self.iter_path().cmp(rhs.iter_path()),
}
}
Trait Implementations§
source§impl Ord for WidgetId
impl Ord for WidgetId
source§impl<'a> PartialEq<&'a Option<WidgetId>> for WidgetId
impl<'a> PartialEq<&'a Option<WidgetId>> for WidgetId
source§impl<'a> PartialEq<&'a WidgetId> for WidgetId
impl<'a> PartialEq<&'a WidgetId> for WidgetId
source§impl<'a> PartialEq<Option<&'a WidgetId>> for WidgetId
impl<'a> PartialEq<Option<&'a WidgetId>> for WidgetId
source§impl PartialEq<Option<WidgetId>> for WidgetId
impl PartialEq<Option<WidgetId>> for WidgetId
source§impl PartialOrd<WidgetId> for WidgetId
impl PartialOrd<WidgetId> for WidgetId
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
operator. Read moreimpl Eq for WidgetId
Auto Trait Implementations§
impl RefUnwindSafe for WidgetId
impl !Send for WidgetId
impl !Sync for WidgetId
impl Unpin for WidgetId
impl UnwindSafe for WidgetId
Blanket Implementations§
source§impl<S, T> CastApprox<T> for Swhere
T: ConvApprox<S>,
impl<S, T> CastApprox<T> for Swhere
T: ConvApprox<S>,
source§fn try_cast_approx(self) -> Result<T, Error>
fn try_cast_approx(self) -> Result<T, Error>
source§fn cast_approx(self) -> T
fn cast_approx(self) -> T
source§impl<S, T> CastFloat<T> for Swhere
T: ConvFloat<S>,
impl<S, T> CastFloat<T> for Swhere
T: ConvFloat<S>,
source§fn cast_trunc(self) -> T
fn cast_trunc(self) -> T
source§fn cast_nearest(self) -> T
fn cast_nearest(self) -> T
source§fn cast_floor(self) -> T
fn cast_floor(self) -> T
source§impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.