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, reflect::Reflect},
25    io::ResourceIo,
26};
27use fyrox_core::Downcast;
28use ron::ser::PrettyConfig;
29use serde::{de::DeserializeOwned, Serialize};
30use std::{fs::File, path::Path};
31
32/// Extension of import options file.
33pub const OPTIONS_EXTENSION: &str = "options";
34
35/// Base type-agnostic trait for resource import options. This trait has automatic implementation
36/// for everything that implements [`ImportOptions`] trait.
37pub trait BaseImportOptions: Downcast + Reflect {
38    /// Saves the options to a file at the given path.
39    fn save(&self, path: &Path) -> bool;
40}
41
42/// A trait for resource import options. It provides generic functionality shared over all types of import options.
43pub trait ImportOptions:
44    BaseImportOptions + Serialize + DeserializeOwned + Default + Clone
45{
46    /// Saves import options into a specified file.
47    fn save_internal(&self, path: &Path) -> bool {
48        if let Ok(file) = File::create(path) {
49            if ron::ser::to_writer_pretty(file, self, PrettyConfig::default()).is_ok() {
50                return true;
51            }
52        }
53        false
54    }
55}
56
57impl<T> BaseImportOptions for T
58where
59    T: ImportOptions,
60{
61    fn save(&self, path: &Path) -> bool {
62        self.save_internal(path)
63    }
64}
65
66/// Tries to load import settings for a resource. It is not part of ImportOptions trait because
67/// `async fn` is not yet supported for traits.
68pub async fn try_get_import_settings<T>(resource_path: &Path, io: &dyn ResourceIo) -> Option<T>
69where
70    T: ImportOptions,
71{
72    let settings_path = append_extension(resource_path, OPTIONS_EXTENSION);
73
74    match io.load_file(settings_path.as_ref()).await {
75        Ok(bytes) => match ron::de::from_bytes::<T>(&bytes) {
76            Ok(options) => Some(options),
77            Err(e) => {
78                Log::warn(format!(
79                    "Malformed options file {} for {} resource, fallback to defaults! Reason: {:?}",
80                    settings_path.display(),
81                    resource_path.display(),
82                    e
83                ));
84
85                None
86            }
87        },
88        Err(e) => {
89            Log::warn(format!(
90                "Unable to load options file {} for {} resource, fallback to defaults! Reason: {:?}",
91                settings_path.display(),
92                resource_path.display(),
93                e
94            ));
95
96            None
97        }
98    }
99}
100
101/// Same as [`try_get_import_settings`], but returns opaque import settings.
102pub async fn try_get_import_settings_opaque<T>(
103    resource_path: &Path,
104    io: &dyn ResourceIo,
105) -> Option<Box<dyn BaseImportOptions>>
106where
107    T: ImportOptions,
108{
109    try_get_import_settings::<T>(resource_path, io)
110        .await
111        .map(|options| Box::new(options) as Box<dyn BaseImportOptions>)
112}