loadorder/
enums.rs

1/*
2 * This file is part of libloadorder
3 *
4 * Copyright (C) 2017 Oliver Hamlet
5 *
6 * libloadorder is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * libloadorder is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with libloadorder. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20use std::error;
21use std::ffi::OsString;
22use std::fmt;
23use std::io;
24use std::path::Path;
25use std::path::PathBuf;
26use std::slice::EscapeAscii;
27
28#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
29#[non_exhaustive]
30pub enum LoadOrderMethod {
31    Timestamp,
32    Textfile,
33    Asterisk,
34    OpenMW,
35}
36
37#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
38#[non_exhaustive]
39pub enum GameId {
40    Morrowind = 1,
41    Oblivion,
42    Skyrim,
43    Fallout3,
44    FalloutNV,
45    Fallout4,
46    SkyrimSE,
47    Fallout4VR,
48    SkyrimVR,
49    Starfield,
50    OpenMW,
51    OblivionRemastered,
52}
53
54impl GameId {
55    pub fn to_esplugin_id(self) -> esplugin::GameId {
56        match self {
57            GameId::Morrowind | GameId::OpenMW => esplugin::GameId::Morrowind,
58            GameId::Oblivion | GameId::OblivionRemastered => esplugin::GameId::Oblivion,
59            GameId::Skyrim => esplugin::GameId::Skyrim,
60            GameId::SkyrimSE | GameId::SkyrimVR => esplugin::GameId::SkyrimSE,
61            GameId::Fallout3 => esplugin::GameId::Fallout3,
62            GameId::FalloutNV => esplugin::GameId::FalloutNV,
63            GameId::Fallout4 | GameId::Fallout4VR => esplugin::GameId::Fallout4,
64            GameId::Starfield => esplugin::GameId::Starfield,
65        }
66    }
67
68    pub fn supports_light_plugins(self) -> bool {
69        matches!(
70            self,
71            Self::Fallout4 | Self::Fallout4VR | Self::SkyrimSE | Self::SkyrimVR | Self::Starfield
72        )
73    }
74
75    pub fn supports_medium_plugins(self) -> bool {
76        self == GameId::Starfield
77    }
78
79    pub fn allow_plugin_ghosting(self) -> bool {
80        self != GameId::OpenMW
81    }
82
83    pub(crate) fn treats_master_files_differently(self) -> bool {
84        !matches!(self, GameId::OpenMW | GameId::OblivionRemastered)
85    }
86}
87
88#[expect(clippy::error_impl_error)]
89#[derive(Debug)]
90#[non_exhaustive]
91pub enum Error {
92    InvalidPath(PathBuf),
93    IoError(PathBuf, io::Error),
94    NoFilename(PathBuf),
95    DecodeError(Vec<u8>),
96    EncodeError(String),
97    PluginParsingError(PathBuf, Box<dyn error::Error + Send + Sync + 'static>),
98    PluginNotFound(String),
99    TooManyActivePlugins {
100        light_count: usize,
101        medium_count: usize,
102        full_count: usize,
103    },
104    DuplicatePlugin(String),
105    NonMasterBeforeMaster {
106        master: String,
107        non_master: String,
108    },
109    InvalidEarlyLoadingPluginPosition {
110        name: String,
111        pos: usize,
112        expected_pos: usize,
113    },
114    ImplicitlyActivePlugin(String),
115    NoLocalAppData,
116    NoDocumentsPath,
117    NoUserConfigPath,
118    NoUserDataPath,
119    NoProgramFilesPath,
120    UnrepresentedHoist {
121        plugin: String,
122        master: String,
123    },
124    InstalledPlugin(String),
125    IniParsingError {
126        path: PathBuf,
127        line: usize,
128        column: usize,
129        message: String,
130    },
131    VdfParsingError(PathBuf, String),
132    SystemError(i32, OsString),
133    InvalidBlueprintPluginPosition {
134        name: String,
135        pos: usize,
136        expected_pos: usize,
137    },
138}
139
140#[cfg(windows)]
141impl From<windows_result::Error> for Error {
142    fn from(error: windows_result::Error) -> Self {
143        Error::SystemError(error.code().0, error.message().into())
144    }
145}
146
147impl fmt::Display for Error {
148    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
149        match self {
150            Error::InvalidPath(path) => write!(f, "The path \"{}\" is invalid", escape_ascii(path)),
151            Error::IoError(path, error) =>
152                write!(f, "I/O error involving the path \"{}\": {error}", escape_ascii(path)),
153            Error::NoFilename(path) =>
154                write!(f, "The plugin path \"{}\" has no filename part", escape_ascii(path)),
155            Error::DecodeError(bytes) => write!(f, "String could not be decoded from Windows-1252: {}", bytes.escape_ascii()),
156            Error::EncodeError(string) => write!(f, "The string \"{string}\" could not be encoded to Windows-1252"),
157            Error::PluginParsingError(path, err) => {
158                write!(f, "An error was encountered while parsing the plugin at \"{}\": {err}", escape_ascii(path))
159            }
160            Error::PluginNotFound(name) => {
161                write!(f, "The plugin \"{name}\" is not in the load order")
162            }
163            Error::TooManyActivePlugins {light_count, medium_count, full_count } =>
164                write!(f, "Maximum number of active plugins exceeded: there are {full_count} active full plugins, {medium_count} active medium plugins and {light_count} active light plugins"),
165            Error::DuplicatePlugin(name) =>
166                write!(f, "The given plugin list contains more than one instance of \"{name}\""),
167            Error::NonMasterBeforeMaster{ master, non_master} =>
168                write!(f, "Attempted to load the non-master plugin \"{non_master}\" before the master plugin \"{master}\""),
169            Error::InvalidEarlyLoadingPluginPosition{ name, pos, expected_pos } =>
170                write!(f, "Attempted to load the early-loading plugin \"{name}\" at position {pos}, its expected position is {expected_pos}"),
171            Error::ImplicitlyActivePlugin(name) =>
172                write!(f, "The implicitly active plugin \"{name}\" cannot be deactivated"),
173            Error::NoLocalAppData => {
174                write!(f, "The game's local app data folder could not be detected")
175            }
176            Error::NoDocumentsPath => write!(f, "The user's Documents path could not be detected"),
177            Error::NoUserConfigPath => write!(f, "The user's config path could not be detected"),
178            Error::NoUserDataPath => write!(f, "The user's data path could not be detected"),
179            Error::NoProgramFilesPath => write!(f, "The Program Files path could not be obtained"),
180            Error::UnrepresentedHoist { plugin, master } =>
181                write!(f, "The plugin \"{plugin}\" is a master of \"{master}\", which will hoist it"),
182            Error::InstalledPlugin(plugin) =>
183                write!(f, "The plugin \"{plugin}\" is installed, so cannot be removed from the load order"),
184            Error::IniParsingError {
185                path,
186                line,
187                column,
188                message,
189            } => write!(f, "Failed to parse ini file at \"{}\", error at line {line}, column {column}: {message}", escape_ascii(path)),
190            Error::VdfParsingError(path, message) =>
191                write!(f, "Failed to parse VDF file at \"{}\": {message}", escape_ascii(path)),
192            Error::SystemError(code, message) =>
193                write!(f, "Error returned by the operating system, code {code}: \"{}\"", message.as_encoded_bytes().escape_ascii()),
194            Error::InvalidBlueprintPluginPosition{ name, pos, expected_pos } =>
195                write!(f, "Attempted to load the blueprint plugin \"{name}\" at position {pos}, its expected position is {expected_pos}"),
196        }
197    }
198}
199
200impl error::Error for Error {
201    fn cause(&self) -> Option<&dyn error::Error> {
202        match self {
203            Error::IoError(_, x) => Some(x),
204            Error::PluginParsingError(_, x) => Some(x.as_ref()),
205            _ => None,
206        }
207    }
208}
209
210fn escape_ascii(path: &Path) -> EscapeAscii<'_> {
211    path.as_os_str().as_encoded_bytes().escape_ascii()
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn game_id_should_map_to_libespm_id_correctly() {
220        assert_eq!(
221            esplugin::GameId::Morrowind,
222            GameId::Morrowind.to_esplugin_id()
223        );
224        assert_eq!(
225            esplugin::GameId::Oblivion,
226            GameId::Oblivion.to_esplugin_id()
227        );
228        assert_eq!(esplugin::GameId::Skyrim, GameId::Skyrim.to_esplugin_id());
229        assert_eq!(
230            esplugin::GameId::SkyrimSE,
231            GameId::SkyrimSE.to_esplugin_id()
232        );
233        assert_eq!(
234            esplugin::GameId::SkyrimSE,
235            GameId::SkyrimVR.to_esplugin_id()
236        );
237        assert_eq!(
238            esplugin::GameId::Fallout3,
239            GameId::Fallout3.to_esplugin_id()
240        );
241        assert_eq!(
242            esplugin::GameId::FalloutNV,
243            GameId::FalloutNV.to_esplugin_id()
244        );
245        assert_eq!(
246            esplugin::GameId::Fallout4,
247            GameId::Fallout4.to_esplugin_id()
248        );
249        assert_eq!(
250            esplugin::GameId::Fallout4,
251            GameId::Fallout4VR.to_esplugin_id()
252        );
253        assert_eq!(
254            esplugin::GameId::Starfield,
255            GameId::Starfield.to_esplugin_id()
256        );
257    }
258
259    #[test]
260    fn game_id_supports_light_plugins_should_be_false_until_fallout_4() {
261        assert!(!GameId::OpenMW.supports_light_plugins());
262        assert!(!GameId::Morrowind.supports_light_plugins());
263        assert!(!GameId::Oblivion.supports_light_plugins());
264        assert!(!GameId::Skyrim.supports_light_plugins());
265        assert!(GameId::SkyrimSE.supports_light_plugins());
266        assert!(GameId::SkyrimVR.supports_light_plugins());
267        assert!(!GameId::Fallout3.supports_light_plugins());
268        assert!(!GameId::FalloutNV.supports_light_plugins());
269        assert!(GameId::Fallout4.supports_light_plugins());
270        assert!(GameId::Fallout4VR.supports_light_plugins());
271        assert!(GameId::Starfield.supports_light_plugins());
272    }
273
274    #[test]
275    fn game_id_supports_medium_plugins_should_be_false_except_for_starfield() {
276        assert!(!GameId::OpenMW.supports_medium_plugins());
277        assert!(!GameId::Morrowind.supports_medium_plugins());
278        assert!(!GameId::Oblivion.supports_medium_plugins());
279        assert!(!GameId::Skyrim.supports_medium_plugins());
280        assert!(!GameId::SkyrimSE.supports_medium_plugins());
281        assert!(!GameId::SkyrimVR.supports_medium_plugins());
282        assert!(!GameId::Fallout3.supports_medium_plugins());
283        assert!(!GameId::FalloutNV.supports_medium_plugins());
284        assert!(!GameId::Fallout4.supports_medium_plugins());
285        assert!(!GameId::Fallout4VR.supports_medium_plugins());
286        assert!(GameId::Starfield.supports_medium_plugins());
287    }
288
289    #[test]
290    fn game_id_allow_plugin_ghosting_should_be_false_for_openmw_only() {
291        assert!(!GameId::OpenMW.allow_plugin_ghosting());
292        assert!(GameId::Morrowind.allow_plugin_ghosting());
293        assert!(GameId::Oblivion.allow_plugin_ghosting());
294        assert!(GameId::Skyrim.allow_plugin_ghosting());
295        assert!(GameId::SkyrimSE.allow_plugin_ghosting());
296        assert!(GameId::SkyrimVR.allow_plugin_ghosting());
297        assert!(GameId::Fallout3.allow_plugin_ghosting());
298        assert!(GameId::FalloutNV.allow_plugin_ghosting());
299        assert!(GameId::Fallout4.allow_plugin_ghosting());
300        assert!(GameId::Fallout4VR.allow_plugin_ghosting());
301        assert!(GameId::Starfield.allow_plugin_ghosting());
302    }
303
304    #[test]
305    fn game_id_treats_master_files_differently_should_be_false_for_openmw_and_oblivion_remastered_only(
306    ) {
307        assert!(!GameId::OpenMW.treats_master_files_differently());
308        assert!(GameId::Morrowind.treats_master_files_differently());
309        assert!(GameId::Oblivion.treats_master_files_differently());
310        assert!(!GameId::OblivionRemastered.treats_master_files_differently());
311        assert!(GameId::Skyrim.treats_master_files_differently());
312        assert!(GameId::SkyrimSE.treats_master_files_differently());
313        assert!(GameId::SkyrimVR.treats_master_files_differently());
314        assert!(GameId::Fallout3.treats_master_files_differently());
315        assert!(GameId::FalloutNV.treats_master_files_differently());
316        assert!(GameId::Fallout4.treats_master_files_differently());
317        assert!(GameId::Fallout4VR.treats_master_files_differently());
318        assert!(GameId::Starfield.treats_master_files_differently());
319    }
320
321    #[test]
322    fn error_display_should_print_double_quoted_paths() {
323        let string = format!("{}", Error::InvalidPath(PathBuf::from("foo")));
324
325        assert_eq!("The path \"foo\" is invalid", string);
326    }
327
328    #[test]
329    fn error_display_should_print_os_string_as_quoted_string() {
330        let string = format!("{}", Error::SystemError(1, OsString::from("foo")));
331
332        assert_eq!(
333            "Error returned by the operating system, code 1: \"foo\"",
334            string
335        );
336    }
337}