A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! src\dialogo\dialogo.cpp: DialogoMac.dll, que troca a janela de Abrir/Salvar do Windows (IFileOpenDialog /
//! IFileSaveDialog) pelo Finder em modo escolher (WacOSFinder.exe --escolher ...).
//!
//! Registrada só para o usuário (HKCU\Software\Classes\CLSID\{...}\InprocServer32), no lugar das classes do comdlg32.
//! Para cada pedido:
//! - programa fora da lista (%APPDATA%\Shell\dialogo.txt) → entrega o diálogo original na hora;
//! - na lista → cria o diálogo original por dentro e repassa a ele todas as chamadas (tipos, controles extras,
//! eventos...); só o Show abre o Finder, e depois GetResult/GetResults/GetFileName devolvem o que foi escolhido.
//! Shift segurado no Show, ou Finder ausente, mostra o diálogo original.
//! O modo nativo (MacDialogo.dll com o Finder dentro, DIALOGO_NATIVO) não foi portado (abandonado com o Shell nativo).
//! O QueryInterface repassa ao original as interfaces que o embrulho não conhece (controles extras, IObjectWithSite,
//! as privadas do comdlg32...), como no C++: o `#[implement]` não tem esse gancho, então `gancho_qi` troca o
//! QueryInterface de cada vtable do objeto (cópias das vtables, presas ao objeto e soltas com ele).
#![allow(non_snake_case)]
use std::cell::RefCell;
use std::sync::atomic::{AtomicIsize, Ordering};
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::LibraryLoader::*;
use comum::windows::Win32::System::Ole::IObjectWithSite_Impl;
use comum::windows::Win32::System::Ole::IObjectWithSite;
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::{EnableWindow, GetKeyState, VK_SHIFT};
use comum::windows::Win32::UI::Shell::Common::*;
use comum::windows::Win32::UI::Shell::PropertiesSystem::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::{from_w, pc, wz};
/// A DLL roda dentro dos programas que abrem o Abrir/Salvar: um pânico do Rust num método COM derrubaria o programa.
/// Com o perfil `dll` (panic = "unwind", build-rust.ps1) vira E_UNEXPECTED (ou o valor neutro nas exportadas).
fn guarda<R>(padrao: R, f: impl FnOnce() -> R) -> R {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or(padrao)
}
fn guarda_com<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| Err(E_UNEXPECTED.into()))
}
static SELF: AtomicIsize = AtomicIsize::new(0);
const CLSID_OPEN: GUID = GUID::from_u128(0xDC1C5A9C_E88A_4DDE_A5A1_60F82A20AEF7);
const CLSID_SAVE: GUID = GUID::from_u128(0xC0B4E2F3_BA21_4773_8DBA_335EC946EB8B);
fn self_dir() -> String {
let mut p = [0u16; 260];
let n = unsafe { GetModuleFileNameW(HMODULE(SELF.load(Ordering::SeqCst) as *mut _), &mut p) } as usize;
let s = String::from_utf16_lossy(&p[..n]);
s.rfind('\\').map(|i| s[..i].to_string()).unwrap_or(s)
}
fn log(s: &str) {
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(format!("{}\\dialogo.log", self_dir())) {
let _ = writeln!(f, "{s}");
}
}
/// o original do Windows (comdlg32.dll) para esta classe
fn real_factory(clsid: &GUID) -> Result<IClassFactory> {
unsafe {
let m = LoadLibraryW(w!("comdlg32.dll"))?;
let f = GetProcAddress(m, s!("DllGetClassObject")).ok_or(Error::from(CLASS_E_CLASSNOTAVAILABLE))?;
let f: unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut core::ffi::c_void) -> HRESULT = std::mem::transmute(f);
let mut out: *mut core::ffi::c_void = std::ptr::null_mut();
f(clsid, &IClassFactory::IID, &mut out).ok()?;
Ok(IClassFactory::from_raw(out))
}
}
/// programa na lista? (%APPDATA%\Shell\dialogo.txt, um .exe por linha; "*" = todos)
fn allowed() -> bool {
let exe = std::env::current_exe().ok().and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_lowercase())).unwrap_or_default();
if exe == "arquivos.exe" || exe == "wacosfinder.exe" {
return false;
}
// Adobe Illustrator (issue #486): o Salvar Como abria as duas janelas, a do Windows e o Finder; fica a original
if exe == "illustrator.exe" {
return false;
}
let Ok(t) = std::fs::read_to_string(format!("{}\\Shell\\dialogo.txt", std::env::var("APPDATA").unwrap_or_default())) else { return exe == "dialogoteste.exe" };
// o C++ lê com ccs=UTF-8: o BOM do começo some
t.trim_start_matches('\u{feff}').lines().map(|l| l.trim_end_matches([' ', '\r']).to_lowercase()).any(|l| l == "*" || l == exe)
}
/// vale também para arquivo que ainda não existe
fn item_from_path(path: &str) -> Result<IShellItem> {
unsafe {
let pidl = SHSimpleIDListFromPath(pc(&wz(path)));
if pidl.is_null() {
return Err(E_FAIL.into());
}
let r = SHCreateItemFromIDList(pidl);
CoTaskMemFree(Some(pidl as *const _));
r
}
}
fn path_of(it: Option<&IShellItem>) -> String {
let Some(it) = it else { return String::new() };
unsafe {
match it.GetDisplayName(SIGDN_FILESYSPATH) {
Ok(p) => {
let s = p.to_string().unwrap_or_default();
CoTaskMemFree(Some(p.0 as *const _));
s
}
Err(_) => String::new(),
}
}
}
fn file_name(p: &str) -> &str {
p.rsplit('\\').next().unwrap_or(p)
}
/// aspas do jeito que o CommandLineToArgvW do Finder entende: barras antes de aspa dobram e aspas internas são escapadas
/// (só pôr aspas em volta quebrava tudo com uma pasta "D:\": issue #19)
fn q(s: &str) -> String {
let mut r = String::from("\"");
let mut bs = 0;
for c in s.chars() {
if c == '\\' {
bs += 1;
continue;
}
if c == '"' {
r.push_str(&"\\".repeat(bs * 2 + 1));
r.push('"');
bs = 0;
continue;
}
r.push_str(&"\\".repeat(bs));
bs = 0;
r.push(c);
}
r.push_str(&"\\".repeat(bs * 2));
r.push('"');
r
}
#[derive(Default)]
struct Estado {
// o que o programa configurou
types: Vec<(String, String)>,
type_index: u32,
opts: u32,
folder: String,
def_folder: String,
file_name: String,
ok_label: String,
def_ext: String,
events: Option<IFileDialogEvents>,
// o que foi escolhido no Finder
chosen: bool,
results: Vec<String>,
}
/// dois tipos (Abrir e Salvar) com o mesmo código: cada um responde só pela interface dele, como o C++
#[implement(IFileOpenDialog, IFileDialog2, IFileDialogCustomize, IObjectWithSite)]
#[allow(dead_code)]
struct WrapOpen {
save: bool,
/// o original
inner: IFileDialog,
inner_open: Option<IFileOpenDialog>,
inner_save: Option<IFileSaveDialog>,
st: RefCell<Estado>,
}
#[implement(IFileSaveDialog, IFileDialog2, IFileDialogCustomize, IObjectWithSite)]
#[allow(dead_code)]
struct WrapSave {
save: bool,
/// o original
inner: IFileDialog,
inner_open: Option<IFileOpenDialog>,
inner_save: Option<IFileSaveDialog>,
st: RefCell<Estado>,
}
/// o mesmo código para os dois tipos
macro_rules! impls {
($w:ty, $t:ty) => {
impl $w {
fn d2(&self) -> Result<IFileDialog2> {
crate::guarda_com(|| {
self.inner.cast::<IFileDialog2>().map_err(|_| Error::from(E_NOTIMPL))
})
}
fn customize(&self) -> Result<IFileDialogCustomize> {
crate::guarda_com(|| {
self.inner.cast()
})
}
}
impl IModalWindow_Impl for $t {
fn Show(&self, owner: HWND) -> Result<()> {
crate::guarda_com(|| {
unsafe {
let finder = format!("{}\\WacOSFinder.exe", self_dir());
if GetKeyState(VK_SHIFT.0 as i32) as u16 & 0x8000 != 0 || !std::path::Path::new(&finder).exists() {
return self.inner.Show(owner); // escape: o original
}
let mut st = self.st.borrow_mut();
st.chosen = false;
st.results.clear();
let mut start = if !st.folder.is_empty() { st.folder.clone() } else { st.def_folder.clone() };
if start.is_empty() {
if let Ok(d) = SHGetKnownFolderPath(&FOLDERID_Documents, KF_FLAG_DEFAULT, None) {
start = d.to_string().unwrap_or_default();
CoTaskMemFree(Some(d.0 as *const _));
}
}
let res = format!("{}dlg{}-{}.tmp", std::env::temp_dir().to_string_lossy().trim_end_matches('\\').to_string() + "\\", GetCurrentProcessId(), GetTickCount64Safe());
let modo = if st.opts & FOS_PICKFOLDERS.0 != 0 {
"pasta"
} else if self.save {
"salvar"
} else {
"abrir"
};
let mut cmd = format!("{} {} --lista --escolher {modo}", q(&finder), q(&start));
if st.opts & FOS_ALLOWMULTISELECT.0 != 0 {
cmd += " --multi";
}
if self.save && st.opts & FOS_OVERWRITEPROMPT.0 == 0 {
cmd += " --sem-confirmar";
}
if !st.types.is_empty() {
let t = st.types.iter().map(|(d, sp)| format!("{d}|{sp}")).collect::<Vec<_>>().join("||");
cmd += &format!(" --tipos {} --tipo {}", q(&t), st.type_index.max(1) - 1);
}
if !st.file_name.is_empty() {
cmd += &format!(" --nome {}", q(&st.file_name));
}
if !st.ok_label.is_empty() {
cmd += &format!(" --ok {}", q(&st.ok_label));
}
if !st.def_ext.is_empty() {
cmd += &format!(" --ext {}", q(&st.def_ext));
}
cmd += &format!(" --resultado {}", q(&res));
let root = if owner.0.is_null() { HWND::default() } else { GetAncestor(owner, GA_ROOT) };
if !owner.0.is_null() {
cmd += &format!(" --pai {}", root.0 as usize);
}
log(&format!("Show: {cmd}"));
drop(st);
let mut c = wz(&cmd);
let si = STARTUPINFOW { cb: std::mem::size_of::<STARTUPINFOW>() as u32, ..Default::default() };
let mut pi = PROCESS_INFORMATION::default();
if let Err(e) = CreateProcessW(None, PWSTR(c.as_mut_ptr()), None, None, false, PROCESS_CREATION_FLAGS(0), None, None, &si, &mut pi) {
log(&format!(" não abriu o Finder ({}): diálogo original", e.code().0 as u32));
return self.inner.Show(owner);
}
let _ = AllowSetForegroundWindow(pi.dwProcessId);
if !root.0.is_null() {
let _ = EnableWindow(root, false); // modal, como o original
}
loop {
// espera o Finder fechar sem travar o programa (mensagens continuam)
let w_ = MsgWaitForMultipleObjects(Some(&[pi.hProcess]), false, INFINITE, QS_ALLINPUT);
if w_ == WAIT_OBJECT_0 {
break;
}
let mut m = MSG::default();
while PeekMessageW(&mut m, None, 0, 0, PM_REMOVE).as_bool() {
let _ = TranslateMessage(&m);
DispatchMessageW(&m);
}
}
let mut code = 1u32;
let _ = GetExitCodeProcess(pi.hProcess, &mut code);
let _ = CloseHandle(pi.hProcess);
let _ = CloseHandle(pi.hThread);
if !root.0.is_null() {
let _ = EnableWindow(root, true);
let _ = SetForegroundWindow(root);
}
let mut st = self.st.borrow_mut();
if code == 0 {
if let Ok(t) = std::fs::read_to_string(&res) {
// o Finder grava com BOM (app2d::write_lines): com ele a 1ª linha virava "\u{feff}C:\..." e o
// programa não recebia o arquivo escolhido (teste ao vivo de 27/11/2026)
for l in t.trim_start_matches('\u{feff}').lines() {
let l = l.trim_end_matches('\r');
if let Some(n) = l.strip_prefix("tipo=") {
st.type_index = n.trim().parse::<u32>().unwrap_or(0) + 1;
} else if !l.is_empty() {
st.results.push(l.to_string());
}
}
}
}
let _ = std::fs::remove_file(&res);
if st.results.is_empty() {
log(" cancelado");
return Err(HRESULT::from_win32(ERROR_CANCELLED.0).into());
}
st.chosen = true;
log(&format!(" escolhido: {}", st.results[0]));
// o original fica coerente, para quem perguntar a ele (ex.: controles extras)
let _ = self.inner.SetFileTypeIndex(st.type_index);
let first = st.results[0].clone();
// issue #387: quem abre pelo GetOpenFileName recebe o resultado do diálogo de dentro, que ficava só com o
// 1º nome. Agora a pasta e, com vários, os nomes entre aspas ("a.png" "b.png"), como no do Windows
if st.opts & FOS_PICKFOLDERS.0 == 0 {
if let Some(i) = first.rfind('\\') {
let mut pasta = first[..i].to_string();
if pasta.len() == 2 {
pasta.push('\\');
}
if let Ok(it) = item_from_path(&pasta) {
let _ = self.inner.SetFolder(&it);
}
}
}
if st.results.len() > 1 {
let nomes = st.results.iter().map(|r| format!("\"{}\"", file_name(r))).collect::<Vec<_>>().join(" ");
let _ = self.inner.SetFileName(pc(&wz(&nomes)));
} else {
let _ = self.inner.SetFileName(pc(&wz(file_name(&first))));
}
let ev = st.events.clone();
drop(st);
if let Some(ev) = ev {
if let Ok(me) = self.cast::<IFileDialog>() {
let _ = ev.OnFileOk(&me);
}
}
Ok(())
}
})
}
}
impl IFileDialog_Impl for $t {
fn SetFileTypes(&self, n: u32, s: *const COMDLG_FILTERSPEC) -> Result<()> {
crate::guarda_com(|| {
let mut st = self.st.borrow_mut();
st.types.clear();
for i in 0..n as usize {
let f = unsafe { &*s.add(i) };
let name = if f.pszName.is_null() { String::new() } else { unsafe { f.pszName.to_string().unwrap_or_default() } };
let spec = if f.pszSpec.is_null() { "*.*".to_string() } else { unsafe { f.pszSpec.to_string().unwrap_or_default() } };
st.types.push((name, spec));
}
unsafe { self.inner.SetFileTypes(std::slice::from_raw_parts(s, n as usize)) }
})
}
fn SetFileTypeIndex(&self, i: u32) -> Result<()> {
crate::guarda_com(|| {
self.st.borrow_mut().type_index = i;
unsafe { self.inner.SetFileTypeIndex(i) }
})
}
fn GetFileTypeIndex(&self) -> Result<u32> {
crate::guarda_com(|| {
let st = self.st.borrow();
if st.chosen {
return Ok(st.type_index);
}
unsafe { self.inner.GetFileTypeIndex() }
})
}
fn Advise(&self, e: Option<&IFileDialogEvents>) -> Result<u32> {
crate::guarda_com(|| {
if let Some(e) = e {
self.st.borrow_mut().events = Some(e.clone());
}
unsafe { self.inner.Advise(e) }
})
}
fn Unadvise(&self, c: u32) -> Result<()> {
crate::guarda_com(|| {
self.st.borrow_mut().events = None;
unsafe { self.inner.Unadvise(c) }
})
}
fn SetOptions(&self, o: FILEOPENDIALOGOPTIONS) -> Result<()> {
crate::guarda_com(|| {
self.st.borrow_mut().opts = o.0;
unsafe { self.inner.SetOptions(o) }
})
}
fn GetOptions(&self) -> Result<FILEOPENDIALOGOPTIONS> {
crate::guarda_com(|| {
unsafe { self.inner.GetOptions() }
})
}
fn SetDefaultFolder(&self, s: Option<&IShellItem>) -> Result<()> {
crate::guarda_com(|| {
self.st.borrow_mut().def_folder = path_of(s);
unsafe { self.inner.SetDefaultFolder(s) }
})
}
fn SetFolder(&self, s: Option<&IShellItem>) -> Result<()> {
crate::guarda_com(|| {
self.st.borrow_mut().folder = path_of(s);
unsafe { self.inner.SetFolder(s) }
})
}
fn GetFolder(&self) -> Result<IShellItem> {
crate::guarda_com(|| {
let st = self.st.borrow();
if st.chosen {
let mut p = st.results[0].clone();
if st.opts & FOS_PICKFOLDERS.0 == 0 {
if let Some(i) = p.rfind('\\') {
p.truncate(i);
}
if p.len() == 2 {
p.push('\\');
}
}
return item_from_path(&p);
}
unsafe { self.inner.GetFolder() }
})
}
fn GetCurrentSelection(&self) -> Result<IShellItem> {
crate::guarda_com(|| {
if self.st.borrow().chosen {
return self.GetResult();
}
unsafe { self.inner.GetCurrentSelection() }
})
}
fn SetFileName(&self, n: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
self.st.borrow_mut().file_name = if n.is_null() { String::new() } else { unsafe { n.to_string().unwrap_or_default() } };
unsafe { self.inner.SetFileName(*n) }
})
}
fn GetFileName(&self) -> Result<PWSTR> {
crate::guarda_com(|| {
let st = self.st.borrow();
if st.chosen {
return unsafe { SHStrDupW(pc(&wz(file_name(&st.results[0])))) };
}
unsafe { self.inner.GetFileName() }
})
}
fn SetTitle(&self, t: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.inner.SetTitle(*t) }
})
}
fn SetOkButtonLabel(&self, t: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
self.st.borrow_mut().ok_label = if t.is_null() { String::new() } else { unsafe { t.to_string().unwrap_or_default() } };
unsafe { self.inner.SetOkButtonLabel(*t) }
})
}
fn SetFileNameLabel(&self, t: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.inner.SetFileNameLabel(*t) }
})
}
fn GetResult(&self) -> Result<IShellItem> {
crate::guarda_com(|| {
let st = self.st.borrow();
if !st.chosen {
return unsafe { self.inner.GetResult() };
}
item_from_path(&st.results[0])
})
}
fn AddPlace(&self, s: Option<&IShellItem>, a: FDAP) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.inner.AddPlace(s, a) }
})
}
fn SetDefaultExtension(&self, e: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
self.st.borrow_mut().def_ext = if e.is_null() { String::new() } else { unsafe { e.to_string().unwrap_or_default() } };
unsafe { self.inner.SetDefaultExtension(*e) }
})
}
fn Close(&self, h: HRESULT) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.inner.Close(h) }
})
}
fn SetClientGuid(&self, g: *const GUID) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.inner.SetClientGuid(g) }
})
}
fn ClearClientData(&self) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.inner.ClearClientData() }
})
}
fn SetFilter(&self, f: Option<&IShellItemFilter>) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.inner.SetFilter(f) }
})
}
}
impl IFileDialog2_Impl for $t {
fn SetCancelButtonLabel(&self, t: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.d2()?.SetCancelButtonLabel(*t) }
})
}
fn SetNavigationRoot(&self, i: Option<&IShellItem>) -> Result<()> {
crate::guarda_com(|| {
{
let mut st = self.st.borrow_mut();
if st.folder.is_empty() && st.def_folder.is_empty() {
st.def_folder = path_of(i);
}
}
unsafe { self.d2()?.SetNavigationRoot(i) }
})
}
}
// os controles extras e o site ficam com o original (no C++ o QueryInterface repassava as interfaces desconhecidas)
impl IObjectWithSite_Impl for $t {
fn SetSite(&self, s: Option<&IUnknown>) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.inner.cast::<IObjectWithSite>()?.SetSite(s) }
})
}
fn GetSite(&self, riid: *const GUID, out: *mut *mut core::ffi::c_void) -> Result<()> {
crate::guarda_com(|| {
let ows = self.inner.cast::<IObjectWithSite>()?;
unsafe { (Interface::vtable(&ows).GetSite)(Interface::as_raw(&ows), riid, out).ok() }
})
}
}
impl IFileDialogCustomize_Impl for $t {
fn EnableOpenDropDown(&self, id: u32) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.EnableOpenDropDown(id) }
})
}
fn AddMenu(&self, id: u32, l: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.AddMenu(id, *l) }
})
}
fn AddPushButton(&self, id: u32, l: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.AddPushButton(id, *l) }
})
}
fn AddComboBox(&self, id: u32) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.AddComboBox(id) }
})
}
fn AddRadioButtonList(&self, id: u32) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.AddRadioButtonList(id) }
})
}
fn AddCheckButton(&self, id: u32, l: &PCWSTR, c: BOOL) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.AddCheckButton(id, *l, c) }
})
}
fn AddEditBox(&self, id: u32, t: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.AddEditBox(id, *t) }
})
}
fn AddSeparator(&self, id: u32) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.AddSeparator(id) }
})
}
fn AddText(&self, id: u32, t: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.AddText(id, *t) }
})
}
fn SetControlLabel(&self, id: u32, l: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.SetControlLabel(id, *l) }
})
}
fn GetControlState(&self, id: u32) -> Result<CDCONTROLSTATEF> {
crate::guarda_com(|| {
unsafe { self.customize()?.GetControlState(id) }
})
}
fn SetControlState(&self, id: u32, s: CDCONTROLSTATEF) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.SetControlState(id, s) }
})
}
fn GetEditBoxText(&self, id: u32) -> Result<*mut u16> {
crate::guarda_com(|| {
unsafe { self.customize()?.GetEditBoxText(id) }
})
}
fn SetEditBoxText(&self, id: u32, t: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.SetEditBoxText(id, *t) }
})
}
fn GetCheckButtonState(&self, id: u32) -> Result<BOOL> {
crate::guarda_com(|| {
unsafe { self.customize()?.GetCheckButtonState(id) }
})
}
fn SetCheckButtonState(&self, id: u32, c: BOOL) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.SetCheckButtonState(id, c) }
})
}
fn AddControlItem(&self, id: u32, item: u32, l: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.AddControlItem(id, item, *l) }
})
}
fn RemoveControlItem(&self, id: u32, item: u32) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.RemoveControlItem(id, item) }
})
}
fn RemoveAllControlItems(&self, id: u32) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.RemoveAllControlItems(id) }
})
}
fn GetControlItemState(&self, id: u32, item: u32) -> Result<CDCONTROLSTATEF> {
crate::guarda_com(|| {
unsafe { self.customize()?.GetControlItemState(id, item) }
})
}
fn SetControlItemState(&self, id: u32, item: u32, s: CDCONTROLSTATEF) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.SetControlItemState(id, item, s) }
})
}
fn GetSelectedControlItem(&self, id: u32) -> Result<u32> {
crate::guarda_com(|| {
unsafe { self.customize()?.GetSelectedControlItem(id) }
})
}
fn SetSelectedControlItem(&self, id: u32, item: u32) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.SetSelectedControlItem(id, item) }
})
}
fn StartVisualGroup(&self, id: u32, l: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.StartVisualGroup(id, *l) }
})
}
fn EndVisualGroup(&self) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.EndVisualGroup() }
})
}
fn MakeProminent(&self, id: u32) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.MakeProminent(id) }
})
}
fn SetControlItemText(&self, id: u32, item: u32, l: &PCWSTR) -> Result<()> {
crate::guarda_com(|| {
unsafe { self.customize()?.SetControlItemText(id, item, *l) }
})
}
}
};
}
impls!(WrapOpen, WrapOpen_Impl);
impls!(WrapSave, WrapSave_Impl);
#[allow(non_snake_case)]
fn GetTickCount64Safe() -> u64 {
unsafe { comum::windows::Win32::System::SystemInformation::GetTickCount64() }
}
impl IFileOpenDialog_Impl for WrapOpen_Impl {
fn GetResults(&self) -> Result<IShellItemArray> {
crate::guarda_com(|| {
let st = self.st.borrow();
if !st.chosen {
return match &self.inner_open {
Some(o) => unsafe { o.GetResults() },
None => Err(E_UNEXPECTED.into()),
};
}
unsafe {
let pidls: Vec<*const ITEMIDLIST> = st.results.iter().map(|r| SHSimpleIDListFromPath(pc(&wz(r))) as *const ITEMIDLIST).filter(|p| !p.is_null()).collect();
let r = SHCreateShellItemArrayFromIDLists(&pidls);
for p in &pidls {
CoTaskMemFree(Some(*p as *const _));
}
r
}
})
}
fn GetSelectedItems(&self) -> Result<IShellItemArray> {
crate::guarda_com(|| {
if self.st.borrow().chosen {
return self.GetResults();
}
match &self.inner_open {
Some(o) => unsafe { o.GetSelectedItems() },
None => Err(E_UNEXPECTED.into()),
}
})
}
}
impl IFileSaveDialog_Impl for WrapSave_Impl {
fn SetSaveAsItem(&self, s: Option<&IShellItem>) -> Result<()> {
crate::guarda_com(|| {
let p = path_of(s);
if !p.is_empty() {
let mut st = self.st.borrow_mut();
st.file_name = file_name(&p).to_string();
if let Some(i) = p.rfind('\\') {
st.folder = p[..i].to_string();
}
}
match &self.inner_save {
Some(v) => unsafe { v.SetSaveAsItem(s) },
None => Err(E_UNEXPECTED.into()),
}
})
}
fn SetProperties(&self, s: Option<&IPropertyStore>) -> Result<()> {
crate::guarda_com(|| {
match &self.inner_save {
Some(v) => unsafe { v.SetProperties(s) },
None => Err(E_UNEXPECTED.into()),
}
})
}
fn SetCollectedProperties(&self, l: Option<&IPropertyDescriptionList>, b: BOOL) -> Result<()> {
crate::guarda_com(|| {
match &self.inner_save {
Some(v) => unsafe { v.SetCollectedProperties(l, b) },
None => Err(E_UNEXPECTED.into()),
}
})
}
fn GetProperties(&self) -> Result<IPropertyStore> {
crate::guarda_com(|| {
match &self.inner_save {
Some(v) => unsafe { v.GetProperties() },
None => Err(E_UNEXPECTED.into()),
}
})
}
fn ApplyProperties(&self, i: Option<&IShellItem>, s: Option<&IPropertyStore>, h: HWND, k: Option<&IFileOperationProgressSink>) -> Result<()> {
crate::guarda_com(|| {
match &self.inner_save {
Some(v) => unsafe { v.ApplyProperties(i, s, h, k) },
None => Err(E_UNEXPECTED.into()),
}
})
}
}
// ---- o QueryInterface que repassa ao original (o do C++: `return inner->QueryInterface(iid, o)` no fim)
type FnQi = unsafe extern "system" fn(*mut core::ffi::c_void, *const GUID, *mut *mut core::ffi::c_void) -> HRESULT;
type FnRel = unsafe extern "system" fn(*mut core::ffi::c_void) -> u32;
struct Gancho {
inner: IUnknown,
/// o original tem IFileDialog2? (senão o embrulho também não diz ter, como no C++)
d2: bool,
qi: Vec<FnQi>,
rel: Vec<FnRel>,
/// cópia de cada vtable: [gancho, índice, entradas...]; o objeto aponta para as entradas
copias: Vec<Box<[usize]>>,
}
unsafe fn gancho_de(this: *mut core::ffi::c_void) -> (*mut Gancho, usize) {
let vt = *(this as *const *const usize);
(*vt.sub(2) as *mut Gancho, *vt.sub(1))
}
unsafe extern "system" fn qi_thunk(this: *mut core::ffi::c_void, iid: *const GUID, o: *mut *mut core::ffi::c_void) -> HRESULT {
let (g, i) = gancho_de(this);
let g = &*g;
if !iid.is_null() && *iid == IFileDialog2::IID && !g.d2 {
if !o.is_null() {
*o = std::ptr::null_mut();
}
return E_NOINTERFACE;
}
let hr = (g.qi[i])(this, iid, o);
if hr != E_NOINTERFACE {
return hr;
}
g.inner.query(iid, o) // controles extras, IObjectWithSite... ficam com o original
}
unsafe extern "system" fn rel_thunk(this: *mut core::ffi::c_void) -> u32 {
let (g, i) = gancho_de(this);
let f = (&*g).rel[i];
let r = f(this);
if r == 0 {
drop(Box::from_raw(g)); // o objeto se foi: as cópias das vtables e a referência ao original vão junto
}
r
}
/// troca o QueryInterface (e o Release, para soltar as cópias) de todas as vtables do objeto
fn gancho_qi(unk: &IUnknown, inner: &IUnknown) {
unsafe {
let w = std::mem::size_of::<usize>();
// (ponteiro da interface no objeto, entradas da vtable)
let mut slots: Vec<(*mut core::ffi::c_void, usize)> = vec![(unk.as_raw(), 3)];
macro_rules! slot {
($i:ty, $v:ty) => {
if let Ok(x) = unk.cast::<$i>() {
let p = x.as_raw();
if !slots.iter().any(|s| s.0 == p) {
slots.push((p, std::mem::size_of::<$v>() / w));
}
}
};
}
slot!(IFileOpenDialog, IFileOpenDialog_Vtbl);
slot!(IFileSaveDialog, IFileSaveDialog_Vtbl);
slot!(IFileDialog2, IFileDialog2_Vtbl);
slot!(IFileDialogCustomize, IFileDialogCustomize_Vtbl);
slot!(IObjectWithSite, comum::windows::Win32::System::Ole::IObjectWithSite_Vtbl);
let g = Box::into_raw(Box::new(Gancho { inner: inner.clone(), d2: inner.cast::<IFileDialog2>().is_ok(), qi: vec![], rel: vec![], copias: vec![] }));
for (i, &(p, n)) in slots.iter().enumerate() {
let vt = *(p as *const *const usize);
let mut c = vec![0usize; n + 2].into_boxed_slice();
c[0] = g as usize;
c[1] = i;
std::ptr::copy_nonoverlapping(vt, c.as_mut_ptr().add(2), n);
(&mut *g).qi.push(std::mem::transmute::<usize, FnQi>(c[2]));
(&mut *g).rel.push(std::mem::transmute::<usize, FnRel>(c[4]));
c[2] = qi_thunk as *const () as usize;
c[4] = rel_thunk as *const () as usize;
*(p as *mut *const usize) = c.as_ptr().add(2);
(&mut *g).copias.push(c);
}
}
}
#[implement(IClassFactory)]
struct Factory {
clsid: GUID,
}
impl IClassFactory_Impl for Factory_Impl {
fn CreateInstance(&self, outer: Option<&IUnknown>, iid: *const GUID, o: *mut *mut core::ffi::c_void) -> Result<()> {
crate::guarda_com(|| {
unsafe {
*o = std::ptr::null_mut();
if outer.is_some() {
return Err(CLASS_E_NOAGGREGATION.into());
}
let real = real_factory(&self.clsid)?;
let inner: IFileDialog = real.CreateInstance(None)?;
let inner_unk: IUnknown = inner.cast()?;
let st = RefCell::new(Estado { type_index: 1, ..Default::default() });
let unk: IUnknown = if self.clsid == CLSID_SAVE {
WrapSave { save: true, inner_open: None, inner_save: inner.cast().ok(), inner, st }.into()
} else {
WrapOpen { save: false, inner_open: inner.cast().ok(), inner_save: None, inner, st }.into()
};
gancho_qi(&unk, &inner_unk);
unk.query(iid, o).ok()
}
})
}
fn LockServer(&self, _: BOOL) -> Result<()> {
crate::guarda_com(|| {
Ok(())
})
}
}
#[no_mangle]
pub unsafe extern "system" fn DllGetClassObject(clsid: *const GUID, iid: *const GUID, o: *mut *mut core::ffi::c_void) -> HRESULT {
crate::guarda(E_UNEXPECTED, || {
let clsid = *clsid;
if clsid != CLSID_OPEN && clsid != CLSID_SAVE {
return CLASS_E_CLASSNOTAVAILABLE;
}
if !allowed() {
// fora da lista: o original, direto
return match real_factory(&clsid) {
Ok(real) => real.query(iid, o),
Err(e) => e.code(),
};
}
let f: IUnknown = Factory { clsid }.into();
f.query(iid, o)
})
}
#[no_mangle]
pub extern "system" fn DllCanUnloadNow() -> HRESULT {
crate::guarda(E_UNEXPECTED, || {
S_FALSE // fica carregada: mais seguro
})
}
#[no_mangle]
pub extern "system" fn DllMain(h: HINSTANCE, why: u32, _: *mut core::ffi::c_void) -> BOOL {
crate::guarda(TRUE, || {
if why == 1 {
// DLL_PROCESS_ATTACH
SELF.store(h.0 as isize, Ordering::SeqCst);
unsafe {
let _ = DisableThreadLibraryCalls(HMODULE(h.0));
}
}
TRUE
})
}
#[allow(dead_code)]
fn _usa(x: &[u16]) -> String {
from_w(x)
}