A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! som.cpp: o Som do macOS na barra de menus:
//! - menu "Som" do ícone de som: título, controle de volume (trilho azul, botão branco; no Tahoe o botão vira uma lente
//! de vidro maior enquanto é arrastado e estica com a velocidade), "Saída" com as saídas de áudio de verdade (Core
//! Audio), "Apps" (o volume de cada app que está tocando) e "Ajustes de Som…";
//! - aviso de volume (HUD) das teclas de volume: no Sequoia o quadrado de vidro no centro embaixo com o alto-falante
//! grande e a barra de 16 segmentos; no Tahoe a pílula de vidro logo abaixo do ícone de som com o nome da saída, o
//! controle e os pontinhos de marcação. Some sozinho depois de ~1,5 s.
//! Medidas do menu tiradas da captura do Tahoe (2x): 320 pt de largura, título a 20, controle a 46, separador a 60,
//! "Saída" a 72, saídas a cada 32 pt com círculo de 26.
#![allow(dead_code)]
use std::ffi::c_void;
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Graphics::Gdi::{BeginPaint, EndPaint, GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTOPRIMARY, PAINTSTRUCT};
use comum::windows::Win32::Media::Audio::Endpoints::IAudioEndpointVolume;
use comum::windows::Win32::Media::Audio::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::SystemInformation::GetTickCount;
use comum::windows::Win32::System::Threading::{GetCurrentProcessId, OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION};
use comum::windows::Win32::UI::Controls::WM_MOUSELEAVE;
use comum::windows::Win32::UI::HiDpi::GetDpiForWindow;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::Shell::PropertiesSystem::PROPERTYKEY;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;
use crate::{anim, apps, backdrop, central, ilha, liquid, log, menubar, shell, ui};
// ================= áudio (Core Audio)
/// PKEY_AudioEndpoint_FormFactor
const KEY_FORM: PROPERTYKEY = PROPERTYKEY { fmtid: GUID::from_u128(0x1da5d803_d492_4edd_8c23_e0c0ffee7f0e), pid: 0 };
#[derive(Clone, Default)]
struct Out {
id: String,
name: String,
form: u32,
def: bool,
}
/// volume por app (mixer de volume): as sessões de áudio da saída padrão juntas por programa, como o Mixer do Windows
struct AppVol {
exe: String,
name: String,
vol: f32,
mute: bool,
vs: Vec<ISimpleAudioVolume>,
}
const MAX_APPS: usize = 8;
#[derive(Clone, Copy, PartialEq)]
enum HitId {
Out(usize),
Settings,
Slider,
App(usize),
}
struct Glass {
wnd: HWND,
back: HWND,
s: ui::GpuSurface,
glass: bool,
}
impl Default for Glass {
fn default() -> Self {
Glass { wnd: HWND::default(), back: HWND::default(), s: ui::GpuSurface::default(), glass: false }
}
}
#[derive(Default)]
struct S {
vol: f32,
mute: bool,
ok: bool,
name: String,
outs: Vec<Out>,
apps: Vec<AppVol>,
// menu
m: Glass,
open: bool,
open_at: f64,
closed_at: u32,
hover: Option<HitId>,
drag: bool,
drag_app: Option<usize>,
press: f32,
stretch: f32,
last_kx: f32,
last_frame: f64,
hits: Vec<(HitId, RectF)>,
mw: f32,
// aviso
h: Glass,
hud_on: bool,
hud_tahoe: bool,
hud_shown_at: f64,
hud_fade_at: f64,
// fontes
tf: Option<[IDWriteTextFormat; 4]>,
/// modo foto: onde ficam o menu e o aviso (px)
foto: bool,
}
static SS: Global<Option<S>> = Global::new(None);
fn s() -> &'static mut S {
SS.get().get_or_insert_with(|| S { mw: 320.0, last_kx: -1.0, ..Default::default() })
}
fn dev_name(d: &IMMDevice) -> (String, u32) {
unsafe {
let Ok(ps) = d.OpenPropertyStore(STGM_READ) else { return (String::new(), 0) };
(prop_text(&ps, &comum::windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName), prop_u64(&ps, &KEY_FORM) as u32)
}
}
fn enumerator() -> Option<IMMDeviceEnumerator> {
unsafe { CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok() }
}
fn endpoint() -> Option<IAudioEndpointVolume> {
unsafe { enumerator()?.GetDefaultAudioEndpoint(eRender, eConsole).ok()?.Activate(CLSCTX_ALL, None).ok() }
}
fn take_id(d: &IMMDevice) -> String {
unsafe {
match d.GetId() {
Ok(p) => {
let s = from_w(p.as_wide());
CoTaskMemFree(Some(p.0 as *const c_void));
s
}
Err(_) => String::new(),
}
}
}
/// volume, mudo e nome da saída padrão; com `outs`, a lista das saídas ativas
fn read(outs: bool) {
let st = s();
st.ok = false;
let Some(en) = enumerator() else { return };
unsafe {
let mut def = String::new();
if let Ok(d) = en.GetDefaultAudioEndpoint(eRender, eConsole) {
def = take_id(&d);
st.name = dev_name(&d).0;
if let Ok(v) = d.Activate::<IAudioEndpointVolume>(CLSCTX_ALL, None) {
st.vol = v.GetMasterVolumeLevelScalar().unwrap_or(0.0);
st.mute = v.GetMute().map(|b| b.as_bool()).unwrap_or(false);
st.ok = true;
if VOL_BUSY.load(std::sync::atomic::Ordering::Relaxed) {
// a thread ainda grava: a leitura não volta atrás
st.vol = f32::from_bits(VOL_ULTIMO.load(std::sync::atomic::Ordering::Relaxed));
st.mute = st.vol <= 0.001;
}
}
}
if outs {
st.outs.clear();
if let Ok(col) = en.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE) {
for i in 0..col.GetCount().unwrap_or(0) {
let Ok(x) = col.Item(i) else { continue };
let id = take_id(&x);
if id.is_empty() {
continue;
}
let (name, form) = dev_name(&x);
st.outs.push(Out { def: id == def, id, name, form });
}
}
}
}
}
/// o nome do app no Dock quando ele está lá (com o nome escolhido em Renomear…), senão o do .exe
fn nome_do_app(exe: &str) -> String {
let low = exe.to_lowercase();
for a in apps::list().iter() {
if !a.exe.is_empty() && a.exe.to_lowercase() == low {
return if a.finder { a.name.clone() } else { apps::nome_visivel(&a.name, &a.exe) };
}
}
let mut n = exe.rsplit('\\').next().unwrap_or("").to_string();
if n.len() > 4 && n.to_lowercase().ends_with(".exe") {
n.truncate(n.len() - 4);
}
let mut c = n.chars();
let n = match c.next() {
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
None => n,
};
apps::nome_visivel(&n, exe)
}
fn read_apps() {
let st = s();
st.apps.clear();
let Some(en) = enumerator() else { return };
unsafe {
let Ok(d) = en.GetDefaultAudioEndpoint(eRender, eConsole) else { return };
let Ok(mg) = d.Activate::<IAudioSessionManager2>(CLSCTX_ALL, None) else { return };
let Ok(se) = mg.GetSessionEnumerator() else { return };
for i in 0..se.GetCount().unwrap_or(0) {
let Ok(c) = se.GetSession(i) else { continue };
if c.GetState().unwrap_or(AudioSessionStateExpired) == AudioSessionStateExpired {
continue;
}
let Ok(c2) = c.cast::<IAudioSessionControl2>() else { continue };
if c2.IsSystemSoundsSession() == S_OK {
continue; // os sons do sistema ficam de fora (o volume geral já é deles)
}
let pid = c2.GetProcessId().unwrap_or(0);
let mut exe = String::new();
if pid != 0 && pid != GetCurrentProcessId() {
if let Ok(ph) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) {
let mut p = [0u16; 260];
let mut len = p.len() as u32;
if QueryFullProcessImageNameW(ph, PROCESS_NAME_WIN32, PWSTR(p.as_mut_ptr()), &mut len).is_ok() {
exe = String::from_utf16_lossy(&p[..len as usize]);
}
let _ = CloseHandle(ph);
}
}
if exe.is_empty() {
continue;
}
let Ok(sv) = c.cast::<ISimpleAudioVolume>() else { continue };
if let Some(a) = st.apps.iter_mut().find(|a| a.exe.eq_ignore_ascii_case(&exe)) {
a.vs.push(sv);
} else if st.apps.len() < MAX_APPS {
let vol = sv.GetMasterVolume().unwrap_or(1.0);
let mute = sv.GetMute().map(|b| b.as_bool()).unwrap_or(false);
st.apps.push(AppVol { name: nome_do_app(&exe), exe, vol, mute, vs: vec![sv] });
}
}
}
st.apps.sort_by_key(|a| a.name.to_lowercase());
}
fn set_app_volume(i: usize, v: f32) {
let st = s();
let Some(a) = st.apps.get_mut(i) else { return };
let v = v.clamp(0.0, 1.0);
if !st.foto {
for sv in &a.vs {
unsafe {
let _ = sv.SetMasterVolume(v, std::ptr::null());
let _ = sv.SetMute(v <= 0.001, std::ptr::null());
}
}
}
a.vol = v;
a.mute = v <= 0.001;
}
// issue #172: o volume mudado por fora (botões/roda do fone, teclado que manda direto ao driver) também mostra o aviso
// de volume do Mac. As mudanças do próprio Shell levam este contexto e são ignoradas.
const CTX_SHELL: GUID = GUID::from_values(0x5f3c7a21, 0x9b4e, 0x4d6a, [0x8e, 0x12, 0x6c, 0x0b, 0x77, 0x3a, 0x51, 0xd4]);
const WM_VOL_FORA: u32 = WM_APP + 71;
/// a janela do aviso (recebe WM_VOL_FORA); lida pela thread do áudio
static VOL_AVISO: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);
fn posta_vol_fora(w: usize) {
let h = VOL_AVISO.load(std::sync::atomic::Ordering::Relaxed);
if h != 0 {
unsafe {
let _ = PostMessageW(HWND(h as *mut _), WM_VOL_FORA, WPARAM(w), LPARAM(0));
}
}
}
#[implement(Endpoints::IAudioEndpointVolumeCallback, IMMNotificationClient)]
struct VolCb;
impl Endpoints::IAudioEndpointVolumeCallback_Impl for VolCb_Impl {
fn OnNotify(&self, d: *mut AUDIO_VOLUME_NOTIFICATION_DATA) -> Result<()> {
if !d.is_null() && unsafe { (*d).guidEventContext } != CTX_SHELL {
posta_vol_fora(0);
}
Ok(())
}
}
impl IMMNotificationClient_Impl for VolCb_Impl {
fn OnDeviceStateChanged(&self, _: &PCWSTR, _: DEVICE_STATE) -> Result<()> {
Ok(())
}
fn OnDeviceAdded(&self, _: &PCWSTR) -> Result<()> {
Ok(())
}
fn OnDeviceRemoved(&self, _: &PCWSTR) -> Result<()> {
Ok(())
}
fn OnDefaultDeviceChanged(&self, f: EDataFlow, r: ERole, _: &PCWSTR) -> Result<()> {
if f == eRender && r == eConsole {
posta_vol_fora(1); // outra saída: registra de novo
}
Ok(())
}
fn OnPropertyValueChanged(&self, _: &PCWSTR, _: &PROPERTYKEY) -> Result<()> {
Ok(())
}
}
struct VolReg {
cb: Endpoints::IAudioEndpointVolumeCallback,
/// a saída em que o aviso está registrado
ep: Option<IAudioEndpointVolume>,
/// quando trocou de saída (o volume da nova saída não é "mudança")
em: u32,
/// o enumerador fica vivo com o registro da troca de saída
en: Option<IMMDeviceEnumerator>,
}
static VOL_REG: Global<Option<VolReg>> = Global::new(None);
fn registra_volume() {
let Some(r) = VOL_REG.get().as_mut() else { return };
unsafe {
if let Some(e) = r.ep.take() {
let _ = e.UnregisterControlChangeNotify(&r.cb);
}
r.ep = endpoint().filter(|e| e.RegisterControlChangeNotify(&r.cb).is_ok());
r.em = GetTickCount();
}
}
/// Issue #269: arrastar o volume travava e às vezes parava o WacOS por segundos. Cada movimento do mouse abria a saída
/// de som de novo na thread da interface (o serviço de áudio pode demorar). Agora vai numa thread, só o último valor,
/// sempre com a marca do Shell (a Central de Controle também usa esta: sem a marca, o aviso de "volume mudado fora"
/// relia tudo a cada passo).
static VOL_WANT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(u32::MAX);
pub(crate) static VOL_BUSY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static VOL_ULTIMO: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
pub fn volume_pedir(v: f32) {
use std::sync::atomic::Ordering::Relaxed;
VOL_WANT.store(v.to_bits(), Relaxed);
VOL_ULTIMO.store(v.to_bits(), Relaxed);
if VOL_BUSY.swap(true, Relaxed) {
return;
}
std::thread::spawn(|| loop {
unsafe {
let ci = CoInitializeEx(None, COINIT_MULTITHREADED);
if let Some(e) = endpoint() {
// issue #381: o mudo só vai quando muda de verdade e o volume no máximo a cada 16 ms (SetMute repetido a
// cada passo reinicia o som em alguns drivers/APO: "Audio Renderer error" no YouTube)
let mut mudo: Option<bool> = e.GetMute().ok().map(|m| m.as_bool());
loop {
let b = VOL_WANT.swap(u32::MAX, Relaxed);
if b == u32::MAX {
break;
}
let v = f32::from_bits(b);
let _ = e.SetMasterVolumeLevelScalar(v, &CTX_SHELL);
let quer = v <= 0.001; // no zero, mudo (o ícone vira o alto-falante cortado)
if mudo != Some(quer) {
let _ = e.SetMute(quer, &CTX_SHELL);
mudo = Some(quer);
}
std::thread::sleep(std::time::Duration::from_millis(16));
}
} else {
VOL_WANT.store(u32::MAX, Relaxed);
}
if ci.is_ok() {
CoUninitialize();
}
}
VOL_BUSY.store(false, Relaxed);
// chegou um valor no fim: segue nesta mesma thread
if VOL_WANT.load(Relaxed) == u32::MAX || VOL_BUSY.swap(true, Relaxed) {
break;
}
});
}
fn set_volume(v: f32) {
let st = s();
let v = v.clamp(0.0, 1.0);
if !st.foto {
volume_pedir(v);
}
st.vol = v;
st.mute = v <= 0.001;
menubar::sound_changed(false);
}
fn set_mute(m: bool) {
if let Some(e) = endpoint() {
unsafe {
let _ = e.SetMute(m, &CTX_SHELL);
}
}
s().mute = m;
menubar::sound_changed(false);
}
fn set_default(id: &str) {
central::set_default_output(id);
log!("som: saída padrão trocada para {id}");
read(true);
menubar::sound_changed(true);
}
fn out_symbol(o: &Out) -> &'static str {
let n = o.name.to_lowercase();
if n.contains("airpods") {
return "airpods.gen3";
}
if o.form == 3 || o.form == 5 || n.contains("fone") || n.contains("headphone") || n.contains("headset") {
return "headphones";
}
if o.form == 8 || n.contains("hdmi") || n.contains("displayport") || n.contains("monitor") || n.contains("nvidia") {
return "display";
}
"speaker.wave.2.fill"
}
fn level_symbol(v: f32, mute: bool) -> &'static str {
if mute || v < 0.001 {
"speaker.slash.fill"
} else if v < 0.34 {
"speaker.wave.1.fill"
} else if v < 0.67 {
"speaker.wave.2.fill"
} else {
"speaker.wave.3.fill"
}
}
// ================= janela de vidro: atrás o vidro do Shell (backdrop), na frente o desenho na GPU
unsafe extern "system" fn back_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
if m == WM_MOUSEACTIVATE {
return LRESULT(MA_NOACTIVATE as isize);
}
DefWindowProcW(h, m, w_, l)
}
unsafe fn make_glass(g: &mut Glass, hi: HINSTANCE, cls: PCWSTR, proc_: WNDPROC, click_through: bool, title: PCWSTR) -> bool {
RegisterClassW(&WNDCLASSW { lpfnWndProc: proc_, hInstance: hi, lpszClassName: cls, hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), ..Default::default() });
RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(back_proc), hInstance: hi, lpszClassName: w!("ShellSomFundo"), ..Default::default() });
let ex = WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP | if click_through { WS_EX_NOACTIVATE | WS_EX_TRANSPARENT } else { WINDOW_EX_STYLE(0) };
g.wnd = CreateWindowExW(ex, cls, title, WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
g.back = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_TRANSPARENT | WS_EX_NOREDIRECTIONBITMAP, w!("ShellSomFundo"), w!(""), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
if g.wnd.0.is_null() || g.back.0.is_null() {
return false;
}
g.glass = backdrop::attach(g.back);
let mut corner: u32 = 1;
if !g.glass {
// sem a Composição: acrílico do Windows com o canto do DWM
let _ = DestroyWindow(g.back);
g.back = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_TRANSPARENT, w!("ShellSomFundo"), w!(""), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
corner = 2;
ui::acrylic(g.back, if ui::dark() { 0x6020_1E1E } else { 0x70F4_F4F4 });
}
let c1: u32 = 1;
let none: u32 = 0xFFFF_FFFE;
let _ = DwmSetWindowAttribute(g.back, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const _, 4);
let _ = DwmSetWindowAttribute(g.wnd, DWMWINDOWATTRIBUTE(33), &c1 as *const _ as *const _, 4);
let _ = DwmSetWindowAttribute(g.back, DWMWINDOWATTRIBUTE(34), &none as *const _ as *const _, 4);
let _ = DwmSetWindowAttribute(g.wnd, DWMWINDOWATTRIBUTE(34), &none as *const _ as *const _, 4);
g.s.hwnd = g.wnd;
apps::ours().push(g.wnd);
apps::ours().push(g.back);
true
}
fn glass_shape(g: &Glass, wpx: i32, hpx: i32, rpx: f32, tint: Cor, opacity: f32, scale: f32, cx: f32, cy: f32) {
if !g.glass {
return;
}
if liquid::on() && backdrop::real() {
backdrop::set_pieces(g.back, wpx as f32, hpx as f32, &[backdrop::Piece { r: rf(0.0, 0.0, wpx as f32, hpx as f32), radius: rpx, ..Default::default() }], tint, 16.0);
} else {
backdrop::set(g.back, wpx as f32, hpx as f32, rpx, tint);
}
backdrop::fade(g.back, opacity, scale, cx, cy);
}
fn glass_place(g: &Glass, x: i32, y: i32, w_: i32, h: i32, activate: bool) {
unsafe {
let _ = SetWindowPos(g.back, HWND_TOPMOST, x, y, w_, h, SWP_NOACTIVATE | SWP_SHOWWINDOW);
let _ = SetWindowPos(g.wnd, HWND_TOPMOST, x, y, w_, h, SWP_SHOWWINDOW | if activate { SET_WINDOW_POS_FLAGS(0) } else { SWP_NOACTIVATE });
}
}
fn glass_hide(g: &Glass) {
unsafe {
let _ = ShowWindow(g.wnd, SW_HIDE);
let _ = ShowWindow(g.back, SW_HIDE);
}
}
// ================= desenho comum
const BLUE: Cor = Cor { r: 0.04, g: 0.52, b: 1.0, a: 1.0 };
struct Pal {
tint: Cor,
text: Cor,
text2: Cor,
sep: Cor,
hover: Cor,
track: Cor,
circle: Cor,
circle_glyph: Cor,
}
fn colors() -> Pal {
if ui::dark() {
return Pal { tint: col(0.13, 0.13, 0.14, 0.62), text: col(1.0, 1.0, 1.0, 0.92), text2: col(1.0, 1.0, 1.0, 0.48), sep: col(1.0, 1.0, 1.0, 0.12), hover: col(1.0, 1.0, 1.0, 0.10), track: col(1.0, 1.0, 1.0, 0.18), circle: col(1.0, 1.0, 1.0, 0.16), circle_glyph: col(1.0, 1.0, 1.0, 0.88) };
}
Pal {
tint: if liquid::on() { col(1.0, 1.0, 1.0, 0.62) } else { col(0.97, 0.97, 0.98, 0.66) },
text: col(0.0, 0.0, 0.0, 0.86),
text2: col(0.0, 0.0, 0.0, 0.45),
sep: col(0.0, 0.0, 0.0, 0.10),
hover: col(0.0, 0.0, 0.0, 0.07),
track: col(0.0, 0.0, 0.0, 0.10),
circle: col(0.0, 0.0, 0.0, 0.09),
circle_glyph: col(0.0, 0.0, 0.0, 0.62),
}
}
unsafe fn sym(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, name: &str, r: RectF, c: Cor) {
br.SetColor(&c);
simbolo::draw(&dc.cast().unwrap(), name, r, &br.cast().unwrap());
}
unsafe fn text(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, t: &str, r: RectF, tf: &IDWriteTextFormat, c: Cor) {
br.SetColor(&c);
dc.DrawText(&w(t), tf, &r, br, D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
}
fn tfs() -> &'static [IDWriteTextFormat; 4] {
s().tf.get_or_insert_with(|| {
let mk = |size: f32, wt: DWRITE_FONT_WEIGHT| {
let tf = ui::fmt(size, wt);
unsafe {
let tr_ = DWRITE_TRIMMING { granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER, delimiter: 0, delimiterCount: 0 };
let _ = tf.SetTrimming(&tr_, None);
}
tf
};
[mk(13.0, DWRITE_FONT_WEIGHT_BOLD), mk(12.0, DWRITE_FONT_WEIGHT_SEMI_BOLD), mk(13.0, DWRITE_FONT_WEIGHT_NORMAL), mk(11.5, DWRITE_FONT_WEIGHT_SEMI_BOLD)]
})
}
fn layer(dc: &ID2D1DeviceContext, op: f32, mask: Option<ID2D1Geometry>) {
let lp = D2D1_LAYER_PARAMETERS1 { contentBounds: rf(-1e7, -1e7, 1e7, 1e7), geometricMask: std::mem::ManuallyDrop::new(mask), maskAntialiasMode: D2D1_ANTIALIAS_MODE_PER_PRIMITIVE, maskTransform: mat::ident(), opacity: op, opacityBrush: std::mem::ManuallyDrop::new(None), layerOptions: D2D1_LAYER_OPTIONS1_NONE };
unsafe { dc.PushLayer(&lp, None) };
}
// ================= menu "Som"
// a largura muda ao abrir: Tahoe = 308 (os menus da barra usam o painel de 308 da Central de Controle); Sequoia = 320
const TRACK_L: f32 = 30.0;
const SL_Y: f32 = 46.0;
const TRACK_H: f32 = 6.0;
const KNOB_W: f32 = 22.0;
const KNOB_H: f32 = 16.0; // Tahoe: pílula branca em repouso
const LENS_K: f32 = 1.6; // Tahoe: a lente cresce ~60% enquanto arrasta
const ROWS_Y: f32 = 84.0;
const ROW_H: f32 = 32.0;
const APP_H: f32 = 30.0;
const APP_L: f32 = 128.0; // o controle de cada app começa aqui
const WM_SOM_FRAME: u32 = WM_APP + 90;
const WM_HUD_FRAME: u32 = WM_APP + 91;
const T_POLL: usize = 1;
const T_FADE: usize = 2;
fn mw() -> f32 {
s().mw
}
fn track_r() -> f32 {
mw() - 38.0
}
fn sep_y2() -> f32 {
ROWS_Y + ROW_H * s().outs.len() as f32 + 6.0
}
fn apps_h() -> f32 {
if s().apps.is_empty() {
0.0
} else {
26.0 + APP_H * s().apps.len() as f32 + 4.0
}
}
fn sep_y3() -> f32 {
sep_y2() + apps_h()
}
fn menu_h() -> f32 {
sep_y3() + 33.0
}
fn menu_r() -> f32 {
if liquid::on() {
14.0
} else {
10.0
}
}
fn sc_menu() -> f32 {
if s().foto {
ui::foto_scale()
} else {
ui::scale(s().m.wnd)
}
}
/// posição do centro do botão para o valor v (o botão nunca sai do trilho)
fn knob_x(v: f32) -> f32 {
TRACK_L + KNOB_W / 2.0 + v.clamp(0.0, 1.0) * (track_r() - TRACK_L - KNOB_W)
}
fn value_at(x: f32) -> f32 {
((x - TRACK_L - KNOB_W / 2.0) / (track_r() - TRACK_L - KNOB_W)).clamp(0.0, 1.0)
}
unsafe fn track(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, p: &Pal, cy: f32, kx: f32, th: f32) {
br.SetColor(&p.track);
dc.FillRoundedRectangle(&rr(rf(TRACK_L, cy - th / 2.0, track_r(), cy + th / 2.0), th / 2.0, th / 2.0), br);
br.SetColor(&BLUE);
dc.FillRoundedRectangle(&rr(rf(TRACK_L, cy - th / 2.0, kx.max(TRACK_L + th), cy + th / 2.0), th / 2.0, th / 2.0), br);
}
unsafe fn shadow(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, k: RectF, rad: f32, a: f32) {
for i in (1..=3).rev() {
let g = i as f32 * 1.1;
br.SetColor(&col(0.0, 0.0, 0.0, a / (i + 1) as f32));
dc.FillRoundedRectangle(&rr(rf(k.left - g, k.top - g + 1.5, k.right + g, k.bottom + g + 1.5), rad + g, rad + g), br);
}
}
unsafe fn slider(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, p: &Pal, v: f32) {
let st = s();
let cy = SL_Y;
let dark = ui::dark();
let tr_ = track_r();
sym(dc, br, "speaker.fill", rf(12.0, cy - 5.5, 24.0, cy + 5.5), p.text2);
sym(dc, br, "speaker.wave.3.fill", rf(tr_ + 8.0, cy - 6.0, tr_ + 26.0, cy + 6.0), p.text2);
let kx = knob_x(v);
track(dc, br, p, cy, kx, TRACK_H);
st.hits.push((HitId::Slider, rf(TRACK_L - 10.0, cy - 13.0, tr_ + 10.0, cy + 13.0)));
if !liquid::on() {
// Sequoia: botão redondo branco com sombra curta e um fio de borda
let r = 9.0;
shadow(dc, br, rf(kx - r, cy - r, kx + r, cy + r), r, 0.16);
br.SetColor(&if st.drag { col(0.93, 0.93, 0.94, 1.0) } else { col(1.0, 1.0, 1.0, 1.0) });
dc.FillEllipse(&ell(pt(kx, cy), r, r), br);
br.SetColor(&col(0.0, 0.0, 0.0, if dark { 0.25 } else { 0.12 }));
dc.DrawEllipse(&ell(pt(kx, cy), r - 0.25, r - 0.25), br, 0.5, None);
return;
}
// Tahoe: pílula branca em repouso; arrastando, uma lente de vidro maior que mostra o trilho ampliado, com borda
// azulada da luz que ela entorta, e que estica na direção do movimento
let pr = st.press.clamp(0.0, 1.0);
let grow = 1.0 + (LENS_K - 1.0) * pr;
let (kw, kh) = (KNOB_W * grow * (1.0 + st.stretch), KNOB_H * grow * (1.0 - st.stretch * 0.35));
let rad = kh / 2.0;
let k = rf(kx - kw / 2.0, cy - kh / 2.0, kx + kw / 2.0, cy + kh / 2.0);
let rrk = rr(k, rad, rad);
shadow(dc, br, k, rad, 0.10 + 0.06 * pr);
if pr < 0.999 {
// pílula branca (some conforme a lente aparece)
br.SetColor(&col(1.0, 1.0, 1.0, 1.0 - pr));
dc.FillRoundedRectangle(&rrk, br);
br.SetColor(&col(0.0, 0.0, 0.0, 0.08 * (1.0 - pr)));
dc.DrawRoundedRectangle(&rr(rf(k.left + 0.25, k.top + 0.25, k.right - 0.25, k.bottom - 0.25), rad, rad), br, 0.5, None);
}
if pr > 0.001 {
if let Ok(geo) = ui::d2d().CreateRoundedRectangleGeometry(&rrk) {
layer(dc, pr, Some(geo.cast().unwrap()));
br.SetColor(&col(1.0, 1.0, 1.0, if dark { 0.10 } else { 0.30 })); // o corpo do vidro, quase transparente
dc.FillRoundedRectangle(&rrk, br);
// refração: o trilho embaixo aparece ampliado (mais grosso) dentro da lente
let mut old = mat::ident();
dc.GetTransform(&mut old);
dc.SetTransform(&mat::mul(&mat::scale(1.18, 1.9, kx, cy), &old));
track(dc, br, p, cy, kx - kw * 0.02, TRACK_H);
dc.SetTransform(&old);
// luz por dentro: forte em cima, fraca embaixo
if let Some(lg) = linear(&dc.cast().unwrap(), &[(0.0, col(1.0, 1.0, 1.0, 0.95)), (0.5, col(1.0, 1.0, 1.0, 0.25)), (1.0, col(1.0, 1.0, 1.0, 0.65))], pt(0.0, k.top), pt(0.0, k.bottom)) {
dc.DrawRoundedRectangle(&rr(rf(k.left + 1.2, k.top + 1.2, k.right - 1.2, k.bottom - 1.2), rad - 1.2, rad - 1.2), &lg, 1.4, None);
}
dc.PopLayer();
}
// borda: o azul do trilho entortado pela lente
br.SetColor(&col(0.25, 0.62, 1.0, 0.55 * pr));
dc.DrawRoundedRectangle(&rr(rf(k.left + 0.4, k.top + 0.4, k.right - 0.4, k.bottom - 0.4), rad - 0.4, rad - 0.4), br, 0.9, None);
}
}
unsafe fn paint_menu_on(dc: &ID2D1DeviceContext, fade: f32) {
let st = s();
let (mw_, h, r) = (mw(), menu_h(), menu_r());
let p = colors();
let dark = ui::dark();
let tf = tfs();
let Ok(br) = dc.CreateSolidColorBrush(&p.text, None) else { return };
let rt: ID2D1RenderTarget = dc.cast().unwrap();
let all = rf(0.0, 0.0, mw_, h);
if st.foto {
backdrop::foto_vidro(dc, all, r, p.tint);
}
layer(dc, fade, None);
if !st.m.glass && !st.foto {
br.SetColor(&if dark { col(0.17, 0.17, 0.18, 0.80) } else { col(0.965, 0.965, 0.965, 0.80) });
dc.FillRoundedRectangle(&rr(all, r, r), &br);
}
if liquid::on() {
liquid::rim0(&rt, all, r, dark);
} else {
// borda dos menus do Sequoia: escura por fora, clara por dentro
br.SetColor(&if dark { col(0.0, 0.0, 0.0, 0.45) } else { col(0.0, 0.0, 0.0, 0.12) });
dc.DrawRoundedRectangle(&rr(rf(0.5, 0.5, mw_ - 0.5, h - 0.5), r, r), &br, 1.0, None);
br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.14) } else { col(1.0, 1.0, 1.0, 0.5) });
dc.DrawRoundedRectangle(&rr(rf(1.5, 1.5, mw_ - 1.5, h - 1.5), r - 1.0, r - 1.0), &br, 1.0, None);
}
st.hits.clear();
text(dc, &br, &tr("Som"), rf(14.0, 8.0, mw_ - 14.0, 32.0), &tf[0], p.text);
slider(dc, &br, &p, if st.mute { 0.0 } else { st.vol });
let px = 1.0 / sc_menu();
let sep = |y: f32| {
br.SetColor(&p.sep);
dc.FillRectangle(&rf(10.0, y, mw_ - 10.0, y + px), &br);
};
sep(60.0);
text(dc, &br, &tr("Saída"), rf(14.0, 62.0, mw_ - 14.0, 82.0), &tf[1], p.text2);
for (i, o) in st.outs.iter().enumerate() {
let y = ROWS_Y + ROW_H * i as f32;
let cy = y + ROW_H / 2.0;
let row = rf(5.0, y + 1.0, mw_ - 5.0, y + ROW_H - 1.0);
if st.hover == Some(HitId::Out(i)) {
br.SetColor(&p.hover);
dc.FillRoundedRectangle(&rr(row, 7.0, 7.0), &br);
}
let (r_, cx) = (13.0, 27.0);
br.SetColor(&if o.def { BLUE } else { p.circle });
dc.FillEllipse(&ell(pt(cx, cy), r_, r_), &br);
let sname = out_symbol(o);
let gh = if sname == "headphones" { 7.5 } else { 6.5 };
sym(dc, &br, sname, rf(cx - 8.0, cy - gh, cx + 8.0, cy + gh), if o.def { col(1.0, 1.0, 1.0, 1.0) } else { p.circle_glyph });
text(dc, &br, &if o.name.is_empty() { tr("(sem nome)") } else { o.name.clone() }, rf(48.0, y, mw_ - 14.0, y + ROW_H), &tf[2], p.text);
st.hits.push((HitId::Out(i), row));
}
let mut s2 = sep_y2();
sep(s2);
if !st.apps.is_empty() {
// Apps: um controle de volume para cada app que está tocando som
text(dc, &br, &tr("Apps"), rf(14.0, s2 + 3.0, mw_ - 14.0, s2 + 23.0), &tf[1], p.text2);
for (i, a) in st.apps.iter().enumerate() {
let y = s2 + 26.0 + APP_H * i as f32;
let cy = y + APP_H / 2.0;
text(dc, &br, &a.name, rf(14.0, y, APP_L - 8.0, y + APP_H), &tf[2], p.text);
let (l, r_) = (APP_L, mw_ - 18.0);
let v = if a.mute { 0.0 } else { a.vol };
let kx = l + 7.0 + v * (r_ - l - 14.0);
br.SetColor(&p.sep);
dc.FillRoundedRectangle(&rr(rf(l, cy - 2.0, r_, cy + 2.0), 2.0, 2.0), &br);
br.SetColor(&BLUE);
dc.FillRoundedRectangle(&rr(rf(l, cy - 2.0, kx, cy + 2.0), 2.0, 2.0), &br);
shadow(dc, &br, rf(kx - 7.0, cy - 7.0, kx + 7.0, cy + 7.0), 7.0, 0.16);
br.SetColor(&if st.drag_app == Some(i) { col(0.93, 0.93, 0.94, 1.0) } else { col(1.0, 1.0, 1.0, 1.0) });
dc.FillEllipse(&ell(pt(kx, cy), 7.0, 7.0), &br);
br.SetColor(&col(0.0, 0.0, 0.0, if dark { 0.25 } else { 0.12 }));
dc.DrawEllipse(&ell(pt(kx, cy), 6.75, 6.75), &br, 0.5, None);
st.hits.push((HitId::App(i), rf(l - 8.0, y + 2.0, r_ + 8.0, y + APP_H - 2.0)));
}
s2 = sep_y3();
sep(s2);
}
let set = rf(5.0, s2 + 5.0, mw_ - 5.0, s2 + 28.0);
if st.hover == Some(HitId::Settings) {
br.SetColor(&p.hover);
dc.FillRoundedRectangle(&rr(set, 6.0, 6.0), &br);
}
text(dc, &br, &tr("Ajustes de Som…"), rf(14.0, set.top, mw_ - 14.0, set.bottom), &tf[2], p.text);
st.hits.push((HitId::Settings, set));
dc.PopLayer();
}
fn paint_menu() {
let st = s();
if !st.open {
return;
}
let k = sc_menu();
let (wpx, hpx) = ((mw() * k).round() as i32, (menu_h() * k).round() as i32);
let mo = if st.foto { anim::Panel { fade: 1.0, scale: 1.0, done: true } } else { anim::panel_in(anim::now() - st.open_at) };
let Some(dc) = ui::gpu_begin(&mut st.m.s, wpx, hpx, k) else { return };
unsafe { paint_menu_on(&dc, mo.fade) };
ui::gpu_end(&mut st.m.s);
if st.foto {
return;
}
ui::gpu_scale(&st.m.s, mo.scale, wpx as f32 / 2.0, 0.0);
glass_shape(&st.m, wpx, hpx, menu_r() * k, colors().tint, mo.fade, mo.scale, wpx as f32 / 2.0, 0.0);
}
/// lente do Tahoe: aproxima a pressão do alvo e solta o esticão; true enquanto ainda mexe
fn step_knob() -> bool {
let st = s();
let now = anim::now();
let dt = (now - st.last_frame).clamp(1.0, 50.0) as f32;
st.last_frame = now;
let target = if st.drag { 1.0 } else { 0.0 };
let k = 1.0 - (-dt / if st.drag { 55.0 } else { 80.0 }).exp();
st.press += (target - st.press) * k;
if (target - st.press).abs() < 0.004 {
st.press = target;
}
st.stretch *= (-dt / 90.0).exp();
if st.stretch < 0.003 {
st.stretch = 0.0;
}
st.press != target || st.stretch > 0.0
}
fn animate() {
ui::frame_clock(s().m.wnd, WM_SOM_FRAME, true);
}
fn close_menu() {
let st = s();
if !st.open {
return;
}
st.open = false;
st.closed_at = unsafe { GetTickCount() };
unsafe {
if st.drag || st.drag_app.is_some() {
let _ = ReleaseCapture();
}
let _ = KillTimer(st.m.wnd, T_POLL);
}
st.drag = false;
st.drag_app = None;
st.press = 0.0;
st.stretch = 0.0;
st.hover = None;
st.apps.clear();
ui::frame_clock(st.m.wnd, WM_SOM_FRAME, false);
glass_hide(&st.m);
menubar::sound_changed(false); // o destaque do ícone sai
}
fn drag_to(x: f32) {
let st = s();
let v = value_at(x);
let kx = knob_x(v);
if st.last_kx >= 0.0 && liquid::on() {
// esticão: proporcional à velocidade do botão
let dx = (kx - st.last_kx).abs();
st.stretch = 0.32f32.min(st.stretch.max(dx * 0.018));
}
st.last_kx = kx;
set_volume(v);
paint_menu();
animate();
}
fn hit_at(x: f32, y: f32) -> Option<HitId> {
s().hits.iter().find(|(_, r)| in_rect(r, x, y)).map(|h| h.0)
}
fn app_value(x: f32) -> f32 {
(x - APP_L - 7.0) / (mw() - 18.0 - APP_L - 14.0)
}
fn replace_menu(h: HWND) {
// o menu muda de altura (a lista de saídas ou de apps mudou)
let mut wr = RECT::default();
unsafe {
let _ = GetWindowRect(h, &mut wr);
}
let k = sc_menu();
glass_place(&s().m, wr.left, wr.top, (mw() * k).round() as i32, (menu_h() * k).round() as i32, false);
}
fn apps_key() -> String {
s().apps.iter().map(|a| format!("{}|{}|", a.exe, a.vol)).collect()
}
unsafe extern "system" fn menu_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
let st = s();
let k = ui::scale(h);
let (px, py) = (get_x_lparam(l) as f32 / k, get_y_lparam(l) as f32 / k);
match m {
WM_PAINT => {
let mut ps = PAINTSTRUCT::default();
BeginPaint(h, &mut ps);
let _ = EndPaint(h, &ps);
paint_menu();
LRESULT(0)
}
WM_SOM_FRAME => {
ui::frame_ack(h, WM_SOM_FRAME);
let moving = step_knob();
paint_menu();
if !moving && anim::panel_in(anim::now() - st.open_at).done {
ui::frame_clock(h, WM_SOM_FRAME, false);
}
LRESULT(0)
}
WM_TIMER => {
// volume mudado por fora (teclas, outros apps) aparece no controle
if w_.0 == T_POLL && st.open && !st.drag && st.drag_app.is_none() {
let (v, mu, n) = (st.vol, st.mute, st.outs.len());
read(false);
let antes = apps_key();
read_apps();
let depois = apps_key();
if antes != depois {
replace_menu(h); // um app começou ou parou de tocar
}
if v != st.vol || mu != st.mute || n != st.outs.len() || antes != depois {
paint_menu();
}
}
LRESULT(0)
}
WM_LBUTTONDOWN => {
match hit_at(px, py) {
Some(HitId::Slider) => {
st.drag = true;
st.last_kx = -1.0;
st.last_frame = anim::now();
SetCapture(h);
drag_to(px);
}
Some(HitId::App(i)) => {
st.drag_app = Some(i);
SetCapture(h);
set_app_volume(i, app_value(px));
paint_menu();
}
Some(HitId::Settings) => {
close_menu();
shell::open_settings("som");
}
Some(HitId::Out(i)) => {
if !st.outs[i].def {
let id = st.outs[i].id.clone();
set_default(&id);
if matches!(st.hover, Some(HitId::Out(j)) if j >= st.outs.len()) {
st.hover = None;
}
replace_menu(h);
paint_menu();
}
}
None => {}
}
LRESULT(0)
}
WM_MOUSEMOVE => {
if st.drag {
drag_to(px);
return LRESULT(0);
}
if let Some(i) = st.drag_app {
set_app_volume(i, app_value(px));
paint_menu();
return LRESULT(0);
}
let mut t = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };
let _ = TrackMouseEvent(&mut t);
let hv = match hit_at(px, py) {
x @ Some(HitId::Settings | HitId::Out(_)) => x,
_ => None,
};
if hv != st.hover {
st.hover = hv;
paint_menu();
}
LRESULT(0)
}
WM_MOUSELEAVE => {
if st.hover.is_some() {
st.hover = None;
paint_menu();
}
LRESULT(0)
}
WM_LBUTTONUP => {
if st.drag_app.is_some() {
st.drag_app = None;
let _ = ReleaseCapture();
paint_menu();
return LRESULT(0);
}
if st.drag {
st.drag = false;
st.last_kx = -1.0;
let _ = ReleaseCapture();
shell::sound("Pop"); // como no Mac: o estalo no volume novo ao soltar
st.last_frame = anim::now();
animate();
}
LRESULT(0)
}
WM_CAPTURECHANGED => {
if l.0 != h.0 as isize {
if st.drag_app.is_some() {
st.drag_app = None;
paint_menu();
}
if st.drag {
st.drag = false;
st.last_kx = -1.0;
animate();
}
}
LRESULT(0)
}
WM_MOUSEWHEEL => {
let d = ((w_.0 >> 16) as u16 as i16) as f32;
set_volume(if st.mute { 0.0 } else { st.vol } + d / 120.0 / 32.0);
paint_menu();
LRESULT(0)
}
WM_KEYDOWN => {
let vk = VIRTUAL_KEY(w_.0 as u16);
if vk == VK_ESCAPE {
close_menu();
} else if vk == VK_RIGHT || vk == VK_UP {
set_volume(st.vol + 1.0 / 16.0);
paint_menu();
} else if vk == VK_LEFT || vk == VK_DOWN {
set_volume(st.vol - 1.0 / 16.0);
paint_menu();
}
LRESULT(0)
}
WM_ACTIVATE => {
if loword(w_.0) == WA_INACTIVE {
close_menu();
}
LRESULT(0)
}
_ => DefWindowProcW(h, m, w_, l),
}
}
// ================= aviso de volume (HUD)
const SQ: f32 = 200.0; // Sequoia: quadrado de 200 pt
const SQ_R: f32 = 18.0;
const PILL_W: f32 = 224.0; // Tahoe: pílula embaixo do ícone
const PILL_H: f32 = 50.0;
const PILL_R: f32 = 15.0;
const HUD_HOLD: u32 = 1500;
const HUD_FADE_SQ: f64 = 400.0;
const HUD_FADE_T: f64 = 260.0;
fn hud_w() -> f32 {
if s().hud_tahoe {
PILL_W
} else {
SQ
}
}
fn hud_h() -> f32 {
if s().hud_tahoe {
PILL_H
} else {
SQ
}
}
fn sc_hud() -> f32 {
if s().foto {
ui::foto_scale()
} else {
ui::scale(s().h.wnd)
}
}
unsafe fn paint_hud_on(dc: &ID2D1DeviceContext, fade: f32, scale: f32, cx: f32, cy: f32, tint: Cor) {
let st = s();
let (ww, hh, r) = (hud_w(), hud_h(), if st.hud_tahoe { PILL_R } else { SQ_R });
let dark = ui::dark();
let p = colors();
let Ok(br) = dc.CreateSolidColorBrush(&p.text, None) else { return };
let rt: ID2D1RenderTarget = dc.cast().unwrap();
let all = rf(0.0, 0.0, ww, hh);
let mut old = mat::ident();
dc.GetTransform(&mut old);
dc.SetTransform(&mat::mul(&mat::scale(scale, scale, cx, cy), &old));
if st.foto {
backdrop::foto_vidro(dc, all, r, tint);
}
layer(dc, fade, None);
if !st.h.glass && !st.foto {
br.SetColor(&if dark { col(0.17, 0.17, 0.18, 0.85) } else { col(0.94, 0.94, 0.95, 0.85) });
dc.FillRoundedRectangle(&rr(all, r, r), &br);
}
let v = if st.mute { 0.0 } else { st.vol };
if !st.hud_tahoe {
if liquid::on() {
liquid::rim0(&rt, all, r, dark);
} else {
br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.10) } else { col(1.0, 1.0, 1.0, 0.35) });
dc.DrawRoundedRectangle(&rr(rf(0.5, 0.5, ww - 0.5, hh - 0.5), r, r), &br, 1.0, None);
}
// alto-falante grande: a caixa é a da versão com 3 ondas, alinhada à esquerda (o corpo não pula)
let ink = if dark { col(1.0, 1.0, 1.0, 0.85) } else { col(0.05, 0.04, 0.12, 0.78) };
let sname = level_symbol(st.vol, st.mute);
let gw = match sname {
"speaker.wave.3.fill" => 108.0,
"speaker.wave.2.fill" | "speaker.slash.fill" => 92.0,
"speaker.wave.1.fill" => 76.0,
_ => 58.0,
};
let left = ww / 2.0 - 54.0;
sym(dc, &br, sname, rf(left, 46.0, left + gw, 118.0), ink);
// barra de 16 segmentos: trilho escuro, segmentos claros (com 1/64 de passo, o último pela metade)
let (bx, bw, by, bh, gap) = (19.0, ww - 38.0, 172.0, 9.0, 1.2);
br.SetColor(&if dark { col(0.0, 0.0, 0.0, 0.55) } else { col(0.05, 0.04, 0.12, 0.72) });
dc.FillRectangle(&rf(bx, by, bx + bw, by + bh), &br);
let seg_w = (bw - gap * 17.0) / 16.0;
let filled = v * 16.0;
br.SetColor(&col(1.0, 1.0, 1.0, if dark { 0.92 } else { 0.95 }));
for i in 0..16 {
let f = (filled - i as f32).clamp(0.0, 1.0);
if f <= 0.01 {
break;
}
let x0 = bx + gap + i as f32 * (seg_w + gap);
dc.FillRectangle(&rf(x0, by + gap, x0 + seg_w * f, by + bh - gap), &br);
}
} else {
liquid::rim0(&rt, all, r, dark);
let ink = if dark { col(1.0, 1.0, 1.0, 0.95) } else { col(0.0, 0.0, 0.0, 0.82) };
let ink2 = if dark { col(1.0, 1.0, 1.0, 0.75) } else { col(0.0, 0.0, 0.0, 0.55) };
text(dc, &br, &if st.name.is_empty() { tr("Saída de Som") } else { st.name.clone() }, rf(12.0, 5.0, ww - 12.0, 21.0), &tfs()[3], ink);
let (tl, tr_, ty) = (30.0, ww - 32.0, 30.0);
sym(dc, &br, if st.mute || v < 0.001 { "speaker.slash.fill" } else { "speaker.fill" }, rf(11.0, ty - 5.0, 24.0, ty + 5.0), ink2);
sym(dc, &br, "speaker.wave.3.fill", rf(tr_ + 6.0, ty - 5.5, tr_ + 22.0, ty + 5.5), ink2);
br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.22) } else { col(0.0, 0.0, 0.0, 0.14) });
dc.FillRoundedRectangle(&rr(rf(tl, ty - 2.5, tr_, ty + 2.5), 2.5, 2.5), &br);
br.SetColor(&ink);
if v > 0.001 {
dc.FillRoundedRectangle(&rr(rf(tl, ty - 2.5, tl + 5.0f32.max(v * (tr_ - tl)), ty + 2.5), 2.5, 2.5), &br);
}
// pontinhos de marcação: um a cada passo da tecla (16 passos, 17 pontos)
br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.55) } else { col(0.0, 0.0, 0.0, 0.38) });
for i in 0..=16 {
dc.FillEllipse(&ell(pt(tl + 1.2 + (tr_ - tl - 2.4) * i as f32 / 16.0, ty + 9.5), 1.2, 1.2), &br);
}
}
dc.PopLayer();
dc.SetTransform(&old);
}
fn paint_hud() {
let st = s();
if !st.hud_on {
return;
}
let k = sc_hud();
let (ww, hh) = (hud_w(), hud_h());
let (wpx, hpx) = ((ww * k).round() as i32, (hh * k).round() as i32);
let now = anim::now();
let (mut fade, mut scale) = (1.0f32, 1.0f32);
if st.hud_tahoe && !st.foto {
// aparece crescendo um pouco a partir do ícone, com a mola do Mac
let sp = anim::spring(((now - st.hud_shown_at) / 1000.0) as f32, 0.38, 0.8);
scale = 0.86 + 0.14 * sp;
fade = (((now - st.hud_shown_at) / 120.0) as f32).min(1.0);
}
if st.hud_fade_at > 0.0 {
let f = (1.0 - ((now - st.hud_fade_at) / if st.hud_tahoe { HUD_FADE_T } else { HUD_FADE_SQ }) as f32).clamp(0.0, 1.0);
fade *= f;
if st.hud_tahoe {
scale *= 0.96 + 0.04 * f;
}
}
let dark = ui::dark();
let (cx, cy) = if st.hud_tahoe { (ww * 0.7, 0.0) } else { (ww / 2.0, hh / 2.0) }; // centro da escala (Tahoe: perto do ícone)
let tint = if st.hud_tahoe {
if dark {
col(0.12, 0.12, 0.14, 0.45)
} else {
col(1.0, 1.0, 1.0, 0.40)
}
} else if dark {
col(0.14, 0.14, 0.15, 0.55)
} else {
col(0.93, 0.93, 0.95, 0.45)
};
let Some(dc) = ui::gpu_begin(&mut st.h.s, wpx, hpx, k) else { return };
unsafe { paint_hud_on(&dc, fade, scale, cx, cy, tint) };
ui::gpu_end(&mut st.h.s);
if !st.foto {
glass_shape(&st.h, wpx, hpx, if st.hud_tahoe { PILL_R } else { SQ_R } * k, tint, fade, scale, cx * k, cy * k);
}
}
fn hide_hud() {
let st = s();
if !st.hud_on {
return;
}
st.hud_on = false;
unsafe {
let _ = KillTimer(st.h.wnd, T_FADE);
}
ui::frame_clock(st.h.wnd, WM_HUD_FRAME, false);
glass_hide(&st.h);
menubar::sound_changed(false);
}
/// onde fica o aviso (px de tela): Tahoe logo abaixo da barra, com o ícone de som perto da ponta direita; Sequoia no
/// centro, embaixo (acima do Dock)
fn hud_pos(mon: RECT, icon: Option<RECT>, k: f32, top_inset: i32) -> (i32, i32) {
let (w_, h) = ((hud_w() * k).round() as i32, (hud_h() * k).round() as i32);
if s().hud_tahoe {
let right = match icon {
Some(i) => (i.left + i.right) / 2 + (56.0 * k).round() as i32,
None => mon.right - (10.0 * k).round() as i32,
};
let x = right - w_;
let x = x.min(mon.right - w_ - (6.0 * k) as i32).max(mon.left + (6.0 * k) as i32);
(x, mon.top + top_inset + (6.0 * k).round() as i32)
} else {
(mon.left + (mon.right - mon.left - w_) / 2, mon.bottom - (140.0 * k).round() as i32 - h)
}
}
fn place_hud() {
let st = s();
let icon = menubar::sound_icon();
let rp = icon.map(|i| POINT { x: (i.left + i.right) / 2, y: i.bottom }).unwrap_or_default();
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
unsafe {
let _ = GetMonitorInfoW(MonitorFromPoint(rp, MONITOR_DEFAULTTOPRIMARY), &mut mi);
}
// a escala segue o monitor da barra (o aviso pode estar em outro)
let dpi = unsafe { GetDpiForWindow(menubar::hwnd()) };
let k = if dpi != 0 { dpi as f32 / 96.0 } else { ui::scale(st.h.wnd) };
let (x, y) = hud_pos(mi.rcMonitor, icon, k, menubar::top_inset());
glass_place(&st.h, x, y, (hud_w() * k).round() as i32, (hud_h() * k).round() as i32, false);
}
fn show_hud() {
let st = s();
let tahoe = liquid::on();
let now = anim::now();
let fresh = !st.hud_on || tahoe != st.hud_tahoe || (st.hud_fade_at > 0.0 && now - st.hud_fade_at > 120.0);
st.hud_tahoe = tahoe;
if fresh {
st.hud_shown_at = now;
}
st.hud_fade_at = 0.0;
st.hud_on = true;
if fresh {
place_hud();
}
paint_hud();
unsafe {
SetTimer(st.h.wnd, T_FADE, HUD_HOLD, None);
}
ui::frame_clock(st.h.wnd, WM_HUD_FRAME, true);
menubar::sound_changed(false);
}
unsafe extern "system" fn hud_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
let st = s();
match m {
WM_PAINT => {
let mut ps = PAINTSTRUCT::default();
BeginPaint(h, &mut ps);
let _ = EndPaint(h, &ps);
paint_hud();
LRESULT(0)
}
WM_MOUSEACTIVATE => LRESULT(MA_NOACTIVATE as isize),
WM_VOL_FORA => {
// issue #172: volume mudado fora do Shell (fone, teclado externo)
if w_.0 == 1 {
registra_volume();
read(false);
return LRESULT(0);
}
let (antes, mudo_antes) = (st.vol, st.mute);
read(false);
let em = VOL_REG.get().as_ref().map(|r| r.em).unwrap_or(0);
if !st.ok || GetTickCount().wrapping_sub(em) < 1500 {
return LRESULT(0);
}
if (st.vol - antes).abs() < 0.004 && st.mute == mudo_antes {
return LRESULT(0); // nada que se veja
}
menubar::sound_changed(false);
if st.open {
paint_menu();
return LRESULT(0);
}
if central::is_open() {
return LRESULT(0); // o controle de som da Central de Controle sendo arrastado
}
if shell::setting("aviso_volume_fora", "1") == "0" {
return LRESULT(0);
}
if ilha::volume(if st.mute { 0.0 } else { st.vol }, st.mute) {
hide_hud();
return LRESULT(0);
}
show_hud();
LRESULT(0)
}
WM_TIMER => {
if w_.0 == T_FADE {
let _ = KillTimer(h, T_FADE);
st.hud_fade_at = anim::now();
ui::frame_clock(h, WM_HUD_FRAME, true);
}
LRESULT(0)
}
WM_HUD_FRAME => {
ui::frame_ack(h, WM_HUD_FRAME);
let now = anim::now();
if st.hud_fade_at > 0.0 && now - st.hud_fade_at >= if st.hud_tahoe { HUD_FADE_T } else { HUD_FADE_SQ } {
hide_hud();
return LRESULT(0);
}
paint_hud();
let appearing = st.hud_tahoe && now - st.hud_shown_at < 700.0;
if !appearing && st.hud_fade_at == 0.0 {
ui::frame_clock(h, WM_HUD_FRAME, false);
}
LRESULT(0)
}
_ => DefWindowProcW(h, m, w_, l),
}
}
// ================= API
pub fn create(hi: HINSTANCE) -> bool {
let st = s();
if !unsafe { make_glass(&mut st.m, hi, w!("ShellSomMenu"), Some(menu_proc), false, w!("Som")) && make_glass(&mut st.h, hi, w!("ShellSomAviso"), Some(hud_proc), true, w!("Volume")) } {
return false;
}
if !shell::foto() {
// issue #172: o aviso também para o volume mudado por fora; a troca da saída padrão passa o aviso para a nova
VOL_AVISO.store(st.h.wnd.0 as isize, std::sync::atomic::Ordering::Relaxed);
read(false);
let obj: IUnknown = VolCb.into();
if let (Ok(cb), Ok(nc)) = (obj.cast::<Endpoints::IAudioEndpointVolumeCallback>(), obj.cast::<IMMNotificationClient>()) {
let en = enumerator();
if let Some(e) = &en {
let _ = unsafe { e.RegisterEndpointNotificationCallback(&nc) };
}
*VOL_REG.get() = Some(VolReg { cb, ep: None, em: 0, en });
registra_volume();
}
}
true
}
pub fn is_open() -> bool {
s().open
}
pub fn hud_lit() -> bool {
s().hud_on && s().hud_tahoe
}
pub fn toggle(icon: RECT) {
let st = s();
if st.open {
close_menu();
return;
}
if unsafe { GetTickCount() }.wrapping_sub(st.closed_at) < 300 {
return; // o clique no ícone acabou de fechar o menu (perdeu o foco)
}
hide_hud();
read(true);
read_apps();
st.mw = if liquid::on() { 308.0 } else { 320.0 };
st.open = true;
st.open_at = anim::now();
st.hover = None;
st.press = 0.0;
st.stretch = 0.0;
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
unsafe {
let _ = GetMonitorInfoW(MonitorFromPoint(POINT { x: icon.left, y: icon.bottom }, MONITOR_DEFAULTTOPRIMARY), &mut mi);
}
let k = ui::scale(menubar::hwnd());
let (w_, h) = ((mw() * k).round() as i32, (menu_h() * k).round() as i32);
let x = icon.left.min(mi.rcMonitor.right - w_ - (5.0 * k) as i32).max(mi.rcMonitor.left + (5.0 * k) as i32);
let mut y = icon.bottom + ((if liquid::on() { 3.0 } else { 1.0 }) * k).round() as i32;
if menubar::embaixo() {
y = mi.rcMonitor.top.max(icon.top - h - (6.0 * k).round() as i32); // abre para cima
}
glass_place(&st.m, x, y, w_, h, true);
paint_menu();
unsafe {
let _ = SetForegroundWindow(st.m.wnd);
let _ = SetFocus(st.m.wnd);
SetTimer(st.m.wnd, T_POLL, 500, None);
}
animate();
menubar::sound_changed(false); // destaque do ícone
}
/// tecla de volume/mudo (fino: Shift+Alt, quartos de passo, como Shift+Option no Mac)
pub fn key(vk: u32, fine: bool) {
let st = s();
read(false);
if !st.ok {
return;
}
let steps = if fine { 64.0 } else { 16.0 };
let vk = VIRTUAL_KEY(vk as u16);
if vk == VK_VOLUME_MUTE {
set_mute(!st.mute);
} else if vk == VK_VOLUME_UP {
let mut v = (((st.vol * steps + 0.5).floor() + 1.0) / steps).min(1.0);
if st.mute && st.vol > 0.001 {
v = st.vol; // estava mudo: volta ao volume de antes
}
set_volume(v);
} else if vk == VK_VOLUME_DOWN {
let v = (((st.vol * steps + 0.5).floor() - 1.0) / steps).max(0.0);
set_volume(if st.mute { 0.0 } else { v });
}
if st.open {
paint_menu(); // com o menu aberto, o controle dele mostra
return;
}
if ilha::volume(if st.mute { 0.0 } else { st.vol }, st.mute) {
hide_hud(); // Ilha Dinâmica ligada: o volume aparece nela
return;
}
show_hud();
}
/// modo foto: o menu aberto embaixo do ícone (padrão) ou, com `aviso`, o aviso de volume; lê o volume e as saídas de
/// verdade, nada muda
pub fn foto(tela_w: f32, tela_h: f32, aviso: bool) {
let st = s();
st.foto = true;
read(true);
let k = ui::foto_scale();
let bar = menubar::bar_pt();
if aviso {
st.hud_tahoe = liquid::on();
st.hud_on = true;
// o ícone de som fica perto da ponta direita da barra (antes do relógio e da Central)
let icon = RECT { left: ((tela_w - 200.0) * k) as i32, top: 0, right: ((tela_w - 180.0) * k) as i32, bottom: (bar * k) as i32 };
let (x, y) = hud_pos(RECT { left: 0, top: 0, right: (tela_w * k) as i32, bottom: (tela_h * k) as i32 }, Some(icon), k, (bar * k) as i32);
st.h.s.foto_pos = (x as f32, y as f32);
paint_hud();
return;
}
read_apps();
st.mw = if liquid::on() { 308.0 } else { 320.0 };
st.open = true;
st.m.s.foto_pos = (((tela_w - 200.0 - 10.0) * k).min((tela_w - mw() - 5.0) * k), (bar + if liquid::on() { 3.0 } else { 1.0 }) * k);
paint_menu();
}