A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! ponteiro.cpp: "Sacudir o ponteiro para localizar" do macOS: sacudir o mouse rápido faz o ponteiro crescer (até 6×) e,
//! desacelerando, ele volta. Detecção (a ideia do efeito do KDE): o caminho do último ~0,7 s comparado com a diagonal da
//! área coberta (> 4× = sacudida). O mouse é lido por Raw Input numa thread só dela; crescer troca o cursor do sistema
//! pelo mesmo arquivo do esquema em tamanho maior, e voltar relê o esquema do registro (SPI_SETCURSORS, sem gravar).
//! Também aplica/devolve o esquema de cursores do Mac OS X no tema Leopard (o anterior em cursor-antes.txt).
#![allow(dead_code)]
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicIsize, AtomicU32, Ordering};
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Dwm::DwmFlush;
use comum::windows::Win32::System::Environment::ExpandEnvironmentStringsW;
use comum::windows::Win32::System::Registry::*;
use comum::windows::Win32::System::Threading::GetCurrentThreadId;
use comum::windows::Win32::UI::HiDpi::*;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::Input::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;
use crate::{anim, log, shell};
const WINDOW_MS: f64 = 700.0;
const SENSITIVITY: f32 = 4.0;
const MIN_DIAG: f32 = 90.0;
const FIRST: f32 = 4.0;
const STEP: f32 = 0.75;
const MAXMAG: f32 = 6.0;
/// voltar como no Mac: assim que o mouse desacelera, encolhe
const SLOW_MS: f64 = 110.0;
const HOLD_MS: f64 = 450.0;
const FAST: f32 = 1.1;
const GROW_MS: f64 = 200.0;
const SHRINK_MS: f64 = 170.0;
const WM_PT_PAUSA: u32 = WM_APP + 0x50;
#[derive(Clone, Copy)]
struct Kind {
ocr: u32,
reg: &'static str,
idc: PCWSTR,
}
const KINDS: [Kind; 3] = [Kind { ocr: 32512, reg: "Arrow", idc: IDC_ARROW }, Kind { ocr: 32513, reg: "IBeam", idc: IDC_IBEAM }, Kind { ocr: 32649, reg: "Hand", idc: IDC_HAND }];
struct S {
hist: VecDeque<(f64, f32, f32)>,
dpi_k: f32,
kind: Option<Kind>,
file: String,
cache: HashMap<i32, HCURSOR>,
base: i32,
applied: i32,
mag: f32,
from: f32,
target: f32,
anim_at: f64,
anim_ms: f64,
last_shake: f64,
last_fast: f64,
prev_pt: POINT,
prev_at: f64,
}
static SS: Global<Option<S>> = Global::new(None);
fn s() -> &'static mut S {
SS.get().get_or_insert_with(|| S { hist: VecDeque::new(), dpi_k: 1.0, kind: None, file: String::new(), cache: HashMap::new(), base: 32, applied: 0, mag: 1.0, from: 1.0, target: 1.0, anim_at: 0.0, anim_ms: GROW_MS, last_shake: 0.0, last_fast: 0.0, prev_pt: POINT::default(), prev_at: 0.0 })
}
static TID: AtomicU32 = AtomicU32::new(0);
static WND: AtomicIsize = AtomicIsize::new(0);
fn in_out_cubic(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
if t < 0.5 {
4.0 * t * t * t
} else {
1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
}
}
fn out_cubic(t: f32) -> f32 {
1.0 - (1.0 - t.clamp(0.0, 1.0)).powi(3)
}
fn detect(now: f64, x: f32, y: f32) -> bool {
let st = s();
while st.hist.front().is_some_and(|f| now - f.0 >= WINDOW_MS) {
st.hist.pop_front();
}
let same = |a: f32, b: f32| (a >= -1.0 && b >= -1.0) || (a <= 1.0 && b <= 1.0); // ±1 px vale qualquer lado
let n = st.hist.len();
if n >= 2 {
let (p, q) = (st.hist[n - 2], st.hist[n - 1]);
if same(q.1 - p.1, x - q.1) && same(q.2 - p.2, y - q.2) {
st.hist[n - 1] = (now, x, y); // trecho reto: só as pontas
return false;
}
}
st.hist.push_back((now, x, y));
if st.hist.len() < 4 {
return false;
}
let (mut dist, mut l, mut r, mut t, mut b) = (0.0f32, st.hist[0].1, st.hist[0].1, st.hist[0].2, st.hist[0].2);
for i in 1..st.hist.len() {
let (a, c) = (st.hist[i - 1], st.hist[i]);
dist += (c.1 - a.1).hypot(c.2 - a.2);
l = l.min(c.1);
r = r.max(c.1);
t = t.min(c.2);
b = b.max(c.2);
}
let diag = (r - l).hypot(b - t);
if diag < MIN_DIAG * st.dpi_k {
return false;
}
if dist / diag > SENSITIVITY {
st.hist.clear();
return true;
}
false
}
fn current_kind() -> Option<Kind> {
unsafe {
let mut ci = CURSORINFO { cbSize: std::mem::size_of::<CURSORINFO>() as u32, ..Default::default() };
if GetCursorInfo(&mut ci).is_err() || ci.flags.0 & CURSOR_SHOWING.0 == 0 || ci.hCursor.is_invalid() {
return None; // escondido (jogo, vídeo): nada
}
KINDS.iter().copied().find(|k| LoadCursorW(None, k.idc).is_ok_and(|c| c == ci.hCursor)) // cursor próprio de um app: não
}
}
fn load(size: i32) -> HCURSOR {
let st = s();
if let Some(c) = st.cache.get(&size) {
return *c;
}
let Some(k) = st.kind else { return HCURSOR::default() };
let c = unsafe {
if st.file.is_empty() {
LoadImageW(None, PCWSTR(k.ocr as usize as *const u16), IMAGE_CURSOR, size, size, IMAGE_FLAGS(0))
} else {
LoadImageW(None, pc(&wz(&st.file)), IMAGE_CURSOR, size, size, LR_LOADFROMFILE)
}
};
let c = HCURSOR(c.map(|h| h.0).unwrap_or(std::ptr::null_mut()));
st.cache.insert(size, c);
c
}
fn clear_cache() {
for (_, c) in s().cache.drain() {
if !c.is_invalid() {
unsafe {
let _ = DestroyCursor(c);
}
}
}
}
fn restore_scheme() {
let st = s();
if st.applied == 0 {
return;
}
unsafe {
let _ = SystemParametersInfoW(SPI_SETCURSORS, 0, None, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0)); // relê do registro
}
st.applied = 0;
}
fn apply(mag: f32) {
let st = s();
let Some(k) = st.kind else { return };
let size = ((st.base as f32 * mag / 2.0).round() as i32) * 2;
if mag <= 1.001 || size <= st.base {
restore_scheme();
return;
}
if size == st.applied {
return;
}
let c = load(size);
if c.is_invalid() {
return;
}
unsafe {
if let Ok(copia) = CopyIcon(HICON(c.0)) {
if SetSystemCursor(HCURSOR(copia.0), SYSTEM_CURSOR_ID(k.ocr)).is_ok() {
st.applied = size; // o sistema fica com a cópia
}
}
}
}
/// primeira sacudida: qual cursor e de onde vem
fn begin() {
let st = s();
st.kind = current_kind();
let Some(k) = st.kind else { return };
let raw = ler_cur(Some(k.reg));
let path = expand(&raw);
if path.to_lowercase().ends_with(".ani") {
st.kind = None; // animado (ocupado): fica como está
return;
}
if path != st.file {
clear_cache();
}
st.file = path;
unsafe {
st.base = GetSystemMetricsForDpi(SM_CXCURSOR, GetDpiForSystem());
}
if st.base < 16 {
st.base = 32;
}
}
fn animate(now: f64) {
let st = s();
let t = ((now - st.anim_at) / st.anim_ms) as f32;
st.mag = st.from + (st.target - st.from) * if st.target < st.from { out_cubic(t) } else { in_out_cubic(t) }; // encolher começa já rápido
if t >= 1.0 {
st.mag = st.target;
}
apply(st.mag);
}
fn animate_to(target: f32, now: f64) {
let st = s();
st.from = st.mag;
st.target = target;
st.anim_at = now;
st.anim_ms = if target > st.mag { GROW_MS } else { SHRINK_MS };
}
fn rid(remove: bool, h: HWND) -> RAWINPUTDEVICE {
RAWINPUTDEVICE { usUsagePage: 1, usUsage: 2, dwFlags: if remove { RIDEV_REMOVE } else { RIDEV_INPUTSINK }, hwndTarget: if remove { HWND::default() } else { h } }
}
unsafe extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
let st = s();
if m == WM_PT_PAUSA {
// num jogo, cada movimento do mouse (1000 por segundo) acordava esta thread
let _ = RegisterRawInputDevices(&[rid(w_.0 != 0, h)], std::mem::size_of::<RAWINPUTDEVICE>() as u32);
if w_.0 != 0 {
st.hist.clear();
animate_to(1.0, anim::now());
}
return LRESULT(0);
}
if m == WM_INPUT {
let mut ri = RAWINPUT::default();
let mut sz = std::mem::size_of::<RAWINPUT>() as u32;
if GetRawInputData(HRAWINPUT(l.0 as *mut _), RID_INPUT, Some(&mut ri as *mut _ as *mut _), &mut sz, std::mem::size_of::<RAWINPUTHEADER>() as u32) != u32::MAX && ri.header.dwType == RIM_TYPEMOUSE.0 {
let now = anim::now();
// botão segurado (arrastando, desenhando): não é sacudida
if [VK_LBUTTON, VK_RBUTTON, VK_MBUTTON].iter().any(|v| GetAsyncKeyState(v.0 as i32) < 0) {
st.hist.clear();
return LRESULT(0);
}
let mut p = POINT::default();
let _ = GetCursorPos(&mut p);
if st.prev_at <= 0.0 || now - st.prev_at >= 4.0 {
// velocidade a cada ~4 ms
if st.prev_at > 0.0 && now - st.prev_at < 100.0 {
let v = (((p.x - st.prev_pt.x) as f64).hypot((p.y - st.prev_pt.y) as f64) / (now - st.prev_at)) as f32;
if v > FAST * st.dpi_k {
st.last_fast = now;
}
}
st.prev_pt = p;
st.prev_at = now;
}
if detect(now, p.x as f32, p.y as f32) {
if st.target <= 1.0 {
begin();
}
if st.kind.is_some() {
let target = if st.target <= 1.0 { FIRST } else { MAXMAG.min(st.target + STEP) };
if target != st.target {
animate_to(target, now);
}
st.last_shake = now;
st.last_fast = now;
}
}
}
}
DefWindowProcW(h, m, w_, l)
}
fn thread() {
unsafe {
TID.store(GetCurrentThreadId(), Ordering::Relaxed);
let _ = SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
s().dpi_k = GetDpiForSystem() as f32 / 96.0;
let hi = shell::inst();
RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hi, lpszClassName: w!("ShellPonteiro"), ..Default::default() });
let h = CreateWindowExW(WINDOW_EX_STYLE(0), w!("ShellPonteiro"), w!(""), WINDOW_STYLE(0), 0, 0, 0, 0, HWND_MESSAGE, None, hi, None).unwrap_or_default();
WND.store(h.0 as isize, Ordering::Relaxed);
if h.0.is_null() || RegisterRawInputDevices(&[rid(false, h)], std::mem::size_of::<RAWINPUTDEVICE>() as u32).is_err() {
log!("ponteiro: sem raw input");
return;
}
log!("ponteiro: sacudir para localizar ligado");
let mut msg = MSG::default();
'fora: loop {
let st = s();
let busy = st.mag != st.target || st.target > 1.0;
if !busy {
// parado: só acorda com mouse (nenhum custo)
if GetMessageW(&mut msg, None, 0, 0).0 <= 0 {
break;
}
DispatchMessageW(&msg);
continue;
}
while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
if msg.message == WM_QUIT {
break 'fora;
}
DispatchMessageW(&msg);
}
let now = anim::now();
if st.target > 1.0 && (now - st.last_fast > SLOW_MS || now - st.last_shake > HOLD_MS) {
animate_to(1.0, now); // desacelerou: encolhe já
st.hist.clear();
}
if st.mag != st.target {
animate(now);
let _ = DwmFlush(); // um passo por quadro da tela
} else {
MsgWaitForMultipleObjects(None, false, 30, QS_ALLINPUT);
}
if st.mag == 1.0 && st.target == 1.0 {
restore_scheme();
st.kind = None;
}
}
restore_scheme();
clear_cache();
}
}
pub fn start() {
if shell::foto() || shell::setting("sacudir_ponteiro", "1") != "1" {
return;
}
std::thread::spawn(thread);
}
pub fn pausar(p: bool) {
let h = WND.load(Ordering::Relaxed);
if h != 0 {
unsafe {
let _ = PostMessageW(HWND(h as *mut _), WM_PT_PAUSA, WPARAM(p as usize), LPARAM(0));
}
}
}
pub fn stop() {
unsafe {
let t = TID.load(Ordering::Relaxed);
if t != 0 {
let _ = PostThreadMessageW(t, WM_QUIT, WPARAM(0), LPARAM(0));
}
let _ = SystemParametersInfoW(SPI_SETCURSORS, 0, None, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0)); // o cursor volta mesmo se a thread não chegar a tempo
}
}
// ---- cursor do tema Mac OS X Leopard (HKCU\Control Panel\Cursors; o anterior em %APPDATA%\Shell\cursor-antes.txt)
const LEO_CURSORES: &[(&str, &str)] = &[
("Arrow", "Normal Select.cur"),
("Help", "Help Select.cur"),
("AppStarting", "RainbowSwirl-Background.ani"),
("Wait", "RainbowSwirl-Busy.ani"),
("Crosshair", "Precision Select.cur"),
("IBeam", "Text Select.cur"),
("NWPen", "Handwriting.cur"),
("No", "Unavailable.cur"),
("SizeNS", "Vertical Resize.cur"),
("SizeWE", "Horizontal Resize.cur"),
("SizeNWSE", "Diagonal Resize 1.cur"),
("SizeNESW", "Diagonal Resize 2.cur"),
("SizeAll", "Move.cur"),
("UpArrow", "Alternate Select.cur"),
("Hand", "Link Select.cur"),
];
const CUR_KEY: &str = "Control Panel\\Cursors";
fn leo_dir() -> String {
let d = shell::dir();
format!("{}\\cursor\\Leopard", d.rsplit_once('\\').map(|x| x.0).unwrap_or(&d))
}
fn antes_path() -> String {
format!("{}\\Shell\\cursor-antes.txt", std::env::var("APPDATA").unwrap_or_default())
}
fn expand(raw: &str) -> String {
let mut b = [0u16; 520];
unsafe {
let n = ExpandEnvironmentStringsW(pc(&wz(raw)), Some(&mut b));
if n == 0 {
return raw.to_string();
}
}
from_w(&b)
}
fn ler_cur(nome: Option<&str>) -> String {
let mut v = [0u16; 520];
let mut cb = (v.len() * 2) as u32;
let n = nome.map(wz);
unsafe {
if RegGetValueW(HKEY_CURRENT_USER, pc(&wz(CUR_KEY)), n.as_ref().map(|x| pc(x)).unwrap_or(PCWSTR::null()), RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | RRF_NOEXPAND, None, Some(v.as_mut_ptr() as *mut _), Some(&mut cb)).is_err() {
return String::new();
}
}
from_w(&v)
}
fn gravar_cur(nome: Option<&str>, v: &str, expand_: bool) {
unsafe {
let mut k = HKEY::default();
if RegOpenKeyExW(HKEY_CURRENT_USER, pc(&wz(CUR_KEY)), 0, KEY_SET_VALUE, &mut k).is_err() {
return;
}
let n = nome.map(wz);
let w_ = wz(v);
let _ = RegSetValueExW(k, n.as_ref().map(|x| pc(x)).unwrap_or(PCWSTR::null()), 0, if expand_ { REG_EXPAND_SZ } else { REG_SZ }, Some(std::slice::from_raw_parts(w_.as_ptr() as *const u8, w_.len() * 2)));
let _ = RegCloseKey(k);
}
}
pub fn tema_leopard(on: bool) {
if shell::foto() {
return;
}
let dir = leo_dir();
let arrow = format!("{dir}\\Normal Select.cur");
let ativo = ler_cur(Some("Arrow")).eq_ignore_ascii_case(&arrow); // o cursor do Leopard já está aplicado
let ap = antes_path();
if on {
if ativo {
return;
}
if !std::path::Path::new(&arrow).exists() {
log!("cursor do Leopard: arquivos não encontrados em {dir}");
return;
}
// guarda o esquema de agora (só se ainda não houver um: trocar de tema duas vezes não perde o original)
if !std::path::Path::new(&ap).exists() {
let mut t = format!("\u{FEFF}(Default)={}\n", ler_cur(None));
for (reg, _) in LEO_CURSORES {
t += &format!("{reg}={}\n", ler_cur(Some(reg)));
}
if std::fs::write(&ap, t.as_bytes()).is_err() {
log!("cursor do Leopard: não deu para guardar o anterior");
return;
}
}
gravar_cur(None, "Mac OS X Leopard", false);
for (reg, arq) in LEO_CURSORES {
gravar_cur(Some(reg), &format!("{dir}\\{arq}"), true);
}
unsafe {
let _ = SystemParametersInfoW(SPI_SETCURSORS, 0, None, SPIF_SENDCHANGE);
}
log!("cursor do Leopard aplicado (o anterior em {ap})");
return;
}
let Ok(b) = std::fs::read(&ap) else { return }; // nada guardado: nada a devolver
let t = String::from_utf8_lossy(b.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(&b)).into_owned();
if ativo {
// só devolve se o cursor ainda for o do Leopard
for l in t.lines() {
if let Some((k, v)) = l.split_once('=') {
if k == "(Default)" {
gravar_cur(None, v, false);
} else {
gravar_cur(Some(k), v, true);
}
}
}
unsafe {
let _ = SystemParametersInfoW(SPI_SETCURSORS, 0, None, SPIF_SENDCHANGE);
}
log!("cursor do Leopard: esquema anterior devolvido");
}
let _ = std::fs::remove_file(&ap);
}