Skip to main content

qtbridge_runtime/
qqmllistproperty.rs

1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only
3
4use std::rc::Rc;
5use std::cell::RefCell;
6
7use crate::QObjectHolder;
8use crate::qproxies::QRustProxy;
9use crate::rustobjectgetter::get_rust_proxy;
10use qtbridge_type_lib::QObject;
11
12#[cxx::bridge]
13mod ffi {
14    unsafe extern "C++" {
15        include!("qtbridge-type-lib/src/core/qmetatype/cpp/qmetatype.h");
16        type QMetaType = qtbridge_type_lib::QMetaType;
17        include!("qtbridge-type-lib/src/core/qmetatypeinterface/cpp/qmetatypeinterface.h");
18        #[namespace = "QtPrivate"]
19        type QMetaTypeInterface = qtbridge_type_lib::QMetaTypeInterface;
20        include!("qtbridge-type-lib/src/core/qobject/cpp/qobject.h");
21        type QObject = qtbridge_type_lib::QObject;
22        include!("qtbridge-type-lib/src/core/qvariant/cpp/qvariant.h");
23        type QVariant = qtbridge_type_lib::QVariant;
24    }
25
26    #[namespace = "rust::bridge::qqmllistproperty"]
27    unsafe extern "C++" {
28        include!("cpp/qqmllistproperty.h");
29
30        /// Build a `QVariant` holding a `QQmlListProperty<QObject>` stamped with the per-type list metatype.
31        #[rust_name = "list_property_to_qvariant"]
32        unsafe fn listPropertyToQVariant(
33            meta_type: &QMetaType,
34            object: *mut QObject,
35            data: *mut u8,
36            append_fn: usize,
37            count_fn: usize,
38            at_fn: usize,
39            clear_fn: usize,
40        ) -> QVariant;
41
42        /// The list metatype interface for an element type: a clone of `QQmlListProperty<QObject>`
43        /// (layout-identical to any `QQmlListProperty<T>`), named `QQmlListProperty<{element.name}>`
44        /// with the cached typeId reset to 0 so it registers as a fresh, distinct type.
45        ///
46        /// The name is derived from `element`'s own registered name (so the list and element types
47        /// can't drift apart) and leaked in C++.
48        #[rust_name = "list_property_interface_for"]
49        fn listPropertyInterfaceFor(element: &QMetaType) -> QMetaTypeInterface;
50    }
51}
52
53pub(crate) use ffi::{list_property_interface_for, list_property_to_qvariant};
54
55/// Plain `#[repr(C)]` view of `QQmlListProperty<QObject>`, used only to read fields out of the
56/// raw pointer QML passes to the callbacks. NOT a cxx type; it never crosses the FFI boundary.
57#[repr(C)]
58pub(crate) struct QQmlListPropertyCpp {
59    pub object: *mut QObject,
60    pub data: *mut u8,
61    pub append: *const (),
62    pub count: *const (),
63    pub at: *const (),
64    pub clear: *const (),
65    pub replace: *const (),
66    pub remove_last: *const (),
67}
68
69unsafe fn get_proxy_ptr<Owner>(
70    qobj: *const QObject,
71) -> *mut <Owner as QObjectHolder>::ProxyRust
72where
73    Owner: QObjectHolder,
74{
75    let qobj_ref = unsafe { qobj.as_ref() }.expect("QObject pointer is null");
76    let ptr = get_rust_proxy(qobj_ref);
77    assert!(!ptr.is_null(), "Rust proxy not registered for QObject");
78    ptr as *mut <Owner as QObjectHolder>::ProxyRust
79}
80
81/// `CountFunction` callback for `QQmlListProperty`. Wraps the operation in
82/// `with_rust_ref` to handle re-entrant borrows via `RustObjAccess`.
83pub(crate) unsafe extern "C" fn list_count<Owner, Elem>(prop: *const u8) -> isize
84where
85    Owner: QObjectHolder,
86{
87    let list_prop = unsafe { &*(prop as *const QQmlListPropertyCpp) };
88    let proxy_ptr = unsafe { get_proxy_ptr::<Owner>(list_prop.object) };
89    let store_offset = list_prop.data as usize;
90    unsafe { &*proxy_ptr }.with_rust_ref(|adapter| {
91        unsafe {
92            let owner = &*(adapter as *const _ as *const Owner);
93            let store = &*((owner as *const Owner).byte_add(store_offset) as *const Vec<Rc<RefCell<Elem>>>);
94            store.len() as isize
95        }
96    })
97}
98
99/// `AtFunction` callback for `QQmlListProperty`. Wraps the operation in
100/// `with_rust_ref` to handle re-entrant borrows via `RustObjAccess`.
101pub(crate) unsafe extern "C" fn list_at<Owner, Elem>(prop: *const u8, idx: isize) -> *mut QObject
102where
103    Owner: QObjectHolder,
104    Elem: QObjectHolder,
105{
106    let list_prop = unsafe { &*(prop as *const QQmlListPropertyCpp) };
107    let proxy_ptr = unsafe { get_proxy_ptr::<Owner>(list_prop.object) };
108    let store_offset = list_prop.data as usize;
109    unsafe { &*proxy_ptr }.with_rust_ref(|adapter| {
110        unsafe {
111            let owner = &*(adapter as *const _ as *const Owner);
112            let store = &*((owner as *const Owner).byte_add(store_offset) as *const Vec<Rc<RefCell<Elem>>>);
113            <Elem as QObjectHolder>::rc_ref_cell_to_qobject(&store[idx as usize]).cast_mut()
114        }
115    })
116}
117
118/// `AppendFunction` callback for `QQmlListProperty`. Wraps the operation in
119/// `with_rust_ref_mut` to handle re-entrant borrows via `RustObjAccess`, then
120/// pushes the new element and emits the `Notify` signal. `Notify` must be a
121/// zero-sized function item (a method of `Owner` with no parameters beyond `&mut self`).
122pub(crate) unsafe extern "C" fn list_append<Owner, Elem, Notify>(prop: *const u8, item: *mut QObject)
123where
124    Owner: QObjectHolder,
125    Elem: QObjectHolder,
126    Notify: Fn(&mut Owner) + 'static,
127{
128    debug_assert_eq!(std::mem::size_of::<Notify>(), 0, "Notify must be a zero-sized type");
129    let list_prop = unsafe { &*(prop as *const QQmlListPropertyCpp) };
130    let proxy_ptr = unsafe { get_proxy_ptr::<Owner>(list_prop.object) };
131    let store_offset = list_prop.data as usize;
132    unsafe { &*proxy_ptr }.with_rust_ref_mut(|adapter| {
133        unsafe {
134            let owner = &mut *(adapter as *mut _ as *mut Owner);
135            let store = &mut *((owner as *mut Owner).byte_add(store_offset) as *mut Vec<Rc<RefCell<Elem>>>);
136            store.push(<Elem as QObjectHolder>::qobject_to_rc_ref_cell(item));
137            let notify = std::mem::zeroed::<Notify>();
138            notify(owner);
139        }
140    });
141}
142
143/// `ClearFunction` callback for `QQmlListProperty`. Wraps the operation in
144/// `with_rust_ref_mut` to handle re-entrant borrows via `RustObjAccess`, then
145/// clears the list and emits the `Notify` signal. `Notify` must be a
146/// zero-sized function item (a method of `Owner` with no parameters beyond `&mut self`).
147pub(crate) unsafe extern "C" fn list_clear<Owner, Elem, Notify>(prop: *const u8)
148where
149    Owner: QObjectHolder,
150    Notify: Fn(&mut Owner) + 'static,
151{
152    debug_assert_eq!(std::mem::size_of::<Notify>(), 0, "Notify must be a zero-sized type");
153    let list_prop = unsafe { &*(prop as *const QQmlListPropertyCpp) };
154    let proxy_ptr = unsafe { get_proxy_ptr::<Owner>(list_prop.object) };
155    let store_offset = list_prop.data as usize;
156    unsafe { &*proxy_ptr }.with_rust_ref_mut(|adapter| {
157        unsafe {
158            let owner = &mut *(adapter as *mut _ as *mut Owner);
159            let store = &mut *((owner as *mut Owner).byte_add(store_offset) as *mut Vec<Rc<RefCell<Elem>>>);
160            store.clear();
161            let notify = std::mem::zeroed::<Notify>();
162            notify(owner);
163        }
164    });
165}