fix(text): always draw the first line under overflow: elide
Vendor i-slint-core 1.16.1 with a one-rule patch in sharedparley's
line culling: with overflow: elide, every line whose bottom edge
exceeded max_height was dropped — INCLUDING the first one, eliding the
text to literally nothing. CJK fallback fonts report line metrics
taller than snug fixed-height boxes (Hiragino at 14px measures ~21px
inside TrackRow's 20px title line), so on macOS every CJK track title
rendered blank while Latin titles fit; Linux survived because Noto's
metrics fit the box. Root-caused with a headless render matrix on the
Mac Mini: the verbatim TrackRow structure reproduced the blank title,
removing elide rendered it, and the patched core renders all variants.
The first line still receives the ellipsis treatment as the last
visible line.
This is the real #543 mechanism. The earlier femtovg render_glyph
retry (3a1c367d) addressed a different, hypothesized layer and stays
as harmless defense in depth.
Fixes #543
cc
This commit is contained in:
82 files changed
+51634
-2
No files matched your search
@@ -0,0 +1,425 @@
|
||||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use super::{
|
||||
BindingHolder, BindingResult, BindingVTable, DependencyListHead, DependencyNode,
|
||||
single_linked_list_pin::SingleLinkedListPinHead,
|
||||
};
|
||||
use alloc::boxed::Box;
|
||||
use core::cell::{Cell, UnsafeCell};
|
||||
use core::marker::PhantomPinned;
|
||||
use core::pin::Pin;
|
||||
use core::ptr::addr_of;
|
||||
|
||||
// TODO a pinned thread local key?
|
||||
crate::thread_local! {static CHANGED_NODES : Pin<Box<DependencyListHead>> = Box::pin(DependencyListHead::default()) }
|
||||
|
||||
struct ChangeTrackerInner<T, EvalFn, NotifyFn, Data> {
|
||||
eval_fn: EvalFn,
|
||||
notify_fn: NotifyFn,
|
||||
/// The value. Borrowed-mut when `evaluating` is true
|
||||
value: UnsafeCell<T>,
|
||||
data: Data,
|
||||
/// When true, we are currently running eval_fn or notify_fn and we shouldn't be dropped
|
||||
evaluating: Cell<bool>,
|
||||
}
|
||||
|
||||
/// A change tracker is used to run a callback when a property value changes.
|
||||
///
|
||||
/// The Change Tracker must be initialized with the [`Self::init`] method.
|
||||
///
|
||||
/// When the property changes, the ChangeTracker is added to a thread local list, and the notify
|
||||
/// callback is called when the [`Self::run_change_handlers()`] method is called
|
||||
#[derive(Debug)]
|
||||
pub struct ChangeTracker {
|
||||
/// (Actually a `BindingHolder<ChangeTrackerInner>`)
|
||||
inner: Cell<*mut BindingHolder>,
|
||||
}
|
||||
|
||||
impl Default for ChangeTracker {
|
||||
fn default() -> Self {
|
||||
Self { inner: Cell::new(core::ptr::null_mut()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ChangeTracker {
|
||||
fn drop(&mut self) {
|
||||
self.clear();
|
||||
}
|
||||
}
|
||||
|
||||
impl ChangeTracker {
|
||||
/// Initialize the change tracker with the given data and callbacks.
|
||||
///
|
||||
/// The `data` is any struct that is going to be passed to the functor.
|
||||
/// The `eval_fn` is a function that queries and return the property.
|
||||
/// And the `notify_fn` is the callback run if the property is changed
|
||||
pub fn init<
|
||||
Data: 'static,
|
||||
T: Default + PartialEq,
|
||||
EF: Fn(&Data) -> T + 'static,
|
||||
NF: Fn(&Data, &T) + 'static,
|
||||
>(
|
||||
&self,
|
||||
data: Data,
|
||||
eval_fn: EF,
|
||||
notify_fn: NF,
|
||||
) {
|
||||
self.init_impl(data, eval_fn, notify_fn, false);
|
||||
}
|
||||
|
||||
/// Initialize the change tracker with the given data and callbacks.
|
||||
///
|
||||
/// Same as [`Self::init`], but the first eval function is called in a future evaluation of the event loop.
|
||||
/// This means that the change tracker will consider the value as default initialized, and the eval function will
|
||||
/// be called the firs ttime if the initial value is not equal to the default constructed value.
|
||||
pub fn init_delayed<
|
||||
Data: 'static,
|
||||
T: Default + PartialEq,
|
||||
EF: Fn(&Data) -> T + 'static,
|
||||
NF: Fn(&Data, &T) + 'static,
|
||||
>(
|
||||
&self,
|
||||
data: Data,
|
||||
eval_fn: EF,
|
||||
notify_fn: NF,
|
||||
) {
|
||||
self.init_impl(data, eval_fn, notify_fn, true);
|
||||
}
|
||||
|
||||
fn init_impl<
|
||||
Data: 'static,
|
||||
T: Default + PartialEq,
|
||||
EF: Fn(&Data) -> T + 'static,
|
||||
NF: Fn(&Data, &T) + 'static,
|
||||
>(
|
||||
&self,
|
||||
data: Data,
|
||||
eval_fn: EF,
|
||||
notify_fn: NF,
|
||||
delayed: bool,
|
||||
) {
|
||||
self.clear();
|
||||
let inner = ChangeTrackerInner {
|
||||
eval_fn,
|
||||
notify_fn,
|
||||
value: T::default().into(),
|
||||
data,
|
||||
evaluating: false.into(),
|
||||
};
|
||||
|
||||
unsafe fn evaluate<
|
||||
T: PartialEq,
|
||||
EF: Fn(&Data) -> T + 'static,
|
||||
NF: Fn(&Data, &T) + 'static,
|
||||
Data: 'static,
|
||||
>(
|
||||
_self: *const BindingHolder,
|
||||
_value: *mut (),
|
||||
) -> BindingResult {
|
||||
unsafe {
|
||||
let pinned_holder = Pin::new_unchecked(&*_self);
|
||||
let _self = _self as *const BindingHolder<ChangeTrackerInner<T, EF, NF, Data>>;
|
||||
let inner = core::ptr::addr_of!((*_self).binding).as_ref().unwrap();
|
||||
(*core::ptr::addr_of!((*_self).dep_nodes)).take();
|
||||
assert!(!inner.evaluating.get());
|
||||
inner.evaluating.set(true);
|
||||
let new_value = super::CURRENT_BINDING
|
||||
.set(Some(pinned_holder), || (inner.eval_fn)(&inner.data));
|
||||
{
|
||||
// Safety: We just set `evaluating` to true which means we can borrow
|
||||
let inner_value = &mut *inner.value.get();
|
||||
if new_value != *inner_value {
|
||||
*inner_value = new_value;
|
||||
(inner.notify_fn)(&inner.data, inner_value);
|
||||
}
|
||||
}
|
||||
|
||||
if !inner.evaluating.replace(false) {
|
||||
// `drop` from the vtable was called while evaluating. Do it now.
|
||||
core::mem::drop(Box::from_raw(
|
||||
_self as *mut BindingHolder<ChangeTrackerInner<T, EF, NF, Data>>,
|
||||
));
|
||||
}
|
||||
BindingResult::KeepBinding
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn drop<T, EF, NF, Data>(_self: *mut BindingHolder) {
|
||||
unsafe {
|
||||
let _self = _self as *mut BindingHolder<ChangeTrackerInner<T, EF, NF, Data>>;
|
||||
let evaluating = core::ptr::addr_of!((*_self).binding)
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.evaluating
|
||||
.replace(false);
|
||||
if !evaluating {
|
||||
core::mem::drop(Box::from_raw(_self));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait HasBindingVTable {
|
||||
const VT: &'static BindingVTable;
|
||||
}
|
||||
impl<T: PartialEq, EF: Fn(&Data) -> T + 'static, NF: Fn(&Data, &T) + 'static, Data: 'static>
|
||||
HasBindingVTable for ChangeTrackerInner<T, EF, NF, Data>
|
||||
{
|
||||
const VT: &'static BindingVTable = &BindingVTable {
|
||||
drop: drop::<T, EF, NF, Data>,
|
||||
evaluate: evaluate::<T, EF, NF, Data>,
|
||||
mark_dirty: ChangeTracker::mark_dirty,
|
||||
intercept_set: |_, _| false,
|
||||
intercept_set_binding: |_, _| false,
|
||||
};
|
||||
}
|
||||
let holder = BindingHolder {
|
||||
dependencies: Cell::new(0),
|
||||
dep_nodes: Default::default(),
|
||||
vtable: <ChangeTrackerInner<T, EF, NF, Data> as HasBindingVTable>::VT,
|
||||
dirty: Cell::new(false),
|
||||
is_two_way_binding: false,
|
||||
pinned: PhantomPinned,
|
||||
binding: inner,
|
||||
#[cfg(slint_debug_property)]
|
||||
debug_name: "<ChangeTracker>".into(),
|
||||
};
|
||||
|
||||
let raw = Box::into_raw(Box::new(holder));
|
||||
unsafe { self.set_internal(raw as *mut BindingHolder) };
|
||||
if delayed {
|
||||
let mut dep_nodes = SingleLinkedListPinHead::default();
|
||||
let node = dep_nodes.push_front(DependencyNode::new(raw as *const BindingHolder));
|
||||
CHANGED_NODES.with(|changed_nodes| {
|
||||
changed_nodes.append(node);
|
||||
});
|
||||
unsafe { (*core::ptr::addr_of_mut!((*raw).dep_nodes)).set(dep_nodes) };
|
||||
return;
|
||||
}
|
||||
let value = unsafe {
|
||||
let pinned_holder = Pin::new_unchecked((raw as *mut BindingHolder).as_ref().unwrap());
|
||||
let inner = core::ptr::addr_of!((*raw).binding).as_ref().unwrap();
|
||||
super::CURRENT_BINDING.set(Some(pinned_holder), || (inner.eval_fn)(&inner.data))
|
||||
};
|
||||
unsafe {
|
||||
*core::ptr::addr_of_mut!((*raw).binding).as_mut().unwrap().value.get_mut() = value
|
||||
};
|
||||
}
|
||||
|
||||
/// Clear the change tracker.
|
||||
/// No notify function will be called after this.
|
||||
pub fn clear(&self) {
|
||||
let inner = self.inner.get();
|
||||
if !inner.is_null() {
|
||||
unsafe {
|
||||
let drop = (*core::ptr::addr_of!((*inner).vtable)).drop;
|
||||
drop(inner);
|
||||
}
|
||||
self.inner.set(core::ptr::null_mut());
|
||||
}
|
||||
}
|
||||
|
||||
/// Run all the change handler that were queued.
|
||||
pub fn run_change_handlers() {
|
||||
CHANGED_NODES.with(|list| {
|
||||
let old_list = DependencyListHead::default();
|
||||
let old_list = core::pin::pin!(old_list);
|
||||
let mut count = 0;
|
||||
while !list.is_empty() {
|
||||
count += 1;
|
||||
if count > 9 {
|
||||
crate::debug_log!("Slint: long changed callback chain detected");
|
||||
return;
|
||||
}
|
||||
DependencyListHead::swap(list.as_ref(), old_list.as_ref());
|
||||
while let Some(node) = old_list.take_head() {
|
||||
unsafe {
|
||||
((*addr_of!((*node).vtable)).evaluate)(
|
||||
node as *mut BindingHolder,
|
||||
core::ptr::null_mut(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) unsafe fn mark_dirty(_self: *const BindingHolder, _was_dirty: bool) {
|
||||
let _self = unsafe { _self.as_ref().unwrap() };
|
||||
let node_head = _self.dep_nodes.take();
|
||||
if let Some(node) = node_head.iter().next() {
|
||||
node.remove();
|
||||
CHANGED_NODES.with(|changed_nodes| {
|
||||
changed_nodes.append(node);
|
||||
});
|
||||
}
|
||||
let other = _self.dep_nodes.replace(node_head);
|
||||
debug_assert!(other.iter().next().is_none());
|
||||
}
|
||||
|
||||
pub(super) unsafe fn set_internal(&self, raw: *mut BindingHolder) {
|
||||
self.inner.set(raw);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_tracker() {
|
||||
use super::Property;
|
||||
use std::rc::Rc;
|
||||
let prop1 = Rc::pin(Property::new(42));
|
||||
let prop2 = Rc::pin(Property::<i32>::default());
|
||||
prop2.as_ref().set_binding({
|
||||
let prop1 = prop1.clone();
|
||||
move || prop1.as_ref().get() * 2
|
||||
});
|
||||
|
||||
let change1 = ChangeTracker::default();
|
||||
let change2 = ChangeTracker::default();
|
||||
|
||||
let state = Rc::new(core::cell::RefCell::new(std::string::String::new()));
|
||||
|
||||
change1.init(
|
||||
(state.clone(), prop1.clone()),
|
||||
|(_, prop1)| prop1.as_ref().get(),
|
||||
|(state, _), val| {
|
||||
*state.borrow_mut() += &std::format!(":1({val})");
|
||||
},
|
||||
);
|
||||
change2.init(
|
||||
(state.clone(), prop2.clone()),
|
||||
|(_, prop2)| prop2.as_ref().get(),
|
||||
|(state, _), val| {
|
||||
*state.borrow_mut() += &std::format!(":2({val})");
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(state.borrow().as_str(), "");
|
||||
prop1.as_ref().set(10);
|
||||
assert_eq!(state.borrow().as_str(), "");
|
||||
prop1.as_ref().set(30);
|
||||
assert_eq!(state.borrow().as_str(), "");
|
||||
|
||||
ChangeTracker::run_change_handlers();
|
||||
assert_eq!(state.borrow().as_str(), ":1(30):2(60)");
|
||||
ChangeTracker::run_change_handlers();
|
||||
assert_eq!(state.borrow().as_str(), ":1(30):2(60)");
|
||||
prop1.as_ref().set(1);
|
||||
assert_eq!(state.borrow().as_str(), ":1(30):2(60)");
|
||||
ChangeTracker::run_change_handlers();
|
||||
assert_eq!(state.borrow().as_str(), ":1(30):2(60):1(1):2(2)");
|
||||
}
|
||||
|
||||
/// test for issue #8741
|
||||
#[test]
|
||||
fn delete_from_eval_fn() {
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::string::String;
|
||||
|
||||
let change = Rc::<RefCell<Option<ChangeTracker>>>::new(Some(ChangeTracker::default()).into());
|
||||
let xyz = RefCell::new(String::from("*"));
|
||||
let result = Rc::new(RefCell::new(String::new()));
|
||||
let result2 = result.clone();
|
||||
// The change event are run in reverse order as they are created, so this one shouldn't be ever called as it is being detroyed from `change`
|
||||
let another = Rc::<RefCell<Option<ChangeTracker>>>::new(Some(ChangeTracker::default()).into());
|
||||
another.borrow().as_ref().unwrap().init_delayed(
|
||||
(),
|
||||
|()| unreachable!(),
|
||||
move |(), &()| unreachable!(),
|
||||
);
|
||||
change.borrow().as_ref().unwrap().init_delayed(
|
||||
change.clone(),
|
||||
|x| {
|
||||
x.borrow_mut().take().unwrap();
|
||||
String::from("hi")
|
||||
},
|
||||
move |x, val| {
|
||||
assert!(x.borrow().is_none());
|
||||
assert_eq!(val, "hi");
|
||||
xyz.borrow_mut().push_str("+");
|
||||
assert!(xyz.borrow().as_str().starts_with("*+"));
|
||||
result2.replace(xyz.borrow().clone());
|
||||
another.borrow_mut().take().unwrap();
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(result.borrow().as_str(), "");
|
||||
ChangeTracker::run_change_handlers();
|
||||
assert_eq!(result.borrow().as_str(), "*+");
|
||||
ChangeTracker::run_change_handlers();
|
||||
assert_eq!(result.borrow().as_str(), "*+");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_mutliple_dependencies() {
|
||||
use super::Property;
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::string::String;
|
||||
let prop1 = Rc::pin(Property::new(1));
|
||||
let prop2 = Rc::pin(Property::new(2));
|
||||
let prop3 = Rc::pin(Property::new(3));
|
||||
let prop4 = Rc::pin(Property::new(4));
|
||||
let prop_with_deps = Rc::pin(Property::new(5));
|
||||
let result = Rc::new(RefCell::new(String::new()));
|
||||
|
||||
let change_tracker = ChangeTracker::default();
|
||||
change_tracker.init(
|
||||
result.clone(),
|
||||
{
|
||||
let prop1 = prop1.clone();
|
||||
let prop2 = prop2.clone();
|
||||
let prop3 = prop3.clone();
|
||||
let prop4 = prop4.clone();
|
||||
let prop_with_deps = prop_with_deps.clone();
|
||||
move |_| {
|
||||
prop1.as_ref().get()
|
||||
+ prop2.as_ref().get()
|
||||
+ prop3.as_ref().get()
|
||||
+ prop4.as_ref().get()
|
||||
+ prop_with_deps.as_ref().get()
|
||||
}
|
||||
},
|
||||
move |result, val| {
|
||||
*result.borrow_mut() += &std::format!("[{val}]");
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(result.borrow().as_str(), "");
|
||||
ChangeTracker::run_change_handlers();
|
||||
assert_eq!(result.borrow().as_str(), "");
|
||||
|
||||
prop_with_deps.as_ref().set_binding({
|
||||
let prop1 = prop1.clone();
|
||||
let prop2 = prop2.clone();
|
||||
move || prop1.as_ref().get() + prop2.as_ref().get()
|
||||
});
|
||||
|
||||
assert_eq!(result.borrow().as_str(), "");
|
||||
ChangeTracker::run_change_handlers();
|
||||
assert_eq!(prop_with_deps.as_ref().get(), 3);
|
||||
assert_eq!(result.borrow().as_str(), "[13]"); // 1 + 2 + 3 + 4 + 3
|
||||
|
||||
ChangeTracker::run_change_handlers();
|
||||
assert_eq!(result.borrow().as_str(), "[13]");
|
||||
|
||||
prop1.as_ref().set(10);
|
||||
assert_eq!(result.borrow().as_str(), "[13]");
|
||||
ChangeTracker::run_change_handlers();
|
||||
assert_eq!(result.borrow().as_str(), "[13][31]"); // 10 + 2 + 3 + 4 + 12
|
||||
|
||||
prop2.as_ref().set(20);
|
||||
prop3.as_ref().set(30);
|
||||
assert_eq!(result.borrow().as_str(), "[13][31]");
|
||||
ChangeTracker::run_change_handlers();
|
||||
assert_eq!(result.borrow().as_str(), "[13][31][94]"); // 10 + 20 + 30 + 4 + 30
|
||||
|
||||
ChangeTracker::run_change_handlers();
|
||||
assert_eq!(result.borrow().as_str(), "[13][31][94]");
|
||||
|
||||
// just swap prop1 and prop2, doesn't change the outcome
|
||||
prop1.as_ref().set(20);
|
||||
prop2.as_ref().set(10);
|
||||
ChangeTracker::run_change_handlers();
|
||||
assert_eq!(result.borrow().as_str(), "[13][31][94]");
|
||||
}
|
||||
+568
@@ -0,0 +1,568 @@
|
||||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use super::*;
|
||||
use crate::graphics::{Brush, Color};
|
||||
use crate::items::PropertyAnimation;
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
type c_void = ();
|
||||
#[repr(C)]
|
||||
/// Has the same layout as PropertyHandle
|
||||
pub struct PropertyHandleOpaque(PropertyHandle);
|
||||
|
||||
/// Initialize the first pointer of the Property. Does not initialize the content.
|
||||
/// `out` is assumed to be uninitialized
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_init(out: *mut PropertyHandleOpaque) {
|
||||
unsafe { core::ptr::write(out, PropertyHandleOpaque(PropertyHandle::default())) };
|
||||
}
|
||||
|
||||
/// To be called before accessing the value
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_update(handle: &PropertyHandleOpaque, val: *mut c_void) {
|
||||
unsafe {
|
||||
let handle = Pin::new_unchecked(&handle.0);
|
||||
handle.update(val);
|
||||
handle.register_as_dependency_to_current_binding();
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark the fact that the property was changed and that its binding need to be removed, and
|
||||
/// the dependencies marked dirty.
|
||||
/// To be called after the `value` has been changed
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_set_changed(
|
||||
handle: &PropertyHandleOpaque,
|
||||
value: *const c_void,
|
||||
) {
|
||||
unsafe {
|
||||
if !handle.0.access(|b| {
|
||||
b.is_some_and(|b| (b.vtable.intercept_set)(&*b as *const BindingHolder, value))
|
||||
}) {
|
||||
handle.0.remove_binding();
|
||||
}
|
||||
handle.0.mark_dirty();
|
||||
}
|
||||
}
|
||||
|
||||
fn make_c_function_binding(
|
||||
binding: extern "C" fn(*mut c_void, *mut c_void),
|
||||
user_data: *mut c_void,
|
||||
drop_user_data: Option<extern "C" fn(*mut c_void)>,
|
||||
intercept_set: Option<
|
||||
extern "C" fn(user_data: *mut c_void, pointer_to_value: *const c_void) -> bool,
|
||||
>,
|
||||
intercept_set_binding: Option<
|
||||
extern "C" fn(user_data: *mut c_void, new_binding: *mut c_void) -> bool,
|
||||
>,
|
||||
) -> impl BindingCallable<c_void> {
|
||||
struct CFunctionBinding<T> {
|
||||
binding_function: extern "C" fn(*mut c_void, *mut T),
|
||||
user_data: *mut c_void,
|
||||
drop_user_data: Option<extern "C" fn(*mut c_void)>,
|
||||
intercept_set:
|
||||
Option<extern "C" fn(user_data: *mut c_void, pointer_to_value: *const T) -> bool>,
|
||||
intercept_set_binding:
|
||||
Option<extern "C" fn(user_data: *mut c_void, new_binding: *mut c_void) -> bool>,
|
||||
}
|
||||
|
||||
impl<T> Drop for CFunctionBinding<T> {
|
||||
fn drop(&mut self) {
|
||||
if let Some(x) = self.drop_user_data {
|
||||
x(self.user_data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl<T> BindingCallable<T> for CFunctionBinding<T> {
|
||||
fn evaluate(self: Pin<&Self>, value: &mut T) -> BindingResult {
|
||||
(self.binding_function)(self.user_data, value as *mut T);
|
||||
BindingResult::KeepBinding
|
||||
}
|
||||
fn intercept_set(self: Pin<&Self>, value: &T) -> bool {
|
||||
match self.intercept_set {
|
||||
None => false,
|
||||
Some(intercept_set) => intercept_set(self.user_data, value as *const T),
|
||||
}
|
||||
}
|
||||
unsafe fn intercept_set_binding(self: Pin<&Self>, new_binding: *mut BindingHolder) -> bool {
|
||||
match self.intercept_set_binding {
|
||||
None => false,
|
||||
Some(intercept_set_b) => intercept_set_b(self.user_data, new_binding.cast()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CFunctionBinding {
|
||||
binding_function: binding,
|
||||
user_data,
|
||||
drop_user_data,
|
||||
intercept_set,
|
||||
intercept_set_binding,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a binding
|
||||
///
|
||||
/// The current implementation will do usually two memory allocation:
|
||||
/// 1. the allocation from the calling code to allocate user_data
|
||||
/// 2. the box allocation within this binding
|
||||
///
|
||||
/// It might be possible to reduce that by passing something with a
|
||||
/// vtable, so there is the need for less memory allocation.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_set_binding(
|
||||
handle: &PropertyHandleOpaque,
|
||||
binding: extern "C" fn(user_data: *mut c_void, pointer_to_value: *mut c_void),
|
||||
user_data: *mut c_void,
|
||||
drop_user_data: Option<extern "C" fn(*mut c_void)>,
|
||||
intercept_set: Option<
|
||||
extern "C" fn(user_data: *mut c_void, pointer_to_value: *const c_void) -> bool,
|
||||
>,
|
||||
intercept_set_binding: Option<
|
||||
extern "C" fn(user_data: *mut c_void, new_binding: *mut c_void) -> bool,
|
||||
>,
|
||||
) {
|
||||
let binding = make_c_function_binding(
|
||||
binding,
|
||||
user_data,
|
||||
drop_user_data,
|
||||
intercept_set,
|
||||
intercept_set_binding,
|
||||
);
|
||||
unsafe { handle.0.set_binding(binding) };
|
||||
}
|
||||
|
||||
/// Set a binding using an already allocated building holder
|
||||
///
|
||||
/// (take ownership of the binding)
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_set_binding_internal(
|
||||
handle: &PropertyHandleOpaque,
|
||||
binding: *mut c_void,
|
||||
) {
|
||||
handle.0.set_binding_impl(binding.cast());
|
||||
}
|
||||
|
||||
/// Delete a binding. The pointer must be a pointer to a binding (so a BindingHolder)
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_delete_binding(binding: *mut c_void) {
|
||||
let b = binding as *mut BindingHolder;
|
||||
unsafe { ((*b).vtable.drop)(b) };
|
||||
}
|
||||
|
||||
/// Evaluate a raw binding
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_evaluate_binding(binding: *mut c_void, value: *mut c_void) {
|
||||
let b = binding as *mut BindingHolder;
|
||||
unsafe { ((*b).vtable.evaluate)(b, value) };
|
||||
}
|
||||
|
||||
/// Returns whether the property behind this handle is marked as dirty
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn slint_property_is_dirty(handle: &PropertyHandleOpaque) -> bool {
|
||||
handle.0.access(|binding| binding.is_some_and(|b| b.dirty.get()))
|
||||
}
|
||||
|
||||
/// Marks the property as dirty and notifies dependencies.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn slint_property_mark_dirty(handle: &PropertyHandleOpaque) {
|
||||
handle.0.mark_dirty()
|
||||
}
|
||||
|
||||
/// Marks the property as dirty and notifies dependencies.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn slint_property_set_constant(handle: &PropertyHandleOpaque) {
|
||||
handle.0.set_constant()
|
||||
}
|
||||
|
||||
/// Destroy handle
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_drop(handle: *mut PropertyHandleOpaque) {
|
||||
unsafe {
|
||||
core::ptr::drop_in_place(handle);
|
||||
}
|
||||
}
|
||||
|
||||
fn c_set_animated_value<T: InterpolatedPropertyValue + Clone>(
|
||||
handle: &PropertyHandleOpaque,
|
||||
from: T,
|
||||
to: T,
|
||||
animation_data: &PropertyAnimation,
|
||||
) {
|
||||
let d = RefCell::new(properties_animations::PropertyValueAnimationData::new(
|
||||
from,
|
||||
to,
|
||||
animation_data.clone(),
|
||||
));
|
||||
// Safety: The BindingCallable is for type T
|
||||
unsafe {
|
||||
handle.0.set_binding(move |val: &mut T| {
|
||||
let (value, finished) = d.borrow_mut().compute_interpolated_value();
|
||||
*val = value;
|
||||
if finished {
|
||||
BindingResult::RemoveBinding
|
||||
} else {
|
||||
crate::animations::CURRENT_ANIMATION_DRIVER
|
||||
.with(|driver| driver.set_has_active_animations());
|
||||
BindingResult::KeepBinding
|
||||
}
|
||||
})
|
||||
};
|
||||
handle.0.mark_dirty();
|
||||
}
|
||||
|
||||
/// Internal function to set up a property animation to the specified target value for an integer property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_set_animated_value_int(
|
||||
handle: &PropertyHandleOpaque,
|
||||
from: i32,
|
||||
to: i32,
|
||||
animation_data: &PropertyAnimation,
|
||||
) {
|
||||
c_set_animated_value(handle, from, to, animation_data)
|
||||
}
|
||||
|
||||
/// Internal function to set up a property animation to the specified target value for a float property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_set_animated_value_float(
|
||||
handle: &PropertyHandleOpaque,
|
||||
from: f32,
|
||||
to: f32,
|
||||
animation_data: &PropertyAnimation,
|
||||
) {
|
||||
c_set_animated_value(handle, from, to, animation_data)
|
||||
}
|
||||
|
||||
/// Internal function to set up a property animation to the specified target value for a color property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_set_animated_value_color(
|
||||
handle: &PropertyHandleOpaque,
|
||||
from: Color,
|
||||
to: Color,
|
||||
animation_data: &PropertyAnimation,
|
||||
) {
|
||||
c_set_animated_value(handle, from, to, animation_data);
|
||||
}
|
||||
|
||||
/// Internal function to set up a property animation to the specified target value for a brush property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_set_animated_value_brush(
|
||||
handle: &PropertyHandleOpaque,
|
||||
from: &Brush,
|
||||
to: &Brush,
|
||||
animation_data: &PropertyAnimation,
|
||||
) {
|
||||
c_set_animated_value(handle, from.clone(), to.clone(), animation_data);
|
||||
}
|
||||
|
||||
unsafe fn c_set_animated_binding<T: InterpolatedPropertyValue + Clone>(
|
||||
handle: &PropertyHandleOpaque,
|
||||
binding: extern "C" fn(*mut c_void, *mut T),
|
||||
user_data: *mut c_void,
|
||||
drop_user_data: Option<extern "C" fn(*mut c_void)>,
|
||||
transition_data: extern "C" fn(
|
||||
user_data: *mut c_void,
|
||||
start_instant: &mut *mut u64,
|
||||
) -> PropertyAnimation,
|
||||
) {
|
||||
unsafe {
|
||||
let binding = core::mem::transmute::<
|
||||
extern "C" fn(*mut c_void, *mut T),
|
||||
extern "C" fn(*mut c_void, *mut ()),
|
||||
>(binding);
|
||||
let original_binding = PropertyHandle {
|
||||
handle: Cell::new(
|
||||
(alloc_binding_holder(make_c_function_binding(
|
||||
binding,
|
||||
user_data,
|
||||
drop_user_data,
|
||||
None,
|
||||
None,
|
||||
)) as usize)
|
||||
| 0b10,
|
||||
),
|
||||
};
|
||||
let animation_data = RefCell::new(properties_animations::PropertyValueAnimationData::new(
|
||||
T::default(),
|
||||
T::default(),
|
||||
PropertyAnimation::default(),
|
||||
));
|
||||
|
||||
handle.0.set_binding(properties_animations::AnimatedBindingCallable::<T, _> {
|
||||
original_binding,
|
||||
state: Cell::new(properties_animations::AnimatedBindingState::NotAnimating),
|
||||
animation_data,
|
||||
compute_animation_details: move || -> properties_animations::AnimationDetail {
|
||||
// The transition_data function receives a *mut *mut u64 pointer for the
|
||||
// timestamp.
|
||||
// If the function sets the pointer to nullptr, it doesn't provide a start_time.
|
||||
// Otherwise, we assume it has written a value to the start_instant.
|
||||
// This basically models a `&mut Option<u64>`, which is then converted to an
|
||||
// `Option<Instant>`
|
||||
let mut start_instant = 0u64;
|
||||
let mut start_instant_ref = &mut start_instant as *mut u64;
|
||||
let anim = transition_data(user_data, &mut start_instant_ref);
|
||||
let start_instant = if start_instant_ref.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(crate::animations::Instant(start_instant))
|
||||
};
|
||||
(anim, start_instant)
|
||||
},
|
||||
});
|
||||
handle.0.mark_dirty();
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal function to set up a property animation between values produced by the specified binding for an integer property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_set_animated_binding_int(
|
||||
handle: &PropertyHandleOpaque,
|
||||
binding: extern "C" fn(*mut c_void, *mut core::ffi::c_int),
|
||||
user_data: *mut c_void,
|
||||
drop_user_data: Option<extern "C" fn(*mut c_void)>,
|
||||
transition_data: extern "C" fn(
|
||||
user_data: *mut c_void,
|
||||
start_instant: &mut *mut u64,
|
||||
) -> PropertyAnimation,
|
||||
) {
|
||||
unsafe {
|
||||
c_set_animated_binding(handle, binding, user_data, drop_user_data, transition_data);
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal function to set up a property animation between values produced by the specified binding for a float property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_set_animated_binding_float(
|
||||
handle: &PropertyHandleOpaque,
|
||||
binding: extern "C" fn(*mut c_void, *mut f32),
|
||||
user_data: *mut c_void,
|
||||
drop_user_data: Option<extern "C" fn(*mut c_void)>,
|
||||
transition_data: extern "C" fn(
|
||||
user_data: *mut c_void,
|
||||
start_instant: &mut *mut u64,
|
||||
) -> PropertyAnimation,
|
||||
) {
|
||||
unsafe {
|
||||
c_set_animated_binding(handle, binding, user_data, drop_user_data, transition_data);
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal function to set up a property animation between values produced by the specified binding for a color property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_set_animated_binding_color(
|
||||
handle: &PropertyHandleOpaque,
|
||||
binding: extern "C" fn(*mut c_void, *mut Color),
|
||||
user_data: *mut c_void,
|
||||
drop_user_data: Option<extern "C" fn(*mut c_void)>,
|
||||
transition_data: extern "C" fn(
|
||||
user_data: *mut c_void,
|
||||
start_instant: &mut *mut u64,
|
||||
) -> PropertyAnimation,
|
||||
) {
|
||||
unsafe {
|
||||
c_set_animated_binding(handle, binding, user_data, drop_user_data, transition_data);
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal function to set up a property animation between values produced by the specified binding for a brush property.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_set_animated_binding_brush(
|
||||
handle: &PropertyHandleOpaque,
|
||||
binding: extern "C" fn(*mut c_void, *mut Brush),
|
||||
user_data: *mut c_void,
|
||||
drop_user_data: Option<extern "C" fn(*mut c_void)>,
|
||||
transition_data: extern "C" fn(
|
||||
user_data: *mut c_void,
|
||||
start_instant: &mut *mut u64,
|
||||
) -> PropertyAnimation,
|
||||
) {
|
||||
unsafe {
|
||||
c_set_animated_binding(handle, binding, user_data, drop_user_data, transition_data);
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal function to set up a state binding on a Property<StateInfo>.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_set_state_binding(
|
||||
handle: &PropertyHandleOpaque,
|
||||
binding: extern "C" fn(*mut c_void) -> i32,
|
||||
user_data: *mut c_void,
|
||||
drop_user_data: Option<extern "C" fn(*mut c_void)>,
|
||||
) {
|
||||
struct CStateBinding {
|
||||
binding: extern "C" fn(*mut c_void) -> i32,
|
||||
user_data: *mut c_void,
|
||||
drop_user_data: Option<extern "C" fn(*mut c_void)>,
|
||||
}
|
||||
|
||||
impl Drop for CStateBinding {
|
||||
fn drop(&mut self) {
|
||||
if let Some(x) = self.drop_user_data {
|
||||
x(self.user_data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CStateBinding {
|
||||
fn call(&self) -> i32 {
|
||||
(self.binding)(self.user_data)
|
||||
}
|
||||
}
|
||||
|
||||
let c_state_binding = CStateBinding { binding, user_data, drop_user_data };
|
||||
let bind_callable =
|
||||
StateInfoBinding { dirty_time: Cell::new(None), binding: move || c_state_binding.call() };
|
||||
unsafe { handle.0.set_binding(bind_callable) }
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
/// Opaque type representing the PropertyTracker
|
||||
pub struct PropertyTrackerOpaque {
|
||||
dependencies: usize,
|
||||
dep_nodes: usize,
|
||||
vtable: usize,
|
||||
dirty: bool,
|
||||
}
|
||||
|
||||
static_assertions::assert_eq_align!(PropertyTrackerOpaque, PropertyTracker);
|
||||
static_assertions::assert_eq_size!(PropertyTrackerOpaque, PropertyTracker);
|
||||
|
||||
/// Initialize the first pointer of the PropertyTracker.
|
||||
/// `out` is assumed to be uninitialized
|
||||
/// slint_property_tracker_drop need to be called after that
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_tracker_init(out: *mut PropertyTrackerOpaque) {
|
||||
unsafe {
|
||||
core::ptr::write(out as *mut PropertyTracker, PropertyTracker::default());
|
||||
}
|
||||
}
|
||||
|
||||
/// Call the callback with the user data. Any properties access within the callback will be registered.
|
||||
/// Any currently evaluated bindings or property trackers will be notified if accessed properties are changed.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_tracker_evaluate(
|
||||
handle: *const PropertyTrackerOpaque,
|
||||
callback: extern "C" fn(user_data: *mut c_void),
|
||||
user_data: *mut c_void,
|
||||
) {
|
||||
unsafe { Pin::new_unchecked(&*(handle as *const PropertyTracker)) }
|
||||
.evaluate(|| callback(user_data))
|
||||
}
|
||||
|
||||
/// Call the callback with the user data. Any properties access within the callback will be registered.
|
||||
/// Any currently evaluated bindings or property trackers will be not notified if accessed properties are changed.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_tracker_evaluate_as_dependency_root(
|
||||
handle: *const PropertyTrackerOpaque,
|
||||
callback: extern "C" fn(user_data: *mut c_void),
|
||||
user_data: *mut c_void,
|
||||
) {
|
||||
unsafe { Pin::new_unchecked(&*(handle as *const PropertyTracker)) }
|
||||
.evaluate_as_dependency_root(|| callback(user_data))
|
||||
}
|
||||
/// Query if the property tracker is dirty
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_tracker_is_dirty(
|
||||
handle: *const PropertyTrackerOpaque,
|
||||
) -> bool {
|
||||
unsafe { (*(handle as *const PropertyTracker)).is_dirty() }
|
||||
}
|
||||
|
||||
/// Destroy handle
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_property_tracker_drop(handle: *mut PropertyTrackerOpaque) {
|
||||
unsafe { core::ptr::drop_in_place(handle as *mut PropertyTracker) };
|
||||
}
|
||||
|
||||
/// Construct a ChangeTracker
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_change_tracker_construct(ct: *mut ChangeTracker) {
|
||||
unsafe { core::ptr::write(ct, ChangeTracker::default()) };
|
||||
}
|
||||
|
||||
/// Drop a ChangeTracker
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_change_tracker_drop(ct: *mut ChangeTracker) {
|
||||
unsafe { core::ptr::drop_in_place(ct) };
|
||||
}
|
||||
|
||||
/// initialize the change tracker
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn slint_change_tracker_init(
|
||||
ct: &ChangeTracker,
|
||||
user_data: *mut c_void,
|
||||
drop_user_data: extern "C" fn(user_data: *mut c_void),
|
||||
eval_fn: extern "C" fn(user_data: *mut c_void) -> bool,
|
||||
notify_fn: extern "C" fn(user_data: *mut c_void),
|
||||
) {
|
||||
#[allow(non_camel_case_types)]
|
||||
struct C_ChangeTrackerInner {
|
||||
user_data: *mut c_void,
|
||||
drop_user_data: extern "C" fn(user_data: *mut c_void),
|
||||
eval_fn: extern "C" fn(user_data: *mut c_void) -> bool,
|
||||
notify_fn: extern "C" fn(user_data: *mut c_void),
|
||||
}
|
||||
impl Drop for C_ChangeTrackerInner {
|
||||
fn drop(&mut self) {
|
||||
(self.drop_user_data)(self.user_data);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn drop(_self: *mut BindingHolder) {
|
||||
core::mem::drop(unsafe {
|
||||
Box::from_raw(_self as *mut BindingHolder<C_ChangeTrackerInner>)
|
||||
});
|
||||
}
|
||||
|
||||
unsafe fn evaluate(_self: *const BindingHolder, _value: *mut ()) -> BindingResult {
|
||||
let pinned_holder = unsafe { Pin::new_unchecked(&*_self) };
|
||||
let _self = _self as *mut BindingHolder<C_ChangeTrackerInner>;
|
||||
let inner = unsafe { core::ptr::addr_of_mut!((*_self).binding).as_mut().unwrap() };
|
||||
let notify =
|
||||
super::CURRENT_BINDING.set(Some(pinned_holder), || (inner.eval_fn)(inner.user_data));
|
||||
if notify {
|
||||
(inner.notify_fn)(inner.user_data);
|
||||
}
|
||||
BindingResult::KeepBinding
|
||||
}
|
||||
|
||||
const VT: &BindingVTable = &BindingVTable {
|
||||
drop,
|
||||
evaluate,
|
||||
mark_dirty: ChangeTracker::mark_dirty,
|
||||
intercept_set: |_, _| false,
|
||||
intercept_set_binding: |_, _| false,
|
||||
};
|
||||
|
||||
ct.clear();
|
||||
|
||||
let inner = C_ChangeTrackerInner { user_data, drop_user_data, eval_fn, notify_fn };
|
||||
|
||||
let holder = BindingHolder {
|
||||
dependencies: Cell::new(0),
|
||||
dep_nodes: Default::default(),
|
||||
vtable: VT,
|
||||
dirty: Cell::new(false),
|
||||
is_two_way_binding: false,
|
||||
pinned: PhantomPinned,
|
||||
binding: inner,
|
||||
#[cfg(slint_debug_property)]
|
||||
debug_name: "<ChangeTracker>".into(),
|
||||
};
|
||||
|
||||
let raw = Box::into_raw(Box::new(holder));
|
||||
unsafe { ct.set_internal(raw as *mut BindingHolder) };
|
||||
|
||||
let pinned_holder = unsafe { Pin::new_unchecked(&*(raw as *mut BindingHolder)) };
|
||||
let inner = unsafe { core::ptr::addr_of_mut!((*raw).binding).as_mut().unwrap() };
|
||||
super::CURRENT_BINDING.set(Some(pinned_holder), || (inner.eval_fn)(inner.user_data));
|
||||
}
|
||||
|
||||
/// return the current animation tick for the `animation-tick` function
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn slint_animation_tick() -> u64 {
|
||||
crate::animations::animation_tick()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,614 @@
|
||||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use super::*;
|
||||
use alloc::rc::Rc;
|
||||
use core::cell::Cell;
|
||||
use core::cell::UnsafeCell;
|
||||
use core::marker::PhantomData;
|
||||
use core::marker::PhantomPinned;
|
||||
use core::pin::Pin;
|
||||
|
||||
struct TwoWayBinding<T> {
|
||||
common_property: Pin<Rc<Property<T>>>,
|
||||
}
|
||||
unsafe impl<T: PartialEq + Clone + 'static> BindingCallable<T> for TwoWayBinding<T> {
|
||||
fn evaluate(self: Pin<&Self>, value: &mut T) -> BindingResult {
|
||||
*value = self.common_property.as_ref().get();
|
||||
BindingResult::KeepBinding
|
||||
}
|
||||
|
||||
fn intercept_set(self: Pin<&Self>, value: &T) -> bool {
|
||||
self.common_property.as_ref().set(value.clone());
|
||||
true
|
||||
}
|
||||
|
||||
unsafe fn intercept_set_binding(self: Pin<&Self>, new_binding: *mut BindingHolder) -> bool {
|
||||
self.common_property.handle.set_binding_impl(new_binding);
|
||||
true
|
||||
}
|
||||
|
||||
const IS_TWO_WAY_BINDING: bool = true;
|
||||
}
|
||||
|
||||
impl<T: PartialEq + Clone + 'static> Property<T> {
|
||||
/// If the property is a two way binding, return the common property
|
||||
pub(crate) fn check_common_property(self: Pin<&Self>) -> Option<Pin<Rc<Property<T>>>> {
|
||||
let handle_val = self.handle.handle.get();
|
||||
if let Some(holder) = PropertyHandle::pointer_to_binding(handle_val) {
|
||||
// Safety: the handle is a pointer to a binding
|
||||
if unsafe { (*holder).is_two_way_binding } {
|
||||
// Safety: the handle is a pointer to a binding whose B is a TwoWayBinding<T>
|
||||
return Some(unsafe {
|
||||
(*(holder as *const BindingHolder<TwoWayBinding<T>>))
|
||||
.binding
|
||||
.common_property
|
||||
.clone()
|
||||
});
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Link two property such that any change to one property is affecting the other property as if they
|
||||
/// where, in fact, a single property.
|
||||
/// The value or binding of prop2 is kept.
|
||||
pub fn link_two_way(prop1: Pin<&Self>, prop2: Pin<&Self>) {
|
||||
#[cfg(slint_debug_property)]
|
||||
let debug_name =
|
||||
alloc::format!("<{}<=>{}>", prop1.debug_name.borrow(), prop2.debug_name.borrow());
|
||||
|
||||
let value = prop2.get_untracked();
|
||||
|
||||
if let Some(common_property) = prop1.check_common_property() {
|
||||
// Safety: TwoWayBinding is a BindingCallable for type T
|
||||
unsafe {
|
||||
prop2.handle.set_binding(
|
||||
TwoWayBinding::<T> { common_property },
|
||||
#[cfg(slint_debug_property)]
|
||||
debug_name.as_str(),
|
||||
);
|
||||
}
|
||||
prop2.set(value);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(common_property) = prop2.check_common_property() {
|
||||
// Safety: TwoWayBinding is a BindingCallable for type T
|
||||
unsafe {
|
||||
prop1.handle.set_binding(
|
||||
TwoWayBinding::<T> { common_property },
|
||||
#[cfg(slint_debug_property)]
|
||||
debug_name.as_str(),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let prop2_handle_val = prop2.handle.handle.get();
|
||||
let handle = if PropertyHandle::is_pointer_to_binding(prop2_handle_val) {
|
||||
// If prop2 is a binding, just "steal it"
|
||||
prop2.handle.handle.set(0);
|
||||
PropertyHandle { handle: Cell::new(prop2_handle_val) }
|
||||
} else {
|
||||
PropertyHandle::default()
|
||||
};
|
||||
|
||||
let common_property = Rc::pin(Property {
|
||||
handle,
|
||||
value: UnsafeCell::new(value),
|
||||
pinned: PhantomPinned,
|
||||
#[cfg(slint_debug_property)]
|
||||
debug_name: debug_name.clone().into(),
|
||||
});
|
||||
// Safety: TwoWayBinding's T is the same as the type for both properties
|
||||
unsafe {
|
||||
prop1.handle.set_binding(
|
||||
TwoWayBinding { common_property: common_property.clone() },
|
||||
#[cfg(slint_debug_property)]
|
||||
debug_name.as_str(),
|
||||
);
|
||||
prop2.handle.set_binding(
|
||||
TwoWayBinding { common_property },
|
||||
#[cfg(slint_debug_property)]
|
||||
debug_name.as_str(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Link a property to another property of a different type, with mapping function to go between them.
|
||||
///
|
||||
/// the value of the `prop1` (of type `T`) is kept. (This is the opposite of [`Self::link_two_way`])
|
||||
/// `T2` must be able to be derived from `T` using the `map_to` function.
|
||||
/// `T` may contain more information than `T2` and the value of prop1 will be updated with the `map_from` function when `prop2` changes
|
||||
pub fn link_two_way_with_map<T2: PartialEq + Clone + 'static>(
|
||||
prop1: Pin<&Self>,
|
||||
prop2: Pin<&Property<T2>>,
|
||||
map_to: impl Fn(&T) -> T2 + Clone + 'static, // Rename map_to_t2
|
||||
map_from: impl Fn(&mut T, &T2) + Clone + 'static,
|
||||
) {
|
||||
let common_property = if let Some(common_property) = prop1.check_common_property() {
|
||||
common_property
|
||||
} else {
|
||||
let prop1_handle_val = prop1.handle.handle.get();
|
||||
let handle = if PropertyHandle::is_pointer_to_binding(prop1_handle_val) {
|
||||
// If prop1 is a binding, just "steal it"
|
||||
prop1.handle.handle.set(0);
|
||||
PropertyHandle { handle: Cell::new(prop1_handle_val) }
|
||||
} else {
|
||||
PropertyHandle::default()
|
||||
};
|
||||
|
||||
#[cfg(slint_debug_property)]
|
||||
let debug_name = alloc::format!("{}*", prop1.debug_name.borrow());
|
||||
|
||||
let common_property = Rc::pin(Property {
|
||||
handle,
|
||||
value: UnsafeCell::new(prop1.get_internal()),
|
||||
pinned: PhantomPinned,
|
||||
#[cfg(slint_debug_property)]
|
||||
debug_name: debug_name.clone().into(),
|
||||
});
|
||||
// Safety: TwoWayBinding's T is the same as the type for both properties
|
||||
unsafe {
|
||||
prop1.handle.set_binding(
|
||||
TwoWayBinding::<T> { common_property: common_property.clone() },
|
||||
#[cfg(slint_debug_property)]
|
||||
debug_name.as_str(),
|
||||
);
|
||||
}
|
||||
common_property
|
||||
};
|
||||
Self::link_two_way_with_map_to_common_property(common_property, prop2, map_to, map_from);
|
||||
}
|
||||
|
||||
/// Make a two way binding between the common property and the binding prop2.
|
||||
/// if prop2 has a binding, it will be preserved
|
||||
pub(crate) fn link_two_way_with_map_to_common_property<T2: PartialEq + Clone + 'static>(
|
||||
common_property: Pin<Rc<Self>>,
|
||||
prop2: Pin<&Property<T2>>,
|
||||
map_to: impl Fn(&T) -> T2 + Clone + 'static,
|
||||
map_from: impl Fn(&mut T, &T2) + Clone + 'static,
|
||||
) {
|
||||
struct TwoWayBindingWithMap<T, T2, M1, M2> {
|
||||
common_property: Pin<Rc<Property<T>>>,
|
||||
map_to: M1,
|
||||
map_from: M2,
|
||||
marker: PhantomData<(T, T2)>,
|
||||
}
|
||||
unsafe impl<
|
||||
T: PartialEq + Clone + 'static,
|
||||
T2: PartialEq + Clone + 'static,
|
||||
M1: Fn(&T) -> T2 + Clone + 'static,
|
||||
M2: Fn(&mut T, &T2) + Clone + 'static,
|
||||
> BindingCallable<T2> for TwoWayBindingWithMap<T, T2, M1, M2>
|
||||
{
|
||||
fn evaluate(self: Pin<&Self>, value: &mut T2) -> BindingResult {
|
||||
*value = (self.map_to)(&self.common_property.as_ref().get());
|
||||
BindingResult::KeepBinding
|
||||
}
|
||||
|
||||
fn intercept_set(self: Pin<&Self>, value: &T2) -> bool {
|
||||
let mut old = self.common_property.as_ref().get();
|
||||
(self.map_from)(&mut old, value);
|
||||
self.common_property.as_ref().set(old);
|
||||
true
|
||||
}
|
||||
|
||||
unsafe fn intercept_set_binding(
|
||||
self: Pin<&Self>,
|
||||
new_binding: *mut BindingHolder,
|
||||
) -> bool {
|
||||
let new_new_binding = alloc_binding_holder(BindingMapper::<T, T2, M1, M2> {
|
||||
b: new_binding,
|
||||
map_to: self.map_to.clone(),
|
||||
map_from: self.map_from.clone(),
|
||||
marker: PhantomData,
|
||||
});
|
||||
self.common_property.handle.set_binding_impl(new_new_binding);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Given a binding for T2, maps to a binding for T
|
||||
struct BindingMapper<T, T2, M1, M2> {
|
||||
/// Binding that returns a `T2`
|
||||
b: *mut BindingHolder,
|
||||
map_to: M1,
|
||||
map_from: M2,
|
||||
marker: PhantomData<(T, T2)>,
|
||||
}
|
||||
unsafe impl<
|
||||
T: PartialEq + Clone + 'static,
|
||||
T2: PartialEq + Clone + 'static,
|
||||
M1: Fn(&T) -> T2 + 'static,
|
||||
M2: Fn(&mut T, &T2) + 'static,
|
||||
> BindingCallable<T> for BindingMapper<T, T2, M1, M2>
|
||||
{
|
||||
fn evaluate(self: Pin<&Self>, value: &mut T) -> BindingResult {
|
||||
let mut sub_value = (self.map_to)(value);
|
||||
// Safety: `self.b` is a BindingHolder that expects a `T2`
|
||||
unsafe {
|
||||
((*self.b).vtable.evaluate)(self.b, &mut sub_value as *mut T2 as *mut ());
|
||||
}
|
||||
(self.map_from)(value, &sub_value);
|
||||
BindingResult::KeepBinding
|
||||
}
|
||||
|
||||
fn intercept_set(self: Pin<&Self>, value: &T) -> bool {
|
||||
let sub_value = (self.map_to)(value);
|
||||
// Safety: `self.b` is a BindingHolder that expects a `T2`
|
||||
unsafe {
|
||||
((*self.b).vtable.intercept_set)(self.b, &sub_value as *const T2 as *const ())
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<T, T2, M1, M2> Drop for BindingMapper<T, T2, M1, M2> {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
((*self.b).vtable.drop)(self.b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(slint_debug_property)]
|
||||
let debug_name = alloc::format!(
|
||||
"<{}<=>{}>",
|
||||
common_property.debug_name.borrow(),
|
||||
prop2.debug_name.borrow()
|
||||
);
|
||||
|
||||
// Detach the old binding (if any) from prop2, transferring its
|
||||
// dependency list back to the handle so that set_binding() will
|
||||
// properly move it into the new TwoWayBindingWithMap binding.
|
||||
// Without this, the old binding's dependency list would be orphaned
|
||||
// when it is later freed via BindingMapper::drop, leaving
|
||||
// DependencyNodes with dangling prev pointers.
|
||||
let old_binding = prop2.handle.detach_binding();
|
||||
|
||||
unsafe {
|
||||
prop2.handle.set_binding(
|
||||
TwoWayBindingWithMap { common_property, map_to, map_from, marker: PhantomData },
|
||||
#[cfg(slint_debug_property)]
|
||||
debug_name.as_str(),
|
||||
);
|
||||
|
||||
if let Some(binding) = old_binding {
|
||||
prop2.handle.set_binding_impl(binding);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn property_two_ways_test() {
|
||||
let p1 = Rc::pin(Property::new(42));
|
||||
let p2 = Rc::pin(Property::new(88));
|
||||
|
||||
let depends = Box::pin(Property::new(0));
|
||||
depends.as_ref().set_binding({
|
||||
let p1 = p1.clone();
|
||||
move || p1.as_ref().get() + 8
|
||||
});
|
||||
assert_eq!(depends.as_ref().get(), 42 + 8);
|
||||
Property::link_two_way(p1.as_ref(), p2.as_ref());
|
||||
assert_eq!(p1.as_ref().get(), 88);
|
||||
assert_eq!(p2.as_ref().get(), 88);
|
||||
assert_eq!(depends.as_ref().get(), 88 + 8);
|
||||
p2.as_ref().set(5);
|
||||
assert_eq!(p1.as_ref().get(), 5);
|
||||
assert_eq!(p2.as_ref().get(), 5);
|
||||
assert_eq!(depends.as_ref().get(), 5 + 8);
|
||||
p1.as_ref().set(22);
|
||||
assert_eq!(p1.as_ref().get(), 22);
|
||||
assert_eq!(p2.as_ref().get(), 22);
|
||||
assert_eq!(depends.as_ref().get(), 22 + 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn property_two_ways_test_binding() {
|
||||
let p1 = Rc::pin(Property::new(42));
|
||||
let p2 = Rc::pin(Property::new(88));
|
||||
let global = Rc::pin(Property::new(23));
|
||||
p2.as_ref().set_binding({
|
||||
let global = global.clone();
|
||||
move || global.as_ref().get() + 9
|
||||
});
|
||||
|
||||
let depends = Box::pin(Property::new(0));
|
||||
depends.as_ref().set_binding({
|
||||
let p1 = p1.clone();
|
||||
move || p1.as_ref().get() + 8
|
||||
});
|
||||
|
||||
Property::link_two_way(p1.as_ref(), p2.as_ref());
|
||||
assert_eq!(p1.as_ref().get(), 23 + 9);
|
||||
assert_eq!(p2.as_ref().get(), 23 + 9);
|
||||
assert_eq!(depends.as_ref().get(), 23 + 9 + 8);
|
||||
global.as_ref().set(55);
|
||||
assert_eq!(p1.as_ref().get(), 55 + 9);
|
||||
assert_eq!(p2.as_ref().get(), 55 + 9);
|
||||
assert_eq!(depends.as_ref().get(), 55 + 9 + 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn property_two_ways_recurse_from_binding() {
|
||||
let xx = Rc::pin(Property::new(0));
|
||||
|
||||
let p1 = Rc::pin(Property::new(42));
|
||||
let p2 = Rc::pin(Property::new(88));
|
||||
let global = Rc::pin(Property::new(23));
|
||||
|
||||
let done = Rc::new(Cell::new(false));
|
||||
xx.set_binding({
|
||||
let p1 = p1.clone();
|
||||
let p2 = p2.clone();
|
||||
let global = global.clone();
|
||||
let xx_weak = pin_weak::rc::PinWeak::downgrade(xx.clone());
|
||||
move || {
|
||||
if !done.get() {
|
||||
done.set(true);
|
||||
Property::link_two_way(p1.as_ref(), p2.as_ref());
|
||||
let xx_weak = xx_weak.clone();
|
||||
p1.as_ref().set_binding(move || xx_weak.upgrade().unwrap().as_ref().get() + 9);
|
||||
}
|
||||
global.as_ref().get() + 2
|
||||
}
|
||||
});
|
||||
assert_eq!(xx.as_ref().get(), 23 + 2);
|
||||
assert_eq!(p1.as_ref().get(), 23 + 2 + 9);
|
||||
assert_eq!(p2.as_ref().get(), 23 + 2 + 9);
|
||||
|
||||
global.as_ref().set(55);
|
||||
assert_eq!(p1.as_ref().get(), 55 + 2 + 9);
|
||||
assert_eq!(p2.as_ref().get(), 55 + 2 + 9);
|
||||
assert_eq!(xx.as_ref().get(), 55 + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn property_two_ways_binding_of_two_way_binding_first() {
|
||||
let p1_1 = Rc::pin(Property::new(2));
|
||||
let p1_2 = Rc::pin(Property::new(4));
|
||||
Property::link_two_way(p1_1.as_ref(), p1_2.as_ref());
|
||||
|
||||
assert_eq!(p1_1.as_ref().get(), 4);
|
||||
assert_eq!(p1_2.as_ref().get(), 4);
|
||||
|
||||
let p2 = Rc::pin(Property::new(3));
|
||||
Property::link_two_way(p1_1.as_ref(), p2.as_ref());
|
||||
|
||||
assert_eq!(p1_1.as_ref().get(), 3);
|
||||
assert_eq!(p1_2.as_ref().get(), 3);
|
||||
assert_eq!(p2.as_ref().get(), 3);
|
||||
|
||||
p1_1.set(6);
|
||||
|
||||
assert_eq!(p1_1.as_ref().get(), 6);
|
||||
assert_eq!(p1_2.as_ref().get(), 6);
|
||||
assert_eq!(p2.as_ref().get(), 6);
|
||||
|
||||
p1_2.set(8);
|
||||
|
||||
assert_eq!(p1_1.as_ref().get(), 8);
|
||||
assert_eq!(p1_2.as_ref().get(), 8);
|
||||
assert_eq!(p2.as_ref().get(), 8);
|
||||
|
||||
p2.set(7);
|
||||
|
||||
assert_eq!(p1_1.as_ref().get(), 7);
|
||||
assert_eq!(p1_2.as_ref().get(), 7);
|
||||
assert_eq!(p2.as_ref().get(), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn property_two_ways_binding_of_two_way_binding_second() {
|
||||
let p1 = Rc::pin(Property::new(2));
|
||||
let p2_1 = Rc::pin(Property::new(3));
|
||||
let p2_2 = Rc::pin(Property::new(5));
|
||||
Property::link_two_way(p2_1.as_ref(), p2_2.as_ref());
|
||||
|
||||
assert_eq!(p2_1.as_ref().get(), 5);
|
||||
assert_eq!(p2_2.as_ref().get(), 5);
|
||||
|
||||
Property::link_two_way(p1.as_ref(), p2_2.as_ref());
|
||||
|
||||
assert_eq!(p1.as_ref().get(), 5);
|
||||
assert_eq!(p2_1.as_ref().get(), 5);
|
||||
assert_eq!(p2_2.as_ref().get(), 5);
|
||||
|
||||
p1.set(6);
|
||||
|
||||
assert_eq!(p1.as_ref().get(), 6);
|
||||
assert_eq!(p2_1.as_ref().get(), 6);
|
||||
assert_eq!(p2_2.as_ref().get(), 6);
|
||||
|
||||
p2_1.set(7);
|
||||
|
||||
assert_eq!(p1.as_ref().get(), 7);
|
||||
assert_eq!(p2_1.as_ref().get(), 7);
|
||||
assert_eq!(p2_2.as_ref().get(), 7);
|
||||
|
||||
p2_2.set(9);
|
||||
|
||||
assert_eq!(p1.as_ref().get(), 9);
|
||||
assert_eq!(p2_1.as_ref().get(), 9);
|
||||
assert_eq!(p2_2.as_ref().get(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn property_two_ways_binding_of_two_two_way_bindings() {
|
||||
let p1_1 = Rc::pin(Property::new(2));
|
||||
let p1_2 = Rc::pin(Property::new(4));
|
||||
Property::link_two_way(p1_1.as_ref(), p1_2.as_ref());
|
||||
assert_eq!(p1_1.as_ref().get(), 4);
|
||||
assert_eq!(p1_2.as_ref().get(), 4);
|
||||
|
||||
let p2_1 = Rc::pin(Property::new(3));
|
||||
let p2_2 = Rc::pin(Property::new(5));
|
||||
Property::link_two_way(p2_1.as_ref(), p2_2.as_ref());
|
||||
|
||||
assert_eq!(p2_1.as_ref().get(), 5);
|
||||
assert_eq!(p2_2.as_ref().get(), 5);
|
||||
|
||||
Property::link_two_way(p1_1.as_ref(), p2_2.as_ref());
|
||||
|
||||
assert_eq!(p1_1.as_ref().get(), 5);
|
||||
assert_eq!(p1_2.as_ref().get(), 5);
|
||||
assert_eq!(p2_1.as_ref().get(), 5);
|
||||
assert_eq!(p2_2.as_ref().get(), 5);
|
||||
|
||||
p1_1.set(6);
|
||||
assert_eq!(p1_1.as_ref().get(), 6);
|
||||
assert_eq!(p1_2.as_ref().get(), 6);
|
||||
assert_eq!(p2_1.as_ref().get(), 6);
|
||||
assert_eq!(p2_2.as_ref().get(), 6);
|
||||
|
||||
p1_2.set(8);
|
||||
assert_eq!(p1_1.as_ref().get(), 8);
|
||||
assert_eq!(p1_2.as_ref().get(), 8);
|
||||
assert_eq!(p2_1.as_ref().get(), 8);
|
||||
assert_eq!(p2_2.as_ref().get(), 8);
|
||||
|
||||
p2_1.set(7);
|
||||
assert_eq!(p1_1.as_ref().get(), 7);
|
||||
assert_eq!(p1_2.as_ref().get(), 7);
|
||||
assert_eq!(p2_1.as_ref().get(), 7);
|
||||
assert_eq!(p2_2.as_ref().get(), 7);
|
||||
|
||||
p2_2.set(9);
|
||||
assert_eq!(p1_1.as_ref().get(), 9);
|
||||
assert_eq!(p1_2.as_ref().get(), 9);
|
||||
assert_eq!(p2_1.as_ref().get(), 9);
|
||||
assert_eq!(p2_2.as_ref().get(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_two_way_with_map() {
|
||||
#[derive(PartialEq, Clone, Default, Debug)]
|
||||
struct Struct {
|
||||
foo: i32,
|
||||
bar: alloc::string::String,
|
||||
}
|
||||
let p1 = Rc::pin(Property::new(Struct { foo: 42, bar: "hello".into() }));
|
||||
let p2 = Rc::pin(Property::new(88));
|
||||
let p3 = Rc::pin(Property::new(alloc::string::String::from("xyz")));
|
||||
Property::link_two_way_with_map(p1.as_ref(), p2.as_ref(), |s| s.foo, |s, foo| s.foo = *foo);
|
||||
assert_eq!(p1.as_ref().get(), Struct { foo: 42, bar: "hello".into() });
|
||||
assert_eq!(p2.as_ref().get(), 42);
|
||||
|
||||
p2.as_ref().set(81);
|
||||
assert_eq!(p1.as_ref().get(), Struct { foo: 81, bar: "hello".into() });
|
||||
assert_eq!(p2.as_ref().get(), 81);
|
||||
|
||||
p1.as_ref().set(Struct { foo: 78, bar: "world".into() });
|
||||
assert_eq!(p1.as_ref().get(), Struct { foo: 78, bar: "world".into() });
|
||||
assert_eq!(p2.as_ref().get(), 78);
|
||||
|
||||
Property::link_two_way_with_map(
|
||||
p1.as_ref(),
|
||||
p3.as_ref(),
|
||||
|s| s.bar.clone(),
|
||||
|s, bar| s.bar = bar.clone(),
|
||||
);
|
||||
assert_eq!(p1.as_ref().get(), Struct { foo: 78, bar: "world".into() });
|
||||
assert_eq!(p2.as_ref().get(), 78);
|
||||
assert_eq!(p3.as_ref().get(), "world");
|
||||
|
||||
p3.as_ref().set("abc".into());
|
||||
assert_eq!(p1.as_ref().get(), Struct { foo: 78, bar: "abc".into() });
|
||||
assert_eq!(p2.as_ref().get(), 78);
|
||||
assert_eq!(p3.as_ref().get(), "abc");
|
||||
|
||||
let p4 = Rc::pin(Property::new(123));
|
||||
p2.set_binding({
|
||||
let p4 = p4.clone();
|
||||
move || p4.as_ref().get() + 1
|
||||
});
|
||||
|
||||
assert_eq!(p1.as_ref().get(), Struct { foo: 124, bar: "abc".into() });
|
||||
assert_eq!(p2.as_ref().get(), 124);
|
||||
assert_eq!(p3.as_ref().get(), "abc");
|
||||
|
||||
p4.as_ref().set(456);
|
||||
assert_eq!(p1.as_ref().get(), Struct { foo: 457, bar: "abc".into() });
|
||||
assert_eq!(p2.as_ref().get(), 457);
|
||||
assert_eq!(p3.as_ref().get(), "abc");
|
||||
|
||||
p3.as_ref().set("def".into());
|
||||
assert_eq!(p1.as_ref().get(), Struct { foo: 457, bar: "def".into() });
|
||||
assert_eq!(p2.as_ref().get(), 457);
|
||||
assert_eq!(p3.as_ref().get(), "def");
|
||||
|
||||
p4.as_ref().set(789);
|
||||
// Note that the binding with `p2 : p4+1` is broken
|
||||
assert_eq!(p1.as_ref().get(), Struct { foo: 457, bar: "def".into() });
|
||||
assert_eq!(p2.as_ref().get(), 457);
|
||||
assert_eq!(p3.as_ref().get(), "def");
|
||||
}
|
||||
|
||||
/// Regression test for use-after-free in `link_two_way_with_map_to_common_property`.
|
||||
///
|
||||
/// When a property already has a binding with dependants and is then linked
|
||||
/// via `link_two_way_with_map`, the old binding's dependency list must be
|
||||
/// transferred to the new `TwoWayBindingWithMap` binding. Without this
|
||||
/// transfer, the old binding is later freed (via `BindingMapper::drop`) while
|
||||
/// dependency nodes still point into its `dependencies` field, causing
|
||||
/// panics in `DependencyNode::debug_assert_valid` on drop.
|
||||
///
|
||||
/// The drop order is arranged so that the tracker (which owns the
|
||||
/// dependency node) outlives the properties, forcing the node to be
|
||||
/// removed after the old binding would have been freed.
|
||||
#[test]
|
||||
fn test_two_way_with_map_dependency_list_transfer() {
|
||||
#[derive(PartialEq, Clone, Default, Debug)]
|
||||
struct Wrapper {
|
||||
value: i32,
|
||||
}
|
||||
|
||||
let source = Rc::pin(Property::new(10));
|
||||
|
||||
// Declare the tracker before the properties so it is dropped *after*
|
||||
// them (Rust drops locals in reverse declaration order). This ensures
|
||||
// the dependency node outlives the old binding.
|
||||
let tracker = Box::pin(<PropertyTracker>::default());
|
||||
|
||||
let p_field = Rc::pin(Property::new(0i32));
|
||||
p_field.as_ref().set_binding({
|
||||
let source = source.clone();
|
||||
move || source.as_ref().get() * 2
|
||||
});
|
||||
assert_eq!(p_field.as_ref().get(), 20);
|
||||
|
||||
// Evaluate the tracker, which reads p_field and registers a dependency
|
||||
// node on p_field's binding's dependency list.
|
||||
let val = tracker.as_ref().evaluate({
|
||||
let p_field = p_field.clone();
|
||||
move || p_field.as_ref().get()
|
||||
});
|
||||
assert_eq!(val, 20);
|
||||
assert!(!tracker.as_ref().is_dirty());
|
||||
|
||||
// link_two_way_with_map replaces p_field's binding with a
|
||||
// TwoWayBindingWithMap and wraps the old binding in a BindingMapper
|
||||
// on the common property. The dependency list must be transferred.
|
||||
let p_struct = Rc::pin(Property::new(Wrapper { value: 0 }));
|
||||
Property::link_two_way_with_map(
|
||||
p_struct.as_ref(),
|
||||
p_field.as_ref(),
|
||||
|s| s.value,
|
||||
|s, v| s.value = *v,
|
||||
);
|
||||
|
||||
assert_eq!(p_field.as_ref().get(), 20);
|
||||
assert_eq!(p_struct.as_ref().get(), Wrapper { value: 20 });
|
||||
|
||||
// The tracker's dependency should still fire when the source changes.
|
||||
source.as_ref().set(5);
|
||||
assert!(tracker.as_ref().is_dirty());
|
||||
|
||||
// Implicit drop order: p_struct, p_field, tracker, source.
|
||||
// p_field's drop frees the common property chain (including the old
|
||||
// binding via BindingMapper::drop). tracker is dropped afterwards —
|
||||
// its DependencyNode::remove would panic in debug_assert_valid if
|
||||
// the dependency list was not properly transferred.
|
||||
}
|
||||
Reference in new issue
Block a user