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
use crate::{error::CobbleError, CobbleResult};
use ipc_channel::ipc;
use parking_lot::Mutex;
use std::sync::Arc;

/// Handle to the forked game process.
/// This handle allows stopping the game (sends SIGINT to the game process).
/// It is also possible to check if the game exited or is still running.
#[derive(Clone, Debug)]
pub struct GameProcessHandle {
    stop_sender: Arc<Mutex<ipc::IpcBytesSender>>,
    stopped_receiver: Arc<Mutex<ipc::IpcBytesReceiver>>,
}

impl GameProcessHandle {
    pub(crate) fn new(
        stop_sender: ipc::IpcBytesSender,
        stopped_receiver: ipc::IpcBytesReceiver,
    ) -> Self {
        Self {
            stop_sender: Arc::new(Mutex::new(stop_sender)),
            stopped_receiver: Arc::new(Mutex::new(stopped_receiver)),
        }
    }

    /// Stops the game process by sending SIGINT to the process.
    pub fn stop_game(&self) -> CobbleResult<()> {
        let sender = self.stop_sender.lock();
        sender.send(&[])?;
        Ok(())
    }

    /// Blocks until the game process has exited.
    pub fn wait_stopped(&self) -> CobbleResult<()> {
        let receiver = self.stopped_receiver.lock();
        receiver.recv()?;
        Ok(())
    }

    /// Checks if the game process has exited.
    pub fn is_stopped(&self) -> CobbleResult<bool> {
        let receiver = self.stopped_receiver.lock();
        match receiver.try_recv() {
            Ok(_) => Ok(true),
            Err(ipc::TryRecvError::Empty) => Ok(false),
            Err(ipc::TryRecvError::IpcError(err)) => Err(CobbleError::IpcError(err)),
        }
    }
}