1#![allow(clippy::new_without_default)]
8
9use std::cell::Cell;
10use std::fmt;
11use std::marker::PhantomData;
12use std::num::NonZeroU32;
13use std::sync::atomic::{AtomicU32, Ordering};
14use std::sync::{Arc, LazyLock};
15
16use accesskit::{TreeId, Uuid};
17use malloc_size_of::MallocSizeOfOps;
18use malloc_size_of_derive::MallocSizeOf;
19use parking_lot::Mutex;
20use regex::Regex;
21use serde::{Deserialize, Serialize};
22use webrender_api::{
23 ExternalScrollId, FontInstanceKey, FontKey, IdNamespace, ImageKey,
24 PipelineId as WebRenderPipelineId, SpatialTreeItemKey,
25};
26
27use crate::generic_channel::{self, GenericReceiver, GenericSender};
28
29macro_rules! size_of_test {
31 ($t: ty, $expected_size: expr) => {
32 const _: () = assert!(std::mem::size_of::<$t>() == $expected_size);
33 };
34}
35
36pub trait Indexable {
39 const DISPLAY_PREFIX: &'static str;
42}
43
44#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
45pub struct Index<T>(pub NonZeroU32, pub PhantomData<T>);
47
48#[derive(Debug)]
49pub struct ZeroIndex;
52
53impl<T> Index<T> {
54 pub fn new(value: u32) -> Result<Index<T>, ZeroIndex> {
57 Ok(Index(NonZeroU32::new(value).ok_or(ZeroIndex)?, PhantomData))
58 }
59}
60
61impl<T> malloc_size_of::MallocSizeOf for Index<T> {
62 fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
63 0
64 }
65}
66
67#[derive(
68 Clone, Copy, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize,
69)]
70pub struct NamespaceIndex<T> {
72 pub namespace_id: PipelineNamespaceId,
73 pub index: Index<T>,
74}
75
76impl<T> fmt::Debug for NamespaceIndex<T> {
77 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
78 let PipelineNamespaceId(namespace_id) = self.namespace_id;
79 let Index(index, _) = self.index;
80 write!(fmt, "({},{})", namespace_id, index.get())
81 }
82}
83
84impl<T: Indexable> fmt::Display for NamespaceIndex<T> {
85 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
86 write!(fmt, "{}{:?}", T::DISPLAY_PREFIX, self)
87 }
88}
89
90macro_rules! namespace_id {
91 ($id_name:ident, $index_name:ident, $display_prefix:literal) => {
92 #[derive(
93 Clone,
94 Copy,
95 Debug,
96 Deserialize,
97 Eq,
98 Hash,
99 Ord,
100 PartialEq,
101 PartialOrd,
102 Serialize,
103 MallocSizeOf,
104 )]
105 pub struct $index_name;
106 impl Indexable for $index_name {
107 const DISPLAY_PREFIX: &'static str = $display_prefix;
108 }
109 pub type $id_name = NamespaceIndex<$index_name>;
110 impl $id_name {
111 pub fn new() -> $id_name {
112 PIPELINE_NAMESPACE.with(|tls| {
113 let mut namespace = tls.get().expect("No namespace set for this thread!");
114 let next_id = namespace.next_namespace_index();
115 tls.set(Some(namespace));
116 next_id
117 })
118 }
119 }
120 };
121}
122
123#[derive(Debug, Deserialize, Serialize)]
124pub struct PipelineNamespaceRequest(pub GenericSender<PipelineNamespaceId>);
126
127pub struct PipelineNamespaceInstaller {
129 request_sender: Option<GenericSender<PipelineNamespaceRequest>>,
130 namespace_sender: GenericSender<PipelineNamespaceId>,
131 namespace_receiver: GenericReceiver<PipelineNamespaceId>,
132}
133
134impl Default for PipelineNamespaceInstaller {
135 fn default() -> Self {
136 let (namespace_sender, namespace_receiver) =
137 generic_channel::channel().expect("PipelineNamespaceInstaller channel failure");
138 Self {
139 request_sender: None,
140 namespace_sender,
141 namespace_receiver,
142 }
143 }
144}
145
146impl PipelineNamespaceInstaller {
147 pub fn set_sender(&mut self, sender: GenericSender<PipelineNamespaceRequest>) {
149 self.request_sender = Some(sender);
150 }
151
152 pub fn install_namespace(&self) {
154 match self.request_sender.as_ref() {
155 Some(sender) => {
156 let _ = sender.send(PipelineNamespaceRequest(self.namespace_sender.clone()));
157 let namespace_id = self
158 .namespace_receiver
159 .recv()
160 .expect("The constellation to make a pipeline namespace id available");
161 PipelineNamespace::install(namespace_id);
162 },
163 None => unreachable!("PipelineNamespaceInstaller should have a request_sender setup"),
164 }
165 }
166}
167
168static PIPELINE_NAMESPACE_INSTALLER: LazyLock<Arc<Mutex<PipelineNamespaceInstaller>>> =
176 LazyLock::new(|| Arc::new(Mutex::new(PipelineNamespaceInstaller::default())));
177
178#[derive(Clone, Copy)]
198pub struct PipelineNamespace {
199 id: PipelineNamespaceId,
200 index: u32,
201}
202
203impl PipelineNamespace {
204 pub fn install(namespace_id: PipelineNamespaceId) {
206 PIPELINE_NAMESPACE.with(|tls| {
207 assert!(tls.get().is_none());
208 tls.set(Some(PipelineNamespace {
209 id: namespace_id,
210 index: 0,
211 }));
212 });
213 }
214
215 pub fn set_installer_sender(sender: GenericSender<PipelineNamespaceRequest>) {
218 PIPELINE_NAMESPACE_INSTALLER.lock().set_sender(sender);
219 }
220
221 pub fn auto_install() {
224 PIPELINE_NAMESPACE_INSTALLER.lock().install_namespace();
232 }
233
234 fn next_index(&mut self) -> NonZeroU32 {
235 self.index += 1;
236 NonZeroU32::new(self.index).expect("pipeline id index wrapped!")
237 }
238
239 fn next_namespace_index<T>(&mut self) -> NamespaceIndex<T> {
240 NamespaceIndex {
241 namespace_id: self.id,
242 index: Index(self.next_index(), PhantomData),
243 }
244 }
245}
246
247thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = const { Cell::new(None) });
248
249#[derive(
250 Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize,
251)]
252pub struct PipelineNamespaceId(pub u32);
253
254namespace_id! {PipelineId, PipelineIndex, "Pipeline"}
255
256size_of_test!(PipelineId, 8);
257size_of_test!(Option<PipelineId>, 8);
258
259impl PipelineId {
260 pub fn root_scroll_id(&self) -> webrender_api::ExternalScrollId {
261 ExternalScrollId(0, self.into())
262 }
263}
264
265impl From<PipelineId> for TreeId {
266 fn from(pipeline_id: PipelineId) -> TreeId {
274 const PIPELINE_IDS: Uuid = Uuid::from_u128(0x429419c0_3277_47eb_8d31_7573b97621ee);
275 let with_namespace_id =
276 Uuid::new_v5(&PIPELINE_IDS, &pipeline_id.namespace_id.0.to_be_bytes());
277 let with_index = Uuid::new_v5(&with_namespace_id, &pipeline_id.index.0.get().to_be_bytes());
278 TreeId(with_index)
279 }
280}
281
282impl From<PipelineId> for u64 {
283 fn from(pipeline_id: PipelineId) -> Self {
284 ((pipeline_id.namespace_id.0 as u64) << 32) + pipeline_id.index.0.get() as u64
285 }
286}
287
288#[cfg(test)]
289#[test]
290fn test_pipeline_id_to_accesskit_tree_id() {
291 let namespace_id = PipelineNamespaceId(1);
292 let index = Index::new(1).expect("Guaranteed by argument");
293 let pipeline_id = PipelineId {
294 namespace_id,
295 index,
296 };
297 assert_eq!(
298 TreeId::from(pipeline_id),
299 TreeId(Uuid::from_u128(0x879211fb_8799_5492_9a31_95a35c05a192))
300 );
301}
302
303impl From<WebRenderPipelineId> for PipelineId {
304 #[expect(unsafe_code)]
305 fn from(pipeline: WebRenderPipelineId) -> Self {
306 let WebRenderPipelineId(namespace_id, index) = pipeline;
307 unsafe {
308 PipelineId {
309 namespace_id: PipelineNamespaceId(namespace_id),
310 index: Index(NonZeroU32::new_unchecked(index), PhantomData),
311 }
312 }
313 }
314}
315
316impl From<PipelineId> for WebRenderPipelineId {
317 fn from(value: PipelineId) -> Self {
318 let PipelineNamespaceId(namespace_id) = value.namespace_id;
319 let Index(index, _) = value.index;
320 WebRenderPipelineId(namespace_id, index.get())
321 }
322}
323
324impl From<&PipelineId> for WebRenderPipelineId {
325 fn from(value: &PipelineId) -> Self {
326 (*value).into()
327 }
328}
329
330namespace_id! {BrowsingContextId, BrowsingContextIndex, "BrowsingContext"}
331
332size_of_test!(BrowsingContextId, 8);
333size_of_test!(Option<BrowsingContextId>, 8);
334
335#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
336pub struct BrowsingContextGroupId(pub u32);
337impl fmt::Display for BrowsingContextGroupId {
338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339 write!(f, "BrowsingContextGroup{:?}", self)
340 }
341}
342
343impl BrowsingContextId {
344 pub fn from_string(str: &str) -> Option<BrowsingContextId> {
345 let re = Regex::new(r"^BrowsingContext\((\d+),(\d+)\)$").ok()?;
346 let caps = re.captures(str)?;
347 let namespace_id = caps.get(1)?.as_str().parse::<u32>().ok()?;
348 let index = caps.get(2)?.as_str().parse::<u32>().ok()?;
349
350 let result = BrowsingContextId {
351 namespace_id: PipelineNamespaceId(namespace_id),
352 index: Index::new(index).ok()?,
353 };
354 assert_eq!(result.to_string(), str.to_string());
355 Some(result)
356 }
357}
358
359#[derive(
360 Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize,
361)]
362pub struct WebViewId(PainterId, BrowsingContextId);
363
364size_of_test!(WebViewId, 12);
365size_of_test!(Option<WebViewId>, 12);
366
367impl fmt::Display for WebViewId {
368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369 write!(f, "{}, TopLevel{}", self.0, self.1)
370 }
371}
372
373impl From<WebViewId> for SpatialTreeItemKey {
374 fn from(webview_id: WebViewId) -> Self {
375 Self::new(webview_id.1.index.0.get() as u64, 0)
376 }
377}
378
379impl WebViewId {
380 pub fn new(painter_id: PainterId) -> WebViewId {
381 WebViewId(painter_id, BrowsingContextId::new())
382 }
383
384 pub fn mock_for_testing(browsing_context_id: BrowsingContextId) -> WebViewId {
385 WebViewId(TEST_PAINTER_ID, browsing_context_id)
386 }
387}
388
389impl From<WebViewId> for BrowsingContextId {
390 fn from(id: WebViewId) -> BrowsingContextId {
391 id.1
392 }
393}
394
395impl From<WebViewId> for PainterId {
396 fn from(id: WebViewId) -> PainterId {
397 id.0
398 }
399}
400
401impl PartialEq<WebViewId> for BrowsingContextId {
402 fn eq(&self, rhs: &WebViewId) -> bool {
403 self.eq(&rhs.1)
404 }
405}
406
407impl PartialEq<BrowsingContextId> for WebViewId {
408 fn eq(&self, rhs: &BrowsingContextId) -> bool {
409 self.1.eq(rhs)
410 }
411}
412
413namespace_id! {MessagePortId, MessagePortIndex, "MessagePort"}
414
415namespace_id! {MessagePortRouterId, MessagePortRouterIndex, "MessagePortRouter"}
416
417namespace_id! {BroadcastChannelRouterId, BroadcastChannelRouterIndex, "BroadcastChannelRouter"}
418
419namespace_id! {ServiceWorkerId, ServiceWorkerIndex, "ServiceWorker"}
420
421namespace_id! {ServiceWorkerRegistrationId, ServiceWorkerRegistrationIndex, "ServiceWorkerRegistration"}
422
423namespace_id! {BlobId, BlobIndex, "Blob"}
424
425namespace_id! {DomPointId, DomPointIndex, "DomPoint"}
426
427namespace_id! {DomRectId, DomRectIndex, "DomRect"}
428
429namespace_id! {DomQuadId, DomQuadIndex, "DomQuad"}
430
431namespace_id! {DomMatrixId, DomMatrixIndex, "DomMatrix"}
432
433namespace_id! {DomExceptionId, DomExceptionIndex, "DomException"}
434
435namespace_id! {QuotaExceededErrorId, QuotaExceededErrorIndex, "QuotaExceededError"}
436
437namespace_id! {HistoryStateId, HistoryStateIndex, "HistoryState"}
438
439namespace_id! {ImageBitmapId, ImageBitmapIndex, "ImageBitmap"}
440
441namespace_id! {OffscreenCanvasId, OffscreenCanvasIndex, "OffscreenCanvas"}
442
443namespace_id! {CookieStoreId, CookieStoreIndex, "CookieStore"}
444
445namespace_id! {ImageDataId, ImageDataIndex, "ImageData"}
446
447pub const TEST_NAMESPACE: PipelineNamespaceId = PipelineNamespaceId(1234);
449pub const TEST_PIPELINE_INDEX: Index<PipelineIndex> =
450 Index(NonZeroU32::new(5678).unwrap(), PhantomData);
451pub const TEST_PIPELINE_ID: PipelineId = PipelineId {
452 namespace_id: TEST_NAMESPACE,
453 index: TEST_PIPELINE_INDEX,
454};
455pub const TEST_BROWSING_CONTEXT_INDEX: Index<BrowsingContextIndex> =
456 Index(NonZeroU32::new(8765).unwrap(), PhantomData);
457pub const TEST_BROWSING_CONTEXT_ID: BrowsingContextId = BrowsingContextId {
458 namespace_id: TEST_NAMESPACE,
459 index: TEST_BROWSING_CONTEXT_INDEX,
460};
461
462pub const TEST_PAINTER_ID: PainterId = PainterId(9999);
463pub const TEST_WEBVIEW_ID: WebViewId = WebViewId(TEST_PAINTER_ID, TEST_BROWSING_CONTEXT_ID);
464pub const TEST_SCRIPT_EVENT_LOOP_ID: ScriptEventLoopId = ScriptEventLoopId(1234);
465
466#[derive(Clone, Copy, Debug, Default, Deserialize, MallocSizeOf, PartialEq, Serialize)]
470pub struct ScrollTreeNodeId {
471 pub index: usize,
473}
474
475static PAINTER_ID: AtomicU32 = AtomicU32::new(1);
476
477#[derive(
478 Clone, Copy, Debug, PartialEq, PartialOrd, Ord, Hash, Eq, Serialize, Deserialize, MallocSizeOf,
479)]
480pub struct PainterId(u32);
481
482impl fmt::Display for PainterId {
483 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
484 write!(f, "PainterId: {}", self.0)
485 }
486}
487
488impl PainterId {
489 pub fn next() -> Self {
490 Self(PAINTER_ID.fetch_add(1, Ordering::Relaxed))
491 }
492}
493
494impl From<PainterId> for IdNamespace {
495 fn from(painter_id: PainterId) -> Self {
496 IdNamespace(painter_id.0)
497 }
498}
499
500impl From<IdNamespace> for PainterId {
501 fn from(id_namespace: IdNamespace) -> Self {
502 PainterId(id_namespace.0)
503 }
504}
505
506impl From<FontKey> for PainterId {
507 fn from(font_key: FontKey) -> Self {
508 font_key.0.into()
509 }
510}
511
512impl From<FontInstanceKey> for PainterId {
513 fn from(font_instance_key: FontInstanceKey) -> Self {
514 font_instance_key.0.into()
515 }
516}
517
518impl From<ImageKey> for PainterId {
519 fn from(image_key: ImageKey) -> Self {
520 image_key.0.into()
521 }
522}
523
524static SCRIPT_EVENT_LOOP_ID: AtomicU32 = AtomicU32::new(1);
525thread_local!(pub static INSTALLED_SCRIPT_EVENT_LOOP_ID: Cell<Option<ScriptEventLoopId>> =
526 const { Cell::new(None) });
527
528#[derive(
529 Clone, Copy, Debug, PartialEq, PartialOrd, Ord, Hash, Eq, Serialize, Deserialize, MallocSizeOf,
530)]
531pub struct ScriptEventLoopId(u32);
532
533impl ScriptEventLoopId {
534 pub fn new() -> Self {
535 Self(SCRIPT_EVENT_LOOP_ID.fetch_add(1, Ordering::Relaxed))
536 }
537
538 pub fn install(id: Self) {
541 INSTALLED_SCRIPT_EVENT_LOOP_ID.with(|tls| tls.set(Some(id)))
542 }
543
544 pub fn installed() -> Option<Self> {
545 INSTALLED_SCRIPT_EVENT_LOOP_ID.with(|tls| tls.get())
546 }
547}
548
549impl fmt::Display for ScriptEventLoopId {
550 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551 write!(f, "{}", self.0)
552 }
553}