A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! mesas.cpp: as Mesas (áreas de trabalho virtuais do Windows) sem atalhos de teclado, pela interface interna do Explorer
//! (IVirtualDesktopManagerInternal, Windows 11 24H2/25H2). Antes de usar ela é conferida contra o registro (mesmo número e
//! mesmos IDs); se não bater, as funções devolvem false e quem chamou usa os atalhos (Win+Ctrl+setas/D/F4).
#![allow(dead_code, non_snake_case)]
use std::ffi::c_void;
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::Registry::*;
use comum::windows::Win32::UI::Shell::Common::IObjectArray;
use comum::windows::Win32::UI::Shell::{IVirtualDesktopManager, VirtualDesktopManager};
use crate::{log, mesa};
const CLSID_IMMERSIVE_SHELL: GUID = GUID::from_u128(0xC2F03A33_21F5_47FA_B4BB_156362A2F239);
const CLSID_VDM_INTERNAL: GUID = GUID::from_u128(0xC5E0CDCA_7B6E_41B2_9FC4_D93975CC467B);
mod iface {
use super::*;
#[windows_core::interface("3F07F4BE-B107-441A-AF0F-39D82529072C")]
pub unsafe trait IVD: IUnknown {
fn IsViewVisible(&self, view: *mut c_void, visible: *mut BOOL) -> HRESULT;
fn GetID(&self, id: *mut GUID) -> HRESULT;
}
#[windows_core::interface("53F5CA0B-158F-4124-900C-057158060B27")]
pub unsafe trait IVDMI: IUnknown {
fn GetCount(&self, count: *mut u32) -> HRESULT;
fn MoveViewToDesktop(&self, view: *mut c_void, d: *mut c_void) -> HRESULT;
fn CanViewMoveDesktops(&self, view: *mut c_void, can: *mut BOOL) -> HRESULT;
fn GetCurrentDesktop(&self, d: *mut *mut c_void) -> HRESULT;
fn GetDesktops(&self, arr: *mut *mut c_void) -> HRESULT;
fn GetAdjacentDesktop(&self, from: *mut c_void, dir: i32, d: *mut *mut c_void) -> HRESULT;
fn SwitchDesktop(&self, d: *mut c_void) -> HRESULT;
fn SwitchDesktopAndMoveForegroundView(&self, d: *mut c_void) -> HRESULT;
fn CreateDesktop(&self, d: *mut *mut c_void) -> HRESULT;
fn MoveDesktop(&self, d: *mut c_void, index: i32) -> HRESULT;
fn RemoveDesktop(&self, d: *mut c_void, fallback: *mut c_void) -> HRESULT;
}
/// a "vista" de uma janela (o que a interface das mesas move); IID estável do Windows 10 ao 11 25H2
#[windows_core::interface("1841C6D7-4F9D-42C0-AF41-8747538F10E5")]
pub unsafe trait IAVC: IUnknown {
fn GetViews(&self, a: *mut *mut c_void) -> HRESULT;
fn GetViewsByZOrder(&self, a: *mut *mut c_void) -> HRESULT;
fn GetViewsByAppUserModelId(&self, id: PCWSTR, a: *mut *mut c_void) -> HRESULT;
fn GetViewForHwnd(&self, h: HWND, view: *mut *mut c_void) -> HRESULT;
}
pub unsafe fn query<T: Interface>(sp: &IServiceProvider, service: &GUID) -> Option<T> {
sp.QueryService::<T>(service).ok()
}
fn registry_ids() -> Vec<GUID> {
let mut ids = [0u8; 16 * 64];
let mut cb = ids.len() as u32;
let ok = unsafe { RegGetValueW(HKEY_CURRENT_USER, w!("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\VirtualDesktops"), w!("VirtualDesktopIDs"), RRF_RT_REG_BINARY, None, Some(ids.as_mut_ptr() as *mut _), Some(&mut cb)).is_ok() };
if !ok {
return Vec::new();
}
ids[..cb as usize].chunks_exact(16).map(|c| GUID::from_u128(u128::from_be_bytes(guid_be(c)))).collect()
}
/// os 16 bytes do GUID como estão na memória (Data1..3 little-endian) para a forma u128 do GUID::from_u128
fn guid_be(c: &[u8]) -> [u8; 16] {
let mut o = [0u8; 16];
o[0..4].copy_from_slice(&[c[3], c[2], c[1], c[0]]);
o[4..6].copy_from_slice(&[c[5], c[4]]);
o[6..8].copy_from_slice(&[c[7], c[6]]);
o[8..16].copy_from_slice(&c[8..16]);
o
}
fn service_provider() -> Option<IServiceProvider> {
unsafe { CoCreateInstance(&CLSID_IMMERSIVE_SHELL, None, CLSCTX_LOCAL_SERVER).ok() }
}
/// a interface interna, conferida contra o registro; None se não der para confiar nela
fn open() -> Option<(IVDMI, Vec<IVD>)> {
if mesa::standalone() {
return None; // a interface é do Explorador: sem ele não há mesas virtuais
}
unsafe {
let sp = service_provider()?;
let Some(m) = query::<IVDMI>(&sp, &CLSID_VDM_INTERNAL) else {
log!("mesas: interface interna indisponível; usando atalhos");
return None;
};
let reg = registry_ids();
let mut n = 0u32;
let mut desks = Vec::new();
let mut arr: *mut c_void = std::ptr::null_mut();
// PR #355: com uma Mesa só o Windows ainda não gravou a lista no registro (vazia): vale a que existe
let primeira = reg.is_empty();
let mut ok = m.GetCount(&mut n).is_ok() && n > 0 && n as usize == if primeira { 1 } else { reg.len() } && m.GetDesktops(&mut arr).is_ok() && !arr.is_null();
if ok {
let arr = IObjectArray::from_raw(arr);
ok = arr.GetCount().ok() == Some(n);
for i in 0..n {
if !ok {
break;
}
let Ok(d) = arr.GetAt::<IVD>(i) else {
ok = false;
break;
};
let mut g = GUID::zeroed();
if d.GetID(&mut g).is_err() || g == GUID::zeroed() || (!primeira && g != reg[i as usize]) {
ok = false;
}
desks.push(d);
}
}
if !ok {
log!("mesas: interface interna não confere com o registro; usando atalhos");
return None;
}
Some((m, desks))
}
}
/// PR #355: vai para a Mesa onde a janela está (Exposé do app escolhendo uma janela de outra Mesa)
pub fn switch_to_window(h: HWND) -> bool {
let id = unsafe { CoCreateInstance::<_, IVirtualDesktopManager>(&VirtualDesktopManager, None, CLSCTX_ALL).ok().and_then(|v| v.GetWindowDesktopId(h).ok()) };
let Some(id) = id.filter(|g| *g != GUID::zeroed()) else { return false };
let Some((m, d)) = open() else { return false };
for dk in &d {
let mut g = GUID::zeroed();
if unsafe { dk.GetID(&mut g).is_ok() } && g == id {
return unsafe { m.SwitchDesktop(dk.as_raw()).is_ok() };
}
}
false
}
pub fn switch(index: usize) -> bool {
let Some((m, d)) = open() else { return false };
index < d.len() && unsafe { m.SwitchDesktop(d[index].as_raw()).is_ok() }
}
pub fn create() -> bool {
let Some((m, _)) = open() else { return false };
let mut nd: *mut c_void = std::ptr::null_mut();
let ok = unsafe { m.CreateDesktop(&mut nd).is_ok() } && !nd.is_null();
if ok {
unsafe { drop(IVD::from_raw(nd)) };
}
ok
}
pub fn move_window(h: HWND, index: usize) -> bool {
let mut ok = false;
if let Some((m, d)) = open() {
if index < d.len() {
unsafe {
if let Some(c) = service_provider().and_then(|sp| query::<IAVC>(&sp, &IAVC::IID)) {
let mut view: *mut c_void = std::ptr::null_mut();
let hr = c.GetViewForHwnd(h, &mut view);
if hr.is_ok() && !view.is_null() {
let v = IUnknown::from_raw(view);
ok = m.MoveViewToDesktop(v.as_raw(), d[index].as_raw()).is_ok();
}
if !ok {
log!("mesas: mover janela falhou ({hr:?})");
}
}
}
}
}
if !ok {
// a API pública (só funciona com janelas do próprio Shell, mas não custa tentar)
let ids = registry_ids();
if index < ids.len() {
if let Ok(vdm) = unsafe { CoCreateInstance::<_, IVirtualDesktopManager>(&VirtualDesktopManager, None, CLSCTX_ALL) } {
ok = unsafe { vdm.MoveWindowToDesktop(h, &ids[index]).is_ok() };
}
}
}
ok
}
pub fn remove(index: usize) -> bool {
let Some((m, d)) = open() else { return false };
if index >= d.len() || d.len() < 2 {
return false;
}
let fallback = &d[if index > 0 { index - 1 } else { 1 }]; // as janelas vão para a mesa vizinha, como no Mac
unsafe { m.RemoveDesktop(d[index].as_raw(), fallback.as_raw()).is_ok() }
}
}
#[allow(unused_imports)] // nem todo uso passa por aqui
pub use iface::{create, move_window, remove, switch, switch_to_window};