1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 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
// Copyright 2020 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! The context types that are passed into various widget methods. use std::ops::{Deref, DerefMut}; use std::time::Instant; use log; use crate::core::{BaseState, CommandQueue, FocusChange}; use crate::piet::Piet; use crate::piet::RenderContext; use crate::{ Affine, Command, Cursor, Insets, Rect, Size, Target, Text, TimerToken, WidgetId, WindowHandle, WindowId, }; /// A mutable context provided to event handling methods of widgets. /// /// Widgets should call [`request_paint`] whenever an event causes a change /// in the widget's appearance, to schedule a repaint. /// /// [`request_paint`]: #method.request_paint pub struct EventCtx<'a> { // Note: there's a bunch of state that's just passed down, might // want to group that into a single struct. pub(crate) cursor: &'a mut Option<Cursor>, /// Commands submitted to be run after this event. pub(crate) command_queue: &'a mut CommandQueue, pub(crate) window_id: WindowId, pub(crate) window: &'a WindowHandle, pub(crate) base_state: &'a mut BaseState, pub(crate) focus_widget: Option<WidgetId>, pub(crate) had_active: bool, pub(crate) is_handled: bool, pub(crate) is_root: bool, } /// A mutable context provided to the [`lifecycle`] method on widgets. /// /// Certain methods on this context are only meaningful during the handling of /// specific lifecycle events; for instance [`register_child`] /// should only be called while handling [`LifeCycle::WidgetAdded`]. /// /// [`lifecycle`]: trait.Widget.html#tymethod.lifecycle /// [`register_child`]: #method.register_child /// [`LifeCycle::WidgetAdded`]: enum.LifeCycle.html#variant.WidgetAdded pub struct LifeCycleCtx<'a> { pub(crate) command_queue: &'a mut CommandQueue, pub(crate) base_state: &'a mut BaseState, pub(crate) window_id: WindowId, } /// A mutable context provided to data update methods of widgets. /// /// Widgets should call [`request_paint`] whenever a data change causes a change /// in the widget's appearance, to schedule a repaint. /// /// [`request_paint`]: #method.request_paint pub struct UpdateCtx<'a> { pub(crate) window: &'a WindowHandle, // Discussion: we probably want to propagate more fine-grained // invalidations, which would mean a structure very much like // `EventCtx` (and possibly using the same structure). But for // now keep it super-simple. pub(crate) window_id: WindowId, pub(crate) base_state: &'a mut BaseState, } /// A context provided to layout handling methods of widgets. /// /// As of now, the main service provided is access to a factory for /// creating text layout objects, which are likely to be useful /// during widget layout. pub struct LayoutCtx<'a, 'b: 'a> { pub(crate) text_factory: &'a mut Text<'b>, pub(crate) paint_insets: Insets, pub(crate) window_id: WindowId, } /// Z-order paint operations with transformations. pub(crate) struct ZOrderPaintOp { pub z_index: u32, pub paint_func: Box<dyn FnOnce(&mut PaintCtx) + 'static>, pub transform: Affine, } /// A context passed to paint methods of widgets. /// /// Widgets paint their appearance by calling methods on the /// `render_ctx`, which PaintCtx derefs to for convenience. /// This struct is expected to grow, for example to include the /// "damage region" indicating that only a subset of the entire /// widget hierarchy needs repainting. pub struct PaintCtx<'a, 'b: 'a> { /// The render context for actually painting. pub render_ctx: &'a mut Piet<'b>, pub window_id: WindowId, /// The z-order paint operations. pub(crate) z_ops: Vec<ZOrderPaintOp>, /// The currently visible region. pub(crate) region: Region, pub(crate) base_state: &'a BaseState, pub(crate) focus_widget: Option<WidgetId>, } /// A region of a widget, generally used to describe what needs to be drawn. #[derive(Debug, Clone)] pub struct Region(Rect); impl<'a> EventCtx<'a> { #[deprecated(since = "0.5.0", note = "use request_paint instead")] pub fn invalidate(&mut self) { // Note: for the current functionality, we could shortcut and just // request an invalidate on the window. But when we do fine-grained // invalidation, we'll want to compute the invalidation region, and // that needs to be propagated (with, likely, special handling for // scrolling). self.base_state.needs_inval = true; } /// Request a [`paint`] pass. /// /// [`paint`]: trait.Widget.html#tymethod.paint pub fn request_paint(&mut self) { self.base_state.needs_inval = true; } /// Request a layout pass. /// /// A Widget's [`layout`] method is always called when the widget tree /// changes, or the window is resized. /// /// If your widget would like to have layout called at any other time, /// (such as if it would like to change the layout of children in /// response to some event) it must call this method. /// /// [`layout`]: trait.Widget.html#tymethod.layout pub fn request_layout(&mut self) { self.base_state.needs_layout = true; self.base_state.needs_inval = true; } /// Indicate that your children have changed. /// /// Widgets must call this method after adding a new child. pub fn children_changed(&mut self) { self.base_state.children_changed = true; } /// Get an object which can create text layouts. pub fn text(&mut self) -> Text { self.window.text() } /// Set the cursor icon. /// /// Call this when handling a mouse move event, to set the cursor for the /// widget. A container widget can safely call this method, then recurse /// to its children, as a sequence of calls within an event propagation /// only has the effect of the last one (ie no need to worry about /// flashing). /// /// This method is expected to be called mostly from the [`MouseMoved`] /// event handler, but can also be called in response to other events, /// for example pressing a key to change the behavior of a widget. /// /// [`MouseMoved`]: enum.Event.html#variant.MouseDown pub fn set_cursor(&mut self, cursor: &Cursor) { *self.cursor = Some(cursor.clone()); } /// Set the "active" state of the widget. /// /// See [`EventCtx::is_active`](struct.EventCtx.html#method.is_active). pub fn set_active(&mut self, active: bool) { self.base_state.is_active = active; // TODO: plumb mouse grab through to platform (through druid-shell) } /// The "hot" (aka hover) status of a widget. /// /// A widget is "hot" when the mouse is hovered over it. Widgets will /// often change their appearance as a visual indication that they /// will respond to mouse interaction. /// /// The hot status is computed from the widget's layout rect. In a /// container hierarchy, all widgets with layout rects containing the /// mouse position have hot status. /// /// Discussion: there is currently some confusion about whether a /// widget can be considered hot when some other widget is active (for /// example, when clicking to one widget and dragging to the next). /// The documentation should clearly state the resolution. pub fn is_hot(&self) -> bool { self.base_state.is_hot } /// The active status of a widget. /// /// Active status generally corresponds to a mouse button down. Widgets /// with behavior similar to a button will call [`set_active`] on mouse /// down and then up. /// /// When a widget is active, it gets mouse events even when the mouse /// is dragged away. /// /// [`set_active`]: struct.EventCtx.html#method.set_active pub fn is_active(&self) -> bool { self.base_state.is_active } /// Returns a reference to the current `WindowHandle`. pub fn window(&self) -> &WindowHandle { &self.window } /// Set the event as "handled", which stops its propagation to other /// widgets. pub fn set_handled(&mut self) { self.is_handled = true; } /// Determine whether the event has been handled by some other widget. pub fn is_handled(&self) -> bool { self.is_handled } /// The focus status of a widget. /// /// Focus means that the widget receives keyboard events. /// /// A widget can request focus using the [`request_focus`] method. /// This will generally result in a separate event propagation of /// a `FocusChanged` method, including sending `false` to the previous /// widget that held focus. /// /// Only one leaf widget at a time has focus. However, in a container /// hierarchy, all ancestors of that leaf widget are also invoked with /// `FocusChanged(true)`. /// /// Discussion question: is "is_focused" a better name? /// /// [`request_focus`]: struct.EventCtx.html#method.request_focus pub fn has_focus(&self) -> bool { let is_child = self .focus_widget .map(|id| self.base_state.children.contains(&id)) .unwrap_or(false); is_child || self.focus_widget == Some(self.widget_id()) } /// The (leaf) focus status of a widget. See [`has_focus`]. /// /// [`has_focus`]: struct.EventCtx.html#method.has_focus pub fn is_focused(&self) -> bool { self.focus_widget == Some(self.widget_id()) } /// Request keyboard focus. /// /// See [`has_focus`] for more information. /// /// [`has_focus`]: struct.EventCtx.html#method.has_focus pub fn request_focus(&mut self) { self.base_state.request_focus = Some(FocusChange::Focus(self.widget_id())); } /// Transfer focus to the next focusable widget. /// /// This should only be called by a widget that currently has focus. pub fn focus_next(&mut self) { if self.focus_widget == Some(self.widget_id()) { self.base_state.request_focus = Some(FocusChange::Next); } else { log::warn!("focus_next can only be called by the currently focused widget"); } } /// Transfer focus to the previous focusable widget. /// /// This should only be called by a widget that currently has focus. pub fn focus_prev(&mut self) { if self.focus_widget == Some(self.widget_id()) { self.base_state.request_focus = Some(FocusChange::Previous); } else { log::warn!("focus_prev can only be called by the currently focused widget"); } } /// Give up focus. /// /// This should only be called by a widget that currently has focus. pub fn resign_focus(&mut self) { if self.focus_widget == Some(self.widget_id()) { self.base_state.request_focus = Some(FocusChange::Resign); } else { log::warn!("resign_focus can only be called by the currently focused widget"); } } /// Request an animation frame. pub fn request_anim_frame(&mut self) { self.base_state.request_anim = true; self.base_state.needs_inval = true; } /// Request a timer event. /// /// The return value is a token, which can be used to associate the /// request with the event. pub fn request_timer(&mut self, deadline: Instant) -> TimerToken { self.base_state.request_timer = true; self.window.request_timer(deadline) } /// The layout size. /// /// This is the layout size as ultimately determined by the parent /// container, on the previous layout pass. /// /// Generally it will be the same as the size returned by the child widget's /// [`layout`] method. /// /// [`layout`]: trait.Widget.html#tymethod.layout pub fn size(&self) -> Size { self.base_state.size() } /// Submit a [`Command`] to be run after this event is handled. /// /// Commands are run in the order they are submitted; all commands /// submitted during the handling of an event are executed before /// the [`update`] method is called. /// /// [`Command`]: struct.Command.html /// [`update`]: trait.Widget.html#tymethod.update pub fn submit_command( &mut self, command: impl Into<Command>, target: impl Into<Option<Target>>, ) { let target = target.into().unwrap_or_else(|| self.window_id.into()); self.command_queue.push_back((target, command.into())) } /// Get the window id. pub fn window_id(&self) -> WindowId { self.window_id } /// get the `WidgetId` of the current widget. pub fn widget_id(&self) -> WidgetId { self.base_state.id } pub(crate) fn make_lifecycle_ctx(&mut self) -> LifeCycleCtx { LifeCycleCtx { command_queue: self.command_queue, base_state: self.base_state, window_id: self.window_id, } } } impl<'a> LifeCycleCtx<'a> { #[deprecated(since = "0.5.0", note = "use request_paint instead")] pub fn invalidate(&mut self) { self.base_state.needs_inval = true; } /// Request a [`paint`] pass. /// /// [`paint`]: trait.Widget.html#tymethod.paint pub fn request_paint(&mut self) { self.base_state.needs_inval = true; } /// Request layout. /// /// See [`EventCtx::request_layout`] for more information. /// /// [`EventCtx::request_layout`]: struct.EventCtx.html#method.request_layout pub fn request_layout(&mut self) { self.base_state.needs_layout = true; self.base_state.needs_inval = true; } /// Returns the current widget's `WidgetId`. pub fn widget_id(&self) -> WidgetId { self.base_state.id } /// Registers a child widget. /// /// This should only be called in response to a `LifeCycle::WidgetAdded` event. /// /// In general, you should not need to call this method; it is handled by /// the `WidgetPod`. pub fn register_child(&mut self, child_id: WidgetId) { self.base_state.children.add(&child_id); } /// Register this widget to be eligile to accept focus automatically. pub fn register_for_focus(&mut self) { self.base_state.focus_chain.push(self.widget_id()); } /// Indicate that your children have changed. /// /// Widgets must call this method after adding a new child. pub fn children_changed(&mut self) { self.base_state.children_changed = true; } /// Request an animation frame. pub fn request_anim_frame(&mut self) { self.base_state.request_anim = true; } /// Submit a [`Command`] to be run after this event is handled. /// /// Commands are run in the order they are submitted; all commands /// submitted during the handling of an event are executed before /// the [`update`] method is called. /// /// [`Command`]: struct.Command.html /// [`update`]: trait.Widget.html#tymethod.update pub fn submit_command( &mut self, command: impl Into<Command>, target: impl Into<Option<Target>>, ) { let target = target.into().unwrap_or_else(|| self.window_id.into()); self.command_queue.push_back((target, command.into())) } } impl<'a> UpdateCtx<'a> { #[deprecated(since = "0.5.0", note = "use request_paint instead")] pub fn invalidate(&mut self) { self.base_state.needs_inval = true; } /// Request a [`paint`] pass. /// /// [`paint`]: trait.Widget.html#tymethod.paint pub fn request_paint(&mut self) { self.base_state.needs_inval = true; } /// Request layout. /// /// See [`EventCtx::request_layout`] for more information. /// /// [`EventCtx::request_layout`]: struct.EventCtx.html#method.request_layout pub fn request_layout(&mut self) { self.base_state.needs_layout = true; self.base_state.needs_inval = true; } /// Indicate that your children have changed. /// /// Widgets must call this method after adding a new child. pub fn children_changed(&mut self) { self.base_state.children_changed = true; } /// Get an object which can create text layouts. pub fn text(&mut self) -> Text { self.window.text() } /// Returns a reference to the current `WindowHandle`. //TODO: can we delete this? where is it used? pub fn window(&self) -> &WindowHandle { &self.window } /// Get the window id. pub fn window_id(&self) -> WindowId { self.window_id } /// get the `WidgetId` of the current widget. pub fn widget_id(&self) -> WidgetId { self.base_state.id } } impl<'a, 'b> LayoutCtx<'a, 'b> { /// Get an object which can create text layouts. pub fn text(&mut self) -> &mut Text<'b> { &mut self.text_factory } /// Get the window id. pub fn window_id(&self) -> WindowId { self.window_id } /// Set explicit paint [`Insets`] for this widget. /// /// You are not required to set explicit paint bounds unless you need /// to paint outside of your layout bounds. In this case, the argument /// should be an [`Insets`] struct that indicates where your widget /// needs to overpaint, relative to its bounds. /// /// For more information, see [`WidgetPod::paint_insets`]. /// /// [`Insets`]: struct.Insets.html /// [`WidgetPod::paint_insets`]: struct.WidgetPod.html#method.paint_insets pub fn set_paint_insets(&mut self, insets: impl Into<Insets>) { self.paint_insets = insets.into().nonnegative(); } } impl<'a, 'b: 'a> PaintCtx<'a, 'b> { /// get the `WidgetId` of the current widget. pub fn widget_id(&self) -> WidgetId { self.base_state.id } /// Query the "hot" state of the widget. /// /// See [`EventCtx::is_hot`](struct.EventCtx.html#method.is_hot) for /// additional information. pub fn is_hot(&self) -> bool { self.base_state.is_hot } /// Query the "active" state of the widget. /// /// See [`EventCtx::is_active`](struct.EventCtx.html#method.is_active) for /// additional information. pub fn is_active(&self) -> bool { self.base_state.is_active } /// Returns the layout size of the current widget. /// /// See [`EventCtx::size`](struct.EventCtx.html#method.size) for /// additional information. pub fn size(&self) -> Size { self.base_state.size() } /// Query the focus state of the widget. /// /// This is true only if this widget has focus. pub fn is_focused(&self) -> bool { self.focus_widget == Some(self.widget_id()) } /// The focus status of a widget. /// /// See [`has_focus`](struct.EventCtx.html#method.has_focus). pub fn has_focus(&self) -> bool { let is_child = self .focus_widget .map(|id| self.base_state.children.contains(&id)) .unwrap_or(false); is_child || self.focus_widget == Some(self.widget_id()) } /// Returns the currently visible [`Region`]. /// /// [`Region`]: struct.Region.html #[inline] pub fn region(&self) -> &Region { &self.region } /// Creates a temporary `PaintCtx` with a new visible region, and calls /// the provided function with that `PaintCtx`. /// /// This is used by containers to ensure that their children have the correct /// visible region given their layout. pub fn with_child_ctx(&mut self, region: impl Into<Region>, f: impl FnOnce(&mut PaintCtx)) { let mut child_ctx = PaintCtx { render_ctx: self.render_ctx, base_state: self.base_state, z_ops: Vec::new(), window_id: self.window_id, focus_widget: self.focus_widget, region: region.into(), }; f(&mut child_ctx); self.z_ops.append(&mut child_ctx.z_ops); } /// Saves the current context, executes the closures, and restores the context. /// /// This is useful if you would like to transform or clip or otherwise /// modify the drawing context but do not want that modification to /// effect other widgets. /// /// # Examples /// /// ``` /// # use druid::{Env, PaintCtx, RenderContext, theme}; /// # struct T; /// # impl T { /// fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, env: &Env) { /// let clip_rect = ctx.size().to_rect().inset(5.0); /// ctx.with_save(|ctx| { /// ctx.clip(clip_rect); /// ctx.stroke(clip_rect, &env.get(theme::PRIMARY_DARK), 5.0); /// }); /// } /// # } /// ``` pub fn with_save(&mut self, f: impl FnOnce(&mut PaintCtx)) { if let Err(e) = self.render_ctx.save() { log::error!("Failed to save RenderContext: '{}'", e); return; } f(self); if let Err(e) = self.render_ctx.restore() { log::error!("Failed to restore RenderContext: '{}'", e); } } /// Allows to specify order for paint operations. /// /// Larger `z_index` indicate that an operation will be executed later. pub fn paint_with_z_index( &mut self, z_index: u32, paint_func: impl FnOnce(&mut PaintCtx) + 'static, ) { let current_transform = self.render_ctx.current_transform(); self.z_ops.push(ZOrderPaintOp { z_index, paint_func: Box::new(paint_func), transform: current_transform, }) } } impl Region { /// Returns the smallest `Rect` that encloses the entire region. pub fn to_rect(&self) -> Rect { self.0 } /// Returns `true` if `self` intersects with `other`. #[inline] pub fn intersects(&self, other: Rect) -> bool { self.0.intersect(other).area() > 0. } } impl From<Rect> for Region { fn from(src: Rect) -> Region { Region(src) } } impl<'a, 'b: 'a> Deref for PaintCtx<'a, 'b> { type Target = Piet<'b>; fn deref(&self) -> &Self::Target { self.render_ctx } } impl<'a, 'b: 'a> DerefMut for PaintCtx<'a, 'b> { fn deref_mut(&mut self) -> &mut Self::Target { self.render_ctx } }