jay-compositor 1.14.0

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

thread_local! {
    static EMPTY: Rc<Region> =
        Rc::new(Region {
            rects: Default::default(),
            extents: Default::default(),
        });
}

impl Region {
    pub fn empty() -> Rc<Self> {
        EMPTY.with(|e| e.clone())
    }

    pub fn from_rects(rects: &[Rect]) -> Rc<Self> {
        if rects.is_empty() {
            return Self::empty();
        }
        Rc::new(Self::from_rects2(rects))
    }

    pub fn from_rects2(rects: &[Rect]) -> Self {
        if rects.is_empty() {
            return Self::default();
        }
        if rects.len() == 1 {
            return Self::new(rects[0]);
        }
        let rects = rects_to_bands(unsafe { mem::transmute::<&[Rect], &[RectRaw]>(rects) });
        Self {
            extents: Rect {
                raw: extents(&rects),
            },
            rects,
        }
    }

    pub fn union(self: &Rc<Self>, other: &Rc<Self>) -> Rc<Self> {
        if self.extents.is_empty() {
            return other.clone();
        }
        if other.extents.is_empty() {
            return self.clone();
        }
        let rects = union(&self.rects, &other.rects);
        Rc::new(Self {
            rects,
            extents: self.extents.union(other.extents),
        })
    }

    pub fn union_cow<'a>(&'a self, other: &'a Self) -> Cow<'a, Region> {
        if self.extents.is_empty() {
            return Cow::Borrowed(other);
        }
        if other.extents.is_empty() {
            return Cow::Borrowed(self);
        }
        let rects = union(&self.rects, &other.rects);
        Cow::Owned(Self {
            rects,
            extents: self.extents.union(other.extents),
        })
    }

    pub fn subtract(self: &Rc<Self>, other: &Rc<Self>) -> Rc<Self> {
        if self.extents.is_empty() || other.extents.is_empty() {
            return self.clone();
        }
        let rects = subtract(&self.rects, &other.rects);
        Rc::new(Self {
            extents: Rect {
                raw: extents(&rects),
            },
            rects,
        })
    }

    pub fn subtract_cow<'a>(&'a self, other: &Self) -> Cow<'a, Self> {
        if self.extents.is_empty() || other.extents.is_empty() {
            return Cow::Borrowed(self);
        }
        let rects = subtract(&self.rects, &other.rects);
        Cow::Owned(Self {
            extents: Rect {
                raw: extents(&rects),
            },
            rects,
        })
    }

    pub fn intersect(&self, other: &Region) -> Self {
        if self.is_empty() || other.is_empty() {
            return Self::default();
        }
        let rects = intersect(&self.rects, &other.rects);
        Self {
            extents: Rect {
                raw: extents(&rects),
            },
            rects,
        }
    }
}

impl Region<u32> {
    pub fn from_rects_tagged(rects: &[Rect<u32>]) -> Self {
        if rects.is_empty() {
            return Self::default();
        }
        if rects.len() == 1 {
            let mut rect = rects[0];
            rect.raw.tag = rect.raw.tag.constrain();
            return Self::new(rect);
        }
        let rects = rects_to_bands_tagged(unsafe {
            mem::transmute::<&[Rect<u32>], &[RectRaw<u32>]>(rects)
        });
        Self {
            extents: Rect {
                raw: extents(&rects),
            },
            rects,
        }
    }

    pub fn intersect_tagged(&self, other: &Region) -> Self {
        if self.is_empty() || other.is_empty() {
            return Self::default();
        }
        let rects = intersect_tagged(&self.rects, &other.rects);
        Self {
            extents: Rect {
                raw: extents(&rects),
            },
            rects,
        }
    }
}

impl<T> Region<T>
where
    T: Tag,
{
    pub fn new(rect: Rect<T>) -> Self {
        let mut rects = SmallVec::new();
        rects.push(rect.raw);
        Self {
            rects,
            extents: rect.untag(),
        }
    }

    pub fn extents(&self) -> Rect {
        self.extents
    }

    pub fn rects(&self) -> &[Rect<T>] {
        unsafe { mem::transmute::<&[RectRaw<T>], &[Rect<T>]>(&self.rects[..]) }
    }

    pub fn contains(&self, x: i32, y: i32) -> bool {
        if !self.extents.contains(x, y) {
            return false;
        }
        for r in self.deref() {
            if r.contains(x, y) {
                return true;
            }
        }
        false
    }

    pub fn contains_rect(&self, rect: &Rect) -> bool {
        self.contains_rect2(rect, |r| *r)
    }

    pub fn contains_rect2(&self, rect: &Rect, map: impl Fn(&Rect<T>) -> Rect<T>) -> bool {
        if rect.is_empty() {
            return true;
        }
        let mut y1 = rect.y1();
        for r in self.rects() {
            let r = map(r);
            if r.y2() <= y1 || r.x2() <= rect.x1() {
                continue;
            }
            if r.y1() > y1 || r.x1() > rect.x1() || r.x2() < rect.x2() {
                return false;
            }
            y1 = r.y2();
            if y1 >= rect.y2() {
                return true;
            }
        }
        false
    }
}

impl<T> Deref for Region<T>
where
    T: Tag,
{
    type Target = [Rect<T>];

    fn deref(&self) -> &Self::Target {
        unsafe { mem::transmute::<&[RectRaw<T>], _>(&self.rects) }
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Debug, Default)]
enum BuilderOp {
    #[default]
    Add,
    Sub,
}

#[derive(Debug)]
pub struct RegionBuilder {
    base: Rc<Region>,
    op: BuilderOp,
    pending: Vec<Rect>,
}

impl Default for RegionBuilder {
    fn default() -> Self {
        Self {
            base: Region::empty(),
            op: Default::default(),
            pending: Default::default(),
        }
    }
}

impl RegionBuilder {
    pub fn add(&mut self, rect: Rect) {
        self.set_op(BuilderOp::Add);
        self.pending.push(rect);
    }

    pub fn sub(&mut self, rect: Rect) {
        self.set_op(BuilderOp::Sub);
        self.pending.push(rect);
    }

    pub fn get(&mut self) -> Rc<Region> {
        self.flush();
        self.base.clone()
    }

    #[expect(dead_code)]
    pub fn clear(&mut self) {
        self.pending.clear();
        self.base = Region::empty();
    }

    fn set_op(&mut self, op: BuilderOp) {
        if self.op != op {
            self.flush();
            self.op = op;
        }
    }

    fn flush(&mut self) {
        if self.pending.is_empty() {
            return;
        }
        let region = Region::from_rects(&self.pending);
        self.base = match self.op {
            BuilderOp::Add => self.base.union(&region),
            BuilderOp::Sub => self.base.subtract(&region),
        };
        self.pending.clear();
    }
}

pub struct DamageQueue {
    this: usize,
    datas: Rc<UnsafeCell<Vec<Vec<Rect>>>>,
}

impl Debug for DamageQueue {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DamageQueue").finish_non_exhaustive()
    }
}

impl DamageQueue {
    pub fn new<const N: usize>() -> [DamageQueue; N] {
        let datas = Rc::new(UnsafeCell::new(vec![vec!(); N]));
        array::from_fn(|this| DamageQueue {
            this,
            datas: datas.clone(),
        })
    }

    pub fn damage(&self, rects: &[Rect]) {
        let datas = unsafe { self.datas.get().deref_mut() };
        for data in datas {
            data.extend(rects);
        }
    }

    pub fn clear(&self) {
        let data = unsafe { &mut self.datas.get().deref_mut()[self.this] };
        data.clear();
    }

    pub fn clear_all(&self) {
        let datas = unsafe { self.datas.get().deref_mut() };
        for data in datas {
            data.clear();
        }
    }

    pub fn get(&self) -> Region {
        let data = unsafe { &self.datas.get().deref()[self.this] };
        Region::from_rects2(data)
    }
}

#[derive(Default)]
pub struct DynamicDamageQueue {
    datas: UnsafeCell<Vec<Option<Rc<UnsafeCell<Vec<Rect>>>>>>,
}

pub struct DynamicDamageQueueElement {
    this: usize,
    queue: Rc<DynamicDamageQueue>,
    damage: Rc<UnsafeCell<Vec<Rect>>>,
}

impl Debug for DynamicDamageQueue {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DynamicDamageQueue").finish_non_exhaustive()
    }
}

impl DynamicDamageQueue {
    pub fn add_element(self: &Rc<Self>) -> DynamicDamageQueueElement {
        let datas = unsafe { self.datas.get().deref_mut() };
        for (idx, vec) in datas.iter_mut().enumerate() {
            if vec.is_none() {
                let damage = vec.insert(Default::default());
                return DynamicDamageQueueElement {
                    this: idx,
                    queue: self.clone(),
                    damage: damage.clone(),
                };
            }
        }
        let idx = datas.len();
        let damage: Rc<UnsafeCell<Vec<Rect>>> = Default::default();
        datas.push(Some(damage.clone()));
        DynamicDamageQueueElement {
            this: idx,
            queue: self.clone(),
            damage,
        }
    }

    pub fn damage(&self, rects: &[Rect]) {
        let datas = unsafe { self.datas.get().deref_mut() };
        for data in datas {
            if let Some(data) = data {
                let data = unsafe { data.get().deref_mut() };
                data.extend_from_slice(rects);
            }
        }
    }

    pub fn clear_all(&self) {
        let datas = unsafe { self.datas.get().deref_mut() };
        for data in datas {
            if let Some(data) = data {
                let data = unsafe { data.get().deref_mut() };
                data.clear();
            }
        }
    }
}

impl DynamicDamageQueueElement {
    pub fn clear(&self) {
        let damage = unsafe { self.damage.get().deref_mut() };
        damage.clear();
    }

    pub fn get(&self) -> Region {
        let damage = unsafe { self.damage.get().deref() };
        Region::from_rects2(damage)
    }

    pub fn damage_self(&self, rects: &[Rect]) {
        let damage = unsafe { self.damage.get().deref_mut() };
        damage.extend_from_slice(rects);
    }
}

impl Deref for DynamicDamageQueueElement {
    type Target = DynamicDamageQueue;

    fn deref(&self) -> &Self::Target {
        &self.queue
    }
}

impl Drop for DynamicDamageQueueElement {
    fn drop(&mut self) {
        let data = unsafe { self.queue.datas.get().deref_mut() };
        data[self.this] = None;
        while let Some(None) = data.last() {
            data.pop();
        }
    }
}