Skip to main content

ocio_rs/
file_rules.rs

1use std::ffi::c_void;
2use std::ptr::NonNull;
3
4use crate::{cstr_from_mut, cstring, OcioError, Result};
5use ocio_sys;
6
7fn checked_index(index: u64) -> Result<usize> {
8    usize::try_from(index).map_err(|_| {
9        OcioError::InvalidInput("file rule or custom key index does not fit usize".into())
10    })
11}
12
13/// Holds filename-based routing rules that map media paths to color spaces.
14pub struct FileRules {
15    pub(crate) handle: NonNull<c_void>,
16}
17
18impl FileRules {
19    /// Native name of the mandatory final rule.
20    pub const DEFAULT_RULE_NAME: &'static str = "Default";
21    /// Native name of the special color-space-name path search rule.
22    pub const FILE_PATH_SEARCH_RULE_NAME: &'static str = "ColorSpaceNamePathSearch";
23
24    /// Create file rules containing OCIO's mandatory default rule.
25    pub fn create() -> Result<Self> {
26        crate::clear_last_error();
27        let handle = unsafe { ocio_sys::ocio_file_rules_create() };
28        crate::handle_result(handle).map(|handle| Self { handle })
29    }
30
31    /// Create an editable deep copy of these file rules.
32    pub fn create_editable_copy(&self) -> Result<Self> {
33        crate::clear_last_error();
34        let handle = unsafe {
35            ocio_sys::ocio_file_rules_create_editable_copy(self.handle.as_ptr() as *mut c_void)
36        };
37        crate::handle_result(handle).map(|handle| Self { handle })
38    }
39
40    /// Get the total number of rule entries.
41    pub fn num_entries(&self) -> u64 {
42        unsafe { ocio_sys::ocio_file_rules_get_num_entries(self.handle.as_ptr()) as u64 }
43    }
44
45    /// Look up the index for a rule name using OCIO's case-insensitive matching.
46    ///
47    /// This compatibility method returns `u64::MAX` when OCIO rejects the name.
48    /// Prefer [`Self::try_index_for_rule`] to preserve the OCIO error, or
49    /// [`Self::rule_index`] for an optional lookup.
50    pub fn index_for_rule(&self, rule_name: impl AsRef<str>) -> u64 {
51        self.try_index_for_rule(rule_name).unwrap_or(u64::MAX)
52    }
53
54    /// Look up a rule index while preserving OCIO missing-rule errors.
55    pub fn try_index_for_rule(&self, rule_name: impl AsRef<str>) -> Result<u64> {
56        let rule_name = cstring(rule_name)?;
57        crate::clear_last_error();
58        let index = unsafe {
59            ocio_sys::ocio_file_rules_get_index_for_rule(
60                self.handle.as_ptr(),
61                rule_name.as_ptr().cast(),
62            ) as u64
63        };
64        crate::ocio_call_status()?;
65        Ok(index)
66    }
67
68    /// Look up the index for a rule name.
69    ///
70    /// Returns `None` when the rule is absent or the rule name is not a valid
71    /// C string for the OCIO ABI.
72    pub fn rule_index(&self, rule_name: impl AsRef<str>) -> Option<u64> {
73        self.try_index_for_rule(rule_name).ok()
74    }
75
76    /// Get the rule name at the given index.
77    pub fn name(&self, rule_index: u64) -> Option<String> {
78        self.try_name(rule_index).ok().flatten()
79    }
80
81    /// Get a rule name while preserving invalid-index and bridge failures.
82    pub fn try_name(&self, rule_index: u64) -> Result<Option<String>> {
83        crate::clear_last_error();
84        let name = unsafe {
85            cstr_from_mut(ocio_sys::ocio_file_rules_get_name(
86                self.handle.as_ptr(),
87                checked_index(rule_index)?,
88            ))
89        };
90        crate::ocio_call_status()?;
91        Ok(name)
92    }
93
94    /// Get the filename pattern for the rule at the given index.
95    pub fn pattern(&self, rule_index: u64) -> Option<String> {
96        self.try_pattern(rule_index).ok().flatten()
97    }
98
99    /// Get a filename pattern while preserving invalid-index and bridge failures.
100    pub fn try_pattern(&self, rule_index: u64) -> Result<Option<String>> {
101        crate::clear_last_error();
102        let pattern = unsafe {
103            cstr_from_mut(ocio_sys::ocio_file_rules_get_pattern(
104                self.handle.as_ptr(),
105                checked_index(rule_index)?,
106            ))
107        };
108        crate::ocio_call_status()?;
109        Ok(pattern)
110    }
111
112    /// Set the filename pattern for the rule at the given index.
113    pub fn set_pattern(&self, rule_index: u64, pattern: impl AsRef<str>) -> Result<()> {
114        let pattern = cstring(pattern)?;
115        crate::clear_last_error();
116        unsafe {
117            ocio_sys::ocio_file_rules_set_pattern(
118                self.handle.as_ptr(),
119                checked_index(rule_index)?,
120                pattern.as_ptr().cast(),
121            )
122        };
123        crate::ocio_call_status()
124    }
125
126    /// Get the file extension for the rule at the given index.
127    pub fn extension(&self, rule_index: u64) -> Option<String> {
128        self.try_extension(rule_index).ok().flatten()
129    }
130
131    /// Get a file extension while preserving invalid-index and bridge failures.
132    pub fn try_extension(&self, rule_index: u64) -> Result<Option<String>> {
133        crate::clear_last_error();
134        let extension = unsafe {
135            cstr_from_mut(ocio_sys::ocio_file_rules_get_extension(
136                self.handle.as_ptr(),
137                checked_index(rule_index)?,
138            ))
139        };
140        crate::ocio_call_status()?;
141        Ok(extension)
142    }
143
144    /// Set the file extension for the rule at the given index.
145    pub fn set_extension(&self, rule_index: u64, extension: impl AsRef<str>) -> Result<()> {
146        let extension = cstring(extension)?;
147        crate::clear_last_error();
148        unsafe {
149            ocio_sys::ocio_file_rules_set_extension(
150                self.handle.as_ptr(),
151                checked_index(rule_index)?,
152                extension.as_ptr().cast(),
153            )
154        };
155        crate::ocio_call_status()
156    }
157
158    /// Get the regex pattern for the rule at the given index.
159    pub fn regex(&self, rule_index: u64) -> Option<String> {
160        self.try_regex(rule_index).ok().flatten()
161    }
162
163    /// Get a regex pattern while preserving invalid-index and bridge failures.
164    pub fn try_regex(&self, rule_index: u64) -> Result<Option<String>> {
165        crate::clear_last_error();
166        let regex = unsafe {
167            cstr_from_mut(ocio_sys::ocio_file_rules_get_regex(
168                self.handle.as_ptr(),
169                checked_index(rule_index)?,
170            ))
171        };
172        crate::ocio_call_status()?;
173        Ok(regex)
174    }
175
176    /// Set the regex pattern for the rule at the given index.
177    pub fn set_regex(&self, rule_index: u64, regex: impl AsRef<str>) -> Result<()> {
178        let regex = cstring(regex)?;
179        crate::clear_last_error();
180        unsafe {
181            ocio_sys::ocio_file_rules_set_regex(
182                self.handle.as_ptr(),
183                checked_index(rule_index)?,
184                regex.as_ptr().cast(),
185            )
186        };
187        crate::ocio_call_status()
188    }
189
190    /// Get the color space name for the rule at the given index.
191    pub fn color_space(&self, rule_index: u64) -> Option<String> {
192        self.try_color_space(rule_index).ok().flatten()
193    }
194
195    /// Get a rule color-space name while preserving invalid-index and bridge failures.
196    pub fn try_color_space(&self, rule_index: u64) -> Result<Option<String>> {
197        crate::clear_last_error();
198        let color_space = unsafe {
199            cstr_from_mut(ocio_sys::ocio_file_rules_get_color_space(
200                self.handle.as_ptr(),
201                checked_index(rule_index)?,
202            ))
203        };
204        crate::ocio_call_status()?;
205        Ok(color_space)
206    }
207
208    /// Set the color space name for the rule at the given index.
209    pub fn set_color_space(&self, rule_index: u64, color_space: impl AsRef<str>) -> Result<()> {
210        let color_space = cstring(color_space)?;
211        crate::clear_last_error();
212        unsafe {
213            ocio_sys::ocio_file_rules_set_color_space(
214                self.handle.as_ptr(),
215                checked_index(rule_index)?,
216                color_space.as_ptr().cast(),
217            )
218        };
219        crate::ocio_call_status()
220    }
221
222    /// Get the number of custom keys on the rule at the given index.
223    pub fn num_custom_keys(&self, rule_index: u64) -> u64 {
224        self.try_num_custom_keys(rule_index).unwrap_or(0)
225    }
226
227    /// Get the number of custom keys, preserving invalid-index and bridge failures.
228    pub fn try_num_custom_keys(&self, rule_index: u64) -> Result<u64> {
229        let rule_index = checked_index(rule_index)?;
230        crate::clear_last_error();
231        let count = unsafe {
232            ocio_sys::ocio_file_rules_get_num_custom_keys(self.handle.as_ptr(), rule_index) as u64
233        };
234        crate::ocio_call_status()?;
235        Ok(count)
236    }
237
238    /// Get the name of the custom key at the given key index.
239    pub fn custom_key_name(&self, rule_index: u64, key: u64) -> Option<String> {
240        self.try_custom_key_name(rule_index, key).ok().flatten()
241    }
242
243    /// Get a custom-key name while preserving invalid-index and bridge failures.
244    pub fn try_custom_key_name(&self, rule_index: u64, key: u64) -> Result<Option<String>> {
245        crate::clear_last_error();
246        let name = unsafe {
247            cstr_from_mut(ocio_sys::ocio_file_rules_get_custom_key_name(
248                self.handle.as_ptr(),
249                checked_index(rule_index)?,
250                checked_index(key)?,
251            ))
252        };
253        crate::ocio_call_status()?;
254        Ok(name)
255    }
256
257    /// Get the value of the custom key at the given key index.
258    pub fn custom_key_value(&self, rule_index: u64, key: u64) -> Option<String> {
259        self.try_custom_key_value(rule_index, key).ok().flatten()
260    }
261
262    /// Get a custom-key value while preserving invalid-index and bridge failures.
263    pub fn try_custom_key_value(&self, rule_index: u64, key: u64) -> Result<Option<String>> {
264        crate::clear_last_error();
265        let value = unsafe {
266            cstr_from_mut(ocio_sys::ocio_file_rules_get_custom_key_value(
267                self.handle.as_ptr(),
268                checked_index(rule_index)?,
269                checked_index(key)?,
270            ))
271        };
272        crate::ocio_call_status()?;
273        Ok(value)
274    }
275
276    /// Set a custom key-value pair. An empty value removes the key.
277    pub fn set_custom_key(
278        &self,
279        rule_index: u64,
280        key: impl AsRef<str>,
281        value: impl AsRef<str>,
282    ) -> Result<()> {
283        let key = cstring(key)?;
284        let value = cstring(value)?;
285        crate::clear_last_error();
286        unsafe {
287            ocio_sys::ocio_file_rules_set_custom_key(
288                self.handle.as_ptr(),
289                checked_index(rule_index)?,
290                key.as_ptr().cast(),
291                value.as_ptr().cast(),
292            )
293        };
294        crate::ocio_call_status()
295    }
296
297    /// Insert a new rule with a filename pattern and extension at the given index.
298    pub fn insert_rule(
299        &self,
300        rule_index: u64,
301        name: impl AsRef<str>,
302        color_space: impl AsRef<str>,
303        pattern: impl AsRef<str>,
304        extension: impl AsRef<str>,
305    ) -> Result<()> {
306        let name = cstring(name)?;
307        let color_space = cstring(color_space)?;
308        let pattern = cstring(pattern)?;
309        let extension = cstring(extension)?;
310        crate::clear_last_error();
311        unsafe {
312            ocio_sys::ocio_file_rules_insert_rule(
313                self.handle.as_ptr(),
314                checked_index(rule_index)?,
315                name.as_ptr().cast(),
316                color_space.as_ptr().cast(),
317                pattern.as_ptr().cast(),
318                extension.as_ptr().cast(),
319            );
320        }
321        crate::ocio_call_status()
322    }
323
324    /// Insert a new rule with a regex pattern at the given index.
325    pub fn insert_rule_regex(
326        &self,
327        rule_index: u64,
328        name: impl AsRef<str>,
329        color_space: impl AsRef<str>,
330        regex: impl AsRef<str>,
331    ) -> Result<()> {
332        let name = cstring(name)?;
333        let color_space = cstring(color_space)?;
334        let regex = cstring(regex)?;
335        crate::clear_last_error();
336        unsafe {
337            ocio_sys::ocio_file_rules_insert_rule_v1(
338                self.handle.as_ptr(),
339                checked_index(rule_index)?,
340                name.as_ptr().cast(),
341                color_space.as_ptr().cast(),
342                regex.as_ptr().cast(),
343            );
344        }
345        crate::ocio_call_status()
346    }
347
348    #[deprecated(since = "0.2.0", note = "compat alias; prefer insert_rule_regex()")]
349    pub fn insert_rule_v1(
350        &self,
351        rule_index: u64,
352        name: impl AsRef<str>,
353        color_space: impl AsRef<str>,
354        regex: impl AsRef<str>,
355    ) -> Result<()> {
356        self.insert_rule_regex(rule_index, name, color_space, regex)
357    }
358
359    #[deprecated(
360        since = "0.2.0",
361        note = "panics on OCIO errors; prefer try_insert_path_search_rule()"
362    )]
363    pub fn insert_path_search_rule(&self, rule_index: u64) {
364        self.try_insert_path_search_rule(rule_index)
365            .expect("FileRules::insert_path_search_rule failed");
366    }
367
368    /// Insert OCIO's built-in path-search rule at `rule_index`.
369    pub fn try_insert_path_search_rule(&self, rule_index: u64) -> Result<()> {
370        crate::clear_last_error();
371        unsafe {
372            ocio_sys::ocio_file_rules_insert_path_search_rule(
373                self.handle.as_ptr(),
374                checked_index(rule_index)?,
375            )
376        };
377        crate::ocio_call_status()
378    }
379
380    /// Set the default color space used when no rule matches.
381    pub fn set_default_rule_color_space(&self, color_space: impl AsRef<str>) -> Result<()> {
382        let color_space = cstring(color_space)?;
383        crate::clear_last_error();
384        unsafe {
385            ocio_sys::ocio_file_rules_set_default_rule_color_space(
386                self.handle.as_ptr(),
387                color_space.as_ptr().cast(),
388            )
389        };
390        crate::ocio_call_status()
391    }
392
393    #[deprecated(
394        since = "0.2.0",
395        note = "panics on OCIO errors; prefer try_remove_rule()"
396    )]
397    pub fn remove_rule(&self, rule_index: u64) {
398        self.try_remove_rule(rule_index)
399            .expect("FileRules::remove_rule failed");
400    }
401
402    /// Remove the rule at `rule_index`.
403    pub fn try_remove_rule(&self, rule_index: u64) -> Result<()> {
404        crate::clear_last_error();
405        unsafe {
406            ocio_sys::ocio_file_rules_remove_rule(self.handle.as_ptr(), checked_index(rule_index)?)
407        };
408        crate::ocio_call_status()
409    }
410
411    #[deprecated(
412        since = "0.2.0",
413        note = "panics on OCIO errors; prefer try_increase_rule_priority()"
414    )]
415    pub fn increase_rule_priority(&self, rule_index: u64) {
416        self.try_increase_rule_priority(rule_index)
417            .expect("FileRules::increase_rule_priority failed");
418    }
419
420    /// Move the rule at `rule_index` toward the front of the rule list.
421    pub fn try_increase_rule_priority(&self, rule_index: u64) -> Result<()> {
422        crate::clear_last_error();
423        unsafe {
424            ocio_sys::ocio_file_rules_increase_rule_priority(
425                self.handle.as_ptr(),
426                checked_index(rule_index)?,
427            )
428        };
429        crate::ocio_call_status()
430    }
431
432    #[deprecated(
433        since = "0.2.0",
434        note = "panics on OCIO errors; prefer try_decrease_rule_priority()"
435    )]
436    pub fn decrease_rule_priority(&self, rule_index: u64) {
437        self.try_decrease_rule_priority(rule_index)
438            .expect("FileRules::decrease_rule_priority failed");
439    }
440
441    /// Move the rule at `rule_index` toward the end of the rule list.
442    pub fn try_decrease_rule_priority(&self, rule_index: u64) -> Result<()> {
443        crate::clear_last_error();
444        unsafe {
445            ocio_sys::ocio_file_rules_decrease_rule_priority(
446                self.handle.as_ptr(),
447                checked_index(rule_index)?,
448            )
449        };
450        crate::ocio_call_status()
451    }
452
453    /// Check whether the file rules are in their default (empty) state.
454    pub fn is_default(&self) -> bool {
455        unsafe { ocio_sys::ocio_file_rules_is_default(self.handle.as_ptr() as *mut c_void) }
456    }
457}
458
459impl Drop for FileRules {
460    fn drop(&mut self) {
461        unsafe { ocio_sys::ocio_file_rules_destroy(self.handle.as_ptr() as *mut c_void) };
462    }
463}
464
465#[cfg(test)]
466mod tests {
467    use super::*;
468
469    #[test]
470    fn create_file_rules() {
471        let rules = FileRules::create();
472        assert!(rules.is_ok());
473    }
474
475    #[test]
476    fn file_rules_methods_no_crash() {
477        let rules = FileRules::create().unwrap();
478        let _ = rules.num_entries();
479        let _ = rules.name(0);
480        let _ = rules.pattern(0);
481        let _ = rules.extension(0);
482        let _ = rules.regex(0);
483        let _ = rules.color_space(0);
484        let _ = rules.num_custom_keys(0);
485        let _ = rules.custom_key_name(0, 0);
486        let _ = rules.custom_key_value(0, 0);
487        let _ = rules.is_default();
488        let _ = rules.index_for_rule("Default");
489    }
490
491    #[test]
492    fn set_pattern_extension_regex_no_crash() {
493        let rules = FileRules::create().unwrap();
494        rules
495            .insert_rule(0, "TestRule", "ACEScg", "*.dpx", "dpx")
496            .unwrap();
497        assert!(rules.set_pattern(0, "*.exr").is_ok());
498        assert!(rules.set_extension(0, "exr").is_ok());
499        assert!(rules.set_regex(0, ".*").is_ok());
500        assert!(rules.set_color_space(0, "ACEScg").is_ok());
501    }
502
503    #[test]
504    fn insert_remove_rule_no_crash() {
505        let rules = FileRules::create().unwrap();
506        assert!(rules
507            .insert_rule(0, "TestRule", "ACEScg", "*.exr", "exr")
508            .is_ok());
509        assert!(rules
510            .insert_rule_regex(1, "RegexRule", "ACEScg", ".*\\.exr")
511            .is_ok());
512        rules.try_insert_path_search_rule(2).unwrap();
513        assert!(rules.set_default_rule_color_space("ACEScg").is_ok());
514        rules.try_remove_rule(0).unwrap();
515    }
516
517    #[test]
518    fn priority_no_crash() {
519        let rules = FileRules::create().unwrap();
520        rules
521            .insert_rule(0, "TestRule", "ACEScg", "*.exr", "exr")
522            .unwrap();
523        rules
524            .insert_rule(1, "SecondRule", "ACEScg", "*.dpx", "dpx")
525            .unwrap();
526        rules.try_increase_rule_priority(1).unwrap();
527        rules.try_decrease_rule_priority(0).unwrap();
528    }
529
530    #[test]
531    fn custom_keys_no_crash() {
532        let rules = FileRules::create().unwrap();
533        assert!(rules.set_custom_key(0, "key1", "value1").is_ok());
534    }
535
536    #[test]
537    fn create_editable_copy_no_crash() {
538        let rules = FileRules::create().unwrap();
539        let _ = rules.create_editable_copy();
540    }
541}