A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! dialogs.cpp: a janela de Abrir/Salvar do Windows trocada pelo Finder, POR FORA, para os programas que não deixam a
//! DLL entrar (Chrome, Discord, WhatsApp...).
//! 1. O Windows avisa (WinEvent, fora do processo) quando um diálogo aparece; é o de arquivos se tem o campo de nome
//! (controle 1148), o botão OK e a área de itens do Explorador. Todo #32770 novo nasce invisível (alfa 0) até
//! sabermos o que é.
//! 2. Lemos o modo (abrir/salvar/pasta), os tipos (combo 1136), o nome e a pasta atual; a original sai da tela
//! (continua aberta) e o Finder abre em modo escolher (pela reserva escondida, se houver).
//! 3. Escolheu: o caminho vai para o campo de nome da original e ela recebe OK. Cancelou: Cancelar na original.
//! Shift segurado deixa a original. Programas elevados ficam com a original. (O modo nativo, com o Finder embutido no
//! explorer pela MacDialogo.dll, não foi portado: o Rust só roda como Shell próprio.)
#![allow(dead_code)]
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::DataExchange::COPYDATASTRUCT;
use comum::windows::Win32::System::SystemInformation::{GetTickCount, GetTickCount64};
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::UI::Accessibility::*;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;
use crate::{log, shell};
const IDOK_: i32 = 1;
const IDCANCEL_: usize = 2;
fn hk(h: HWND) -> isize {
h.0 as isize
}
fn hw(k: isize) -> HWND {
HWND(k as *mut _)
}
#[derive(Clone, Copy)]
struct Veil {
at: u32,
had_layered: bool,
}
#[derive(Default)]
struct Shared {
/// diálogos sendo atendidos
busy: HashSet<isize>,
/// onde a original estava antes de sair da tela
orig_pos: HashMap<isize, RECT>,
/// o Finder que atende cada um (para fechar se o Shell sair): thread do processo próprio ou a janela da reserva
finder_tid: HashMap<isize, u32>,
finder_wnd: HashMap<isize, isize>,
}
static SHARED: Mutex<Option<Shared>> = Mutex::new(None);
fn shared<R>(f: impl FnOnce(&mut Shared) -> R) -> R {
f(SHARED.lock().unwrap().get_or_insert_with(Shared::default))
}
static STOPPING: AtomicBool = AtomicBool::new(false);
static SELF_PID: AtomicU32 = AtomicU32::new(0);
static LAST: Mutex<(String, u64)> = Mutex::new((String::new(), 0));
/// só na thread da interface
#[derive(Default)]
struct Ui {
hook: HWINEVENTHOOK,
obj_hook: HWINEVENTHOOK,
veiled: HashMap<isize, Veil>,
veil_timer: usize,
recheck: HashMap<isize, u32>,
recheck_timer: usize,
picker: HashMap<u32, bool>,
}
static UI: Global<Option<Ui>> = Global::new(None);
fn ui_() -> &'static mut Ui {
UI.get().get_or_insert_with(Ui::default)
}
thread_local!(static TEXT_MS: std::cell::Cell<u32> = const { std::cell::Cell::new(300) });
fn text(h: HWND) -> String {
let mut b = vec![0u16; 2048];
unsafe {
let _ = SendMessageTimeoutW(h, WM_GETTEXT, WPARAM(b.len()), LPARAM(b.as_mut_ptr() as isize), SMTO_ABORTIFHUNG, TEXT_MS.with(|t| t.get()), None);
}
from_w(&b)
}
/// a original responde a mensagens? (depois de trocar de pasta o Photoshop fica alguns segundos ocupado; issue #15)
fn responde(dlg: HWND, ms: u64) -> bool {
let fim = unsafe { GetTickCount64() } + ms;
loop {
let mut r = 0usize;
if unsafe { SendMessageTimeoutW(dlg, WM_NULL, WPARAM(0), LPARAM(0), SMTO_NORMAL, 250, Some(&mut r)) }.0 != 0 {
return true;
}
if !unsafe { IsWindow(dlg).as_bool() } {
return false;
}
std::thread::sleep(Duration::from_millis(50));
if unsafe { GetTickCount64() } >= fim {
return false;
}
}
}
/// escreve no campo e confere (até 5 vezes, esperando a janela ficar livre entre elas)
fn poe_texto(dlg: HWND, edit: HWND, v: &str) -> bool {
let vw = wz(v);
for _ in 0..5 {
if !unsafe { IsWindow(edit).as_bool() } {
break;
}
responde(dlg, 3000);
unsafe {
let _ = SendMessageTimeoutW(edit, WM_SETTEXT, WPARAM(0), LPARAM(vw.as_ptr() as isize), SMTO_NORMAL, 3000, None);
}
if text(edit) == v {
return true;
}
std::thread::sleep(Duration::from_millis(100));
}
false
}
fn class_of(h: HWND) -> String {
let mut c = [0u16; 64];
let n = unsafe { GetClassNameW(h, &mut c) };
String::from_utf16_lossy(&c[..n.max(0) as usize])
}
unsafe extern "system" fn collect_cb(h: HWND, l: LPARAM) -> BOOL {
(*(l.0 as *mut Vec<HWND>)).push(h);
TRUE
}
fn children(p: HWND) -> Vec<HWND> {
let mut v: Vec<HWND> = Vec::new();
unsafe {
let _ = EnumChildWindows(p, Some(collect_cb), LPARAM(&mut v as *mut _ as isize));
}
v
}
fn dlg_item(dlg: HWND, id: i32) -> HWND {
unsafe { GetDlgItem(dlg, id).unwrap_or_default() }
}
/// controle pelo id em qualquer nível (nas janelas antigas com modelo próprio, ex.: o Ableton, os campos ficam dentro
/// da área do Explorador, não como filhos diretos)
fn item(dlg: HWND, id: i32) -> HWND {
let c = dlg_item(dlg, id);
if !c.0.is_null() {
return c;
}
children(dlg).into_iter().find(|&c| unsafe { GetDlgCtrlID(c) } == id).unwrap_or_default()
}
fn find_ex(p: HWND, cls: PCWSTR) -> HWND {
unsafe { FindWindowExW(p, None, cls, None).unwrap_or_default() }
}
/// as caixas da faixa de baixo das janelas novas montadas pelo programa: dentro de FloatNotifySink e sem número; a do
/// nome tem um Edit dentro, a dos tipos não
fn float_combos(dlg: HWND) -> (HWND, HWND) {
let (mut edit, mut ty) = (HWND::default(), HWND::default());
for c in children(dlg) {
if class_of(c) != "ComboBox" || class_of(unsafe { GetParent(c).unwrap_or_default() }) != "FloatNotifySink" {
continue;
}
let e = find_ex(c, w!("Edit"));
if !e.0.is_null() {
if edit.0.is_null() {
edit = e;
}
} else if ty.0.is_null() {
ty = c;
}
}
(edit, ty)
}
fn type_combo(dlg: HWND) -> HWND {
let c = item(dlg, 1136);
if !c.0.is_null() {
c
} else {
float_combos(dlg).1
}
}
/// o campo de texto de verdade do "Nome do arquivo" (ComboBoxEx32 > ComboBox > Edit, ou só Edit)
fn name_edit(dlg: HWND) -> HWND {
let mut c = item(dlg, 1148);
if c.0.is_null() {
c = item(dlg, 1152); // janela antiga de abrir/salvar
}
if c.0.is_null() {
return float_combos(dlg).0; // janela nova montada pelo programa
}
if class_of(c) == "Edit" {
return c;
}
let cb = find_ex(c, w!("ComboBox"));
if !cb.0.is_null() {
let e = find_ex(cb, w!("Edit"));
if !e.0.is_null() {
return e;
}
}
find_ex(c, w!("Edit"))
}
fn has_child_class(p: HWND, cls: &str) -> bool {
children(p).into_iter().any(|c| class_of(c) == cls)
}
fn is_file_dialog(dlg: HWND) -> bool {
if class_of(dlg) != "#32770" {
return false;
}
let ok = !dlg_item(dlg, IDOK_).0.is_null();
if ok && !name_edit(dlg).0.is_null() && (has_child_class(dlg, "DirectUIHWND") || has_child_class(dlg, "SHELLDLL_DefView")) {
return true;
}
// "Procurar Pasta" (SHBrowseForFolder) com campo de texto: dá para preencher
ok && !dlg_item(dlg, 0x3744).0.is_null() && has_child_class(dlg, "SysTreeView32")
}
fn folder_edit(dlg: HWND) -> HWND {
dlg_item(dlg, 0x3744)
}
/// marca para a barra do Mac (WacOSWindow.dll) esconder o que ela desenha em volta; o reposicionamento sem mudar nada
/// faz ela reavaliar na hora
fn mark(h: HWND, on: bool) {
unsafe {
if on {
let _ = SetPropW(h, w!("ShellDialogoPorFora"), HANDLE(1 as *mut _));
} else {
let _ = RemovePropW(h, w!("ShellDialogoPorFora"));
}
let _ = SetWindowPos(h, None, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_ASYNCWINDOWPOS);
}
}
fn unveil(h: HWND) {
let Some(v) = ui_().veiled.remove(&hk(h)) else { return };
unsafe {
if IsWindow(h).as_bool() {
mark(h, false);
let _ = SetLayeredWindowAttributes(h, COLORREF(0), 255, LWA_ALPHA);
if !v.had_layered {
SetWindowLongPtrW(h, GWL_EXSTYLE, GetWindowLongPtrW(h, GWL_EXSTYLE) & !(WS_EX_LAYERED.0 as isize));
}
}
}
}
fn veil(h: HWND) {
unsafe {
let ex = GetWindowLongPtrW(h, GWL_EXSTYLE);
let had = ex & WS_EX_LAYERED.0 as isize != 0;
if !had && SetWindowLongPtrW(h, GWL_EXSTYLE, ex | WS_EX_LAYERED.0 as isize) == 0 {
return; // programa elevado: deixa
}
if SetLayeredWindowAttributes(h, COLORREF(0), 0, LWA_ALPHA).is_err() {
if !had {
SetWindowLongPtrW(h, GWL_EXSTYLE, ex);
}
return;
}
ui_().veiled.insert(hk(h), Veil { at: GetTickCount(), had_layered: had });
}
mark(h, true);
}
/// segurança: nada fica invisível por engano
unsafe extern "system" fn veil_timer(_: HWND, _: u32, _: usize, _: u32) {
let now = GetTickCount();
let late: Vec<isize> = ui_()
.veiled
.iter()
.filter(|(h, v)| !IsWindow(hw(**h)).as_bool() || (!shared(|s| s.busy.contains(h)) && now.wrapping_sub(v.at) > 700))
.map(|(h, _)| *h)
.collect();
for h in late {
unveil(hw(h));
}
let u = ui_();
if u.veiled.is_empty() && u.veil_timer != 0 {
let _ = KillTimer(None, u.veil_timer);
u.veil_timer = 0;
}
}
/// pastas especiais pelo nome que a barra de endereço mostra ("Área de Trabalho", "Bibliotecas\Documentos"): nome →
/// caminho de todas as pastas conhecidas do Windows que têm caminho, montado uma vez (issue #15)
fn known_folder_by_name(name: &str) -> String {
static MAPA: OnceLock<HashMap<String, String>> = OnceLock::new();
let m = MAPA.get_or_init(|| {
let mut by: HashMap<String, String> = HashMap::new();
unsafe {
let ci = CoInitializeEx(None, COINIT_MULTITHREADED);
if let Ok(km) = CoCreateInstance::<_, IKnownFolderManager>(&KnownFolderManager, None, CLSCTX_INPROC_SERVER) {
let mut ids: *mut GUID = std::ptr::null_mut();
let mut n = 0u32;
if km.GetFolderIds(&mut ids, &mut n).is_ok() && !ids.is_null() {
let perfil = std::env::var("USERPROFILE").unwrap_or_default().to_lowercase();
let do_usuario = |p: &str| !perfil.is_empty() && p.to_lowercase().starts_with(&perfil);
for i in 0..n as usize {
let Ok(kf) = km.GetFolder(&*ids.add(i)) else { continue };
let Ok(pp) = kf.GetPath(0) else { continue };
let path = from_w(pp.as_wide());
CoTaskMemFree(Some(pp.0 as *const _));
if !std::path::Path::new(&path).is_dir() {
continue;
}
// os nomes que a barra pode mostrar: o da pasta conhecida, o traduzido e o nome no disco
let mut nomes = vec![path.rsplit('\\').next().unwrap_or("").to_string()];
let disp = |it: IShellItem| it.GetDisplayName(SIGDN_NORMALDISPLAY).ok().map(|d| {
let s = from_w(d.as_wide());
CoTaskMemFree(Some(d.0 as *const _));
s
});
if let Some(d) = kf.GetShellItem::<IShellItem>(0).ok().and_then(disp) {
nomes.push(d);
}
if let Some(d) = SHCreateItemFromParsingName::<_, _, IShellItem>(pc(&wz(&path)), None).ok().and_then(disp) {
nomes.push(d);
}
for n_ in nomes {
// o mesmo nome em duas (a Mesa do usuário e a pública): fica a do usuário
let e = by.entry(n_.to_lowercase()).or_insert_with(|| path.clone());
if !do_usuario(e) && do_usuario(&path) {
*e = path.clone();
}
}
}
CoTaskMemFree(Some(ids as *const _));
}
}
if ci.is_ok() {
CoUninitialize();
}
}
by
});
m.get(&name.to_lowercase()).cloned().unwrap_or_default()
}
/// pasta onde a original está: a barra de endereço tem "Endereço: C:\..."; `por_nome`: só veio o nome (pasta especial)
fn current_folder(dlg: HWND, por_nome: Option<&mut bool>) -> String {
let mut found = String::new();
let mut name = String::new();
for c in children(dlg) {
if class_of(c) != "ToolbarWindow32" {
continue;
}
let t = text(c);
let Some(i) = t.find(": ") else { continue };
let p = &t[i + 2..];
if std::path::Path::new(p).is_dir() {
found = p.to_string();
break;
}
if name.is_empty() && !p.is_empty() {
name = p.to_string();
}
}
if found.is_empty() && !name.is_empty() {
found = known_folder_by_name(name.rsplit('\\').next().unwrap_or(&name)); // "Bibliotecas\Documentos"
if let Some(b) = por_nome {
*b = true;
}
}
found
}
/// Entra na pasta pela barra de endereço da janela original (a caixa de texto do "Address Band Root", que existe mesmo
/// escondida atrás do caminho em migalhas): texto + Enter, sem o OK. Issue #35 (Illustrator e outros da Adobe): com a
/// pasta no campo do nome + OK, o diálogo deles fechava e salvava "Sem título-1" na pasta de antes. true = a original
/// está na pasta; false = não deu (sem a barra, ou não entrou em 4 s): segue o jeito antigo.
fn entra_pela_barra(dlg: HWND, dir: &str) -> bool {
unsafe extern "system" fn achar(w_: HWND, p: LPARAM) -> BOOL {
if shell::class_name(w_) != "ComboBoxEx32" {
return TRUE;
}
let mut a = GetParent(w_).unwrap_or_default();
while !a.0.is_null() {
if shell::class_name(a) == "Address Band Root" {
*(p.0 as *mut HWND) = w_;
return FALSE;
}
a = GetParent(a).unwrap_or_default();
}
TRUE
}
const CBEM_GETEDITCONTROL: u32 = 0x0400 + 7;
unsafe {
let mut combo = HWND::default();
let _ = EnumChildWindows(dlg, Some(achar), LPARAM(&mut combo as *mut HWND as isize));
if combo.0.is_null() {
return false;
}
let mut r = 0usize;
if SendMessageTimeoutW(combo, CBEM_GETEDITCONTROL, WPARAM(0), LPARAM(0), SMTO_ABORTIFHUNG, 3000, Some(&mut r)).0 == 0 || r == 0 {
return false;
}
let edit = HWND(r as *mut _);
let t = wz(dir);
let _ = SendMessageTimeoutW(edit, WM_SETTEXT, WPARAM(0), LPARAM(t.as_ptr() as isize), SMTO_ABORTIFHUNG, 3000, None);
let _ = SendMessageTimeoutW(edit, WM_KEYDOWN, WPARAM(0x0D), LPARAM(0x001C0001), SMTO_ABORTIFHUNG, 3000, None);
let _ = SendMessageTimeoutW(edit, WM_CHAR, WPARAM('\r' as usize), LPARAM(0x001C0001), SMTO_ABORTIFHUNG, 3000, None);
let _ = SendMessageTimeoutW(edit, WM_KEYUP, WPARAM(0x0D), LPARAM(0xC01C0001u32 as isize), SMTO_ABORTIFHUNG, 3000, None);
let ate = GetTickCount64() + 4000;
while IsWindow(dlg).as_bool() && GetTickCount64() < ate {
std::thread::sleep(Duration::from_millis(40));
if same_folder(¤t_folder(dlg, None), dir) {
return true;
}
}
}
false
}
fn same_folder(a: &str, b: &str) -> bool {
if a.is_empty() || b.is_empty() {
return false;
}
let t = |s: &str| {
let mut x = s.to_string();
while x.len() > 3 && x.ends_with('\\') {
x.pop();
}
x.to_lowercase()
};
t(a) == t(b)
}
#[derive(Clone)]
struct Request {
dlg: isize,
owner: isize,
/// 0 abrir, 1 salvar, 2 pasta
mode: i32,
types: Vec<(String, String)>,
ty: i32,
name: String,
folder: String,
}
fn read(dlg: HWND) -> Request {
let mut r = Request { dlg: hk(dlg), owner: hk(unsafe { GetWindow(dlg, GW_OWNER).unwrap_or_default() }), mode: 0, types: Vec::new(), ty: 0, name: String::new(), folder: String::new() };
let ok = text(dlg_item(dlg, IDOK_)).to_lowercase();
let combo = type_combo(dlg);
// o texto do OK no idioma do Windows (em coreano a janela de Salvar abria o Finder em modo Abrir)
let has = |ws: &[&str]| ws.iter().any(|w_| ok.contains(w_));
if has(&["salv", "save", "저장", "保存", "guard", "enregistr", "speicher", "сохран", "zapisz", "kaydet"]) {
r.mode = 1;
} else if has(&["pasta", "folder", "폴더", "フォルダー", "文件夹", "資料夾", "carpeta", "dossier", "ordner", "cartella", "папк", "klasör"]) || combo.0.is_null() {
r.mode = 2;
}
if !combo.0.is_null() {
// "Imagens (*.png;*.jpg)" → descrição + padrões; com tempo-limite (o combo é do programa que pediu a janela)
let ms = TEXT_MS.with(|t| t.get());
let cb = |m: u32, w_: usize, l: isize| -> isize {
let mut res = 0usize;
if unsafe { SendMessageTimeoutW(combo, m, WPARAM(w_), LPARAM(l), SMTO_ABORTIFHUNG, ms, Some(&mut res)) }.0 != 0 {
res as isize
} else {
-1
}
};
let n = cb(CB_GETCOUNT, 0, 0);
for i in 0..n.clamp(0, 64) as usize {
let len = cb(CB_GETLBTEXTLEN, i, 0);
if !(0..511).contains(&len) {
continue;
}
let mut buf = [0u16; 512];
cb(CB_GETLBTEXT, i, buf.as_mut_ptr() as isize);
let t = from_w(&buf);
let (mut desc, mut spec) = (t.clone(), "*.*".to_string());
if let (Some(o), Some(c)) = (t.rfind('('), t.rfind(')')) {
if c > o {
spec = t[o + 1..c].to_string();
desc = t[..o].trim_end().to_string();
}
}
r.types.push((if desc.is_empty() { t.clone() } else { desc }, spec.replace(',', ";")));
}
r.ty = cb(CB_GETCURSEL, 0, 0).max(0) as i32;
}
// Salvar pela estrutura: a de Abrir sempre tem o campo 1148; a de Salvar não tem (o nome fica num Edit dentro de
// FloatNotifySink). O botão nasce com o texto "Abrir" e o programa troca depois (issue #8)
if r.mode == 0 && item(dlg, 1148).0.is_null() && item(dlg, 1152).0.is_null() && !float_combos(dlg).0 .0.is_null() {
r.mode = 1;
}
let ne = name_edit(dlg);
if ne.0.is_null() && !folder_edit(dlg).0.is_null() {
r.mode = 2;
}
if !ne.0.is_null() {
r.name = text(ne);
}
r.folder = current_folder(dlg, None);
r
}
fn file_name(p: &str) -> &str {
p.rsplit('\\').next().unwrap_or(p)
}
fn dir_of(p: &str) -> String {
let mut d = p.rsplit_once('\\').map(|x| x.0.to_string()).unwrap_or_default();
if d.len() == 2 {
d.push('\\');
}
d
}
fn post_ok(dlg: HWND) {
unsafe {
let _ = PostMessageW(dlg, WM_COMMAND, WPARAM(IDOK_ as usize), LPARAM(dlg_item(dlg, IDOK_).0 as isize));
}
}
fn send_ok(dlg: HWND) {
unsafe {
let _ = SendMessageTimeoutW(dlg, WM_COMMAND, WPARAM(IDOK_ as usize), LPARAM(dlg_item(dlg, IDOK_).0 as isize), SMTO_NORMAL, 10000, None);
}
}
fn finish(r: &Request, paths: &[String], ty: i32) {
let dlg = hw(r.dlg);
unsafe {
if !IsWindow(dlg).as_bool() {
return; // o programa já fechou a janela
}
if paths.is_empty() {
let _ = PostMessageW(dlg, WM_COMMAND, WPARAM(IDCANCEL_), LPARAM(0));
return;
}
}
TEXT_MS.with(|t| t.set(2000));
responde(dlg, 10000);
if r.mode == 1 {
*LAST.lock().unwrap() = (paths[0].clone(), unsafe { GetTickCount64() });
}
let combo = type_combo(dlg);
if !combo.0.is_null() && ty >= 0 && ty != r.ty {
unsafe {
let _ = SendMessageTimeoutW(combo, CB_SETCURSEL, WPARAM(ty as usize), LPARAM(0), SMTO_NORMAL, 3000, None);
let _ = SendMessageTimeoutW(dlg, WM_COMMAND, WPARAM((1136 | (CBN_SELCHANGE << 16)) as usize), LPARAM(combo.0 as isize), SMTO_NORMAL, 3000, None);
}
}
let mut edit = name_edit(dlg);
if edit.0.is_null() {
edit = folder_edit(dlg);
}
let mut value = paths[0].clone();
if paths.len() > 1 {
// vários: entra na pasta e depois lista os nomes entre aspas
poe_texto(dlg, edit, paths[0].rsplit_once('\\').map(|x| x.0).unwrap_or(""));
send_ok(dlg);
value = paths.iter().map(|p| format!("\"{}\" ", file_name(p))).collect();
} else if r.mode != 2 && edit == name_edit(dlg) {
// um só: a original entra antes na pasta escolhida e recebe só o nome (Photoshop, Figma montam o destino com a
// pasta da janela: issue #15). Já "na" pasta só vale com o caminho lido na barra (pelo nome pode ser outra)
let dir = dir_of(&paths[0]);
let mut por_nome = false;
let atual = current_folder(dlg, Some(&mut por_nome));
let mut ja_nela = !por_nome && same_folder(&atual, &dir);
log!(" original em '{atual}'{}; escolhida '{dir}'", if por_nome { " (pelo nome)" } else { "" });
if ja_nela {
value = file_name(&paths[0]).to_string();
}
if !dir.is_empty() && !ja_nela && entra_pela_barra(dlg, &dir) {
log!(" original na pasta escolhida pela barra de endereço");
value = file_name(&paths[0]).to_string();
ja_nela = true;
}
if !dir.is_empty() && !ja_nela {
poe_texto(dlg, edit, &dir);
send_ok(dlg);
let mut entrou = false;
let ate = unsafe { GetTickCount64() } + 10000; // pasta do OneDrive/rede e programa ocupado podem demorar
while unsafe { IsWindow(dlg).as_bool() } && !entrou && unsafe { GetTickCount64() } < ate {
std::thread::sleep(Duration::from_millis(40));
if responde(dlg, 2000) {
entrou = same_folder(¤t_folder(dlg, None), &dir);
}
}
if !unsafe { IsWindow(dlg).as_bool() } {
return;
}
if entrou {
value = file_name(&paths[0]).to_string(); // sem confirmar a pasta, segue com o caminho inteiro
}
log!(" original na pasta escolhida: {} (está em '{}')", if entrou { "sim" } else { "não (vai o caminho inteiro)" }, current_folder(dlg, None));
}
}
// a janela pode refazer o campo do nome ao trocar de pasta: o de antes já não vale
responde(dlg, 10000);
let e2 = name_edit(dlg);
if !e2.0.is_null() && e2 != edit && r.mode != 2 {
log!(" o campo do nome mudou ao trocar de pasta");
edit = e2;
}
// só o nome: confere de novo que a original continua na pasta escolhida; se saiu, vai o caminho inteiro
if r.mode == 1 && paths.len() == 1 && !value.contains('\\') {
let atual = current_folder(dlg, None);
if !same_folder(&atual, &dir_of(&paths[0])) {
log!(" a original saiu da pasta escolhida ('{atual}'): vai o caminho inteiro");
value = paths[0].clone();
}
}
let mut nome_ok = poe_texto(dlg, edit, &value);
if !nome_ok {
// o campo pode ter sido refeito: procura de novo e tenta mais uma vez
responde(dlg, 5000);
let e3 = if r.mode != 2 { name_edit(dlg) } else { HWND::default() };
if !e3.0.is_null() {
edit = e3;
}
nome_ok = poe_texto(dlg, edit, &value);
}
if !nome_ok {
log!(" o campo do nome não ficou com o escolhido ('{}')", text(edit));
}
// o programa pode trocar o nome DEPOIS (o Illustrator põe de volta "Sem título-1": issue #35): o nome tem que ficar
// igual em 3 conferências seguidas (~300 ms) antes do OK
if nome_ok && r.mode != 2 {
let (mut iguais, mut refeitos) = (0, 0);
for _ in 0..25 {
if iguais >= 3 || !unsafe { IsWindow(dlg).as_bool() } {
break;
}
std::thread::sleep(Duration::from_millis(100));
responde(dlg, 2000);
let e4 = name_edit(dlg);
if !e4.0.is_null() && e4 != edit {
edit = e4;
}
if text(edit) == value {
iguais += 1;
continue;
}
iguais = 0;
refeitos += 1;
log!(" o programa trocou o nome para '{}': escrevendo de novo", text(edit));
poe_texto(dlg, edit, &value);
}
if refeitos > 0 {
log!(" nome {} depois de {refeitos} troca(s) do programa", if iguais >= 3 { "firme" } else { "ainda instável" });
}
}
if !unsafe { IsWindow(dlg).as_bool() } {
return;
}
post_ok(dlg);
// a original (fora da tela) pode abrir uma pergunta depois do OK ("já existe, substituir?"): caixas de mensagem viram
// o alerta do Mac; qualquer outra vem para o meio da tela, à frente (Firefox, issue #8)
let mut reenviou = false;
for i in 0..60 {
if !unsafe { IsWindow(dlg).as_bool() } {
break;
}
std::thread::sleep(Duration::from_millis(50));
let pop = unsafe { GetWindow(dlg, GW_ENABLEDPOPUP).unwrap_or_default() };
if pop.0.is_null() || pop == dlg {
// escolher pasta (VS Code "Abrir Pasta", issue #8): já dentro da pasta escolhida, campo vazio + OK escolhe a
// pasta atual; só depois de ela estar MESMO lá (issue #15)
if r.mode == 2 && !reenviou && i >= 4 && responde(dlg, 5000) && (same_folder(¤t_folder(dlg, None), &paths[0]) || i >= 50) {
reenviou = true;
log!(" a original entrou na pasta: confirma a pasta atual ({})", if same_folder(¤t_folder(dlg, None), &paths[0]) { "a escolhida" } else { "não confirmada" });
if !edit.0.is_null() {
poe_texto(dlg, edit, "");
}
post_ok(dlg);
}
continue;
}
if class_of(pop) == "#32770" && shell::setting("alertas_mac", "1") != "0" {
log!(" a original perguntou algo: vai para o alerta do Mac");
break;
}
unsafe {
let mut pr = RECT::default();
let _ = GetWindowRect(pop, &mut pr);
let o = hw(r.owner);
let mon = MonitorFromWindow(if o.0.is_null() { GetForegroundWindow() } else { o }, MONITOR_DEFAULTTOPRIMARY);
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
let _ = GetMonitorInfoW(mon, &mut mi);
let (w_, h) = (pr.right - pr.left, pr.bottom - pr.top);
let _ = SetWindowPos(pop, HWND_TOP, (mi.rcWork.left + mi.rcWork.right - w_) / 2, (mi.rcWork.top + mi.rcWork.bottom - h) / 3, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW);
let _ = SetLayeredWindowAttributes(pop, COLORREF(0), 255, LWA_ALPHA);
let _ = SetForegroundWindow(pop);
}
log!(" aviso da original trazido para a tela");
break;
}
}
/// o programa aceita vários arquivos? A lista de itens da original diz (SelectionPattern)
fn allows_multiple(dlg: HWND) -> bool {
let mut multi = false;
unsafe {
let co = CoInitializeEx(None, COINIT_MULTITHREADED);
if let Ok(uia) = CoCreateInstance::<_, IUIAutomation>(&CUIAutomation, None, CLSCTX_INPROC_SERVER) {
if let Ok(root) = uia.ElementFromHandle(dlg) {
let v = VARIANT::from(UIA_ListControlTypeId.0);
if let Ok(cond) = uia.CreatePropertyCondition(UIA_ControlTypePropertyId, &v) {
if let Ok(arr) = root.FindAll(TreeScope_Descendants, &cond) {
for i in 0..arr.Length().unwrap_or(0) {
let Ok(e) = arr.GetElement(i) else { continue };
if let Ok(sp) = e.GetCurrentPatternAs::<IUIAutomationSelectionPattern>(UIA_SelectionPatternId) {
if sp.CurrentCanSelectMultiple().is_ok_and(|b| b.as_bool()) {
multi = true;
break;
}
}
}
}
}
}
}
if co.is_ok() {
CoUninitialize();
}
}
multi
}
fn ler_resultado(res: &str) -> (Vec<String>, i32) {
let mut paths = Vec::new();
let mut ty = -1;
let bytes = std::fs::read(res).unwrap_or_default();
// o Finder grava em UTF-8 (com ou sem BOM)
let t = String::from_utf8_lossy(bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(&bytes)).into_owned();
for l in t.lines() {
let l = l.trim_end_matches(['\r', '\n']);
if let Some(x) = l.strip_prefix("tipo=") {
ty = x.trim().parse().unwrap_or(-1);
} else if !l.is_empty() {
paths.push(l.to_string());
}
}
(paths, ty)
}
/// 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 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
}
fn serve(r: Request) {
let dlg = hw(r.dlg);
let finder = format!("{}\\{}", shell::dir(), comum::nomes::EXE_FINDER);
let res = format!("{}\\dlg{:x}.tmp", std::env::temp_dir().to_string_lossy().trim_end_matches('\\'), unsafe { GetTickCount64() } ^ (r.dlg as u64));
let _ = std::fs::write(&res, b"");
let mut start = r.folder.clone();
if start.is_empty() {
start = crate::menubar::known_folder(&FOLDERID_Documents);
}
let mut cmd = format!("{} {} --lista --escolher {}", q(&finder), q(&start), ["abrir", "salvar", "pasta"][r.mode.clamp(0, 2) as usize]);
if r.mode == 1 {
cmd += " --sem-confirmar"; // quem confirma a substituição é a original (vira o alerta do Mac)
}
if r.mode == 0 && allows_multiple(dlg) {
cmd += " --multi"; // vários arquivos de uma vez (upload do navegador etc.)
}
if !r.types.is_empty() && r.mode != 2 {
let t: Vec<String> = r.types.iter().map(|(d, sp)| format!("{d}|{sp}")).collect();
cmd += &format!(" --tipos {} --tipo {}", q(&t.join("||")), r.ty);
}
if !r.name.is_empty() {
cmd += &format!(" --nome {}", q(&r.name));
}
cmd += &format!(" --resultado {}", q(&res));
if r.owner != 0 {
cmd += &format!(" --pai {}", r.owner as usize);
}
log!("diálogo por fora: {cmd}");
let (mut paths, mut ty) = (Vec::new(), -1);
// direto para o Finder reserva (já aberto e escondido): a janela aparece na hora
let mut proc_ = HANDLE::default();
let mut tid = 0u32;
let spare = unsafe { FindWindowW(w!("ArquivosJanela"), w!("\u{200B}ArquivosReserva")).unwrap_or_default() };
unsafe {
if !spare.0.is_null() {
let mut rpid = 0u32;
GetWindowThreadProcessId(spare, Some(&mut rpid));
proc_ = OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, rpid).unwrap_or_default();
let _ = AllowSetForegroundWindow(rpid);
let cw = wz(&cmd);
let cd = COPYDATASTRUCT { dwData: 0x4152_5156, cbData: (cw.len() * 2) as u32, lpData: cw.as_ptr() as *mut _ }; // 'ARQV'
if !proc_.is_invalid() {
// reserva ocupada (ainda se preparando): o pedido fica na fila dela; esgotar o tempo não é recusa (antes
// apareciam DUAS janelas de salvar no Ableton)
SetLastError(WIN32_ERROR(0));
let mut ok = 0usize;
let sent = SendMessageTimeoutW(spare, WM_COPYDATA, WPARAM(0), LPARAM(&cd as *const _ as isize), SMTO_ABORTIFHUNG, 3000, Some(&mut ok)).0 != 0;
let tarde = !sent && GetLastError() == ERROR_TIMEOUT && IsWindow(spare).as_bool();
if tarde {
log!(" reserva do Finder demorou; o pedido segue com ela");
} else if !sent || ok == 0 {
let _ = CloseHandle(proc_);
proc_ = HANDLE::default();
}
}
if !proc_.is_invalid() {
log!(" pela reserva do Finder");
}
}
let mut via_spare = !proc_.is_invalid();
if proc_.is_invalid() {
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 CreateProcessW(None, PWSTR(c.as_mut_ptr()), None, None, false, PROCESS_CREATION_FLAGS(0), None, None, &si, &mut pi).is_ok() {
let _ = AllowSetForegroundWindow(pi.dwProcessId);
let _ = CloseHandle(pi.hThread);
proc_ = pi.hProcess;
tid = pi.dwThreadId;
via_spare = false;
}
}
if !proc_.is_invalid() {
shared(|s| {
s.finder_tid.insert(r.dlg, if via_spare { 0 } else { tid });
s.finder_wnd.insert(r.dlg, if via_spare { hk(spare) } else { 0 });
});
let mut voltou = false;
while WaitForSingleObject(proc_, 250) == WAIT_TIMEOUT {
// o programa pôs a original de volta na tela (centralizou ou lembrou a posição): sai de novo; eram duas
// janelas de salvar, a do Windows e o Finder (issue #486)
let mut rr = RECT::default();
if IsWindowVisible(dlg).as_bool() && GetWindowRect(dlg, &mut rr).is_ok() && rr.left > -30000 && !STOPPING.load(Ordering::SeqCst) {
let _ = SetWindowPos(dlg, None, -32000, -32000, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS);
if !voltou {
voltou = true;
log!(" a original voltou para a tela; saiu de novo");
}
}
if !IsWindow(dlg).as_bool() {
// o programa desistiu
if via_spare {
let _ = PostMessageW(spare, WM_CLOSE, WPARAM(0), LPARAM(0));
} else {
let _ = PostThreadMessageW(tid, WM_QUIT, WPARAM(0), LPARAM(0));
}
break;
}
}
let mut code = 1u32;
let _ = GetExitCodeProcess(proc_, &mut code);
let _ = CloseHandle(proc_);
if code == 0 {
(paths, ty) = ler_resultado(&res);
}
} else {
// sem Finder: devolve a janela original para a tela
let _ = SetWindowPos(dlg, None, 100, 100, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
let _ = SetLayeredWindowAttributes(dlg, COLORREF(0), 255, LWA_ALPHA);
}
}
let _ = std::fs::remove_file(&res);
if STOPPING.load(Ordering::SeqCst) {
return; // a original já foi devolvida à tela por stop: fica com o usuário
}
finish(&r, &paths, ty);
log!(" {}", paths.first().map(|s| s.as_str()).unwrap_or("cancelado"));
shared(|s| {
s.busy.remove(&r.dlg);
s.orig_pos.remove(&r.dlg);
s.finder_tid.remove(&r.dlg);
s.finder_wnd.remove(&r.dlg);
});
}
/// janelas montadas pelo próprio programa (ex.: o Ableton) ganham a área do Explorador e o campo do nome um pouco
/// DEPOIS de aparecer: ficam invisíveis e são olhadas de novo a cada 15 ms por até 600 ms
unsafe extern "system" fn recheck_timer(_: HWND, _: u32, _: usize, _: u32) {
let now = GetTickCount();
let u = ui_();
let (mut ready, mut gone) = (Vec::new(), Vec::new());
for (&h, &at) in u.recheck.iter() {
if !IsWindow(hw(h)).as_bool() {
gone.push(h);
} else if is_file_dialog(hw(h)) {
ready.push(h);
} else if now.wrapping_sub(at) > 600 {
gone.push(h);
}
}
for h in gone {
u.recheck.remove(&h);
let hh = hw(h);
if IsWindow(hh).as_bool() {
let mut t = [0u16; 80];
let n = GetWindowTextW(hh, &mut t);
log!("diálogos por fora: \"{}\" não é de arquivos (nome {}, ok {}, área {})", String::from_utf16_lossy(&t[..n.max(0) as usize]), !item(hh, 1148).0.is_null() as i32, !dlg_item(hh, IDOK_).0.is_null() as i32, (has_child_class(hh, "DirectUIHWND") || has_child_class(hh, "SHELLDLL_DefView")) as i32);
unveil(hh);
}
}
for h in ready {
u.recheck.remove(&h);
log!("diálogos por fora: reconhecida na segunda olhada");
on_dialog(HWINEVENTHOOK::default(), EVENT_SYSTEM_DIALOGSTART, hw(h), OBJID_WINDOW.0, CHILDID_SELF as i32, 0, 0);
}
let u = ui_();
if u.recheck.is_empty() && u.recheck_timer != 0 {
let _ = KillTimer(None, u.recheck_timer);
u.recheck_timer = 0;
}
}
/// programas que ficam com a janela de arquivos do Windows
const FICA_ORIGINAL: &[&str] = &["PickerHost.exe", "Illustrator.exe"];
fn shift() -> bool {
unsafe { GetKeyState(VK_SHIFT.0 as i32) as u16 & 0x8000 != 0 }
}
unsafe extern "system" fn on_dialog(_: HWINEVENTHOOK, ev: u32, hwnd: HWND, obj: i32, child: i32, _: u32, _: u32) {
if obj != OBJID_WINDOW.0 || child != CHILDID_SELF as i32 || hwnd.0.is_null() || class_of(hwnd) != "#32770" {
return;
}
let mut pid = 0u32;
GetWindowThreadProcessId(hwnd, Some(&mut pid));
if pid == SELF_PID.load(Ordering::Relaxed) {
return;
}
// seletor dos apps da Loja (PickerHost.exe): a resposta escrita no diálogo não volta para o app; fica o do Windows
let u = ui_();
if u.picker.len() > 512 {
u.picker.clear();
}
let is_picker = *u.picker.entry(pid).or_insert_with(|| {
let Ok(hp) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) else { return false };
let mut p = [0u16; 260];
let mut n = p.len() as u32;
// e o Adobe Illustrator (issue #486): o Salvar Como dele abria as duas, a do Windows e o Finder
let r = QueryFullProcessImageNameW(hp, PROCESS_NAME_WIN32, PWSTR(p.as_mut_ptr()), &mut n).is_ok() && FICA_ORIGINAL.iter().any(|e| file_name(&String::from_utf16_lossy(&p[..n as usize])).eq_ignore_ascii_case(e));
let _ = CloseHandle(hp);
r
});
if is_picker {
return;
}
if ev == EVENT_OBJECT_CREATE {
// nasce invisível até sabermos o que é
if shift() {
return;
}
veil(hwnd);
if u.veil_timer == 0 {
u.veil_timer = SetTimer(None, 0, 120, Some(veil_timer));
}
return;
}
let k = hk(hwnd);
if !is_file_dialog(hwnd) {
// tem os controles do modelo das janelas de arquivos (lista 1120, textos 1091...): ainda montando, olha de novo
let montando = !dlg_item(hwnd, IDOK_).0.is_null() && (!dlg_item(hwnd, 1120).0.is_null() || !dlg_item(hwnd, 1091).0.is_null() || has_child_class(hwnd, "DUIViewWndClassName"));
if montando && !u.recheck.contains_key(&k) && !shift() {
if !u.veiled.contains_key(&k) {
veil(hwnd);
}
if let Some(v) = ui_().veiled.get_mut(&k) {
v.at = GetTickCount(); // o veil_timer não solta antes
}
let u = ui_();
u.recheck.insert(k, GetTickCount());
if u.recheck_timer == 0 {
u.recheck_timer = SetTimer(None, 0, 15, Some(recheck_timer));
}
return;
}
if !ui_().recheck.contains_key(&k) {
unveil(hwnd);
}
return;
}
if shift() {
unveil(hwnd); // escape: a janela original
return;
}
if !shared(|s| s.busy.insert(k)) {
return;
}
let r = read(hwnd);
mark(hwnd, true); // a barra do Mac do programa some com ela
let mut orig = RECT::default();
let _ = GetWindowRect(hwnd, &mut orig);
if orig.left > -30000 {
shared(|s| s.orig_pos.insert(k, orig));
}
// tira a original da tela; se não der (programa elevado), ela fica
if SetWindowPos(hwnd, None, -32000, -32000, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE).is_err() {
shared(|s| s.busy.remove(&k));
unveil(hwnd);
return;
}
std::thread::spawn(move || serve(r));
}
/// o último arquivo salvo por fora (até 20 s depois)
pub fn last_saved() -> String {
let l = LAST.lock().unwrap();
if unsafe { GetTickCount64() } - l.1 < 20000 {
l.0.clone()
} else {
String::new()
}
}
unsafe extern "system" fn aberta_cb(h: HWND, l: LPARAM) -> BOOL {
let mut pid = 0u32;
GetWindowThreadProcessId(h, Some(&mut pid));
if pid != SELF_PID.load(Ordering::Relaxed) && IsWindowVisible(h).as_bool() && is_file_dialog(h) {
(*(l.0 as *mut Vec<HWND>)).push(h);
}
TRUE
}
pub fn start() {
if shell::setting("dialogo_por_fora", "1") != "1" {
return;
}
SELF_PID.store(unsafe { GetCurrentProcessId() }, Ordering::Relaxed);
let u = ui_();
unsafe {
u.hook = SetWinEventHook(EVENT_SYSTEM_DIALOGSTART, EVENT_SYSTEM_DIALOGSTART, None, Some(on_dialog), 0, 0, WINEVENT_OUTOFCONTEXT | shell::sem_proprio());
u.obj_hook = SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_SHOW, None, Some(on_dialog), 0, 0, WINEVENT_OUTOFCONTEXT | shell::sem_proprio());
}
log!("diálogos por fora: {}", if u.hook.is_invalid() { "falhou" } else { "ok" });
// janelas de abrir/salvar que já estavam abertas (abertas enquanto o Shell reiniciava, ou deixadas fora da tela por
// um Shell que caiu no meio): o Finder atende agora
let mut open: Vec<HWND> = Vec::new();
unsafe {
let _ = EnumWindows(Some(aberta_cb), LPARAM(&mut open as *mut _ as isize));
}
for h in open {
let mut r = RECT::default();
unsafe {
let _ = GetWindowRect(h, &mut r);
}
log!("diálogos por fora: janela de arquivos já aberta{}", if r.left <= -30000 { " (estava fora da tela)" } else { "" });
unsafe { on_dialog(HWINEVENTHOOK::default(), EVENT_SYSTEM_DIALOGSTART, h, OBJID_WINDOW.0, CHILDID_SELF as i32, 0, 0) };
}
}
pub fn stop() {
STOPPING.store(true, Ordering::SeqCst);
let u = ui_();
unsafe {
if !u.hook.is_invalid() {
let _ = UnhookWinEvent(u.hook);
}
if !u.obj_hook.is_invalid() {
let _ = UnhookWinEvent(u.obj_hook);
}
}
u.hook = HWINEVENTHOOK::default();
u.obj_hook = HWINEVENTHOOK::default();
let all: Vec<isize> = u.veiled.keys().copied().collect();
for h in all {
unveil(hw(h)); // nada fica invisível quando o Shell sai
}
// as que estavam sendo atendidas voltam para a tela (senão o app parece travado) e o Finder delas fecha
shared(|s| unsafe {
for &h in &s.busy {
let hh = hw(h);
if !IsWindow(hh).as_bool() {
continue;
}
let r = s.orig_pos.get(&h).copied().unwrap_or(RECT { left: 100, top: 100, right: 100, bottom: 100 });
let _ = SetWindowPos(hh, None, r.left, r.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
let _ = SetLayeredWindowAttributes(hh, COLORREF(0), 255, LWA_ALPHA);
if let Some(&t) = s.finder_tid.get(&h).filter(|t| **t != 0) {
let _ = PostThreadMessageW(t, WM_QUIT, WPARAM(0), LPARAM(0));
}
if let Some(&w_) = s.finder_wnd.get(&h).filter(|w_| **w_ != 0) {
let _ = PostMessageW(hw(w_), WM_CLOSE, WPARAM(0), LPARAM(0));
}
}
});
}