Skip to main content

fyrox_resource/
options.rs

1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21//! Resource import options common traits.
22
23use crate::{
24    core::{append_extension, log::Log},
25    io::ResourceIo,
26};
27use fyrox_core::io::FileError;
28use fyrox_core::reflect::Reflect;
29use ron::ser::PrettyConfig;
30use serde::{de::DeserializeOwned, Serialize};
31use std::io::{ErrorKind, Write};
32use std::{fs::File, path::Path};
33
34/// Extension of import options file.
35pub const OPTIONS_EXTENSION: &str = "options";
36
37/// Base type-agnostic trait for resource import options. This trait has automatic implementation
38/// for everything that implements [`ImportOptions`] trait.
39pub trait BaseImportOptions: Reflect {
40    /// Saves the options to a file at the given path.
41    fn save(&self, path: &Path) -> bool;
42}
43
44/// A trait for resource import options. It provides generic functionality shared over all types of import options.
45pub trait ImportOptions:
46    BaseImportOptions + Serialize + DeserializeOwned + Default + Clone
47{
48    /// Saves import options into a specified file.
49    fn save_internal(&self, path: &Path) -> bool {
50        fn write<T: Serialize>(this: &T, path: &Path) -> std::io::Result<()> {
51            let mut file = File::create(path)?;
52            let string = ron::ser::to_string_pretty(this, PrettyConfig::default())
53                .map_err(|e| std::io::Error::new(ErrorKind::InvalidData, e))?;
54            file.write_all(string.as_bytes())?;
55            Ok(())
56        }
57        let result = write(self, path);
58        let is_ok = result.is_ok();
59        Log::verify(result);
60        is_ok
61    }
62}
63
64impl<T> BaseImportOptions for T
65where
66    T: ImportOptions,
67{
68    fn save(&self, path: &Path) -> bool {
69        self.save_internal(path)
70    }
71}
72
73/// Tries to load import settings for a resource. It is not part of ImportOptions trait because
74/// `async fn` is not yet supported for traits.
75pub async fn try_get_import_settings<T>(resource_path: &Path, io: &dyn ResourceIo) -> Option<T>
76where
77    T: ImportOptions,
78{
79    let settings_path = append_extension(resource_path, OPTIONS_EXTENSION);
80
81    match io.load_file(settings_path.as_ref()).await {
82        Ok(bytes) => match ron::de::from_bytes::<T>(&bytes) {
83            Ok(options) => Some(options),
84            Err(e) => {
85                Log::warn(format!(
86                    "Malformed options file {:?}, fallback to defaults! Reason: {}",
87                    settings_path, e
88                ));
89
90                None
91            }
92        },
93        Err(e) => {
94            // Missing options file is a normal situation, the engine will use default import options
95            // instead. Any other error indicates a real issue that needs to be highlighted to the
96            // user.
97            if let FileError::Io(ref err) = e {
98                if err.kind() == ErrorKind::NotFound {
99                    return None;
100                }
101            }
102
103            Log::warn(format!(
104                "Unable to load options file {:?}, fallback to defaults! Reason: {}",
105                settings_path, e
106            ));
107
108            None
109        }
110    }
111}
112
113/// Same as [`try_get_import_settings`], but returns opaque import settings.
114pub async fn try_get_import_settings_opaque<T>(
115    resource_path: &Path,
116    io: &dyn ResourceIo,
117) -> Option<Box<dyn BaseImportOptions>>
118where
119    T: ImportOptions,
120{
121    try_get_import_settings::<T>(resource_path, io)
122        .await
123        .map(|options| Box::new(options) as Box<dyn BaseImportOptions>)
124}