kitty_image 0.1.0

Display images using the kitty image protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
#![doc=include_str!("../README.md")]

use core::fmt;
use std::{
    borrow::Cow,
    fmt::{Display, Formatter},
    io::{self, ErrorKind, Write},
    num::NonZeroU32,
    path::Path,
};

use base64::engine::general_purpose::STANDARD;
#[cfg(feature = "image")]
use image::{GenericImageView, Pixel};
mod diacritics;
pub use diacritics::*;

/// A command which prints the escape
#[derive(Debug)]
pub struct WrappedCommand<'a> {
    /// The command to enclose
    pub command: Command<'a>,
    // Whether to double escape.
    //
    // This is useful for executing certain commands
    // within TMUX, where you should set this to `true`, and
    // before you start sending any data send `"\x1bPtmux"` and
    // afterwards send `"\x1b\\"`
    pub double_escape: bool,
}

impl<'a> WrappedCommand<'a> {
    pub fn new(command: Command<'a>) -> Self {
        Self {
            command,
            double_escape: false,
        }
    }

    /// Get the escape sequence for this
    pub fn escape(&self) -> &'static str {
        match self.double_escape {
            true => "\x1b\x1b",
            false => "\x1b",
        }
    }

    /// Will write this command chunked
    ///
    /// This is mainly useful for [`Medium::Direct`]
    pub fn send_chunked<W: Write>(&self, mut w: &mut W) -> io::Result<()> {
        let escape = self.escape();

        let mut first = true;
        for (i, bytes) in self.command.payload.chunks(3096).enumerate() {
            if first {
                write!(
                    w,
                    "{escape}{}{escape}\\",
                    Command {
                        action: self.command.action,
                        quietness: self.command.quietness,
                        id: self.command.id,
                        m: (i + 1) * 3096 <= self.command.payload.len(),
                        payload: bytes.into(),
                    }
                )?;
                first = false;
            } else {
                write!(
                    w,
                    "{escape}_Ga={},m={m};",
                    self.command.action.char(),
                    m = u8::from((i + 1) * 3096 < self.command.payload.len()),
                )?;

                // Write payload
                let mut encoder_writer = base64::write::EncoderWriter::new(&mut w, &STANDARD);
                encoder_writer.write_all(bytes)?;
                let w = encoder_writer.finish()?;

                write!(w, "{escape}\\")?;
            };
        }

        Ok(())
    }
}

impl Display for WrappedCommand<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let escape = self.escape();
        write!(f, "{escape}{}{escape}\\", self.command)
    }
}

/// A command to the kitty graphics protocol.
///
/// You will mainly want to format this as a string,
/// which can then be sent to the kitty implementation. Note
/// that this does not automatically include the initial
/// or terminal escape. Use [`WrappedCommand`] for that.
///
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Debug)]
pub struct Command<'a> {
    /// What action to do
    pub action: Action,
    /// How quiet to do it
    pub quietness: Quietness,
    /// The id of the image
    pub id: Option<ID>,
    /// Whether there is more chunked data available
    pub m: bool,
    /// The payload
    pub payload: Cow<'a, [u8]>,
}

impl Command<'static> {
    #[cfg(feature = "image")]
    pub fn with_payload_from_image<I, P>(action: Action, image: &I) -> Self
    where
        I: GenericImageView<Pixel = P>,
        P: Pixel<Subpixel = u8>,
    {
        let mut pixels: Vec<u8> = image.pixels().flat_map(|(_, _, x)| x.to_rgba().0).collect();
        Self {
            action,
            quietness: Quietness::None,
            id: None,
            payload: pixels.into(),
            m: false,
        }
    }
}
impl<'a> Command<'a> {
    pub fn new(action: Action) -> Self {
        Self {
            action,
            quietness: Quietness::None,
            id: None,
            payload: Cow::Borrowed(&[]),
            m: false,
        }
    }

    pub fn with_payload_from_path(action: Action, path: &'a Path) -> Self {
        Self {
            action,
            quietness: Quietness::None,
            id: None,
            payload: path
                .as_os_str()
                .to_str()
                .map(|x| x.as_bytes().into())
                .unwrap_or(Cow::Borrowed(&[])),
            m: false,
        }
    }
}

struct DisplayWriter<'a, 'b>(&'a mut fmt::Formatter<'b>);

impl<'a, 'b> io::Write for DisplayWriter<'a, 'b> {
    fn write(&mut self, bytes: &[u8]) -> Result<usize, io::Error> {
        let s =
            std::str::from_utf8(bytes).map_err(|x| io::Error::new(ErrorKind::InvalidData, x))?;
        self.0
            .write_str(s)
            .map_err(|err| std::io::Error::new(io::ErrorKind::Other, err))?;

        Ok(bytes.len())
    }

    fn flush(&mut self) -> Result<(), io::Error> {
        Ok(())
    }
}

impl Display for Command<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "_G")?;
        write!(f, "{}", self.quietness)?;
        write!(f, "{}", self.action)?;
        if let Some(id) = self.id {
            write!(f, "i={id},")?;
        }
        if self.m {
            write!(f, "m=1")?;
        } else {
            write!(f, "m=0")?;
        }
        write!(f, ";")?;
        let mut encoder_writer = base64::write::EncoderWriter::new(DisplayWriter(f), &STANDARD);
        encoder_writer
            .write_all(&self.payload)
            .map_err(|_| fmt::Error)?;

        Ok(())
    }
}

/// The quiteness of the operation
#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default, Debug)]
pub enum Quietness {
    /// Full volume
    #[default]
    None,
    /// Supresses 'ok' messages
    SupressOk,
    /// Suppressed 'ok' and error messagsde
    SuppressAll,
}

impl Display for Quietness {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Quietness::None => Ok(()),
            Quietness::SupressOk => write!(f, "q=1,"),
            Quietness::SuppressAll => write!(f, "q=2,"),
        }
    }
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Debug)]
pub enum Action {
    /// Transmit image data
    Transmit(ActionTransmission),
    /// Transmist image data and display it
    TransmitAndDisplay(ActionTransmission, ActionPut),
    /// Make a query
    Query,
    /// Display image data
    Put(ActionPut),
    /// Load animation frames
    AnimationFrameLoading(ActionAnimationFrameLoading),
    /// Compose animation frames
    AnimationFrameComposition(ActionAnimationFrameComposition),
    /// Control animation frames
    AnimationFrameControl(ActionAnimationFrameControl),
    /// Delete
    Delete(ActionDelete),
}

impl Action {
    pub fn char(&self) -> char {
        match self {
            Action::Transmit(_) => 't',
            Action::TransmitAndDisplay(_, _) => 'T',
            Action::Query => 'q',
            Action::Put(_) => 'p',
            Action::AnimationFrameLoading(_) => 'f',
            Action::AnimationFrameComposition(_) => 'c',
            Action::AnimationFrameControl(_) => 'a',
            Action::Delete(_) => 'd',
        }
    }
}

impl Display for Action {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Action::Transmit(x) => write!(f, "a=t,{x}"),
            Action::TransmitAndDisplay(t, p) => write!(f, "a=T,{t}{p}"),
            Action::Query => write!(f, "a=q,"),
            Action::Put(x) => write!(f, "a=p,{x}"),
            Action::AnimationFrameLoading(x) => write!(f, "a=f,{x}"),
            Action::AnimationFrameComposition(x) => write!(f, "a=c,{x}"),
            Action::AnimationFrameControl(x) => write!(f, "a=a,{x}"),
            Action::Delete(x) => write!(f, "a=d,{x}"),
        }
    }
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default, Debug)]
pub struct ActionTransmission {
    /// The format in which the image data is sent
    pub format: Format,
    /// The transmission medium used
    pub medium: Medium,
    /// The width of the image being sent
    pub width: u32,
    /// The height of the image being sent
    pub height: u32,
    /// The size of data to read from a file (if applicable)
    pub size: u32,
    /// The offset from which to read data from a file (if applicable)
    pub offset: u32,
    /// The image number
    pub number: u32,
    /// The placement id
    pub placement: Placement,
    /// Whether the data is in zlib compression
    pub compression: bool,
}

impl Display for ActionTransmission {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "f={},", self.format)?;
        write!(f, "t={},", self.medium)?;
        write!(f, "s={},", self.width)?;
        write!(f, "v={},", self.height)?;
        write!(f, "S={},", self.size)?;
        write!(f, "O={},", self.offset)?;
        write!(f, "I={},", self.number)?;
        if let Some(placement) = self.placement.0 {
            write!(f, "p={placement},")?;
        }
        if self.compression {
            write!(f, "o=z,")?;
        }

        Ok(())
    }
}

/// The format of the data
#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default, Debug)]
pub enum Format {
    /// 24 bit rgb
    Rgb24,
    /// 32 bit rgba
    #[default]
    Rgba32,
    /// Png
    Png,
}

impl Display for Format {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Format::Rgb24 => "24",
            Format::Rgba32 => "32",
            Format::Png => "100",
        })
    }
}

/// The medium to use
#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default, Debug)]
pub enum Medium {
    /// The file is stored in the escape code itsel
    #[default]
    Direct,
    /// A simple file (regular files only, not named pipes, device files, &c)
    ///
    /// The filepath should be stored in the data section
    File,
    /// A temporary file
    ///
    /// The terminal emulator will delete the file after reading the pixel data.
    /// For security reasons, the terminal emulator should only delete the file if
    /// in a known temporary directory, such as `/tmp`, `/dev/shm`, `TMPDIR env if present`
    /// and any platform specific temporary directories and the file has the string `tty-graphics-protocol`
    /// in its full path
    TemporaryFile,
    /// A shared memory object, which on POSIX systems is a POSIX shared memory object,
    /// and on Windows is a Named shared memory object. The terminal emulator must read
    /// the data from the memory object and then unlink and close it on POSIX and just
    /// close it on windows.
    SharedMemoryObject,
}

impl Display for Medium {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Medium::Direct => "d",
            Medium::File => "f",
            Medium::TemporaryFile => "t",
            Medium::SharedMemoryObject => "s",
        })
    }
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default, Debug)]
pub struct ActionPut {
    /// The left edge (in pixels) of the image area to display
    pub x: u32,
    /// The top edge (in pixels) of the image area to display
    pub y: u32,
    /// The width (in pixels) of the image area to display.
    /// By default, the entire width is used.
    pub w: u32,
    /// The height (in pixels) of the image area to display.
    /// By default, the entire height is used.
    pub h: u32,
    /// The x-offset within the first cell at which to start
    /// displaying the image
    pub x_offset: u32,
    /// The y-offset within the first cell at which to start
    /// displaying the image
    pub y_offset: u32,
    //// The number of columns to display the image over
    pub columns: u32,
    //// The number of rows to display the image over
    pub rows: u32,
    /// Whether the cursor should be moved after
    /// printing the image
    pub move_cursor: bool,
    /// Whether this is a unicode placeholder. The
    /// cursor will not be moved if it is
    pub unicode_placeholder: bool,
    /// The z-index vertical staking order of the image
    pub z_index: u32,
    /// The ID of a parent image for relative placement
    pub parent_image: Option<ID>,
    /// The id of a placement in the parent image for relative placement
    pub parent_placement: Placement,
    /// The offset in cells in the horizontal direction for
    /// relative placement
    pub cell_relative_offset_horizontal: u32,
    /// The offset in cells in the vertical direction for
    /// relative placement
    pub cell_relative_offset_vertical: u32,
}

impl Display for ActionPut {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if self.x != 0 {
            write!(f, "x={},", self.x)?;
        }
        if self.y != 0 {
            write!(f, "y={},", self.y)?;
        }
        if self.w != 0 {
            write!(f, "w={},", self.w)?;
        }
        if self.h != 0 {
            write!(f, "h={},", self.h)?;
        }
        if self.x_offset != 0 {
            write!(f, "X={},", self.x_offset)?;
        }
        if self.y_offset != 0 {
            write!(f, "Y={},", self.y_offset)?;
        }
        if self.columns != 0 {
            write!(f, "c={},", self.columns)?;
        }
        if self.rows != 0 {
            write!(f, "r={},", self.rows)?;
        }
        if !self.move_cursor {
            write!(f, "C=1,")?;
        }
        if self.unicode_placeholder {
            write!(f, "U=1,")?;
        }
        if self.z_index != 0 {
            write!(f, "z={},", self.z_index)?;
        }
        if let Some(parent) = self.parent_image {
            write!(f, "P={parent},")?;
        }
        if let Some(parent_placement) = self.parent_placement.0 {
            write!(f, "Q={parent_placement},")?;
        }
        if self.cell_relative_offset_horizontal != 0 {
            write!(f, "H={},", self.cell_relative_offset_horizontal)?;
        }
        if self.cell_relative_offset_vertical != 0 {
            write!(f, "V={},", self.cell_relative_offset_vertical)?;
        }

        Ok(())
    }
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default, Debug)]
pub struct ActionAnimationFrameLoading {
    /// The left edge (in pixels) of the image area to display
    pub x: u32,
    /// The top edge (in pixels) of the image area to display
    pub y: u32,
    /// The 1-based frame number of the frame whose image data
    /// serves as the base data when creating a new frame, by
    /// default the base data is black, fully transparent pixels
    pub frame_number: Option<Frame>,
    /// The 1-based frame number of the frame that is being edited.
    /// By default, a new frame is created
    pub frame_edited: Option<Frame>,
    /// The gap (in milliseconds) of this frame from the next one.
    /// A value of zero is ignored. Negative values create
    /// a *gapless* frame. If not specified, frames have a default
    /// gap of `40ms`. The root frame defaults to zero gap
    pub gap: i32,
    /// The composition mode for blending pixels when creating a new frame or
    /// editing a frame's data. The default is full alpha blending.
    pub composition_mode: CompositionMode,
    /// The background color for pixels not specified in the frame data.
    /// In RGBA
    pub color: u32,
}

impl Display for ActionAnimationFrameLoading {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if self.x != 0 {
            write!(f, "x={},", self.x)?;
        }
        if self.y != 0 {
            write!(f, "y={},", self.y)?;
        }
        if let Some(frame_number) = self.frame_number {
            write!(f, "c={frame_number},")?;
        }
        if let Some(frame_edited) = self.frame_edited {
            write!(f, "r={frame_edited },")?;
        }
        if self.gap != 0 {
            write!(f, "z={},", self.gap)?;
        }
        if self.composition_mode != CompositionMode::default() {
            write!(f, "X={},", self.gap)?;
        }
        if self.color != 0 {
            write!(f, "Y={},", self.color)?;
        }

        Ok(())
    }
}

#[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum CompositionMode {
    /// Blend between pixels
    #[default]
    AlphaBlend,
    /// Overwite pixels
    Overwrite,
}

impl Display for CompositionMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            CompositionMode::AlphaBlend => "0",
            CompositionMode::Overwrite => "1",
        })
    }
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Debug)]
pub struct ID(pub NonZeroU32);

impl Display for ID {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default, Debug)]
pub struct ActionAnimationFrameComposition {
    /// The 1-based frame number of the frame whose image data
    /// serves as the overlaid data
    pub frame_number: Option<Frame>,
    /// The 1-based frame number of the frame that is being edited.
    /// By default, a new frame is created
    pub frame_edited: Option<Frame>,
    /// The left edge (in pixels) of the image area to display
    pub x: u32,
    /// The top edge (in pixels) of the image area to display
    pub y: u32,
    /// The width (in pixels) of the image area to display.
    /// By default, the entire width is used.
    pub w: u32,
    /// The height (in pixels) of the image area to display.
    /// By default, the entire height is used.
    pub h: u32,
    /// The left edge (in pixels) of the source rectangle
    pub source_x: u32,
    /// The top edge (in pixels) of the source rectangle
    pub source_y: u32,
    /// The composition mode for blending pixels when creating a new frame or
    /// editing a frame's data. The default is full alpha blending.
    pub composition_mode: CompositionMode,
}

impl Display for ActionAnimationFrameComposition {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if let Some(frame_number) = self.frame_number {
            write!(f, "c={frame_number},")?;
        }
        if let Some(frame_edited) = self.frame_edited {
            write!(f, "c={frame_edited},")?;
        }

        if self.x != 0 {
            write!(f, "x={},", self.x)?;
        }
        if self.y != 0 {
            write!(f, "y={},", self.y)?;
        }
        if self.w != 0 {
            write!(f, "w={},", self.w)?;
        }
        if self.h != 0 {
            write!(f, "h={},", self.h)?;
        }

        if self.source_x != 0 {
            write!(f, "X={},", self.source_x)?;
        }
        if self.source_y != 0 {
            write!(f, "Y={},", self.source_y)?;
        }
        if self.composition_mode != CompositionMode::default() {
            write!(f, "C={},", self.composition_mode)?;
        }

        Ok(())
    }
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default, Debug)]
pub struct ActionAnimationFrameControl {
    /// The mode of this command
    pub mode: AnimationMode,
    /// The 1-based frame number of the frame that is being affected
    pub frame_number: Option<Frame>,
    /// The gap (in milliseconds) of this frame from the next one.
    /// A value of zero is ignored. Negative values create a gapless frame.
    pub gap: i32,
    /// The 1-based frame number of the frame that should be made
    /// the current frame
    pub frame: Option<Frame>,
    /// The loop mode
    pub loop_mode: Option<LoopMode>,
}

impl Display for ActionAnimationFrameControl {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "s={},", self.mode)?;

        if let Some(frame_number) = self.frame_number {
            write!(f, "r={frame_number},")?;
        }
        write!(f, "z={},", self.gap)?;
        if let Some(frame) = self.frame {
            write!(f, "c={},", frame)?;
        }
        if let Some(loop_mode) = self.loop_mode {
            write!(f, "v={},", loop_mode)?;
        }

        Ok(())
    }
}

/// A frame
#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Debug)]
pub struct Frame(pub NonZeroU32);

impl Display for Frame {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// How to loop an animation
#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Debug)]
pub enum LoopMode {
    /// Loop forever
    Infinite,
    /// Loop a finite amount of times
    Finite(NonZeroU32),
}

impl Display for LoopMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Infinite => write!(f, "1"),
            Self::Finite(x) => write!(f, "{}", x.get() - 1),
        }
    }
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default, Debug)]
pub enum AnimationMode {
    /// Stop the animation
    #[default]
    Stop,
    /// Run the animation, but wait for new frames
    RunWithNewFrames,
    /// Run the animation
    Run,
}

impl Display for AnimationMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            AnimationMode::Stop => "1",
            AnimationMode::RunWithNewFrames => "2",
            AnimationMode::Run => "3",
        })
    }
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Debug)]
pub struct ActionDelete {
    /// Whether to delete the storage data as well
    pub hard: bool,
    /// What to delete
    pub target: DeleteTarget,
}

impl Display for ActionDelete {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match (self.hard, &self.target) {
            (true, DeleteTarget::Placements) => write!(f, "d=A,"),
            (true, DeleteTarget::ID { placement }) => {
                write!(f, "d=I,")?;
                if let Some(placement) = placement.0 {
                    write!(f, "p={placement},")?;
                }
                Ok(())
            }
            (true, DeleteTarget::Newest { number, placement }) => {
                write!(f, "d=N,I={number},")?;
                if let Some(placement) = placement.0 {
                    write!(f, "p={placement},")?;
                }
                Ok(())
            }
            (true, DeleteTarget::Cursor) => write!(f, "d=C,"),
            (true, DeleteTarget::Frames) => write!(f, "d=D,"),
            (true, DeleteTarget::Cell { x, y }) => write!(f, "d=P,x={x},y={y},"),
            (true, DeleteTarget::CellWithZIndex { x, y, z }) => write!(f, "d=P,x={x},y={y},z={z},"),
            (true, DeleteTarget::Column(x)) => write!(f, "d=X,x={x}"),
            (true, DeleteTarget::Row(y)) => write!(f, "d=Y,y={y}"),
            (true, DeleteTarget::ZIndex(z)) => write!(f, "d=Z,z={z}"),
            (false, DeleteTarget::Placements) => write!(f, "d=a,"),
            (false, DeleteTarget::ID { placement }) => {
                write!(f, "d=i,")?;
                if let Some(placement) = placement.0 {
                    write!(f, "p={placement},")?;
                }
                Ok(())
            }
            (false, DeleteTarget::Newest { number, placement }) => {
                write!(f, "d=n,I={number},")?;
                if let Some(placement) = placement.0 {
                    write!(f, "p={placement},")?;
                }
                Ok(())
            }
            (false, DeleteTarget::Cursor) => write!(f, "d=c,"),
            (false, DeleteTarget::Frames) => write!(f, "d=d,"),
            (false, DeleteTarget::Cell { x, y }) => write!(f, "d=p,x={x},y={y},"),
            (false, DeleteTarget::CellWithZIndex { x, y, z }) => {
                write!(f, "d=p,x={x},y={y},z={z},")
            }
            (false, DeleteTarget::Column(x)) => write!(f, "d=x,x={x}"),
            (false, DeleteTarget::Row(y)) => write!(f, "d=y,y={y}"),
            (false, DeleteTarget::ZIndex(z)) => write!(f, "d=z,z={z}"),
        }
    }
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default, Debug)]
pub struct Placement(pub Option<NonZeroU32>);

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Debug)]
pub enum DeleteTarget {
    /// Deletes all placements visible on screen
    Placements,
    /// Deletes all imagees with the specified id.
    ID { placement: Placement },
    /// Deletes the newest image with the specified number
    Newest { number: u32, placement: Placement },
    /// Delete all placements that intersect with the current
    /// cursor position
    Cursor,
    /// Delete all animation frames
    Frames,
    /// Delete all placements that intersect a specific cell
    Cell { x: u32, y: u32 },
    /// Delete all placements that intersect a specific cell having a specifi z-index
    CellWithZIndex { x: u32, y: u32, z: u32 },
    /// Delete all placements that intersect a specific column
    Column(u32),
    /// Delete all placements that intersect a specific row
    Row(u32),
    /// Delete all placements that intersect a specific z-index
    ZIndex(u32),
}