A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! atualizacao.cpp: aviso de atualização (ajuste avisar_atualizacao, ligado por padrão): 90 s depois de entrar e a cada
//! 6 horas o Shell roda tools\atualizar-github.ps1 -Verificar numa thread; versão nova no GitHub = notificação
//! "Atualizações Disponíveis" uma vez por versão (atualizacao_avisada=). O remetente é o AUMID WacOS.Atualizacao
//! (HKCU\Software\Classes\AppUserModelId). Nunca roda no modo foto.
use std::sync::atomic::{AtomicIsize, AtomicU32, Ordering};
use std::sync::Mutex;
use comum::windows::core::*;
use comum::windows::Data::Xml::Dom::XmlDocument;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::System::Registry::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::windows::UI::Notifications::{ToastNotification, ToastNotificationManager};
use comum::*;
use crate::{log, shell};
const AUMID: &str = "WacOS.Atualizacao";
static TO: AtomicIsize = AtomicIsize::new(0);
static MSG: AtomicU32 = AtomicU32::new(0);
/// (atual, novo, mudanças)
static ACHADO: Mutex<(String, String, usize)> = Mutex::new((String::new(), String::new(), 0));
/// a instalação que o GitHub atualiza: a edição em Rust não tem tools\, quem confere e atualiza é a instalação normal
/// (Programs\WacOS), que traz as duas edições na mesma release (issue #238)
fn root() -> String {
let d = shell::dir();
let r = d.rsplit_once('\\').map(|x| x.0.to_string()).unwrap_or(d);
if std::path::Path::new(&format!("{r}\\tools\\atualizar-github.ps1")).exists() {
return r;
}
match std::env::var("LOCALAPPDATA") {
Ok(l) if std::path::Path::new(&format!("{l}\\Programs\\WacOS\\tools\\atualizar-github.ps1")).exists() => format!("{l}\\Programs\\WacOS"),
_ => r,
}
}
/// a edição em Rust (sem tools\ ao lado): o instalar.ps1 do pacote não sabe trocar de edição; o WacOSSetup --atualizar sabe
fn sou_rust() -> bool {
let d = shell::dir();
let r = d.rsplit_once('\\').map(|x| x.0).unwrap_or("");
!std::path::Path::new(&format!("{r}\\tools\\atualizar-github.ps1")).exists()
}
/// uma conferência (≈ 2 a 10 s, rede): atual= e novo= do script
fn checar() {
if shell::setting("avisar_atualizacao", "1") == "0" && shell::setting("atualizacao_automatica", "0") == "0" {
return; // aviso e instalação automática desligados: nem confere
}
let script = format!("{}\\tools\\atualizar-github.ps1", root());
if !std::path::Path::new(&script).exists() {
return;
}
let saida = std::env::temp_dir().join(format!("wau{}.txt", std::process::id()));
use std::os::windows::process::CommandExt;
let Ok(mut c) = std::process::Command::new("powershell.exe")
.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", &script, "-Verificar", "-Saida", &saida.to_string_lossy(), "-Bin", &format!("{}\\bin", root())])
.creation_flags(0x0800_0000 | 0x0000_4000)
.spawn()
else {
return;
};
let t0 = std::time::Instant::now();
loop {
if !matches!(c.try_wait(), Ok(None)) {
break;
}
if t0.elapsed().as_secs() > 60 {
// rede parada: sem encerrar, o script ficava rodando e um a mais a cada 6 h
let _ = c.kill();
log!("atualização: a conferência passou de 60 s e foi encerrada");
break;
}
std::thread::sleep(std::time::Duration::from_millis(250));
}
let txt = std::fs::read(&saida).map(|b| String::from_utf8_lossy(&b).into_owned()).unwrap_or_default();
let _ = std::fs::remove_file(&saida);
let (mut atual, mut novo, mut erro, mut n) = (String::new(), String::new(), String::new(), 0);
for l in txt.lines() {
let l = l.trim_start_matches('\u{FEFF}');
if let Some(v) = l.strip_prefix("atual=") {
atual = v.into();
} else if let Some(v) = l.strip_prefix("novo=") {
novo = v.into();
} else if let Some(v) = l.strip_prefix("erro=") {
erro = v.into();
} else if l.starts_with("commit=") {
n += 1;
}
}
if !erro.is_empty() {
log!("atualização: não deu para conferir ({erro})");
return;
}
if novo.is_empty() || novo == atual {
return;
}
*ACHADO.lock().unwrap() = (atual, novo, n);
unsafe {
let _ = PostMessageW(HWND(TO.load(Ordering::Relaxed) as *mut _), MSG.load(Ordering::Relaxed), WPARAM(0), LPARAM(0));
}
}
fn registrar() {
let key = format!("Software\\Classes\\AppUserModelId\\{AUMID}");
unsafe {
let mut k = HKEY::default();
let mut disp = REG_CREATE_KEY_DISPOSITION(0);
if RegCreateKeyExW(HKEY_CURRENT_USER, pc(&wz(&key)), 0, PCWSTR::null(), REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, None, &mut k, Some(&mut disp)).is_err() {
return;
}
let set = |name: &str, v: &str| {
let w_ = wz(v);
let _ = RegSetValueExW(k, pc(&wz(name)), 0, REG_SZ, Some(std::slice::from_raw_parts(w_.as_ptr() as *const u8, w_.len() * 2)));
};
set("DisplayName", &tr("Ajustes do Sistema"));
let icon = format!("{}\\icones\\tahoe\\Settings.png", root());
if std::path::Path::new(&icon).exists() {
set("IconUri", &icon);
}
let _ = RegCloseKey(k);
if disp == REG_CREATED_NEW_KEY {
log!("registro: criada HKCU\\{key} (remetente do aviso de atualização)");
}
}
}
fn xml(t: &str) -> String {
t.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
}
fn toast(launch: &str, title: &str, body: &str) -> Result<()> {
let doc = XmlDocument::new()?;
doc.LoadXml(&HSTRING::from(format!("<toast launch=\"{launch}\"><visual><binding template=\"ToastGeneric\"><text>{}</text><text>{}</text></binding></visual></toast>", xml(title), xml(body))))?;
ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(AUMID))?.Show(&ToastNotification::CreateToastNotification(&doc)?)
}
pub fn start(msg_wnd: HWND) {
if shell::foto() || !comum::edicao::ATUALIZA_PELO_GITHUB {
// edição em Rust: as releases do GitHub são do C++ (trocariam esta instalação por ele)
return;
}
TO.store(msg_wnd.0 as isize, Ordering::Relaxed);
MSG.store(unsafe { RegisterWindowMessageW(w!("ShellAtualizacaoDisponivel")) }, Ordering::Relaxed);
std::thread::spawn(|| {
std::thread::sleep(std::time::Duration::from_secs(90)); // depois de entrar: não disputa a rede com o login
loop {
checar();
std::thread::sleep(std::time::Duration::from_secs(6 * 3600));
}
});
}
/// outros avisos do próprio WacOS pelo mesmo remetente; clicar abre o Ajustes
pub fn avisar(title: &str, body: &str) {
if shell::foto() {
return;
}
registrar();
match toast("aviso", title, body) {
Ok(()) => log!("aviso do WacOS: {title}"),
Err(e) => log!("aviso do WacOS: notificação recusada ({e})"),
}
}
pub fn handle(m: u32) -> bool {
let msg = MSG.load(Ordering::Relaxed);
if msg == 0 || m != msg {
return false;
}
let (atual, novo, n) = ACHADO.lock().unwrap().clone();
if novo.is_empty() {
return true;
}
if shell::setting("atualizacao_automatica", "0") != "0" {
// baixar e instalar sozinho (issue #102), com um aviso antes de começar; uma tentativa por versão
if shell::setting("atualizacao_avisada", "") == novo {
return true;
}
shell::set_setting("atualizacao_avisada", &novo);
log!("atualização automática: instalando {novo} (instalada {atual})");
registrar();
let corpo = format!("WacOS {novo} {}", tr("está sendo instalada automaticamente. O WacOS fecha e abre de novo para aplicar."));
let _ = toast("atualizacao", &tr("Atualizações Disponíveis"), &corpo);
std::thread::spawn(|| {
// o mesmo script do "Atualizar Agora", sem janela: baixa o pacote do GitHub, confere o SHA-256 e roda
// instalar.ps1 -Atualizar -Silencioso (só troca os programas; os ajustes ficam como estavam). O WacOS fecha
// e abre de novo no fim; se a rede falhar, a página do Ajustes continua instalando na mão.
let script = format!("{}\\tools\\atualizar-github.ps1", root());
if !std::path::Path::new(&script).exists() {
return;
}
if sou_rust() {
// com a janela do instalador: ele volta para o C++, atualiza as duas edições e troca de volta para o Rust
let _ = std::process::Command::new(format!("{}\\WacOSSetup.exe", root())).arg("--atualizar").spawn();
return;
}
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
const BELOW_NORMAL_PRIORITY_CLASS: u32 = 0x0000_4000;
if let Ok(mut c) = std::process::Command::new("powershell.exe")
.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", &script])
.creation_flags(CREATE_NO_WINDOW | BELOW_NORMAL_PRIORITY_CLASS)
.spawn()
{
// download grande em rede lenta: até 20 min
let ate = std::time::Instant::now() + std::time::Duration::from_secs(20 * 60);
while std::time::Instant::now() < ate {
if !matches!(c.try_wait(), Ok(None)) {
break;
}
std::thread::sleep(std::time::Duration::from_secs(2));
}
}
});
return true;
}
if shell::setting("avisar_atualizacao", "1") == "0" || shell::setting("atualizacao_avisada", "") == novo {
return true; // uma vez por versão
}
shell::set_setting("atualizacao_avisada", &novo);
log!("atualização: {novo} disponível (instalada {atual}, {n} mudanças)");
registrar();
let corpo = if n > 0 {
format!("WacOS {novo} {} ({n}{}).", tr("está pronto para instalar"), if n == 1 { tr(" mudança") } else { tr(" mudanças") })
} else {
format!("WacOS {novo} {}.", tr("está pronto para instalar"))
};
if let Err(e) = toast("atualizacao", &tr("Atualizações Disponíveis"), &corpo) {
log!("atualização: notificação recusada ({e})");
}
true
}