Skip to content

armgit / WacOS

Public Imported from GitHub
0

A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.

Rust
7.9 KB
Raw Blame
//! migrar.cpp: troca de nome Sequoia → WacOS (16/11/2026). O que o Windows guardava com o nome velho (o shell do
//! Windows no Winlogon, o Win+E e o .zip do Finder, Música e QuickTime, diálogos de arquivo, a tarefa do login) é
//! corrigido na primeira vez que o WacOSShell abre; cada caminho só muda se o arquivo com o nome novo existir.

use comum::windows::core::{PCWSTR, PWSTR};
use comum::windows::Win32::System::Registry::*;
use comum::*;

use crate::{log, shell};

const NOMES: &[&str] = &[
    "Shell", "Finder", "Settings", "ActivityMonitor", "Terminal", "Calculator", "Notes", "Screenshot", "Preview", "Reminders", "Calendar", "TextEdit", "Clock", "Weather", "Contacts", "Photos", "TimeMachine", "Music", "QuickTime",
    "ForceQuit", "Window32Host", "Window32", "Window",
];
/// troca, sem diferenciar maiúsculas, `de` por `para` em `v`
fn troca_ci(v: &str, de: &str, para: &str) -> String {
    let (lv, ld) = (v.to_lowercase(), de.to_lowercase());
    // to_lowercase preserva os índices nos caminhos ASCII que importam aqui; se não preservar, não mexe
    if lv.len() != v.len() {
        return v.to_string();
    }
    let mut out = String::new();
    let mut i = 0;
    while let Some(k) = lv[i..].find(&ld) {
        out += &v[i..i + k];
        out += para;
        i += k + de.len();
    }
    out + &v[i..]
}
fn novo(v: &str) -> String {
    let mut t = troca_ci(v, "\\Programs\\SequoiaShell\\", "\\Programs\\WacOS\\");
    for n in NOMES {
        for ext in ["exe", "dll"] {
            t = troca_ci(&t, &format!("\\Sequoia{n}.{ext}"), &format!("\\WacOS{n}.{ext}"));
        }
    }
    if t == v {
        return t;
    }
    // o arquivo novo tem que existir: o caminho vai até o .exe/.dll (entre aspas ou não)
    let low = t.to_lowercase();
    let fim = [low.find(".exe"), low.find(".dll")].into_iter().flatten().min();
    let Some(fim) = fim else { return v.to_string() };
    let ini = if t.starts_with('"') { 1 } else { 0 };
    if !std::path::Path::new(&t[ini..fim + 4]).exists() {
        return v.to_string();
    }
    t
}
fn corrige(key: &str, only: Option<&str>, recurse: bool, depth: i32) -> i32 {
    let mut n = 0;
    unsafe {
        let mut h = HKEY::default();
        if RegOpenKeyExW(HKEY_CURRENT_USER, pc(&wz(key)), 0, KEY_READ | KEY_SET_VALUE, &mut h).is_err() {
            return 0;
        }
        for i in 0.. {
            let mut name = [0u16; 256];
            let mut nl = 256u32;
            let mut ty = 0u32;
            let mut cb = 0u32;
            if RegEnumValueW(h, i, PWSTR(name.as_mut_ptr()), &mut nl, None, Some(&mut ty), None, Some(&mut cb)).is_err() {
                break;
            }
            if ty != REG_SZ.0 && ty != REG_EXPAND_SZ.0 {
                continue;
            }
            let nm = String::from_utf16_lossy(&name[..nl as usize]);
            if only.is_some_and(|o| !o.eq_ignore_ascii_case(&nm)) {
                continue;
            }
            let mut buf = vec![0u16; cb as usize / 2 + 2];
            let mut cb2 = cb;
            if RegQueryValueExW(h, PCWSTR(name.as_ptr()), None, None, Some(buf.as_mut_ptr() as *mut u8), Some(&mut cb2)).is_err() {
                continue;
            }
            let v = from_w(&buf);
            let nv = novo(&v);
            if nv == v {
                continue;
            }
            let w_ = wz(&nv);
            let bytes = std::slice::from_raw_parts(w_.as_ptr() as *const u8, w_.len() * 2);
            if RegSetValueExW(h, PCWSTR(name.as_ptr()), 0, REG_VALUE_TYPE(ty), Some(bytes)).is_ok() {
                log!("wacos: registro HKCU\\{key} [{}]: {v} -> {nv}", if nm.is_empty() { "(padrão)" } else { &nm });
                n += 1;
            }
        }
        if recurse && depth < 6 {
            let mut subs = Vec::new();
            for i in 0.. {
                let mut sub = [0u16; 256];
                let mut sl = 256u32;
                if RegEnumKeyExW(h, i, PWSTR(sub.as_mut_ptr()), &mut sl, None, PWSTR::null(), None, None).is_err() {
                    break;
                }
                subs.push(String::from_utf16_lossy(&sub[..sl as usize]));
            }
            for s in subs {
                n += corrige(&format!("{key}\\{s}"), None, true, depth + 1);
            }
        }
        let _ = RegCloseKey(h);
    }
    n
}
/// rodando com o nome velho (SequoiaShell.exe) e o WacOSShell.exe ao lado: abre o novo com os mesmos argumentos e sai
pub fn trocar_pelo_novo() -> bool {
    let Ok(exe) = std::env::current_exe() else { return false };
    if !exe.file_name().is_some_and(|f| f.to_string_lossy().eq_ignore_ascii_case("SequoiaShell.exe")) {
        return false;
    }
    let Some(dir) = exe.parent() else { return false };
    let novo = dir.join("WacOSShell.exe");
    if !novo.exists() {
        return false;
    }
    let mut args: Vec<String> = std::env::args().skip(1).collect();
    if !args.iter().any(|a| a == "--depois-de") {
        args.push("--depois-de".into());
        args.push(std::process::id().to_string());
    }
    std::process::Command::new(novo).args(args).current_dir(dir).spawn().is_ok()
}
pub fn registro() {
    // a edição em Rust não migra o SequoiaShell antigo para o WacOS do C++ (isso é do C++)
    if shell::foto() || comum::edicao::PASTA != "WacOS" {
        return;
    }
    let mut n = corrige("Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", Some("Shell"), false, 0);
    n += corrige("Software\\Microsoft\\Windows\\CurrentVersion\\Run", None, false, 0);
    for k in [
        "Software\\Classes\\CompressedFolder\\shell",
        "Software\\Classes\\CLSID\\{52205fd8-5dfb-447d-801a-d0b52f2e83e1}",
        "Software\\Classes\\CLSID\\{DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7}",
        "Software\\Classes\\CLSID\\{C0B4E2F3-BA21-4773-8DBA-335EC9468EB8}",
        "Software\\Classes\\SequoiaMusic.Audio",
        "Software\\Classes\\SequoiaQuickTime.Video",
        "Software\\Classes\\Applications\\SequoiaMusic.exe",
        "Software\\Classes\\Applications\\SequoiaQuickTime.exe",
        "Software\\SequoiaShell",
    ] {
        n += corrige(k, None, true, 0);
    }
    if n > 0 {
        log!("wacos: {n} caminho(s) do nome velho corrigido(s) no registro");
    }
    // a tarefa que abre o Shell no login: "SequoiaShell" vira "WacOS" (uma vez; em segundo plano)
    if shell::setting("wacos_tarefa", "0") == "1" {
        return;
    }
    shell::set_setting("wacos_tarefa", "1");
    std::thread::spawn(|| {
        let ps = "$t = Get-ScheduledTask -TaskName SequoiaShell -ErrorAction SilentlyContinue; if (-not $t) { exit 2 }; \
                  $x = $t.Actions[0].Execute -replace '\\\\Programs\\\\SequoiaShell\\\\', '\\Programs\\WacOS\\' -replace 'SequoiaShell\\.exe$', 'WacOSShell.exe'; \
                  if (-not (Test-Path $x)) { exit 3 }; \
                  $a = if ($t.Actions[0].Arguments) { New-ScheduledTaskAction -Execute $x -Argument $t.Actions[0].Arguments } else { New-ScheduledTaskAction -Execute $x }; \
                  Register-ScheduledTask -TaskName WacOS -Action $a -Trigger $t.Triggers -Settings $t.Settings -Principal $t.Principal -Force | Out-Null; \
                  Unregister-ScheduledTask -TaskName SequoiaShell -Confirm:$false; exit 0";
        use std::os::windows::process::CommandExt;
        let r = std::process::Command::new("powershell.exe").args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps]).creation_flags(0x0800_0000).status().ok().and_then(|s| s.code()).unwrap_or(1);
        log!(
            "wacos: tarefa do login {}",
            match r {
                0 => "SequoiaShell trocada por WacOS",
                2 => "SequoiaShell não existe (nada a trocar)",
                3 => "não trocada: o WacOSShell.exe novo não está no lugar",
                _ => "não trocada (erro)",
            }
        );
        if r == 3 {
            // tenta de novo quando a instalação nova existir (gravado pela interface)
            shell::na_interface(Box::new(|| shell::set_setting("wacos_tarefa", "0")));
        }
    });
}