use waft_embedder::{Matrix4, Offset, Rect, Size, TextDirection};
use waft_foundation::{
App, Handle, HandleId, ListenableHandle, ListenableObject, Listener, Ref, Retained,
};
use crate::layer::LayerLink;
use crate::object::AnyRenderObject;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SelectionResult {
Next,
Previous,
End,
Pending,
None,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SelectedContentRange {
pub start_offset: i32,
pub end_offset: i32,
}
impl SelectedContentRange {
pub fn new(start_offset: i32, end_offset: i32) -> SelectedContentRange {
debug_assert!(start_offset >= 0 && end_offset >= 0);
SelectedContentRange {
start_offset,
end_offset,
}
}
}
#[derive(Clone, Debug)]
pub struct SelectedContent {
pub plain_text: String,
}
impl SelectedContent {
pub fn new(plain_text: impl Into<String>) -> SelectedContent {
SelectedContent {
plain_text: plain_text.into(),
}
}
}
pub trait SelectionHandler: ListenableObject {
fn value(self: Handle<Self>, app: &App) -> SelectionGeometry;
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>;
fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange>;
fn dispatch_selection_event(
self: Handle<Self>,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult;
fn content_length(self: Handle<Self>, app: &App) -> usize;
}
pub trait Selectable: SelectionHandler {
fn as_selectable(self: Handle<Self>) -> AnySelectable {
AnySelectable {
id: self.id(),
vtable: const { &SelectableVTable::of::<Self>() },
}
}
fn get_transform_to(
self: Handle<Self>,
app: &App,
ancestor: Option<AnyRenderObject>,
) -> Matrix4;
fn size(self: Handle<Self>, app: &mut App) -> Size;
fn bounding_boxes(self: Handle<Self>, app: &mut App) -> Vec<Rect>;
fn dispose_selectable(self: Handle<Self>, app: &mut App);
}
#[derive(Clone, Copy)]
pub struct AnySelectable {
id: HandleId,
vtable: &'static SelectableVTable,
}
pub type PushHandleLayers = fn(&mut App, HandleId, Option<Ref<LayerLink>>, Option<Ref<LayerLink>>);
struct SelectableVTable {
value: fn(&App, HandleId) -> SelectionGeometry,
push_handle_layers: PushHandleLayers,
selected_content: fn(&App, HandleId) -> Option<SelectedContent>,
selection: fn(&App, HandleId) -> Option<SelectedContentRange>,
dispatch_selection_event: fn(&mut App, HandleId, &SelectionEvent) -> SelectionResult,
content_length: fn(&App, HandleId) -> usize,
get_transform_to: fn(&App, HandleId, Option<AnyRenderObject>) -> Matrix4,
size: fn(&mut App, HandleId) -> Size,
bounding_boxes: fn(&mut App, HandleId) -> Vec<Rect>,
dispose_selectable: fn(&mut App, HandleId),
add_listener: fn(&mut App, HandleId, Listener),
remove_listener: fn(&mut App, HandleId, &Listener),
}
impl SelectableVTable {
const fn of<A: Selectable>() -> SelectableVTable {
SelectableVTable {
value: |app, id| A::value(resolve(id), app),
push_handle_layers: |app, id, start, end| {
A::push_handle_layers(resolve(id), app, start, end)
},
selected_content: |app, id| A::selected_content(resolve(id), app),
selection: |app, id| A::selection(resolve(id), app),
dispatch_selection_event: |app, id, event| {
A::dispatch_selection_event(resolve(id), app, event)
},
content_length: |app, id| A::content_length(resolve(id), app),
get_transform_to: |app, id, ancestor| A::get_transform_to(resolve(id), app, ancestor),
size: |app, id| A::size(resolve(id), app),
bounding_boxes: |app, id| A::bounding_boxes(resolve(id), app),
dispose_selectable: |app, id| A::dispose_selectable(resolve(id), app),
add_listener: |app, id, listener| {
ListenableObject::add_listener(resolve::<A>(id), app, listener)
},
remove_listener: |app, id, listener| {
ListenableObject::remove_listener(resolve::<A>(id), app, listener)
},
}
}
}
fn resolve<A: 'static>(id: HandleId) -> Handle<A> {
Handle::from_id(id)
}
impl AnySelectable {
pub fn id(self) -> HandleId {
self.id
}
pub fn value(self, app: &App) -> SelectionGeometry {
(self.vtable.value)(app, self.id)
}
pub fn push_handle_layers(
self,
app: &mut App,
start_handle: Option<Ref<LayerLink>>,
end_handle: Option<Ref<LayerLink>>,
) {
(self.vtable.push_handle_layers)(app, self.id, start_handle, end_handle)
}
pub fn selected_content(self, app: &App) -> Option<SelectedContent> {
(self.vtable.selected_content)(app, self.id)
}
pub fn selection(self, app: &App) -> Option<SelectedContentRange> {
(self.vtable.selection)(app, self.id)
}
pub fn dispatch_selection_event(
self,
app: &mut App,
event: &SelectionEvent,
) -> SelectionResult {
(self.vtable.dispatch_selection_event)(app, self.id, event)
}
pub fn content_length(self, app: &App) -> usize {
(self.vtable.content_length)(app, self.id)
}
pub fn get_transform_to(self, app: &App, ancestor: Option<AnyRenderObject>) -> Matrix4 {
(self.vtable.get_transform_to)(app, self.id, ancestor)
}
pub fn size(self, app: &mut App) -> Size {
(self.vtable.size)(app, self.id)
}
pub fn bounding_boxes(self, app: &mut App) -> Vec<Rect> {
(self.vtable.bounding_boxes)(app, self.id)
}
pub fn dispose_selectable(self, app: &mut App) {
(self.vtable.dispose_selectable)(app, self.id)
}
pub fn add_listener(self, app: &mut App, listener: Listener) {
(self.vtable.add_listener)(app, self.id, listener)
}
pub fn remove_listener(self, app: &mut App, listener: &Listener) {
(self.vtable.remove_listener)(app, self.id, listener)
}
}
impl std::fmt::Debug for AnySelectable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnySelectable")
.field("id", &self.id)
.finish()
}
}
waft_foundation::erased_handle!(AnySelectable: Selectable => Selectable::as_selectable);
#[derive(Debug, Default)]
pub struct SelectionRegistrantData {
registrar: Option<SelectionRegistrarRef>,
subscribed_to_selection_registrar: bool,
}
impl SelectionRegistrantData {
pub fn new() -> SelectionRegistrantData {
SelectionRegistrantData::default()
}
}
pub trait SelectionRegistrant: Selectable {
fn selection_registrant_data(self: Handle<Self>, app: &App) -> &SelectionRegistrantData;
fn selection_registrant_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SelectionRegistrantData;
fn registrar(self: Handle<Self>, app: &App) -> Option<AnySelectionRegistrar> {
self.selection_registrant_data(app)
.registrar
.as_ref()
.map(Retained::handle)
}
fn set_registrar(self: Handle<Self>, app: &mut App, value: Option<SelectionRegistrarRef>) {
let registrar = self.registrar(app);
if value.as_ref().map(Retained::handle) == registrar {
return;
}
let listener = Listener::handle_method(self, Self::update_selection_registrar_subscription);
if value.is_none() {
self.remove_listener_from(app, &listener);
} else if registrar.is_none() {
self.add_listener_to(app, listener);
}
self.remove_selection_registrar_subscription(app);
self.selection_registrant_data_mut(app).registrar = value;
self.update_selection_registrar_subscription(app);
}
fn update_selection_registrar_subscription(self: Handle<Self>, app: &mut App) {
let Some(registrar) = self.registrar(app) else {
self.selection_registrant_data_mut(app)
.subscribed_to_selection_registrar = false;
return;
};
let has_content = self.value(app).has_content;
let subscribed = self
.selection_registrant_data(app)
.subscribed_to_selection_registrar;
if subscribed && !has_content {
registrar.remove(app, self.as_selectable());
self.selection_registrant_data_mut(app)
.subscribed_to_selection_registrar = false;
} else if !subscribed && has_content {
registrar.add(app, self.as_selectable());
self.selection_registrant_data_mut(app)
.subscribed_to_selection_registrar = true;
}
}
fn remove_selection_registrar_subscription(self: Handle<Self>, app: &mut App) {
if self
.selection_registrant_data(app)
.subscribed_to_selection_registrar
{
let registrar = self
.registrar(app)
.expect("a subscribed registrant has a registrar");
registrar.remove(app, self.as_selectable());
self.selection_registrant_data_mut(app)
.subscribed_to_selection_registrar = false;
}
}
fn dispose_selection_registrant(self: Handle<Self>, app: &mut App) {
self.remove_selection_registrar_subscription(app);
}
}
pub trait SelectionRegistrar: Sized + 'static {
fn as_selection_registrar(self: Handle<Self>) -> AnySelectionRegistrar {
AnySelectionRegistrar {
id: self.id(),
vtable: const { &SelectionRegistrarVTable::of::<Self>() },
}
}
fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable);
fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable);
}
#[derive(Clone, Copy)]
pub struct AnySelectionRegistrar {
id: HandleId,
vtable: &'static SelectionRegistrarVTable,
}
struct SelectionRegistrarVTable {
add: fn(&mut App, HandleId, AnySelectable),
remove: fn(&mut App, HandleId, AnySelectable),
}
impl SelectionRegistrarVTable {
const fn of<A: SelectionRegistrar>() -> SelectionRegistrarVTable {
SelectionRegistrarVTable {
add: |app, id, selectable| A::add(resolve(id), app, selectable),
remove: |app, id, selectable| A::remove(resolve(id), app, selectable),
}
}
}
impl AnySelectionRegistrar {
pub fn id(self) -> HandleId {
self.id
}
pub fn add(self, app: &mut App, selectable: AnySelectable) {
(self.vtable.add)(app, self.id, selectable)
}
pub fn remove(self, app: &mut App, selectable: AnySelectable) {
(self.vtable.remove)(app, self.id, selectable)
}
}
impl std::fmt::Debug for AnySelectionRegistrar {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnySelectionRegistrar")
.field("id", &self.id)
.finish()
}
}
pub type SelectionRegistrarRef = Retained<AnySelectionRegistrar>;
waft_foundation::erased_handle!(AnySelectionRegistrar: SelectionRegistrar => SelectionRegistrar::as_selection_registrar);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SelectionStatus {
Uncollapsed,
Collapsed,
None,
}
#[derive(Clone, Debug, PartialEq)]
pub struct SelectionGeometry {
pub start_selection_point: Option<SelectionPoint>,
pub end_selection_point: Option<SelectionPoint>,
pub status: SelectionStatus,
pub selection_rects: Vec<Rect>,
pub has_content: bool,
}
impl SelectionGeometry {
pub fn new(status: SelectionStatus, has_content: bool) -> SelectionGeometry {
SelectionGeometry {
start_selection_point: None,
end_selection_point: None,
status,
selection_rects: Vec::new(),
has_content,
}
}
pub fn start_selection_point(mut self, value: Option<SelectionPoint>) -> SelectionGeometry {
self.start_selection_point = value;
self.debug_assert_points_have_selection();
self
}
pub fn end_selection_point(mut self, value: Option<SelectionPoint>) -> SelectionGeometry {
self.end_selection_point = value;
self.debug_assert_points_have_selection();
self
}
pub fn selection_rects(mut self, value: Vec<Rect>) -> SelectionGeometry {
self.selection_rects = value;
self
}
pub fn status(mut self, value: SelectionStatus) -> SelectionGeometry {
self.status = value;
self
}
pub fn has_content(mut self, value: bool) -> SelectionGeometry {
self.has_content = value;
self
}
fn debug_assert_points_have_selection(&self) {
debug_assert!(
(self.start_selection_point.is_none() && self.end_selection_point.is_none())
|| self.status != SelectionStatus::None
);
}
pub fn has_selection(&self) -> bool {
self.status != SelectionStatus::None
}
pub fn copy_with(&self) -> SelectionGeometry {
self.clone()
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SelectionPoint {
pub local_position: Offset,
pub line_height: f64,
pub handle_type: TextSelectionHandleType,
}
impl SelectionPoint {
pub fn new(
local_position: Offset,
line_height: f64,
handle_type: TextSelectionHandleType,
) -> SelectionPoint {
SelectionPoint {
local_position,
line_height,
handle_type,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TextSelectionHandleType {
Left,
Right,
Collapsed,
}
pub struct SelectionUtils;
impl SelectionUtils {
pub fn get_result_based_on_rect(target_rect: Rect, point: Offset) -> SelectionResult {
if target_rect.contains(point) {
return SelectionResult::End;
}
if point.dy() < target_rect.top {
return SelectionResult::Previous;
}
if point.dy() > target_rect.bottom {
return SelectionResult::Next;
}
if point.dx() >= target_rect.right {
SelectionResult::Next
} else {
SelectionResult::Previous
}
}
pub fn adjust_drag_offset(
target_rect: Rect,
point: Offset,
direction: TextDirection,
) -> Offset {
if target_rect.contains(point) {
return point;
}
if point.dy() <= target_rect.top
|| point.dy() <= target_rect.bottom && point.dx() <= target_rect.left
{
if direction == TextDirection::Ltr {
Offset::new(target_rect.left, target_rect.top)
} else {
Offset::new(target_rect.right, target_rect.top)
}
} else {
if direction == TextDirection::Ltr {
Offset::new(target_rect.right, target_rect.bottom)
} else {
Offset::new(target_rect.left, target_rect.bottom)
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextGranularity {
Character,
Word,
Paragraph,
Line,
Document,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SelectionExtendDirection {
PreviousLine,
NextLine,
Forward,
Backward,
}
#[derive(Clone, Debug)]
pub enum SelectionEvent {
StartEdgeUpdate {
global_position: Offset,
granularity: TextGranularity,
},
EndEdgeUpdate {
global_position: Offset,
granularity: TextGranularity,
},
Clear,
SelectAll,
SelectWord {
global_position: Offset,
},
SelectParagraph {
global_position: Offset,
absorb: bool,
},
GranularlyExtendSelection {
forward: bool,
is_end: bool,
granularity: TextGranularity,
},
DirectionallyExtendSelection {
dx: f64,
is_end: bool,
direction: SelectionExtendDirection,
},
}
impl SelectionEvent {
pub fn ty(&self) -> SelectionEventType {
match self {
SelectionEvent::StartEdgeUpdate { .. } => SelectionEventType::StartEdgeUpdate,
SelectionEvent::EndEdgeUpdate { .. } => SelectionEventType::EndEdgeUpdate,
SelectionEvent::Clear => SelectionEventType::Clear,
SelectionEvent::SelectAll => SelectionEventType::SelectAll,
SelectionEvent::SelectWord { .. } => SelectionEventType::SelectWord,
SelectionEvent::SelectParagraph { .. } => SelectionEventType::SelectParagraph,
SelectionEvent::GranularlyExtendSelection { .. } => {
SelectionEventType::GranularlyExtendSelection
}
SelectionEvent::DirectionallyExtendSelection { .. } => {
SelectionEventType::DirectionallyExtendSelection
}
}
}
pub fn for_start(
global_position: Offset,
granularity: Option<TextGranularity>,
) -> SelectionEvent {
SelectionEvent::StartEdgeUpdate {
global_position,
granularity: granularity.unwrap_or(TextGranularity::Character),
}
}
pub fn for_end(
global_position: Offset,
granularity: Option<TextGranularity>,
) -> SelectionEvent {
SelectionEvent::EndEdgeUpdate {
global_position,
granularity: granularity.unwrap_or(TextGranularity::Character),
}
}
pub fn copy_with(
&self,
dx: Option<f64>,
is_end: Option<bool>,
direction: Option<SelectionExtendDirection>,
) -> SelectionEvent {
match self {
SelectionEvent::DirectionallyExtendSelection {
dx: old_dx,
is_end: old_is_end,
direction: old_direction,
} => SelectionEvent::DirectionallyExtendSelection {
dx: dx.unwrap_or(*old_dx),
is_end: is_end.unwrap_or(*old_is_end),
direction: direction.unwrap_or(*old_direction),
},
event => event.clone(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SelectionEventType {
StartEdgeUpdate,
EndEdgeUpdate,
Clear,
SelectAll,
SelectWord,
SelectParagraph,
GranularlyExtendSelection,
DirectionallyExtendSelection,
}
#[cfg(test)]
mod tests {
use super::*;
const RECT: Rect = Rect::from_ltrb(100.0, 100.0, 300.0, 600.0);
const OUTSIDE_TOP_LEFT: Offset = Offset::new(50.0, 50.0);
const OUTSIDE_LEFT: Offset = Offset::new(50.0, 200.0);
const OUTSIDE_BOTTOM_LEFT: Offset = Offset::new(50.0, 700.0);
const OUTSIDE_TOP: Offset = Offset::new(200.0, 50.0);
const OUTSIDE_TOP_RIGHT: Offset = Offset::new(350.0, 50.0);
const OUTSIDE_RIGHT: Offset = Offset::new(350.0, 200.0);
const OUTSIDE_BOTTOM_RIGHT: Offset = Offset::new(350.0, 700.0);
const OUTSIDE_BOTTOM: Offset = Offset::new(200.0, 700.0);
const CENTER: Offset = Offset::new(150.0, 300.0);
#[test]
fn selection_based_on_rect_works() {
assert_eq!(
SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_TOP_LEFT),
SelectionResult::Previous
);
assert_eq!(
SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_LEFT),
SelectionResult::Previous
);
assert_eq!(
SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_BOTTOM_LEFT),
SelectionResult::Next
);
assert_eq!(
SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_TOP),
SelectionResult::Previous
);
assert_eq!(
SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_TOP_RIGHT),
SelectionResult::Previous
);
assert_eq!(
SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_RIGHT),
SelectionResult::Next
);
assert_eq!(
SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_BOTTOM_RIGHT),
SelectionResult::Next
);
assert_eq!(
SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_BOTTOM),
SelectionResult::Next
);
assert_eq!(
SelectionUtils::get_result_based_on_rect(RECT, CENTER),
SelectionResult::End
);
}
#[test]
fn adjust_drag_offset_works() {
let top_left = Offset::new(RECT.left, RECT.top);
let top_right = Offset::new(RECT.right, RECT.top);
let bottom_left = Offset::new(RECT.left, RECT.bottom);
let bottom_right = Offset::new(RECT.right, RECT.bottom);
for (point, expected) in [
(OUTSIDE_TOP_LEFT, top_left),
(OUTSIDE_LEFT, top_left),
(OUTSIDE_BOTTOM_LEFT, bottom_right),
(OUTSIDE_TOP, top_left),
(OUTSIDE_TOP_RIGHT, top_left),
(OUTSIDE_RIGHT, bottom_right),
(OUTSIDE_BOTTOM_RIGHT, bottom_right),
(OUTSIDE_BOTTOM, bottom_right),
(CENTER, CENTER),
] {
assert_eq!(
SelectionUtils::adjust_drag_offset(RECT, point, TextDirection::Ltr),
expected
);
}
for (point, expected) in [
(OUTSIDE_TOP_LEFT, top_right),
(OUTSIDE_LEFT, top_right),
(OUTSIDE_BOTTOM_LEFT, bottom_left),
(OUTSIDE_TOP, top_right),
(OUTSIDE_TOP_RIGHT, top_right),
(OUTSIDE_RIGHT, bottom_left),
(OUTSIDE_BOTTOM_RIGHT, bottom_left),
(OUTSIDE_BOTTOM, bottom_left),
(CENTER, CENTER),
] {
assert_eq!(
SelectionUtils::adjust_drag_offset(RECT, point, TextDirection::Rtl),
expected
);
}
}
}