layaway 0.2.0

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

pub type Pixel = i32;

/// Rectangle in pixels.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Rect {
    pub x: Interval,
    pub y: Interval,
}

impl Rect {
    #[must_use]
    pub fn vertices(&self) -> [Point; 4] {
        [
            (self.x.start(), self.y.start()),
            (self.x.end(), self.y.start()),
            (self.x.start(), self.y.end()),
            (self.x.end(), self.y.end()),
        ]
        .map(|(x, y)| Point { x, y })
    }

    #[must_use]
    pub fn size(&self) -> Size {
        Size {
            width: self.x.len(),
            height: self.y.len(),
        }
    }

    #[must_use]
    pub fn contains(&self, subject: Point) -> bool {
        self.x.contains(subject.x) && self.y.contains(subject.y)
    }

    /// If `target` is outside of the rect,
    /// move corners of the rect to exactly include it.
    /// Otherwise, do nothing.
    pub fn stretch_to_point(&mut self, target: Point) {
        self.x.stretch_to(target.x);
        self.y.stretch_to(target.y);
    }

    pub fn stretch_to_rect(&mut self, target: Self) {
        for vertex in target.vertices() {
            self.stretch_to_point(vertex);
        }
    }

    /// Divides the size by the given `factor`,
    /// such that all corners _except_ the given one move
    /// (if `factor != 1.0`).
    /// The given corner is not moved.
    ///
    /// Assumes a coordinate system where
    /// x+ is right-hand and y+ is towards bottom.
    pub fn divide_at(&mut self, corner: Corner, divisor: f64) {
        self.x.divide_at(corner.hori.into(), divisor);
        self.y.divide_at(corner.vert.into(), divisor);
    }

    /// Swaps width and height
    /// if the rotation is [`Rotation::Quarter`] or [`Rotation::ThreeQuarter`],
    /// keeping `corner` at the same position in any case.
    /// Otherwise, does nothing.
    pub fn rotate_in_place(&mut self, corner: Corner, amount: Rotation) {
        if let Rotation::None | Rotation::Half = amount {
            // no need to "rotate"
            return;
        }

        self.transpose(corner);
    }

    /// Swaps width and height
    /// keeping `corner` at the same position in any case.
    pub fn transpose(&mut self, Corner { vert, hori }: Corner) {
        let prev_x_len = self.x.len();
        self.x.set_len(hori.into(), self.y.len());
        self.y.set_len(vert.into(), prev_x_len);
    }
}

impl Add<Point> for Rect {
    type Output = Self;
    fn add(self, rhs: Point) -> Self {
        Self {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
        }
    }
}

impl Sub<Point> for Rect {
    type Output = Self;
    fn sub(self, rhs: Point) -> Self {
        self + -rhs
    }
}

impl AddAssign<Point> for Rect {
    fn add_assign(&mut self, rhs: Point) {
        *self = *self + rhs;
    }
}

impl SubAssign<Point> for Rect {
    fn sub_assign(&mut self, rhs: Point) {
        *self += -rhs;
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Point {
    pub x: Pixel,
    pub y: Pixel,
}

impl Neg for Point {
    type Output = Self;
    fn neg(self) -> Self {
        Self {
            x: -self.x,
            y: -self.y,
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Size {
    pub width: Pixel,
    pub height: Pixel,
}

impl Size {
    /// Flips width and height
    /// if the rotation is [`Rotation::Quarter`] or [`Rotation::ThreeQuarter`],
    #[must_use]
    pub fn rotate(&self, amount: Rotation) -> Self {
        if let Rotation::None | Rotation::Half = amount {
            return *self;
        }

        let Self { width, height } = *self;
        Self {
            width: height,
            height: width,
        }
    }
}

impl Mul<f64> for Size {
    type Output = Self;

    #[allow(clippy::cast_possible_truncation)]
    fn mul(self, rhs: f64) -> Self::Output {
        Self {
            width: (self.width as f64 * rhs) as Pixel,
            height: (self.height as f64 * rhs) as Pixel,
        }
    }
}

impl Div<f64> for Size {
    type Output = Self;

    #[allow(clippy::cast_possible_truncation)]
    fn div(self, rhs: f64) -> Self::Output {
        Self {
            width: (self.width as f64 / rhs) as Pixel,
            height: (self.height as f64 / rhs) as Pixel,
        }
    }
}

/// Range thought in pixels.
/// [`std::ops::RangeInclusive`] but not since it's too restricted
/// and does not implement `PartialOrd`.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Interval {
    start: Pixel,
    end: Pixel,
}

impl Interval {
    /// Creates a new [`Interval`] between `a` and `b`.
    /// `b` may be less than `a`.
    #[must_use]
    pub fn new(a: Pixel, b: Pixel) -> Self {
        let (start, end) = if b < a { (b, a) } else { (a, b) };

        Self { start, end }
    }

    #[must_use]
    pub fn start(&self) -> Pixel {
        self.start
    }

    #[must_use]
    pub fn end(&self) -> Pixel {
        self.end
    }

    #[must_use]
    pub fn mid(&self) -> Pixel {
        (self.start + self.end) / 2
    }

    #[must_use]
    pub fn len(&self) -> Pixel {
        self.end - self.start
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.start == self.end
    }

    #[must_use]
    pub fn contains(&self, subject: Pixel) -> bool {
        self.start <= subject && subject <= self.end
    }

    /// Sets the length of this interval, keeping one limit
    /// and overriding the other one.
    pub fn set_len(&mut self, keep: Side, to: Pixel) {
        match keep {
            Side::Least => self.end = self.start + to,
            Side::Most => self.start = self.end - to,
        }
        self.fix_invariants();
    }

    /// If `target` is outside the interval,
    /// move the bound which is nearer to be `target` instead.
    /// Otherwise, it's inside, and do nothing.
    ///
    /// # Panics
    ///
    /// Panics if internal invariants are not upheld.
    /// If that happens, that's a bug.
    pub fn stretch_to(&mut self, target: Pixel) {
        if self.contains(target) {
            return;
        }

        let Self { start, end } = self;

        // on which side is `target`, before `start` or after `end`?
        match (target < *start, *end < target) {
            (true, false) => *start = target,
            (false, true) => *end = target,
            _ => panic!("end is before start, meaning broken invariants"),
        }
    }

    /// Divides the length by the given `factor`
    /// such that the limit on `side`
    /// stays at the same position.
    #[allow(clippy::cast_possible_truncation)]
    pub fn divide_at(&mut self, side: Side, divisor: f64) {
        self.set_len(side, (self.len() as f64 / divisor) as Pixel);
    }

    /// Creates a new [`Interval`] of the given `length` next to this interval,
    /// on the given `side`.
    /// The new interval will touch this one and share one limit.
    ///
    /// # Examples
    ///
    /// ```
    /// # use layaway::geometry::{Side, Interval};
    /// let space = Interval::new(100, 200);
    /// let length = 20;
    /// assert_eq!(
    ///     space.place_outside(10, Side::Least),
    ///     Interval::new(90, 100),
    /// );
    /// ```
    #[must_use]
    pub fn place_outside(self, length: Pixel, side: Side) -> Self {
        match side {
            Side::Least => Self::new(self.start - length, self.start()),
            Side::Most => Self::new(self.end, self.end + length),
        }
    }

    /// Creates a new [`Interval`] of the given `length` inside of interval,
    /// on the given `side`.
    #[must_use]
    pub fn place_inside(self, length: Pixel, pos: MaybeCenter<Side>) -> Self {
        match pos {
            MaybeCenter::Extreme(Side::Least) => Self::new(self.start(), self.start() + length),
            MaybeCenter::Center => Self::new(self.mid() - length / 2, self.mid() + length / 2),
            MaybeCenter::Extreme(Side::Most) => Self::new(self.end - length, self.end),
        }
    }

    /// Sets `start` before `end` if necessary.
    fn fix_invariants(&mut self) {
        let Self { start, end } = self;
        if end < start {
            mem::swap(start, end);
        }
    }
}

impl Add<Pixel> for Interval {
    type Output = Self;
    fn add(self, rhs: Pixel) -> Self {
        Self {
            start: self.start + rhs,
            end: self.end + rhs,
        }
    }
}

impl Sub<Pixel> for Interval {
    type Output = Self;
    fn sub(self, rhs: Pixel) -> Self {
        self + -rhs
    }
}

/// One corner of a [`Rect`].
#[derive(Clone, Copy, Debug)]
pub struct Corner {
    /// Whether the corner is left or right.
    pub hori: Hori,
    /// Whether the corner is at the top or bottom.
    pub vert: Vert,
}

impl Corner {
    pub const UPPER_LEFT: Self = Self {
        hori: Hori::Left,
        vert: Vert::Top,
    };
}

#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Hori {
    Left,
    #[default]
    Right,
}

impl From<Corner> for Hori {
    fn from(corner: Corner) -> Self {
        corner.hori
    }
}

#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Vert {
    #[default]
    Top,
    Bottom,
}

impl From<Corner> for Vert {
    fn from(corner: Corner) -> Self {
        corner.vert
    }
}

pub type HoriSpec = MaybeCenter<Hori>;
pub type VertSpec = MaybeCenter<Vert>;

impl Default for HoriSpec {
    fn default() -> Self {
        Self::Center
    }
}

impl Default for VertSpec {
    fn default() -> Self {
        Self::Extreme(Vert::Top)
    }
}

#[derive(Clone, Copy, Debug)]
pub enum MaybeCenter<T: Clone + Copy + fmt::Debug> {
    Extreme(T),
    Center,
}

impl<T: Clone + Copy + fmt::Debug> MaybeCenter<T> {
    pub fn map<U: Clone + Copy + fmt::Debug>(self, op: impl FnOnce(T) -> U) -> MaybeCenter<U> {
        match self {
            Self::Center => MaybeCenter::Center,
            Self::Extreme(extreme) => MaybeCenter::Extreme(op(extreme)),
        }
    }
}

impl<T: Clone + Copy + fmt::Debug> From<T> for MaybeCenter<T> {
    fn from(value: T) -> Self {
        Self::Extreme(value)
    }
}

/// Specifies one side of a 1D [`Interval`].
#[derive(Clone, Copy, Debug)]
pub enum Side {
    Least,
    Most,
}

// assuming a x+ right, y- bottom coordinate system

impl From<Hori> for Side {
    fn from(value: Hori) -> Self {
        match value {
            Hori::Left => Self::Least,
            Hori::Right => Self::Most,
        }
    }
}

impl From<Vert> for Side {
    fn from(value: Vert) -> Self {
        match value {
            Vert::Top => Self::Least,
            Vert::Bottom => Self::Most,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Transform {
    pub flipped: bool,
    pub rotation: Rotation,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum Rotation {
    #[default]
    None,
    Quarter,
    Half,
    ThreeQuarter,
}