Debian Codegraph @

src/windows/reveal.rs

raw
1 use super::convert_path;
2 use crate::OpenError;
3 use normpath::PathExt;
4 use std::path::Path;
5 use std::{io, ptr, thread};
6 use winapi::shared::minwindef::{DWORD, UINT};
7 use winapi::shared::ntdef::PCWSTR;
8 use winapi::shared::winerror::HRESULT;
9 use winapi::um::combaseapi::{CoInitializeEx, CoUninitialize};
10 use winapi::um::objbase::COINIT_MULTITHREADED;
11 use winapi::um::shtypes::{
12 PCIDLIST_ABSOLUTE, PCUITEMID_CHILD_ARRAY, PIDLIST_ABSOLUTE, PIDLIST_RELATIVE,
13 };
14
15 pub(crate) fn reveal(path: &Path) -> Result<(), OpenError> {
16 let path = path.to_owned();
17 thread::Builder::new()
18 .spawn(move || reveal_in_thread(&path).map_err(OpenError::Io))
19 .map_err(OpenError::Io)?
20 .join()
21 .expect("COM worker thread should not panic")
22 }
23
24 fn reveal_in_thread(path: &Path) -> io::Result<()> {
25 to_io_result(unsafe { CoInitializeEx(ptr::null_mut(), COINIT_MULTITHREADED) })?;
26 let item_id_list = ItemIdList::new(path)?;
27 // Because the cidl argument is zero, SHOpenFolderAndSelectItems opens the singular item
28 // in our item id list in its containing folder and selects it.
29 to_io_result(unsafe { SHOpenFolderAndSelectItems(item_id_list.0, 0, ptr::null(), 0) })?;
30 unsafe { CoUninitialize() };
31 Ok(())
32 }
33
34 fn to_io_result(hresult: HRESULT) -> io::Result<()> {
35 if hresult >= 0 {
36 Ok(())
37 } else {
38 // See the HRESULT_CODE macro in winerror.h
39 Err(io::Error::from_raw_os_error(hresult & 0xFFFF))
40 }
41 }
42
43 struct ItemIdList(PIDLIST_ABSOLUTE);
44
45 impl ItemIdList {
46 fn new(path: &Path) -> io::Result<Self> {
47 // The ILCreateFromPathW function expects a canonicalized path.
48 // Unfortunately it does not support NT UNC paths (which std::path::canonicalize returns)
49 // so we use the normpath crate instead.
50 let path = convert_path(path.normalize()?.as_os_str())?;
51 let result = unsafe { ILCreateFromPathW(path.as_ptr()) };
52 if result.is_null() {
53 Err(io::Error::last_os_error())
54 } else {
55 Ok(ItemIdList(result))
56 }
57 }
58 }
59
60 impl Drop for ItemIdList {
61 fn drop(&mut self) {
62 unsafe { ILFree(self.0) }
63 }
64 }
65
66 #[link(name = "Shell32")]
67 extern "C" {
68 fn ILCreateFromPathW(pszPath: PCWSTR) -> PIDLIST_ABSOLUTE;
69
70 fn ILFree(pidl: PIDLIST_RELATIVE);
71
72 fn SHOpenFolderAndSelectItems(
73 pidlFolder: PCIDLIST_ABSOLUTE,
74 cidl: UINT,
75 apidl: PCUITEMID_CHILD_ARRAY,
76 dwFlags: DWORD,
77 ) -> HRESULT;
78 }