1
//! Thread callback information and utilities for azul-layout
2
//!
3
//! This module provides thread-related callback structures for background tasks
4
//! that need to interact with the UI thread and query layout information.
5

            
6
#[cfg(feature = "std")]
7
use alloc::sync::Arc;
8
#[cfg(feature = "std")]
9
use std::sync::{
10
    mpsc::{channel, Receiver, Sender},
11
    Mutex,
12
};
13
#[cfg(feature = "std")]
14
use std::thread::{self, JoinHandle};
15

            
16
use azul_core::{
17
    callbacks::Update,
18
    refany::{OptionRefAny, RefAny},
19
    task::{
20
        CheckThreadFinishedCallback, CheckThreadFinishedCallbackType, LibrarySendThreadMsgCallback,
21
        LibrarySendThreadMsgCallbackType, OptionThreadSendMsg, ThreadId, ThreadReceiver,
22
        ThreadReceiverDestructorCallback, ThreadReceiverInner, ThreadRecvCallback, ThreadSendMsg,
23
    },
24
};
25

            
26
use azul_css::{impl_option, impl_option_inner};
27

            
28
use crate::callbacks::CallbackInfo;
29

            
30
macro_rules! impl_callback_traits {
31
    ($name:ident) => {
32
        impl core::fmt::Debug for $name {
33
1
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
34
1
                write!(
35
1
                    f,
36
1
                    concat!(stringify!($name), " {{ cb: {:p} }}"),
37
1
                    self.cb as *const ()
38
                )
39
1
            }
40
        }
41
        // generated for both Copy and non-Copy callback structs; the explicit field
42
        // copy works uniformly (a derive can't be emitted for an externally-defined struct).
43
        #[allow(clippy::expl_impl_clone_on_copy, clippy::non_canonical_clone_impl)]
44
        impl Clone for $name {
45
1
            fn clone(&self) -> Self {
46
1
                Self { cb: self.cb }
47
1
            }
48
        }
49
        impl PartialEq for $name {
50
1
            fn eq(&self, other: &Self) -> bool {
51
1
                self.cb as *const () as usize == other.cb as *const () as usize
52
1
            }
53
        }
54
        impl Eq for $name {}
55
        impl PartialOrd for $name {
56
            fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
57
                Some(self.cmp(other))
58
            }
59
        }
60
        impl Ord for $name {
61
1
            fn cmp(&self, other: &Self) -> core::cmp::Ordering {
62
1
                (self.cb as *const () as usize).cmp(&(other.cb as *const () as usize))
63
1
            }
64
        }
65
        impl core::hash::Hash for $name {
66
2
            fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
67
2
                (self.cb as *const () as usize).hash(state);
68
2
            }
69
        }
70
    };
71
}
72

            
73
// Types that need to be defined locally (not in azul-core)
74
#[allow(variant_size_differences)]
75
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
76
// disparity accepted
77
/// Message that is sent back from the running thread to the main thread
78
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
79
#[repr(C, u8)]
80
pub enum ThreadReceiveMsg {
81
    WriteBack(ThreadWriteBackMsg),
82
    Update(Update),
83
}
84
#[allow(variant_size_differences)]
85
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
86
// disparity accepted
87
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
88
#[repr(C, u8)]
89
pub enum OptionThreadReceiveMsg {
90
    None,
91
    Some(ThreadReceiveMsg),
92
}
93

            
94
impl From<Option<ThreadReceiveMsg>> for OptionThreadReceiveMsg {
95
23
    fn from(inner: Option<ThreadReceiveMsg>) -> Self {
96
23
        inner.map_or_else(|| Self::None, Self::Some)
97
23
    }
98
}
99

            
100
impl OptionThreadReceiveMsg {
101
    #[must_use]
102
7
    pub fn into_option(self) -> Option<ThreadReceiveMsg> {
103
7
        match self {
104
2
            Self::None => None,
105
5
            Self::Some(v) => Some(v),
106
        }
107
7
    }
108

            
109
    #[must_use]
110
5
    pub const fn as_ref(&self) -> Option<&ThreadReceiveMsg> {
111
5
        match self {
112
1
            Self::None => None,
113
4
            Self::Some(v) => Some(v),
114
        }
115
5
    }
116
}
117

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

            
126
impl ThreadWriteBackMsg {
127
42
    pub fn new<C: Into<WriteBackCallback>>(callback: C, data: RefAny) -> Self {
128
42
        Self {
129
42
            refany: data,
130
42
            callback: callback.into(),
131
42
        }
132
42
    }
133
}
134

            
135
/// `ThreadSender` allows sending messages from the background thread to the main thread
136
#[derive(Debug)]
137
#[repr(C)]
138
pub struct ThreadSender {
139
    #[cfg(feature = "std")]
140
    pub ptr: Box<Arc<Mutex<ThreadSenderInner>>>,
141
    #[cfg(not(feature = "std"))]
142
    pub ptr: *const core::ffi::c_void,
143
    pub run_destructor: bool,
144
    /// For FFI: stores the foreign callable (e.g., `PyFunction`)
145
    pub ctx: OptionRefAny,
146
}
147

            
148
impl Clone for ThreadSender {
149
1
    fn clone(&self) -> Self {
150
1
        Self {
151
1
            ptr: self.ptr.clone(),
152
1
            run_destructor: true,
153
1
            ctx: self.ctx.clone(),
154
1
        }
155
1
    }
156
}
157

            
158
impl Drop for ThreadSender {
159
80
    fn drop(&mut self) {
160
80
        self.run_destructor = false;
161
80
    }
162
}
163

            
164
impl ThreadSender {
165
    #[cfg(not(feature = "std"))]
166
    pub fn new(_t: ThreadSenderInner) -> Self {
167
        Self {
168
            ptr: core::ptr::null(),
169
            run_destructor: false,
170
            ctx: OptionRefAny::None,
171
        }
172
    }
173

            
174
    #[cfg(feature = "std")]
175
    #[must_use]
176
79
    pub fn new(t: ThreadSenderInner) -> Self {
177
79
        Self {
178
79
            ptr: Box::new(Arc::new(Mutex::new(t))),
179
79
            run_destructor: true,
180
79
            ctx: OptionRefAny::None,
181
79
        }
182
79
    }
183

            
184
    /// Get the FFI context (e.g., Python callable)
185
    #[must_use]
186
4
    pub fn get_ctx(&self) -> OptionRefAny {
187
4
        self.ctx.clone()
188
4
    }
189

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

            
195
    #[cfg(feature = "std")]
196
49
    pub fn send(&mut self, msg: ThreadReceiveMsg) -> bool {
197
49
        let Some(ts) = self.ptr.lock().ok() else {
198
1
            return false;
199
        };
200
48
        (ts.send_fn.cb)(
201
48
            std::ptr::from_ref(ts.ptr.as_ref()).cast::<core::ffi::c_void>(),
202
48
            msg,
203
48
        )
204
49
    }
205
}
206

            
207
/// Inner state of a `ThreadSender`, holding the channel sender and associated callbacks
208
#[derive(Debug)]
209
#[cfg_attr(not(feature = "std"), derive(PartialEq, PartialOrd, Eq, Ord))]
210
#[repr(C)]
211
pub struct ThreadSenderInner {
212
    #[cfg(feature = "std")]
213
    pub ptr: Box<Sender<ThreadReceiveMsg>>,
214
    #[cfg(not(feature = "std"))]
215
    pub ptr: *const core::ffi::c_void,
216
    pub send_fn: ThreadSendCallback,
217
    pub destructor: ThreadSenderDestructorCallback,
218
}
219

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

            
223
#[cfg(feature = "std")]
224
impl core::hash::Hash for ThreadSenderInner {
225
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
226
        (std::ptr::from_ref(self.ptr.as_ref()) as usize).hash(state);
227
    }
228
}
229

            
230
#[cfg(feature = "std")]
231
impl PartialEq for ThreadSenderInner {
232
    fn eq(&self, other: &Self) -> bool {
233
        std::ptr::eq(self.ptr.as_ref(), other.ptr.as_ref())
234
    }
235
}
236

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

            
240
#[cfg(feature = "std")]
241
impl PartialOrd for ThreadSenderInner {
242
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
243
        Some(self.cmp(other))
244
    }
245
}
246

            
247
#[cfg(feature = "std")]
248
impl Ord for ThreadSenderInner {
249
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
250
        (std::ptr::from_ref(self.ptr.as_ref()) as usize)
251
            .cmp(&(std::ptr::from_ref(other.ptr.as_ref()) as usize))
252
    }
253
}
254

            
255
impl Drop for ThreadSenderInner {
256
79
    fn drop(&mut self) {
257
79
        (self.destructor.cb)(self);
258
79
    }
259
}
260

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

            
264
#[allow(missing_copy_implementations)]
265
// C-ABI fn-ptr wrapper; Clone is macro-generated (impl_callback_traits!), so Copy would trip
266
// expl_impl_clone_on_copy
267
#[repr(C)]
268
pub struct ThreadSendCallback {
269
    pub cb: ThreadSendCallbackType,
270
}
271

            
272
impl_callback_traits!(ThreadSendCallback);
273

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

            
277
#[allow(missing_copy_implementations)]
278
// C-ABI fn-ptr wrapper; Clone is macro-generated (impl_callback_traits!), so Copy would trip
279
// expl_impl_clone_on_copy
280
#[repr(C)]
281
pub struct ThreadSenderDestructorCallback {
282
    pub cb: ThreadSenderDestructorCallbackType,
283
}
284

            
285
impl_callback_traits!(ThreadSenderDestructorCallback);
286

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

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

            
308
impl WriteBackCallback {
309
    /// Create a new `WriteBackCallback`
310
41
    pub fn new(cb: WriteBackCallbackType) -> Self {
311
41
        Self {
312
41
            cb,
313
41
            ctx: OptionRefAny::None,
314
41
        }
315
41
    }
316

            
317
    /// Invoke the callback
318
    #[must_use]
319
5
    pub fn invoke(
320
5
        &self,
321
5
        thread_data: RefAny,
322
5
        writeback_data: RefAny,
323
5
        callback_info: CallbackInfo,
324
5
    ) -> Update {
325
5
        (self.cb)(thread_data, writeback_data, callback_info)
326
5
    }
327
}
328

            
329
impl core::fmt::Debug for WriteBackCallback {
330
1
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
331
1
        write!(f, "WriteBackCallback {{ cb: {:p} }}", self.cb as *const ())
332
1
    }
333
}
334

            
335
impl Clone for WriteBackCallback {
336
6
    fn clone(&self) -> Self {
337
6
        Self {
338
6
            cb: self.cb,
339
6
            ctx: self.ctx.clone(),
340
6
        }
341
6
    }
342
}
343

            
344
impl From<WriteBackCallbackType> for WriteBackCallback {
345
11
    fn from(cb: WriteBackCallbackType) -> Self {
346
11
        Self {
347
11
            cb,
348
11
            ctx: OptionRefAny::None,
349
11
        }
350
11
    }
351
}
352

            
353
impl PartialEq for WriteBackCallback {
354
9
    fn eq(&self, other: &Self) -> bool {
355
9
        std::ptr::eq(self.cb as *const (), other.cb as *const ())
356
9
    }
357
}
358

            
359
impl Eq for WriteBackCallback {}
360

            
361
impl PartialOrd for WriteBackCallback {
362
3
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
363
3
        Some(self.cmp(other))
364
3
    }
365
}
366

            
367
impl Ord for WriteBackCallback {
368
5
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
369
5
        (self.cb as *const () as usize).cmp(&(other.cb as *const () as usize))
370
5
    }
371
}
372

            
373
impl core::hash::Hash for WriteBackCallback {
374
4
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
375
4
        (self.cb as *const () as usize).hash(state);
376
4
    }
377
}
378

            
379
/// Callback type for the function that runs in the background thread
380
pub type ThreadCallbackType = extern "C" fn(RefAny, ThreadSender, ThreadReceiver);
381

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

            
390
impl ThreadCallback {
391
    /// Create a new `ThreadCallback`
392
28
    pub fn new(cb: ThreadCallbackType) -> Self {
393
28
        Self {
394
28
            cb,
395
28
            ctx: OptionRefAny::None,
396
28
        }
397
28
    }
398
}
399

            
400
impl core::fmt::Debug for ThreadCallback {
401
1
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
402
1
        write!(f, "ThreadCallback {{ cb: {:p} }}", self.cb as *const ())
403
1
    }
404
}
405

            
406
impl Clone for ThreadCallback {
407
30
    fn clone(&self) -> Self {
408
30
        Self {
409
30
            cb: self.cb,
410
30
            ctx: self.ctx.clone(),
411
30
        }
412
30
    }
413
}
414

            
415
impl From<ThreadCallbackType> for ThreadCallback {
416
10
    fn from(cb: ThreadCallbackType) -> Self {
417
10
        Self {
418
10
            cb,
419
10
            ctx: OptionRefAny::None,
420
10
        }
421
10
    }
422
}
423

            
424
impl PartialEq for ThreadCallback {
425
3
    fn eq(&self, other: &Self) -> bool {
426
3
        std::ptr::eq(self.cb as *const (), other.cb as *const ())
427
3
    }
428
}
429

            
430
impl Eq for ThreadCallback {}
431

            
432
impl PartialOrd for ThreadCallback {
433
2
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
434
2
        Some(self.cmp(other))
435
2
    }
436
}
437

            
438
impl Ord for ThreadCallback {
439
2
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
440
2
        (self.cb as *const () as usize).cmp(&(other.cb as *const () as usize))
441
2
    }
442
}
443

            
444
impl core::hash::Hash for ThreadCallback {
445
2
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
446
2
        (self.cb as *const () as usize).hash(state);
447
2
    }
448
}
449

            
450
// Host-invoker plumbing for ThreadCallback. NOTE: this callback fires
451
// on a worker thread (spawned by `Thread::create`), not the main
452
// `App.run` thread. The per-language host-invoker thunk MUST acquire
453
// the host VM lock before dispatching to user code:
454
//   * CPython: PyGILState_Ensure / _Release
455
//   * MRI Ruby: rb_thread_call_with_gvl
456
//   * OpenJDK: AttachCurrentThread / DetachCurrentThread
457
//   * CLR / .NET: nothing ([UnmanagedCallersOnly] auto-trampolines)
458
//   * OCaml: caml_acquire_runtime_system / _release
459
//   * Lua / Perl / PHP / Pharo: cannot be called from worker thread (single-threaded interpreter) —
460
//     fall back to writeback-only pattern (Rust extern "C" cb on worker, host fn on main via
461
//     WriteBackCallback).
462
// Each VM has its own lock-acquire call: PyGILState_Ensure,
463
// rb_thread_call_with_gvl, AttachCurrentThread, and so on.
464
azul_core::impl_managed_callback! {
465
    wrapper:        ThreadCallback,
466
    info_ty:        ThreadSender,
467
    return_ty:      (),
468
    // unit default-return; written via Default::default() so clippy's unused_unit
469
    // doesn't fire on a bare `()` in this macro-argument position.
470
    default_ret:    Default::default(),
471
    invoker_static: THREAD_CALLBACK_INVOKER,
472
    invoker_ty:     AzThreadCallbackInvoker,
473
    thunk_fn:       az_thread_callback_thunk,
474
    setter_fn:      AzApp_setThreadCallbackInvoker,
475
    from_handle_fn: AzThreadCallback_createFromHostHandle,
476
    extra_args:     [receiver: ThreadReceiver],
477
}
478

            
479
/// Callback type for receiving messages from a background thread
480
pub type LibraryReceiveThreadMsgCallbackType =
481
    extern "C" fn(*const core::ffi::c_void) -> OptionThreadReceiveMsg;
482

            
483
#[allow(missing_copy_implementations)]
484
// C-ABI fn-ptr wrapper; Clone is macro-generated (impl_callback_traits!), so Copy would trip
485
// expl_impl_clone_on_copy
486
#[repr(C)]
487
pub struct LibraryReceiveThreadMsgCallback {
488
    pub cb: LibraryReceiveThreadMsgCallbackType,
489
}
490

            
491
impl_callback_traits!(LibraryReceiveThreadMsgCallback);
492

            
493
/// Callback type for the destructor that cleans up a `ThreadInner`
494
pub type ThreadDestructorCallbackType = extern "C" fn(*mut ThreadInner);
495

            
496
#[allow(missing_copy_implementations)]
497
// C-ABI fn-ptr wrapper; Clone is macro-generated (impl_callback_traits!), so Copy would trip
498
// expl_impl_clone_on_copy
499
#[repr(C)]
500
pub struct ThreadDestructorCallback {
501
    pub cb: ThreadDestructorCallbackType,
502
}
503

            
504
impl_callback_traits!(ThreadDestructorCallback);
505

            
506
/// Wrapper around Thread because Thread needs to be clone-able
507
#[derive(Debug)]
508
#[repr(C)]
509
pub struct Thread {
510
    #[cfg(feature = "std")]
511
    pub ptr: Box<Arc<Mutex<ThreadInner>>>,
512
    #[cfg(not(feature = "std"))]
513
    pub ptr: *const core::ffi::c_void,
514
    pub run_destructor: bool,
515
}
516

            
517
impl Clone for Thread {
518
1
    fn clone(&self) -> Self {
519
1
        Self {
520
1
            ptr: self.ptr.clone(),
521
1
            run_destructor: true,
522
1
        }
523
1
    }
524
}
525

            
526
impl Drop for Thread {
527
48
    fn drop(&mut self) {
528
48
        self.run_destructor = false;
529
48
    }
530
}
531

            
532
impl Thread {
533
    #[cfg(feature = "std")]
534
    #[must_use]
535
47
    pub fn new(ti: ThreadInner) -> Self {
536
47
        Self {
537
47
            ptr: Box::new(Arc::new(Mutex::new(ti))),
538
47
            run_destructor: true,
539
47
        }
540
47
    }
541

            
542
    #[cfg(not(feature = "std"))]
543
    pub fn new(_ti: ThreadInner) -> Self {
544
        Self {
545
            ptr: core::ptr::null(),
546
            run_destructor: false,
547
        }
548
    }
549

            
550
    /// Creates a new thread that will execute the given callback function.
551
    ///
552
    /// # Arguments
553
    /// * `thread_initialize_data` - Data passed to the callback when the thread starts
554
    /// * `writeback_data` - Data that will be passed back when writeback messages are received
555
    /// * `callback` - The callback to execute in the background thread
556
    ///
557
    /// # Returns
558
    /// A new Thread handle that can be added to the event loop with `CallbackInfo::add_thread`
559
37
    pub fn create<C: Into<ThreadCallback>>(
560
37
        thread_initialize_data: RefAny,
561
37
        writeback_data: RefAny,
562
37
        callback: C,
563
37
    ) -> Self {
564
37
        create_thread_libstd(thread_initialize_data, writeback_data, callback.into())
565
37
    }
566

            
567
    /// Send a control message to the running worker. Interior-mutable (the worker
568
    /// state is behind a `Mutex`), so this takes `&self` and is callable from a
569
    /// callback that only holds `&Thread` via `CallbackInfo::get_thread`. Used to push
570
    /// resize / seek / source-change messages to a persistent worker. Returns false
571
    /// if the channel is closed (or always, on `no_std`).
572
    #[cfg(feature = "std")]
573
    #[must_use]
574
12
    pub fn send_message(&self, msg: ThreadSendMsg) -> bool {
575
12
        self.ptr
576
12
            .lock()
577
12
            .is_ok_and(|inner| inner.sender.send(msg).is_ok())
578
12
    }
579
    #[cfg(not(feature = "std"))]
580
    pub fn send_message(&self, _msg: ThreadSendMsg) -> bool {
581
        false
582
    }
583

            
584
    /// Clone the main→worker `Sender` so a holder without a `CallbackInfo` (e.g. a
585
    /// dataset-merge callback) can message the running worker later — used for the
586
    /// scrub/seek path, where the merge callback compares the old/new `VideoConfig`
587
    /// and pushes a seek to the worker. `None` on `no_std`.
588
    #[cfg(feature = "std")]
589
    #[must_use]
590
5
    pub fn clone_sender(&self) -> Option<Sender<ThreadSendMsg>> {
591
5
        self.ptr.lock().ok().map(|inner| (*inner.sender).clone())
592
5
    }
593
    #[cfg(not(feature = "std"))]
594
    pub fn clone_sender(&self) -> Option<Sender<ThreadSendMsg>> {
595
        None
596
    }
597
}
598

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

            
612
    #[cfg(feature = "std")]
613
    pub sender: Box<Sender<ThreadSendMsg>>,
614
    #[cfg(not(feature = "std"))]
615
    pub sender: *const core::ffi::c_void,
616

            
617
    #[cfg(feature = "std")]
618
    pub receiver: Box<Receiver<ThreadReceiveMsg>>,
619
    #[cfg(not(feature = "std"))]
620
    pub receiver: *const core::ffi::c_void,
621

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

            
627
    pub writeback_data: RefAny,
628
    pub check_thread_finished_fn: CheckThreadFinishedCallback,
629
    pub send_thread_msg_fn: LibrarySendThreadMsgCallback,
630
    pub receive_thread_msg_fn: LibraryReceiveThreadMsgCallback,
631
    pub thread_destructor_fn: ThreadDestructorCallback,
632
}
633

            
634
#[cfg(feature = "std")]
635
impl ThreadInner {
636
    /// Returns true if the Thread has been finished, false otherwise
637
    #[must_use]
638
54
    pub fn is_finished(&self) -> bool {
639
54
        (self.check_thread_finished_fn.cb)(
640
54
            std::ptr::from_ref(self.dropcheck.as_ref()).cast::<core::ffi::c_void>(),
641
54
        )
642
54
    }
643

            
644
    /// Send a message to the thread
645
2
    pub fn sender_send(&mut self, msg: ThreadSendMsg) -> bool {
646
2
        (self.send_thread_msg_fn.cb)(
647
2
            std::ptr::from_ref(self.sender.as_ref()).cast::<core::ffi::c_void>(),
648
2
            msg,
649
2
        )
650
2
    }
651

            
652
    /// Try to receive a message from the thread (non-blocking)
653
15
    pub fn receiver_try_recv(&mut self) -> OptionThreadReceiveMsg {
654
15
        (self.receive_thread_msg_fn.cb)(
655
15
            std::ptr::from_ref(self.receiver.as_ref()).cast::<core::ffi::c_void>(),
656
15
        )
657
15
    }
658
}
659

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

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

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

            
678
impl Drop for ThreadInner {
679
47
    fn drop(&mut self) {
680
47
        (self.thread_destructor_fn.cb)(self);
681
47
    }
682
}
683

            
684
/// How long `default_thread_destructor_fn` waits for a worker to acknowledge
685
/// `TerminateThread` before detaching it: 200 steps x 10ms = 2s.
686
///
687
/// Module scope rather than inside the function because clippy's
688
/// `items_after_statements` is denied here — an item declared mid-body reads as
689
/// if it were scoped to that point when it is not.
690
#[cfg(feature = "std")]
691
const THREAD_TERMINATE_GRACE_STEPS: u32 = 200;
692

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

            
698
    // Sent to every worker, including a job on a `ThreadPool` worker that has
699
    // not started yet: it can then skip its work entirely.
700
58
    drop(thread.sender.send(ThreadSendMsg::TerminateThread));
701

            
702
    // A job on a `ThreadPool` worker has no handle: the OS thread is shared, so
703
    // there is nothing to join.
704
58
    if let Some(thread_handle) = thread.thread_handle.take() {
705
        // BOUNDED wait, then DETACH. This was an unconditional
706
        // `thread_handle.join()`, which hangs forever whenever the worker does
707
        // not observe `TerminateThread` — and a worker blocked in a device read
708
        // (v4l2, ALSA) or on a different channel never does.
709
        //
710
        // Measured on the published 0.2.0 azul-self-test-linux: after the
711
        // window closed and the Wayland display was disconnected, the main
712
        // thread sat in `pthread_join` on an unnamed worker while 22 other
713
        // threads idled. `App::run()` never returned, so the process never
714
        // reached `std::process::exit()` in main and had to be killed. The demo
715
        // advertises "exits on its own (~4s)".
716
        //
717
        // `dropcheck` already tells us what we need: the worker holds an Arc
718
        // whose Weak lives here, so `strong_count() == 0` means it has actually
719
        // finished and the join will return immediately. If it has not finished
720
        // within the grace period we DROP the handle instead, which detaches the
721
        // thread. A detached thread cannot block `process::exit`, and shutting
722
        // down is precisely when refusing to wait is correct: the alternative on
723
        // display is a hang, which users read as a crash.
724
        //
725
        // Spin on a sleep rather than `Instant`: this file is compiled for wasm
726
        // and the clockless targets, where the strict `Instant` gate is 0.
727
41
        let mut finished = thread.dropcheck.strong_count() == 0;
728
41
        let mut waited = 0_u32;
729
59
        while !finished && waited < THREAD_TERMINATE_GRACE_STEPS {
730
18
            thread::sleep(core::time::Duration::from_millis(10));
731
18
            waited += 1;
732
18
            finished = thread.dropcheck.strong_count() == 0;
733
18
        }
734

            
735
41
        if finished {
736
41
            drop(thread_handle.join()); // returns immediately; ignore the result
737
41
        } else {
738
            // Detached. Say so — a silently leaked worker is how a "why is this
739
            // slow to exit" question becomes unanswerable.
740
            eprintln!(
741
                "[azul][thread] a background thread did not acknowledge TerminateThread within \
742
                 {}ms and was DETACHED rather than joined. It will be torn down by process exit. \
743
                 If this recurs, that worker is blocking on something it cannot be interrupted \
744
                 from (a device read, or a channel other than its terminate channel).",
745
                THREAD_TERMINATE_GRACE_STEPS * 10,
746
            );
747
            drop(thread_handle);
748
        }
749
17
    }
750
58
}
751

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

            
755
#[cfg(feature = "std")]
756
5
extern "C" fn library_send_thread_msg_fn(
757
5
    sender: *const core::ffi::c_void,
758
5
    msg: ThreadSendMsg,
759
5
) -> bool {
760
5
    unsafe { &*sender.cast::<Sender<ThreadSendMsg>>() }
761
5
        .send(msg)
762
5
        .is_ok()
763
5
}
764

            
765
#[cfg(not(feature = "std"))]
766
extern "C" fn library_send_thread_msg_fn(
767
    _sender: *const core::ffi::c_void,
768
    _msg: ThreadSendMsg,
769
) -> bool {
770
    false
771
}
772

            
773
#[cfg(feature = "std")]
774
19
extern "C" fn library_receive_thread_msg_fn(
775
19
    receiver: *const core::ffi::c_void,
776
19
) -> OptionThreadReceiveMsg {
777
19
    unsafe { &*receiver.cast::<Receiver<ThreadReceiveMsg>>() }
778
19
        .try_recv()
779
19
        .ok()
780
19
        .into()
781
19
}
782

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

            
790
#[cfg(feature = "std")]
791
19
extern "C" fn default_send_thread_msg_fn(
792
19
    sender: *const core::ffi::c_void,
793
19
    msg: ThreadReceiveMsg,
794
19
) -> bool {
795
19
    unsafe { &*sender.cast::<Sender<ThreadReceiveMsg>>() }
796
19
        .send(msg)
797
19
        .is_ok()
798
19
}
799

            
800
#[cfg(not(feature = "std"))]
801
extern "C" fn default_send_thread_msg_fn(
802
    _sender: *const core::ffi::c_void,
803
    _msg: ThreadReceiveMsg,
804
) -> bool {
805
    false
806
}
807

            
808
#[cfg(feature = "std")]
809
19
extern "C" fn default_receive_thread_msg_fn(
810
19
    receiver: *const core::ffi::c_void,
811
19
) -> OptionThreadSendMsg {
812
19
    unsafe { &*receiver.cast::<Receiver<ThreadSendMsg>>() }
813
19
        .try_recv()
814
19
        .ok()
815
19
        .into()
816
19
}
817

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

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

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

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

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

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

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

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

            
851
#[repr(C)]
852
pub struct CreateThreadCallback {
853
    pub cb: CreateThreadCallbackType,
854
}
855

            
856
impl_callback_traits!(CreateThreadCallback);
857
impl Copy for CreateThreadCallback {}
858

            
859
/// Create a new thread using the standard library
860
#[cfg(feature = "std")]
861
#[must_use]
862
41
pub extern "C" fn create_thread_libstd(
863
41
    thread_initialize_data: RefAny,
864
41
    writeback_data: RefAny,
865
41
    callback: ThreadCallback,
866
41
) -> Thread {
867
41
    build_thread(
868
41
        thread_initialize_data,
869
41
        writeback_data,
870
41
        callback,
871
41
        |job| Some(thread::spawn(job)),
872
    )
873
41
}
874

            
875
/// A job handed to [`build_thread`]'s spawner: the worker body, ready to run on
876
/// whichever OS thread the spawner picks.
877
#[cfg(feature = "std")]
878
type ThreadJob = Box<dyn FnOnce() + Send + 'static>;
879

            
880
/// The channels, finish check and destructor every `Thread` needs, around a
881
/// body that `spawn` starts. `spawn` returns the `JoinHandle` when the body got
882
/// an OS thread of its own, `None` when it runs on a thread it does not own (a
883
/// [`ThreadPool`] worker).
884
#[cfg(feature = "std")]
885
47
fn build_thread(
886
47
    thread_initialize_data: RefAny,
887
47
    writeback_data: RefAny,
888
47
    callback: ThreadCallback,
889
47
    spawn: impl FnOnce(ThreadJob) -> Option<JoinHandle<()>>,
890
47
) -> Thread {
891
47
    let (sender_receiver, receiver_receiver) = channel::<ThreadReceiveMsg>();
892
47
    let mut sender_receiver = ThreadSender::new(ThreadSenderInner {
893
47
        ptr: Box::new(sender_receiver),
894
47
        send_fn: ThreadSendCallback {
895
47
            cb: default_send_thread_msg_fn,
896
47
        },
897
47
        destructor: ThreadSenderDestructorCallback {
898
47
            cb: thread_sender_drop,
899
47
        },
900
47
    });
901
    // Set the ctx from the callback for FFI
902
47
    sender_receiver.ctx = callback.ctx.clone();
903

            
904
47
    let (sender_sender, receiver_sender) = channel::<ThreadSendMsg>();
905
47
    let mut receiver_sender = ThreadReceiver::new(ThreadReceiverInner {
906
47
        ptr: Box::new(receiver_sender),
907
47
        recv_fn: ThreadRecvCallback {
908
47
            cb: default_receive_thread_msg_fn,
909
47
        },
910
47
        destructor: ThreadReceiverDestructorCallback {
911
47
            cb: thread_receiver_drop,
912
47
        },
913
47
    });
914
    // Set the ctx from the callback for FFI
915
47
    receiver_sender.ctx = callback.ctx.clone();
916

            
917
47
    let thread_check = Arc::new(());
918
47
    let dropcheck = Arc::downgrade(&thread_check);
919

            
920
47
    let thread_handle = spawn(Box::new(move || {
921
        // `thread_check` is captured BY MOVE, so it stays alive for the whole
922
        // body; dropping it here is what makes `dropcheck.upgrade()` start
923
        // returning `None`, i.e. signals that the thread has finished.
924
47
        (callback.cb)(thread_initialize_data, sender_receiver, receiver_sender);
925
47
        drop(thread_check);
926
47
    }));
927

            
928
47
    let thread_handle: Box<Option<JoinHandle<()>>> = Box::new(thread_handle);
929
47
    let sender: Box<Sender<ThreadSendMsg>> = Box::new(sender_sender);
930
47
    let receiver: Box<Receiver<ThreadReceiveMsg>> = Box::new(receiver_receiver);
931
47
    let dropcheck: Box<alloc::sync::Weak<()>> = Box::new(dropcheck);
932

            
933
47
    Thread::new(ThreadInner {
934
47
        thread_handle,
935
47
        sender,
936
47
        receiver,
937
47
        writeback_data,
938
47
        dropcheck,
939
47
        thread_destructor_fn: ThreadDestructorCallback {
940
47
            cb: default_thread_destructor_fn,
941
47
        },
942
47
        check_thread_finished_fn: CheckThreadFinishedCallback {
943
47
            cb: default_check_thread_finished,
944
47
        },
945
47
        send_thread_msg_fn: LibrarySendThreadMsgCallback {
946
47
            cb: library_send_thread_msg_fn,
947
47
        },
948
47
        receive_thread_msg_fn: LibraryReceiveThreadMsgCallback {
949
47
            cb: library_receive_thread_msg_fn,
950
47
        },
951
47
    })
952
47
}
953

            
954
#[cfg(not(feature = "std"))]
955
pub extern "C" fn create_thread_libstd(
956
    _thread_initialize_data: RefAny,
957
    _writeback_data: RefAny,
958
    _callback: ThreadCallback,
959
) -> Thread {
960
    Thread {
961
        ptr: core::ptr::null(),
962
        run_destructor: false,
963
    }
964
}
965

            
966
#[cfg(test)]
967
mod tests {
968
    use super::*;
969

            
970
    extern "C" fn test_writeback_callback(
971
        _thread_data: RefAny,
972
        _writeback_data: RefAny,
973
        _callback_info: CallbackInfo,
974
    ) -> Update {
975
        Update::DoNothing
976
    }
977

            
978
    #[test]
979
1
    fn test_writeback_callback_creation() {
980
1
        let callback = WriteBackCallback::new(test_writeback_callback);
981
1
        assert_eq!(
982
1
            callback.cb as *const () as usize,
983
1
            test_writeback_callback as *const () as usize
984
        );
985
1
    }
986

            
987
    #[test]
988
1
    fn test_writeback_callback_clone() {
989
1
        let callback = WriteBackCallback::new(test_writeback_callback);
990
1
        let cloned = callback.clone();
991
1
        assert_eq!(callback, cloned);
992
1
    }
993
}
994
#[allow(variant_size_differences)]
995
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
996
// disparity accepted
997
/// Optional Thread type for API compatibility
998
#[derive(Debug, Clone)]
999
#[repr(C, u8)]
pub enum OptionThread {
    None,
    Some(Thread),
}
impl From<Option<Thread>> for OptionThread {
1
    fn from(o: Option<Thread>) -> Self {
1
        o.map_or_else(|| Self::None, Self::Some)
1
    }
}
impl OptionThread {
    #[must_use]
2
    pub fn into_option(self) -> Option<Thread> {
2
        match self {
1
            Self::None => None,
1
            Self::Some(t) => Some(t),
        }
2
    }
}
/// A fixed set of worker threads that runs `Thread` bodies, created by the
/// application and shared by whoever it hands a clone to.
///
/// [`Thread::create`] starts one OS thread per call. A widget that starts many
/// short jobs (a map fetching tiles) can instead be given a pool: at most
/// `threads` jobs then run at once and the rest wait in the pool's queue.
/// Cloning is cheap and shares the same workers; the workers exit once the last
/// handle is dropped and the queue is empty.
#[derive(Debug)]
#[repr(C)]
pub struct ThreadPool {
    #[cfg(feature = "std")]
    pub ptr: Box<Arc<ThreadPoolInner>>,
    #[cfg(not(feature = "std"))]
    pub ptr: *const core::ffi::c_void,
    pub run_destructor: bool,
}
/// The shared state behind a [`ThreadPool`] handle.
#[cfg(feature = "std")]
#[derive(Debug)]
pub struct ThreadPoolInner {
    /// Queue into the workers. `None` where no worker could be started (a
    /// target without threads): jobs then get a thread of their own.
    queue: Option<Mutex<Sender<ThreadJob>>>,
    threads: usize,
}
impl Clone for ThreadPool {
4
    fn clone(&self) -> Self {
4
        Self {
4
            #[cfg(feature = "std")]
4
            ptr: self.ptr.clone(),
4
            #[cfg(not(feature = "std"))]
4
            ptr: self.ptr,
4
            run_destructor: true,
4
        }
4
    }
}
impl Drop for ThreadPool {
10
    fn drop(&mut self) {
10
        self.run_destructor = false;
10
    }
}
/// Two handles are equal when they share the same workers.
impl PartialEq for ThreadPool {
4
    fn eq(&self, other: &Self) -> bool {
        #[cfg(feature = "std")]
        {
4
            Arc::ptr_eq(&self.ptr, &other.ptr)
        }
        #[cfg(not(feature = "std"))]
        {
            core::ptr::eq(self.ptr, other.ptr)
        }
4
    }
}
impl ThreadPool {
    /// Start a pool of `threads` workers (at least one).
    #[cfg(feature = "std")]
    #[must_use]
6
    pub fn create(threads: usize) -> Self {
6
        let threads = threads.max(1);
6
        let (sender, receiver) = channel::<ThreadJob>();
6
        let receiver = Arc::new(Mutex::new(receiver));
6
        let mut started = 0;
12
        for i in 0..threads {
12
            let receiver = Arc::clone(&receiver);
12
            let worker = thread::Builder::new()
12
                .name(alloc::format!("azul-pool-{i}"))
12
                .spawn(move || loop {
                    // Hold the lock only while waiting, never while running a job.
18
                    let job = match receiver.lock() {
18
                        Ok(queue) => queue.recv(),
                        Err(_) => return,
                    };
18
                    let Ok(job) = job else {
12
                        return; // every handle dropped and the queue drained
                    };
                    // A panicking job must not take the worker down with it.
6
                    drop(std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)));
12
                });
12
            if worker.is_ok() {
12
                started += 1;
12
            }
        }
        Self {
6
            ptr: Box::new(Arc::new(ThreadPoolInner {
6
                queue: (started > 0).then(|| Mutex::new(sender)),
6
                threads: started,
            })),
            run_destructor: true,
        }
6
    }
    #[cfg(not(feature = "std"))]
    pub fn create(_threads: usize) -> Self {
        Self {
            ptr: core::ptr::null(),
            run_destructor: false,
        }
    }
    /// How many workers are running (0 where the target cannot start threads).
    #[must_use]
2
    pub fn thread_count(&self) -> usize {
        #[cfg(feature = "std")]
        {
2
            self.ptr.threads
        }
        #[cfg(not(feature = "std"))]
        {
            0
        }
2
    }
    /// Like [`Thread::create`], but the body runs on one of this pool's workers
    /// instead of a new OS thread. Hand the result to `CallbackInfo::add_thread`
    /// exactly like any other `Thread`.
    #[must_use]
6
    pub fn create_thread<C: Into<ThreadCallback>>(
6
        &self,
6
        thread_initialize_data: RefAny,
6
        writeback_data: RefAny,
6
        callback: C,
6
    ) -> Thread {
        #[cfg(feature = "std")]
        {
6
            let Some(queue) = self.ptr.queue.as_ref() else {
                return Thread::create(thread_initialize_data, writeback_data, callback);
            };
6
            build_thread(
6
                thread_initialize_data,
6
                writeback_data,
6
                callback.into(),
6
                |job| {
6
                    if let Ok(queue) = queue.lock() {
6
                        // The workers only stop once every handle is gone, and
6
                        // `self` is one, so the queue is still open here.
6
                        drop(queue.send(job));
6
                    }
6
                    None
6
                },
            )
        }
        #[cfg(not(feature = "std"))]
        {
            create_thread_libstd(thread_initialize_data, writeback_data, callback.into())
        }
6
    }
}
impl_option!(
    ThreadPool,
    OptionThreadPool,
    copy = false,
    [Debug, Clone, PartialEq]
);
// ============================================================================
// Generated adversarial tests
// ============================================================================
#[cfg(all(test, feature = "std"))]
#[allow(clippy::too_many_lines, clippy::unreadable_literal)]
mod autotest_generated {
    use core::{
        hash::{Hash, Hasher},
        sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrd},
    };
    use std::{
        collections::{hash_map::DefaultHasher, BTreeMap},
        sync::{Arc, Mutex},
    };
    use azul_core::{
        dom::{DomId, DomNodeId},
        geom::OptionLogicalPosition,
        gl::OptionGlContextPtr,
        hit_test::ScrollPosition,
        resources::RendererResources,
        styled_dom::NodeHierarchyItemId,
        window::{MonitorVec, RawWindowHandle},
    };
    use azul_css::{corety::EmptyStruct, system::SystemStyle};
    use rust_fontconfig::FcFontCache;
    use super::*;
    #[cfg(feature = "icu")]
    use crate::icu::IcuLocalizerHandle;
    use crate::{
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
        window::LayoutWindow,
        window_state::FullWindowState,
    };
    // ------------------------------------------------------------------
    // Harness
    // ------------------------------------------------------------------
    /// Upper bound on a worker's non-blocking poll loop: `ThreadReceiver::recv` is
    /// `try_recv` under the hood, so a worker that waits for `TerminateThread` MUST
    /// be bounded or a lost message would hang the whole test binary.
    const MAX_WORKER_POLLS: usize = 10_000;
    fn hash_of<T: Hash>(value: &T) -> u64 {
        let mut hasher = DefaultHasher::new();
        value.hash(&mut hasher);
        hasher.finish()
    }
    /// A live `ThreadSender` plus the receiving end of its channel.
    fn make_sender() -> (Receiver<ThreadReceiveMsg>, ThreadSender) {
        let (tx, rx) = channel::<ThreadReceiveMsg>();
        let sender = ThreadSender::new(ThreadSenderInner {
            ptr: Box::new(tx),
            send_fn: ThreadSendCallback {
                cb: default_send_thread_msg_fn,
            },
            destructor: ThreadSenderDestructorCallback {
                cb: thread_sender_drop,
            },
        });
        (rx, sender)
    }
    /// Drain every message currently queued on the main->worker side.
    fn drain(inner: &mut ThreadInner) -> Vec<ThreadReceiveMsg> {
        let mut out = Vec::new();
        while let OptionThreadReceiveMsg::Some(msg) = inner.receiver_try_recv() {
            out.push(msg);
        }
        out
    }
    /// Runs the thread destructor by hand (terminate + join), so every assertion
    /// after it observes a *finished* worker instead of racing one.
    fn join_worker(t: &Thread) {
        let mut guard = t.ptr.lock().expect("thread mutex must not be poisoned");
        default_thread_destructor_fn(core::ptr::from_mut::<ThreadInner>(&mut guard));
    }
    /// Builds a real `CallbackInfo` (the only way to exercise `WriteBackCallback::invoke`)
    /// over an otherwise-empty `LayoutWindow`.
    fn with_callback_info<R>(f: impl FnOnce(CallbackInfo) -> R) -> R {
        let layout_window =
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
        let renderer_resources = RendererResources::default();
        let previous_window_state: Option<FullWindowState> = None;
        let current_window_state = FullWindowState::default();
        let gl_context = OptionGlContextPtr::None;
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
            BTreeMap::new();
        let window_handle = RawWindowHandle::Unsupported;
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
        let ref_data = CallbackInfoRefData {
            layout_window: &layout_window,
            renderer_resources: &renderer_resources,
            previous_window_state: &previous_window_state,
            current_window_state: &current_window_state,
            gl_context: &gl_context,
            current_scroll_manager: &scroll_states,
            current_window_handle: &window_handle,
            system_callbacks: &system_callbacks,
            system_style: Arc::new(SystemStyle::default()),
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
            #[cfg(feature = "icu")]
            icu_localizer: IcuLocalizerHandle::default(),
            ctx: OptionRefAny::None,
        };
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
        let info = CallbackInfo::new(
            &ref_data,
            &changes,
            DomNodeId {
                dom: DomId::ROOT_ID,
                node: NodeHierarchyItemId::NONE,
            },
            OptionLogicalPosition::None,
            OptionLogicalPosition::None,
        );
        f(info)
    }
    // ------------------------------------------------------------------
    // Callback fixtures
    // ------------------------------------------------------------------
    static WB_THREAD_DATA: AtomicUsize = AtomicUsize::new(0);
    static WB_WRITEBACK_DATA: AtomicUsize = AtomicUsize::new(0);
    extern "C" fn wb_record(
        mut thread_data: RefAny,
        mut writeback_data: RefAny,
        _callback_info: CallbackInfo,
    ) -> Update {
        if let Some(v) = thread_data.downcast_ref::<usize>() {
            WB_THREAD_DATA.store(*v, AtomicOrd::SeqCst);
        }
        if let Some(v) = writeback_data.downcast_ref::<usize>() {
            WB_WRITEBACK_DATA.store(*v, AtomicOrd::SeqCst);
        }
        Update::RefreshDomAllWindows
    }
    extern "C" fn wb_do_nothing(
        _thread_data: RefAny,
        _writeback_data: RefAny,
        _callback_info: CallbackInfo,
    ) -> Update {
        Update::DoNothing
    }
    /// A worker that exits immediately without ever touching its channels.
    extern "C" fn worker_quiet(_d: RefAny, _s: ThreadSender, _r: ThreadReceiver) {}
    /// A worker that pushes exactly one `Update` back to the main thread, then exits.
    extern "C" fn worker_send_update(_d: RefAny, mut sender: ThreadSender, _r: ThreadReceiver) {
        let _sent = sender.send(ThreadReceiveMsg::Update(Update::RefreshDom));
    }
    /// A worker that pushes one `WriteBack` message (the RefAny-carrying variant).
    extern "C" fn worker_send_writeback(_d: RefAny, mut sender: ThreadSender, _r: ThreadReceiver) {
        let _sent = sender.send(ThreadReceiveMsg::WriteBack(ThreadWriteBackMsg::new(
            wb_do_nothing as WriteBackCallbackType,
            RefAny::new(77_usize),
        )));
    }
    /// Generates a worker that echoes `Tick`s back until it is told to terminate.
    /// Each instance gets its own statics so tests can run in parallel without racing.
    macro_rules! terminating_worker {
        ($fn_name:ident, $ticks:ident, $terminated:ident) => {
            static $ticks: AtomicUsize = AtomicUsize::new(0);
            static $terminated: AtomicBool = AtomicBool::new(false);
            extern "C" fn $fn_name(
                _d: RefAny,
                mut sender: ThreadSender,
                mut receiver: ThreadReceiver,
            ) {
                for _ in 0..MAX_WORKER_POLLS {
                    match receiver.recv() {
                        OptionThreadSendMsg::Some(ThreadSendMsg::TerminateThread) => {
                            $terminated.store(true, AtomicOrd::SeqCst);
                            break;
                        }
                        OptionThreadSendMsg::Some(ThreadSendMsg::Tick) => {
                            $ticks.fetch_add(1, AtomicOrd::SeqCst);
                            let _sent = sender.send(ThreadReceiveMsg::Update(Update::RefreshDom));
                        }
                        OptionThreadSendMsg::Some(ThreadSendMsg::Custom(_)) => {
                            $ticks.fetch_add(1, AtomicOrd::SeqCst);
                        }
                        OptionThreadSendMsg::None => {
                            thread::sleep(std::time::Duration::from_millis(1));
                        }
                    }
                }
            }
        };
    }
    terminating_worker!(worker_wait_a, WAIT_A_TICKS, WAIT_A_TERMINATED);
    terminating_worker!(worker_wait_b, WAIT_B_TICKS, WAIT_B_TERMINATED);
    terminating_worker!(worker_wait_c, WAIT_C_TICKS, WAIT_C_TERMINATED);
    terminating_worker!(worker_wait_d, WAIT_D_TICKS, WAIT_D_TERMINATED);
    terminating_worker!(worker_wait_e, WAIT_E_TICKS, WAIT_E_TERMINATED);
    // ==================================================================
    // OptionThreadReceiveMsg — getters / predicates
    // ==================================================================
    #[test]
    fn option_thread_receive_msg_none_into_option_is_none() {
        assert!(OptionThreadReceiveMsg::None.into_option().is_none());
        assert!(OptionThreadReceiveMsg::None.as_ref().is_none());
    }
    #[test]
    fn option_thread_receive_msg_round_trips_through_from_and_into_option() {
        // Round-trip: Option -> OptionThreadReceiveMsg -> Option must be the identity.
        for update in [
            Update::DoNothing,
            Update::RefreshDom,
            Update::RefreshDomAllWindows,
        ] {
            let msg = ThreadReceiveMsg::Update(update);
            let ffi: OptionThreadReceiveMsg = Some(msg.clone()).into();
            assert_eq!(ffi.into_option(), Some(msg));
        }
        let empty: OptionThreadReceiveMsg = None.into();
        assert_eq!(empty, OptionThreadReceiveMsg::None);
        assert!(empty.into_option().is_none());
    }
    #[test]
    fn option_thread_receive_msg_as_ref_does_not_consume() {
        let opt = OptionThreadReceiveMsg::Some(ThreadReceiveMsg::Update(Update::RefreshDom));
        // as_ref() borrows: calling it repeatedly must keep returning the same payload.
        for _ in 0..3 {
            assert_eq!(
                opt.as_ref(),
                Some(&ThreadReceiveMsg::Update(Update::RefreshDom))
            );
        }
        // ... and the value is still intact afterwards.
        assert_eq!(
            opt.into_option(),
            Some(ThreadReceiveMsg::Update(Update::RefreshDom))
        );
    }
    #[test]
    fn option_thread_receive_msg_as_ref_handles_writeback_variant() {
        let opt = OptionThreadReceiveMsg::Some(ThreadReceiveMsg::WriteBack(
            ThreadWriteBackMsg::new(wb_do_nothing as WriteBackCallbackType, RefAny::new(1_usize)),
        ));
        let Some(ThreadReceiveMsg::WriteBack(inner)) = opt.as_ref() else {
            panic!("as_ref() must expose the WriteBack payload");
        };
        assert_eq!(
            inner.callback.cb as *const () as usize,
            wb_do_nothing as *const () as usize
        );
        assert!(opt.into_option().is_some());
    }
    #[test]
    fn option_thread_receive_msg_ord_and_hash_are_consistent() {
        let none = OptionThreadReceiveMsg::None;
        let some = OptionThreadReceiveMsg::Some(ThreadReceiveMsg::Update(Update::DoNothing));
        // Declaration order: None < Some.
        assert!(none < some);
        assert_eq!(none.cmp(&none), core::cmp::Ordering::Equal);
        // Eq => equal hashes.
        assert_eq!(hash_of(&none), hash_of(&OptionThreadReceiveMsg::None));
        assert_eq!(
            hash_of(&some),
            hash_of(&OptionThreadReceiveMsg::Some(ThreadReceiveMsg::Update(
                Update::DoNothing
            )))
        );
    }
    #[test]
    fn thread_receive_msg_orders_writeback_before_update() {
        let wb = ThreadReceiveMsg::WriteBack(ThreadWriteBackMsg::new(
            wb_do_nothing as WriteBackCallbackType,
            RefAny::new(0_usize),
        ));
        let up = ThreadReceiveMsg::Update(Update::DoNothing);
        assert!(wb < up, "variant order (WriteBack=0, Update=1) must decide");
        assert!(
            ThreadReceiveMsg::Update(Update::DoNothing)
                < ThreadReceiveMsg::Update(Update::RefreshDom)
        );
    }
    // ==================================================================
    // ThreadWriteBackMsg — constructor invariants
    // ==================================================================
    #[test]
    fn thread_write_back_msg_new_stores_both_fields() {
        let mut msg = ThreadWriteBackMsg::new(
            wb_do_nothing as WriteBackCallbackType,
            RefAny::new(0xDEAD_BEEF_usize),
        );
        assert_eq!(
            msg.callback.cb as *const () as usize,
            wb_do_nothing as *const () as usize
        );
        assert_eq!(
            msg.refany
                .downcast_ref::<usize>()
                .map(|v| *v)
                .expect("payload type must survive construction"),
            0xDEAD_BEEF_usize
        );
        // A fn-ptr-built callback carries no FFI ctx.
        assert_eq!(msg.callback.ctx, OptionRefAny::None);
    }
    #[test]
    fn thread_write_back_msg_new_accepts_both_into_impls() {
        // `C: Into<WriteBackCallback>` must accept a bare fn pointer *and* an
        // already-built WriteBackCallback; both must land on the same cb.
        let from_fn =
            ThreadWriteBackMsg::new(wb_record as WriteBackCallbackType, RefAny::new(1_usize));
        let from_struct =
            ThreadWriteBackMsg::new(WriteBackCallback::new(wb_record), RefAny::new(1_usize));
        assert_eq!(from_fn.callback, from_struct.callback);
    }
    #[test]
    fn thread_write_back_msg_clone_shares_payload_and_compares_equal() {
        // FIXED (this test previously pinned the opposite). `RefAny`'s equality no
        // longer includes `instance_id` — it keys on `sharing_info` alone (see the
        // comment on `RefAny` in core/src/refany.rs). So every type that transitively
        // contains a `RefAny` and derives `PartialEq` (ThreadWriteBackMsg,
        // ThreadReceiveMsg, OptionThreadReceiveMsg, ThreadSendMsg) now honours the
        // `a.clone() == a` contract, matching the shared heap payload.
        let msg =
            ThreadWriteBackMsg::new(wb_do_nothing as WriteBackCallbackType, RefAny::new(5_usize));
        let mut cloned = msg.clone();
        // Same callback, same underlying data ...
        assert_eq!(msg.callback, cloned.callback);
        assert_eq!(
            cloned.refany.downcast_ref::<usize>().map(|v| *v),
            Some(5_usize)
        );
        // ... and therefore `==`.
        assert_eq!(msg, cloned);
        // Two clones of the same message are equal to each other as well.
        assert_eq!(msg.clone(), msg.clone());
    }
    // ==================================================================
    // WriteBackCallback / ThreadCallback — fn-pointer identity semantics
    // ==================================================================
    #[test]
    fn writeback_callback_new_has_no_ctx_and_matches_fn_ptr() {
        let cb = WriteBackCallback::new(wb_record);
        assert_eq!(cb.ctx, OptionRefAny::None);
        assert_eq!(cb.cb as *const () as usize, wb_record as *const () as usize);
        // The From<fn ptr> impl must be equivalent to ::new.
        assert_eq!(
            cb,
            WriteBackCallback::from(wb_record as WriteBackCallbackType)
        );
    }
    #[test]
    fn writeback_callback_eq_ord_hash_key_off_the_fn_pointer_only() {
        let a = WriteBackCallback::new(wb_record);
        let b = WriteBackCallback::new(wb_record);
        let c = WriteBackCallback::new(wb_do_nothing);
        assert_eq!(a, b);
        assert_eq!(hash_of(&a), hash_of(&b));
        assert_eq!(a.cmp(&b), core::cmp::Ordering::Equal);
        assert_ne!(a, c);
        // Ord must be a strict total order: exactly one direction holds.
        assert!((a < c) ^ (c < a));
        assert_eq!(a.partial_cmp(&c), Some(a.cmp(&c)));
        // Clone preserves identity (no RefAny in the compared fields).
        assert_eq!(a, a.clone());
        assert_eq!(hash_of(&a), hash_of(&a.clone()));
    }
    #[test]
    fn writeback_callback_debug_does_not_panic() {
        let s = format!("{:?}", WriteBackCallback::new(wb_record));
        assert!(s.starts_with("WriteBackCallback {"), "got {s}");
    }
    #[test]
    fn writeback_callback_invoke_forwards_args_and_returns_callback_update() {
        WB_THREAD_DATA.store(0, AtomicOrd::SeqCst);
        WB_WRITEBACK_DATA.store(0, AtomicOrd::SeqCst);
        let cb = WriteBackCallback::new(wb_record);
        let update = with_callback_info(|info| {
            cb.invoke(RefAny::new(11_usize), RefAny::new(22_usize), info)
        });
        // The return value must be whatever the callback returned, unmodified.
        assert_eq!(update, Update::RefreshDomAllWindows);
        // ... and the two RefAnys must arrive in the documented order (not swapped).
        assert_eq!(WB_THREAD_DATA.load(AtomicOrd::SeqCst), 11);
        assert_eq!(WB_WRITEBACK_DATA.load(AtomicOrd::SeqCst), 22);
    }
    #[test]
    fn writeback_callback_invoke_is_repeatable() {
        let cb = WriteBackCallback::new(wb_do_nothing);
        with_callback_info(|info| {
            // CallbackInfo is Copy, so the same info can back several invocations.
            for _ in 0..4 {
                assert_eq!(
                    cb.invoke(RefAny::new(0_usize), RefAny::new(0_usize), info),
                    Update::DoNothing
                );
            }
        });
    }
    #[test]
    fn thread_callback_new_has_no_ctx_and_orders_by_fn_ptr() {
        let a = ThreadCallback::new(worker_quiet);
        let b = ThreadCallback::from(worker_quiet as ThreadCallbackType);
        let c = ThreadCallback::new(worker_send_update);
        assert_eq!(a.ctx, OptionRefAny::None);
        assert_eq!(a, b);
        assert_eq!(hash_of(&a), hash_of(&b));
        assert_ne!(a, c);
        assert!((a < c) ^ (c < a));
        assert_eq!(a, a.clone());
        assert!(format!("{a:?}").starts_with("ThreadCallback {"));
    }
    #[test]
    fn thread_send_callback_wrapper_traits_are_consistent() {
        // impl_callback_traits! generated Clone/Eq/Ord/Hash for the FFI wrappers.
        let a = ThreadSendCallback {
            cb: default_send_thread_msg_fn,
        };
        let b = a.clone();
        assert_eq!(a, b);
        assert_eq!(hash_of(&a), hash_of(&b));
        assert_eq!(a.cmp(&b), core::cmp::Ordering::Equal);
        assert!(format!("{a:?}").starts_with("ThreadSendCallback {"));
    }
    // ==================================================================
    // ThreadSender
    // ==================================================================
    #[test]
    fn thread_sender_send_delivers_the_exact_message() {
        let (rx, mut sender) = make_sender();
        assert!(sender.send(ThreadReceiveMsg::Update(Update::RefreshDom)));
        assert_eq!(
            rx.try_recv().ok(),
            Some(ThreadReceiveMsg::Update(Update::RefreshDom))
        );
        assert!(rx.try_recv().is_err(), "channel must now be empty");
    }
    #[test]
    fn thread_sender_send_returns_false_when_receiver_is_gone() {
        let (rx, mut sender) = make_sender();
        drop(rx);
        // Disconnected channel: must report failure, not panic.
        assert!(!sender.send(ThreadReceiveMsg::Update(Update::RefreshDom)));
        assert!(
            !sender.send(ThreadReceiveMsg::WriteBack(ThreadWriteBackMsg::new(
                wb_do_nothing as WriteBackCallbackType,
                RefAny::new(0_usize),
            )))
        );
    }
    #[test]
    fn thread_sender_send_survives_a_poisoned_mutex() {
        let (rx, mut sender) = make_sender();
        let arc = Arc::clone(&*sender.ptr);
        let handle = thread::spawn(move || {
            let _guard = arc.lock().expect("mutex is fresh here");
            panic!("intentional poison");
        });
        assert!(handle.join().is_err(), "helper thread must have panicked");
        // ThreadSender::send does `.lock().ok()` — a poisoned lock must degrade to
        // `false`, never to an unwrap panic.
        assert!(!sender.send(ThreadReceiveMsg::Update(Update::RefreshDom)));
        // ... and nothing was actually pushed onto the channel.
        assert!(rx.try_recv().is_err());
    }
    #[test]
    fn thread_sender_get_ctx_is_none_by_default_and_clones_the_payload() {
        let (_rx, mut sender) = make_sender();
        assert_eq!(sender.get_ctx(), OptionRefAny::None);
        sender.ctx = OptionRefAny::Some(RefAny::new(9_usize));
        let OptionRefAny::Some(mut ctx) = sender.get_ctx() else {
            panic!("get_ctx must hand back the ctx that was set");
        };
        assert_eq!(ctx.downcast_ref::<usize>().map(|v| *v), Some(9_usize));
        // get_ctx clones rather than moves: the sender still holds its ctx.
        assert!(matches!(sender.get_ctx(), OptionRefAny::Some(_)));
    }
    #[test]
    fn thread_sender_clone_shares_the_underlying_channel() {
        let (rx, mut sender) = make_sender();
        sender.ctx = OptionRefAny::Some(RefAny::new(3_usize));
        let mut cloned = sender.clone();
        assert!(sender.send(ThreadReceiveMsg::Update(Update::DoNothing)));
        assert!(cloned.send(ThreadReceiveMsg::Update(Update::RefreshDom)));
        // Both endpoints feed the same channel, in order.
        assert_eq!(
            rx.try_recv().ok(),
            Some(ThreadReceiveMsg::Update(Update::DoNothing))
        );
        assert_eq!(
            rx.try_recv().ok(),
            Some(ThreadReceiveMsg::Update(Update::RefreshDom))
        );
        // The FFI ctx survives the clone.
        assert!(matches!(cloned.get_ctx(), OptionRefAny::Some(_)));
    }
    // ==================================================================
    // Private FFI callbacks — the raw-pointer trampolines
    // ==================================================================
    #[test]
    fn default_send_thread_msg_fn_reports_disconnect_instead_of_panicking() {
        let (tx, rx) = channel::<ThreadReceiveMsg>();
        let tx_ptr =
            core::ptr::from_ref::<Sender<ThreadReceiveMsg>>(&tx).cast::<core::ffi::c_void>();
        assert!(default_send_thread_msg_fn(
            tx_ptr,
            ThreadReceiveMsg::Update(Update::RefreshDom)
        ));
        assert_eq!(
            rx.try_recv().ok(),
            Some(ThreadReceiveMsg::Update(Update::RefreshDom))
        );
        drop(rx);
        assert!(!default_send_thread_msg_fn(
            tx_ptr,
            ThreadReceiveMsg::Update(Update::RefreshDom)
        ));
    }
    #[test]
    fn library_send_thread_msg_fn_reports_disconnect_instead_of_panicking() {
        let (tx, rx) = channel::<ThreadSendMsg>();
        let tx_ptr = core::ptr::from_ref::<Sender<ThreadSendMsg>>(&tx).cast::<core::ffi::c_void>();
        assert!(library_send_thread_msg_fn(tx_ptr, ThreadSendMsg::Tick));
        assert!(library_send_thread_msg_fn(
            tx_ptr,
            ThreadSendMsg::Custom(RefAny::new(4_usize))
        ));
        assert_eq!(rx.try_recv().ok(), Some(ThreadSendMsg::Tick));
        assert!(matches!(rx.try_recv(), Ok(ThreadSendMsg::Custom(_))));
        drop(rx);
        assert!(!library_send_thread_msg_fn(
            tx_ptr,
            ThreadSendMsg::TerminateThread
        ));
    }
    #[test]
    fn library_receive_thread_msg_fn_is_non_blocking_on_empty_and_disconnected() {
        let (tx, rx) = channel::<ThreadReceiveMsg>();
        let rx_ptr =
            core::ptr::from_ref::<Receiver<ThreadReceiveMsg>>(&rx).cast::<core::ffi::c_void>();
        // Empty but connected: must return immediately with None (not block).
        assert_eq!(
            library_receive_thread_msg_fn(rx_ptr),
            OptionThreadReceiveMsg::None
        );
        tx.send(ThreadReceiveMsg::Update(Update::RefreshDomAllWindows))
            .expect("receiver is alive");
        assert_eq!(
            library_receive_thread_msg_fn(rx_ptr),
            OptionThreadReceiveMsg::Some(ThreadReceiveMsg::Update(Update::RefreshDomAllWindows))
        );
        // Disconnected: still None, still no panic, and it stays None.
        drop(tx);
        assert_eq!(
            library_receive_thread_msg_fn(rx_ptr),
            OptionThreadReceiveMsg::None
        );
        assert_eq!(
            library_receive_thread_msg_fn(rx_ptr),
            OptionThreadReceiveMsg::None
        );
    }
    #[test]
    fn default_receive_thread_msg_fn_is_non_blocking_on_empty_and_disconnected() {
        let (tx, rx) = channel::<ThreadSendMsg>();
        let rx_ptr =
            core::ptr::from_ref::<Receiver<ThreadSendMsg>>(&rx).cast::<core::ffi::c_void>();
        assert_eq!(
            default_receive_thread_msg_fn(rx_ptr),
            OptionThreadSendMsg::None
        );
        tx.send(ThreadSendMsg::TerminateThread)
            .expect("receiver is alive");
        assert_eq!(
            default_receive_thread_msg_fn(rx_ptr),
            OptionThreadSendMsg::Some(ThreadSendMsg::TerminateThread)
        );
        drop(tx);
        assert_eq!(
            default_receive_thread_msg_fn(rx_ptr),
            OptionThreadSendMsg::None
        );
    }
    #[test]
    fn default_check_thread_finished_tracks_the_dropcheck_arc() {
        let alive = Arc::new(());
        let weak = Arc::downgrade(&alive);
        let weak_ptr =
            core::ptr::from_ref::<alloc::sync::Weak<()>>(&weak).cast::<core::ffi::c_void>();
        // Strong ref still held by the (simulated) worker => not finished.
        assert!(!default_check_thread_finished(weak_ptr));
        drop(alive);
        // Worker gone => finished, and the answer is stable across calls.
        assert!(default_check_thread_finished(weak_ptr));
        assert!(default_check_thread_finished(weak_ptr));
    }
    #[test]
    fn sender_and_receiver_drop_stubs_ignore_their_argument() {
        // Both destructors are documented no-ops: they must never dereference the
        // pointer, so even a null one is safe to hand them.
        thread_sender_drop(core::ptr::null_mut::<ThreadSenderInner>());
        thread_receiver_drop(core::ptr::null_mut::<ThreadReceiverInner>());
    }
    // ==================================================================
    // Thread / create_thread_libstd — the live-worker paths
    // ==================================================================
    #[test]
    fn create_thread_libstd_runs_the_callback_and_delivers_its_message() {
        let t = create_thread_libstd(
            RefAny::new(0_usize),
            RefAny::new(0_usize),
            ThreadCallback::new(worker_send_update),
        );
        join_worker(&t);
        let mut guard = t.ptr.lock().expect("not poisoned");
        assert!(
            guard.is_finished(),
            "after join the dropcheck Arc must be gone"
        );
        assert_eq!(
            drain(&mut guard),
            vec![ThreadReceiveMsg::Update(Update::RefreshDom)]
        );
    }
    #[test]
    fn thread_create_delivers_a_writeback_message_intact() {
        let t = Thread::create(
            RefAny::new(0_usize),
            RefAny::new(0_usize),
            worker_send_writeback as ThreadCallbackType,
        );
        join_worker(&t);
        let mut guard = t.ptr.lock().expect("not poisoned");
        let msgs = drain(&mut guard);
        assert_eq!(msgs.len(), 1);
        let ThreadReceiveMsg::WriteBack(wb) = &msgs[0] else {
            panic!("expected a WriteBack message, got {:?}", msgs[0]);
        };
        assert_eq!(
            wb.callback.cb as *const () as usize,
            wb_do_nothing as *const () as usize
        );
        // The RefAny payload survived the channel hop between threads.
        let mut payload = wb.refany.clone();
        assert_eq!(payload.downcast_ref::<usize>().map(|v| *v), Some(77_usize));
    }
    #[test]
    fn quiet_worker_leaves_the_receive_queue_empty() {
        let t = Thread::create(
            RefAny::new(0_usize),
            RefAny::new(0_usize),
            worker_quiet as ThreadCallbackType,
        );
        join_worker(&t);
        let mut guard = t.ptr.lock().expect("not poisoned");
        // try_recv on a worker that sent nothing must be None, never a block/panic.
        assert!(drain(&mut guard).is_empty());
        assert_eq!(guard.receiver_try_recv(), OptionThreadReceiveMsg::None);
    }
    #[test]
    fn thread_destructor_is_idempotent() {
        let t = create_thread_libstd(
            RefAny::new(0_usize),
            RefAny::new(0_usize),
            ThreadCallback::new(worker_send_update),
        );
        // Running the destructor twice by hand must not double-join (which would
        // panic / abort); `thread_handle.take()` makes the second call a no-op.
        join_worker(&t);
        join_worker(&t);
        // ... and the real Drop impl will run it a third time when `t` goes away.
        drop(t);
    }
    #[test]
    fn thread_send_message_reaches_the_worker_in_order() {
        let t = Thread::create(
            RefAny::new(0_usize),
            RefAny::new(0_usize),
            worker_wait_a as ThreadCallbackType,
        );
        // The worker holds its ThreadReceiver alive, so every send must succeed.
        for _ in 0..3 {
            assert!(t.send_message(ThreadSendMsg::Tick));
        }
        assert!(t.send_message(ThreadSendMsg::Custom(RefAny::new(1_usize))));
        join_worker(&t); // queues TerminateThread behind the 4 messages, then joins
        assert!(WAIT_A_TERMINATED.load(AtomicOrd::SeqCst));
        assert_eq!(WAIT_A_TICKS.load(AtomicOrd::SeqCst), 4);
        let mut guard = t.ptr.lock().expect("not poisoned");
        assert!(guard.is_finished());
        // 3 Ticks echoed back; Custom is counted but not echoed.
        assert_eq!(drain(&mut guard).len(), 3);
    }
    #[test]
    fn thread_send_message_returns_false_once_the_worker_is_gone() {
        let t = Thread::create(
            RefAny::new(0_usize),
            RefAny::new(0_usize),
            worker_wait_b as ThreadCallbackType,
        );
        assert!(t.send_message(ThreadSendMsg::Tick));
        join_worker(&t); // worker exits, dropping its Receiver<ThreadSendMsg>
        assert!(WAIT_B_TERMINATED.load(AtomicOrd::SeqCst));
        // Disconnected channel: report false rather than panicking.
        assert!(!t.send_message(ThreadSendMsg::Tick));
        assert!(!t.send_message(ThreadSendMsg::TerminateThread));
    }
    #[test]
    fn thread_is_finished_is_false_while_the_worker_is_alive() {
        let t = Thread::create(
            RefAny::new(0_usize),
            RefAny::new(0_usize),
            worker_wait_c as ThreadCallbackType,
        );
        {
            // The dropcheck Arc is moved into the closure before spawn, so it is
            // alive from creation until the worker body returns: deterministic false.
            let guard = t.ptr.lock().expect("not poisoned");
            assert!(!guard.is_finished());
        }
        join_worker(&t);
        assert!(t.ptr.lock().expect("not poisoned").is_finished());
        assert!(WAIT_C_TERMINATED.load(AtomicOrd::SeqCst));
    }
    #[test]
    fn thread_clone_sender_shares_the_worker_channel() {
        let t = Thread::create(
            RefAny::new(0_usize),
            RefAny::new(0_usize),
            worker_wait_d as ThreadCallbackType,
        );
        let sender = t.clone_sender().expect("std build must hand back a Sender");
        // Same channel as `send_message`: both reach the worker's receiver, which
        // stays alive until it is told to terminate.
        assert!(sender.send(ThreadSendMsg::Tick).is_ok());
        assert!(t.send_message(ThreadSendMsg::Tick));
        drop(sender);
        join_worker(&t);
        assert!(WAIT_D_TERMINATED.load(AtomicOrd::SeqCst));
        assert_eq!(WAIT_D_TICKS.load(AtomicOrd::SeqCst), 2);
    }
    #[test]
    fn thread_send_message_and_clone_sender_survive_a_poisoned_mutex() {
        let t = Thread::create(
            RefAny::new(0_usize),
            RefAny::new(0_usize),
            worker_wait_e as ThreadCallbackType,
        );
        let arc = Arc::clone(&*t.ptr);
        let handle = thread::spawn(move || {
            let _guard = arc.lock().expect("mutex is fresh here");
            panic!("intentional poison");
        });
        assert!(handle.join().is_err(), "helper thread must have panicked");
        // Both accessors are `.lock()`-fallible by design; poison must degrade
        // gracefully, not unwind through the FFI boundary.
        assert!(!t.send_message(ThreadSendMsg::Tick));
        assert!(t.clone_sender().is_none());
        // Teardown still works: Mutex::drop hands out the inner value regardless of
        // poison, so the Drop impl can still terminate + join the worker.
        drop(t);
        assert!(WAIT_E_TERMINATED.load(AtomicOrd::SeqCst));
    }
    #[test]
    fn thread_clone_shares_the_same_inner_state() {
        let t = create_thread_libstd(
            RefAny::new(0_usize),
            RefAny::new(0_usize),
            ThreadCallback::new(worker_quiet),
        );
        let cloned = t.clone();
        assert_eq!(Arc::strong_count(&*t.ptr), 2, "clone must be shallow");
        assert!(cloned.run_destructor);
        join_worker(&t);
        // The clone sees the same (now finished) ThreadInner.
        assert!(cloned.ptr.lock().expect("not poisoned").is_finished());
        drop(cloned);
        drop(t);
    }
    #[test]
    fn option_thread_into_option_round_trips() {
        assert!(OptionThread::None.into_option().is_none());
        let t = create_thread_libstd(
            RefAny::new(0_usize),
            RefAny::new(0_usize),
            ThreadCallback::new(worker_quiet),
        );
        let opt: OptionThread = Some(t).into();
        let recovered = opt.into_option().expect("Some must round-trip to Some");
        join_worker(&recovered);
        assert!(recovered.ptr.lock().expect("not poisoned").is_finished());
    }
}
#[cfg(all(test, feature = "std"))]
mod thread_pool_tests {
    use core::sync::atomic::{AtomicUsize, Ordering};
    use super::*;
    static RUNNING: AtomicUsize = AtomicUsize::new(0);
    static PEAK: AtomicUsize = AtomicUsize::new(0);
    static DONE: AtomicUsize = AtomicUsize::new(0);
6
    extern "C" fn busy(_: RefAny, _: ThreadSender, _: ThreadReceiver) {
6
        let now = RUNNING.fetch_add(1, Ordering::SeqCst) + 1;
6
        PEAK.fetch_max(now, Ordering::SeqCst);
6
        thread::sleep(core::time::Duration::from_millis(20));
6
        RUNNING.fetch_sub(1, Ordering::SeqCst);
6
        DONE.fetch_add(1, Ordering::SeqCst);
6
    }
    #[test]
1
    fn a_pool_runs_every_job_but_never_more_than_its_workers_at_once() {
1
        let pool = ThreadPool::create(2);
1
        assert_eq!(pool.thread_count(), 2);
1
        let threads: Vec<Thread> = (0..6)
6
            .map(|_| pool.create_thread(RefAny::new(()), RefAny::new(()), ThreadCallback::new(busy)))
1
            .collect();
34
        let finished = |t: &Thread| t.ptr.lock().is_ok_and(|inner| inner.is_finished());
1
        let mut waited = 0;
8
        while !threads.iter().all(finished) && waited < 500 {
7
            thread::sleep(core::time::Duration::from_millis(10));
7
            waited += 1;
7
        }
1
        assert!(threads.iter().all(finished), "every queued job must run");
1
        assert_eq!(DONE.load(Ordering::SeqCst), 6);
1
        let peak = PEAK.load(Ordering::SeqCst);
1
        assert!((1..=2).contains(&peak), "ran {peak} jobs at once on 2 workers");
1
    }
    #[test]
1
    fn clones_share_the_workers() {
1
        let pool = ThreadPool::create(3);
1
        assert_eq!(pool.clone(), pool);
1
        assert_ne!(ThreadPool::create(3), pool);
1
        assert_eq!(ThreadPool::create(0).thread_count(), 1, "at least one worker");
1
    }
}