use std::any::TypeId;
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use waft_embedder::{
AppLifecycleState, Offset, PointerDeviceKind, Rect, TargetPlatform, TextDirection, clamp_double,
};
use waft_foundation::{
App, ChangeNotifier, ChangeNotifierData, Handle, ListenableObject, Listener,
PRECISION_ERROR_TOLERANCE, Ref, ValueChanged, ValueListenable, ValueListenableHandle,
};
use waft_gestures::{
BaseTapAndDragGestureRecognizer, DragEndDetails, DragStartBehavior, DragStartDetails,
DragUpdateDetails, LongPressGestureRecognizer, LongPressMoveUpdateDetails,
LongPressStartDetails, TapAndHorizontalDragGestureRecognizer, TapAndPanGestureRecognizer,
TapDownDetails, TapDragDownDetails, TapDragEndDetails, TapDragStartDetails, TapDragUpDetails,
TapDragUpdateDetails, TapGestureRecognizer, TapStatusTracker,
};
use waft_painting::{transform_point, transform_rect};
use waft_rendering::{
AnySelectable, HitTestBehavior, LayerLink, SelectedContent, SelectedContentRange,
SelectionEvent, SelectionEventType, SelectionExtendDirection, SelectionGeometry,
SelectionHandler, SelectionPoint, SelectionRegistrar, SelectionResult, SelectionStatus,
TextGranularity, TextSelectionHandleType, TextSelectionPoint,
};
use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase};
use waft_services::{
Clipboard, ClipboardData, HapticFeedback, HardwareKeyboard, LogicalKeyboardKey,
SelectionChangedCause,
};
use crate::framework::{
BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
};
use crate::widgets::actions::{
Action, ActionData, ActionRef, Actions, AnyAction, CallbackAction, ContextAction,
DismissIntent, Intent,
};
use crate::widgets::basic::CompositedTransformTarget;
use crate::widgets::context_menu_button_item::{ContextMenuButtonItem, ContextMenuButtonType};
use crate::widgets::focus_manager::{FocusNode, FocusNodeLeaf, FocusNodeRef};
use crate::widgets::focus_scope::Focus;
use crate::widgets::gesture_detector::{
GestureRecognizerFactories, GestureRecognizerFactory, GestureRecognizerFactoryWithHandlers,
RawGestureDetector,
};
use crate::widgets::magnifier::{MagnifierInfo, TextMagnifierConfiguration};
use crate::widgets::media_query::{MediaQuery, Orientation};
use crate::widgets::selection_container::{
SelectionContainer, SelectionContainerDelegate, SelectionContainerDelegateData,
};
use crate::widgets::tap_region::TapRegion;
use crate::widgets::text_editing_intents::{
CopySelectionTextIntent, ExpandSelectionToDocumentBoundaryIntent,
ExpandSelectionToLineBreakIntent, ExtendSelectionByCharacterIntent,
ExtendSelectionToDocumentBoundaryIntent, ExtendSelectionToLineBreakIntent,
ExtendSelectionToNextWordBoundaryIntent,
ExtendSelectionToNextWordBoundaryOrCaretLocationIntent,
ExtendSelectionVerticallyToAdjacentLineIntent, SelectAllTextIntent,
};
use crate::widgets::text_selection::{SelectionOverlay, TextSelectionControls};
use crate::widgets::text_selection_toolbar_anchors::TextSelectionToolbarAnchors;
const K_SELECTABLE_VERTICAL_COMPARING_THRESHOLD: f64 = 3.0;
const K_SELECTION_HANDLE_DRAWABLE_AREA_PADDING: f64 = 5.0;
fn set_contains(set: &[AnySelectable], selectable: AnySelectable) -> bool {
set.contains(&selectable)
}
fn set_add(set: &mut Vec<AnySelectable>, selectable: AnySelectable) -> bool {
if set_contains(set, selectable) {
return false;
}
set.push(selectable);
true
}
fn set_remove(set: &mut Vec<AnySelectable>, selectable: AnySelectable) -> bool {
let Some(index) = set.iter().position(|held| *held == selectable) else {
return false;
};
set.remove(index);
true
}
fn selectable_geometry_change_listener<T: MultiSelectableSelectionContainerDelegate>(
this: Handle<T>,
) -> Listener {
Listener::handle_method(this, notify_selectable_geometry_change::<T>)
}
fn notify_selectable_geometry_change<T: MultiSelectableSelectionContainerDelegate>(
this: Handle<T>,
app: &mut App,
) {
MultiSelectableSelectionContainerDelegateBase::handle_selectable_geometry_change(this, app);
}
fn scheduled_update_listener<T: MultiSelectableSelectionContainerDelegate>(
this: Handle<T>,
) -> Listener {
Listener::handle_method(this, run_scheduled_task_tearoff::<T>)
}
fn scheduled_update_frame_callback<T: MultiSelectableSelectionContainerDelegate>(
this: Handle<T>,
) -> FrameCallback {
FrameCallback::handle_method(this, post_frame_run_scheduled_task_tearoff::<T>)
}
fn run_scheduled_task_tearoff<T: MultiSelectableSelectionContainerDelegate>(
this: Handle<T>,
app: &mut App,
) {
MultiSelectableSelectionContainerDelegateBase::run_scheduled_task(this, app);
}
fn post_frame_run_scheduled_task_tearoff<T: MultiSelectableSelectionContainerDelegate>(
this: Handle<T>,
app: &mut App,
_time_stamp: std::time::Duration,
) {
MultiSelectableSelectionContainerDelegateBase::run_scheduled_task(this, app);
}
pub struct MultiSelectableSelectionContainerDelegateData {
pub change_notifier: ChangeNotifierData,
pub selectables: Vec<AnySelectable>,
pub current_selection_end_index: i32,
pub current_selection_start_index: i32,
start_handle_layer: Option<Ref<LayerLink>>,
start_handle_layer_owner: Option<AnySelectable>,
end_handle_layer: Option<Ref<LayerLink>>,
end_handle_layer_owner: Option<AnySelectable>,
is_handling_selection_event: bool,
scheduled_selectable_update: bool,
selection_in_progress: bool,
additions: Vec<AnySelectable>,
extend_selection_in_progress: bool,
selection_geometry: SelectionGeometry,
}
impl MultiSelectableSelectionContainerDelegateData {
pub fn new() -> MultiSelectableSelectionContainerDelegateData {
MultiSelectableSelectionContainerDelegateData {
change_notifier: ChangeNotifierData::new(),
selectables: Vec::new(),
current_selection_end_index: -1,
current_selection_start_index: -1,
start_handle_layer: None,
start_handle_layer_owner: None,
end_handle_layer: None,
end_handle_layer_owner: None,
is_handling_selection_event: false,
scheduled_selectable_update: false,
selection_in_progress: false,
additions: Vec::new(),
extend_selection_in_progress: false,
selection_geometry: SelectionGeometry::new(SelectionStatus::None, false),
}
}
}
impl Default for MultiSelectableSelectionContainerDelegateData {
fn default() -> Self {
Self::new()
}
}
#[macro_export]
macro_rules! multi_selectable_selection_container_delegate_accessors {
() => {
fn multi_selectable_selection_container_delegate_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::MultiSelectableSelectionContainerDelegateData {
&app.get(self).multi_selectable_selection_container_delegate
}
fn multi_selectable_selection_container_delegate_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::MultiSelectableSelectionContainerDelegateData {
&mut app
.get_mut(self)
.multi_selectable_selection_container_delegate
}
};
}
pub trait MultiSelectableSelectionContainerDelegate:
SelectionContainerDelegate + ChangeNotifier + Sized + 'static
{
fn multi_selectable_selection_container_delegate_data(
self: Handle<Self>,
app: &App,
) -> &MultiSelectableSelectionContainerDelegateData;
fn multi_selectable_selection_container_delegate_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut MultiSelectableSelectionContainerDelegateData;
fn layout_did_change(self: Handle<Self>, app: &mut App) {
MultiSelectableSelectionContainerDelegateBase::update_selection_geometry(self, app);
}
fn did_change_selectables(self: Handle<Self>, app: &mut App) {
MultiSelectableSelectionContainerDelegateBase::did_change_selectables(self, app);
}
fn get_selection_geometry(self: Handle<Self>, app: &mut App) -> SelectionGeometry {
MultiSelectableSelectionContainerDelegateBase::get_selection_geometry(self, app)
}
fn compare_order(
self: Handle<Self>,
app: &mut App,
a: AnySelectable,
b: AnySelectable,
) -> Ordering {
MultiSelectableSelectionContainerDelegateBase::compare_order(self, app, a, b)
}
fn handle_select_all(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
MultiSelectableSelectionContainerDelegateBase::handle_select_all(self, app, event)
}
fn handle_select_word(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
MultiSelectableSelectionContainerDelegateBase::handle_select_word(self, app, event)
}
fn handle_select_paragraph(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
MultiSelectableSelectionContainerDelegateBase::handle_select_paragraph(self, app, event)
}
fn handle_clear_selection(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
MultiSelectableSelectionContainerDelegateBase::handle_clear_selection(self, app, event)
}
fn handle_granularly_extend_selection(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
MultiSelectableSelectionContainerDelegateBase::handle_granularly_extend_selection(
self, app, event,
)
}
fn handle_directionally_extend_selection(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
MultiSelectableSelectionContainerDelegateBase::handle_directionally_extend_selection(
self, app, event,
)
}
fn handle_selection_edge_update(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
MultiSelectableSelectionContainerDelegateBase::handle_selection_edge_update(
self, app, event,
)
}
fn dispose(self: Handle<Self>, app: &mut App) {
MultiSelectableSelectionContainerDelegateBase::dispose(self, app);
}
fn ensure_child_updated(self: Handle<Self>, app: &mut App, selectable: AnySelectable);
fn dispatch_selection_event_to_child(
self: Handle<Self>,
app: &mut App,
selectable: AnySelectable,
event: &SelectionEvent,
) -> SelectionResult {
MultiSelectableSelectionContainerDelegateBase::dispatch_selection_event_to_child(
self, app, selectable, event,
)
}
}
pub trait MultiSelectableSelectionContainerDelegateBase:
MultiSelectableSelectionContainerDelegate
{
fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
let data = self.multi_selectable_selection_container_delegate_data(app);
debug_assert!(!data.selectables.contains(&selectable));
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
set_add(&mut data.additions, selectable);
MultiSelectableSelectionContainerDelegateBase::schedule_selectable_update(self, app);
}
fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
if set_remove(
&mut self
.multi_selectable_selection_container_delegate_data_mut(app)
.additions,
selectable,
) {
return;
}
self.remove_selectable(app, selectable);
MultiSelectableSelectionContainerDelegateBase::schedule_selectable_update(self, app);
}
fn dispatch_selection_event_to_child(
self: Handle<Self>,
app: &mut App,
selectable: AnySelectable,
event: &SelectionEvent,
) -> SelectionResult {
selectable.dispatch_selection_event(app, event)
}
fn schedule_selectable_update(self: Handle<Self>, app: &mut App) {
if self
.multi_selectable_selection_container_delegate_data(app)
.scheduled_selectable_update
{
return;
}
self.multi_selectable_selection_container_delegate_data_mut(app)
.scheduled_selectable_update = true;
if SchedulerBinding::scheduler_phase(app) == SchedulerPhase::PostFrameCallbacks {
app.schedule_microtask(scheduled_update_listener(self));
} else {
SchedulerBinding::add_post_frame_callback(
app,
scheduled_update_frame_callback(self),
None,
);
}
}
fn run_scheduled_task(self: Handle<Self>, app: &mut App) {
if !self
.multi_selectable_selection_container_delegate_data(app)
.scheduled_selectable_update
{
return;
}
self.multi_selectable_selection_container_delegate_data_mut(app)
.scheduled_selectable_update = false;
MultiSelectableSelectionContainerDelegateBase::update_selectables(self, app);
}
fn update_selectables(self: Handle<Self>, app: &mut App) {
if !self
.multi_selectable_selection_container_delegate_data(app)
.additions
.is_empty()
{
self.flush_additions(app);
}
MultiSelectableSelectionContainerDelegate::did_change_selectables(self, app);
}
fn flush_additions(self: Handle<Self>, app: &mut App) {
let mut merging_selectables = self
.multi_selectable_selection_container_delegate_data(app)
.additions
.clone();
waft_foundation::merge_sort(&mut merging_selectables, |a, b| {
MultiSelectableSelectionContainerDelegate::compare_order(self, app, *a, *b)
});
let existing_selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
let current_selection_start_index = self
.multi_selectable_selection_container_delegate_data(app)
.current_selection_start_index;
let current_selection_end_index = self
.multi_selectable_selection_container_delegate_data(app)
.current_selection_end_index;
let mut selectables = Vec::new();
let mut selection_start_index = current_selection_start_index;
let mut selection_end_index = current_selection_end_index;
let mut merging_index = 0;
let mut existing_index = 0;
while merging_index < merging_selectables.len()
|| existing_index < existing_selectables.len()
{
if merging_index >= merging_selectables.len()
|| (existing_index < existing_selectables.len()
&& MultiSelectableSelectionContainerDelegate::compare_order(
self,
app,
existing_selectables[existing_index],
merging_selectables[merging_index],
) == Ordering::Less)
{
if existing_index as i32 == current_selection_start_index {
selection_start_index = selectables.len() as i32;
}
if existing_index as i32 == current_selection_end_index {
selection_end_index = selectables.len() as i32;
}
selectables.push(existing_selectables[existing_index]);
existing_index += 1;
continue;
}
let merging_selectable = merging_selectables[merging_index];
if (existing_index as i32)
< current_selection_start_index.max(current_selection_end_index)
&& (existing_index as i32)
> current_selection_start_index.min(current_selection_end_index)
{
MultiSelectableSelectionContainerDelegate::ensure_child_updated(
self,
app,
merging_selectable,
);
}
merging_selectable.add_listener(app, selectable_geometry_change_listener(self));
selectables.push(merging_selectable);
merging_index += 1;
}
debug_assert_eq!(merging_index, merging_selectables.len());
debug_assert_eq!(existing_index, existing_selectables.len());
debug_assert_eq!(
selectables.len(),
existing_index + merging_index,
"the merged list holds every selectable once"
);
debug_assert!(
selection_start_index >= -1 || (selection_start_index as usize) < selectables.len()
);
debug_assert!(
selection_end_index >= -1 || (selection_end_index as usize) < selectables.len()
);
debug_assert_eq!(
current_selection_start_index == -1,
selection_start_index == -1
);
debug_assert_eq!(current_selection_end_index == -1, selection_end_index == -1);
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.selectables = selectables;
data.current_selection_end_index = selection_end_index;
data.current_selection_start_index = selection_start_index;
data.additions = Vec::new();
}
fn remove_selectable(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
let data = self.multi_selectable_selection_container_delegate_data(app);
debug_assert!(
data.selectables.contains(&selectable),
"The selectable is not in this registrar."
);
let index = data
.selectables
.iter()
.position(|held| *held == selectable)
.expect("checked just now");
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.selectables.remove(index);
if index as i32 <= data.current_selection_end_index {
data.current_selection_end_index -= 1;
}
if index as i32 <= data.current_selection_start_index {
data.current_selection_start_index -= 1;
}
selectable.remove_listener(app, &selectable_geometry_change_listener(self));
}
fn did_change_selectables(self: Handle<Self>, app: &mut App) {
MultiSelectableSelectionContainerDelegateBase::update_selection_geometry(self, app);
}
fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
self.multi_selectable_selection_container_delegate_data(app)
.selection_geometry
.clone()
}
fn update_selection_geometry(self: Handle<Self>, app: &mut App) {
let new_value =
MultiSelectableSelectionContainerDelegate::get_selection_geometry(self, app);
if self
.multi_selectable_selection_container_delegate_data(app)
.selection_geometry
!= new_value
{
self.multi_selectable_selection_container_delegate_data_mut(app)
.selection_geometry = new_value;
self.notify_listeners(app);
}
self.update_handle_layers_and_owners(app);
}
fn handle_selectable_geometry_change(self: Handle<Self>, app: &mut App) {
if self
.multi_selectable_selection_container_delegate_data(app)
.is_handling_selection_event
{
return;
}
MultiSelectableSelectionContainerDelegateBase::update_selection_geometry(self, app);
}
fn get_selection_geometry(self: Handle<Self>, app: &mut App) -> SelectionGeometry {
{
let data = self.multi_selectable_selection_container_delegate_data(app);
if data.current_selection_end_index == -1
|| data.current_selection_start_index == -1
|| data.selectables.is_empty()
{
return SelectionGeometry::new(SelectionStatus::None, !data.selectables.is_empty());
}
if !data.extend_selection_in_progress {
let start = self.adjust_selection_index_based_on_selection_geometry(
app,
data.current_selection_start_index,
data.current_selection_end_index,
);
let end = self.adjust_selection_index_based_on_selection_geometry(
app,
data.current_selection_end_index,
start,
);
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.current_selection_start_index = start;
data.current_selection_end_index = end;
}
}
let start_index = self
.multi_selectable_selection_container_delegate_data(app)
.current_selection_start_index;
let end_index = self
.multi_selectable_selection_container_delegate_data(app)
.current_selection_end_index;
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
let forward_selection = end_index >= start_index;
let mut start_geometry = selectables[start_index as usize].value(app);
let mut start_index_walker = start_index;
while start_index_walker != end_index && start_geometry.start_selection_point.is_none() {
start_index_walker += if forward_selection { 1 } else { -1 };
start_geometry = selectables[start_index_walker as usize].value(app);
}
let start_point = start_geometry.start_selection_point.and_then(|point| {
let transform = self.get_transform_from(app, selectables[start_index_walker as usize]);
let start = transform_point(&transform, point.local_position);
start
.is_finite()
.then(|| SelectionPoint::new(start, point.line_height, point.handle_type))
});
let mut end_geometry = selectables[end_index as usize].value(app);
let mut end_index_walker = end_index;
while end_index_walker != start_index && end_geometry.end_selection_point.is_none() {
end_index_walker += if forward_selection { -1 } else { 1 };
end_geometry = selectables[end_index_walker as usize].value(app);
}
let end_point = end_geometry.end_selection_point.and_then(|point| {
let transform = self.get_transform_from(app, selectables[end_index_walker as usize]);
let end = transform_point(&transform, point.local_position);
end.is_finite()
.then(|| SelectionPoint::new(end, point.line_height, point.handle_type))
});
let mut selection_rects = Vec::new();
let drawable_area = if self.has_size(app) {
let size = self.container_size(app);
Some(Rect::from_ltrb(0.0, 0.0, size.width(), size.height()))
} else {
None
};
for index in start_index..=end_index {
let selectable = selectables[index as usize];
let transform = self.get_transform_from(app, selectable);
for selection_rect in selectable.value(app).selection_rects {
let local_rect = transform_rect(&transform, selection_rect);
let within_drawable_area =
drawable_area.map_or(local_rect, |area| area.intersect(local_rect));
if within_drawable_area.is_finite() && !within_drawable_area.is_empty() {
selection_rects.push(within_drawable_area);
}
}
}
SelectionGeometry {
start_selection_point: start_point,
end_selection_point: end_point,
selection_rects,
status: if start_geometry != end_geometry {
SelectionStatus::Uncollapsed
} else {
start_geometry.status
},
has_content: true,
}
}
fn adjust_selection_index_based_on_selection_geometry(
self: Handle<Self>,
app: &App,
current_index: i32,
toward_index: i32,
) -> i32 {
let forward = toward_index > current_index;
let mut index = current_index;
while index != toward_index {
let selectable = self
.multi_selectable_selection_container_delegate_data(app)
.selectables[index as usize];
if selectable.value(app).status == SelectionStatus::Uncollapsed {
break;
}
index += if forward { 1 } else { -1 };
}
index
}
fn compare_order(
self: Handle<Self>,
app: &mut App,
a: AnySelectable,
b: AnySelectable,
) -> Ordering {
let rect_a = transform_rect(
&a.get_transform_to(app, None),
self.get_bounding_box(app, a),
);
let rect_b = transform_rect(
&b.get_transform_to(app, None),
self.get_bounding_box(app, b),
);
let result = compare_vertically(rect_a, rect_b);
if result != Ordering::Equal {
return result;
}
compare_horizontally(rect_a, rect_b)
}
fn get_bounding_box(self: Handle<Self>, app: &mut App, selectable: AnySelectable) -> Rect {
let mut boxes = selectable.bounding_boxes(app).into_iter();
let mut result = boxes.next().expect("a selectable has a bounding box");
for other in boxes {
result = result.expand_to_include(other);
}
result
}
fn push_handle_layers(
self: Handle<Self>,
app: &mut App,
start_handle: Option<Ref<LayerLink>>,
end_handle: Option<Ref<LayerLink>>,
) {
{
let data = self.multi_selectable_selection_container_delegate_data(app);
if data.start_handle_layer == start_handle && data.end_handle_layer == end_handle {
return;
}
}
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.start_handle_layer = start_handle;
data.end_handle_layer = end_handle;
self.update_handle_layers_and_owners(app);
}
fn update_handle_layers_and_owners(self: Handle<Self>, app: &mut App) {
let start_layer = self
.multi_selectable_selection_container_delegate_data(app)
.start_handle_layer
.clone();
let end_layer = self
.multi_selectable_selection_container_delegate_data(app)
.end_handle_layer
.clone();
let mut effective_start_handle = start_layer.clone();
let mut effective_end_handle = end_layer.clone();
if effective_start_handle.is_some() || effective_end_handle.is_some() {
let drawable_area = if self.has_size(app) {
let size = self.container_size(app);
Some(
Rect::from_ltrb(0.0, 0.0, size.width(), size.height())
.inflate(K_SELECTION_HANDLE_DRAWABLE_AREA_PADDING),
)
} else {
None
};
let value = SelectionHandler::value(self, app);
let hide_start_handle = value.start_selection_point.is_none()
|| drawable_area.is_none()
|| !drawable_area.expect("checked just now").contains(
value
.start_selection_point
.expect("checked just now")
.local_position,
);
let hide_end_handle = value.end_selection_point.is_none()
|| drawable_area.is_none()
|| !drawable_area.expect("checked just now").contains(
value
.end_selection_point
.expect("checked just now")
.local_position,
);
effective_start_handle = if hide_start_handle { None } else { start_layer };
effective_end_handle = if hide_end_handle { None } else { end_layer };
}
let start_index = self
.multi_selectable_selection_container_delegate_data(app)
.current_selection_start_index;
let end_index = self
.multi_selectable_selection_container_delegate_data(app)
.current_selection_end_index;
if start_index == -1 || end_index == -1 {
let start_owner = self
.multi_selectable_selection_container_delegate_data_mut(app)
.start_handle_layer_owner
.take();
if let Some(owner) = start_owner {
owner.push_handle_layers(app, None, None);
}
let end_owner = self
.multi_selectable_selection_container_delegate_data_mut(app)
.end_handle_layer_owner
.take();
if let Some(owner) = end_owner {
owner.push_handle_layers(app, None, None);
}
return;
}
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
let start_selectable = selectables[start_index as usize];
let end_selectable = selectables[end_index as usize];
if self
.multi_selectable_selection_container_delegate_data(app)
.start_handle_layer_owner
!= Some(start_selectable)
&& let Some(owner) = self
.multi_selectable_selection_container_delegate_data(app)
.start_handle_layer_owner
{
owner.push_handle_layers(app, None, None);
}
if self
.multi_selectable_selection_container_delegate_data(app)
.end_handle_layer_owner
!= Some(end_selectable)
&& let Some(owner) = self
.multi_selectable_selection_container_delegate_data(app)
.end_handle_layer_owner
{
owner.push_handle_layers(app, None, None);
}
{
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.start_handle_layer_owner = Some(start_selectable);
if start_index == end_index {
data.end_handle_layer_owner = Some(start_selectable);
} else {
data.end_handle_layer_owner = Some(end_selectable);
}
}
if start_index == end_index {
start_selectable.push_handle_layers(app, effective_start_handle, effective_end_handle);
return;
}
start_selectable.push_handle_layers(app, effective_start_handle, None);
end_selectable.push_handle_layers(app, None, effective_end_handle);
}
fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
let selections: Vec<SelectedContent> = selectables
.iter()
.filter_map(|selectable| selectable.selected_content(app))
.collect();
if selections.is_empty() {
return None;
}
let mut plain_text = String::new();
for selection in selections {
plain_text.push_str(&selection.plain_text);
}
Some(SelectedContent::new(plain_text))
}
fn content_length(self: Handle<Self>, app: &App) -> usize {
self.multi_selectable_selection_container_delegate_data(app)
.selectables
.iter()
.map(|selectable| selectable.content_length(app))
.sum()
}
fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
let selections: Vec<(usize, Option<SelectedContentRange>)> = selectables
.iter()
.map(|selectable| (selectable.content_length(app), selectable.selection(app)))
.collect();
self.calculate_local_range(app, &selections)
}
fn calculate_local_range(
self: Handle<Self>,
app: &App,
selections: &[(usize, Option<SelectedContentRange>)],
) -> Option<SelectedContentRange> {
let data = self.multi_selectable_selection_container_delegate_data(app);
if data.current_selection_start_index == -1 || data.current_selection_end_index == -1 {
return None;
}
let mut start_offset = 0i32;
let mut end_offset = 0i32;
let mut found_start = false;
let mut forward_selection =
data.current_selection_end_index >= data.current_selection_start_index;
if data.current_selection_end_index == data.current_selection_start_index {
let range_at_selectable_in_selection = data.selectables
[data.current_selection_start_index as usize]
.selection(app)
.expect("the selectable holding both edges has a selection");
forward_selection = range_at_selectable_in_selection.end_offset
>= range_at_selectable_in_selection.start_offset;
}
for (content_length, range) in selections {
let Some(range) = range else {
if found_start {
return Some(SelectedContentRange::new(
if forward_selection {
start_offset
} else {
end_offset
},
if forward_selection {
end_offset
} else {
start_offset
},
));
}
start_offset += *content_length as i32;
end_offset = start_offset;
continue;
};
let selection_start_normalized = range.start_offset.min(range.end_offset);
let selection_end_normalized = range.start_offset.max(range.end_offset);
if !found_start {
start_offset += selection_start_normalized;
end_offset =
start_offset + (selection_end_normalized - selection_start_normalized).abs();
found_start = true;
} else {
end_offset += (selection_end_normalized - selection_start_normalized).abs();
}
}
debug_assert!(
found_start,
"The start of the selection has not been found despite this selection delegate \
having an existing currentSelectionStartIndex and currentSelectionEndIndex."
);
Some(SelectedContentRange::new(
if forward_selection {
start_offset
} else {
end_offset
},
if forward_selection {
end_offset
} else {
start_offset
},
))
}
fn flush_inactive_selections(self: Handle<Self>, app: &mut App) {
let start_index = self
.multi_selectable_selection_container_delegate_data(app)
.current_selection_start_index;
let end_index = self
.multi_selectable_selection_container_delegate_data(app)
.current_selection_end_index;
if start_index == -1 && end_index == -1 {
return;
}
if start_index == -1 || end_index == -1 {
let skip_index = if start_index == -1 {
end_index
} else {
start_index
};
self.clear_selectables(app, Some(skip_index));
return;
}
let skip_start = start_index.min(end_index);
let skip_end = start_index.max(end_index);
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
for (index, selectable) in selectables.iter().enumerate() {
if (index as i32) >= skip_start && (index as i32) <= skip_end {
continue;
}
MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
self,
app,
*selectable,
&SelectionEvent::Clear,
);
}
}
fn handle_select_all(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
for selectable in &selectables {
MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
self,
app,
*selectable,
event,
);
}
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.current_selection_start_index = 0;
data.current_selection_end_index = selectables.len() as i32 - 1;
SelectionResult::None
}
fn clear_selectables(self: Handle<Self>, app: &mut App, skip_index: Option<i32>) {
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
for (index, selectable) in selectables.iter().enumerate() {
if Some(index as i32) == skip_index {
continue;
}
MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
self,
app,
*selectable,
&SelectionEvent::Clear,
);
}
}
fn handle_select_boundary(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
debug_assert!(
matches!(
event,
SelectionEvent::SelectWord { .. } | SelectionEvent::SelectParagraph { .. }
),
"This method should only be given selection events that select text boundaries."
);
let effective_global_position = match event {
SelectionEvent::SelectWord { global_position } => *global_position,
SelectionEvent::SelectParagraph {
global_position, ..
} => *global_position,
_ => panic!("Unsupported selection event"),
};
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
let mut last_selection_result: Option<SelectionResult> = None;
let mut min_distance_squared = f64::INFINITY;
let mut nearest_index = 0usize;
for index in 0..selectables.len() {
let mut global_rects_contain_position = false;
let transform = selectables[index].get_transform_to(app, None);
for rect in selectables[index].bounding_boxes(app) {
let global_rect = transform_rect(&transform, rect);
if global_rect.contains(effective_global_position) {
global_rects_contain_position = true;
break;
}
let dx = effective_global_position.dx()
- clamp_double(
effective_global_position.dx(),
global_rect.left,
global_rect.right,
);
let dy = effective_global_position.dy()
- clamp_double(
effective_global_position.dy(),
global_rect.top,
global_rect.bottom,
);
let distance_squared = dx * dx + dy * dy;
if distance_squared < min_distance_squared {
min_distance_squared = distance_squared;
nearest_index = index;
}
}
if global_rects_contain_position {
let existing_geometry = selectables[index].value(app);
last_selection_result = Some(
MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
self,
app,
selectables[index],
event,
),
);
let result = last_selection_result.expect("assigned just now");
if index == selectables.len() - 1 && result == SelectionResult::Next {
return SelectionResult::Next;
}
if result == SelectionResult::Next {
continue;
}
if index == 0 && result == SelectionResult::Previous {
return SelectionResult::Previous;
}
if selectables[index].value(app) != existing_geometry {
self.clear_selectables(app, Some(index as i32));
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.current_selection_start_index = index as i32;
data.current_selection_end_index = index as i32;
}
return SelectionResult::End;
} else if last_selection_result == Some(SelectionResult::Next) {
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.current_selection_start_index = index as i32 - 1;
data.current_selection_end_index = index as i32 - 1;
return SelectionResult::End;
}
}
debug_assert!(last_selection_result.is_none());
if !selectables.is_empty() {
let existing_geometry = selectables[nearest_index].value(app);
MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
self,
app,
selectables[nearest_index],
event,
);
if selectables[nearest_index].value(app) != existing_geometry {
self.clear_selectables(app, Some(nearest_index as i32));
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.current_selection_start_index = nearest_index as i32;
data.current_selection_end_index = nearest_index as i32;
}
}
SelectionResult::End
}
fn handle_select_word(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
self.handle_select_boundary(app, event)
}
fn handle_select_paragraph(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
self.handle_select_boundary(app, event)
}
fn handle_clear_selection(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
for selectable in &selectables {
MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
self,
app,
*selectable,
event,
);
}
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.current_selection_end_index = -1;
data.current_selection_start_index = -1;
SelectionResult::None
}
fn handle_granularly_extend_selection(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
let SelectionEvent::GranularlyExtendSelection {
forward, is_end, ..
} = event
else {
panic!("a granular extension event updates the selection");
};
let (forward, is_end) = (*forward, *is_end);
self.assert_selection_indices_agree(app);
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
if self
.multi_selectable_selection_container_delegate_data(app)
.current_selection_start_index
== -1
{
let index = if forward {
0
} else {
selectables.len() as i32 - 1
};
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.current_selection_start_index = index;
data.current_selection_end_index = index;
}
let mut target_index = {
let data = self.multi_selectable_selection_container_delegate_data(app);
if is_end {
data.current_selection_end_index
} else {
data.current_selection_start_index
}
};
let mut result =
MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
self,
app,
selectables[target_index as usize],
event,
);
if forward {
debug_assert_ne!(result, SelectionResult::Previous);
while (target_index as usize) < selectables.len() - 1 && result == SelectionResult::Next
{
target_index += 1;
result =
MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
self,
app,
selectables[target_index as usize],
event,
);
debug_assert_ne!(result, SelectionResult::Previous);
}
} else {
debug_assert_ne!(result, SelectionResult::Next);
while target_index > 0 && result == SelectionResult::Previous {
target_index -= 1;
result =
MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
self,
app,
selectables[target_index as usize],
event,
);
debug_assert_ne!(result, SelectionResult::Next);
}
}
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
if is_end {
data.current_selection_end_index = target_index;
} else {
data.current_selection_start_index = target_index;
}
result
}
fn handle_directionally_extend_selection(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
let SelectionEvent::DirectionallyExtendSelection {
is_end, direction, ..
} = event
else {
panic!("a directional extension event updates the selection");
};
let (is_end, direction) = (*is_end, *direction);
self.assert_selection_indices_agree(app);
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
if self
.multi_selectable_selection_container_delegate_data(app)
.current_selection_start_index
== -1
{
let index = match direction {
SelectionExtendDirection::PreviousLine | SelectionExtendDirection::Backward => {
selectables.len() as i32 - 1
}
SelectionExtendDirection::NextLine | SelectionExtendDirection::Forward => 0,
};
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.current_selection_start_index = index;
data.current_selection_end_index = index;
}
let mut target_index = {
let data = self.multi_selectable_selection_container_delegate_data(app);
if is_end {
data.current_selection_end_index
} else {
data.current_selection_start_index
}
};
let mut result =
MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
self,
app,
selectables[target_index as usize],
event,
);
match direction {
SelectionExtendDirection::PreviousLine => {
debug_assert!(
result == SelectionResult::End || result == SelectionResult::Previous
);
if result == SelectionResult::Previous && target_index > 0 {
target_index -= 1;
result = MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(self,
app,
selectables[target_index as usize],
&event.copy_with(None, None, Some(SelectionExtendDirection::Backward)),
);
debug_assert_eq!(result, SelectionResult::End);
}
}
SelectionExtendDirection::NextLine => {
debug_assert!(result == SelectionResult::End || result == SelectionResult::Next);
if result == SelectionResult::Next
&& (target_index as usize) < selectables.len() - 1
{
target_index += 1;
result = MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(self,
app,
selectables[target_index as usize],
&event.copy_with(None, None, Some(SelectionExtendDirection::Forward)),
);
debug_assert_eq!(result, SelectionResult::End);
}
}
SelectionExtendDirection::Forward | SelectionExtendDirection::Backward => {
debug_assert_eq!(result, SelectionResult::End);
}
}
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
if is_end {
data.current_selection_end_index = target_index;
} else {
data.current_selection_start_index = target_index;
}
result
}
fn assert_selection_indices_agree(self: Handle<Self>, app: &App) {
let data = self.multi_selectable_selection_container_delegate_data(app);
debug_assert_eq!(
data.current_selection_start_index == -1,
data.current_selection_end_index == -1,
"both selection edges exist, or neither does"
);
}
fn handle_selection_edge_update(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
let is_end = event.ty() == SelectionEventType::EndEdgeUpdate;
let edge_index = {
let data = self.multi_selectable_selection_container_delegate_data(app);
if is_end {
data.current_selection_end_index
} else {
data.current_selection_start_index
}
};
if edge_index == -1 {
self.init_selection(app, event, is_end)
} else {
self.adjust_selection(app, event, is_end)
}
}
fn init_selection(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
is_end: bool,
) -> SelectionResult {
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
let opposite_edge_index = {
let data = self.multi_selectable_selection_container_delegate_data(app);
if is_end {
data.current_selection_start_index
} else {
data.current_selection_end_index
}
};
let mut new_index: i32 = -1;
let mut has_found_edge_index = false;
let mut result: Option<SelectionResult> = None;
let mut forward: Option<bool> = None;
let mut index = opposite_edge_index.max(0);
while index >= 0 && (index as usize) < selectables.len() {
let child = selectables[index as usize];
let child_result =
MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
self, app, child, event,
);
match child_result {
SelectionResult::Next => {
if forward == Some(false) {
has_found_edge_index = true;
result = Some(SelectionResult::End);
} else {
forward = Some(true);
new_index = index;
}
}
SelectionResult::None => new_index = index,
SelectionResult::End => {
new_index = index;
result = Some(SelectionResult::End);
has_found_edge_index = true;
}
SelectionResult::Previous => {
if index == 0 {
has_found_edge_index = true;
new_index = 0;
result = Some(SelectionResult::Previous);
} else if forward == Some(true) {
has_found_edge_index = true;
result = Some(SelectionResult::End);
} else {
forward = Some(false);
new_index = index;
}
}
SelectionResult::Pending => {
new_index = index;
result = Some(SelectionResult::Pending);
has_found_edge_index = true;
}
}
if has_found_edge_index {
break;
}
index += if forward.unwrap_or(true) { 1 } else { -1 };
}
if new_index == -1 {
debug_assert!(selectables.is_empty());
return SelectionResult::None;
}
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
if is_end {
data.current_selection_end_index = new_index;
} else {
data.current_selection_start_index = new_index;
}
self.flush_inactive_selections(app);
result.unwrap_or(SelectionResult::Next)
}
fn adjust_selection(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
is_end: bool,
) -> SelectionResult {
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
let value = self
.multi_selectable_selection_container_delegate_data(app)
.selection_geometry
.clone();
let is_current_edge_within_viewport = if is_end {
value.end_selection_point.is_some()
} else {
value.start_selection_point.is_some()
};
let is_opposite_edge_within_viewport = if is_end {
value.start_selection_point.is_some()
} else {
value.end_selection_point.is_some()
};
let data = self.multi_selectable_selection_container_delegate_data(app);
let mut new_index: i32 = if is_end {
if is_current_edge_within_viewport {
data.current_selection_end_index
} else if is_opposite_edge_within_viewport {
data.current_selection_start_index
} else {
0
}
} else if is_current_edge_within_viewport {
data.current_selection_start_index
} else if is_opposite_edge_within_viewport {
data.current_selection_end_index
} else {
0
};
debug_assert!(new_index < selectables.len() as i32 && new_index >= 0);
let mut final_result: Option<SelectionResult> = None;
let mut forward: Option<bool> = None;
while (new_index as usize) < selectables.len() && new_index >= 0 && final_result.is_none() {
let current_selectable_result =
MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
self,
app,
selectables[new_index as usize],
event,
);
match current_selectable_result {
SelectionResult::End | SelectionResult::Pending | SelectionResult::None => {
final_result = Some(current_selectable_result);
}
SelectionResult::Next => {
if forward == Some(false) {
new_index += 1;
final_result = Some(SelectionResult::End);
} else if new_index as usize == selectables.len() - 1 {
final_result = Some(current_selectable_result);
} else {
forward = Some(true);
new_index += 1;
}
}
SelectionResult::Previous => {
if forward == Some(true) {
new_index -= 1;
final_result = Some(SelectionResult::End);
} else if new_index == 0 {
final_result = Some(current_selectable_result);
} else {
forward = Some(false);
new_index -= 1;
}
}
}
}
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
if is_end {
data.current_selection_end_index = new_index;
} else {
data.current_selection_start_index = new_index;
}
self.flush_inactive_selections(app);
final_result.expect("the loop answered a result")
}
fn dispatch_selection_event(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
let selection_will_be_in_progress = event.ty() != SelectionEventType::Clear;
let was_in_progress = self
.multi_selectable_selection_container_delegate_data(app)
.selection_in_progress;
if !was_in_progress && selection_will_be_in_progress {
let mut selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
waft_foundation::merge_sort(&mut selectables, |a, b| {
MultiSelectableSelectionContainerDelegate::compare_order(self, app, *a, *b)
});
self.multi_selectable_selection_container_delegate_data_mut(app)
.selectables = selectables;
}
self.multi_selectable_selection_container_delegate_data_mut(app)
.selection_in_progress = selection_will_be_in_progress;
self.multi_selectable_selection_container_delegate_data_mut(app)
.is_handling_selection_event = true;
let result = match event.ty() {
SelectionEventType::StartEdgeUpdate | SelectionEventType::EndEdgeUpdate => {
self.set_extend_selection_in_progress(app, false);
MultiSelectableSelectionContainerDelegate::handle_selection_edge_update(
self, app, event,
)
}
SelectionEventType::Clear => {
self.set_extend_selection_in_progress(app, false);
MultiSelectableSelectionContainerDelegate::handle_clear_selection(self, app, event)
}
SelectionEventType::SelectAll => {
self.set_extend_selection_in_progress(app, false);
MultiSelectableSelectionContainerDelegate::handle_select_all(self, app, event)
}
SelectionEventType::SelectWord => {
self.set_extend_selection_in_progress(app, false);
MultiSelectableSelectionContainerDelegate::handle_select_word(self, app, event)
}
SelectionEventType::SelectParagraph => {
self.set_extend_selection_in_progress(app, false);
MultiSelectableSelectionContainerDelegate::handle_select_paragraph(self, app, event)
}
SelectionEventType::GranularlyExtendSelection => {
self.set_extend_selection_in_progress(app, true);
MultiSelectableSelectionContainerDelegate::handle_granularly_extend_selection(
self, app, event,
)
}
SelectionEventType::DirectionallyExtendSelection => {
self.set_extend_selection_in_progress(app, true);
MultiSelectableSelectionContainerDelegate::handle_directionally_extend_selection(
self, app, event,
)
}
};
self.multi_selectable_selection_container_delegate_data_mut(app)
.is_handling_selection_event = false;
MultiSelectableSelectionContainerDelegateBase::update_selection_geometry(self, app);
result
}
fn set_extend_selection_in_progress(self: Handle<Self>, app: &mut App, value: bool) {
self.multi_selectable_selection_container_delegate_data_mut(app)
.extend_selection_in_progress = value;
}
fn dispose(self: Handle<Self>, app: &mut App) {
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
for selectable in &selectables {
selectable.remove_listener(app, &selectable_geometry_change_listener(self));
}
let data = self.multi_selectable_selection_container_delegate_data_mut(app);
data.selectables = Vec::new();
data.scheduled_selectable_update = false;
ChangeNotifierData::dispose(app, self);
}
}
pub(crate) fn compare_vertically(a: Rect, b: Rect) -> Ordering {
if !a.is_finite() || !b.is_finite() {
return Ordering::Less;
}
if (a.top - b.top < K_SELECTABLE_VERTICAL_COMPARING_THRESHOLD
&& a.bottom - b.bottom > -K_SELECTABLE_VERTICAL_COMPARING_THRESHOLD)
|| (b.top - a.top < K_SELECTABLE_VERTICAL_COMPARING_THRESHOLD
&& b.bottom - a.bottom > -K_SELECTABLE_VERTICAL_COMPARING_THRESHOLD)
{
return Ordering::Equal;
}
if (a.top - b.top).abs() > K_SELECTABLE_VERTICAL_COMPARING_THRESHOLD {
return if a.top > b.top {
Ordering::Greater
} else {
Ordering::Less
};
}
if a.bottom > b.bottom {
Ordering::Greater
} else {
Ordering::Less
}
}
pub(crate) fn compare_horizontally(a: Rect, b: Rect) -> Ordering {
if a.left - b.left < PRECISION_ERROR_TOLERANCE && a.right - b.right > -PRECISION_ERROR_TOLERANCE
{
return Ordering::Less;
}
if b.left - a.left < PRECISION_ERROR_TOLERANCE && b.right - a.right > -PRECISION_ERROR_TOLERANCE
{
return Ordering::Greater;
}
if (a.left - b.left).abs() > PRECISION_ERROR_TOLERANCE {
return if a.left > b.left {
Ordering::Greater
} else {
Ordering::Less
};
}
if a.right > b.right {
Ordering::Greater
} else {
Ordering::Less
}
}
pub struct StaticSelectionContainerDelegateData {
has_received_start_event: Vec<AnySelectable>,
has_received_end_event: Vec<AnySelectable>,
last_start_edge_update_global_position: Option<Offset>,
last_end_edge_update_global_position: Option<Offset>,
}
impl StaticSelectionContainerDelegateData {
pub fn new() -> StaticSelectionContainerDelegateData {
StaticSelectionContainerDelegateData {
has_received_start_event: Vec::new(),
has_received_end_event: Vec::new(),
last_start_edge_update_global_position: None,
last_end_edge_update_global_position: None,
}
}
}
impl Default for StaticSelectionContainerDelegateData {
fn default() -> Self {
Self::new()
}
}
#[macro_export]
macro_rules! static_selection_container_delegate_accessors {
() => {
fn static_selection_container_delegate_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::StaticSelectionContainerDelegateData {
&app.get(self).static_selection_container_delegate
}
fn static_selection_container_delegate_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::StaticSelectionContainerDelegateData {
&mut app.get_mut(self).static_selection_container_delegate
}
};
}
pub trait StaticSelectionContainerDelegate: MultiSelectableSelectionContainerDelegate {
fn static_selection_container_delegate_data(
self: Handle<Self>,
app: &App,
) -> &StaticSelectionContainerDelegateData;
fn static_selection_container_delegate_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut StaticSelectionContainerDelegateData;
fn did_receive_selection_event_for(
self: Handle<Self>,
app: &mut App,
selectable: AnySelectable,
for_end: Option<bool>,
) {
StaticSelectionContainerDelegateBase::did_receive_selection_event_for(
self, app, selectable, for_end,
);
}
fn did_receive_selection_boundary_events(self: Handle<Self>, app: &mut App) {
StaticSelectionContainerDelegateBase::did_receive_selection_boundary_events(self, app);
}
fn update_last_selection_edge_location(
self: Handle<Self>,
app: &mut App,
global_selection_edge_location: Offset,
for_end: bool,
) {
StaticSelectionContainerDelegateBase::update_last_selection_edge_location(
self,
app,
global_selection_edge_location,
for_end,
);
}
fn clear_internal_selection_state(self: Handle<Self>, app: &mut App) {
StaticSelectionContainerDelegateBase::clear_internal_selection_state(self, app);
}
fn clear_internal_selection_state_for_selectable(
self: Handle<Self>,
app: &mut App,
selectable: AnySelectable,
) {
StaticSelectionContainerDelegateBase::clear_internal_selection_state_for_selectable(
self, app, selectable,
);
}
}
#[macro_export]
macro_rules! static_selection_container_delegate_selection_handler {
() => {
fn value(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> ::waft_rendering::SelectionGeometry {
$crate::StaticSelectionContainerDelegateBase::value(self, app)
}
fn push_handle_layers(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
start_handle: ::std::option::Option<
::waft_foundation::Ref<::waft_rendering::LayerLink>,
>,
end_handle: ::std::option::Option<::waft_foundation::Ref<::waft_rendering::LayerLink>>,
) {
$crate::StaticSelectionContainerDelegateBase::push_handle_layers(
self,
app,
start_handle,
end_handle,
)
}
fn selected_content(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> ::std::option::Option<::waft_rendering::SelectedContent> {
$crate::StaticSelectionContainerDelegateBase::selected_content(self, app)
}
fn selection(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> ::std::option::Option<::waft_rendering::SelectedContentRange> {
$crate::StaticSelectionContainerDelegateBase::selection(self, app)
}
fn dispatch_selection_event(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
event: &::waft_rendering::SelectionEvent,
) -> ::waft_rendering::SelectionResult {
$crate::StaticSelectionContainerDelegateBase::dispatch_selection_event(self, app, event)
}
fn content_length(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> usize {
$crate::StaticSelectionContainerDelegateBase::content_length(self, app)
}
};
}
#[macro_export]
macro_rules! static_selection_container_delegate_selection_registrar {
() => {
fn add(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
selectable: ::waft_rendering::AnySelectable,
) {
$crate::StaticSelectionContainerDelegateBase::add(self, app, selectable)
}
fn remove(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
selectable: ::waft_rendering::AnySelectable,
) {
$crate::StaticSelectionContainerDelegateBase::remove(self, app, selectable)
}
};
}
#[macro_export]
macro_rules! static_selection_container_delegate_overrides {
() => {
fn did_change_selectables(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) {
$crate::StaticSelectionContainerDelegateBase::did_change_selectables(self, app)
}
fn handle_select_all(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
event: &::waft_rendering::SelectionEvent,
) -> ::waft_rendering::SelectionResult {
$crate::StaticSelectionContainerDelegateBase::handle_select_all(self, app, event)
}
fn handle_select_word(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
event: &::waft_rendering::SelectionEvent,
) -> ::waft_rendering::SelectionResult {
$crate::StaticSelectionContainerDelegateBase::handle_select_word(self, app, event)
}
fn handle_select_paragraph(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
event: &::waft_rendering::SelectionEvent,
) -> ::waft_rendering::SelectionResult {
$crate::StaticSelectionContainerDelegateBase::handle_select_paragraph(self, app, event)
}
fn handle_clear_selection(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
event: &::waft_rendering::SelectionEvent,
) -> ::waft_rendering::SelectionResult {
$crate::StaticSelectionContainerDelegateBase::handle_clear_selection(self, app, event)
}
fn handle_selection_edge_update(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
event: &::waft_rendering::SelectionEvent,
) -> ::waft_rendering::SelectionResult {
$crate::StaticSelectionContainerDelegateBase::handle_selection_edge_update(
self, app, event,
)
}
fn dispose(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
$crate::StaticSelectionContainerDelegateBase::dispose(self, app)
}
fn ensure_child_updated(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
selectable: ::waft_rendering::AnySelectable,
) {
$crate::StaticSelectionContainerDelegateBase::ensure_child_updated(
self, app, selectable,
)
}
fn dispatch_selection_event_to_child(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
selectable: ::waft_rendering::AnySelectable,
event: &::waft_rendering::SelectionEvent,
) -> ::waft_rendering::SelectionResult {
$crate::StaticSelectionContainerDelegateBase::dispatch_selection_event_to_child(
self, app, selectable, event,
)
}
};
}
pub trait StaticSelectionContainerDelegateBase: StaticSelectionContainerDelegate {
fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
MultiSelectableSelectionContainerDelegateBase::selected_content(self, app)
}
fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
MultiSelectableSelectionContainerDelegateBase::value(self, app)
}
fn push_handle_layers(
self: Handle<Self>,
app: &mut App,
start_handle: Option<Ref<LayerLink>>,
end_handle: Option<Ref<LayerLink>>,
) {
MultiSelectableSelectionContainerDelegateBase::push_handle_layers(
self,
app,
start_handle,
end_handle,
);
}
fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
MultiSelectableSelectionContainerDelegateBase::selection(self, app)
}
fn dispatch_selection_event(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
MultiSelectableSelectionContainerDelegateBase::dispatch_selection_event(self, app, event)
}
fn content_length(self: Handle<Self>, app: &App) -> usize {
MultiSelectableSelectionContainerDelegateBase::content_length(self, app)
}
fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
MultiSelectableSelectionContainerDelegateBase::add(self, app, selectable);
}
fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
StaticSelectionContainerDelegate::clear_internal_selection_state_for_selectable(
self, app, selectable,
);
MultiSelectableSelectionContainerDelegateBase::remove(self, app, selectable);
}
fn did_receive_selection_event_for(
self: Handle<Self>,
app: &mut App,
selectable: AnySelectable,
for_end: Option<bool>,
) {
let data = self.static_selection_container_delegate_data_mut(app);
match for_end {
Some(true) => {
set_add(&mut data.has_received_end_event, selectable);
}
Some(false) => {
set_add(&mut data.has_received_start_event, selectable);
}
None => {
set_add(&mut data.has_received_start_event, selectable);
set_add(&mut data.has_received_end_event, selectable);
}
}
}
fn did_receive_selection_boundary_events(self: Handle<Self>, app: &mut App) {
let data = self.multi_selectable_selection_container_delegate_data(app);
if data.current_selection_start_index == -1 || data.current_selection_end_index == -1 {
return;
}
let start = data
.current_selection_start_index
.min(data.current_selection_end_index);
let end = data
.current_selection_start_index
.max(data.current_selection_end_index);
let selectables = data.selectables.clone();
for index in start..=end {
StaticSelectionContainerDelegate::did_receive_selection_event_for(
self,
app,
selectables[index as usize],
None,
);
}
self.update_last_selection_edge_locations_from_geometries(app);
}
fn update_last_selection_edge_location(
self: Handle<Self>,
app: &mut App,
global_selection_edge_location: Offset,
for_end: bool,
) {
let data = self.static_selection_container_delegate_data_mut(app);
if for_end {
data.last_end_edge_update_global_position = Some(global_selection_edge_location);
} else {
data.last_start_edge_update_global_position = Some(global_selection_edge_location);
}
}
fn update_last_selection_edge_locations_from_geometries(self: Handle<Self>, app: &mut App) {
let data = self.multi_selectable_selection_container_delegate_data(app);
let start_index = data.current_selection_start_index;
let end_index = data.current_selection_end_index;
let selectables = data.selectables.clone();
if start_index != -1 && selectables[start_index as usize].value(app).has_selection() {
let start = selectables[start_index as usize];
let point = start
.value(app)
.start_selection_point
.expect("a selectable with a selection has a start point");
let local_start_edge =
point.local_position + Offset::new(0.0, -point.line_height / 2.0);
let global_start_edge =
transform_point(&start.get_transform_to(app, None), local_start_edge);
StaticSelectionContainerDelegate::update_last_selection_edge_location(
self,
app,
global_start_edge,
false,
);
}
if end_index != -1 && selectables[end_index as usize].value(app).has_selection() {
let end = selectables[end_index as usize];
let point = end
.value(app)
.end_selection_point
.expect("a selectable with a selection has an end point");
let local_end_edge = point.local_position + Offset::new(0.0, -point.line_height / 2.0);
let global_end_edge = transform_point(&end.get_transform_to(app, None), local_end_edge);
StaticSelectionContainerDelegate::update_last_selection_edge_location(
self,
app,
global_end_edge,
true,
);
}
}
fn clear_internal_selection_state(self: Handle<Self>, app: &mut App) {
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
for selectable in &selectables {
StaticSelectionContainerDelegate::clear_internal_selection_state_for_selectable(
self,
app,
*selectable,
);
}
let data = self.static_selection_container_delegate_data_mut(app);
data.last_start_edge_update_global_position = None;
data.last_end_edge_update_global_position = None;
}
fn clear_internal_selection_state_for_selectable(
self: Handle<Self>,
app: &mut App,
selectable: AnySelectable,
) {
let data = self.static_selection_container_delegate_data_mut(app);
set_remove(&mut data.has_received_start_event, selectable);
set_remove(&mut data.has_received_end_event, selectable);
}
fn handle_select_all(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
let result =
MultiSelectableSelectionContainerDelegateBase::handle_select_all(self, app, event);
StaticSelectionContainerDelegate::did_receive_selection_boundary_events(self, app);
result
}
fn handle_select_word(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
let result =
MultiSelectableSelectionContainerDelegateBase::handle_select_word(self, app, event);
StaticSelectionContainerDelegate::did_receive_selection_boundary_events(self, app);
result
}
fn handle_select_paragraph(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
let result = MultiSelectableSelectionContainerDelegateBase::handle_select_paragraph(
self, app, event,
);
StaticSelectionContainerDelegate::did_receive_selection_boundary_events(self, app);
result
}
fn handle_clear_selection(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
let result =
MultiSelectableSelectionContainerDelegateBase::handle_clear_selection(self, app, event);
StaticSelectionContainerDelegate::clear_internal_selection_state(self, app);
result
}
fn handle_selection_edge_update(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
let (global_position, for_end) = match event {
SelectionEvent::StartEdgeUpdate {
global_position, ..
} => (*global_position, false),
SelectionEvent::EndEdgeUpdate {
global_position, ..
} => (*global_position, true),
_ => panic!("a selection edge update names an edge"),
};
StaticSelectionContainerDelegate::update_last_selection_edge_location(
self,
app,
global_position,
for_end,
);
MultiSelectableSelectionContainerDelegateBase::handle_selection_edge_update(
self, app, event,
)
}
fn dispose(self: Handle<Self>, app: &mut App) {
StaticSelectionContainerDelegate::clear_internal_selection_state(self, app);
MultiSelectableSelectionContainerDelegateBase::dispose(self, app);
}
fn dispatch_selection_event_to_child(
self: Handle<Self>,
app: &mut App,
selectable: AnySelectable,
event: &SelectionEvent,
) -> SelectionResult {
match event.ty() {
SelectionEventType::StartEdgeUpdate => {
StaticSelectionContainerDelegate::did_receive_selection_event_for(
self,
app,
selectable,
Some(false),
);
MultiSelectableSelectionContainerDelegate::ensure_child_updated(
self, app, selectable,
);
}
SelectionEventType::EndEdgeUpdate => {
StaticSelectionContainerDelegate::did_receive_selection_event_for(
self,
app,
selectable,
Some(true),
);
MultiSelectableSelectionContainerDelegate::ensure_child_updated(
self, app, selectable,
);
}
SelectionEventType::Clear => {
StaticSelectionContainerDelegate::clear_internal_selection_state_for_selectable(
self, app, selectable,
);
}
SelectionEventType::SelectAll
| SelectionEventType::SelectWord
| SelectionEventType::SelectParagraph => {}
SelectionEventType::GranularlyExtendSelection
| SelectionEventType::DirectionallyExtendSelection => {
StaticSelectionContainerDelegate::did_receive_selection_event_for(
self, app, selectable, None,
);
MultiSelectableSelectionContainerDelegate::ensure_child_updated(
self, app, selectable,
);
}
}
MultiSelectableSelectionContainerDelegateBase::dispatch_selection_event_to_child(
self, app, selectable, event,
)
}
fn ensure_child_updated(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
let last_end = self
.static_selection_container_delegate_data(app)
.last_end_edge_update_global_position;
if let Some(global_position) = last_end
&& set_add(
&mut self
.static_selection_container_delegate_data_mut(app)
.has_received_end_event,
selectable,
)
{
let synthesized_event = SelectionEvent::for_end(global_position, None);
if self
.multi_selectable_selection_container_delegate_data(app)
.current_selection_end_index
== -1
{
MultiSelectableSelectionContainerDelegate::handle_selection_edge_update(
self,
app,
&synthesized_event,
);
}
selectable.dispatch_selection_event(app, &synthesized_event);
}
let last_start = self
.static_selection_container_delegate_data(app)
.last_start_edge_update_global_position;
if let Some(global_position) = last_start
&& set_add(
&mut self
.static_selection_container_delegate_data_mut(app)
.has_received_start_event,
selectable,
)
{
let synthesized_event = SelectionEvent::for_start(global_position, None);
if self
.multi_selectable_selection_container_delegate_data(app)
.current_selection_start_index
== -1
{
MultiSelectableSelectionContainerDelegate::handle_selection_edge_update(
self,
app,
&synthesized_event,
);
}
selectable.dispatch_selection_event(app, &synthesized_event);
}
}
fn did_change_selectables(self: Handle<Self>, app: &mut App) {
let last_end = self
.static_selection_container_delegate_data(app)
.last_end_edge_update_global_position;
if let Some(global_position) = last_end {
MultiSelectableSelectionContainerDelegate::handle_selection_edge_update(
self,
app,
&SelectionEvent::for_end(global_position, None),
);
}
let last_start = self
.static_selection_container_delegate_data(app)
.last_start_edge_update_global_position;
if let Some(global_position) = last_start {
MultiSelectableSelectionContainerDelegate::handle_selection_edge_update(
self,
app,
&SelectionEvent::for_start(global_position, None),
);
}
let selectable_set = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
let data = self.static_selection_container_delegate_data_mut(app);
data.has_received_end_event
.retain(|selectable| set_contains(&selectable_set, *selectable));
data.has_received_start_event
.retain(|selectable| set_contains(&selectable_set, *selectable));
MultiSelectableSelectionContainerDelegateBase::did_change_selectables(self, app);
}
}
impl<T: StaticSelectionContainerDelegate> StaticSelectionContainerDelegateBase for T {}
pub struct PlainStaticSelectionContainerDelegate {
selection_container_delegate: SelectionContainerDelegateData,
multi_selectable_selection_container_delegate: MultiSelectableSelectionContainerDelegateData,
static_selection_container_delegate: StaticSelectionContainerDelegateData,
}
impl PlainStaticSelectionContainerDelegate {
pub fn new(app: &mut App) -> Ref<PlainStaticSelectionContainerDelegate> {
app.create(PlainStaticSelectionContainerDelegate {
selection_container_delegate: SelectionContainerDelegateData::new(),
multi_selectable_selection_container_delegate:
MultiSelectableSelectionContainerDelegateData::new(),
static_selection_container_delegate: StaticSelectionContainerDelegateData::new(),
})
}
}
impl SelectionContainerDelegate for PlainStaticSelectionContainerDelegate {
fn selection_container_delegate_data(
self: Handle<Self>,
app: &App,
) -> &SelectionContainerDelegateData {
&app.get(self).selection_container_delegate
}
fn selection_container_delegate_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SelectionContainerDelegateData {
&mut app.get_mut(self).selection_container_delegate
}
}
impl MultiSelectableSelectionContainerDelegate for PlainStaticSelectionContainerDelegate {
crate::multi_selectable_selection_container_delegate_accessors!();
crate::static_selection_container_delegate_overrides!();
}
impl StaticSelectionContainerDelegate for PlainStaticSelectionContainerDelegate {
crate::static_selection_container_delegate_accessors!();
}
impl SelectionHandler for PlainStaticSelectionContainerDelegate {
crate::static_selection_container_delegate_selection_handler!();
}
impl SelectionRegistrar for PlainStaticSelectionContainerDelegate {
crate::static_selection_container_delegate_selection_registrar!();
}
impl ChangeNotifier for PlainStaticSelectionContainerDelegate {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self
.multi_selectable_selection_container_delegate
.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self
.multi_selectable_selection_container_delegate
.change_notifier
}
}
impl std::fmt::Debug for PlainStaticSelectionContainerDelegate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StaticSelectionContainerDelegate")
.field(
"selectables",
&self
.multi_selectable_selection_container_delegate
.selectables,
)
.finish_non_exhaustive()
}
}
impl<T: MultiSelectableSelectionContainerDelegate> MultiSelectableSelectionContainerDelegateBase
for T
{
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SelectableRegionSelectionStatus {
Changing,
Finalized,
}
pub type SelectableRegionContextMenuBuilder =
Rc<dyn Fn(&mut App, BuildContext, Handle<SelectableRegionState>) -> WidgetRef>;
pub struct SelectableRegionSelectionStatusNotifier {
change_notifier: ChangeNotifierData,
selectable_region_selection_status: SelectableRegionSelectionStatus,
}
impl SelectableRegionSelectionStatusNotifier {
fn new() -> SelectableRegionSelectionStatusNotifier {
SelectableRegionSelectionStatusNotifier {
change_notifier: ChangeNotifierData::new(),
selectable_region_selection_status: SelectableRegionSelectionStatus::Finalized,
}
}
fn set_value(self: Handle<Self>, app: &mut App, new_status: SelectableRegionSelectionStatus) {
debug_assert!(
new_status == SelectableRegionSelectionStatus::Finalized
&& *self.value_of(app) == SelectableRegionSelectionStatus::Changing
|| new_status == SelectableRegionSelectionStatus::Changing,
"Attempting to finalize the selection when it is already finalized."
);
app.get_mut(self).selectable_region_selection_status = new_status;
self.notify_listeners(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ChangeNotifierData::dispose(app, self);
}
}
impl ChangeNotifier for SelectableRegionSelectionStatusNotifier {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self.change_notifier
}
}
impl ValueListenableHandle<SelectableRegionSelectionStatus>
for Handle<SelectableRegionSelectionStatusNotifier>
{
fn value_of(self, app: &App) -> &SelectableRegionSelectionStatus {
&app.get(self).selectable_region_selection_status
}
}
pub struct SelectableRegionSelectionStatusScope {
pub key: Option<KeyRef>,
notifier: Ref<SelectableRegionSelectionStatusNotifier>,
child: WidgetRef,
}
impl SelectableRegionSelectionStatusScope {
pub fn new<K: 'static>(
notifier: Ref<SelectableRegionSelectionStatusNotifier>,
child: impl IntoWidget<K>,
) -> SelectableRegionSelectionStatusScope {
SelectableRegionSelectionStatusScope {
key: None,
notifier,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> SelectableRegionSelectionStatusScope {
self.key = Some(key);
self
}
pub fn maybe_of(
app: &mut App,
context: BuildContext,
) -> Option<Rc<dyn ValueListenable<SelectableRegionSelectionStatus>>> {
context
.depend_on_inherited_widget_of_exact_type::<SelectableRegionSelectionStatusScope>(app)
.map(|scope| {
Rc::new(scope.notifier.clone())
as Rc<dyn ValueListenable<SelectableRegionSelectionStatus>>
})
}
}
impl std::fmt::Debug for SelectableRegionSelectionStatusScope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SelectableRegionSelectionStatusScope")
.finish_non_exhaustive()
}
}
impl InheritedWidget for SelectableRegionSelectionStatusScope {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn child(&self) -> &WidgetRef {
&self.child
}
fn update_should_notify(&self, old_widget: &SelectableRegionSelectionStatusScope) -> bool {
old_widget.notifier != self.notifier
}
}
pub struct SelectableRegion {
pub key: Option<KeyRef>,
pub magnifier_configuration: TextMagnifierConfiguration,
pub focus_node: Option<FocusNodeRef>,
pub child: WidgetRef,
pub context_menu_builder: Option<SelectableRegionContextMenuBuilder>,
pub selection_controls: Rc<dyn TextSelectionControls>,
pub on_selection_changed: Option<ValueChanged<Option<SelectedContent>>>,
}
impl SelectableRegion {
pub fn new<K>(
selection_controls: Rc<dyn TextSelectionControls>,
child: impl IntoWidget<K>,
) -> SelectableRegion {
SelectableRegion {
key: None,
magnifier_configuration: TextMagnifierConfiguration::DISABLED,
focus_node: None,
child: child.into_widget(),
context_menu_builder: None,
selection_controls,
on_selection_changed: None,
}
}
pub fn key(mut self, key: KeyRef) -> SelectableRegion {
self.key = Some(key);
self
}
pub fn focus_node(mut self, focus_node: FocusNodeRef) -> SelectableRegion {
self.focus_node = Some(focus_node);
self
}
pub fn magnifier_configuration(
mut self,
magnifier_configuration: TextMagnifierConfiguration,
) -> SelectableRegion {
self.magnifier_configuration = magnifier_configuration;
self
}
pub fn context_menu_builder(
mut self,
context_menu_builder: SelectableRegionContextMenuBuilder,
) -> SelectableRegion {
self.context_menu_builder = Some(context_menu_builder);
self
}
pub fn on_selection_changed(
mut self,
on_selection_changed: ValueChanged<Option<SelectedContent>>,
) -> SelectableRegion {
self.on_selection_changed = Some(on_selection_changed);
self
}
pub fn get_selectable_button_items(
app: &App,
selection_geometry: &SelectionGeometry,
on_copy: Listener,
on_select_all: Listener,
on_share: Option<Listener>,
) -> Vec<ContextMenuButtonItem> {
let can_copy = selection_geometry.status == SelectionStatus::Uncollapsed;
let can_select_all = selection_geometry.has_content;
let platform_can_share =
matches!(app.platform().target_platform(), TargetPlatform::Android)
&& selection_geometry.status == SelectionStatus::Uncollapsed;
let can_share = on_share.is_some() && platform_can_share;
let show_share_before_select_all =
app.platform().target_platform() == TargetPlatform::Android;
let mut items = Vec::new();
if can_copy {
items.push(
ContextMenuButtonItem::new(Some(on_copy)).r#type(ContextMenuButtonType::Copy),
);
}
if can_share && show_share_before_select_all {
items.push(
ContextMenuButtonItem::new(on_share.clone()).r#type(ContextMenuButtonType::Share),
);
}
if can_select_all {
items.push(
ContextMenuButtonItem::new(Some(on_select_all))
.r#type(ContextMenuButtonType::SelectAll),
);
}
if can_share && !show_share_before_select_all {
items.push(ContextMenuButtonItem::new(on_share).r#type(ContextMenuButtonType::Share));
}
items
}
}
impl std::fmt::Debug for SelectableRegion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SelectableRegion").finish_non_exhaustive()
}
}
impl StatefulWidget for SelectableRegion {
type State = SelectableRegionState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> SelectableRegionState {
SelectableRegionState {
state: StateData::new(),
selection_delegate: None,
selectable: None,
start_handle_layer_link: None,
end_handle_layer_link: None,
toolbar_layer_link: None,
selection_overlay: None,
last_selected_content: None,
last_orientation: None,
last_secondary_tap_down_position: None,
last_pointer_device_kind: None,
is_shift_pressed: false,
selection_start_position: None,
selection_end_position: None,
selection_start_handle_drag_position: Offset::ZERO,
selection_end_handle_drag_position: Offset::ZERO,
scheduled_selection_start_edge_update: false,
scheduled_selection_end_edge_update: false,
adjusting_selection_end: None,
directional_horizontal_baseline: None,
local_focus_node: None,
gesture_recognizers: None,
actions: None,
selection_status_notifier: None,
}
}
}
pub struct SelectableRegionState {
state: StateData<SelectableRegion>,
selection_delegate: Option<Ref<PlainStaticSelectionContainerDelegate>>,
selectable: Option<AnySelectable>,
start_handle_layer_link: Option<Ref<LayerLink>>,
end_handle_layer_link: Option<Ref<LayerLink>>,
toolbar_layer_link: Option<Ref<LayerLink>>,
selection_overlay: Option<Ref<SelectionOverlay>>,
last_selected_content: Option<SelectedContent>,
last_orientation: Option<Orientation>,
last_secondary_tap_down_position: Option<Offset>,
last_pointer_device_kind: Option<PointerDeviceKind>,
is_shift_pressed: bool,
selection_start_position: Option<Offset>,
selection_end_position: Option<Offset>,
selection_start_handle_drag_position: Offset,
selection_end_handle_drag_position: Offset,
scheduled_selection_start_edge_update: bool,
scheduled_selection_end_edge_update: bool,
adjusting_selection_end: Option<bool>,
directional_horizontal_baseline: Option<f64>,
local_focus_node: Option<Ref<FocusNode>>,
gesture_recognizers: Option<GestureRecognizerFactories>,
actions: Option<HashMap<TypeId, ActionRef>>,
selection_status_notifier: Option<Ref<SelectableRegionSelectionStatusNotifier>>,
}
impl SelectableRegionState {
fn selection_delegate(
self: Handle<Self>,
app: &App,
) -> Handle<PlainStaticSelectionContainerDelegate> {
app.get(self)
.selection_delegate
.as_ref()
.expect("the delegate is created in init_state")
.handle()
}
fn selection_geometry(self: Handle<Self>, app: &App) -> SelectionGeometry {
SelectionHandler::value(self.selection_delegate(app), app)
}
fn selectable(self: Handle<Self>, app: &App) -> Option<AnySelectable> {
app.get(self).selectable
}
fn selection_status_notifier(
self: Handle<Self>,
app: &App,
) -> Ref<SelectableRegionSelectionStatusNotifier> {
app.get(self)
.selection_status_notifier
.as_ref()
.expect("the notifier is created in init_state")
.clone()
}
fn set_selection_status(
self: Handle<Self>,
app: &mut App,
status: SelectableRegionSelectionStatus,
) {
self.selection_status_notifier(app)
.handle()
.set_value(app, status);
}
fn finalize_selectable_region_status(self: Handle<Self>, app: &mut App) {
let notifier = self.selection_status_notifier(app).handle();
if notifier.value_of(app) != &SelectableRegionSelectionStatus::Changing {
return;
}
notifier.set_value(app, SelectableRegionSelectionStatus::Finalized);
}
fn focus_node(self: Handle<Self>, app: &App) -> FocusNodeRef {
let widget = self.widget(app);
match &widget.focus_node {
Some(focus_node) => focus_node.clone(),
None => app
.get(self)
.local_focus_node
.as_ref()
.expect("a local focus node is created in init_state")
.erase(),
}
}
fn has_selection_overlay_geometry(self: Handle<Self>, app: &App) -> bool {
let geometry = self.selection_geometry(app);
geometry.start_selection_point.is_some() || geometry.end_selection_point.is_some()
}
fn select_end_to(
self: Handle<Self>,
app: &mut App,
offset: Offset,
continuous: bool,
text_granularity: Option<TextGranularity>,
) {
let Some(selectable) = self.selectable(app) else {
return;
};
if !continuous {
selectable
.dispatch_selection_event(app, &SelectionEvent::for_end(offset, text_granularity));
return;
}
if app.get(self).selection_end_position != Some(offset) {
app.get_mut(self).selection_end_position = Some(offset);
self.trigger_selection_end_edge_update(app, text_granularity);
}
}
fn select_start_to(
self: Handle<Self>,
app: &mut App,
offset: Offset,
continuous: bool,
text_granularity: Option<TextGranularity>,
) {
let Some(selectable) = self.selectable(app) else {
return;
};
if !continuous {
selectable.dispatch_selection_event(
app,
&SelectionEvent::for_start(offset, text_granularity),
);
return;
}
if app.get(self).selection_start_position != Some(offset) {
app.get_mut(self).selection_start_position = Some(offset);
self.trigger_selection_start_edge_update(app, text_granularity);
}
}
fn trigger_selection_end_edge_update(
self: Handle<Self>,
app: &mut App,
text_granularity: Option<TextGranularity>,
) {
let Some(offset) = app.get(self).selection_end_position else {
return;
};
if app.get(self).scheduled_selection_end_edge_update {
return;
}
let Some(selectable) = self.selectable(app) else {
return;
};
if selectable
.dispatch_selection_event(app, &SelectionEvent::for_end(offset, text_granularity))
== SelectionResult::Pending
{
app.get_mut(self).scheduled_selection_end_edge_update = true;
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::handle_method(self, move |this, app, _time_stamp| {
this.post_frame_end_edge_update(app, text_granularity)
}),
None,
);
}
}
fn post_frame_end_edge_update(
self: Handle<Self>,
app: &mut App,
text_granularity: Option<TextGranularity>,
) {
if !app.get(self).scheduled_selection_end_edge_update {
return;
}
app.get_mut(self).scheduled_selection_end_edge_update = false;
self.trigger_selection_end_edge_update(app, text_granularity);
}
fn trigger_selection_start_edge_update(
self: Handle<Self>,
app: &mut App,
text_granularity: Option<TextGranularity>,
) {
let Some(offset) = app.get(self).selection_start_position else {
return;
};
if app.get(self).scheduled_selection_start_edge_update {
return;
}
let Some(selectable) = self.selectable(app) else {
return;
};
if selectable
.dispatch_selection_event(app, &SelectionEvent::for_start(offset, text_granularity))
== SelectionResult::Pending
{
app.get_mut(self).scheduled_selection_start_edge_update = true;
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::handle_method(self, move |this, app, _time_stamp| {
this.post_frame_start_edge_update(app, text_granularity)
}),
None,
);
}
}
fn post_frame_start_edge_update(
self: Handle<Self>,
app: &mut App,
text_granularity: Option<TextGranularity>,
) {
if !app.get(self).scheduled_selection_start_edge_update {
return;
}
app.get_mut(self).scheduled_selection_start_edge_update = false;
self.trigger_selection_start_edge_update(app, text_granularity);
}
fn stop_selection_end_edge_update(self: Handle<Self>, app: &mut App) {
app.get_mut(self).scheduled_selection_end_edge_update = false;
app.get_mut(self).selection_end_position = None;
}
fn stop_selection_start_edge_update(self: Handle<Self>, app: &mut App) {
app.get_mut(self).scheduled_selection_start_edge_update = false;
app.get_mut(self).selection_end_position = None;
}
fn finalize_selection(self: Handle<Self>, app: &mut App) {
self.stop_selection_end_edge_update(app);
self.stop_selection_start_edge_update(app);
}
pub fn clear_selection(self: Handle<Self>, app: &mut App) {
self.finalize_selection(app);
app.get_mut(self).directional_horizontal_baseline = None;
app.get_mut(self).adjusting_selection_end = None;
if let Some(selectable) = self.selectable(app) {
selectable.dispatch_selection_event(app, &SelectionEvent::Clear);
}
self.update_selected_content_if_needed(app);
}
fn select_word_at(self: Handle<Self>, app: &mut App, offset: Offset) {
self.finalize_selection(app);
if let Some(selectable) = self.selectable(app) {
selectable.dispatch_selection_event(
app,
&SelectionEvent::SelectWord {
global_position: offset,
},
);
}
}
fn select_paragraph_at(self: Handle<Self>, app: &mut App, offset: Offset) {
self.finalize_selection(app);
if let Some(selectable) = self.selectable(app) {
selectable.dispatch_selection_event(
app,
&SelectionEvent::SelectParagraph {
global_position: offset,
absorb: false,
},
);
}
}
fn collapse_selection_at(self: Handle<Self>, app: &mut App, offset: Offset) {
self.finalize_selection(app);
self.select_start_to(app, offset, false, None);
self.select_end_to(app, offset, false, None);
}
pub fn select_all(self: Handle<Self>, app: &mut App, cause: Option<SelectionChangedCause>) {
self.clear_selection(app);
if let Some(selectable) = self.selectable(app) {
selectable.dispatch_selection_event(app, &SelectionEvent::SelectAll);
}
if cause == Some(SelectionChangedCause::Toolbar) {
self.show_handles(app);
self.show_toolbar(app, None);
}
self.update_selected_content_if_needed(app);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
self.finalize_selectable_region_status(app);
}
fn copy_selected_content(self: Handle<Self>, app: &mut App) {
let Some(selectable) = self.selectable(app) else {
return;
};
let Some(content) = selectable.selected_content(app) else {
return;
};
drop(Clipboard::set_data(
app,
ClipboardData::new(content.plain_text),
));
}
fn update_selected_content_if_needed(self: Handle<Self>, app: &mut App) {
if self.widget(app).on_selection_changed.is_none() {
return;
}
let content = self
.selectable(app)
.and_then(|selectable| selectable.selected_content(app));
let changed = app
.get(self)
.last_selected_content
.as_ref()
.map(|last| &last.plain_text)
!= content.as_ref().map(|content| &content.plain_text);
if changed {
let callback = self
.widget(app)
.on_selection_changed
.clone()
.expect("checked just now");
app.get_mut(self).last_selected_content = content.clone();
callback(app, content);
}
}
fn position_is_on_active_selection(
self: Handle<Self>,
app: &App,
global_position: Offset,
) -> bool {
let Some(selectable) = self.selectable(app) else {
return false;
};
let transform = selectable.get_transform_to(app, None);
self.selection_geometry(app)
.selection_rects
.iter()
.any(|rect| transform_rect(&transform, *rect).contains(global_position))
}
pub fn start_glyph_height(self: Handle<Self>, app: &App) -> f64 {
self.selection_geometry(app)
.start_selection_point
.expect("the region has a selection start")
.line_height
}
pub fn end_glyph_height(self: Handle<Self>, app: &App) -> f64 {
self.selection_geometry(app)
.end_selection_point
.expect("the region has a selection end")
.line_height
}
pub fn selection_endpoints(self: Handle<Self>, app: &App) -> Vec<TextSelectionPoint> {
let geometry = self.selection_geometry(app);
let start = geometry.start_selection_point;
let end = geometry.end_selection_point;
let start_local = start
.map(|point| point.local_position)
.or(end.map(|point| point.local_position))
.expect("the region has a selection point");
let end_local = end
.map(|point| point.local_position)
.or(start.map(|point| point.local_position))
.expect("the region has a selection point");
if start_local.dy() > end_local.dy() {
vec![
TextSelectionPoint::new(end_local, Some(TextDirection::Ltr)),
TextSelectionPoint::new(start_local, Some(TextDirection::Ltr)),
]
} else {
vec![
TextSelectionPoint::new(start_local, Some(TextDirection::Ltr)),
TextSelectionPoint::new(end_local, Some(TextDirection::Ltr)),
]
}
}
pub fn context_menu_button_items(
self: Handle<Self>,
app: &mut App,
) -> Vec<ContextMenuButtonItem> {
let geometry = self.selection_geometry(app);
let on_copy = Listener::handle_method(self, Self::copy_from_context_menu);
let on_select_all = Listener::handle_method(self, Self::select_all_from_context_menu);
SelectableRegion::get_selectable_button_items(app, &geometry, on_copy, on_select_all, None)
}
fn copy_from_context_menu(self: Handle<Self>, app: &mut App) {
self.copy_selected_content(app);
match app.platform().target_platform() {
TargetPlatform::Android | TargetPlatform::Fuchsia => {
self.clear_selection(app);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
self.finalize_selectable_region_status(app);
}
TargetPlatform::IOS => self.hide_toolbar(app, false),
TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
self.hide_toolbar(app, true)
}
}
}
fn select_all_from_context_menu(self: Handle<Self>, app: &mut App) {
match app.platform().target_platform() {
TargetPlatform::Android | TargetPlatform::IOS | TargetPlatform::Fuchsia => {
self.select_all(app, Some(SelectionChangedCause::Toolbar))
}
TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
self.select_all(app, None);
self.hide_toolbar(app, true);
}
}
}
pub fn context_menu_anchors(self: Handle<Self>, app: &mut App) -> TextSelectionToolbarAnchors {
if let Some(position) = app.get(self).last_secondary_tap_down_position {
app.get_mut(self).last_secondary_tap_down_position = None;
return TextSelectionToolbarAnchors::new(position);
}
let render_box = self
.context(app)
.find_render_object(app)
.and_then(|object| object.as_box())
.expect("a SelectableRegion's render object is a RenderBox");
TextSelectionToolbarAnchors::from_selection(
app,
render_box,
self.start_glyph_height(app),
self.end_glyph_height(app),
&self.selection_endpoints(app),
)
}
fn selection_overlay(self: Handle<Self>, app: &App) -> Option<Ref<SelectionOverlay>> {
app.get(self).selection_overlay.clone()
}
fn create_selection_overlay(self: Handle<Self>, app: &mut App) {
debug_assert!(self.has_selection_overlay_geometry(app));
if app.get(self).selection_overlay.is_some() {
return;
}
let geometry = self.selection_geometry(app);
let start = geometry.start_selection_point;
let end = geometry.end_selection_point;
let start_type = start
.map(|point| point.handle_type)
.unwrap_or(TextSelectionHandleType::Collapsed);
let end_type = end
.map(|point| point.handle_type)
.unwrap_or(TextSelectionHandleType::Collapsed);
let line_height_at_start = start
.map(|point| point.line_height)
.or(end.map(|point| point.line_height))
.unwrap_or(0.0);
let line_height_at_end = end
.map(|point| point.line_height)
.or(start.map(|point| point.line_height))
.unwrap_or(0.0);
let context = self.context(app);
let (start_link, end_link, toolbar_link) = {
let state = app.get(self);
(
state
.start_handle_layer_link
.clone()
.expect("created in init_state"),
state
.end_handle_layer_link
.clone()
.expect("created in init_state"),
state
.toolbar_layer_link
.clone()
.expect("created in init_state"),
)
};
let controls = self.widget(app).selection_controls.clone();
let overlay = SelectionOverlay::new(
app,
context,
start_type,
line_height_at_start,
end_type,
line_height_at_end,
self.selection_endpoints(app),
Some(controls),
None,
None,
start_link,
end_link,
toolbar_link,
);
overlay.set_on_start_handle_drag_start(
app,
Rc::new(move |app, details| {
self.handle_selection_start_handle_drag_start(app, details)
}),
);
overlay.set_on_start_handle_drag_update(
app,
Rc::new(move |app, details| {
self.handle_selection_start_handle_drag_update(app, details)
}),
);
overlay.set_on_start_handle_drag_end(
app,
Rc::new(move |app, details| self.handle_any_drag_end(app, details)),
);
overlay.set_on_end_handle_drag_start(
app,
Rc::new(move |app, details| self.handle_selection_end_handle_drag_start(app, details)),
);
overlay.set_on_end_handle_drag_update(
app,
Rc::new(move |app, details| self.handle_selection_end_handle_drag_update(app, details)),
);
overlay.set_on_end_handle_drag_end(
app,
Rc::new(move |app, details| self.handle_any_drag_end(app, details)),
);
let magnifier_configuration = self.widget(app).magnifier_configuration.clone();
let overlay = overlay.magnifier_configuration(app, magnifier_configuration);
app.get_mut(self).selection_overlay = Some(overlay);
}
fn update_selection_overlay(self: Handle<Self>, app: &mut App) {
let Some(overlay) = self.selection_overlay(app) else {
return;
};
let geometry = self.selection_geometry(app);
let start = geometry.start_selection_point;
let end = geometry.end_selection_point;
overlay.set_start_handle_type(
app,
start
.map(|point| point.handle_type)
.unwrap_or(TextSelectionHandleType::Left),
);
overlay.set_line_height_at_start(
app,
start
.map(|point| point.line_height)
.or(end.map(|point| point.line_height))
.unwrap_or(0.0),
);
overlay.set_end_handle_type(
app,
end.map(|point| point.handle_type)
.unwrap_or(TextSelectionHandleType::Right),
);
overlay.set_line_height_at_end(
app,
end.map(|point| point.line_height)
.or(start.map(|point| point.line_height))
.unwrap_or(0.0),
);
overlay.set_selection_endpoints(app, self.selection_endpoints(app));
}
fn show_handles(self: Handle<Self>, app: &mut App) -> bool {
if let Some(overlay) = self.selection_overlay(app) {
overlay.show_handles(app);
return true;
}
if !self.has_selection_overlay_geometry(app) {
return false;
}
self.create_selection_overlay(app);
self.selection_overlay(app)
.expect("created just now")
.show_handles(app);
true
}
fn show_toolbar(self: Handle<Self>, app: &mut App, location: Option<Offset>) -> bool {
if !self.has_selection_overlay_geometry(app) && self.selection_overlay(app).is_none() {
return false;
}
if self.selection_overlay(app).is_none() {
self.create_selection_overlay(app);
}
let overlay = self.selection_overlay(app).expect("created just now");
overlay.set_toolbar_location(app, location);
let uses_handles = self
.widget(app)
.selection_controls
.as_text_selection_handle_controls()
.is_some();
if !uses_handles {
return false;
}
overlay.hide_toolbar(app);
let Some(context_menu_builder) = self.widget(app).context_menu_builder.clone() else {
return false;
};
overlay.show_toolbar(
app,
Some(self.context(app)),
Some(Rc::new(move |app, context| {
context_menu_builder(app, context, self)
})),
);
true
}
pub fn hide_toolbar(self: Handle<Self>, app: &mut App, hide_handles: bool) {
if let Some(overlay) = self.selection_overlay(app) {
overlay.hide_toolbar(app);
if hide_handles {
overlay.hide_handles(app);
}
}
}
fn hide_toolbar_if_visible(self: Handle<Self>, app: &mut App) -> bool {
let visible = self
.selection_overlay(app)
.is_some_and(|overlay| overlay.toolbar_is_visible(app));
if visible {
self.hide_toolbar(app, false);
}
visible
}
fn update_selection_status(self: Handle<Self>, app: &mut App) {
if self.has_selection_overlay_geometry(app) {
self.update_selection_overlay(app);
} else {
if let Some(overlay) = app.get_mut(self).selection_overlay.take() {
overlay.dispose(app);
}
}
}
}
impl SelectableRegionState {
fn effective_consecutive_tap_count(self: Handle<Self>, app: &App, raw_count: i32) -> i32 {
let max_consecutive_tap = 3;
let platform = app.platform().target_platform();
match platform {
TargetPlatform::Android | TargetPlatform::Fuchsia => {
let max_consecutive_tap = if app
.get(self)
.last_pointer_device_kind
.is_some_and(|kind| kind != PointerDeviceKind::Mouse)
{
2
} else {
max_consecutive_tap
};
if raw_count <= max_consecutive_tap {
raw_count
} else if raw_count % max_consecutive_tap == 0 {
max_consecutive_tap
} else {
raw_count % max_consecutive_tap
}
}
TargetPlatform::Linux => {
if raw_count <= max_consecutive_tap {
raw_count
} else if raw_count % max_consecutive_tap == 0 {
max_consecutive_tap
} else {
raw_count % max_consecutive_tap
}
}
TargetPlatform::IOS | TargetPlatform::MacOS | TargetPlatform::Windows => {
raw_count.min(max_consecutive_tap)
}
}
}
fn is_precise_pointer_device(kind: PointerDeviceKind) -> bool {
matches!(kind, PointerDeviceKind::Mouse)
}
fn start_new_mouse_selection_gesture(
self: Handle<Self>,
app: &mut App,
details: TapDragDownDetails,
) {
app.get_mut(self).last_pointer_device_kind = details.kind;
let kind = details.kind;
let platform = app.platform().target_platform();
match self.effective_consecutive_tap_count(app, details.consecutive_tap_count) {
1 => {
self.focus_node(app).request_focus(app, None);
match platform {
TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {}
TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {
self.hide_toolbar(app, true);
let is_shift_pressed_valid = app.get(self).is_shift_pressed
&& self.selection_geometry(app).start_selection_point.is_some();
if is_shift_pressed_valid {
self.select_end_to(app, details.global_position, false, None);
} else {
self.clear_selection(app);
self.collapse_selection_at(app, details.global_position);
}
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
}
}
}
2 => {
self.select_word_at(app, details.global_position);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
if platform == TargetPlatform::IOS
&& kind.is_some_and(|kind| !Self::is_precise_pointer_device(kind))
{
self.show_handles(app);
}
}
3 => match platform {
TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {
if kind.is_some_and(Self::is_precise_pointer_device) {
self.select_paragraph_at(app, details.global_position);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
}
}
TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {
self.select_paragraph_at(app, details.global_position);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
}
},
_ => {}
}
self.update_selected_content_if_needed(app);
}
fn handle_mouse_drag_start(self: Handle<Self>, app: &mut App, details: TapDragStartDetails) {
let kind = details.kind;
if self.effective_consecutive_tap_count(app, details.consecutive_tap_count) == 1 {
if kind.is_some_and(|kind| !Self::is_precise_pointer_device(kind)) {
return;
}
self.select_start_to(app, details.global_position, false, None);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
}
self.update_selected_content_if_needed(app);
}
fn handle_mouse_drag_update(self: Handle<Self>, app: &mut App, details: TapDragUpdateDetails) {
let kind = details.kind;
let platform = app.platform().target_platform();
match self.effective_consecutive_tap_count(app, details.consecutive_tap_count) {
1 => {
if kind.is_some_and(|kind| !Self::is_precise_pointer_device(kind)) {
return;
}
self.select_end_to(app, details.global_position, true, None);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
}
2 => match platform {
TargetPlatform::Android | TargetPlatform::Fuchsia => {
self.select_end_to(
app,
details.global_position,
true,
Some(TextGranularity::Word),
);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
}
TargetPlatform::IOS => {
self.select_end_to(
app,
details.global_position,
true,
Some(TextGranularity::Word),
);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
if kind.is_some_and(|kind| !Self::is_precise_pointer_device(kind)) {
self.show_handles(app);
}
}
TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {
self.select_end_to(
app,
details.global_position,
true,
Some(TextGranularity::Word),
);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
}
},
3 => match platform {
TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {
if kind.is_some_and(Self::is_precise_pointer_device) {
self.select_end_to(
app,
details.global_position,
true,
Some(TextGranularity::Paragraph),
);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
}
}
TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {
self.select_end_to(
app,
details.global_position,
true,
Some(TextGranularity::Paragraph),
);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
}
},
_ => {}
}
self.update_selected_content_if_needed(app);
}
fn handle_mouse_drag_end(self: Handle<Self>, app: &mut App, _details: TapDragEndDetails) {
let is_pointer_precise = app
.get(self)
.last_pointer_device_kind
.is_some_and(Self::is_precise_pointer_device);
let should_show_selection_overlay_on_mobile = !is_pointer_precise;
match app.platform().target_platform() {
TargetPlatform::Android | TargetPlatform::Fuchsia => {
if should_show_selection_overlay_on_mobile {
self.show_handles(app);
self.show_toolbar(app, None);
}
}
TargetPlatform::IOS => {
if should_show_selection_overlay_on_mobile {
self.show_toolbar(app, None);
}
}
TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {}
}
self.finalize_selection(app);
self.update_selected_content_if_needed(app);
self.finalize_selectable_region_status(app);
}
fn handle_mouse_tap_up(self: Handle<Self>, app: &mut App, details: TapDragUpDetails) {
let platform = app.platform().target_platform();
if platform == TargetPlatform::IOS
&& self.position_is_on_active_selection(app, details.global_position)
{
let toolbar_is_visible = self
.selection_overlay(app)
.is_some_and(|overlay| overlay.toolbar_is_visible(app));
if toolbar_is_visible {
self.hide_toolbar(app, false);
} else {
self.show_toolbar(app, None);
}
return;
}
match self.effective_consecutive_tap_count(app, details.consecutive_tap_count) {
1 => match platform {
TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {
self.hide_toolbar(app, true);
self.collapse_selection_at(app, details.global_position);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
}
TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {}
},
2 => match platform {
TargetPlatform::Android | TargetPlatform::Fuchsia => {
if !Self::is_precise_pointer_device(details.kind) {
self.show_handles(app);
self.show_toolbar(app, None);
}
}
TargetPlatform::IOS => {
if !Self::is_precise_pointer_device(details.kind) {
self.show_toolbar(app, None);
}
}
TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {}
},
_ => {}
}
self.finalize_selectable_region_status(app);
self.update_selected_content_if_needed(app);
}
fn handle_touch_long_press_start(
self: Handle<Self>,
app: &mut App,
details: LongPressStartDetails,
) {
HapticFeedback::selection_click(app);
self.focus_node(app).request_focus(app, None);
self.select_word_at(app, details.global_position);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
if app.platform().target_platform() != TargetPlatform::Android {
self.show_handles(app);
}
self.update_selected_content_if_needed(app);
}
fn handle_touch_long_press_move_update(
self: Handle<Self>,
app: &mut App,
details: LongPressMoveUpdateDetails,
) {
self.select_end_to(
app,
details.global_position,
false,
Some(TextGranularity::Word),
);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
self.update_selected_content_if_needed(app);
}
fn handle_touch_long_press_end(self: Handle<Self>, app: &mut App) {
self.finalize_selection(app);
self.update_selected_content_if_needed(app);
self.finalize_selectable_region_status(app);
if app.platform().target_platform() == TargetPlatform::Android {
self.show_handles(app);
}
self.show_toolbar(app, None);
}
fn handle_right_click_down(self: Handle<Self>, app: &mut App, details: TapDownDetails) {
let previous_secondary_tap_down_position = app.get(self).last_secondary_tap_down_position;
let toolbar_is_visible = self
.selection_overlay(app)
.is_some_and(|overlay| overlay.toolbar_is_visible(app));
app.get_mut(self).last_secondary_tap_down_position = Some(details.global_position);
self.focus_node(app).request_focus(app, None);
match app.platform().target_platform() {
TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::Windows => {
let on_active_selection =
self.position_is_on_active_selection(app, details.global_position);
if on_active_selection {
self.show_handles(app);
self.show_toolbar(app, Some(details.global_position));
self.update_selected_content_if_needed(app);
return;
}
self.collapse_selection_at(app, details.global_position);
}
TargetPlatform::IOS => self.select_word_at(app, details.global_position),
TargetPlatform::MacOS => {
if previous_secondary_tap_down_position == Some(details.global_position)
&& toolbar_is_visible
{
self.hide_toolbar(app, true);
return;
}
self.select_word_at(app, details.global_position);
}
TargetPlatform::Linux => {
if toolbar_is_visible {
self.hide_toolbar(app, true);
return;
}
if !self.position_is_on_active_selection(app, details.global_position) {
self.collapse_selection_at(app, details.global_position);
}
}
}
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
self.finalize_selectable_region_status(app);
app.get_mut(self).last_secondary_tap_down_position = Some(details.global_position);
self.show_handles(app);
self.show_toolbar(app, Some(details.global_position));
self.update_selected_content_if_needed(app);
}
fn determine_is_adjusting_selection_end(
self: Handle<Self>,
app: &mut App,
forward: bool,
) -> bool {
if let Some(adjusting) = app.get(self).adjusting_selection_end {
return adjusting;
}
let geometry = self.selection_geometry(app);
let start = geometry
.start_selection_point
.expect("the region has a selection start");
let end = geometry
.end_selection_point
.expect("the region has a selection end");
let is_reversed = if start.local_position.dy() > end.local_position.dy() {
true
} else if start.local_position.dy() < end.local_position.dy() {
false
} else {
start.local_position.dx() > end.local_position.dx()
};
let adjusting_selection_end = forward != is_reversed;
app.get_mut(self).adjusting_selection_end = Some(adjusting_selection_end);
adjusting_selection_end
}
fn granularly_extend_selection(
self: Handle<Self>,
app: &mut App,
granularity: TextGranularity,
forward: bool,
) {
app.get_mut(self).directional_horizontal_baseline = None;
if !self.selection_geometry(app).has_selection() {
return;
}
let is_end = self.determine_is_adjusting_selection_end(app, forward);
if let Some(selectable) = self.selectable(app) {
selectable.dispatch_selection_event(
app,
&SelectionEvent::GranularlyExtendSelection {
forward,
is_end,
granularity,
},
);
}
self.update_selected_content_if_needed(app);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
self.finalize_selectable_region_status(app);
}
fn directionally_extend_selection(self: Handle<Self>, app: &mut App, forward: bool) {
if !self.selection_geometry(app).has_selection() {
return;
}
let adjusting_selection_end = self.determine_is_adjusting_selection_end(app, forward);
let geometry = self.selection_geometry(app);
let baseline_point = if adjusting_selection_end {
geometry
.end_selection_point
.expect("the region has a selection end")
} else {
geometry
.start_selection_point
.expect("the region has a selection start")
};
let baseline = match app.get(self).directional_horizontal_baseline {
Some(baseline) => baseline,
None => {
let baseline = baseline_point.local_position.dx();
app.get_mut(self).directional_horizontal_baseline = Some(baseline);
baseline
}
};
let context_transform = self
.context(app)
.find_render_object(app)
.expect("the region has a render object")
.get_transform_to(app, None);
let global_selection_point =
transform_point(&context_transform, Offset::new(baseline, 0.0));
if let Some(selectable) = self.selectable(app) {
selectable.dispatch_selection_event(
app,
&SelectionEvent::DirectionallyExtendSelection {
dx: global_selection_point.dx(),
is_end: adjusting_selection_end,
direction: if forward {
SelectionExtendDirection::NextLine
} else {
SelectionExtendDirection::PreviousLine
},
},
);
}
self.update_selected_content_if_needed(app);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
self.finalize_selectable_region_status(app);
}
fn build_gesture_recognizers(self: Handle<Self>) -> GestureRecognizerFactories {
let mut gestures: GestureRecognizerFactories = Vec::new();
let mouse = GestureRecognizerFactoryWithHandlers::new(
TapAndPanGestureRecognizer::new,
move |app, instance: Handle<TapAndPanGestureRecognizer>| {
instance
.set_supported_devices(app, Some(HashSet::from([PointerDeviceKind::Mouse])));
instance.set_on_tap_track_start(
app,
Some(Listener::handle_method(self, Self::handle_tap_track_start)),
);
instance.set_on_tap_track_reset(
app,
Some(Listener::handle_method(self, Self::handle_tap_track_reset)),
);
instance.set_on_tap_down(
app,
Some(Rc::new(move |app, details| {
self.start_new_mouse_selection_gesture(app, details)
})),
);
instance.set_on_tap_up(
app,
Some(Rc::new(move |app, details| {
self.handle_mouse_tap_up(app, details)
})),
);
instance.set_on_drag_start(
app,
Some(Rc::new(move |app, details| {
self.handle_mouse_drag_start(app, details)
})),
);
instance.set_on_drag_update(
app,
Some(Rc::new(move |app, details| {
self.handle_mouse_drag_update(app, details)
})),
);
instance.set_on_drag_end(
app,
Some(Rc::new(move |app, details| {
self.handle_mouse_drag_end(app, details)
})),
);
instance.set_on_cancel(
app,
Some(Listener::handle_method(self, Self::handle_gesture_cancel)),
);
instance.set_drag_start_behavior(app, DragStartBehavior::Down);
},
);
gestures.push((
TypeId::of::<TapAndPanGestureRecognizer>(),
mouse.into_factory(),
));
let touch = GestureRecognizerFactoryWithHandlers::new(
TapAndHorizontalDragGestureRecognizer::new,
move |app, instance: Handle<TapAndHorizontalDragGestureRecognizer>| {
instance.set_supported_devices(
app,
Some(
[
PointerDeviceKind::Touch,
PointerDeviceKind::Stylus,
PointerDeviceKind::InvertedStylus,
PointerDeviceKind::Trackpad,
PointerDeviceKind::Unknown,
]
.into_iter()
.collect(),
),
);
instance.set_eager_victory_on_drag(
app,
app.platform().target_platform() != TargetPlatform::IOS,
);
instance.set_on_tap_down(
app,
Some(Rc::new(move |app, details| {
self.start_new_mouse_selection_gesture(app, details)
})),
);
instance.set_on_tap_up(
app,
Some(Rc::new(move |app, details| {
self.handle_mouse_tap_up(app, details)
})),
);
instance.set_on_drag_start(
app,
Some(Rc::new(move |app, details| {
self.handle_mouse_drag_start(app, details)
})),
);
instance.set_on_drag_update(
app,
Some(Rc::new(move |app, details| {
self.handle_mouse_drag_update(app, details)
})),
);
instance.set_on_drag_end(
app,
Some(Rc::new(move |app, details| {
self.handle_mouse_drag_end(app, details)
})),
);
instance.set_on_cancel(
app,
Some(Listener::handle_method(self, Self::handle_gesture_cancel)),
);
instance.set_drag_start_behavior(app, DragStartBehavior::Down);
},
);
gestures.push((
TypeId::of::<TapAndHorizontalDragGestureRecognizer>(),
touch.into_factory(),
));
let long_press = GestureRecognizerFactoryWithHandlers::new(
LongPressGestureRecognizer::new,
move |app, instance: Handle<LongPressGestureRecognizer>| {
instance.set_supported_devices(
app,
Some(
[
PointerDeviceKind::Touch,
PointerDeviceKind::Stylus,
PointerDeviceKind::InvertedStylus,
]
.into_iter()
.collect(),
),
);
instance.set_on_long_press_start(
app,
Some(Rc::new(move |app, details| {
self.handle_touch_long_press_start(app, details)
})),
);
instance.set_on_long_press_move_update(
app,
Some(Rc::new(move |app, details| {
self.handle_touch_long_press_move_update(app, details)
})),
);
instance.set_on_long_press_end(
app,
Some(Rc::new(move |app, _details| {
self.handle_touch_long_press_end(app)
})),
);
},
);
gestures.push((
TypeId::of::<LongPressGestureRecognizer>(),
long_press.into_factory(),
));
let secondary_tap = GestureRecognizerFactoryWithHandlers::new(
TapGestureRecognizer::new,
move |app, instance: Handle<TapGestureRecognizer>| {
instance.set_on_secondary_tap_down(
app,
Some(Rc::new(move |app, details| {
self.handle_right_click_down(app, details)
})),
);
},
);
gestures.push((
TypeId::of::<TapGestureRecognizer>(),
secondary_tap.into_factory(),
));
gestures
}
fn handle_tap_track_start(self: Handle<Self>, app: &mut App) {
let keyboard = HardwareKeyboard::instance(app);
let pressed = keyboard.logical_keys_pressed(app);
app.get_mut(self).is_shift_pressed = pressed.contains(&LogicalKeyboardKey::SHIFT_LEFT)
|| pressed.contains(&LogicalKeyboardKey::SHIFT_RIGHT);
}
fn handle_tap_track_reset(self: Handle<Self>, app: &mut App) {
app.get_mut(self).is_shift_pressed = false;
}
fn handle_gesture_cancel(self: Handle<Self>, app: &mut App) {
self.clear_selection(app);
}
fn handle_focus_changed(self: Handle<Self>, app: &mut App) {
let has_focus = self.focus_node(app).has_focus(app);
if !has_focus && SchedulerBinding::lifecycle_state(app) == Some(AppLifecycleState::Resumed)
{
self.clear_selection(app);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
self.finalize_selectable_region_status(app);
}
}
fn build_actions(self: Handle<Self>, app: &mut App) -> HashMap<TypeId, ActionRef> {
let context = self.context(app);
let mut actions: HashMap<TypeId, ActionRef> = HashMap::new();
let mut insert_overridable = |app: &mut App, intent: TypeId, action: ActionRef| {
actions.insert(intent, AnyAction::overridable(app, action, context));
};
let select_all = NonOverrideAction::<SelectAllTextIntent>::new(
app,
Rc::new(move |app, _intent| {
self.select_all(app, Some(SelectionChangedCause::Keyboard));
}),
);
insert_overridable(
app,
TypeId::of::<SelectAllTextIntent>(),
select_all.into_erased(),
);
let copy = NonOverrideAction::<CopySelectionTextIntent>::new(
app,
Rc::new(move |app, _intent| self.copy_selected_content(app)),
);
insert_overridable(
app,
TypeId::of::<CopySelectionTextIntent>(),
copy.into_erased(),
);
macro_rules! granular_action {
($intent:ty, $granularity:expr) => {{
let action = NonOverrideAction::<$intent>::new(
app,
Rc::new(move |app, intent: &$intent| {
self.granularly_extend_selection(app, $granularity, intent.forward);
}),
);
insert_overridable(app, TypeId::of::<$intent>(), action.into_erased());
}};
}
macro_rules! granular_caret_action {
($intent:ty, $granularity:expr) => {{
let action = NonOverrideAction::<$intent>::new(
app,
Rc::new(move |app, intent: &$intent| {
if intent.collapse_selection {
return;
}
self.granularly_extend_selection(app, $granularity, intent.forward);
}),
);
insert_overridable(app, TypeId::of::<$intent>(), action.into_erased());
}};
}
granular_action!(
ExtendSelectionToNextWordBoundaryOrCaretLocationIntent,
TextGranularity::Word
);
granular_action!(
ExpandSelectionToDocumentBoundaryIntent,
TextGranularity::Document
);
granular_action!(ExpandSelectionToLineBreakIntent, TextGranularity::Line);
granular_caret_action!(ExtendSelectionByCharacterIntent, TextGranularity::Character);
granular_caret_action!(
ExtendSelectionToNextWordBoundaryIntent,
TextGranularity::Word
);
granular_caret_action!(ExtendSelectionToLineBreakIntent, TextGranularity::Line);
let directional = NonOverrideAction::<ExtendSelectionVerticallyToAdjacentLineIntent>::new(
app,
Rc::new(move |app, intent| {
if intent.collapse_selection {
return;
}
self.directionally_extend_selection(app, intent.forward);
}),
);
insert_overridable(
app,
TypeId::of::<ExtendSelectionVerticallyToAdjacentLineIntent>(),
directional.into_erased(),
);
granular_caret_action!(
ExtendSelectionToDocumentBoundaryIntent,
TextGranularity::Document
);
let dismiss = CallbackAction::<DismissIntent>::new(
app,
Rc::new(move |app, intent| {
if self.hide_toolbar_if_visible(app) {
None
} else {
let context = self.context(app);
Actions::invoke(app, context, intent)
}
}),
);
actions.insert(TypeId::of::<DismissIntent>(), dismiss.into_erased());
actions
}
fn build_info_for_magnifier(
self: Handle<Self>,
app: &mut App,
global_gesture_position: Offset,
selection_point: SelectionPoint,
) -> MagnifierInfo {
let selectable = self
.selectable(app)
.expect("the region has a selectable selection");
let transform = selectable.get_transform_to(app, None);
let storage = transform.to_flutter_array();
let global_transform_as_offset = Offset::new(storage[12] as f64, storage[13] as f64);
let global_selection_point_position =
selection_point.local_position + global_transform_as_offset;
let caret_rect = Rect::from_ltwh(
global_selection_point_position.dx(),
global_selection_point_position.dy() - selection_point.line_height,
0.0,
selection_point.line_height,
);
let selectable_size = selectable.size(app);
let field_bounds = Rect::from_ltwh(
global_transform_as_offset.dx(),
global_transform_as_offset.dy(),
selectable_size.width(),
selectable_size.height(),
);
MagnifierInfo::new(
global_gesture_position,
caret_rect,
field_bounds,
field_bounds,
)
}
fn handle_selection_start_handle_drag_start(
self: Handle<Self>,
app: &mut App,
details: DragStartDetails,
) {
let Some(start) = self.selection_geometry(app).start_selection_point else {
return;
};
let selectable = self.selectable(app).expect("a selection has a selectable");
let global_transform = selectable.get_transform_to(app, None);
app.get_mut(self).selection_start_handle_drag_position =
transform_point(&global_transform, start.local_position);
let info = self.build_info_for_magnifier(app, details.global_position, start);
if let Some(overlay) = self.selection_overlay(app) {
overlay.show_magnifier(app, info);
}
self.update_selected_content_if_needed(app);
}
fn handle_selection_start_handle_drag_update(
self: Handle<Self>,
app: &mut App,
details: DragUpdateDetails,
) {
let Some(start) = self.selection_geometry(app).start_selection_point else {
return;
};
let drag_position = app.get(self).selection_start_handle_drag_position + details.delta;
let state = app.get_mut(self);
state.selection_start_handle_drag_position = drag_position;
state.selection_start_position =
Some(drag_position - Offset::new(0.0, start.line_height / 2.0));
self.trigger_selection_start_edge_update(app, None);
let info = self.build_info_for_magnifier(app, details.global_position, start);
if let Some(overlay) = self.selection_overlay(app) {
overlay.update_magnifier(app, info);
}
self.update_selected_content_if_needed(app);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
}
fn handle_selection_end_handle_drag_start(
self: Handle<Self>,
app: &mut App,
details: DragStartDetails,
) {
let Some(end) = self.selection_geometry(app).end_selection_point else {
return;
};
let selectable = self.selectable(app).expect("a selection has a selectable");
let global_transform = selectable.get_transform_to(app, None);
app.get_mut(self).selection_end_handle_drag_position =
transform_point(&global_transform, end.local_position);
let info = self.build_info_for_magnifier(app, details.global_position, end);
if let Some(overlay) = self.selection_overlay(app) {
overlay.show_magnifier(app, info);
}
self.update_selected_content_if_needed(app);
}
fn handle_selection_end_handle_drag_update(
self: Handle<Self>,
app: &mut App,
details: DragUpdateDetails,
) {
let Some(end) = self.selection_geometry(app).end_selection_point else {
return;
};
let drag_position = app.get(self).selection_end_handle_drag_position + details.delta;
let state = app.get_mut(self);
state.selection_end_handle_drag_position = drag_position;
state.selection_end_position =
Some(drag_position - Offset::new(0.0, end.line_height / 2.0));
self.trigger_selection_end_edge_update(app, None);
let info = self.build_info_for_magnifier(app, details.global_position, end);
if let Some(overlay) = self.selection_overlay(app) {
overlay.update_magnifier(app, info);
}
self.update_selected_content_if_needed(app);
self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
}
fn handle_any_drag_end(self: Handle<Self>, app: &mut App, _details: DragEndDetails) {
let dragging_handles = self.selection_overlay(app).is_some_and(|overlay| {
overlay.is_dragging_start_handle(app) || overlay.is_dragging_end_handle(app)
});
if !dragging_handles {
if let Some(overlay) = self.selection_overlay(app) {
overlay.hide_magnifier(app);
}
self.show_toolbar(app, None);
}
self.finalize_selection(app);
self.update_selected_content_if_needed(app);
self.finalize_selectable_region_status(app);
}
}
impl State for SelectableRegionState {
type Widget = SelectableRegion;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
let delegate = PlainStaticSelectionContainerDelegate::new(app);
let start_handle_layer_link = LayerLink::new(app);
let end_handle_layer_link = LayerLink::new(app);
let toolbar_layer_link = LayerLink::new(app);
let local_focus_node = if self.widget(app).focus_node.is_none() {
Some(FocusNode::new(app))
} else {
None
};
let selection_status_notifier = app.create(SelectableRegionSelectionStatusNotifier::new());
{
let state = app.get_mut(self);
state.selection_delegate = Some(delegate);
state.start_handle_layer_link = Some(start_handle_layer_link);
state.end_handle_layer_link = Some(end_handle_layer_link);
state.toolbar_layer_link = Some(toolbar_layer_link);
state.local_focus_node = local_focus_node;
state.selection_status_notifier = Some(selection_status_notifier);
}
self.focus_node(app).add_listener(
app,
Listener::handle_method(self, Self::handle_focus_changed),
);
let gestures = self.build_gesture_recognizers();
app.get_mut(self).gesture_recognizers = Some(gestures);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SelectableRegion) {
let new_focus_node = self.widget(app).focus_node.clone();
if new_focus_node.as_ref().map(|node| node.id())
!= old_widget.focus_node.as_ref().map(|node| node.id())
{
if old_widget.focus_node.is_none() && new_focus_node.is_some() {
if let Some(local) = app.get_mut(self).local_focus_node.take() {
local.handle().remove_listener(
app,
&Listener::handle_method(self, Self::handle_focus_changed),
);
local.handle().dispose(app);
}
} else if let (None, Some(old_focus_node)) = (&new_focus_node, &old_widget.focus_node) {
old_focus_node.handle().remove_listener(
app,
&Listener::handle_method(self, Self::handle_focus_changed),
);
let local = FocusNode::new(app);
app.get_mut(self).local_focus_node = Some(local);
}
self.focus_node(app).add_listener(
app,
Listener::handle_method(self, Self::handle_focus_changed),
);
let has_focus = self.focus_node(app).has_focus(app);
let old_has_focus = old_widget
.focus_node
.as_ref()
.map(|node| node.handle().has_focus(app));
if Some(has_focus) != old_has_focus {
self.handle_focus_changed(app);
}
}
}
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
let platform = app.platform().target_platform();
if !matches!(platform, TargetPlatform::Android | TargetPlatform::IOS) {
return;
}
let orientation = MediaQuery::orientation_of(app, self.context(app));
let last_orientation = app.get(self).last_orientation;
if last_orientation.is_none() {
app.get_mut(self).last_orientation = Some(orientation);
return;
}
if last_orientation != Some(orientation) {
app.get_mut(self).last_orientation = Some(orientation);
self.hide_toolbar(app, platform == TargetPlatform::Android);
}
}
fn dispose(self: Handle<Self>, app: &mut App) {
if let Some(selectable) = app.get(self).selectable {
selectable.remove_listener(
app,
&Listener::handle_method(self, Self::update_selection_status),
);
selectable.push_handle_layers(app, None, None);
}
let delegate = self.selection_delegate(app);
MultiSelectableSelectionContainerDelegate::dispose(delegate, app);
let notifier = self.selection_status_notifier(app);
notifier.dispose(app);
if let Some(local_focus_node) = app.get_mut(self).local_focus_node.take() {
local_focus_node.handle().remove_listener(
app,
&Listener::handle_method(self, Self::handle_focus_changed),
);
local_focus_node.handle().dispose(app);
} else if let Some(focus_node) = self.widget(app).focus_node.clone() {
focus_node.handle().remove_listener(
app,
&Listener::handle_method(self, Self::handle_focus_changed),
);
}
if let Some(overlay) = app.get_mut(self).selection_overlay.take() {
overlay.hide_magnifier(app);
overlay.dispose(app);
}
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let widget = self.widget(app);
let notifier = self.selection_status_notifier(app);
let delegate = self.selection_delegate(app).keep(app).into_erased();
let registrar = SelectionRegistrar::as_selection_registrar(self).keep(app);
let container =
SelectionContainer::new(delegate, widget.child.clone()).registrar(registrar);
let result = SelectableRegionSelectionStatusScope::new(notifier, container).into_widget();
let gestures = app
.get(self)
.gesture_recognizers
.clone()
.expect("the gestures are created in init_state");
if app.get(self).actions.is_none() {
let actions = self.build_actions(app);
app.get_mut(self).actions = Some(actions);
}
let actions = app.get(self).actions.clone().expect("built above");
let focus_node = self.focus_node(app);
let toolbar_layer_link = app
.get(self)
.toolbar_layer_link
.clone()
.expect("created in init_state");
let focus = Focus::with_external_focus_node(result, focus_node).into_widget();
let actions = Actions::new(actions, focus).into_widget();
let detector = RawGestureDetector::new()
.gestures(gestures)
.behavior(HitTestBehavior::Translucent)
.child(actions)
.into_widget();
let target = CompositedTransformTarget::new(toolbar_layer_link)
.child(detector)
.into_widget();
TapRegion::new(target)
.group_id(TypeId::of::<SelectableRegion>())
.into_widget()
}
}
struct NonOverrideAction<T: Intent> {
action: ActionData,
invoke_action: InvokeAction<T>,
}
type InvokeAction<T> = Rc<dyn Fn(&mut App, &T)>;
impl<T: Intent> NonOverrideAction<T> {
fn new(app: &mut App, invoke_action: InvokeAction<T>) -> Ref<NonOverrideAction<T>> {
app.create(NonOverrideAction {
action: ActionData::new(),
invoke_action,
})
}
}
impl<T: Intent> Action for NonOverrideAction<T> {
type Intent = T;
crate::action_accessors!();
crate::context_action_overrides!();
}
impl<T: Intent> ContextAction for NonOverrideAction<T> {
fn invoke(
self: Handle<Self>,
app: &mut App,
intent: &T,
_context: Option<BuildContext>,
) -> Option<Rc<dyn std::any::Any>> {
if let Some(calling_action) = Action::calling_action(self, app) {
return calling_action.invoke(app, intent, None);
}
let invoke_action = Rc::clone(&app.get(self).invoke_action);
invoke_action(app, intent);
None
}
}
impl SelectionRegistrar for SelectableRegionState {
fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
debug_assert!(app.get(self).selectable.is_none());
app.get_mut(self).selectable = Some(selectable);
selectable.add_listener(
app,
Listener::handle_method(self, Self::update_selection_status),
);
let (start, end) = {
let state = app.get(self);
(
state.start_handle_layer_link.clone(),
state.end_handle_layer_link.clone(),
)
};
selectable.push_handle_layers(app, start, end);
}
fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
debug_assert!(app.get(self).selectable == Some(selectable));
selectable.remove_listener(
app,
&Listener::handle_method(self, Self::update_selection_status),
);
selectable.push_handle_layers(app, None, None);
app.get_mut(self).selectable = None;
}
}
#[cfg(test)]
mod tests {
use waft_embedder::{Offset, Rect, Size, TextDirection, TextPosition};
use waft_foundation::{App, Handle, Ref};
use waft_rendering::{RenderBox, RenderHandle, RenderParagraph};
use super::*;
use crate::Placeholder;
use crate::framework::{IntoWidget, WidgetRef};
use std::time::Duration;
use waft_scheduler::{FrameTarget, SchedulerBinding};
use crate::testing::{
TargetPlatformVariant, TestPointer, WidgetTester, find, test_widgets, test_widgets_variant,
};
use crate::widgets::basic::{Builder, Center, Column, SizedBox};
use crate::widgets::selection_container::{SelectionContainer, SelectionRegistrarScope};
use crate::widgets::text::Text;
fn selectable_text(text: &'static str) -> WidgetRef {
Text::new(text)
.text_direction(TextDirection::Ltr)
.into_widget()
}
fn text_offset_to_position(
tester: &WidgetTester,
paragraph: RenderHandle<RenderParagraph>,
offset: i32,
) -> Offset {
tester.update(|app| {
let caret = Rect::from_ltwh(0.0, 0.0, 2.0, 20.0);
let local_offset =
paragraph.get_offset_for_caret(app, TextPosition::new(offset), caret)
+ Offset::new(0.0, paragraph.preferred_line_height(app));
paragraph.as_box().local_to_global(app, local_offset, None) + Offset::new(0.0, -2.0)
})
}
struct TestSelectionRegistrar {
selectables: Vec<AnySelectable>,
}
impl SelectionRegistrar for TestSelectionRegistrar {
fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
set_add(&mut app.get_mut(self).selectables, selectable);
}
fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
set_remove(&mut app.get_mut(self).selectables, selectable);
}
}
struct TestContainerDelegate {
selection_container_delegate: SelectionContainerDelegateData,
multi_selectable_selection_container_delegate:
MultiSelectableSelectionContainerDelegateData,
}
impl TestContainerDelegate {
fn new(app: &mut App) -> Ref<TestContainerDelegate> {
app.create(TestContainerDelegate {
selection_container_delegate: SelectionContainerDelegateData::new(),
multi_selectable_selection_container_delegate:
MultiSelectableSelectionContainerDelegateData::new(),
})
}
}
impl SelectionContainerDelegate for TestContainerDelegate {
fn selection_container_delegate_data(
self: Handle<Self>,
app: &App,
) -> &SelectionContainerDelegateData {
&app.get(self).selection_container_delegate
}
fn selection_container_delegate_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SelectionContainerDelegateData {
&mut app.get_mut(self).selection_container_delegate
}
}
impl MultiSelectableSelectionContainerDelegate for TestContainerDelegate {
crate::multi_selectable_selection_container_delegate_accessors!();
fn ensure_child_updated(self: Handle<Self>, _app: &mut App, _selectable: AnySelectable) {
panic!("UnimplementedError");
}
fn dispatch_selection_event_to_child(
self: Handle<Self>,
_app: &mut App,
_selectable: AnySelectable,
_event: &SelectionEvent,
) -> SelectionResult {
panic!("UnimplementedError");
}
}
impl SelectionHandler for TestContainerDelegate {
fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
MultiSelectableSelectionContainerDelegateBase::value(self, app)
}
fn push_handle_layers(
self: Handle<Self>,
app: &mut App,
start_handle: Option<Ref<LayerLink>>,
end_handle: Option<Ref<LayerLink>>,
) {
MultiSelectableSelectionContainerDelegateBase::push_handle_layers(
self,
app,
start_handle,
end_handle,
);
}
fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
MultiSelectableSelectionContainerDelegateBase::selected_content(self, app)
}
fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
MultiSelectableSelectionContainerDelegateBase::selection(self, app)
}
fn dispatch_selection_event(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
MultiSelectableSelectionContainerDelegateBase::dispatch_selection_event(
self, app, event,
)
}
fn content_length(self: Handle<Self>, app: &App) -> usize {
MultiSelectableSelectionContainerDelegateBase::content_length(self, app)
}
}
impl SelectionRegistrar for TestContainerDelegate {
fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
MultiSelectableSelectionContainerDelegateBase::add(self, app, selectable);
}
fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
MultiSelectableSelectionContainerDelegateBase::remove(self, app, selectable);
}
}
impl ChangeNotifier for TestContainerDelegate {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self
.multi_selectable_selection_container_delegate
.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self
.multi_selectable_selection_container_delegate
.change_notifier
}
}
struct ColumnSelectionContainerDelegate {
selection_container_delegate: SelectionContainerDelegateData,
multi_selectable_selection_container_delegate:
MultiSelectableSelectionContainerDelegateData,
static_selection_container_delegate: StaticSelectionContainerDelegateData,
}
impl ColumnSelectionContainerDelegate {
fn new(app: &mut App) -> Ref<ColumnSelectionContainerDelegate> {
app.create(ColumnSelectionContainerDelegate {
selection_container_delegate: SelectionContainerDelegateData::new(),
multi_selectable_selection_container_delegate:
MultiSelectableSelectionContainerDelegateData::new(),
static_selection_container_delegate: StaticSelectionContainerDelegateData::new(),
})
}
}
impl SelectionContainerDelegate for ColumnSelectionContainerDelegate {
fn selection_container_delegate_data(
self: Handle<Self>,
app: &App,
) -> &SelectionContainerDelegateData {
&app.get(self).selection_container_delegate
}
fn selection_container_delegate_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SelectionContainerDelegateData {
&mut app.get_mut(self).selection_container_delegate
}
}
impl MultiSelectableSelectionContainerDelegate for ColumnSelectionContainerDelegate {
crate::multi_selectable_selection_container_delegate_accessors!();
crate::static_selection_container_delegate_overrides!();
}
impl StaticSelectionContainerDelegate for ColumnSelectionContainerDelegate {
crate::static_selection_container_delegate_accessors!();
}
impl SelectionHandler for ColumnSelectionContainerDelegate {
fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
StaticSelectionContainerDelegateBase::value(self, app)
}
fn push_handle_layers(
self: Handle<Self>,
app: &mut App,
start_handle: Option<Ref<LayerLink>>,
end_handle: Option<Ref<LayerLink>>,
) {
StaticSelectionContainerDelegateBase::push_handle_layers(
self,
app,
start_handle,
end_handle,
);
}
fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
let selectables = self
.multi_selectable_selection_container_delegate_data(app)
.selectables
.clone();
let selections: Vec<SelectedContent> = selectables
.iter()
.filter_map(|selectable| selectable.selected_content(app))
.collect();
if selections.is_empty() {
return None;
}
let plain_text = selections
.iter()
.map(|selection| selection.plain_text.clone())
.collect::<Vec<String>>()
.join("\n");
Some(SelectedContent::new(plain_text))
}
fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
StaticSelectionContainerDelegateBase::selection(self, app)
}
fn dispatch_selection_event(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
StaticSelectionContainerDelegateBase::dispatch_selection_event(self, app, event)
}
fn content_length(self: Handle<Self>, app: &App) -> usize {
StaticSelectionContainerDelegateBase::content_length(self, app)
}
}
impl SelectionRegistrar for ColumnSelectionContainerDelegate {
crate::static_selection_container_delegate_selection_registrar!();
}
impl ChangeNotifier for ColumnSelectionContainerDelegate {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self
.multi_selectable_selection_container_delegate
.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self
.multi_selectable_selection_container_delegate
.change_notifier
}
}
use std::cell::RefCell;
use waft_gestures::K_PRIMARY_BUTTON;
use crate::testing::TestWidgetsApp;
fn paragraph_showing(tester: &WidgetTester, text: &str) -> RenderHandle<RenderParagraph> {
let paragraphs = tester.all::<RenderParagraph>();
tester.update(|app| {
*paragraphs
.iter()
.find(|paragraph| paragraph.text(app).to_plain_text(true, true) == text)
.unwrap_or_else(|| panic!("a paragraph showing {text}"))
})
}
fn paragraph_selection(
tester: &WidgetTester,
paragraph: RenderHandle<RenderParagraph>,
) -> (i32, i32) {
tester.update(|app| {
let selections = paragraph.selections(app);
assert_eq!(selections.len(), 1, "one selection");
(selections[0].base_offset, selections[0].extent_offset)
})
}
fn selectable_region<K: 'static>(child: impl IntoWidget<K>) -> SelectableRegion {
SelectableRegion::new(crate::testing::test_text_selection_handle_controls(), child)
.context_menu_builder(Rc::new(|_app, _context, _state| {
SizedBox::shrink().into_widget()
}))
}
fn pump_region<K: 'static>(tester: &mut WidgetTester, child: impl IntoWidget<K>) {
tester.pump_widget(TestWidgetsApp::new().home(selectable_region(child)));
}
#[test]
fn mouse_can_select_single_text_on_desktop_platforms() {
test_widgets_variant(TargetPlatformVariant::desktop(), |tester| {
pump_region(tester, Center::new().child(Text::new("How are you")));
let paragraph = paragraph_showing(tester, "How are you");
let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
let at = text_offset_to_position(tester, paragraph, 2);
tester.down(&mut gesture, at);
tester.pump();
let at = text_offset_to_position(tester, paragraph, 4);
tester.move_to(&mut gesture, at, true);
tester.pump();
assert_eq!(paragraph_selection(tester, paragraph), (2, 4));
let at = text_offset_to_position(tester, paragraph, 6);
tester.move_to(&mut gesture, at, true);
tester.pump();
assert_eq!(paragraph_selection(tester, paragraph), (2, 6));
let at = text_offset_to_position(tester, paragraph, 1);
tester.move_to(&mut gesture, at, true);
tester.pump();
assert_eq!(paragraph_selection(tester, paragraph), (2, 1));
tester.up(&gesture);
tester.pump_and_settle();
let at = text_offset_to_position(tester, paragraph, 5);
tester.down(&mut gesture, at);
tester.pump_and_settle();
assert_eq!(paragraph_selection(tester, paragraph), (5, 5));
let at = text_offset_to_position(tester, paragraph, 5) + Offset::new(0.0, 200.0);
tester.move_to(&mut gesture, at, true);
tester.pump();
assert_eq!(paragraph_selection(tester, paragraph), (5, 11));
tester.up(&gesture);
tester.remove_pointer(&gesture);
});
}
#[test]
fn mouse_can_select_multiple_widgets() {
test_widgets(|tester| {
pump_region(tester, three_texts());
let paragraph_1 = paragraph_showing(tester, "How are you?");
let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
let at = text_offset_to_position(tester, paragraph_1, 2);
tester.down(&mut gesture, at);
tester.pump();
let at = text_offset_to_position(tester, paragraph_1, 4);
tester.move_to(&mut gesture, at, true);
tester.pump();
assert_eq!(paragraph_selection(tester, paragraph_1), (2, 4));
let paragraph_2 = paragraph_showing(tester, "Good, and you?");
let at = text_offset_to_position(tester, paragraph_2, 5);
tester.move_to(&mut gesture, at, true);
assert_eq!(paragraph_selection(tester, paragraph_1), (2, 12));
assert_eq!(paragraph_selection(tester, paragraph_2), (0, 5));
let paragraph_3 = paragraph_showing(tester, "Fine, thank you.");
let at = text_offset_to_position(tester, paragraph_3, 6);
tester.move_to(&mut gesture, at, true);
assert_eq!(paragraph_selection(tester, paragraph_1), (2, 12));
assert_eq!(paragraph_selection(tester, paragraph_2), (0, 14));
assert_eq!(paragraph_selection(tester, paragraph_3), (0, 6));
tester.up(&gesture);
tester.remove_pointer(&gesture);
});
}
#[test]
fn mouse_can_reverse_selection() {
test_widgets(|tester| {
pump_region(tester, three_texts());
let paragraph_3 = paragraph_showing(tester, "Fine, thank you.");
let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
let at = text_offset_to_position(tester, paragraph_3, 10);
tester.down(&mut gesture, at);
tester.pump();
let at = text_offset_to_position(tester, paragraph_3, 4);
tester.move_to(&mut gesture, at, true);
tester.pump();
assert_eq!(paragraph_selection(tester, paragraph_3), (10, 4));
let paragraph_2 = paragraph_showing(tester, "Good, and you?");
let at = text_offset_to_position(tester, paragraph_2, 5);
tester.move_to(&mut gesture, at, true);
assert_eq!(paragraph_selection(tester, paragraph_3), (10, 0));
assert_eq!(paragraph_selection(tester, paragraph_2), (14, 5));
let paragraph_1 = paragraph_showing(tester, "How are you?");
let at = text_offset_to_position(tester, paragraph_1, 6);
tester.move_to(&mut gesture, at, true);
assert_eq!(paragraph_selection(tester, paragraph_3), (10, 0));
assert_eq!(paragraph_selection(tester, paragraph_2), (14, 0));
assert_eq!(paragraph_selection(tester, paragraph_1), (12, 6));
tester.up(&gesture);
tester.remove_pointer(&gesture);
});
}
#[derive(Debug)]
struct SelectionSpy;
impl crate::framework::RenderObjectWidget for SelectionSpy {
type RenderObject = RenderSelectionSpy;
fn create_render_object(
&self,
app: &mut App,
context: BuildContext,
) -> waft_rendering::AnyRenderObject {
let registrar = SelectionContainer::maybe_of(app, context);
let spy = RenderHandle::new_box(
app,
RenderSelectionSpy {
render_object: waft_rendering::RenderObjectData::new(),
render_box: waft_rendering::RenderBoxData::new(),
selection_registrant: waft_rendering::SelectionRegistrantData::new(),
listeners: Vec::new(),
events: Vec::new(),
},
);
waft_rendering::SelectionRegistrant::set_registrar(spy.handle(), app, registrar);
spy.as_object()
}
}
impl crate::framework::LeafRenderObjectWidget for SelectionSpy {}
struct RenderSelectionSpy {
render_object: waft_rendering::RenderObjectData,
render_box: waft_rendering::RenderBoxData,
selection_registrant: waft_rendering::SelectionRegistrantData,
listeners: Vec<Listener>,
events: Vec<SelectionEvent>,
}
impl waft_rendering::RenderObject for RenderSelectionSpy {
waft_rendering::render_object_accessors!();
fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
let size = self.constraints(app).biggest();
self.set_size(app, size);
}
fn dispose(self: RenderHandle<Self>, app: &mut App) {
waft_rendering::SelectionRegistrant::dispose_selection_registrant(self.handle(), app);
waft_rendering::RenderObjectBase::dispose(self, app);
}
}
impl RenderBox for RenderSelectionSpy {
waft_rendering::render_box_accessors!();
}
impl waft_foundation::ListenableObject for RenderSelectionSpy {
fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
app.get_mut(self).listeners.push(listener);
}
fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
app.get_mut(self).listeners.retain(|held| held != listener);
}
}
impl SelectionHandler for RenderSelectionSpy {
fn value(self: Handle<Self>, _app: &App) -> SelectionGeometry {
let point = SelectionPoint::new(Offset::ZERO, 0.0, TextSelectionHandleType::Left);
SelectionGeometry::new(SelectionStatus::Uncollapsed, true)
.start_selection_point(Some(point))
.end_selection_point(Some(point))
}
fn push_handle_layers(
self: Handle<Self>,
_app: &mut App,
_start_handle: Option<Ref<LayerLink>>,
_end_handle: Option<Ref<LayerLink>>,
) {
}
fn selected_content(self: Handle<Self>, _app: &App) -> Option<SelectedContent> {
Some(SelectedContent::new("content"))
}
fn selection(self: Handle<Self>, _app: &App) -> Option<SelectedContentRange> {
None
}
fn dispatch_selection_event(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
app.get_mut(self).events.push(event.clone());
SelectionResult::End
}
fn content_length(self: Handle<Self>, _app: &App) -> usize {
1
}
}
impl waft_rendering::Selectable for RenderSelectionSpy {
fn get_transform_to(
self: Handle<Self>,
app: &App,
ancestor: Option<waft_rendering::AnyRenderObject>,
) -> waft_embedder::Matrix4 {
RenderHandle::from_handle(self)
.as_object()
.get_transform_to(app, ancestor)
}
fn size(self: Handle<Self>, app: &mut App) -> Size {
RenderBox::size(RenderHandle::from_handle(self), app)
}
fn bounding_boxes(self: Handle<Self>, app: &mut App) -> Vec<Rect> {
vec![
RenderHandle::from_handle(self)
.as_object()
.paint_bounds(app),
]
}
fn dispose_selectable(self: Handle<Self>, _app: &mut App) {}
}
impl waft_rendering::SelectionRegistrant for RenderSelectionSpy {
fn selection_registrant_data(
self: Handle<Self>,
app: &App,
) -> &waft_rendering::SelectionRegistrantData {
&app.get(self).selection_registrant
}
fn selection_registrant_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut waft_rendering::SelectionRegistrantData {
&mut app.get_mut(self).selection_registrant
}
}
fn spy_events(tester: &WidgetTester) -> Vec<SelectionEvent> {
let spy = tester.all::<RenderSelectionSpy>()[0];
tester.update(|app| spy.get(app).events.clone())
}
fn clear_spy_events(tester: &WidgetTester) {
let spy = tester.all::<RenderSelectionSpy>()[0];
tester.update(|app| spy.get_mut(app).events.clear());
}
fn edge_update(event: &SelectionEvent) -> (SelectionEventType, Offset, TextGranularity) {
match event {
SelectionEvent::StartEdgeUpdate {
global_position,
granularity,
} => (
SelectionEventType::StartEdgeUpdate,
*global_position,
*granularity,
),
SelectionEvent::EndEdgeUpdate {
global_position,
granularity,
} => (
SelectionEventType::EndEdgeUpdate,
*global_position,
*granularity,
),
other => panic!("not an edge update: {other:?}"),
}
}
fn select_word_position(event: &SelectionEvent) -> Offset {
match event {
SelectionEvent::SelectWord { global_position } => *global_position,
other => panic!("not a select-word event: {other:?}"),
}
}
#[test]
fn mouse_selection_single_click_sends_correct_events() {
test_widgets(|tester| {
pump_region(tester, SelectionSpy);
tester.pump_and_settle();
let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
tester.down(&mut gesture, Offset::new(200.0, 200.0));
tester.pump_and_settle();
clear_spy_events(tester);
tester.move_to(&mut gesture, Offset::new(200.0, 100.0), true);
let events = spy_events(tester);
assert_eq!(events.len(), 2);
let (ty, position, _) = edge_update(&events[0]);
assert_eq!(ty, SelectionEventType::StartEdgeUpdate);
assert_eq!(position, Offset::new(200.0, 200.0));
let (ty, position, _) = edge_update(&events[1]);
assert_eq!(ty, SelectionEventType::EndEdgeUpdate);
assert_eq!(position, Offset::new(200.0, 100.0));
clear_spy_events(tester);
tester.move_to(&mut gesture, Offset::new(100.0, 100.0), true);
let events = spy_events(tester);
assert_eq!(events.len(), 1);
let (ty, position, _) = edge_update(&events[0]);
assert_eq!(ty, SelectionEventType::EndEdgeUpdate);
assert_eq!(position, Offset::new(100.0, 100.0));
tester.up(&gesture);
tester.remove_pointer(&gesture);
});
}
fn double_click_spy(tester: &mut WidgetTester, mut gesture: TestPointer) {
pump_region(tester, SelectionSpy);
tester.down(&mut gesture, Offset::new(200.0, 200.0));
tester.pump();
tester.up(&gesture);
tester.pump();
clear_spy_events(tester);
tester.down(&mut gesture, Offset::new(200.0, 200.0));
tester.pump();
tester.up(&gesture);
let events = spy_events(tester);
assert_eq!(events.len(), 1);
assert_eq!(select_word_position(&events[0]), Offset::new(200.0, 200.0));
tester.remove_pointer(&gesture);
}
#[test]
fn mouse_double_click_sends_select_word_event() {
test_widgets(|tester| {
let gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
double_click_spy(tester, gesture);
});
}
#[test]
fn touch_double_click_sends_select_word_event() {
test_widgets(|tester| {
let gesture = TestPointer::touch(tester.next_pointer());
double_click_spy(tester, gesture);
});
}
#[test]
fn touch_does_not_accept_drag() {
test_widgets(|tester| {
pump_region(tester, SelectionSpy);
let mut gesture = TestPointer::touch(tester.next_pointer());
tester.down(&mut gesture, Offset::new(200.0, 200.0));
tester.move_to(&mut gesture, Offset::new(200.0, 100.0), true);
tester.up(&gesture);
assert!(
spy_events(tester)
.iter()
.all(|event| matches!(event, SelectionEvent::Clear))
);
tester.remove_pointer(&gesture);
});
}
#[test]
fn mouse_single_click_selection_collapses_the_selection() {
test_widgets(|tester| {
pump_region(tester, SelectionSpy);
tester.pump_and_settle();
let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
tester.down(&mut gesture, Offset::new(200.0, 200.0));
tester.pump();
tester.up(&gesture);
tester.pump_and_settle();
let events = spy_events(tester);
assert_eq!(events.len(), 2);
assert_eq!(
edge_update(&events[0]).0,
SelectionEventType::StartEdgeUpdate
);
assert_eq!(edge_update(&events[1]).0, SelectionEventType::EndEdgeUpdate);
tester.remove_pointer(&gesture);
});
}
#[test]
fn touch_long_press_sends_select_word_event() {
test_widgets(|tester| {
pump_region(tester, SelectionSpy);
tester.pump_and_settle();
clear_spy_events(tester);
let mut gesture = TestPointer::touch(tester.next_pointer());
tester.down(&mut gesture, Offset::new(200.0, 200.0));
tester.pump_by(Duration::from_millis(500));
tester.up(&gesture);
let events = spy_events(tester);
assert_eq!(events.len(), 1);
assert_eq!(select_word_position(&events[0]), Offset::new(200.0, 200.0));
tester.remove_pointer(&gesture);
});
}
#[test]
fn touch_long_press_and_drag_sends_correct_events() {
test_widgets(|tester| {
pump_region(tester, SelectionSpy);
tester.pump_and_settle();
clear_spy_events(tester);
let mut gesture = TestPointer::touch(tester.next_pointer());
tester.down(&mut gesture, Offset::new(200.0, 200.0));
tester.pump_by(Duration::from_millis(500));
let events = spy_events(tester);
assert_eq!(events.len(), 1);
assert_eq!(select_word_position(&events[0]), Offset::new(200.0, 200.0));
clear_spy_events(tester);
tester.move_to(&mut gesture, Offset::new(200.0, 50.0), true);
tester.up(&gesture);
let events = spy_events(tester);
assert_eq!(events.len(), 1);
let (ty, position, granularity) = edge_update(&events[0]);
assert_eq!(ty, SelectionEventType::EndEdgeUpdate);
assert_eq!(position, Offset::new(200.0, 50.0));
assert_eq!(granularity, TextGranularity::Word);
tester.remove_pointer(&gesture);
});
}
#[test]
fn mouse_long_press_does_not_send_select_word_event() {
test_widgets(|tester| {
pump_region(tester, SelectionSpy);
tester.pump_and_settle();
clear_spy_events(tester);
let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
tester.down(&mut gesture, Offset::new(200.0, 200.0));
tester.pump_by(Duration::from_millis(500));
tester.up(&gesture);
assert!(spy_events(tester).iter().all(|event| matches!(
event,
SelectionEvent::StartEdgeUpdate { .. } | SelectionEvent::EndEdgeUpdate { .. }
)));
tester.remove_pointer(&gesture);
});
}
fn send_key_combination(
tester: &mut WidgetTester,
trigger: (waft_services::PhysicalKeyboardKey, LogicalKeyboardKey),
shift: bool,
alt: bool,
control: bool,
meta: bool,
) {
use waft_services::PhysicalKeyboardKey;
let modifiers: Vec<(PhysicalKeyboardKey, LogicalKeyboardKey)> = [
(
control,
PhysicalKeyboardKey::CONTROL_LEFT,
LogicalKeyboardKey::CONTROL_LEFT,
),
(
shift,
PhysicalKeyboardKey::SHIFT_LEFT,
LogicalKeyboardKey::SHIFT_LEFT,
),
(
alt,
PhysicalKeyboardKey::ALT_LEFT,
LogicalKeyboardKey::ALT_LEFT,
),
(
meta,
PhysicalKeyboardKey::META_LEFT,
LogicalKeyboardKey::META_LEFT,
),
]
.into_iter()
.filter(|(pressed, _, _)| *pressed)
.map(|(_, physical, logical)| (physical, logical))
.collect();
for (physical, logical) in &modifiers {
tester.send_key_down_event(*physical, *logical);
}
tester.send_key_down_event(trigger.0, trigger.1);
tester.send_key_up_event(trigger.0, trigger.1);
tester.pump();
for (physical, logical) in modifiers.iter().rev() {
tester.send_key_up_event(*physical, *logical);
}
}
fn arrow_right() -> (waft_services::PhysicalKeyboardKey, LogicalKeyboardKey) {
(
waft_services::PhysicalKeyboardKey::ARROW_RIGHT,
LogicalKeyboardKey::ARROW_RIGHT,
)
}
fn arrow_left() -> (waft_services::PhysicalKeyboardKey, LogicalKeyboardKey) {
(
waft_services::PhysicalKeyboardKey::ARROW_LEFT,
LogicalKeyboardKey::ARROW_LEFT,
)
}
fn arrow_up() -> (waft_services::PhysicalKeyboardKey, LogicalKeyboardKey) {
(
waft_services::PhysicalKeyboardKey::ARROW_UP,
LogicalKeyboardKey::ARROW_UP,
)
}
fn arrow_down() -> (waft_services::PhysicalKeyboardKey, LogicalKeyboardKey) {
(
waft_services::PhysicalKeyboardKey::ARROW_DOWN,
LogicalKeyboardKey::ARROW_DOWN,
)
}
fn paragraph_selection_start_end(
tester: &WidgetTester,
paragraph: RenderHandle<RenderParagraph>,
) -> (i32, i32) {
tester.update(|app| {
let selections = paragraph.selections(app);
assert_eq!(selections.len(), 1);
(selections[0].start(), selections[0].end())
})
}
fn select_two_to_six_of_the_first_text(
tester: &mut WidgetTester,
) -> RenderHandle<RenderParagraph> {
pump_region(tester, three_texts());
let paragraph_1 = paragraph_showing(tester, "How are you?");
let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
let at = text_offset_to_position(tester, paragraph_1, 2);
tester.down(&mut gesture, at);
tester.pump();
let at = text_offset_to_position(tester, paragraph_1, 6);
tester.move_to(&mut gesture, at, true);
tester.up(&gesture);
tester.pump();
tester.remove_pointer(&gesture);
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 6));
paragraph_1
}
#[test]
fn can_use_keyboard_to_granularly_extend_selection_character() {
test_widgets_variant(TargetPlatformVariant::all(), |tester| {
let paragraph_1 = select_two_to_six_of_the_first_text(tester);
send_key_combination(tester, arrow_right(), true, false, false, false);
tester.pump();
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 7));
for i in 0..5 {
send_key_combination(tester, arrow_right(), true, false, false, false);
tester.pump();
assert_eq!(
paragraph_selection_start_end(tester, paragraph_1),
(2, 8 + i)
);
}
for i in 0..5 {
send_key_combination(tester, arrow_left(), true, false, false, false);
tester.pump();
assert_eq!(
paragraph_selection_start_end(tester, paragraph_1),
(2, 11 - i)
);
}
});
}
#[test]
fn can_use_keyboard_to_granularly_extend_selection_word() {
test_widgets_variant(TargetPlatformVariant::all(), |tester| {
let paragraph_1 = select_two_to_six_of_the_first_text(tester);
let (alt, control) = match tester.target_platform() {
TargetPlatform::Android
| TargetPlatform::Fuchsia
| TargetPlatform::Linux
| TargetPlatform::Windows => (false, true),
TargetPlatform::IOS | TargetPlatform::MacOS => (true, false),
};
send_key_combination(tester, arrow_right(), true, alt, control, false);
tester.pump();
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 7));
send_key_combination(tester, arrow_right(), true, alt, control, false);
tester.pump();
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 11));
send_key_combination(tester, arrow_right(), true, alt, control, false);
tester.pump();
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
send_key_combination(tester, arrow_right(), true, alt, control, false);
tester.pump();
let paragraph_2 = paragraph_showing(tester, "Good, and you?");
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 4));
send_key_combination(tester, arrow_left(), true, alt, control, false);
tester.pump();
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 0));
send_key_combination(tester, arrow_left(), true, alt, control, false);
tester.pump();
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 8));
assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 0));
});
}
fn line_modifiers(platform: TargetPlatform) -> (bool, bool) {
match platform {
TargetPlatform::Android
| TargetPlatform::Fuchsia
| TargetPlatform::Linux
| TargetPlatform::Windows => (true, false),
TargetPlatform::IOS | TargetPlatform::MacOS => (false, true),
}
}
#[test]
fn can_use_keyboard_to_granularly_extend_selection_line() {
test_widgets_variant(TargetPlatformVariant::all(), |tester| {
let paragraph_1 = select_two_to_six_of_the_first_text(tester);
let (alt, meta) = line_modifiers(tester.target_platform());
send_key_combination(tester, arrow_right(), true, alt, false, meta);
tester.pump();
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
send_key_combination(tester, arrow_right(), true, alt, false, meta);
tester.pump();
let paragraph_2 = paragraph_showing(tester, "Good, and you?");
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 14));
send_key_combination(tester, arrow_left(), true, alt, false, meta);
tester.pump();
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 0));
send_key_combination(tester, arrow_left(), true, alt, false, meta);
tester.pump();
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (0, 2));
});
}
#[test]
fn can_use_keyboard_to_granularly_extend_selection_document() {
test_widgets_variant(TargetPlatformVariant::all(), |tester| {
let paragraph_1 = select_two_to_six_of_the_first_text(tester);
let (alt, meta) = line_modifiers(tester.target_platform());
send_key_combination(tester, arrow_down(), true, alt, false, meta);
tester.pump();
let paragraph_2 = paragraph_showing(tester, "Good, and you?");
let paragraph_3 = paragraph_showing(tester, "Fine, thank you.");
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 14));
assert_eq!(paragraph_selection_start_end(tester, paragraph_3), (0, 16));
send_key_combination(tester, arrow_up(), true, alt, false, meta);
tester.pump();
assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (0, 2));
assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 0));
assert_eq!(paragraph_selection_start_end(tester, paragraph_3), (0, 0));
});
}
const K_TEST_HANDLE_SIZE: f64 = 22.0;
struct TestDraggableSelectionControls;
#[allow(deprecated)]
impl TextSelectionControls for TestDraggableSelectionControls {
fn build_handle(
&self,
_app: &mut App,
_context: BuildContext,
handle_type: TextSelectionHandleType,
_text_line_height: f64,
on_tap: Option<Listener>,
) -> WidgetRef {
let mut detector = crate::widgets::gesture_detector::GestureDetector::new()
.behavior(HitTestBehavior::Translucent);
if let Some(on_tap) = on_tap {
detector = detector.on_tap(on_tap);
}
let handle = SizedBox::square(Some(K_TEST_HANDLE_SIZE))
.child(
crate::widgets::basic::CustomPaint::new()
.painter(TestHandlePainter)
.child(detector),
)
.into_widget();
match handle_type {
TextSelectionHandleType::Left => {
crate::widgets::basic::Transform::rotate(std::f64::consts::PI / 2.0)
.child(handle)
.into_widget()
}
TextSelectionHandleType::Right => handle,
TextSelectionHandleType::Collapsed => {
crate::widgets::basic::Transform::rotate(std::f64::consts::PI / 4.0)
.child(handle)
.into_widget()
}
}
}
fn get_handle_anchor(
&self,
handle_type: TextSelectionHandleType,
_text_line_height: f64,
) -> Offset {
match handle_type {
TextSelectionHandleType::Collapsed => Offset::new(K_TEST_HANDLE_SIZE / 2.0, -4.0),
TextSelectionHandleType::Left => Offset::new(K_TEST_HANDLE_SIZE, 0.0),
TextSelectionHandleType::Right => Offset::ZERO,
}
}
fn get_handle_size(&self, _text_line_height: f64) -> Size {
Size::new(K_TEST_HANDLE_SIZE, K_TEST_HANDLE_SIZE)
}
fn build_toolbar(
&self,
_app: &mut App,
_context: BuildContext,
_global_editable_region: Rect,
_text_line_height: f64,
_selection_midpoint: Offset,
_endpoints: &[waft_rendering::TextSelectionPoint],
_delegate: waft_services::AnyTextSelectionDelegate,
_clipboard_status: Option<Ref<crate::widgets::text_selection::ClipboardStatusNotifier>>,
_last_secondary_tap_down_position: Option<Offset>,
) -> WidgetRef {
SizedBox::shrink().into_widget()
}
}
struct TestHandlePainter;
impl waft_rendering::CustomPainter for TestHandlePainter {
fn paint(&self, _app: &mut App, canvas: &mut waft_embedder::Canvas, size: Size) {
let paint = waft_embedder::Paint {
color: waft_embedder::Color::new(0xFF000000).into(),
..waft_embedder::Paint::default()
};
canvas.draw_rect(Offset::ZERO & size, &paint);
}
fn should_repaint(
&self,
_app: &App,
_old_delegate: &dyn waft_rendering::CustomPainter,
) -> bool {
false
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
fn long_press_thank(tester: &mut WidgetTester) -> (TestPointer, RenderHandle<RenderParagraph>) {
let material_default_text_style = waft_painting::TextStyle::new()
.font_size(48.0)
.font_family("monospace")
.font_weight(waft_embedder::FontWeight::W900);
tester.pump_widget(
TestWidgetsApp::new()
.text_style(material_default_text_style)
.home(SelectableRegion::new(
Rc::new(TestDraggableSelectionControls),
three_texts(),
)),
);
tester.pump_and_settle();
let paragraph_3 = paragraph_showing(tester, "Fine, thank you.");
let mut gesture = TestPointer::touch(tester.next_pointer());
let at = text_offset_to_position(tester, paragraph_3, 7);
tester.down(&mut gesture, at);
tester.pump_by(Duration::from_millis(500));
tester.up(&gesture);
tester.pump_by(Duration::from_millis(500));
assert_eq!(paragraph_selection(tester, paragraph_3), (6, 11));
(gesture, paragraph_3)
}
fn selection_box(tester: &WidgetTester, paragraph: RenderHandle<RenderParagraph>) -> Rect {
tester.update(|app| {
let selection = paragraph.selections(app)[0];
let boxes = paragraph.get_boxes_for_selection(
app,
selection,
waft_embedder::BoxHeightStyle::Tight,
waft_embedder::BoxWidthStyle::Tight,
);
assert_eq!(boxes.len(), 1);
let rect = boxes[0].to_rect();
let to_global = |point| paragraph.as_box().local_to_global(app, point, None);
Rect::from_points(to_global(rect.top_left()), to_global(rect.bottom_right()))
})
}
fn paragraph_height(tester: &WidgetTester, paragraph: RenderHandle<RenderParagraph>) -> f64 {
tester.update(|app| paragraph.as_box().size(app).height())
}
#[test]
fn can_drag_start_selection_handle() {
test_widgets(|tester| {
let (mut gesture, paragraph_3) = long_press_thank(tester);
let handle_pos = selection_box(tester, paragraph_3).bottom_left();
tester.down(&mut gesture, handle_pos);
let paragraph_2 = paragraph_showing(tester, "Good, and you?");
let at = text_offset_to_position(tester, paragraph_2, 5)
+ Offset::new(0.0, paragraph_height(tester, paragraph_2) / 2.0);
tester.move_to(&mut gesture, at, true);
assert_eq!(paragraph_selection(tester, paragraph_3), (0, 11));
assert_eq!(paragraph_selection(tester, paragraph_2), (5, 14));
let paragraph_1 = paragraph_showing(tester, "How are you?");
let at = text_offset_to_position(tester, paragraph_1, 6)
+ Offset::new(0.0, paragraph_height(tester, paragraph_1) / 2.0);
tester.move_to(&mut gesture, at, true);
assert_eq!(paragraph_selection(tester, paragraph_3), (0, 11));
assert_eq!(paragraph_selection(tester, paragraph_2), (0, 14));
assert_eq!(paragraph_selection(tester, paragraph_1), (6, 12));
tester.up(&gesture);
tester.remove_pointer(&gesture);
});
}
#[test]
fn can_drag_start_selection_handle_across_end_selection_handle() {
test_widgets(|tester| {
let (mut gesture, paragraph_3) = long_press_thank(tester);
let handle_pos = selection_box(tester, paragraph_3).bottom_left();
tester.down(&mut gesture, handle_pos);
let half_height = paragraph_height(tester, paragraph_3) / 2.0;
let at =
text_offset_to_position(tester, paragraph_3, 14) + Offset::new(0.0, half_height);
tester.move_to(&mut gesture, at, true);
assert_eq!(paragraph_selection(tester, paragraph_3), (14, 11));
let at =
text_offset_to_position(tester, paragraph_3, 4) + Offset::new(0.0, half_height);
tester.move_to(&mut gesture, at, true);
assert_eq!(paragraph_selection(tester, paragraph_3), (4, 11));
tester.up(&gesture);
tester.remove_pointer(&gesture);
});
}
#[test]
fn can_drag_end_selection_handle_across_start_selection_handle() {
test_widgets(|tester| {
let (mut gesture, paragraph_3) = long_press_thank(tester);
let handle_pos = selection_box(tester, paragraph_3).bottom_right();
tester.down(&mut gesture, handle_pos);
let half_height = paragraph_height(tester, paragraph_3) / 2.0;
let at =
text_offset_to_position(tester, paragraph_3, 4) + Offset::new(0.0, half_height);
tester.move_to(&mut gesture, at, true);
assert_eq!(paragraph_selection(tester, paragraph_3), (6, 4));
let at =
text_offset_to_position(tester, paragraph_3, 12) + Offset::new(0.0, half_height);
tester.move_to(&mut gesture, at, true);
assert_eq!(paragraph_selection(tester, paragraph_3), (6, 12));
tester.up(&gesture);
tester.remove_pointer(&gesture);
});
}
fn three_texts() -> Column {
Column::new().children([
Text::new("How are you?").into_widget(),
Text::new("Good, and you?").into_widget(),
Text::new("Fine, thank you.").into_widget(),
])
}
#[test]
fn a_touch_long_press_shows_the_toolbar_and_its_select_all_selects_everything() {
test_widgets(|tester| {
let types = Rc::new(RefCell::new(Vec::new()));
let types_log = Rc::clone(&types);
let region = SelectableRegion::new(
Rc::new(crate::testing::TestTextSelectionHandleControls),
crate::widgets::basic::Column::new().children([
Text::new("How are you?").into_widget(),
Text::new("Good, and you?").into_widget(),
Text::new("Fine, thank you.").into_widget(),
]),
)
.context_menu_builder(Rc::new(move |app, _context, state| {
let items = state.context_menu_button_items(app);
types_log
.borrow_mut()
.extend(items.iter().map(|item| item.r#type));
let mut buttons = Vec::new();
for item in items {
let label = match item.r#type {
ContextMenuButtonType::Copy => "Copy",
ContextMenuButtonType::SelectAll => "Select all",
_ => "Item",
};
let on_pressed = item.on_pressed.clone();
buttons.push(
crate::widgets::gesture_detector::GestureDetector::new()
.on_tap(Listener::new(move |app| {
if let Some(listener) = &on_pressed {
listener.call(app);
}
}))
.child(Text::new(label))
.into_widget(),
);
}
crate::widgets::basic::Column::new()
.children(buttons)
.into_widget()
}));
tester.pump_widget(TestWidgetsApp::new().home(region));
tester.pump_and_settle();
let paragraph_3 = paragraph_showing(tester, "Fine, thank you.");
let at = text_offset_to_position(tester, paragraph_3, 7);
let mut pointer = TestPointer::touch(tester.next_pointer());
tester.down(&mut pointer, at);
tester.pump_by(Duration::from_millis(500));
tester.up(&pointer);
tester.pump_by(Duration::from_millis(500));
assert_eq!(paragraph_selection(tester, paragraph_3), (6, 11));
assert!(types.borrow().contains(&ContextMenuButtonType::SelectAll));
tester.tap(find::text("Select all"));
tester.pump();
assert_eq!(paragraph_selection(tester, paragraph_3), (0, 16));
assert_eq!(
paragraph_selection(tester, paragraph_showing(tester, "Good, and you?")),
(0, 14)
);
assert_eq!(
paragraph_selection(tester, paragraph_showing(tester, "How are you?")),
(0, 12)
);
});
}
struct RockPaperScissorsDelegate {
selection_container_delegate: SelectionContainerDelegateData,
multi_selectable_selection_container_delegate:
MultiSelectableSelectionContainerDelegateData,
lanes: Vec<(AnySelectable, usize)>,
seed: u64,
}
impl RockPaperScissorsDelegate {
fn new(app: &mut App) -> Ref<RockPaperScissorsDelegate> {
app.create(RockPaperScissorsDelegate {
selection_container_delegate: SelectionContainerDelegateData::new(),
multi_selectable_selection_container_delegate:
MultiSelectableSelectionContainerDelegateData::new(),
lanes: Vec::new(),
seed: 12345,
})
}
fn lane(self: Handle<Self>, app: &App, selectable: AnySelectable) -> usize {
app.get(self)
.lanes
.iter()
.find_map(|(held, lane)| (*held == selectable).then_some(*lane))
.unwrap_or(0)
}
}
impl SelectionContainerDelegate for RockPaperScissorsDelegate {
fn selection_container_delegate_data(
self: Handle<Self>,
app: &App,
) -> &SelectionContainerDelegateData {
&app.get(self).selection_container_delegate
}
fn selection_container_delegate_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SelectionContainerDelegateData {
&mut app.get_mut(self).selection_container_delegate
}
}
impl MultiSelectableSelectionContainerDelegate for RockPaperScissorsDelegate {
crate::multi_selectable_selection_container_delegate_accessors!();
fn compare_order(
self: Handle<Self>,
app: &mut App,
a: AnySelectable,
b: AnySelectable,
) -> Ordering {
let (a, b) = (self.lane(app, a), self.lane(app, b));
if a == b {
Ordering::Equal
} else if (a + 1) % 3 == b {
Ordering::Less
} else {
Ordering::Greater
}
}
fn ensure_child_updated(self: Handle<Self>, _app: &mut App, _selectable: AnySelectable) {}
fn dispatch_selection_event_to_child(
self: Handle<Self>,
_app: &mut App,
_selectable: AnySelectable,
_event: &SelectionEvent,
) -> SelectionResult {
SelectionResult::End
}
}
impl SelectionHandler for RockPaperScissorsDelegate {
fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
MultiSelectableSelectionContainerDelegateBase::value(self, app)
}
fn push_handle_layers(
self: Handle<Self>,
app: &mut App,
start_handle: Option<Ref<LayerLink>>,
end_handle: Option<Ref<LayerLink>>,
) {
MultiSelectableSelectionContainerDelegateBase::push_handle_layers(
self,
app,
start_handle,
end_handle,
);
}
fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
MultiSelectableSelectionContainerDelegateBase::selected_content(self, app)
}
fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
MultiSelectableSelectionContainerDelegateBase::selection(self, app)
}
fn dispatch_selection_event(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
MultiSelectableSelectionContainerDelegateBase::dispatch_selection_event(
self, app, event,
)
}
fn content_length(self: Handle<Self>, app: &App) -> usize {
MultiSelectableSelectionContainerDelegateBase::content_length(self, app)
}
}
impl SelectionRegistrar for RockPaperScissorsDelegate {
fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
let seed = app.get(self).seed;
let lane = {
let next = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
app.get_mut(self).seed = next;
((next >> 33) as usize) % 3
};
app.get_mut(self).lanes.push((selectable, lane));
MultiSelectableSelectionContainerDelegateBase::add(self, app, selectable);
}
fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
app.get_mut(self)
.lanes
.retain(|(held, _)| *held != selectable);
MultiSelectableSelectionContainerDelegateBase::remove(self, app, selectable);
}
}
impl ChangeNotifier for RockPaperScissorsDelegate {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self
.multi_selectable_selection_container_delegate
.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self
.multi_selectable_selection_container_delegate
.change_notifier
}
}
#[test]
fn fifty_selectables_sort_with_a_comparator_that_is_not_a_total_order() {
test_widgets(|tester| {
let delegate = tester.update(RockPaperScissorsDelegate::new);
let children: Vec<WidgetRef> = (0..50)
.map(|_| {
SizedBox::new()
.height(10.0)
.child(SelectionSpy)
.into_widget()
})
.collect();
tester.pump_widget(SelectionContainer::new(
delegate.erase(),
Column::new().children(children),
));
for _ in 0..3 {
tester.update(|app| SchedulerBinding::schedule_frame(app, FrameTarget::EveryView));
tester.pump_and_settle();
}
tester.update(|app| {
assert_eq!(
app.get(&delegate)
.multi_selectable_selection_container_delegate
.selectables
.len(),
50,
"the frame merged all fifty selectables"
);
SelectionHandler::dispatch_selection_event(
delegate.handle(),
app,
&SelectionEvent::SelectAll,
);
assert!(SelectionHandler::value(delegate.handle(), app).has_content);
});
});
}
#[test]
fn updates_its_registrar_and_delegate_based_on_the_number_of_selectables() {
test_widgets(|tester| {
let registrar = tester.update(|app| {
app.create(TestSelectionRegistrar {
selectables: Vec::new(),
})
});
let delegate = tester.update(TestContainerDelegate::new);
tester.pump_widget(
SelectionContainer::new(
delegate.erase(),
Column::new().children([
selectable_text("column1"),
selectable_text("column2"),
selectable_text("column3"),
]),
)
.registrar(registrar.erase()),
);
tester.pump_and_settle();
tester.update(|app| {
assert_eq!(app.get(®istrar).selectables.len(), 1);
assert_eq!(
app.get(&delegate)
.multi_selectable_selection_container_delegate
.selectables
.len(),
3
);
});
});
}
#[test]
fn a_disabled_container_registers_neither_itself_nor_its_children() {
test_widgets(|tester| {
let registrar = tester.update(|app| {
app.create(TestSelectionRegistrar {
selectables: Vec::new(),
})
});
let delegate = tester.update(TestContainerDelegate::new);
tester.pump_widget(
SelectionContainer::new(
delegate.erase(),
SelectionContainer::disabled(Column::new().children([
selectable_text("column1"),
selectable_text("column2"),
selectable_text("column3"),
])),
)
.registrar(registrar.erase()),
);
tester.update(|app| {
assert_eq!(app.get(®istrar).selectables.len(), 0);
assert_eq!(
app.get(&delegate)
.multi_selectable_selection_container_delegate
.selectables
.len(),
0
);
});
});
}
#[test]
fn swapping_out_the_container_delegate_does_not_crash() {
test_widgets(|tester| {
let registrar = tester.update(|app| {
app.create(TestSelectionRegistrar {
selectables: Vec::new(),
})
});
let delegate = tester.update(TestContainerDelegate::new);
let child_delegate = tester.update(TestContainerDelegate::new);
let pump_inner = |tester: &mut WidgetTester, inner: &Ref<TestContainerDelegate>| {
let inner = inner.clone();
tester.pump_widget(
SelectionContainer::new(
delegate.erase(),
Builder::new(move |app, context| {
let registrar = SelectionContainer::maybe_of(app, context)
.expect("the outer container hosts a registrar");
SelectionContainer::new(inner.erase(), selectable_text("dummy"))
.registrar(registrar)
.into_widget()
}),
)
.registrar(registrar.erase()),
);
tester.pump_and_settle();
next_frame(tester);
};
pump_inner(tester, &child_delegate);
tester.update(|app| {
assert_eq!(app.get(®istrar).selectables.len(), 1);
assert!(SelectionHandler::value(delegate.handle(), app).has_content);
});
let new_delegate = tester.update(TestContainerDelegate::new);
pump_inner(tester, &new_delegate);
tester.update(|app| {
assert_eq!(app.get(®istrar).selectables.len(), 1);
assert!(SelectionHandler::value(delegate.handle(), app).has_content);
});
});
}
#[test]
fn the_container_updates_within_one_frame() {
test_widgets(|tester| {
let registrar = tester.update(|app| {
app.create(TestSelectionRegistrar {
selectables: Vec::new(),
})
});
let delegate = tester.update(TestContainerDelegate::new);
let child_delegate = tester.update(TestContainerDelegate::new);
tester.pump_widget(
SelectionContainer::new(
delegate.erase(),
Builder::new(move |app, context| {
let registrar = SelectionContainer::maybe_of(app, context)
.expect("the outer container hosts a registrar");
SelectionContainer::new(child_delegate.erase(), selectable_text("dummy"))
.registrar(registrar)
.into_widget()
}),
)
.registrar(registrar.erase()),
);
next_frame(tester);
tester.update(|app| {
assert_eq!(app.get(®istrar).selectables.len(), 1);
assert!(SelectionHandler::value(delegate.handle(), app).has_content);
});
});
}
#[test]
fn a_selection_container_registers_itself_if_there_is_a_selectable_child() {
test_widgets(|tester| {
let registrar = tester.update(|app| {
app.create(TestSelectionRegistrar {
selectables: Vec::new(),
})
});
let delegate = tester.update(TestContainerDelegate::new);
tester.pump_widget(
SelectionContainer::new(delegate.erase(), Column::new())
.registrar(registrar.erase()),
);
tester.update(|app| assert_eq!(app.get(®istrar).selectables.len(), 0));
tester.pump_widget(
SelectionContainer::new(
delegate.erase(),
Column::new().children([selectable_text("column1")]),
)
.registrar(registrar.erase()),
);
tester.pump_and_settle();
tester.update(|app| assert_eq!(app.get(®istrar).selectables.len(), 1));
tester.pump_widget(
SelectionContainer::new(delegate.erase(), Column::new())
.registrar(registrar.erase()),
);
tester.pump_and_settle();
tester.update(|app| assert_eq!(app.get(®istrar).selectables.len(), 0));
});
}
#[test]
fn a_selection_container_gets_its_registrar_from_the_context() {
test_widgets(|tester| {
let registrar = tester.update(|app| {
app.create(TestSelectionRegistrar {
selectables: Vec::new(),
})
});
let delegate = tester.update(TestContainerDelegate::new);
tester.pump_widget(SelectionRegistrarScope::new(
registrar.erase(),
SelectionContainer::new(
delegate.erase(),
Column::new().children([selectable_text("column1")]),
),
));
tester.pump_and_settle();
tester.update(|app| assert_eq!(app.get(®istrar).selectables.len(), 1));
});
}
#[test]
fn a_selection_container_does_not_crash_at_zero_area() {
test_widgets(|tester| {
let delegate = tester.update(TestContainerDelegate::new);
tester.pump_widget(Center::new().child(SizedBox::shrink().child(
SelectionContainer::new(delegate.erase(), Placeholder::new()),
)));
assert_eq!(
tester.get_size(find::by_type::<SelectionContainer>()),
Size::ZERO
);
});
}
fn next_frame(tester: &mut WidgetTester) {
tester.update(|app| SchedulerBinding::schedule_frame(app, FrameTarget::EveryView));
tester.pump_and_settle();
}
fn dispatch<D: SelectionHandler>(
tester: &mut WidgetTester,
handle: Handle<D>,
event: SelectionEvent,
) {
tester.update(|app| {
SelectionHandler::dispatch_selection_event(handle, app, &event);
});
}
fn assert_selection<D: SelectionHandler>(
tester: &WidgetTester,
handle: Handle<D>,
expected_range: Option<(i32, i32)>,
expected_status: SelectionStatus,
) {
tester.update(|app| {
let range = SelectionHandler::selection(handle, app);
assert_eq!(
range.map(|range| (range.start_offset, range.end_offset)),
expected_range
);
let value = SelectionHandler::value(handle, app);
assert_eq!(value.status, expected_status);
assert!(value.has_content);
});
}
fn selected_text<D: SelectionHandler>(
tester: &WidgetTester,
handle: Handle<D>,
) -> Option<String> {
tester.update(|app| {
SelectionHandler::selected_content(handle, app).map(|content| content.plain_text)
})
}
#[test]
fn a_subclass_joins_the_selectable_contents_its_own_way() {
test_widgets(|tester| {
let delegate = tester.update(ColumnSelectionContainerDelegate::new);
tester.pump_widget(SelectionContainer::new(
delegate.erase(),
Column::new().children([
selectable_text("Hello World!"),
selectable_text("How are you!"),
]),
));
tester.pump_and_settle();
let paragraphs = tester.all::<RenderParagraph>();
assert_eq!(paragraphs.len(), 2);
let start = text_offset_to_position(tester, paragraphs[0], 4);
let end = text_offset_to_position(tester, paragraphs[1], 10);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_start(start, None),
);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_end(end, None),
);
assert_eq!(
selected_text(tester, delegate.handle()),
Some("o World!\nHow are yo".to_string())
);
tester.update(|app| {
assert_eq!(SelectionHandler::content_length(delegate.handle(), app), 24);
});
assert_selection(
tester,
delegate.handle(),
Some((4, 22)),
SelectionStatus::Uncollapsed,
);
});
}
#[test]
fn the_delegate_joins_the_selectable_contents_without_a_separator() {
test_widgets(|tester| {
let delegate = tester.update(PlainStaticSelectionContainerDelegate::new);
tester.pump_widget(SelectionContainer::new(
delegate.erase(),
Column::new().children([
selectable_text("Hello World!"),
selectable_text("How are you!"),
]),
));
tester.pump_and_settle();
let paragraphs = tester.all::<RenderParagraph>();
assert_eq!(paragraphs.len(), 2);
let start = text_offset_to_position(tester, paragraphs[0], 4);
let end = text_offset_to_position(tester, paragraphs[1], 10);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_start(start, None),
);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_end(end, None),
);
assert_eq!(
selected_text(tester, delegate.handle()),
Some("o World!How are yo".to_string())
);
assert_selection(
tester,
delegate.handle(),
Some((4, 22)),
SelectionStatus::Uncollapsed,
);
});
}
#[test]
fn the_selection_range_covers_the_selectables_between_the_edges() {
test_widgets(|tester| {
let delegate = tester.update(PlainStaticSelectionContainerDelegate::new);
tester.pump_widget(SelectionContainer::new(
delegate.erase(),
Column::new().children([
selectable_text("How are you?"),
selectable_text("Good, and you?"),
selectable_text("Fine, thank you."),
]),
));
tester.pump_and_settle();
let paragraphs = tester.all::<RenderParagraph>();
assert_eq!(paragraphs.len(), 3);
let start = text_offset_to_position(tester, paragraphs[0], 4);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_start(start, None),
);
let end = text_offset_to_position(tester, paragraphs[0], 7);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_end(end, None),
);
assert_selection(
tester,
delegate.handle(),
Some((4, 7)),
SelectionStatus::Uncollapsed,
);
let end = text_offset_to_position(tester, paragraphs[0], 10);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_end(end, None),
);
assert_selection(
tester,
delegate.handle(),
Some((4, 10)),
SelectionStatus::Uncollapsed,
);
let end = text_offset_to_position(tester, paragraphs[1], 10);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_end(end, None),
);
assert_selection(
tester,
delegate.handle(),
Some((4, 22)),
SelectionStatus::Uncollapsed,
);
let end = text_offset_to_position(tester, paragraphs[2], 10);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_end(end, None),
);
assert_selection(
tester,
delegate.handle(),
Some((4, 36)),
SelectionStatus::Uncollapsed,
);
dispatch(tester, delegate.handle(), SelectionEvent::Clear);
let point = text_offset_to_position(tester, paragraphs[0], 3);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_start(point, None),
);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_end(point, None),
);
assert_selection(
tester,
delegate.handle(),
Some((3, 3)),
SelectionStatus::Collapsed,
);
dispatch(tester, delegate.handle(), SelectionEvent::Clear);
let start = text_offset_to_position(tester, paragraphs[2], 4);
let end = text_offset_to_position(tester, paragraphs[0], 0);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_start(start, None),
);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_end(end, None),
);
assert_selection(
tester,
delegate.handle(),
Some((30, 0)),
SelectionStatus::Uncollapsed,
);
dispatch(tester, delegate.handle(), SelectionEvent::Clear);
let point = text_offset_to_position(tester, paragraphs[0], 0);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_start(point, None),
);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_end(point, None),
);
assert_selection(
tester,
delegate.handle(),
Some((0, 0)),
SelectionStatus::Collapsed,
);
});
}
#[test]
fn a_selectable_added_inside_the_selection_is_selected_at_once() {
test_widgets(|tester| {
let delegate = tester.update(PlainStaticSelectionContainerDelegate::new);
let pump = |tester: &mut WidgetTester, texts: &[&'static str]| {
tester.pump_widget(SelectionContainer::new(
delegate.erase(),
Column::new().children(
texts
.iter()
.map(|text| selectable_text(text))
.collect::<Vec<_>>(),
),
));
tester.pump_and_settle();
};
pump(tester, &["AAA", "CCC"]);
let paragraphs = tester.all::<RenderParagraph>();
let start = text_offset_to_position(tester, paragraphs[0], 0);
let end = text_offset_to_position(tester, paragraphs[1], 2);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_start(start, None),
);
dispatch(
tester,
delegate.handle(),
SelectionEvent::for_end(end, None),
);
assert_eq!(
selected_text(tester, delegate.handle()),
Some("AAACC".to_string())
);
pump(tester, &["AAA", "BBB", "CCC"]);
assert_eq!(
selected_text(tester, delegate.handle()),
Some("AAABB".to_string())
);
assert_selection(
tester,
delegate.handle(),
Some((0, 5)),
SelectionStatus::Uncollapsed,
);
});
}
#[test]
fn select_all_a_word_a_paragraph_and_clear_act_on_the_selectables() {
test_widgets(|tester| {
let delegate = tester.update(PlainStaticSelectionContainerDelegate::new);
tester.pump_widget(SelectionContainer::new(
delegate.erase(),
Column::new().children([
selectable_text("Hello World!"),
selectable_text("How are you!"),
]),
));
tester.pump_and_settle();
dispatch(tester, delegate.handle(), SelectionEvent::SelectAll);
assert_eq!(
selected_text(tester, delegate.handle()),
Some("Hello World!How are you!".to_string())
);
assert_selection(
tester,
delegate.handle(),
Some((0, 24)),
SelectionStatus::Uncollapsed,
);
dispatch(tester, delegate.handle(), SelectionEvent::Clear);
assert_eq!(selected_text(tester, delegate.handle()), None);
assert_selection(tester, delegate.handle(), None, SelectionStatus::None);
tester.update(|app| {
assert_eq!(SelectionHandler::content_length(delegate.handle(), app), 24);
});
let paragraphs = tester.all::<RenderParagraph>();
let word = text_offset_to_position(tester, paragraphs[1], 5);
dispatch(
tester,
delegate.handle(),
SelectionEvent::SelectWord {
global_position: word,
},
);
assert_eq!(
selected_text(tester, delegate.handle()),
Some("are".to_string())
);
assert_selection(
tester,
delegate.handle(),
Some((16, 19)),
SelectionStatus::Uncollapsed,
);
let paragraph = text_offset_to_position(tester, paragraphs[1], 5);
dispatch(
tester,
delegate.handle(),
SelectionEvent::SelectParagraph {
global_position: paragraph,
absorb: false,
},
);
assert_eq!(
selected_text(tester, delegate.handle()),
Some("How are you!".to_string())
);
assert_selection(
tester,
delegate.handle(),
Some((12, 24)),
SelectionStatus::Uncollapsed,
);
});
}
}