azul-layout 0.0.7

Layout solver + font and image loader the Azul GUI framework
Documentation
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
//! Thread callback information and utilities for azul-layout
//!
//! This module provides thread-related callback structures for background tasks
//! that need to interact with the UI thread and query layout information.

#[cfg(feature = "std")]
use alloc::sync::Arc;
#[cfg(feature = "std")]
use core::sync::atomic::AtomicBool;
#[cfg(feature = "std")]
use core::sync::atomic::Ordering;
#[cfg(feature = "std")]
use std::sync::{
    mpsc::{channel, Receiver, Sender},
    Mutex,
};
#[cfg(feature = "std")]
use std::thread::{self, JoinHandle};

use azul_core::{
    callbacks::Update,
    refany::{OptionRefAny, RefAny},
    task::{
        CheckThreadFinishedCallback, CheckThreadFinishedCallbackType, LibrarySendThreadMsgCallback,
        LibrarySendThreadMsgCallbackType, OptionThreadSendMsg, ThreadId, ThreadReceiver,
        ThreadReceiverDestructorCallback, ThreadReceiverInner, ThreadRecvCallback, ThreadSendMsg,
    },
};

use crate::callbacks::CallbackInfo;

// Types that need to be defined locally (not in azul-core)

/// Message that is sent back from the running thread to the main thread
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(C, u8)]
pub enum ThreadReceiveMsg {
    WriteBack(ThreadWriteBackMsg),
    Update(Update),
}

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(C, u8)]
pub enum OptionThreadReceiveMsg {
    None,
    Some(ThreadReceiveMsg),
}

impl From<Option<ThreadReceiveMsg>> for OptionThreadReceiveMsg {
    fn from(inner: Option<ThreadReceiveMsg>) -> Self {
        match inner {
            None => OptionThreadReceiveMsg::None,
            Some(v) => OptionThreadReceiveMsg::Some(v),
        }
    }
}

impl OptionThreadReceiveMsg {
    pub fn into_option(self) -> Option<ThreadReceiveMsg> {
        match self {
            OptionThreadReceiveMsg::None => None,
            OptionThreadReceiveMsg::Some(v) => Some(v),
        }
    }

    pub fn as_ref(&self) -> Option<&ThreadReceiveMsg> {
        match self {
            OptionThreadReceiveMsg::None => None,
            OptionThreadReceiveMsg::Some(v) => Some(v),
        }
    }
}

/// Message containing writeback data and callback
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(C)]
pub struct ThreadWriteBackMsg {
    pub refany: RefAny,
    pub callback: WriteBackCallback,
}

impl ThreadWriteBackMsg {
    pub fn new<C: Into<WriteBackCallback>>(callback: C, data: RefAny) -> Self {
        Self {
            refany: data,
            callback: callback.into(),
        }
    }
}

/// ThreadSender allows sending messages from the background thread to the main thread
#[derive(Debug)]
#[repr(C)]
pub struct ThreadSender {
    #[cfg(feature = "std")]
    pub ptr: alloc::boxed::Box<Arc<Mutex<ThreadSenderInner>>>,
    #[cfg(not(feature = "std"))]
    pub ptr: *const core::ffi::c_void,
    pub run_destructor: bool,
    /// For FFI: stores the foreign callable (e.g., PyFunction)
    pub ctx: OptionRefAny,
}

impl Clone for ThreadSender {
    fn clone(&self) -> Self {
        Self {
            ptr: self.ptr.clone(),
            run_destructor: true,
            ctx: self.ctx.clone(),
        }
    }
}

impl Drop for ThreadSender {
    fn drop(&mut self) {
        self.run_destructor = false;
    }
}

impl ThreadSender {
    #[cfg(not(feature = "std"))]
    pub fn new(_t: ThreadSenderInner) -> Self {
        Self {
            ptr: core::ptr::null(),
            run_destructor: false,
            ctx: OptionRefAny::None,
        }
    }

    #[cfg(feature = "std")]
    pub fn new(t: ThreadSenderInner) -> Self {
        Self {
            ptr: alloc::boxed::Box::new(Arc::new(Mutex::new(t))),
            run_destructor: true,
            ctx: OptionRefAny::None,
        }
    }

    /// Get the FFI context (e.g., Python callable)
    pub fn get_ctx(&self) -> OptionRefAny {
        self.ctx.clone()
    }

    #[cfg(not(feature = "std"))]
    pub fn send(&mut self, _msg: ThreadReceiveMsg) -> bool {
        false
    }

    #[cfg(feature = "std")]
    pub fn send(&mut self, msg: ThreadReceiveMsg) -> bool {
        let ts = match self.ptr.lock().ok() {
            Some(s) => s,
            None => return false,
        };
        (ts.send_fn.cb)(ts.ptr.as_ref() as *const _ as *const core::ffi::c_void, msg)
    }
}

#[derive(Debug)]
#[cfg_attr(not(feature = "std"), derive(PartialEq, PartialOrd, Eq, Ord))]
#[repr(C)]
pub struct ThreadSenderInner {
    #[cfg(feature = "std")]
    pub ptr: alloc::boxed::Box<Sender<ThreadReceiveMsg>>,
    #[cfg(not(feature = "std"))]
    pub ptr: *const core::ffi::c_void,
    pub send_fn: ThreadSendCallback,
    pub destructor: ThreadSenderDestructorCallback,
}

#[cfg(not(feature = "std"))]
unsafe impl Send for ThreadSenderInner {}

#[cfg(feature = "std")]
impl core::hash::Hash for ThreadSenderInner {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        (self.ptr.as_ref() as *const _ as usize).hash(state);
    }
}

#[cfg(feature = "std")]
impl PartialEq for ThreadSenderInner {
    fn eq(&self, other: &Self) -> bool {
        (self.ptr.as_ref() as *const _ as usize) == (other.ptr.as_ref() as *const _ as usize)
    }
}

#[cfg(feature = "std")]
impl Eq for ThreadSenderInner {}

#[cfg(feature = "std")]
impl PartialOrd for ThreadSenderInner {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(
            (self.ptr.as_ref() as *const _ as usize)
                .cmp(&(other.ptr.as_ref() as *const _ as usize)),
        )
    }
}

#[cfg(feature = "std")]
impl Ord for ThreadSenderInner {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        (self.ptr.as_ref() as *const _ as usize).cmp(&(other.ptr.as_ref() as *const _ as usize))
    }
}

impl Drop for ThreadSenderInner {
    fn drop(&mut self) {
        (self.destructor.cb)(self);
    }
}

/// Callback for sending messages from thread to main thread
pub type ThreadSendCallbackType = extern "C" fn(*const core::ffi::c_void, ThreadReceiveMsg) -> bool;

#[repr(C)]
pub struct ThreadSendCallback {
    pub cb: ThreadSendCallbackType,
}

impl core::fmt::Debug for ThreadSendCallback {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(f, "ThreadSendCallback {{ cb: {:p} }}", self.cb as *const ())
    }
}

impl Clone for ThreadSendCallback {
    fn clone(&self) -> Self {
        Self { cb: self.cb }
    }
}

impl PartialEq for ThreadSendCallback {
    fn eq(&self, other: &Self) -> bool {
        self.cb as usize == other.cb as usize
    }
}

impl Eq for ThreadSendCallback {}

impl PartialOrd for ThreadSendCallback {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ThreadSendCallback {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        (self.cb as usize).cmp(&(other.cb as usize))
    }
}

/// Destructor callback for ThreadSender
pub type ThreadSenderDestructorCallbackType = extern "C" fn(*mut ThreadSenderInner);

#[repr(C)]
pub struct ThreadSenderDestructorCallback {
    pub cb: ThreadSenderDestructorCallbackType,
}

impl core::fmt::Debug for ThreadSenderDestructorCallback {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(
            f,
            "ThreadSenderDestructorCallback {{ cb: {:p} }}",
            self.cb as *const ()
        )
    }
}

impl Clone for ThreadSenderDestructorCallback {
    fn clone(&self) -> Self {
        Self { cb: self.cb }
    }
}

impl PartialEq for ThreadSenderDestructorCallback {
    fn eq(&self, other: &Self) -> bool {
        self.cb as usize == other.cb as usize
    }
}

impl Eq for ThreadSenderDestructorCallback {}

impl PartialOrd for ThreadSenderDestructorCallback {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ThreadSenderDestructorCallback {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        (self.cb as usize).cmp(&(other.cb as usize))
    }
}

/// Callback that runs when a thread receives a `WriteBack` message
///
/// This callback runs on the main UI thread and has access dir_to:
/// - The thread's original data
/// - Data sent back from the background thread
/// - Full CallbackInfo for DOM queries and UI updates
pub type WriteBackCallbackType = extern "C" fn(
    /* original thread data */ RefAny,
    /* data to write back */ RefAny,
    /* callback info */ CallbackInfo,
) -> Update;

/// Callback that can run when a thread receives a `WriteBack` message
#[repr(C)]
pub struct WriteBackCallback {
    pub cb: WriteBackCallbackType,
    /// For FFI: stores the foreign callable (e.g., PyFunction)
    /// Native Rust code sets this to None
    pub ctx: OptionRefAny,
}

impl WriteBackCallback {
    /// Create a new WriteBackCallback
    pub fn new(cb: WriteBackCallbackType) -> Self {
        Self {
            cb,
            ctx: OptionRefAny::None,
        }
    }

    /// Invoke the callback
    pub fn invoke(
        &self,
        thread_data: RefAny,
        writeback_data: RefAny,
        callback_info: CallbackInfo,
    ) -> Update {
        (self.cb)(thread_data, writeback_data, callback_info)
    }
}

impl core::fmt::Debug for WriteBackCallback {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(f, "WriteBackCallback {{ cb: {:p} }}", self.cb as *const ())
    }
}

impl Clone for WriteBackCallback {
    fn clone(&self) -> Self {
        Self {
            cb: self.cb,
            ctx: self.ctx.clone(),
        }
    }
}

impl From<WriteBackCallbackType> for WriteBackCallback {
    fn from(cb: WriteBackCallbackType) -> Self {
        Self {
            cb,
            ctx: OptionRefAny::None,
        }
    }
}

impl PartialEq for WriteBackCallback {
    fn eq(&self, other: &Self) -> bool {
        self.cb as usize == other.cb as usize
    }
}

impl Eq for WriteBackCallback {}

impl PartialOrd for WriteBackCallback {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        (self.cb as usize).partial_cmp(&(other.cb as usize))
    }
}

impl Ord for WriteBackCallback {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        (self.cb as usize).cmp(&(other.cb as usize))
    }
}

impl core::hash::Hash for WriteBackCallback {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        (self.cb as usize).hash(state);
    }
}

// ThreadCallback type
pub type ThreadCallbackType = extern "C" fn(RefAny, ThreadSender, ThreadReceiver);

#[repr(C)]
pub struct ThreadCallback {
    pub cb: ThreadCallbackType,
    /// For FFI: stores the foreign callable (e.g., PyFunction)
    /// Native Rust code sets this to None
    pub ctx: OptionRefAny,
}

impl ThreadCallback {
    /// Create a new ThreadCallback
    pub fn new(cb: ThreadCallbackType) -> Self {
        Self {
            cb,
            ctx: OptionRefAny::None,
        }
    }
}

impl core::fmt::Debug for ThreadCallback {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(f, "ThreadCallback {{ cb: {:p} }}", self.cb as *const ())
    }
}

impl Clone for ThreadCallback {
    fn clone(&self) -> Self {
        Self {
            cb: self.cb,
            ctx: self.ctx.clone(),
        }
    }
}

impl From<ThreadCallbackType> for ThreadCallback {
    fn from(cb: ThreadCallbackType) -> Self {
        Self {
            cb,
            ctx: OptionRefAny::None,
        }
    }
}

impl PartialEq for ThreadCallback {
    fn eq(&self, other: &Self) -> bool {
        self.cb as usize == other.cb as usize
    }
}

impl Eq for ThreadCallback {}

impl PartialOrd for ThreadCallback {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        (self.cb as usize).partial_cmp(&(other.cb as usize))
    }
}

impl Ord for ThreadCallback {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        (self.cb as usize).cmp(&(other.cb as usize))
    }
}

impl core::hash::Hash for ThreadCallback {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        (self.cb as usize).hash(state);
    }
}

pub type LibraryReceiveThreadMsgCallbackType =
    extern "C" fn(*const core::ffi::c_void) -> OptionThreadReceiveMsg;

#[repr(C)]
pub struct LibraryReceiveThreadMsgCallback {
    pub cb: LibraryReceiveThreadMsgCallbackType,
}

impl core::fmt::Debug for LibraryReceiveThreadMsgCallback {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(
            f,
            "LibraryReceiveThreadMsgCallback {{ cb: {:p} }}",
            self.cb as *const ()
        )
    }
}

impl Clone for LibraryReceiveThreadMsgCallback {
    fn clone(&self) -> Self {
        Self { cb: self.cb }
    }
}

pub type ThreadDestructorCallbackType = extern "C" fn(*mut ThreadInner);

#[repr(C)]
pub struct ThreadDestructorCallback {
    pub cb: ThreadDestructorCallbackType,
}

impl core::fmt::Debug for ThreadDestructorCallback {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(
            f,
            "ThreadDestructorCallback {{ cb: {:p} }}",
            self.cb as *const ()
        )
    }
}

impl Clone for ThreadDestructorCallback {
    fn clone(&self) -> Self {
        Self { cb: self.cb }
    }
}

/// Wrapper around Thread because Thread needs to be clone-able
#[derive(Debug)]
#[repr(C)]
pub struct Thread {
    #[cfg(feature = "std")]
    pub ptr: alloc::boxed::Box<Arc<Mutex<ThreadInner>>>,
    #[cfg(not(feature = "std"))]
    pub ptr: *const core::ffi::c_void,
    pub run_destructor: bool,
}

impl Clone for Thread {
    fn clone(&self) -> Self {
        Self {
            ptr: self.ptr.clone(),
            run_destructor: true,
        }
    }
}

impl Drop for Thread {
    fn drop(&mut self) {
        self.run_destructor = false;
    }
}

impl Thread {
    #[cfg(feature = "std")]
    pub fn new(ti: ThreadInner) -> Self {
        Self {
            ptr: alloc::boxed::Box::new(Arc::new(Mutex::new(ti))),
            run_destructor: true,
        }
    }

    #[cfg(not(feature = "std"))]
    pub fn new(_ti: ThreadInner) -> Self {
        Self {
            ptr: core::ptr::null(),
            run_destructor: false,
        }
    }

    /// Creates a new thread that will execute the given callback function.
    ///
    /// # Arguments
    /// * `thread_initialize_data` - Data passed to the callback when the thread starts
    /// * `writeback_data` - Data that will be passed back when writeback messages are received
    /// * `callback` - The callback to execute in the background thread
    ///
    /// # Returns
    /// A new Thread handle that can be added to the event loop with `CallbackInfo::add_thread`
    pub fn create<C: Into<ThreadCallback>>(
        thread_initialize_data: RefAny,
        writeback_data: RefAny,
        callback: C,
    ) -> Self {
        create_thread_libstd(thread_initialize_data, writeback_data, callback.into())
    }
}

/// A `Thread` is a separate thread that is owned by the framework.
///
/// In difference to a regular thread, you don't have to `await()` the result,
/// you can just hand the Thread to the framework and it will automatically
/// update the UI when the Thread is finished.
#[derive(Debug)]
#[repr(C)]
pub struct ThreadInner {
    #[cfg(feature = "std")]
    pub thread_handle: alloc::boxed::Box<Option<JoinHandle<()>>>,
    #[cfg(not(feature = "std"))]
    pub thread_handle: *const core::ffi::c_void,

    #[cfg(feature = "std")]
    pub sender: alloc::boxed::Box<Sender<ThreadSendMsg>>,
    #[cfg(not(feature = "std"))]
    pub sender: *const core::ffi::c_void,

    #[cfg(feature = "std")]
    pub receiver: alloc::boxed::Box<Receiver<ThreadReceiveMsg>>,
    #[cfg(not(feature = "std"))]
    pub receiver: *const core::ffi::c_void,

    #[cfg(feature = "std")]
    pub dropcheck: alloc::boxed::Box<alloc::sync::Weak<()>>,
    #[cfg(not(feature = "std"))]
    pub dropcheck: *const core::ffi::c_void,

    pub writeback_data: RefAny,
    pub check_thread_finished_fn: CheckThreadFinishedCallback,
    pub send_thread_msg_fn: LibrarySendThreadMsgCallback,
    pub receive_thread_msg_fn: LibraryReceiveThreadMsgCallback,
    pub thread_destructor_fn: ThreadDestructorCallback,
}

#[cfg(feature = "std")]
impl ThreadInner {
    /// Returns true if the Thread has been finished, false otherwise
    pub fn is_finished(&self) -> bool {
        (self.check_thread_finished_fn.cb)(
            self.dropcheck.as_ref() as *const _ as *const core::ffi::c_void
        )
    }

    /// Send a message to the thread
    pub fn sender_send(&mut self, msg: ThreadSendMsg) -> bool {
        (self.send_thread_msg_fn.cb)(
            self.sender.as_ref() as *const _ as *const core::ffi::c_void,
            msg,
        )
    }

    /// Try to receive a message from the thread (non-blocking)
    pub fn receiver_try_recv(&mut self) -> OptionThreadReceiveMsg {
        (self.receive_thread_msg_fn.cb)(
            self.receiver.as_ref() as *const _ as *const core::ffi::c_void
        )
    }
}

#[cfg(not(feature = "std"))]
impl ThreadInner {
    /// Returns true if the Thread has been finished, false otherwise
    pub fn is_finished(&self) -> bool {
        true
    }

    /// Send a message to the thread (no-op in no_std)
    pub fn sender_send(&mut self, _msg: ThreadSendMsg) -> bool {
        false
    }

    /// Try to receive a message from the thread (always returns None in no_std)
    pub fn receiver_try_recv(&mut self) -> OptionThreadReceiveMsg {
        None.into()
    }
}

impl Drop for ThreadInner {
    fn drop(&mut self) {
        (self.thread_destructor_fn.cb)(self);
    }
}

// Default callback implementations for std
#[cfg(feature = "std")]
extern "C" fn default_thread_destructor_fn(thread: *mut ThreadInner) {
    let thread = unsafe { &mut *thread };

    if let Some(thread_handle) = thread.thread_handle.take() {
        let _ = thread.sender.send(ThreadSendMsg::TerminateThread);
        let _ = thread_handle.join(); // ignore the result, don't panic
    }
}

#[cfg(not(feature = "std"))]
extern "C" fn default_thread_destructor_fn(_thread: *mut ThreadInner) {}

#[cfg(feature = "std")]
extern "C" fn library_send_thread_msg_fn(
    sender: *const core::ffi::c_void,
    msg: ThreadSendMsg,
) -> bool {
    unsafe { &*(sender as *const Sender<ThreadSendMsg>) }
        .send(msg)
        .is_ok()
}

#[cfg(not(feature = "std"))]
extern "C" fn library_send_thread_msg_fn(
    _sender: *const core::ffi::c_void,
    _msg: ThreadSendMsg,
) -> bool {
    false
}

#[cfg(feature = "std")]
extern "C" fn library_receive_thread_msg_fn(
    receiver: *const core::ffi::c_void,
) -> OptionThreadReceiveMsg {
    unsafe { &*(receiver as *const Receiver<ThreadReceiveMsg>) }
        .try_recv()
        .ok()
        .into()
}

#[cfg(not(feature = "std"))]
extern "C" fn library_receive_thread_msg_fn(
    _receiver: *const core::ffi::c_void,
) -> OptionThreadReceiveMsg {
    None.into()
}

#[cfg(feature = "std")]
extern "C" fn default_send_thread_msg_fn(
    sender: *const core::ffi::c_void,
    msg: ThreadReceiveMsg,
) -> bool {
    unsafe { &*(sender as *const Sender<ThreadReceiveMsg>) }
        .send(msg)
        .is_ok()
}

#[cfg(not(feature = "std"))]
extern "C" fn default_send_thread_msg_fn(
    _sender: *const core::ffi::c_void,
    _msg: ThreadReceiveMsg,
) -> bool {
    false
}

#[cfg(feature = "std")]
extern "C" fn default_receive_thread_msg_fn(
    receiver: *const core::ffi::c_void,
) -> OptionThreadSendMsg {
    unsafe { &*(receiver as *const Receiver<ThreadSendMsg>) }
        .try_recv()
        .ok()
        .into()
}

#[cfg(not(feature = "std"))]
extern "C" fn default_receive_thread_msg_fn(
    _receiver: *const core::ffi::c_void,
) -> OptionThreadSendMsg {
    None.into()
}

#[cfg(feature = "std")]
extern "C" fn default_check_thread_finished(dropcheck: *const core::ffi::c_void) -> bool {
    let weak = unsafe { &*(dropcheck as *const alloc::sync::Weak<()>) };
    weak.upgrade().is_none()
}

#[cfg(not(feature = "std"))]
extern "C" fn default_check_thread_finished(_dropcheck: *const core::ffi::c_void) -> bool {
    true
}

#[cfg(feature = "std")]
extern "C" fn thread_sender_drop(_: *mut ThreadSenderInner) {}

#[cfg(not(feature = "std"))]
extern "C" fn thread_sender_drop(_: *mut ThreadSenderInner) {}

#[cfg(feature = "std")]
extern "C" fn thread_receiver_drop(_: *mut ThreadReceiverInner) {}

#[cfg(not(feature = "std"))]
extern "C" fn thread_receiver_drop(_: *mut ThreadReceiverInner) {}

/// Function that creates a new Thread object
pub type CreateThreadCallbackType = extern "C" fn(RefAny, RefAny, ThreadCallback) -> Thread;

#[repr(C)]
pub struct CreateThreadCallback {
    pub cb: CreateThreadCallbackType,
}

impl core::fmt::Debug for CreateThreadCallback {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(
            f,
            "CreateThreadCallback {{ cb: {:p} }}",
            self.cb as *const ()
        )
    }
}

impl Clone for CreateThreadCallback {
    fn clone(&self) -> Self {
        Self { cb: self.cb }
    }
}

impl Copy for CreateThreadCallback {}

impl PartialEq for CreateThreadCallback {
    fn eq(&self, other: &Self) -> bool {
        self.cb as usize == other.cb as usize
    }
}

impl Eq for CreateThreadCallback {}

impl PartialOrd for CreateThreadCallback {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        (self.cb as usize).partial_cmp(&(other.cb as usize))
    }
}

impl Ord for CreateThreadCallback {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        (self.cb as usize).cmp(&(other.cb as usize))
    }
}

impl core::hash::Hash for CreateThreadCallback {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        (self.cb as usize).hash(state);
    }
}

/// Create a new thread using the standard library
#[cfg(feature = "std")]
pub extern "C" fn create_thread_libstd(
    thread_initialize_data: RefAny,
    writeback_data: RefAny,
    callback: ThreadCallback,
) -> Thread {
    let (sender_receiver, receiver_receiver) = channel::<ThreadReceiveMsg>();
    let mut sender_receiver = ThreadSender::new(ThreadSenderInner {
        ptr: alloc::boxed::Box::new(sender_receiver),
        send_fn: ThreadSendCallback {
            cb: default_send_thread_msg_fn,
        },
        destructor: ThreadSenderDestructorCallback {
            cb: thread_sender_drop,
        },
    });
    // Set the ctx from the callback for FFI
    sender_receiver.ctx = callback.ctx.clone();

    let (sender_sender, receiver_sender) = channel::<ThreadSendMsg>();
    let mut receiver_sender = ThreadReceiver::new(ThreadReceiverInner {
        ptr: alloc::boxed::Box::new(receiver_sender),
        recv_fn: ThreadRecvCallback {
            cb: default_receive_thread_msg_fn,
        },
        destructor: ThreadReceiverDestructorCallback {
            cb: thread_receiver_drop,
        },
    });
    // Set the ctx from the callback for FFI
    receiver_sender.ctx = callback.ctx.clone();

    let thread_check = Arc::new(());
    let dropcheck = Arc::downgrade(&thread_check);

    let thread_handle = Some(thread::spawn(move || {
        // Keep thread_check alive for the entire duration of the thread
        // by binding it to a named variable (not `_` which drops immediately)
        let _thread_check_guard = thread_check;
        (callback.cb)(thread_initialize_data, sender_receiver, receiver_sender);
        // _thread_check_guard gets dropped here, signals that the thread has finished
    }));

    let thread_handle: alloc::boxed::Box<Option<JoinHandle<()>>> =
        alloc::boxed::Box::new(thread_handle);
    let sender: alloc::boxed::Box<Sender<ThreadSendMsg>> = alloc::boxed::Box::new(sender_sender);
    let receiver: alloc::boxed::Box<Receiver<ThreadReceiveMsg>> =
        alloc::boxed::Box::new(receiver_receiver);
    let dropcheck: alloc::boxed::Box<alloc::sync::Weak<()>> = alloc::boxed::Box::new(dropcheck);

    Thread::new(ThreadInner {
        thread_handle,
        sender,
        receiver,
        writeback_data,
        dropcheck,
        thread_destructor_fn: ThreadDestructorCallback {
            cb: default_thread_destructor_fn,
        },
        check_thread_finished_fn: CheckThreadFinishedCallback {
            cb: default_check_thread_finished,
        },
        send_thread_msg_fn: LibrarySendThreadMsgCallback {
            cb: library_send_thread_msg_fn,
        },
        receive_thread_msg_fn: LibraryReceiveThreadMsgCallback {
            cb: library_receive_thread_msg_fn,
        },
    })
}

#[cfg(not(feature = "std"))]
pub extern "C" fn create_thread_libstd(
    _thread_initialize_data: RefAny,
    _writeback_data: RefAny,
    _callback: ThreadCallback,
) -> Thread {
    Thread {
        ptr: core::ptr::null(),
        run_destructor: false,
    }
}

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

    extern "C" fn test_writeback_callback(
        _thread_data: RefAny,
        _writeback_data: RefAny,
        _callback_info: CallbackInfo,
    ) -> Update {
        Update::DoNothing
    }

    #[test]
    fn test_writeback_callback_creation() {
        let callback = WriteBackCallback::new(test_writeback_callback);
        assert_eq!(callback.cb as usize, test_writeback_callback as usize);
    }

    #[test]
    fn test_writeback_callback_clone() {
        let callback = WriteBackCallback::new(test_writeback_callback);
        let cloned = callback.clone();
        assert_eq!(callback, cloned);
    }
}

/// Optional Thread type for API compatibility
#[derive(Debug, Clone)]
#[repr(C, u8)]
pub enum OptionThread {
    None,
    Some(Thread),
}

impl From<Option<Thread>> for OptionThread {
    fn from(o: Option<Thread>) -> Self {
        match o {
            None => OptionThread::None,
            Some(t) => OptionThread::Some(t),
        }
    }
}

impl OptionThread {
    pub fn into_option(self) -> Option<Thread> {
        match self {
            OptionThread::None => None,
            OptionThread::Some(t) => Some(t),
        }
    }
}

// ============================================================================
// Sleep utilities
// ============================================================================

/// Sleeps the current thread for the specified number of milliseconds.
///
/// This is a cross-platform utility that can be called from C/C++/Python.
///
/// # Arguments
/// * `milliseconds` - Number of milliseconds to sleep
#[cfg(feature = "std")]
pub fn thread_sleep_ms(milliseconds: u64) -> azul_css::corety::Void {
    std::thread::sleep(std::time::Duration::from_millis(milliseconds));
    azul_css::corety::Void::new()
}

/// Sleeps the current thread for the specified number of milliseconds (no-op on no_std).
#[cfg(not(feature = "std"))]
pub fn thread_sleep_ms(_milliseconds: u64) -> azul_css::corety::Void {
    // No-op on no_std - can't sleep without OS
    azul_css::corety::Void::new()
}

/// Sleeps the current thread for the specified number of microseconds.
///
/// # Arguments
/// * `microseconds` - Number of microseconds to sleep
#[cfg(feature = "std")]
pub fn thread_sleep_us(microseconds: u64) -> azul_css::corety::Void {
    std::thread::sleep(std::time::Duration::from_micros(microseconds));
    azul_css::corety::Void::new()
}

/// Sleeps the current thread for the specified number of microseconds (no-op on no_std).
#[cfg(not(feature = "std"))]
pub fn thread_sleep_us(_microseconds: u64) -> azul_css::corety::Void {
    // No-op on no_std - can't sleep without OS
    azul_css::corety::Void::new()
}

/// Sleeps the current thread for the specified number of nanoseconds.
///
/// # Arguments
/// * `nanoseconds` - Number of nanoseconds to sleep
#[cfg(feature = "std")]
pub fn thread_sleep_ns(nanoseconds: u64) -> azul_css::corety::Void {
    std::thread::sleep(std::time::Duration::from_nanos(nanoseconds));
    azul_css::corety::Void::new()
}

/// Sleeps the current thread for the specified number of nanoseconds (no-op on no_std).
#[cfg(not(feature = "std"))]
pub fn thread_sleep_ns(_nanoseconds: u64) -> azul_css::corety::Void {
    // No-op on no_std - can't sleep without OS
    azul_css::corety::Void::new()
}