ludusavi 0.18.0

Game save backup tool
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
use std::io::{BufRead, BufReader};

use crate::{
    lang::TRANSLATOR,
    prelude::{run_command, CommandError, CommandOutput, Error, Finality, Privacy, StrictPath, SyncDirection},
    resource::config::{App, Config},
    scan::ScanChange,
};

pub fn validate_cloud_config(config: &Config, cloud_path: &str) -> Result<Remote, Error> {
    if !config.apps.rclone.is_valid() {
        return Err(Error::RcloneUnavailable);
    }
    let Some(remote) = config.cloud.remote.clone() else { return Err(Error::CloudNotConfigured) };
    validate_cloud_path(cloud_path)?;
    Ok(remote)
}

pub fn validate_cloud_path(path: &str) -> Result<(), Error> {
    if path.is_empty() || path == "/" {
        Err(Error::CloudPathInvalid)
    } else {
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct CloudChange {
    pub path: String,
    pub change: ScanChange,
}

#[derive(Clone, Debug)]
pub enum RcloneProcessEvent {
    Progress { current: f32, max: f32 },
    Change(CloudChange),
}

#[derive(Debug)]
pub struct RcloneProcess {
    program: String,
    args: Vec<String>,
    child: std::process::Child,
    stderr: Option<BufReader<std::process::ChildStderr>>,
}

impl RcloneProcess {
    pub fn launch(program: String, args: Vec<String>) -> Result<Self, CommandError> {
        let mut command = std::process::Command::new(&program);
        command
            .args(&args)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped());

        #[cfg(target_os = "windows")]
        {
            use std::os::windows::process::CommandExt;
            command.creation_flags(winapi::um::winbase::CREATE_NO_WINDOW);
        }

        log::debug!("Running command: {} {:?}", &program, &args);

        let mut child = command.spawn().map_err(|e| {
            let e = CommandError::Launched {
                program: program.clone(),
                args: args.clone(),
                raw: e.to_string(),
            };
            log::error!("Rclone failed: {e:?}");
            e
        })?;

        let stderr = child.stderr.take().map(BufReader::new);
        Ok(Self {
            program,
            args,
            child,
            stderr,
        })
    }

    pub fn events(&mut self) -> Vec<RcloneProcessEvent> {
        let mut events = vec![];

        #[derive(Debug, serde::Deserialize)]
        #[serde(rename_all = "camelCase", untagged)]
        enum Log {
            Skip { skipped: String, object: String },
            Change { msg: String, object: String },
            Stats { stats: Stats },
        }

        #[derive(Debug, serde::Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Stats {
            bytes: f32,
            total_bytes: f32,
        }

        if let Some(stderr) = self.stderr.as_mut() {
            for line in stderr.lines().take(10).filter_map(|x| x.ok()) {
                match serde_json::from_str::<Log>(&line) {
                    Ok(Log::Skip { skipped, object }) => match skipped.as_str() {
                        "copy" => events.push(RcloneProcessEvent::Change(CloudChange {
                            path: object,
                            change: ScanChange::Different,
                        })),
                        "delete" => events.push(RcloneProcessEvent::Change(CloudChange {
                            path: object,
                            change: ScanChange::Removed,
                        })),
                        raw => {
                            log::trace!("Unhandled Rclone 'skipped': {raw}");
                        }
                    },
                    Ok(Log::Change { msg, object }) => match msg.as_str() {
                        "Copied (new)" => events.push(RcloneProcessEvent::Change(CloudChange {
                            path: object,
                            change: ScanChange::New,
                        })),
                        "Copied (replaced existing)" => events.push(RcloneProcessEvent::Change(CloudChange {
                            path: object,
                            change: ScanChange::Different,
                        })),
                        "Deleted" => events.push(RcloneProcessEvent::Change(CloudChange {
                            path: object,
                            change: ScanChange::Removed,
                        })),
                        raw => {
                            log::trace!("Unhandled Rclone 'msg': {raw}");
                        }
                    },
                    Ok(Log::Stats {
                        stats: Stats { bytes, total_bytes },
                    }) => {
                        if total_bytes > 0.0 {
                            events.push(RcloneProcessEvent::Progress {
                                current: bytes,
                                max: total_bytes,
                            });
                        }
                    }
                    Err(_) => {
                        log::trace!("Unhandled Rclone message: {line}");
                    }
                }
            }
        }

        if !events.is_empty() {
            log::trace!("New Rclone events: {events:?}");
        }
        events
    }

    pub fn succeeded(&mut self) -> Option<Result<(), CommandError>> {
        let res = match self.child.try_wait() {
            Ok(Some(status)) => match status.code() {
                Some(code) if code == 0 => Some(Ok(())),
                Some(code) => {
                    let stdout = self.child.stdout.as_mut().and_then(|x| {
                        let lines = BufReader::new(x).lines().filter_map(|x| x.ok()).collect::<Vec<_>>();
                        (!lines.is_empty()).then_some(lines.join("\n"))
                    });
                    let stderr = self.stderr.as_mut().and_then(|x| {
                        let lines = x.lines().filter_map(|x| x.ok()).collect::<Vec<_>>();
                        (!lines.is_empty()).then_some(lines.join("\n"))
                    });

                    Some(Err(CommandError::Exited {
                        program: self.program.clone(),
                        args: self.args.clone(),
                        code,
                        stdout,
                        stderr,
                    }))
                }
                None => Some(Err(CommandError::Terminated {
                    program: self.program.clone(),
                    args: self.args.clone(),
                })),
            },
            Ok(None) => None,
            Err(_) => Some(Err(CommandError::Terminated {
                program: self.program.clone(),
                args: self.args.clone(),
            })),
        };

        if let Some(Ok(_)) = &res {
            log::debug!("Rclone succeeded");
        }
        if let Some(Err(e)) = &res {
            log::error!("Rclone failed: {e:?}");
        }

        res
    }

    pub fn kill(&mut self) -> Result<(), std::io::Error> {
        let res = self.child.kill();
        if let Err(e) = &res {
            log::error!("Unable to kill child process for Rclone: {e:?}");
        }
        res
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename = "camelCase")]
pub enum RemoteChoice {
    None,
    Custom,
    Box,
    Dropbox,
    Ftp,
    GoogleDrive,
    OneDrive,
    Smb,
    WebDav,
}

impl RemoteChoice {
    pub const ALL: &[Self] = &[
        Self::None,
        Self::Box,
        Self::Dropbox,
        Self::GoogleDrive,
        Self::OneDrive,
        Self::Ftp,
        Self::Smb,
        Self::WebDav,
        Self::Custom,
    ];
}

impl ToString for RemoteChoice {
    fn to_string(&self) -> String {
        match self {
            Self::None => TRANSLATOR.none_label(),
            Self::Custom => TRANSLATOR.custom_label(),
            Self::Box => "Box".to_string(),
            Self::Dropbox => "Dropbox".to_string(),
            Self::Ftp => "FTP".to_string(),
            Self::GoogleDrive => "Google Drive".to_string(),
            Self::OneDrive => "OneDrive".to_string(),
            Self::Smb => "SMB".to_string(),
            Self::WebDav => "WebDAV".to_string(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename = "camelCase")]
pub enum Remote {
    Custom {
        id: String,
    },
    Box {
        id: String,
    },
    Dropbox {
        id: String,
    },
    GoogleDrive {
        id: String,
    },
    OneDrive {
        id: String,
    },
    Ftp {
        id: String,
        host: String,
        port: i32,
        username: String,
        #[serde(skip, default)]
        password: String,
    },
    Smb {
        id: String,
        host: String,
        port: i32,
        username: String,
        #[serde(skip, default)]
        password: String,
    },
    WebDav {
        id: String,
        url: String,
        username: String,
        #[serde(skip, default)]
        password: String,
        provider: WebDavProvider,
    },
}

impl Remote {
    pub fn id(&self) -> &str {
        match self {
            Remote::Box { id } => id,
            Remote::Custom { id } => id,
            Remote::Dropbox { id } => id,
            Remote::GoogleDrive { id } => id,
            Remote::OneDrive { id } => id,
            Remote::Ftp { id, .. } => id,
            Remote::Smb { id, .. } => id,
            Remote::WebDav { id, .. } => id,
        }
    }

    pub fn slug(&self) -> &str {
        match self {
            Self::Custom { .. } => "",
            Self::Box { .. } => "box",
            Self::Dropbox { .. } => "dropbox",
            Self::Ftp { .. } => "ftp",
            Self::GoogleDrive { .. } => "drive",
            Self::OneDrive { .. } => "onedrive",
            Self::Smb { .. } => "smb",
            Self::WebDav { .. } => "webdav",
        }
    }

    pub fn config_args(&self) -> Option<Vec<String>> {
        match self {
            Self::Custom { .. } => None,
            Self::Box { .. } => None,
            Self::Dropbox { .. } => None,
            Self::GoogleDrive { .. } => Some(vec!["scope=drive".to_string()]),
            Self::Ftp {
                id: _,
                host,
                port,
                username,
                password,
            } => Some(vec![
                format!("host={host}"),
                format!("port={port}"),
                format!("user={username}"),
                format!("pass={password}"),
            ]),
            Self::OneDrive { .. } => Some(vec![
                "drive_type=personal".to_string(),
                "access_scopes=Files.ReadWrite,offline_access".to_string(),
            ]),
            Self::Smb {
                id: _,
                host,
                port,
                username,
                password,
                ..
            } => Some(vec![
                format!("host={host}"),
                format!("port={port}"),
                format!("user={username}"),
                format!("pass={password}"),
            ]),
            Self::WebDav {
                id: _,
                url,
                username,
                password,
                provider,
            } => Some(vec![
                format!("url={url}"),
                format!("user={username}"),
                format!("pass={password}"),
                format!("vendor={}", provider.slug()),
            ]),
        }
    }

    pub fn needs_configuration(&self) -> bool {
        match self {
            Self::Custom { .. } => false,
            Self::Box { .. }
            | Self::Dropbox { .. }
            | Self::Ftp { .. }
            | Self::GoogleDrive { .. }
            | Self::OneDrive { .. }
            | Self::Smb { .. }
            | Self::WebDav { .. } => true,
        }
    }

    pub fn description(&self) -> Option<String> {
        match self {
            Remote::Ftp {
                host, port, username, ..
            } => Some(format!("{}@{}:{}", username, host, port)),
            Remote::Smb {
                host, port, username, ..
            } => Some(format!("{}@{}:{}", username, host, port)),
            Remote::WebDav { url, provider, .. } => Some(format!("{} - {}", provider.to_string(), url)),
            _ => None,
        }
    }

    pub fn generate_id() -> String {
        format!("ludusavi-{}", chrono::Utc::now().timestamp())
    }
}

impl From<Option<&Remote>> for RemoteChoice {
    fn from(value: Option<&Remote>) -> Self {
        if let Some(value) = value {
            match value {
                Remote::Custom { .. } => RemoteChoice::Custom,
                Remote::Box { .. } => RemoteChoice::Box,
                Remote::Dropbox { .. } => RemoteChoice::Dropbox,
                Remote::Ftp { .. } => RemoteChoice::Ftp,
                Remote::GoogleDrive { .. } => RemoteChoice::GoogleDrive,
                Remote::OneDrive { .. } => RemoteChoice::OneDrive,
                Remote::Smb { .. } => RemoteChoice::Smb,
                Remote::WebDav { .. } => RemoteChoice::WebDav,
            }
        } else {
            RemoteChoice::None
        }
    }
}

impl TryFrom<RemoteChoice> for Remote {
    type Error = ();

    fn try_from(value: RemoteChoice) -> Result<Self, Self::Error> {
        match value {
            RemoteChoice::None => Err(()),
            RemoteChoice::Custom => Ok(Remote::Custom {
                id: "ludusavi".to_string(),
            }),
            RemoteChoice::Box => Ok(Remote::Box {
                id: Remote::generate_id(),
            }),
            RemoteChoice::Dropbox => Ok(Remote::Dropbox {
                id: Remote::generate_id(),
            }),
            RemoteChoice::Ftp => Ok(Remote::Ftp {
                id: Remote::generate_id(),
                host: String::new(),
                port: 21,
                username: String::new(),
                password: String::new(),
            }),
            RemoteChoice::GoogleDrive => Ok(Remote::GoogleDrive {
                id: Remote::generate_id(),
            }),
            RemoteChoice::OneDrive => Ok(Remote::OneDrive {
                id: Remote::generate_id(),
            }),
            RemoteChoice::Smb => Ok(Remote::Smb {
                id: Remote::generate_id(),
                host: String::new(),
                port: 445,
                username: String::new(),
                password: String::new(),
            }),
            RemoteChoice::WebDav => Ok(Remote::WebDav {
                id: Remote::generate_id(),
                url: String::new(),
                username: String::new(),
                password: String::new(),
                provider: WebDavProvider::Other,
            }),
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum WebDavProvider {
    #[default]
    Other,
    Nextcloud,
    Owncloud,
    Sharepoint,
    SharepointNtlm,
}

impl WebDavProvider {
    pub const ALL: &[Self] = &[
        Self::Other,
        Self::Nextcloud,
        Self::Owncloud,
        Self::Sharepoint,
        Self::SharepointNtlm,
    ];

    pub const ALL_CLI: &[&'static str] = &[
        Self::OTHER,
        Self::NEXTCLOUD,
        Self::OWNCLOUD,
        Self::SHAREPOINT,
        Self::SHAREPOINT_NTLM,
    ];
    pub const OTHER: &str = "other";
    const NEXTCLOUD: &str = "nextcloud";
    const OWNCLOUD: &str = "owncloud";
    const SHAREPOINT: &str = "sharepoint";
    const SHAREPOINT_NTLM: &str = "sharepoint-ntlm";
}

impl WebDavProvider {
    pub fn slug(&self) -> &str {
        match self {
            WebDavProvider::Other => Self::OTHER,
            WebDavProvider::Nextcloud => Self::NEXTCLOUD,
            WebDavProvider::Owncloud => Self::OWNCLOUD,
            WebDavProvider::Sharepoint => Self::SHAREPOINT,
            WebDavProvider::SharepointNtlm => Self::SHAREPOINT_NTLM,
        }
    }
}

impl ToString for WebDavProvider {
    fn to_string(&self) -> String {
        match self {
            Self::Other => crate::resource::manifest::Store::Other.to_string(),
            Self::Nextcloud => "Nextcloud".to_string(),
            Self::Owncloud => "Owncloud".to_string(),
            Self::Sharepoint => "Sharepoint".to_string(),
            Self::SharepointNtlm => "Sharepoint (NTLM)".to_string(),
        }
    }
}

impl std::str::FromStr for WebDavProvider {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            Self::OTHER => Ok(Self::Other),
            Self::NEXTCLOUD => Ok(Self::Nextcloud),
            Self::OWNCLOUD => Ok(Self::Owncloud),
            Self::SHAREPOINT => Ok(Self::Sharepoint),
            Self::SHAREPOINT_NTLM => Ok(Self::SharepointNtlm),
            _ => Err(format!("invalid provider: {}", s)),
        }
    }
}

pub struct Rclone {
    app: App,
    remote: Remote,
}

impl Rclone {
    pub fn new(app: App, remote: Remote) -> Self {
        Self { app, remote }
    }

    fn path(&self, path: &str) -> String {
        format!("{}:{}", self.remote.id(), path)
    }

    fn args(&self, args: &[String]) -> Vec<String> {
        let mut collected = vec![];
        if !self.app.arguments.is_empty() {
            if let Some(parts) = shlex::split(&self.app.arguments) {
                collected.extend(parts);
            }
        }
        for arg in args {
            collected.push(arg.to_string());
        }
        collected
    }

    fn run(&self, args: &[String], success: &[i32], privacy: Privacy) -> Result<CommandOutput, CommandError> {
        let args = self.args(args);
        let args: Vec<_> = args.iter().map(|x| x.as_str()).collect();
        run_command(&self.app.path.raw(), &args, success, privacy)
    }

    fn obscure(&self, credential: &str) -> Result<String, CommandError> {
        let out = self.run(&["obscure".to_string(), credential.to_string()], &[0], Privacy::Private)?;
        Ok(out.stdout)
    }

    pub fn configure_remote(&self) -> Result<(), CommandError> {
        if !self.remote.needs_configuration() {
            return Ok(());
        }

        let mut privacy = Privacy::Public;

        let mut remote = self.remote.clone();
        match &mut remote {
            Remote::Custom { .. }
            | Remote::Box { .. }
            | Remote::Dropbox { .. }
            | Remote::GoogleDrive { .. }
            | Remote::OneDrive { .. } => {}
            Remote::Ftp { password, .. } => {
                privacy = Privacy::Private;
                *password = self.obscure(password)?;
            }
            Remote::Smb { password, .. } => {
                privacy = Privacy::Private;
                *password = self.obscure(password)?;
            }
            Remote::WebDav { password, .. } => {
                privacy = Privacy::Private;
                *password = self.obscure(password)?;
            }
        }

        let mut args = vec![
            "config".to_string(),
            "create".to_string(),
            remote.id().to_string(),
            remote.slug().to_string(),
        ];

        if let Some(config_args) = remote.config_args() {
            args.extend(config_args);
        }

        self.run(&args, &[0], privacy)?;
        Ok(())
    }

    pub fn unconfigure_remote(&self) -> Result<(), CommandError> {
        if !self.remote.needs_configuration() {
            return Ok(());
        }

        let args = vec!["config".to_string(), "delete".to_string(), self.remote.id().to_string()];

        self.run(&args, &[0], Privacy::Public)?;
        Ok(())
    }

    pub fn sync(
        &self,
        local: &StrictPath,
        remote_path: &str,
        direction: SyncDirection,
        finality: Finality,
        game_dirs: &[String],
    ) -> Result<RcloneProcess, CommandError> {
        if direction == SyncDirection::Upload && !local.exists() {
            // Rclone will fail with exit code 3 if the local folder does not exist.
            _ = local.create_dirs();
        }

        let mut args = vec![
            "sync".to_string(),
            "-v".to_string(),
            "--use-json-log".to_string(),
            "--stats=100ms".to_string(),
        ];

        if finality.preview() {
            args.push("--dry-run".to_string());
        }

        for game_dir in game_dirs {
            // Inclusion rules are file-based, so we have to add `**`.
            args.push(format!("--include=/{game_dir}/**"));
        }

        match direction {
            SyncDirection::Upload => {
                args.push(local.render());
                args.push(self.path(remote_path));
            }
            SyncDirection::Download => {
                args.push(self.path(remote_path));
                args.push(local.render());
            }
        }

        RcloneProcess::launch(self.app.path.raw(), self.args(&args))
    }
}

pub mod rclone_monitor {
    use iced_native::{
        futures::{channel::mpsc, StreamExt},
        subscription::{self, Subscription},
    };

    use crate::{
        cloud::{RcloneProcess, RcloneProcessEvent},
        prelude::CommandError,
    };

    #[derive(Debug, Clone)]
    pub enum Event {
        Ready(mpsc::Sender<Input>),
        Data(Vec<RcloneProcessEvent>),
        Succeeded,
        Failed(CommandError),
        Cancelled,
    }

    #[derive(Debug)]
    pub enum Input {
        Process(RcloneProcess),
        Tick,
        Cancel,
    }

    enum State {
        Starting,
        Ready {
            receiver: mpsc::Receiver<Input>,
            process: Option<RcloneProcess>,
            interval: tokio::time::Interval,
        },
    }

    pub fn run() -> Subscription<Event> {
        struct Runner;

        subscription::unfold(std::any::TypeId::of::<Runner>(), State::Starting, |state| async move {
            match state {
                State::Starting => {
                    let (sender, receiver) = mpsc::channel(10_000);

                    (
                        Event::Ready(sender),
                        State::Ready {
                            receiver,
                            process: None,
                            interval: tokio::time::interval(std::time::Duration::from_millis(1)),
                        },
                    )
                }
                State::Ready {
                    mut receiver,
                    mut process,
                    mut interval,
                } => loop {
                    let input = tokio::select!(
                        input = receiver.select_next_some() => {
                            input
                        }
                        _ = interval.tick() => {
                            Input::Tick
                        }
                    );

                    match input {
                        Input::Process(new_process) => {
                            if let Some(proc) = process.as_mut() {
                                let _ = proc.child.kill();
                            }
                            process = Some(new_process);
                        }
                        Input::Tick => {
                            if let Some(proc) = process.as_mut() {
                                let events = proc.events();
                                if !events.is_empty() {
                                    return (
                                        Event::Data(events),
                                        State::Ready {
                                            receiver,
                                            process,
                                            interval,
                                        },
                                    );
                                }
                                if let Some(outcome) = proc.succeeded() {
                                    match outcome {
                                        Ok(_) => {
                                            return (
                                                Event::Succeeded,
                                                State::Ready {
                                                    receiver,
                                                    process: None,
                                                    interval,
                                                },
                                            );
                                        }
                                        Err(e) => {
                                            return (
                                                Event::Failed(e),
                                                State::Ready {
                                                    receiver,
                                                    process: None,
                                                    interval,
                                                },
                                            );
                                        }
                                    }
                                }
                            }
                        }
                        Input::Cancel => {
                            if let Some(proc) = process.as_mut() {
                                let _ = proc.kill();
                            }
                            return (
                                Event::Cancelled,
                                State::Ready {
                                    receiver,
                                    process: None,
                                    interval,
                                },
                            );
                        }
                    }
                },
            }
        })
    }
}