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 if let Ok(mut file) = File::create(path) {
51 if let Ok(string) = ron::ser::to_string_pretty(self, PrettyConfig::default()) {
52 Log::verify(file.write_all(string.as_bytes()));
53 return true;
54 }
55 }
56 false
57 }
58}
59
60impl<T> BaseImportOptions for T
61where
62 T: ImportOptions,
63{
64 fn save(&self, path: &Path) -> bool {
65 self.save_internal(path)
66 }
67}
68
69/// Tries to load import settings for a resource. It is not part of ImportOptions trait because
70/// `async fn` is not yet supported for traits.
71pub async fn try_get_import_settings<T>(resource_path: &Path, io: &dyn ResourceIo) -> Option<T>
72where
73 T: ImportOptions,
74{
75 let settings_path = append_extension(resource_path, OPTIONS_EXTENSION);
76
77 match io.load_file(settings_path.as_ref()).await {
78 Ok(bytes) => match ron::de::from_bytes::<T>(&bytes) {
79 Ok(options) => Some(options),
80 Err(e) => {
81 Log::warn(format!(
82 "Malformed options file {} for {} resource, fallback to defaults! Reason: {:?}",
83 settings_path.display(),
84 resource_path.display(),
85 e
86 ));
87
88 None
89 }
90 },
91 Err(e) => {
92 // Missing options file is a normal situation, the engine will use default import options
93 // instead. Any other error indicates a real issue that needs to be highlighted to the
94 // user.
95 if let FileError::Io(ref err) = e {
96 if err.kind() == ErrorKind::NotFound {
97 return None;
98 }
99 }
100
101 Log::warn(format!(
102 "Unable to load options file {} for {} resource, fallback to defaults! Reason: {:?}",
103 settings_path.display(),
104 resource_path.display(),
105 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}