A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! WacOSTroca.exe: o BETA-TEST (Ajustes > Experimental). Troca o Shell ativo entre o WacOS do C++
//! (%LOCALAPPDATA%\Programs\WacOS) e a edição em Rust (Programs\WacOS-Rust), com volta segura. Vai nos dois pacotes.
//!
//! WacOSTroca --para-rust o login passa a abrir a edição em Rust (por este vigia), o C++ fecha pelo jeito dele
//! (--sair) e o Rust abre; a DialogoMac e o Winlogon (se apontavam para o WacOS) vão junto
//! WacOSTroca --para-cpp o caminho de volta (sempre seguro: fecha só o que é da pasta do Rust)
//! WacOSTroca --iniciar o que o login roda no modo beta: abre o Shell em Rust e fica vigiando. Sem o aviso de
//! "subiu bem" (%APPDATA%\Shell\beta-ok.txt, gravado pelo Shell) em 90 s, ou com 2 quedas em
//! 10 min, volta sozinho para o C++
//! WacOSTroca --instalar baixa a edição em Rust (asset WacOS-Rust.zip da release mais nova do GitHub) e instala em
//! Programs\WacOS-Rust (só com ela fechada); pode vir junto: --instalar --para-rust
//!
//! Estado em %APPDATA%\Shell\beta.txt (edicao=rust|cpp, a ação antiga da tarefa "WacOS"), registro em beta.log.
//! Regras (iguais às do kit de teste rust-teste\teste-pc): nunca abre nem fecha o explorer.exe; só fecha processos
//! da pasta da edição que sai; a troca da tarefa e do registro é feita antes de fechar qualquer coisa e desfeita se o
//! C++ não sair.
#![windows_subsystem = "windows"]
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::System::Threading::*;
const SEM_JANELA: u32 = 0x0800_0000; // CREATE_NO_WINDOW
const PRAZO_SUBIU: Duration = Duration::from_secs(90);
const JANELA_QUEDAS: Duration = Duration::from_secs(600);
fn local() -> String {
std::env::var("LOCALAPPDATA").unwrap_or_default()
}
fn pasta_cpp() -> String {
format!("{}\\Programs\\WacOS", local())
}
fn pasta_rust() -> String {
format!("{}\\Programs\\{}", local(), comum::edicao::PASTA)
}
fn dados() -> PathBuf {
PathBuf::from(std::env::var("APPDATA").unwrap_or_default()).join("Shell")
}
fn log(m: &str) {
use std::io::Write;
let _ = std::fs::create_dir_all(dados());
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dados().join("beta.log")) {
let t = unsafe { comum::windows::Win32::System::SystemInformation::GetLocalTime() };
let _ = writeln!(f, "{:04}-{:02}-{:02} {:02}:{:02}:{:02} {m}", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond);
}
}
fn estado() -> Vec<(String, String)> {
let t = std::fs::read_to_string(dados().join("beta.txt")).unwrap_or_default();
t.trim_start_matches('\u{feff}').lines().filter_map(|l| l.split_once('=').map(|(k, v)| (k.trim().to_string(), v.to_string()))).collect()
}
fn estado_de(k: &str) -> String {
estado().into_iter().find(|(a, _)| a == k).map(|(_, v)| v).unwrap_or_default()
}
fn grava_estado(k: &str, v: &str) {
let mut e = estado();
match e.iter_mut().find(|(a, _)| a == k) {
Some(x) => x.1 = v.to_string(),
None => e.push((k.to_string(), v.to_string())),
}
let s: String = e.iter().map(|(a, b)| format!("{a}={b}\n")).collect();
let _ = std::fs::write(dados().join("beta.txt"), s);
}
/// roda um trecho de PowerShell (codificado: nada de aspas nem de BOM) e devolve a saída
fn ps(script: &str) -> String {
let cab = format!(
"$ErrorActionPreference='SilentlyContinue'; $Cpp='{}'; $Rust='{}'; $Dados='{}'; $Eu={};\n",
pasta_cpp().replace('\'', "''"),
pasta_rust().replace('\'', "''"),
dados().to_string_lossy().replace('\'', "''"),
std::process::id()
);
let tudo = cab + FUNCOES + script;
let b: Vec<u8> = tudo.encode_utf16().flat_map(|u| u.to_le_bytes()).collect();
let enc = base64(&b);
match std::process::Command::new("powershell.exe").args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", &enc]).creation_flags(SEM_JANELA).output() {
Ok(o) => String::from_utf8_lossy(&o.stdout).trim().to_string(),
Err(e) => {
log(&format!("powershell não abriu: {e}"));
String::new()
}
}
}
fn base64(b: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut s = String::with_capacity(b.len() * 4 / 3 + 4);
for c in b.chunks(3) {
let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
for i in 0..4 {
if i <= c.len() {
s.push(T[(n >> (18 - 6 * i) & 63) as usize] as char);
} else {
s.push('=');
}
}
}
s
}
/// funções comuns dos trechos de PowerShell
const FUNCOES: &str = r#"
function Log($m) { Add-Content -Encoding utf8 (Join-Path $Dados 'beta.log') ((Get-Date -Format 'yyyy-MM-dd HH:mm:ss') + ' ' + $m) }
# processos de uma edição: o exe na pasta dela, ou o rundll32 com a DLL de 32 bits de lá (menos este WacOSTroca)
function Procs($pasta) { @(Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -ne $Eu -and ("$($_.ExecutablePath)" -like "$pasta\*" -or ($_.Name -eq 'rundll32.exe' -and "$($_.CommandLine)" -like "*$pasta\*")) }) }
function ShellDe($pasta) { @(Procs $pasta | Where-Object { $_.Name -eq 'WacOSShell.exe' -and "$($_.CommandLine)" -notmatch '--mesa-vigia|--foto|--sair' }) }
# a DialogoMac (64 e 32 bits) e o Winlogon Shell: só se apontam para a pasta $de
function Reaponta($de, $para) {
foreach ($raiz in 'HKCU:\Software\Classes\CLSID', 'HKCU:\Software\Classes\WOW6432Node\CLSID') {
foreach ($c in '{DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7}', '{C0B4E2F3-BA21-4773-8DBA-335EC946EB8B}') {
$k = "$raiz\$c\InprocServer32"; $v = (Get-ItemProperty $k).'(default)'
if ($v -and $v -like "$de\bin\*") {
$n = $para + $v.Substring($de.Length)
if (Test-Path $n) { Set-ItemProperty $k -Name '(default)' -Value $n; Log "DialogoMac: $v -> $n" } else { Log "DialogoMac: $n não existe; fica $v" }
}
}
}
$w = 'HKCU:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon'; $s = (Get-ItemProperty $w -Name Shell).Shell
if ($s -and $s -like "*$de\bin\*") { $i = $s.ToLower().IndexOf($de.ToLower()); $n = $s.Substring(0, $i) + $para + $s.Substring($i + $de.Length); Set-ItemProperty $w -Name Shell -Value $n; Log "Winlogon Shell: $s -> $n" }
}
"#;
fn troca_para_rust() -> i32 {
let rust_exe = format!("{}\\bin\\WacOSShell.exe", pasta_rust());
if !Path::new(&rust_exe).exists() {
log("para-rust: a edição em Rust não está instalada (WacOSTroca --instalar)");
return 2;
}
log("=== para-rust: começo");
// cópia dos ajustes (os arquivos pequenos; o índice e as miniaturas ficam): a volta não depende dela, é só segurança
let _ = ps(r#"$d = Join-Path $Dados 'antes-do-beta'; New-Item -ItemType Directory -Force $d | Out-Null
Get-ChildItem $Dados -File | Where-Object { $_.Length -lt 4MB -and $_.Name -notlike 'indice*' -and $_.Name -notlike 'beta*' } | Copy-Item -Destination $d -Force"#);
// 1. o login: a tarefa "WacOS" passa a abrir o vigia do Rust (a ação antiga fica guardada no beta.txt)
let antes = ps(r#"$t = Get-ScheduledTask -TaskName 'WacOS'
if (-not $t) { 'sem-tarefa'; return }
$a = $t.Actions[0]; "$($a.Execute)|$($a.Arguments)"
Set-ScheduledTask -TaskName 'WacOS' -Action (New-ScheduledTaskAction -Execute "$Rust\bin\WacOSTroca.exe" -Argument '--iniciar') | Out-Null"#);
if !antes.is_empty() && antes != "sem-tarefa" && !antes.to_lowercase().contains("wacostroca") {
grava_estado("tarefa_antes", &antes);
}
let _ = ps("Reaponta $Cpp $Rust");
grava_estado("edicao", "rust");
let _ = std::fs::remove_file(dados().join("beta-ok.txt"));
// 2. o C++ fecha pelo jeito dele; se não sair em 20 s, tudo volta como estava
// espera pelos números dos processos (não pela lista: na primeira troca ao vivo a lista não achou o Shell que ainda
// fechava e ele foi encerrado à força como "ajudante")
let saiu = ps(r#"$s = @(Get-CimInstance Win32_Process -Filter "Name='WacOSShell.exe'" | Where-Object { "$($_.ExecutablePath)" -like "$Cpp\*" })
Log ("Shell do C++ antes do --sair: " + (($s | ForEach-Object { "$($_.ProcessId) [$($_.CommandLine)]" }) -join '; '))
if ($s.Count) {
Start-Process "$Cpp\bin\WacOSShell.exe" -ArgumentList '--sair' -WorkingDirectory "$Cpp\bin" -Wait
$ids = @($s | ForEach-Object { [int]$_.ProcessId })
for ($i = 0; $i -lt 40 -and @(Get-Process -Id $ids -ErrorAction SilentlyContinue).Count; $i++) { Start-Sleep -Milliseconds 500 }
if (@(Get-Process -Id $ids -ErrorAction SilentlyContinue).Count) { 'nao'; return }
Log 'WacOS do C++ fechado (--sair)'
}
if (@(ShellDe $Cpp).Count) { 'nao' } else {
foreach ($p in Procs $Cpp) { Stop-Process -Id $p.ProcessId -Force; Log "ajudante do C++ fechado: $($p.Name) $($p.ProcessId)" }
'sim'
}"#);
if saiu != "sim" {
log("para-rust: o C++ não saiu com --sair em 20 s: troca desfeita");
desfaz_login();
grava_estado("edicao", "cpp");
return 3;
}
// 3. o vigia abre o Shell do Rust e cuida dele daqui em diante
abre_vigia();
log("=== para-rust: fim (vigia aberto)");
0
}
/// a tarefa, a DialogoMac e o Winlogon de volta para o C++
fn desfaz_login() {
let antes = estado_de("tarefa_antes");
let (exe, args) = antes.split_once('|').map(|(a, b)| (a.to_string(), b.to_string())).unwrap_or_default();
let exe = if exe.is_empty() || exe.to_lowercase().contains("wacostroca") { format!("{}\\bin\\WacOSShell.exe", pasta_cpp()) } else { exe };
let _ = ps(&format!(
r#"$t = Get-ScheduledTask -TaskName 'WacOS'
if ($t) {{
$e = '{}'; $g = '{}'
$a = if ($g) {{ New-ScheduledTaskAction -Execute $e -Argument $g }} else {{ New-ScheduledTaskAction -Execute $e }}
Set-ScheduledTask -TaskName 'WacOS' -Action $a | Out-Null; Log "tarefa WacOS: $e $g"
}}
Reaponta $Rust $Cpp"#,
exe.replace('\'', "''"),
args.replace('\'', "''")
));
}
fn troca_para_cpp(motivo: &str) -> i32 {
log(&format!("=== para-cpp: começo ({motivo})"));
desfaz_login();
grava_estado("edicao", "cpp");
if !motivo.is_empty() {
grava_estado("ultima_volta", motivo);
}
// fecha só o que é da pasta do Rust (o vigia que chamou fica de fora: $Eu) e abre o C++ se ele não estiver aberto
let r = ps(r#"foreach ($p in Procs $Rust) { Stop-Process -Id $p.ProcessId -Force; Log "fechado: $($p.Name) $($p.ProcessId)" }
Start-Sleep -Milliseconds 800
if (@(ShellDe $Cpp).Count) { 'ja' } elseif (-not (Test-Path "$Cpp\bin\WacOSShell.exe")) { Log "ERRO: $Cpp\bin\WacOSShell.exe não existe"; 'sem-exe' } else {
Start-ScheduledTask -TaskName 'WacOS'
for ($i = 0; $i -lt 16 -and -not @(ShellDe $Cpp).Count; $i++) { Start-Sleep -Milliseconds 500 }
if (-not @(ShellDe $Cpp).Count) { Start-Process "$Cpp\bin\WacOSShell.exe" -WorkingDirectory "$Cpp\bin"; Start-Sleep -Seconds 4 }
if (@(ShellDe $Cpp).Count) { 'aberto' } else { 'falhou' }
}
Log ("Explorador: " + @(Get-Process explorer).Count + " processo(s), não mexido")"#);
log(&format!("=== para-cpp: fim (WacOS do C++: {r})"));
if r.ends_with("falhou") || r.ends_with("sem-exe") {
1
} else {
0
}
}
fn abre_vigia() {
let me = std::env::current_exe().unwrap_or_default();
let vigia = PathBuf::from(pasta_rust()).join("bin").join("WacOSTroca.exe");
let exe = if vigia.exists() { vigia } else { me };
let _ = std::process::Command::new(&exe).arg("--iniciar").current_dir(exe.parent().unwrap_or(Path::new("."))).creation_flags(0x0000_0008).spawn(); // DETACHED_PROCESS
}
/// o pid do Shell em Rust principal que já está rodando (sem a vigia da mesa e sem foto), se houver
fn shell_rust_rodando() -> Option<u32> {
ps("(@(ShellDe $Rust) | Select-Object -First 1).ProcessId").trim().parse::<u32>().ok()
}
fn abre_shell_rust() -> Option<u32> {
let bin = PathBuf::from(pasta_rust()).join("bin");
std::process::Command::new(bin.join("WacOSShell.exe")).current_dir(&bin).spawn().ok().map(|c| c.id())
}
/// espera o processo sair (até `max`); Some(código) se saiu
fn espera(pid: u32, max: Duration) -> Option<u32> {
unsafe {
let h = OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?;
let r = WaitForSingleObject(h, max.as_millis().min(u32::MAX as u128) as u32);
let mut code = 0u32;
let saiu = r == WAIT_OBJECT_0 && GetExitCodeProcess(h, &mut code).is_ok();
let _ = CloseHandle(h);
if saiu {
Some(code)
} else if r == WAIT_TIMEOUT {
None
} else {
Some(1)
}
}
}
fn subiu_desde(t: std::time::SystemTime) -> bool {
std::fs::metadata(dados().join("beta-ok.txt")).and_then(|m| m.modified()).map(|m| m >= t).unwrap_or(false)
}
/// --iniciar: o vigia do modo beta (um por sessão)
fn vigia() -> i32 {
let _mutex = unsafe { comum::windows::Win32::System::Threading::CreateMutexW(None, true, w!("Local\\WacOSTrocaVigia")) };
if unsafe { GetLastError() } == ERROR_ALREADY_EXISTS {
return 0; // já há um vigia
}
if estado_de("edicao") != "rust" {
// o beta foi desligado (ou nunca ligado) mas o login ainda chamou o vigia: o C++ de sempre
log("vigia: beta desligado; abrindo o WacOS do C++");
return troca_para_cpp("");
}
log("vigia: começo");
let mut quedas: Vec<Instant> = Vec::new();
let mut inicio = std::time::SystemTime::now();
let mut confirmado = false;
let mut pid = match shell_rust_rodando() {
Some(p) => p,
None => match abre_shell_rust() {
Some(p) => p,
None => {
log("vigia: o Shell em Rust não abriu");
return troca_para_cpp("o Shell em Rust não abriu");
}
},
};
log(&format!("vigia: Shell em Rust pid {pid}"));
loop {
// espera o aviso de "subiu bem" (só no começo) e o Shell sair
let saida = if confirmado {
espera(pid, Duration::from_secs(3600 * 24 * 365))
} else {
let t0 = Instant::now();
let mut s = None;
while t0.elapsed() < PRAZO_SUBIU {
s = espera(pid, Duration::from_secs(1));
if s.is_some() || subiu_desde(inicio) {
break;
}
}
if s.is_none() {
if subiu_desde(inicio) {
confirmado = true;
log("vigia: o Shell em Rust avisou que subiu bem");
continue;
}
log("vigia: sem o aviso de \"subiu bem\" em 90 s");
return troca_para_cpp("o Shell em Rust não avisou que subiu em 90 s");
}
s
};
let Some(code) = saida else { continue };
if estado_de("edicao") != "rust" {
log("vigia: o beta foi desligado; fim");
return 0;
}
if code == 0 {
// saiu pelo jeito dele: reiniciou (outro Shell em Rust aparece) ou o usuário fechou
std::thread::sleep(Duration::from_secs(5));
match shell_rust_rodando() {
Some(p) => {
log(&format!("vigia: o Shell reiniciou (pid {p})"));
pid = p;
continue;
}
None => {
log("vigia: o Shell em Rust foi fechado; fim");
return 0;
}
}
}
// caiu
quedas.retain(|t| t.elapsed() < JANELA_QUEDAS);
quedas.push(Instant::now());
log(&format!("vigia: o Shell em Rust caiu (código 0x{code:08X}); {} queda(s) em 10 min", quedas.len()));
if quedas.len() >= 2 {
return troca_para_cpp("duas quedas do Shell em Rust em 10 minutos");
}
inicio = std::time::SystemTime::now();
confirmado = false;
match abre_shell_rust() {
Some(p) => pid = p,
None => return troca_para_cpp("o Shell em Rust não reabriu"),
}
}
}
/// --instalar: baixa o WacOS-Rust.zip da release mais nova e copia para Programs\WacOS-Rust (com ela fechada)
fn instalar() -> i32 {
log("=== instalar: começo");
let r = ps(r#"if (@(Procs $Rust).Count) { 'aberta'; return }
$api = 'https://api.github.com/repos/Eternity070628/WacOS/releases/latest'
$tmp = Join-Path $env:TEMP ('wacos-rust-' + [guid]::NewGuid().ToString('N')); New-Item -ItemType Directory -Force $tmp | Out-Null
try {
$j = & curl.exe -sL -H 'User-Agent: WacOS' $api | ConvertFrom-Json
$a = @($j.assets | Where-Object { $_.name -like 'WacOS-Rust*.zip' }) | Select-Object -First 1
if (-not $a) { 'sem-asset'; return }
& curl.exe -sL -o "$tmp\p.zip" $a.browser_download_url
if (-not (Test-Path "$tmp\p.zip") -or (Get-Item "$tmp\p.zip").Length -lt 1MB) { 'download'; return }
New-Item -ItemType Directory -Force "$tmp\x" | Out-Null
& tar.exe -xf "$tmp\p.zip" -C "$tmp\x"
$src = if (Test-Path "$tmp\x\bin\WacOSShell.exe") { "$tmp\x" } else { (Get-ChildItem "$tmp\x" -Directory | Where-Object { Test-Path "$($_.FullName)\bin\WacOSShell.exe" } | Select-Object -First 1).FullName }
if (-not $src) { 'pacote'; return }
robocopy $src $Rust /MIR /R:1 /W:1 /NFL /NDL /NJH /NJS /NP | Out-Null
if (Test-Path "$src\cursor-leopard\Leopard") { robocopy "$src\cursor-leopard\Leopard" "$Rust\cursor\Leopard" /E /R:1 /W:1 /NFL /NDL /NJH /NJS /NP | Out-Null }
Log "instalar: $($a.name) da release $($j.tag_name) em $Rust"
'ok'
} finally { Remove-Item -Recurse -Force $tmp }"#);
log(&format!("=== instalar: {r}"));
if r.ends_with("ok") {
0
} else {
4
}
}
/// --desinstalar: o que é só da edição em Rust (chamado pela desinstalação do C++, depois de --para-cpp): tarefas,
/// ProgIDs e associações WacOSRust, Aplicativos instalados, "Abrir com" que aponta para a pasta dela, atalhos do Menu
/// Iniciar. A pasta Programs\WacOS-Rust fica para quem chamou (este exe pode estar nela).
fn desinstalar() -> i32 {
log("=== desinstalar (edição em Rust): começo");
let r = ps(r#"foreach ($p in Procs $Rust) { Stop-Process -Id $p.ProcessId -Force; Log "fechado: $($p.Name) $($p.ProcessId)" }
foreach ($t in 'WacOS-Rust', 'WacOS-Rust Title Bars', 'WacOS-Rust volta automatica') {
if (Get-ScheduledTask -TaskName $t) { Unregister-ScheduledTask -TaskName $t -Confirm:$false; Log "tarefa apagada: $t" }
}
$cl = 'HKCU:\Software\Classes'
Get-ChildItem $cl | Where-Object { $_.PSChildName -like 'WacOSRust.*' } | ForEach-Object { Remove-Item -Recurse -Force $_.PSPath; Log "apagado: $($_.PSChildName)" }
foreach ($k in 'HKCU:\Software\WacOS-Rust', 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\WacOS-Rust') { if (Test-Path $k) { Remove-Item -Recurse -Force $k; Log "apagado: $k" } }
$ra = 'HKCU:\Software\RegisteredApplications'
foreach ($v in (Get-Item $ra).Property) { if ($v -like 'WacOS (Rust)*') { Remove-ItemProperty $ra -Name $v; Log "apagado: RegisteredApplications\$v" } }
# Applications\<exe> e as extensões com OpenWithProgids WacOSRust.*
Get-ChildItem "$cl\Applications" | Where-Object { $_.PSChildName -like 'WacOS*.exe' } | ForEach-Object {
$c = (Get-ItemProperty "$($_.PSPath)\shell\open\command").'(default)'
if ($c -and $c -like "*$Rust\*") { Remove-Item -Recurse -Force $_.PSPath; Log "apagado: Applications\$($_.PSChildName)" }
}
Get-ChildItem $cl | Where-Object { $_.PSChildName -like '.*' } | ForEach-Object {
$o = "$($_.PSPath)\OpenWithProgids"
if (Test-Path $o) { foreach ($v in (Get-Item $o).Property) { if ($v -like 'WacOSRust.*') { Remove-ItemProperty $o -Name $v } } }
}
# atalhos do Menu Iniciar que abrem a pasta da edição em Rust
$sm = [Environment]::GetFolderPath('Programs'); $sh = New-Object -ComObject WScript.Shell
Get-ChildItem $sm -Recurse -Filter *.lnk | ForEach-Object { if ($sh.CreateShortcut($_.FullName).TargetPath -like "$Rust\*") { Remove-Item $_.FullName -Force; Log "atalho apagado: $($_.Name)" } }
Get-ChildItem $sm -Directory | Where-Object { $_.Name -like 'WacOS (Rust)*' -and -not (Get-ChildItem $_.FullName) } | Remove-Item -Force
'ok'"#);
log(&format!("=== desinstalar: {r}"));
0
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).map(|a| a.to_lowercase()).collect();
let tem = |a: &str| args.iter().any(|x| x == a);
let mut code = 0;
if tem("--instalar") {
code = instalar();
if code != 0 {
std::process::exit(code);
}
}
if tem("--para-rust") {
code = troca_para_rust();
} else if tem("--para-cpp") {
code = troca_para_cpp("pedido do usuário");
} else if tem("--desinstalar") {
code = desinstalar();
} else if tem("--iniciar") {
code = vigia();
}
std::process::exit(code);
}