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
#![forbid(unsafe_code)]
#![forbid(missing_docs)]
#![forbid(unstable_features)]
#![forbid(missing_fragment_specifier)]
#![warn(clippy::all, clippy::pedantic)]

/*!
# Proton Caller API

This defines the internal API used in `proton-call` to run Proton
*/

mod config;
mod index;
mod runtime;
mod runtime_options;
mod version;

/// Contains the `Error` and `ErrorKind` types
pub mod error;

pub use config::Config;
use error::{Error, Kind};
pub use index::Index;
pub use runtime::RunTimeVersion;
use runtime::Runtime;
pub use runtime_options::RuntimeOption;
use std::borrow::Cow;
use std::fs::create_dir;
pub use version::Version;

use std::path::PathBuf;
use std::process::ExitStatus;

/// Type to handle executing Proton
#[derive(Debug)]
pub struct Proton {
    version: Version,
    path: PathBuf,
    program: PathBuf,
    args: Vec<String>,
    options: Vec<RuntimeOption>,
    compat: PathBuf,
    steam: PathBuf,
    runtime: Option<RunTimeVersion>,
    common: PathBuf,
}

impl Proton {
    #[must_use]
    /// Creates a new instance of `Proton`
    pub fn new(
        version: Version,
        path: PathBuf,
        program: PathBuf,
        args: Vec<String>,
        options: Vec<RuntimeOption>,
        compat: PathBuf,
        steam: PathBuf,
        runtime: Option<RunTimeVersion>,
        common: PathBuf,
    ) -> Proton {
        Proton {
            version,
            path,
            program,
            args,
            options,
            compat,
            steam,
            runtime,
            common,
        }
        .update_path()
    }

    /// Appends the executable to the path
    fn update_path(mut self) -> Proton {
        let str: Cow<str> = self.path.to_string_lossy();
        let str: String = format!("{}/proton", str);
        self.path = PathBuf::from(str);
        self
    }

    fn create_p_dir(&mut self) -> Result<(), Error> {
        let name: Cow<str> = self.compat.to_string_lossy();
        let newdir: PathBuf = PathBuf::from(format!("{}/Proton {}", name, self.version));

        if !newdir.exists() {
            if let Err(e) = create_dir(&newdir) {
                throw!(Kind::ProtonDir, "failed to create Proton directory: {}", e);
            }
        }

        self.compat = newdir;

        pass!()
    }

    fn check_proton(&self) -> Result<(), Error> {
        if !self.path.exists() {
            throw!(Kind::ProtonMissing, "{}", self.version);
        }

        pass!()
    }

    fn check_program(&self) -> Result<(), Error> {
        if !self.program.exists() {
            throw!(Kind::ProgramMissing, "{}", self.program.to_string_lossy());
        }

        pass!()
    }

    fn gen_options(&self) -> Vec<(String, String)> {
        let mut opts = Vec::new();
        for opt in &self.options {
            opts.insert(opts.len(), (opt.to_string(), "1".to_string()))
        }
        opts
    }

    /// Changes `compat` path to the version of Proton in use, creates the directory if doesn't already exist
    ///
    /// # Errors
    ///
    /// Will fail on:
    /// * Creating a Proton compat env directory fails
    /// * Executing Proton fails
    pub fn run(mut self) -> Result<ExitStatus, Error> {
        self.create_p_dir()?;
        self.check_proton()?;
        self.check_program()?;

        // check one for runtimes
        if let Some(runtime) = self.runtime {
            let runtime = Runtime::from_proton(runtime, self)?;
            return runtime.execute();
        }

        // check two for runtimes
        match self.version {
            Version::Mainline(maj, _) => {
                if maj >= 5 {
                    let runtime = Runtime::from_proton(RunTimeVersion::Soldier, self)?;
                    return runtime.execute()
                }
            },
            Version::Experimental => {
                let runtime = Runtime::from_proton(RunTimeVersion::Soldier, self)?;
                return runtime.execute()
            }
            _ => {},
        }

        self.execute()
    }

    /// Executes Proton
    fn execute(self) -> Result<ExitStatus, Error> {
        use std::process::{Child, Command};

        let envs: Vec<(String, String)> = self.gen_options();

        println!(
            "Running Proton {} for {} with:\n{:#?}",
            self.version,
            self.program.to_string_lossy(),
            envs,
        );

        let mut child: Child = match Command::new(&self.path)
            .arg("run")
            .arg(&self.program)
            .args(&self.args)
            .env("STEAM_COMPAT_DATA_PATH", &self.compat)
            .env("STEAM_COMPAT_CLIENT_INSTALL_PATH", &self.steam)
            .envs(envs)
            .spawn()
        {
            Ok(c) => c,
            Err(e) => throw!(Kind::ProtonSpawn, "{}\nDebug:\n{:#?}", e, self),
        };

        let status: ExitStatus = match child.wait() {
            Ok(e) => e,
            Err(e) => throw!(Kind::ProtonWait, "'{}': {}", child.id(), e),
        };

        pass!(status)
    }
}