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
//! Flutter counterpart: `widgets/magnifier.dart` (`MagnifierBuilder`,
//! `MagnifierInfo`, `TextMagnifierConfiguration`, `MagnifierController`).
//!
//! `RawMagnifier`, `MagnifierDecoration`, and the decorative magnifier widgets wait.
use std::fmt::{self, Debug};
use std::rc::Rc;
use waft_animation::AnimationController;
use waft_embedder::{Offset, Rect};
use waft_foundation::{App, Handle, Listener, ValueNotifier};
use waft_scheduler::TickerFuture;
use crate::framework::{BuildContext, WidgetRef};
use crate::widgets::basic::WidgetBuilder;
use crate::widgets::overlay::{Overlay, OverlayEntry};
/// Signature for a builder that builds a [`WidgetRef`] with a [`MagnifierController`].
///
/// The builder is called exactly once per magnifier.
///
/// If the `controller` parameter's [`MagnifierController::animation_controller`]
/// field is set (by the builder) to an [`AnimationController`], the
/// [`MagnifierController`] will drive the animation during entry and exit.
///
/// The `magnifier_info` parameter is updated with new [`MagnifierInfo`] instances
/// during the lifetime of the built magnifier, e.g. as the user moves their
/// finger around the text field.
pub type MagnifierBuilder = Rc<
dyn Fn(
&mut App,
BuildContext,
Handle<MagnifierController>,
Handle<ValueNotifier<MagnifierInfo>>,
) -> Option<WidgetRef>,
>;
/// A data class that contains the geometry information of text layouts
/// and selection gestures, used to position magnifiers.
#[derive(Clone, Copy, PartialEq)]
pub struct MagnifierInfo {
/// The offset of the gesture position that the magnifier should be shown at.
pub global_gesture_position: Offset,
/// The rect of the current line the magnifier should be shown at, without
/// taking into account any padding of the field; only the position of the
/// first and last character.
pub current_line_boundaries: Rect,
/// The rect of the handle that the magnifier should follow.
pub caret_rect: Rect,
/// The bounds of the entire text field that the magnifier is bound to.
pub field_bounds: Rect,
}
impl MagnifierInfo {
/// Constructs a [`MagnifierInfo`] from provided geometry values.
pub const fn new(
global_gesture_position: Offset,
caret_rect: Rect,
field_bounds: Rect,
current_line_boundaries: Rect,
) -> MagnifierInfo {
MagnifierInfo {
global_gesture_position,
caret_rect,
field_bounds,
current_line_boundaries,
}
}
/// Const [`MagnifierInfo`] with all values set to 0.
pub const EMPTY: MagnifierInfo = MagnifierInfo {
global_gesture_position: Offset::ZERO,
caret_rect: Rect::ZERO,
current_line_boundaries: Rect::ZERO,
field_bounds: Rect::ZERO,
};
}
impl Debug for MagnifierInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"MagnifierInfo(position: {:?}, line: {:?}, caret: {:?}, field: {:?})",
self.global_gesture_position,
self.current_line_boundaries,
self.caret_rect,
self.field_bounds
)
}
}
/// A configuration object for a magnifier (e.g. in a text field).
///
/// In general, most features of the magnifier can be configured by controlling
/// the widgets built by the [`magnifier_builder`](Self::magnifier_builder).
#[derive(Clone)]
pub struct TextMagnifierConfiguration {
magnifier_builder: Option<MagnifierBuilder>,
/// Whether a magnifier should show the text editing handles or not.
///
/// This flag is used by `SelectionOverlay.showMagnifier` to control the order
/// of layers in the rendering; specifically, whether to place the layer
/// containing the handles above or below the layer containing the magnifier
/// in the [`Overlay`].
pub should_display_handles_in_magnifier: bool,
}
impl TextMagnifierConfiguration {
/// Constructs a [`TextMagnifierConfiguration`] from parts.
///
/// If [`magnifier_builder`](Self::magnifier_builder) is not set, a default
/// [`MagnifierBuilder`] will be used that does not build a magnifier.
pub const fn new() -> TextMagnifierConfiguration {
TextMagnifierConfiguration {
magnifier_builder: None,
should_display_handles_in_magnifier: true,
}
}
/// The builder callback that creates the widget that renders the magnifier.
pub fn magnifier_builder(&self) -> MagnifierBuilder {
self.magnifier_builder
.clone()
.unwrap_or_else(|| Rc::new(none))
}
/// Dart `TextMagnifierConfiguration(magnifierBuilder:)`.
pub fn with_magnifier_builder(
mut self,
magnifier_builder: MagnifierBuilder,
) -> TextMagnifierConfiguration {
self.magnifier_builder = Some(magnifier_builder);
self
}
/// Dart `TextMagnifierConfiguration(shouldDisplayHandlesInMagnifier:)`.
pub fn should_display_handles_in_magnifier(
mut self,
should_display_handles_in_magnifier: bool,
) -> TextMagnifierConfiguration {
self.should_display_handles_in_magnifier = should_display_handles_in_magnifier;
self
}
pub(crate) fn same_configuration(&self, other: &TextMagnifierConfiguration) -> bool {
self.should_display_handles_in_magnifier == other.should_display_handles_in_magnifier
&& match (&self.magnifier_builder, &other.magnifier_builder) {
(None, None) => true,
(Some(a), Some(b)) => Rc::ptr_eq(a, b),
_ => false,
}
}
/// A constant for a [`TextMagnifierConfiguration`] that is disabled, meaning it
/// never builds anything, regardless of platform.
pub const DISABLED: TextMagnifierConfiguration = TextMagnifierConfiguration::new();
}
impl Default for TextMagnifierConfiguration {
fn default() -> TextMagnifierConfiguration {
TextMagnifierConfiguration::new()
}
}
fn none(
_app: &mut App,
_context: BuildContext,
_controller: Handle<MagnifierController>,
_magnifier_info: Handle<ValueNotifier<MagnifierInfo>>,
) -> Option<WidgetRef> {
None
}
/// A controller for a magnifier.
///
/// [`MagnifierController`]'s main benefit over holding a raw [`OverlayEntry`] is that
/// [`MagnifierController`] will handle logic around waiting for a magnifier to animate in or out.
///
/// If a magnifier chooses to have an entry / exit animation, it should provide the animation
/// controller to [`MagnifierController::animation_controller`]. [`MagnifierController`] will then drive
/// the [`AnimationController`] and wait for it to be complete before removing it from the
/// [`Overlay`].
///
/// To check the status of the magnifier, see [`MagnifierController::shown`].
pub struct MagnifierController {
/// The controller that will be driven in / out when show / hide is triggered,
/// respectively.
pub animation_controller: Option<Handle<AnimationController>>,
overlay_entry: Option<Handle<OverlayEntry>>,
}
impl MagnifierController {
/// If there is no in / out animation for the magnifier, [`animation_controller`](Self::animation_controller)
/// should be left unset.
pub fn new(app: &mut App) -> Handle<MagnifierController> {
app.create(MagnifierController {
animation_controller: None,
overlay_entry: None,
})
}
/// Dart `MagnifierController(animationController:)`.
pub fn animation_controller(
self: Handle<Self>,
app: &mut App,
animation_controller: Handle<AnimationController>,
) -> Handle<Self> {
animation_controller.set_value(app, 0.0);
app.get_mut(self).animation_controller = Some(animation_controller);
self
}
/// The magnifier's [`OverlayEntry`], if currently in the overlay.
///
/// This is exposed so that other overlay entries can be positioned above or
/// below this [`overlay_entry`](Self::overlay_entry). Anything in the paint order after the
/// `RawMagnifier` in this [`OverlayEntry`] will not be displayed in the
/// magnifier; if it is desired for an overlay entry to be displayed in the
/// magnifier, it *must* be positioned below the magnifier.
///
/// To check if a magnifier is in the overlay, use [`shown`](Self::shown). The
/// [`overlay_entry`](Self::overlay_entry) field may be non-null even when the magnifier is
/// not visible.
pub fn overlay_entry(self: Handle<Self>, app: &App) -> Option<Handle<OverlayEntry>> {
app.get(self).overlay_entry
}
/// Whether the magnifier is currently being shown.
///
/// This is false when nothing is in the overlay, when the
/// [`animation_controller`](Self::animation_controller) is in the
/// [`waft_animation::AnimationStatus::Dismissed`] state, or when
/// the [`animation_controller`](Self::animation_controller) is animating out (i.e. in the
/// [`waft_animation::AnimationStatus::Reverse`] state).
///
/// It is true in the opposite cases, i.e. when the overlay is not empty, and
/// either the [`animation_controller`](Self::animation_controller) is `None`, in the
/// [`waft_animation::AnimationStatus::Completed`] state, or in the
/// [`waft_animation::AnimationStatus::Forward`]
/// state.
pub fn shown(self: Handle<Self>, app: &App) -> bool {
app.get(self).overlay_entry.is_some()
&& app
.get(self)
.animation_controller
.is_none_or(|controller| controller.status(app).is_forward_or_completed())
}
/// Displays the magnifier.
///
/// Returns a future that completes when the magnifier is fully shown, i.e. done
/// with its entry animation.
///
/// To control what overlays are shown in the magnifier, use `below`. See
/// [`overlay_entry`](Self::overlay_entry) for more details on how to utilize `below`.
///
/// If the magnifier already exists (i.e. [`overlay_entry`](Self::overlay_entry) is `Some`),
/// then [`show`](Self::show) will replace the old overlay without playing an exit
/// animation. Consider awaiting [`hide`](Self::hide) first, to animate from the old
/// magnifier to the new one.
pub fn show(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
builder: WidgetBuilder,
below: Option<Handle<OverlayEntry>>,
) -> TickerFuture {
if let Some(entry) = app.get(self).overlay_entry {
entry.remove(app);
entry.dispose(app);
}
let overlay_state = Overlay::of(app, context, true);
let overlay_entry = OverlayEntry::new(app, builder, false, false, false);
app.get_mut(self).overlay_entry = Some(overlay_entry);
overlay_state.insert(app, overlay_entry, below, None);
if let Some(controller) = app.get(self).animation_controller {
controller.forward(app, None)
} else {
TickerFuture::complete()
}
}
/// Schedules a hide of the magnifier.
///
/// If this [`MagnifierController`] has an [`animation_controller`](Self::animation_controller),
/// then [`hide`](Self::hide) reverses the animation controller and waits
/// for the animation to complete. Then, if `remove_from_overlay`
/// is true, remove the magnifier from the overlay.
///
/// In general, `remove_from_overlay` should be true, unless
/// the magnifier needs to preserve states between shows / hides.
///
/// See also:
///
/// * [`remove_from_overlay`](Self::remove_from_overlay) which removes the [`OverlayEntry`] from the [`Overlay`]
/// synchronously.
pub fn hide(self: Handle<Self>, app: &mut App, remove_from_overlay: bool) -> TickerFuture {
if app.get(self).overlay_entry.is_none() {
return TickerFuture::complete();
}
if let Some(controller) = app.get(self).animation_controller {
let future = controller.reverse(app, None);
if remove_from_overlay {
future.when_complete(
app,
Listener::handle_method(self, MagnifierController::remove_from_overlay),
);
}
return future;
}
if remove_from_overlay {
self.remove_from_overlay(app);
}
TickerFuture::complete()
}
/// Remove the [`OverlayEntry`] from the [`Overlay`].
///
/// This method removes the [`OverlayEntry`] synchronously,
/// regardless of exit animation: this leads to abrupt removals
/// of [`OverlayEntry`]s with animations.
///
/// To allow the [`OverlayEntry`] to play its exit animation, consider calling
/// [`hide`](Self::hide) instead, with `remove_from_overlay` set to true, and optionally await
/// the returned future.
pub fn remove_from_overlay(self: Handle<Self>, app: &mut App) {
if let Some(entry) = app.get(self).overlay_entry {
entry.remove(app);
entry.dispose(app);
}
app.get_mut(self).overlay_entry = None;
}
/// A utility for calculating a new [`Rect`] from `rect` such that
/// `rect` is fully constrained within `bounds`.
///
/// Any point in the output rect is guaranteed to also be a point contained in `bounds`.
///
/// It is a runtime error for `rect`.width to be greater than `bounds`.width,
/// and it is also an error for `rect`.height to be greater than `bounds`.height.
///
/// This algorithm translates `rect` the shortest distance such that it is entirely within
/// `bounds`.
///
/// If `rect` is already within `bounds`, no shift will be applied to `rect` and
/// `rect` will be returned as-is.
///
/// It is perfectly valid for the output rect to have a point along the edge of the
/// `bounds`. If the desired output rect requires that no edges are parallel to edges
/// of `bounds`, see [`Rect::deflate`] by 1 on `bounds` to achieve this effect.
pub fn shift_within_bounds(rect: Rect, bounds: Rect) -> Rect {
debug_assert!(
rect.width() <= bounds.width(),
"attempted to shift {rect:?} within {bounds:?}, but the rect has a greater width.",
);
debug_assert!(
rect.height() <= bounds.height(),
"attempted to shift {rect:?} within {bounds:?}, but the rect has a greater height.",
);
let mut rect_shift = Offset::ZERO;
if rect.left < bounds.left {
rect_shift = rect_shift + Offset::new(bounds.left - rect.left, 0.0);
} else if rect.right > bounds.right {
rect_shift = rect_shift + Offset::new(bounds.right - rect.right, 0.0);
}
if rect.top < bounds.top {
rect_shift = rect_shift + Offset::new(0.0, bounds.top - rect.top);
} else if rect.bottom > bounds.bottom {
rect_shift = rect_shift + Offset::new(0.0, bounds.bottom - rect.bottom);
}
rect.shift(rect_shift)
}
}