1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use super::*;
use std::ptr;
use std::mem;
use std::ffi::CStr;
use std::os::raw::c_void;
use std::cell::UnsafeCell;
use std::collections::HashMap;

/// A special case for non-thread-aware functions.
///
/// This context is used by default and you don't need to create it manually.
#[doc(hidden)]
pub struct GlobalContext {
    _not_thread_safe: UnsafeCell<()>,
}

#[doc(hidden)]
pub trait Context {
    fn as_ptr(&self) -> ffi::Context;
}

impl<'a> Context for &'a GlobalContext {
    #[inline]
    fn as_ptr(&self) -> ffi::Context {
        ptr::null_mut()
    }
}

impl Context for GlobalContext {
    #[inline]
    fn as_ptr(&self) -> ffi::Context {
        ptr::null_mut()
    }
}

unsafe impl Send for ThreadContext {}

impl<'a> Context for &'a ThreadContext {
    #[inline]
    fn as_ptr(&self) -> ffi::Context {
        self.handle
    }
}

impl Context for ThreadContext {
    #[inline]
    fn as_ptr(&self) -> ffi::Context {
        self.handle
    }
}

/// Per-thread context for multi-threaded operation.
///
/// There are situations where several instances of Little CMS engine have to coexist but on different conditions.
/// For example, when the library is used as a DLL or a shared object, diverse applications may want to use different plug-ins.
/// Another example is when multiple threads are being used in same task and the user wants to pass thread-dependent information to the memory allocators or the logging system.
/// The context is a pointer to an internal structure that keeps track of all plug-ins and static data needed by the THR corresponding function.
///
/// A context-aware app could allocate a new context by calling new() or duplicate a yet-existing one by using clone().
/// Each context can hold different plug-ins, defined by the Plugin parameter. The context can also hold loggers.
///
/// Users may associate private data across a void pointer when creating the context, and can retrieve this pointer later.
///
/// When you see an error "expected reference, found struct `lcms2::GlobalContext`", it means you've mixed global and thread-context objects. They don't work together.
/// For example, if you create a `Transform` with a context (calling `new_*_context()`), then it will only support `Profile` with a context as well.
pub struct ThreadContext {
    handle: ffi::Context,
}

impl GlobalContext {
    pub fn new() -> Self {
        Self {
            _not_thread_safe: UnsafeCell::new(()),
        }
    }

    pub fn unregister_plugins(&mut self) {
        unsafe {
            ffi::cmsUnregisterPlugins();
        }
    }
}

impl ThreadContext {
    pub fn new() -> Self {
        unsafe {
            Self::new_handle(ffi::cmsCreateContext(ptr::null_mut(), ptr::null_mut()))
        }
    }

    unsafe fn new_handle(handle: ffi::Context) -> Self {
        assert!(!handle.is_null());
        Self { handle }
    }

    pub fn user_data(&self) -> *mut c_void {
        unsafe {
            ffi::cmsGetContextUserData(self.handle)
        }
    }

    pub unsafe fn install_plugin(&mut self, plugin: *mut c_void) -> bool {
        0 != ffi::cmsPluginTHR(self.handle, plugin)
    }

    pub fn unregister_plugins(&mut self) {
        unsafe {
            ffi::cmsUnregisterPluginsTHR(self.handle);
        }
    }

    pub fn supported_intents(&self) -> HashMap<Intent, &CStr> {
        let mut codes = [Intent::PreserveKOnlySaturation; 32];
        let mut descs = [ptr::null_mut(); 32];
        let len = unsafe {
            assert_eq!(mem::size_of::<Intent>(), mem::size_of::<u32>());
            ffi::cmsGetSupportedIntentsTHR(self.handle, 32, &mut codes as *mut _ as *mut u32, descs.as_mut_ptr())
        };
        assert!(len <= 32);
        codes.iter().zip(descs.iter()).take(len as usize).map(|(&code,&desc)|{
            (code, unsafe {CStr::from_ptr(desc)})
        }).collect()
    }

    /// Adaptation state for absolute colorimetric intent, on all but cmsCreateExtendedTransform.
    pub fn adaptation_state(&self) -> f64 {
        unsafe { ffi::cmsSetAdaptationStateTHR(self.handle, -1.) }
    }

    /// Sets adaptation state for absolute colorimetric intent in the given context.  Adaptation state applies on all but cmsCreateExtendedTransformTHR().
    /// Little CMS can handle incomplete adaptation states.
    ///
    /// Degree on adaptation 0=Not adapted, 1=Complete adaptation,  in-between=Partial adaptation.
    pub fn set_adaptation_state(&mut self, value: f64) {
        unsafe {
            ffi::cmsSetAdaptationStateTHR(self.handle, value);
        }
    }

    /// Sets the codes used to mark out-out-gamut on Proofing transforms for a given context. Values are meant to be encoded in 16 bits.
    ///
    /// AlarmCodes: Array [16] of codes. ALL 16 VALUES MUST BE SPECIFIED, set to zero unused channels.
    pub fn set_alarm_codes(&mut self, codes: [u16; ffi::MAXCHANNELS]) {
        unsafe { ffi::cmsSetAlarmCodesTHR(self.handle, codes.as_ptr()) }
    }

    /// Gets the current codes used to mark out-out-gamut on Proofing transforms for the given context. Values are meant to be encoded in 16 bits.
    pub fn alarm_codes(&self) -> [u16; ffi::MAXCHANNELS] {
        let mut tmp = [0u16; ffi::MAXCHANNELS];
        unsafe {
            ffi::cmsGetAlarmCodesTHR(self.handle, tmp.as_mut_ptr());
        }
        tmp
    }
}

impl Clone for ThreadContext {
    fn clone(&self) -> Self {
        unsafe { Self::new_handle(ffi::cmsDupContext(self.handle, ptr::null_mut())) }
    }
}

impl Drop for ThreadContext {
    fn drop(&mut self) {
        unsafe { ffi::cmsDeleteContext(self.handle) }
    }
}

impl Default for GlobalContext {
    fn default() -> Self {
        Self::new()
        }
}

impl Default for ThreadContext {
    fn default() -> Self {
        Self::new()
    }
}

#[test]
fn context() {
    let mut c = ThreadContext::new();
    assert!(c.user_data().is_null());
    c.unregister_plugins();
    assert!(Profile::new_icc_context(&c, &[]).is_err());

    assert!(c.supported_intents().contains_key(&Intent::RelativeColorimetric));

    let _ = GlobalContext::default();
}