|
| 1 | +use std::cell::Cell; |
| 2 | +use std::fmt; |
| 3 | +use std::marker::PhantomData; |
| 4 | +use std::rc::Rc; |
| 5 | + |
| 6 | +use windows::Win32::System::Com::{ |
| 7 | + COINIT, COINIT_APARTMENTTHREADED, COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize, |
| 8 | +}; |
| 9 | +use windows::core::HRESULT; |
| 10 | + |
| 11 | +/// COM apartment model. |
| 12 | +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] |
| 13 | +pub enum Type { |
| 14 | + /// Single-Threaded Apartment (STA) |
| 15 | + Sta, |
| 16 | + /// Multi-Threaded Apartment (MTA) |
| 17 | + Mta, |
| 18 | +} |
| 19 | + |
| 20 | +impl Type { |
| 21 | + #[must_use] |
| 22 | + pub fn as_raw(&self) -> COINIT { |
| 23 | + match self { |
| 24 | + Type::Sta => COINIT_APARTMENTTHREADED, |
| 25 | + Type::Mta => COINIT_MULTITHREADED, |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + #[must_use] |
| 30 | + pub fn as_code(&self) -> i32 { |
| 31 | + self.as_raw().0 |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +/// HRESULT returned when COM is already initialized on the current thread with a |
| 36 | +/// different apartment model than requested. |
| 37 | +/// |
| 38 | +/// In this situation COM remains usable, but the requested model is not applied. |
| 39 | +const RPC_E_CHANGED_MODE: HRESULT = HRESULT(0x8001_0106_u32.cast_signed()); |
| 40 | + |
| 41 | +thread_local! { |
| 42 | + /// Per-thread flag that stores whether COM has been initialized. |
| 43 | + static COM_INIT: Cell<bool> = const { Cell::new(false) }; |
| 44 | +} |
| 45 | + |
| 46 | +/// Result of a COM initialization attempt. |
| 47 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 48 | +pub enum Initialization { |
| 49 | + /// COM was successfully initialized by this call. |
| 50 | + Success, |
| 51 | + /// COM was already initialized on this thread, either: |
| 52 | + /// - by a previous call to `initialize_as` |
| 53 | + /// - by external code |
| 54 | + AlreadyInitialized, |
| 55 | +} |
| 56 | + |
| 57 | +/// Initializes COM for the current thread. |
| 58 | +/// This is done automatically when reading or writing shortcuts (as STA). |
| 59 | +pub fn initialize_as(kind: Type) -> Result<Initialization, Error> { |
| 60 | + COM_INIT.with(|state| { |
| 61 | + if state.get() { |
| 62 | + return Ok(Initialization::AlreadyInitialized); |
| 63 | + } |
| 64 | + |
| 65 | + let coinit: COINIT = match kind { |
| 66 | + Type::Sta => COINIT_APARTMENTTHREADED, |
| 67 | + Type::Mta => COINIT_MULTITHREADED, |
| 68 | + }; |
| 69 | + |
| 70 | + let hresult = unsafe { CoInitializeEx(None, coinit) }; |
| 71 | + |
| 72 | + match hresult { |
| 73 | + HRESULT(0) => { |
| 74 | + state.set(true); |
| 75 | + Ok(Initialization::Success) |
| 76 | + } |
| 77 | + HRESULT(1) | RPC_E_CHANGED_MODE => { |
| 78 | + state.set(true); |
| 79 | + Ok(Initialization::AlreadyInitialized) |
| 80 | + } |
| 81 | + _ => Err(windows::core::Error::from_hresult(hresult).context(None, "CoInitializeEx")), |
| 82 | + } |
| 83 | + }) |
| 84 | +} |
| 85 | + |
| 86 | +pub(crate) fn ensure_initialized() -> crate::Result<()> { |
| 87 | + match initialize_as(Type::Sta) { |
| 88 | + Ok(_) => Ok(()), |
| 89 | + Err(err) => Err(crate::Error::Com(err)), |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +/// Uninitialize COM for the current thread. |
| 94 | +pub fn uninitialize() { |
| 95 | + COM_INIT.with(|state| { |
| 96 | + if state.get() { |
| 97 | + unsafe { CoUninitialize() }; |
| 98 | + } |
| 99 | + }); |
| 100 | +} |
| 101 | + |
| 102 | +/// RAII wrapper around [`initialize_as`] / [`uninitialize`]. |
| 103 | +#[derive(Debug)] |
| 104 | +pub struct Session { |
| 105 | + uninit_on_drop: bool, |
| 106 | + _no_send: PhantomData<Rc<()>>, |
| 107 | +} |
| 108 | + |
| 109 | +impl Session { |
| 110 | + /// Initializes COM for the current thread and returns a guard that will call |
| 111 | + /// [`uninitialize`] on drop if COM was not already initialized. |
| 112 | + pub fn new(kind: Type) -> Result<Self, Error> { |
| 113 | + let init = initialize_as(kind)?; |
| 114 | + Ok(Self { |
| 115 | + uninit_on_drop: init == Initialization::Success, |
| 116 | + _no_send: PhantomData, |
| 117 | + }) |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +impl Drop for Session { |
| 122 | + fn drop(&mut self) { |
| 123 | + if self.uninit_on_drop { |
| 124 | + uninitialize(); |
| 125 | + } |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +/// Identifies a COM method. |
| 130 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] |
| 131 | +pub struct MethodInfo<'a> { |
| 132 | + /// Optional COM interface name (e.g. `IShellLinkW`). |
| 133 | + pub interface: Option<&'a str>, |
| 134 | + /// COM method name (e.g. `GetPath`). |
| 135 | + pub method: &'a str, |
| 136 | +} |
| 137 | + |
| 138 | +impl fmt::Display for MethodInfo<'_> { |
| 139 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 140 | + match self.interface { |
| 141 | + Some(interface) => write!(f, "{}::{}", interface, self.method), |
| 142 | + None => write!(f, "{}", self.method), |
| 143 | + } |
| 144 | + } |
| 145 | +} |
| 146 | + |
| 147 | +/// Windows / COM error annotated with the COM method that failed. |
| 148 | +/// |
| 149 | +/// This type exists to add semantic context to `windows::core::Error` |
| 150 | +/// without losing the original error as the source. |
| 151 | +#[derive(Debug, thiserror::Error)] |
| 152 | +#[error("COM error from {method}: {source}")] |
| 153 | +pub struct Error { |
| 154 | + /// The COM method that produced the error. |
| 155 | + pub method: MethodInfo<'static>, |
| 156 | + |
| 157 | + /// The underlying Windows error. |
| 158 | + #[source] |
| 159 | + pub source: windows::core::Error, |
| 160 | +} |
| 161 | + |
| 162 | +pub(crate) trait ComErrorExt { |
| 163 | + fn context(self, interface: Option<&'static str>, method: &'static str) -> Error; |
| 164 | +} |
| 165 | + |
| 166 | +impl ComErrorExt for windows::core::Error { |
| 167 | + fn context(self, interface: Option<&'static str>, method: &'static str) -> Error { |
| 168 | + Error { |
| 169 | + method: MethodInfo { interface, method }, |
| 170 | + source: self, |
| 171 | + } |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | +pub(crate) trait ComResultExt<T> { |
| 176 | + fn context(self, interface: Option<&'static str>, method: &'static str) -> crate::Result<T>; |
| 177 | +} |
| 178 | + |
| 179 | +impl<T> ComResultExt<T> for windows::core::Result<T> { |
| 180 | + fn context(self, interface: Option<&'static str>, method: &'static str) -> crate::Result<T> { |
| 181 | + self.map_err(|source| crate::Error::Com(source.context(interface, method))) |
| 182 | + } |
| 183 | +} |
0 commit comments