qtbridge-interfaces 0.1.4

Qt Bridge: Proxies and interfaces between Rust and Qt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only

use super::proxy_cpp_bridge::{QListModelProxyCpp, ffi};
use crate::{RustObjAccess, call_rust_trait_impl, call_cpp_impl};
use qtbridge_runtime::qrustproxy::{QRustProxy, ConstructionMode};
use qtbridge_runtime::QObjectHolder;
use qtbridge_runtime::QModelItem;
use qtbridge_type_lib::{QByteArray, QHash, QMetaObject, QMetaType, QModelIndex, QVariant};
use std::cell::RefCell;
use std::rc::Rc;

#[doc(hidden)]
pub trait QListModelAdapter {
    fn index(&self, row: i32, column: i32, parent: &QModelIndex) -> QModelIndex;
    fn row_count(&self, parent: &QModelIndex) -> i32;
    fn data(&self, index: &QModelIndex, role: i32) -> QVariant;
    fn role_names(&self) -> QHash<i32, QByteArray>;
    fn set_data(&mut self, index: &QModelIndex, value: &QVariant, role: i32) -> bool;
    fn remove_rows(&mut self, first: i32, count: i32, parent: &QModelIndex) -> bool;
    fn sibling(&self, row: i32, column: i32, idx: &QModelIndex) -> QModelIndex;
}

impl<T> QListModelAdapter for T
where
    T: QListModel + QObjectHolder<ProxyRust = QListModelProxyRust> {
    fn index(&self, row: i32, column: i32, parent: &QModelIndex) -> QModelIndex {
        let proxy = <Self as QObjectHolder>::get_rust_proxy(self);
        proxy.base_index(row, column, parent)
    }
    fn row_count(&self, _parent: &QModelIndex) -> i32 {
        return self.len() as i32;
    }
    fn data(&self, index: &QModelIndex, role: i32) -> QVariant {
        let Some(item) = self.get(index.row() as usize)
        else {
            return QVariant::default();
        };
        item.get_role(role)
    }
    fn role_names(&self) -> QHash<i32, QByteArray> {
        let names = T::Item::role_names();
        let mut result = QHash::default();
        names.iter()
            .for_each(|(k, v)| result.insert(k, &QByteArray::from(v)));
        result
    }
    fn set_data(&mut self, index: &QModelIndex, value: &QVariant, role: i32) -> bool {
        if !index.is_valid() {
            return false;
        }
        let Some(mut item) = self.get(index.row() as usize)
            .cloned()
        else {
            return false;
        };
        let updated = item.set_role(role, value);
        if updated {
            self.set_unnotified(index.row() as usize, item);
            self.get_rust_proxy_mut().base_data_changed(index, index);
        }
        updated
    }
    fn remove_rows(&mut self, first: i32, count: i32, parent: &QModelIndex) -> bool {
        let first = first as usize;
        let last = first + count as usize;
        if last > self.len() {
            return false;
        }
        self.get_rust_proxy_mut().base_begin_remove_rows(parent, first as i32, (last - 1) as i32);
        for index in (first..last).rev() {
            self.remove_unnotified(index);
        }
        self.get_rust_proxy_mut().base_end_remove_rows();
        true
    }
    fn sibling(&self, row: i32, column: i32, idx: &QModelIndex) -> QModelIndex {
        let proxy = self.get_rust_proxy();
        proxy.base_sibling(row, column, idx)
    }
}

/// A trait representing a list-based Qt model.
///
/// [`QListModel`] provides an interface for list-like data structures
/// that are exposed to Qt through the Model-View concept.
/// <https://doc.qt.io/qt-6/qtquick-modelviewsdata-modelview.html>.
///
/// This trait requires the `qobject` macro to set up the correct Qt proxy.
/// The macro will further generate functionality in the form of the
/// [`QListModelBase`] trait that supplements the [`QListModel`] functionality.
///
/// ## Design
///
/// - The model owns items of associated type `Item` that has to implement
///   the [`QModelItem`] trait. Roles are derived from the [`QModelItem`]
///   implementation.
/// - Mutation methods are provided in an **unnotified** form, meaning
///   they modify the underlying data without emitting Qt model signals.
/// - These methods are used by the automatically implemented [`QListModelBase`]
///   trait to create methods that collaborate the UI about changes in collections.
///
/// As a minimum you have to implement the methods [`QListModel::len`] and
/// [`QListModel::get`] to create a readable list model. Further methods can be
/// implemented to make the model fully mutable.
///
/// Methods that do not return an [`Option`] or a boolean value must succeed
/// and perform exactly the operation described in the documentation to avoid
/// invalidating the synchronization between any views and the underlying data.
/// No additional structural changes may occur outside the provided functions.
///
/// **Note, that default implementations may `panic!`** if the corresponding method is
/// not overridden. It is your responsibility to make sure that these functions are
/// not called from QML.
///
/// ## Example
///
/// ``` ignore
/// use qtbridge::qobject;
/// #[qobject(Base = QListModel)]
/// mod backend {
///     use qtbridge::qml_element;
///     use qtbridge::{QListModel, QListModelBase};
///
///     #[derive(Default)]
///     #[qml_element]
///     pub struct Backend {
///         string_list: Vec<String>,
///     }
///     impl QListModel for Backend {
///         type Item = String;
///
///         fn len(&self) -> usize {
///             self.string_list.len()
///         }
///         fn get(&self, index: usize) -> Option<&Self::Item> {
///             self.string_list.get(index)
///         }
///     }
/// }
///
/// ```
///
/// The list model can be used in QML views as follows
/// ``` qml, ignore
/// ListView {
///     model: backend
///     delegate: Text {
///         required property string value
///         text: value
///     }
/// }
/// ```

pub trait QListModel {
    /// The item type stored in the model.
    ///
    /// Items must:
    /// - Implement [`QModelItem`] to integrate with Qt
    /// - Be [`Default`] for creating new items
    /// - Be [`Clone`] for safe data access and copying
    type Item: QModelItem + Default + Clone;

    /// Returns the number of items in the list.
    fn len(&self) -> usize;

    /// Returns a reference to the item at `index`, or `None` if the index
    /// is out of bounds.
    fn get(&self, index: usize) -> Option<&Self::Item>;

    /// Sets the item at `index`. Reimplement this function but call
    /// [`QListModelBase::set`] to notify Qt about the modification.
    ///
    /// Returns `true` if the value was successfully set, or `false` if the
    /// operation failed (e.g., index out of bounds or value fails
    /// validation by the business logic).
    ///
    /// The default implementation does nothing and returns `false`.
    fn set_unnotified(&mut self, _index: usize, _value: Self::Item) -> bool {
        false
    }

    /// Appends an item to the end of the model. Reimplement this
    /// function but call [`QListModelBase::push`] to notify Qt about the
    /// modification.
    ///
    /// The function has to accept the value. Validation has to be
    /// done before this function is called.
    ///
    /// The default implementation falls back to [`QListModel::insert_unnotified`],
    /// which in turn panics by default.
    fn push_unnotified(&mut self, value: Self::Item) {
        self.insert_unnotified(self.len(), value);
    }

    /// Inserts `value` at `index`. Reimplement this function but
    /// call [`QListModelBase::insert`] to notify Qt about the
    /// modification.
    ///
    /// The function has to accept the value. Validation has to be
    /// done before this function is called.
    ///
    /// Panics by default. Implementors must override this method to support
    /// insertion.
    fn insert_unnotified(&mut self, _index: usize, _value: Self::Item) {
        panic!("In order to use insert, implement insert_unnotified")
    }

    /// Removes and returns the last item in the model. Reimplement this
    /// function but call [`QListModelBase::pop`] to notify Qt
    /// about the modification.
    ///
    /// Returns `None` if the model is empty. If the model is not empty,
    /// the function has to guarantee the success of the operation.
    ///
    /// The default implementation falls back to [`QListModel::remove_unnotified`],
    /// which in turn panics by default.
    fn pop_unnotified(&mut self) -> Option<Self::Item> {
        (self.len() > 0)
            .then(|| self.remove_unnotified(self.len() - 1))
    }

    /// Removes and returns the item at `index`. Reimplement this
    /// function but call [`QListModelBase::remove`] to notify Qt
    /// about the modification.
    ///
    /// The index must be valid and the model has to guarantee the success of
    /// the operation.
    ///
    /// Panics by default. Implementors must override this method to support
    /// removal.
    fn remove_unnotified(&mut self, _index: usize) -> Self::Item {
        panic!("In order to use remove, implement remove_unnotified")
    }

    /// Resets the model’s internal storage. Reimplement this function but
    /// call [`QListModelBase::reset`] to notify Qt about the modification.
    ///
    /// Panics by default. Implementors must override this method to support
    /// a model reset.
    ///
    /// After [`QListModel::reset_unnotified`] returns, the internal storage
    /// must reflect the new model state: [`QListModel::len`] and
    /// [`QListModel::get`] must be consistent with the updated storage.
    fn reset_unnotified(&mut self) {
        panic!("In order to use reset, implement reset_unnotified")
    }

}

/// A data-change signaling extension of [`QListModel`].
///
/// `QListModelBase` provides the signaling mutation API for list models.
/// The methods defined in this trait wrap the corresponding
/// `*_unnotified` methods from [`QListModel`] and automatically emit the
/// required Qt model signals (such as `beginInsertRows`, `endInsertRows`,
/// `dataChanged`, etc.). This allows the UI to react to changes in the
/// underlying data.
///
/// This trait is automatically implemented by the [`qobject`] macro and
/// should not be implemented manually.
///
/// ## Usage
///
/// When modifying data that you made accessible with [`QListModel`], you
/// have to use the functions provided by this trait. Do **not** call the
/// `*_unnotified` methods from [`QListModel`] directly unless you are
/// manually handling Qt model notifications.
///
/// The correctness of this trait depends on implementors of [`QListModel`]
/// ensuring that:
///
/// * The `*_unnotified` methods perform the exact mutation corresponding
///   to the emitted Qt signals.
/// * No additional structural changes occur.
///
/// Violating this contract may result in undefined behavior in Qt views.
pub trait QListModelBase : QListModel + QObjectHolder<ProxyRust = QListModelProxyRust> {
    /// Sets the item at `index` and notifies any attached views about
    /// the change, if the operation is successful.
    ///
    /// This method calls [`QListModel::set_unnotified`].
    ///
    /// Returns `true` if the value was successfully updated,
    /// or `false` if the operation failed (for example, if the index
    /// was out of bounds or validation failed).
    fn set(&mut self, index: usize, value: <Self as QListModel>::Item) -> bool {
        if self.set_unnotified(index, value) {
            let model_index = self.get_rust_proxy().base_index(index as i32, 0 , &QModelIndex::default());
            self.get_rust_proxy_mut().base_data_changed(&model_index, &model_index);
            true
        } else {
            false
        }
    }

    /// Appends `value` to the end of the model and notifies any attached views about
    /// the change.
    ///
    /// This method calls [`QListModel::push_unnotified`].
    fn push(&mut self, value: Self::Item) {
        self.get_rust_proxy_mut().base_begin_insert_rows(&QModelIndex::default(), self.len() as i32, self.len() as i32);
        self.push_unnotified(value);
        self.get_rust_proxy_mut().base_end_insert_rows();
    }

    /// Inserts `value` at `index` and notifies any attached views about
    /// the change.
    ///
    /// This method calls [`QListModel::insert_unnotified`].
    fn insert(&mut self, index: usize, value: Self::Item) {
        self.get_rust_proxy_mut().base_begin_insert_rows(&QModelIndex::default(), index as i32, index as i32);
        self.insert_unnotified(index, value);
        self.get_rust_proxy_mut().base_end_insert_rows();
    }

    /// Removes and returns the last item in the model and notifies any attached views about
    /// the change.
    ///
    /// This method calls [`QListModel::pop_unnotified`].
    ///
    /// Returns `None` if the model is empty. If the model is not empty,
    /// the function has to guarantee the success of the operation.
    fn pop(&mut self) -> Option<Self::Item> {
        if self.len() == 0 {
            return None;
        }
        self.get_rust_proxy_mut().base_begin_remove_rows(&QModelIndex::default(), self.len() as i32 - 1, self.len() as i32 - 1);
        let value = self.pop_unnotified();
        self.get_rust_proxy_mut().base_end_remove_rows();
        value
    }

    /// Removes and returns the item at `index` and notifies any attached views about
    /// the change.
    ///
    /// This method calls [`QListModel::remove_unnotified`].
    fn remove(&mut self, index: usize) -> Self::Item {
        self.get_rust_proxy_mut().base_begin_remove_rows(&QModelIndex::default(), index as i32, index as i32);
        let value = self.remove_unnotified(index);
        self.get_rust_proxy_mut().base_end_remove_rows();
        value
    }
    /// Resets the entire model and notifies any attached views to resyncronize all data.
    ///
    /// This method calls [`QListModel::reset_unnotified`].
    fn reset(&mut self) {
        self.get_rust_proxy_mut().base_begin_reset_model();
        self.reset_unnotified();
        self.get_rust_proxy_mut().base_end_reset_model();
    }
}

impl<T> QListModelBase for T
where T: QListModel + QObjectHolder<ProxyRust = QListModelProxyRust> { }

pub struct QListModelProxyRust {
    cpp_proxy: *mut QListModelProxyCpp,
    #[allow(dead_code)]
    rust_obj: RustObjAccess<dyn QListModelAdapter>,
    on_drop: fn(rust_obj: *const u8),
}

impl QRustProxy for QListModelProxyRust {

    type ProxyCppType = QListModelProxyCpp;
    type AdapterType = dyn QListModelAdapter;

    fn new(rust_obj: &Rc<RefCell<dyn QListModelAdapter>>, construct: ConstructionMode, on_drop: fn(rust_obj: *const u8)) -> *mut Self {
        let raw_rust_obj = rust_obj.as_ptr();
        let boxed_self = Box::new(Self {
            cpp_proxy: std::ptr::null_mut(),
            rust_obj: match construct {
                ConstructionMode::Strong | ConstructionMode::AtAddress(_) => RustObjAccess::new_strong(rust_obj.clone()),
                ConstructionMode::Weak => RustObjAccess::new_weak(Rc::downgrade(rust_obj)),
            },
            on_drop,
        });
        let raw_self = Box::into_raw(boxed_self);

        unsafe{ (*raw_self).cpp_proxy = match construct {
            ConstructionMode::AtAddress(addr) => {
                ffi::create_qlist_model_proxy_cpp_at( addr, raw_rust_obj.cast(), raw_self)
            }
            ConstructionMode::Strong | ConstructionMode::Weak => {
                ffi::create_qlist_model_proxy_cpp(raw_rust_obj.cast(), raw_self)
            }
        }};
        raw_self
    }
    fn drop_self(raw_self: *mut Self, rust_obj_ptr: *const u8) {
        Self::drop_self_impl(raw_self, rust_obj_ptr)
    }
    fn get_static_meta_object() -> &'static QMetaObject {
        ffi::static_qmeta_object_of_qlist_model_proxy_cpp()
    }
    fn get_size_of_cpp_proxy() -> usize {
        ffi::size_of_qlist_model_proxy_cpp()
    }
    fn get_align_of_cpp_proxy() -> usize {
        ffi::align_of_qlist_model_proxy_cpp()
    }
    fn get_qmetatype_list_of_cpp_proxy() -> QMetaType {
        ffi::qmetatype_list_of_qlist_model_proxy_cpp()
    }
    fn get_cpp_proxy(&self) -> *const QListModelProxyCpp {
        self.cpp_proxy as *const _
    }
    fn get_cpp_proxy_mut(&self) -> *mut QListModelProxyCpp {
        self.cpp_proxy
    }
}

impl QListModelProxyRust {
    pub fn drop_self_impl(raw_self: *mut Self, rust_obj_ptr: *const u8) {
        let boxed_self = unsafe { Box::from_raw(raw_self) };
        (boxed_self.on_drop)(rust_obj_ptr);
    }
    pub fn index(&self, row: i32, column: i32, parent: &QModelIndex) -> QModelIndex {
        call_rust_trait_impl!(self, index(row, column, parent))
    }
    pub fn row_count(&self, parent: &QModelIndex) -> i32 {
        call_rust_trait_impl!(self, row_count(parent))
    }
    pub fn data(&self, index: &QModelIndex, role: i32) -> QVariant {
        call_rust_trait_impl!(self, data(index, role))
    }
    pub fn role_names(&self) -> QHash<i32, QByteArray> {
        call_rust_trait_impl!(self, role_names())
    }
    pub fn set_data(&mut self, index: &QModelIndex, value: &QVariant, role: i32) -> bool {
        call_rust_trait_impl!(mut self, set_data(index, value, role))
    }
    pub fn remove_rows(&mut self, first: i32, count: i32, parent: &QModelIndex) -> bool {
        call_rust_trait_impl!(mut self, remove_rows(first, count, parent))
    }
    pub fn sibling(&self, row: i32, column: i32, idx: &QModelIndex) -> QModelIndex {
        call_rust_trait_impl!(self, sibling(row, column, idx))
    }
    pub fn base_index(&self, row: i32, column: i32, parent: &QModelIndex) -> QModelIndex {
        call_cpp_impl!(self, base_index(row, column, parent))
    }
    pub fn base_role_names(&self) -> QHash<i32, QByteArray> {
        call_cpp_impl!(self, base_role_names())
    }
    pub fn base_set_data(&mut self, index: &QModelIndex, value: &QVariant, role: i32) -> bool {
        call_cpp_impl!(mut self, base_set_data(index, value, role))
    }
    pub fn base_remove_rows(&mut self, first: i32, count: i32, parent: &QModelIndex) -> bool {
        call_cpp_impl!(mut self, base_remove_rows(first, count, parent))
    }
    pub fn base_sibling(&self, row: i32, column: i32, idx: &QModelIndex) -> QModelIndex {
        call_cpp_impl!(self, base_sibling(row, column, idx))
    }
    pub fn base_data_changed(&mut self, top_left: &QModelIndex, bottom_right: &QModelIndex) {
        call_cpp_impl!(mut self, base_data_changed(top_left, bottom_right))
    }
    pub fn base_begin_insert_rows(&mut self, parent: &QModelIndex, first: i32, last: i32) {
        call_cpp_impl!(mut self, base_begin_insert_rows(parent, first, last))
    }
    pub fn base_end_insert_rows(&mut self) {
        call_cpp_impl!(mut self, base_end_insert_rows())
    }
    pub fn base_begin_move_rows(&mut self, source_parent: &QModelIndex, source_first: i32, source_last: i32, destination_parent: &QModelIndex, destination_child: i32) {
        call_cpp_impl!(mut self, base_begin_move_rows(source_parent, source_first, source_last, destination_parent, destination_child))
    }
    pub fn base_end_move_rows(&mut self) {
        call_cpp_impl!(mut self, base_end_move_rows())
    }
    pub fn base_begin_remove_rows(&mut self, parent: &QModelIndex, first: i32, last: i32) {
        call_cpp_impl!(mut self, base_begin_remove_rows(parent, first, last))
    }
    pub fn base_end_remove_rows(&mut self) {
        call_cpp_impl!(mut self, base_end_remove_rows())
    }
    pub fn base_begin_reset_model(&mut self) {
        call_cpp_impl!(mut self, base_begin_reset_model())
    }
    pub fn base_end_reset_model(&mut self) {
        call_cpp_impl!(mut self, base_end_reset_model())
    }
}