use super::*;
use block2::RcBlock;
use day_spec::ScrollPhase;
use objc2_app_kit::{NSClipView, NSEventPhase, NSScrollElasticity};
use std::ptr::NonNull;
pub(super) fn reveal_origin(view: f64, view_len: f64, lo: f64, len: f64) -> f64 {
let (a, b) = (lo, lo + len - view_len);
view.clamp(a.min(b), a.max(b))
}
pub(super) fn row_origin(
view: f64,
view_len: f64,
top: f64,
bottom: f64,
align: day_spec::RowAlign,
) -> f64 {
match align {
day_spec::RowAlign::Nearest => reveal_origin(view, view_len, top, bottom - top),
day_spec::RowAlign::Start => top,
day_spec::RowAlign::Center => f64::midpoint(top, bottom) - view_len / 2.0,
day_spec::RowAlign::End => bottom - view_len,
}
}
const TOUCH: f64 = 1e-3;
pub(super) fn visible_span(
top: f64,
bottom: f64,
first: usize,
count: usize,
row: impl Fn(usize) -> (f64, f64),
) -> Option<(usize, usize)> {
if count == 0 {
return None;
}
let (mut lo, mut hi) = (first, first + count - 1);
while lo < hi && row(lo).1 <= top + TOUCH {
lo += 1;
}
while hi > lo && row(hi).0 >= bottom - TOUCH {
hi -= 1;
}
Some((lo, hi))
}
pub(super) fn snap_stop(
offset: f64,
start: f64,
extent: f64,
snap: ScrollSnap,
max: f64,
) -> Option<f64> {
let max = max.max(0.0);
let stop = match snap {
ScrollSnap::Interval(step) if step.is_finite() && step > 0.0 => {
(offset / step).round() * step
}
ScrollSnap::Page if extent.is_finite() && extent > 0.0 => {
let from = (start / extent).round();
(offset / extent).round().clamp(from - 1.0, from + 1.0) * extent
}
_ => return None,
};
let stop = stop.clamp(0.0, max);
Some(if (offset - max).abs() < (offset - stop).abs() {
max
} else {
stop
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum WheelStep {
None,
Touch,
Began,
Changed,
Ended,
}
impl WheelStep {
fn of(phase: NSEventPhase) -> Self {
if phase.contains(NSEventPhase::Began) {
Self::Began
} else if phase.intersects(NSEventPhase::Changed | NSEventPhase::Stationary) {
Self::Changed
} else if phase.intersects(NSEventPhase::Ended | NSEventPhase::Cancelled) {
Self::Ended
} else if phase.contains(NSEventPhase::MayBegin) {
Self::Touch
} else {
Self::None
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PhaseInput {
LiveStart,
LiveEnd,
Wheel {
gesture: WheelStep,
momentum: WheelStep,
},
Quiet,
}
pub(super) fn next_phase(now: ScrollPhase, input: PhaseInput) -> (ScrollPhase, bool) {
match input {
PhaseInput::LiveStart => (ScrollPhase::Dragging, false),
PhaseInput::LiveEnd
| PhaseInput::Quiet
| PhaseInput::Wheel {
momentum: WheelStep::Ended,
..
} => (ScrollPhase::Idle, false),
PhaseInput::Wheel {
momentum: WheelStep::Began | WheelStep::Changed,
..
} => (ScrollPhase::Coasting, false),
PhaseInput::Wheel { gesture, .. } => match gesture {
WheelStep::Began | WheelStep::Changed => (ScrollPhase::Dragging, false),
WheelStep::Ended => (now, true),
WheelStep::Touch => (now, false),
WheelStep::None => (ScrollPhase::Dragging, true),
},
}
}
const WHEEL_QUIET_MS: u32 = 150;
pub(super) struct ScrollIvars {
node: NodeId,
horizontal: bool,
track_offset: bool,
track_phase: bool,
snap: ScrollSnap,
zoom: Option<ZoomRange>,
offset: Cell<Option<(f64, f64)>>,
scale: Cell<f64>,
phase: Cell<ScrollPhase>,
start: Cell<f64>,
wheel: Cell<u64>,
zooms: Cell<u64>,
}
define_class!(
#[unsafe(super(NSScrollView))]
#[thread_kind = MainThreadOnly]
#[name = "DayScrollView"]
#[ivars = ScrollIvars]
pub(super) struct DayScrollView;
unsafe impl NSObjectProtocol for DayScrollView {}
impl DayScrollView {
#[unsafe(method(dayBoundsChanged:))]
fn bounds_changed(&self, _notification: &NSNotification) {
ffi_guard::contain((), || report(self, self.ivars(), false));
}
#[unsafe(method(dayLiveMagnifyEnded:))]
fn live_magnify_ended(&self, _notification: &NSNotification) {
ffi_guard::contain((), || report(self, self.ivars(), true));
}
}
);
define_class!(
#[unsafe(super(NSScrollView))]
#[thread_kind = MainThreadOnly]
#[name = "DayPhasedScrollView"]
#[ivars = ScrollIvars]
pub(super) struct DayPhasedScrollView;
unsafe impl NSObjectProtocol for DayPhasedScrollView {}
impl DayPhasedScrollView {
#[unsafe(method(dayBoundsChanged:))]
fn bounds_changed(&self, _notification: &NSNotification) {
ffi_guard::contain((), || report(self, self.ivars(), false));
}
#[unsafe(method(dayLiveMagnifyEnded:))]
fn live_magnify_ended(&self, _notification: &NSNotification) {
ffi_guard::contain((), || report(self, self.ivars(), true));
}
#[unsafe(method(dayLiveScrollStarted:))]
fn live_scroll_started(&self, _notification: &NSNotification) {
ffi_guard::contain((), || track(self, self.ivars(), PhaseInput::LiveStart));
}
#[unsafe(method(dayLiveScrollEnded:))]
fn live_scroll_ended(&self, _notification: &NSNotification) {
ffi_guard::contain((), || track(self, self.ivars(), PhaseInput::LiveEnd));
}
#[unsafe(method(scrollWheel:))]
fn scroll_wheel(&self, event: &NSEvent) {
ffi_guard::contain((), || {
let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
let gesture = WheelStep::of(unsafe { event.phase() });
let momentum = WheelStep::of(unsafe { event.momentumPhase() });
let ivars = self.ivars();
ivars.wheel.set(ivars.wheel.get().wrapping_add(1));
track(self, ivars, PhaseInput::Wheel { gesture, momentum });
});
}
}
);
fn parts(h: &NSView) -> Option<(&NSScrollView, &ScrollIvars)> {
if let Some(sv) = h.downcast_ref::<DayScrollView>() {
return Some((sv, sv.ivars()));
}
h.downcast_ref::<DayPhasedScrollView>()
.map(|sv| (&**sv, sv.ivars()))
}
fn viewport_offset(sv: &NSScrollView) -> (f64, f64) {
let origin = unsafe { sv.contentView() }.bounds().origin;
let scale = unsafe { sv.magnification() };
(origin.x * scale, origin.y * scale)
}
fn report(sv: &NSScrollView, ivars: &ScrollIvars, settle: bool) {
if ivars.zoom.is_some() {
let scale = unsafe { sv.magnification() };
if settle || (scale - ivars.scale.get()).abs() > 1e-6 {
ivars.scale.set(scale);
emit(ivars.node, Event::ScrollZoomed(scale));
}
}
if ivars.track_offset {
let now = viewport_offset(sv);
if ivars.offset.replace(Some(now)) != Some(now) {
emit(ivars.node, Event::ScrollChanged(Point::new(now.0, now.1)));
}
}
}
fn along(sv: &NSScrollView, ivars: &ScrollIvars) -> f64 {
let origin = unsafe { sv.contentView() }.bounds().origin;
if ivars.horizontal { origin.x } else { origin.y }
}
fn track(sv: &NSScrollView, ivars: &ScrollIvars, input: PhaseInput) {
let before = ivars.phase.get();
let (after, quiet) = next_phase(before, input);
if before == ScrollPhase::Idle && after != ScrollPhase::Idle {
ivars.start.set(along(sv, ivars));
}
if quiet {
arm_quiet(sv, ivars);
}
if after == ScrollPhase::Idle && before != ScrollPhase::Idle && snap(sv, ivars) {
return; }
enter(ivars, after);
}
fn enter(ivars: &ScrollIvars, phase: ScrollPhase) {
if ivars.phase.replace(phase) != phase && ivars.track_phase {
emit(ivars.node, Event::ScrollPhase(phase));
}
}
fn arm_quiet(sv: &NSScrollView, ivars: &ScrollIvars) {
let generation = ivars.wheel.get();
let this = Retained::into_raw(sv.retain()) as usize;
<AppKit as Platform>::post_delayed(
WHEEL_QUIET_MS,
Box::new(move || {
let Some(sv) = (unsafe { Retained::from_raw(this as *mut NSScrollView) }) else {
return;
};
if let Some((sv, ivars)) = parts(&sv)
&& ivars.wheel.get() == generation
{
track(sv, ivars, PhaseInput::Quiet);
}
}),
);
}
fn snap(sv: &NSScrollView, ivars: &ScrollIvars) -> bool {
let clip = unsafe { sv.contentView() };
let bounds = clip.bounds();
let Some(doc) = (unsafe { sv.documentView() }) else {
return false;
};
let content = doc.frame().size;
let (extent, max) = if ivars.horizontal {
(bounds.size.width, content.width - bounds.size.width)
} else {
(bounds.size.height, content.height - bounds.size.height)
};
let offset = along(sv, ivars);
let Some(stop) = snap_stop(offset, ivars.start.get(), extent, ivars.snap, max) else {
return false;
};
if (stop - offset).abs() < 0.5 {
return false;
}
enter(ivars, ScrollPhase::Coasting);
let mut to = bounds.origin;
if ivars.horizontal {
to.x = stop;
} else {
to.y = stop;
}
let view = sv.retain();
scroll_clip_to(
sv,
to,
true,
Some(Box::new(move || {
if let Some((_, ivars)) = parts(&view) {
enter(ivars, ScrollPhase::Idle);
}
})),
);
true
}
pub(super) fn realize(mtm: MainThreadMarker, node: NodeId, p: &ScrollProps) -> Retained<NSView> {
let ivars = ScrollIvars {
node,
horizontal: p.horizontal,
track_offset: p.track_offset,
track_phase: p.track_phase,
snap: p.snap,
zoom: p.zoom,
offset: Cell::new(None),
scale: Cell::new(1.0),
phase: Cell::new(ScrollPhase::Idle),
start: Cell::new(0.0),
wheel: Cell::new(0),
zooms: Cell::new(0),
};
let phased = p.track_phase || p.snap != ScrollSnap::None;
let sv: Retained<NSScrollView> = if phased {
let this = DayPhasedScrollView::alloc(mtm).set_ivars(ivars);
let this: Retained<DayPhasedScrollView> = unsafe { msg_send![super(this), init] };
Retained::into_super(this)
} else {
let this = DayScrollView::alloc(mtm).set_ivars(ivars);
let this: Retained<DayScrollView> = unsafe { msg_send![super(this), init] };
Retained::into_super(this)
};
let hidden = p.indicators == ScrollIndicators::Hidden;
unsafe {
sv.setHasVerticalScroller(!p.horizontal && !hidden);
sv.setHasHorizontalScroller(p.horizontal && !hidden);
sv.setDrawsBackground(false);
sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
let (along, across) = match p.bounce {
None => (NSScrollElasticity::Automatic, NSScrollElasticity::Automatic),
Some(false) => (NSScrollElasticity::None, NSScrollElasticity::None),
Some(true) => (NSScrollElasticity::Allowed, NSScrollElasticity::Automatic),
};
let (vertical, horizontal) = if p.horizontal {
(across, along)
} else {
(along, across)
};
sv.setVerticalScrollElasticity(vertical);
sv.setHorizontalScrollElasticity(horizontal);
if let Some(zoom) = p.zoom {
sv.setAllowsMagnification(true);
sv.setMinMagnification(zoom.min);
sv.setMaxMagnification(zoom.max);
}
}
let doc = DayFlipped::new(mtm);
unsafe { sv.setDocumentView(Some(doc.as_ref())) };
let center = objc2_foundation::NSNotificationCenter::defaultCenter();
let clip = unsafe { sv.contentView() };
unsafe {
if p.track_offset || p.zoom.is_some() {
clip.setPostsBoundsChangedNotifications(true);
center.addObserver_selector_name_object(
&sv,
sel!(dayBoundsChanged:),
Some(objc2_app_kit::NSViewBoundsDidChangeNotification),
Some(&clip),
);
}
if phased {
center.addObserver_selector_name_object(
&sv,
sel!(dayLiveScrollStarted:),
Some(objc2_app_kit::NSScrollViewWillStartLiveScrollNotification),
Some(&sv),
);
center.addObserver_selector_name_object(
&sv,
sel!(dayLiveScrollEnded:),
Some(objc2_app_kit::NSScrollViewDidEndLiveScrollNotification),
Some(&sv),
);
}
if p.zoom.is_some() {
center.addObserver_selector_name_object(
&sv,
sel!(dayLiveMagnifyEnded:),
Some(objc2_app_kit::NSScrollViewDidEndLiveMagnifyNotification),
Some(&sv),
);
}
}
Retained::into_super(sv)
}
pub(super) fn offset(h: &NSView) -> Point {
match h.downcast_ref::<NSScrollView>() {
Some(sv) => {
let (x, y) = viewport_offset(sv);
Point::new(x, y)
}
None => Point::ZERO,
}
}
pub(super) fn zoom(h: &NSView, scale: f64, animated: bool) {
let Some((sv, ivars)) = parts(h) else {
return;
};
let Some(range) = ivars.zoom else {
return;
};
if !scale.is_finite() {
return;
}
let scale = scale.clamp(range.min, range.max);
let zoom = ivars.zooms.get().wrapping_add(1);
ivars.zooms.set(zoom);
let clip = unsafe { sv.contentView() };
let bounds = clip.bounds();
let center = NSPoint::new(
bounds.origin.x + bounds.size.width / 2.0,
bounds.origin.y + bounds.size.height / 2.0,
);
if !animated {
unsafe { sv.setMagnification_centeredAtPoint(scale, center) };
report(sv, ivars, true);
return;
}
let (target, done) = (sv.retain(), sv.retain());
let changes = RcBlock::new(move |_ctx: NonNull<NSAnimationContext>| {
let animator: Retained<AnyObject> = unsafe { msg_send![&*target, animator] };
let value = NSNumber::new_f64(scale);
let key = NSString::from_str("magnification");
let _: () = unsafe { msg_send![&*animator, setValue: &*value, forKey: &*key] };
});
let completion = RcBlock::new(move || {
ffi_guard::contain((), || {
let Some((sv, ivars)) = parts(&done) else {
return;
};
if ivars.zooms.get() != zoom {
return;
}
unsafe { sv.setMagnification_centeredAtPoint(scale, center) };
report(sv, ivars, true);
});
});
unsafe { NSAnimationContext::runAnimationGroup_completionHandler(&changes, Some(&completion)) };
}
pub(super) fn scroll_clip_to(
scroll: &NSScrollView,
to: NSPoint,
animated: bool,
done: Option<Box<dyn FnOnce()>>,
) {
let clip: Retained<NSClipView> = unsafe { scroll.contentView() };
let mut bounds = clip.bounds();
bounds.origin = to;
let to = clip.constrainBoundsRect(bounds).origin;
if animated {
let target = clip.clone();
let changes = RcBlock::new(move |_ctx: NonNull<NSAnimationContext>| {
let animator: Retained<NSClipView> = unsafe { msg_send![&*target, animator] };
animator.setBoundsOrigin(to);
});
let (scroll, done) = (scroll.retain(), Cell::new(done));
let completion = RcBlock::new(move || {
ffi_guard::contain((), || {
scroll.reflectScrolledClipView(&scroll.contentView());
if let Some(done) = done.take() {
done();
}
});
});
unsafe {
NSAnimationContext::runAnimationGroup_completionHandler(&changes, Some(&completion));
}
} else {
settle_clip_at(&clip, to);
clip.scrollToPoint(to);
unsafe { scroll.reflectScrolledClipView(&clip) };
if let Some(done) = done {
done();
}
}
}
fn settle_clip_at(clip: &NSClipView, to: NSPoint) {
unsafe {
NSAnimationContext::beginGrouping();
NSAnimationContext::currentContext().setDuration(0.0);
let animator: Retained<NSClipView> = msg_send![clip, animator];
animator.setBoundsOrigin(to);
NSAnimationContext::endGrouping();
}
}
pub(super) fn stop_clip_animation(scroll: &NSScrollView) {
let clip: Retained<NSClipView> = unsafe { scroll.contentView() };
settle_clip_at(&clip, clip.bounds().origin);
}
#[cfg(test)]
mod tests {
use super::*;
use day_spec::RowAlign;
#[test]
fn reveal_moves_as_little_as_it_can() {
assert_eq!(reveal_origin(100.0, 50.0, 110.0, 20.0), 100.0);
assert_eq!(reveal_origin(100.0, 50.0, 160.0, 20.0), 130.0);
assert_eq!(reveal_origin(100.0, 50.0, 40.0, 20.0), 40.0);
assert_eq!(reveal_origin(0.0, 50.0, 100.0, 200.0), 100.0);
assert_eq!(reveal_origin(400.0, 50.0, 100.0, 200.0), 250.0);
assert_eq!(reveal_origin(150.0, 50.0, 100.0, 200.0), 150.0);
}
#[test]
fn rows_land_where_their_alignment_says() {
let (top, bottom) = (3200.0, 3232.0);
assert_eq!(row_origin(0.0, 160.0, top, bottom, RowAlign::Start), 3200.0);
assert_eq!(row_origin(0.0, 160.0, top, bottom, RowAlign::End), 3072.0);
assert_eq!(
row_origin(0.0, 160.0, top, bottom, RowAlign::Center),
3136.0
);
assert_eq!(
row_origin(0.0, 160.0, top, bottom, RowAlign::Nearest),
3072.0
);
assert_eq!(
row_origin(3100.0, 160.0, top, bottom, RowAlign::Nearest),
3100.0
);
}
#[test]
fn rows_that_only_touch_the_viewport_are_outside_it() {
let row = |i: usize| (i as f64 * 32.0, (i + 1) as f64 * 32.0);
assert_eq!(visible_span(3200.0, 3360.0, 99, 7, row), Some((100, 104)));
assert_eq!(visible_span(3216.0, 3376.0, 100, 6, row), Some((100, 105)));
assert_eq!(visible_span(0.0, 160.0, 0, 0, row), None);
assert_eq!(
visible_span(10.0, 20.0, 0, 1, |_| (0.0, 100.0)),
Some((0, 0))
);
}
#[test]
fn snaps_rest_on_their_stops() {
assert_eq!(snap_stop(130.0, 0.0, 100.0, ScrollSnap::None, 1000.0), None);
assert_eq!(
snap_stop(130.0, 0.0, 100.0, ScrollSnap::Interval(40.0), 1000.0),
Some(120.0)
);
assert_eq!(
snap_stop(160.0, 100.0, 100.0, ScrollSnap::Page, 1000.0),
Some(200.0)
);
assert_eq!(
snap_stop(140.0, 100.0, 100.0, ScrollSnap::Page, 1000.0),
Some(100.0)
);
assert_eq!(
snap_stop(480.0, 100.0, 100.0, ScrollSnap::Page, 1000.0),
Some(200.0)
);
assert_eq!(
snap_stop(950.0, 900.0, 100.0, ScrollSnap::Page, 950.0),
Some(950.0)
);
assert_eq!(
snap_stop(10.0, 0.0, 100.0, ScrollSnap::Interval(0.0), 1000.0),
None
);
}
#[test]
fn phases_follow_gestures_momentum_and_wheels() {
use PhaseInput::{LiveEnd, LiveStart, Quiet, Wheel};
use ScrollPhase::{Coasting, Dragging, Idle};
let wheel = |gesture, momentum| Wheel { gesture, momentum };
let mut now = Idle;
for (input, want) in [
(wheel(WheelStep::Touch, WheelStep::None), Idle),
(LiveStart, Dragging),
(wheel(WheelStep::Began, WheelStep::None), Dragging),
(wheel(WheelStep::Changed, WheelStep::None), Dragging),
(wheel(WheelStep::Ended, WheelStep::None), Dragging),
(wheel(WheelStep::None, WheelStep::Began), Coasting),
(wheel(WheelStep::None, WheelStep::Changed), Coasting),
(wheel(WheelStep::None, WheelStep::Ended), Idle),
(LiveEnd, Idle),
] {
now = next_phase(now, input).0;
assert_eq!(now, want, "{input:?}");
}
assert_eq!(
next_phase(Dragging, wheel(WheelStep::Ended, WheelStep::None)),
(Dragging, true)
);
assert_eq!(
next_phase(Idle, wheel(WheelStep::None, WheelStep::None)),
(Dragging, true)
);
assert_eq!(next_phase(Dragging, Quiet), (Idle, false));
}
}