qtrs 0.5.5

qtrs - A type-safe, builder-pattern-driven Qt6 GUI library for Rust
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! Qt Variant — A type-erased value container
//!
//! QVariant can store values of many different types, similar to `std::any`.
//! This module provides a type-safe Rust wrapper around QVariant.

use crate::ffi::ffi_inner;
use std::fmt;

/// A type-erased value container that can hold various Qt types.
///
/// # Examples
/// ```
/// use qtrs::Variant;
///
/// let v = Variant::from(42);
/// assert_eq!(v.convert::<i32>(), Some(42));
///
/// let v = Variant::from("hello");
/// assert_eq!(v.convert::<String>(), Some("hello".to_string()));
/// ```
pub struct Variant {
    pub(crate) inner: *mut ffi_inner::QVariant,
}

unsafe impl Send for Variant {}
unsafe impl Sync for Variant {}

impl Variant {
    // ============================================================
    // Type-safe extraction
    // ============================================================

    /// Extract a value of type `T` from the Variant
    ///
    /// Returns `Some(T)` if the Variant contains the correct type,
    /// otherwise returns `None`.
    ///
    /// # Examples
    /// ```
    /// # use qtrs::Variant;
    /// let v = Variant::from(42);
    /// assert_eq!(v.convert::<i32>(), Some(42));
    /// assert_eq!(v.convert::<String>(), Some("42".to_string()));
    /// ```
    pub fn convert<T: VariantType>(&self) -> Option<T> {
        if T::is_type(self.inner) {
            unsafe { T::try_extract(self.inner) }
        } else {
            None
        }
    }

    /// Extract a value of type `T` or return a default value
    pub fn convert_or<T: VariantType + Default>(&self) -> T {
        self.convert::<T>().unwrap_or_default()
    }

    /// Extract a value of type `T` or return a provided default
    pub fn convert_or_else<T: VariantType>(&self, default: T) -> T {
        self.convert::<T>().unwrap_or(default)
    }

    /// Returns the raw pointer (for advanced use)
    pub(crate) fn raw_ptr(&self) -> *mut ffi_inner::QVariant {
        self.inner
    }
}

// ============================================================
// Drop
// ============================================================

impl Drop for Variant {
    fn drop(&mut self) {
        if !self.inner.is_null() {
            unsafe {
                ffi_inner::QVariant_delete(self.inner);
            }
        }
    }
}

// ============================================================
// VariantType trait
// ============================================================

/// Trait for types that can be stored in a Variant
pub trait VariantType: Sized + 'static {
    /// Check if the variant contains this type
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool;

    /// Try to extract the value; returns None if conversion fails
    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self>;

    /// Extract the value from the variant
    /// # Safety
    /// Caller must ensure the variant contains the correct type
    unsafe fn extract(ptr: *mut ffi_inner::QVariant) -> Self {
        Self::try_extract(ptr).unwrap_or_else(|| panic!("Variant type mismatch in extract"))
    }

    /// Create a Variant from this type
    fn into_variant(self) -> Variant;
}

// Helper: returns Some(value) only if ok is true, None otherwise
macro_rules! extract_checked {
    ($ptr:expr, $ffi_fn:ident, $ty:ty) => {{
        let mut ok = false;
        let val = ffi_inner::$ffi_fn($ptr, &mut ok);
        if ok { Some(val as $ty) } else { None }
    }};
    ($ptr:expr, $ffi_fn:ident) => {{
        let mut ok = false;
        let val = ffi_inner::$ffi_fn($ptr, &mut ok);
        if ok { Some(val) } else { None }
    }};
}

// ============================================================
// Implementations for concrete types
// ============================================================

// src/variant.rs

impl VariantType for i32 {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_int(ptr) }
    }

    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        extract_checked!(ptr, QVariant_to_int, i32)
    }

    fn into_variant(self) -> Variant {
        unsafe { Variant { inner: ffi_inner::QVariant_from_int(self) } }
    }
}

impl VariantType for u32 {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_uint(ptr) }
    }
    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        extract_checked!(ptr, QVariant_to_uint)
    }
    fn into_variant(self) -> Variant {
        unsafe { Variant { inner: ffi_inner::QVariant_from_uint(self) } }
    }
}

impl VariantType for i64 {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_long(ptr) }
    }
    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        extract_checked!(ptr, QVariant_to_long)
    }
    fn into_variant(self) -> Variant {
        unsafe { Variant { inner: ffi_inner::QVariant_from_long(self) } }
    }
}

impl VariantType for bool {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_bool(ptr) }
    }
    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        extract_checked!(ptr, QVariant_to_bool)
    }
    fn into_variant(self) -> Variant {
        unsafe { Variant { inner: ffi_inner::QVariant_from_bool(self) } }
    }
}

impl VariantType for f64 {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_double(ptr) }
    }
    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        extract_checked!(ptr, QVariant_to_double)
    }

    fn into_variant(self) -> Variant {
        unsafe {
            Variant {
                inner: ffi_inner::QVariant_from_double(self),
            }
        }
    }
}

// ============================================================
// 小整数类型
// ============================================================

impl VariantType for u8 {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_uint(ptr) }
    }

    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        extract_checked!(ptr, QVariant_to_uint, u8)
    }

    fn into_variant(self) -> Variant {
        unsafe {
            Variant {
                inner: ffi_inner::QVariant_from_uint(self as u32),
            }
        }
    }
}

impl VariantType for i8 {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_int(ptr) }
    }

    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        extract_checked!(ptr, QVariant_to_int, i8)
    }

    fn into_variant(self) -> Variant {
        unsafe {
            Variant {
                inner: ffi_inner::QVariant_from_int(self as i32),
            }
        }
    }
}

impl VariantType for u16 {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_uint(ptr) }
    }

    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        extract_checked!(ptr, QVariant_to_uint, u16)
    }

    fn into_variant(self) -> Variant {
        unsafe {
            Variant {
                inner: ffi_inner::QVariant_from_uint(self as u32),
            }
        }
    }
}

impl VariantType for i16 {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_int(ptr) }
    }

    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        extract_checked!(ptr, QVariant_to_int, i16)
    }

    fn into_variant(self) -> Variant {
        unsafe {
            Variant {
                inner: ffi_inner::QVariant_from_int(self as i32),
            }
        }
    }
}

impl VariantType for f32 {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_double(ptr) }
    }

    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        extract_checked!(ptr, QVariant_to_double, f32)
    }

    fn into_variant(self) -> Variant {
        unsafe {
            Variant {
                inner: ffi_inner::QVariant_from_double(self as f64),
            }
        }
    }
}

impl VariantType for String {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_string(ptr) }
    }

    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        extract_checked!(ptr, QVariant_to_string)
    }

    fn into_variant(self) -> Variant {
        unsafe {
            Variant {
                inner: ffi_inner::QVariant_from_string(self),
            }
        }
    }
}

impl VariantType for Vec<String> {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_stringlist(ptr) }
    }
    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        Some(ffi_inner::QVariant_to_stringlist(ptr))
    }

    fn into_variant(self) -> Variant {
        unsafe {
            Variant {
                inner: ffi_inner::QVariant_from_stringlist(self),
            }
        }
    }
}

impl VariantType for Vec<u8> {
    fn is_type(ptr: *mut ffi_inner::QVariant) -> bool {
        unsafe { ffi_inner::QVariant_is_bytearray(ptr) }
    }
    unsafe fn try_extract(ptr: *mut ffi_inner::QVariant) -> Option<Self> {
        Some(ffi_inner::QVariant_to_bytearray(ptr))
    }

    fn into_variant(self) -> Variant {
        unsafe {
            Variant {
                inner: ffi_inner::QVariant_from_bytearray(&self),
            }
        }
    }
}

// ============================================================
// From / Into traits (convenience)
// ============================================================

impl<T: VariantType> From<T> for Variant {
    fn from(value: T) -> Self {
        value.into_variant()
    }
}

impl From<&str> for Variant {
    fn from(value: &str) -> Self {
        Variant::from(value.to_string())
    }
}

// ============================================================
// PartialEq trait(for assert_eq!, etc.)
// ============================================================

impl PartialEq for Variant {
    fn eq(&self, other: &Self) -> bool {
        // i32
        if let (Some(v1), Some(v2)) = (self.convert::<i32>(), other.convert::<i32>()) {
            return v1 == v2;
        }
        // u32
        if let (Some(v1), Some(v2)) = (self.convert::<u32>(), other.convert::<u32>()) {
            return v1 == v2;
        }
        // i64
        if let (Some(v1), Some(v2)) = (self.convert::<i64>(), other.convert::<i64>()) {
            return v1 == v2;
        }
        // String
        if let (Some(v1), Some(v2)) = (self.convert::<String>(), other.convert::<String>()) {
            return v1 == v2;
        }
        // bool
        if let (Some(v1), Some(v2)) = (self.convert::<bool>(), other.convert::<bool>()) {
            return v1 == v2;
        }
        // f64
        if let (Some(v1), Some(v2)) = (self.convert::<f64>(), other.convert::<f64>()) {
            // oh my god why the world has a thing named nan!
            // i want to impl Eq btw
            return v1 == v2;
        }
        // Vec<String>
        if let (Some(v1), Some(v2)) = (self.convert::<Vec<String>>(), other.convert::<Vec<String>>()) {
            return v1 == v2;
        }
        // Vec<u8>
        if let (Some(v1), Some(v2)) = (self.convert::<Vec<u8>>(), other.convert::<Vec<u8>>()) {
            return v1 == v2;
        }
        false
    }
}

// ============================================================
// Debug trait
// ============================================================

impl fmt::Debug for Variant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(v) = self.convert::<i32>() {
            return write!(f, "Variant({})", v);
        }
        if let Some(v) = self.convert::<u32>() {
            return write!(f, "Variant({})", v);
        }
        if let Some(v) = self.convert::<i64>() {
            return write!(f, "Variant({})", v);
        }
        if let Some(v) = self.convert::<String>() {
            return write!(f, "Variant({:?})", v);
        }
        if let Some(v) = self.convert::<bool>() {
            return write!(f, "Variant({})", v);
        }
        if let Some(v) = self.convert::<f64>() {
            if v.is_nan() {
                return write!(f, "Variant(NaN)");
            } else if v.is_infinite() {
                return write!(f, "Variant({})", if v.is_sign_positive() { "inf" } else { "-inf" });
            }
            return write!(f, "Variant({})", v);
        }
        if let Some(v) = self.convert::<Vec<String>>() {
            return write!(f, "Variant({:?})", v);
        }
        if let Some(v) = self.convert::<Vec<u8>>() {
            return write!(f, "Variant({:?})", v);
        }
        
        // 未知类型
        write!(f, "Variant(<unknown>)")
    }
}

// ============================================================
// Tests
// ============================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_convert() {
        let v = Variant::from(42_i32);
        assert_eq!(v.convert::<i32>(), Some(42));
        assert_eq!(v.convert::<String>(), Some("42".to_string()));

        let v = Variant::from("hello");
        assert_eq!(v.convert::<String>(), Some("hello".to_string()));
        assert_eq!(v.convert::<i32>(), None);
    }

    #[test]
    fn test_convert_or() {
        let v = Variant::from(42_i32);
        assert_eq!(v.convert_or::<i32>(), 42);
        assert_eq!(v.convert_or::<String>(), "42".to_string());

        let v = Variant::from("hello".to_string());
        assert_eq!(v.convert_or_else::<String>("default".to_string()), "hello");
        assert_eq!(v.convert_or::<i32>(), 0);
    }

    #[test]
    fn test_all_types() {
        let v = Variant::from(42_i32);
        assert_eq!(v.convert::<i32>(), Some(42));

        let v = Variant::from(42_u32);
        assert_eq!(v.convert::<u32>(), Some(42));

        let v = Variant::from(42_i64);
        assert_eq!(v.convert::<i64>(), Some(42));

        let v = Variant::from(true);
        assert_eq!(v.convert::<bool>(), Some(true));

        let v = Variant::from(3.14);
        assert_eq!(v.convert::<f64>(), Some(3.14));

        let v = Variant::from("hello".to_string());
        assert_eq!(v.convert::<String>(), Some("hello".to_string()));

        let v = Variant::from(vec!["a".to_string(), "b".to_string()]);
        assert_eq!(v.convert::<Vec<String>>(), Some(vec!["a".to_string(), "b".to_string()]));

        let v = Variant::from(vec![1, 2, 3]);
        assert_eq!(v.convert::<Vec<u8>>(), Some(vec![1, 2, 3]));
    }
}