Files
VoelinClient/crates/voelin-gpui/src/shell/sidebar.rs
T
faumarayandGemini 4 Neon a16e4d4b93 voelin-gpui: harden push-to-talk and global hotkey transmit state machine
Track the window hold-to-talk button (`button_held`) beside the global hotkey (`hotkey_held`) and a `shutting_down` flag in `AppState`, closing Security Review MEDIUM #2 and Opus gate probes P1, P2, P3, P4, P5, P6, and P8:

- `stop_transmitting_if_unheld`, `release_button_hold`, and `release_hotkey_hold` keep transmit active while either source holds the session and avoid duplicate start/stop commands (P6).
- `hotkey_transmit(true)` on a different connected server stops the previous held session before starting the new one (Security MEDIUM #2 / P2), while `select_server` preserves `hotkey_held` (P2b) and releases `button_held` when the held server leaves the screen (P8).
- `handle_events` checks `Connected -> !Connected` transitions per event inside the batch loop so a drop and reconnect within one 64-event batch still releases both holds and emits `SetTransmitting(false)` once (P3).
- `setting_changed` releases `button_held` when `audio.transmit` leaves `PushToTalk` (P1/P1b); `delete_bookmark` clears holds on the removed session (P4); `shutdown` sets `shutting_down`, drops `ptt`, and releases both holds before closing sessions, ignoring late `Later` presses (P5).
- `Sidebar` clears `holding` whenever voice disconnects, transmit leaves push-to-talk, the shown server changes, or `AppState::button_held` no longer matches; `MainView`'s focus-loss observer unconditionally releases `Sidebar` and `AppState::push_to_talk(false)` without cutting `hotkey_held`.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
2026-11-23 08:21:09 +03:00

495 lines
15 KiB
Rust

//! The sidebar (`Sidebar` of `ui/shells/desktop.slint`, with the cards of
//! `shells/common.slint`): the server on screen (its card has the server's
//! banner behind it, under the same veil as the tree's rows), its channel tree
//! ([`super::ChannelTree`], a cached pane of its own), the voice card while
//! voice is connecting or connected, and the user's own card with the voice
//! buttons. An entity of its own: it listens to the servers' and the toolbar's
//! signals and tells the window only when what it shows changed.
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
Context, Entity, FontWeight, InteractiveElement as _, IntoElement, MouseButton, MouseUpEvent,
ObjectFit, ParentElement as _, Render, StatefulInteractiveElement as _, StyleRefinement,
Styled as _, StyledImage as _, Subscription, Window, div, px,
};
use voelin_core::TransmitMode;
use voelin_ui_vm::Rgb;
use voelin_ui_vm::bridge::ServerItem;
use voelin_ui_vm::image::ImageRef;
use voelin_ui_vm::servers::logic;
use super::actions::{
DisconnectVoice, Invite, OpenSettings, PushToTalk, SetInputMuted, SetOutputMuted,
};
use super::channels::ChannelTree;
use super::widgets::{Avatar, IconButton, Presence, banner_scrim, card, icon, panel};
use crate::app::AppState;
use crate::meter::Counters;
use crate::pictures::{PictureKey, picture};
use crate::signals::Area;
use crate::theme::{VoelinTheme, hsla};
/// What the sidebar shows.
#[derive(Clone, Debug, PartialEq)]
pub struct SidebarView {
/// The server on screen, as the rail has it.
pub server: Option<ServerItem>,
/// "9 online · 7 channels" once its presence is known, else empty.
pub stats: String,
/// The server's banner, behind its card; empty without one.
pub server_banner: ImageRef,
/// Our nickname there; empty without a server.
pub nickname: String,
/// The channel we are in; empty while connecting.
pub own_channel: String,
/// Our picture on the server.
pub own_avatar: ImageRef,
/// Voice is connected.
pub voice_connected: bool,
/// Voice is connecting.
pub voice_connecting: bool,
/// The server is observed.
pub observing: bool,
/// Our microphone is muted.
pub input_muted: bool,
/// Our sound is muted.
pub output_muted: bool,
/// Voice goes out.
pub transmitting: bool,
/// The transmit mode is push-to-talk, so the card has a hold-to-talk button.
pub hold_to_talk: bool,
/// How our voice is sent, as the audio settings say: the card has the
/// button for push-to-talk and says the mode otherwise.
pub transmit: TransmitMode,
}
impl SidebarView {
/// The sidebar for the state.
pub fn of(app: &AppState) -> Self {
let card = logic::toolbar(&app.vm, |bookmark| app.server_icon(bookmark));
let server = app.vm.current.and_then(|id| {
logic::rail(&app.vm, |bookmark| app.server_icon(bookmark))
.into_iter()
.find(|item| i64::from(item.id) == id)
});
Self {
server,
stats: card.server_stats,
server_banner: card.server_banner,
nickname: card.nickname,
own_channel: card.own_channel,
own_avatar: card.own_avatar,
voice_connected: card.voice_connected,
voice_connecting: card.voice_connecting,
observing: card.observing,
input_muted: card.input_muted,
output_muted: card.output_muted,
transmitting: card.transmitting,
hold_to_talk: app.vm.audio.transmit == TransmitMode::PushToTalk,
transmit: app.vm.audio.transmit,
}
}
}
/// The sidebar.
pub struct Sidebar {
view: SidebarView,
/// The channel tree, a pane of its own between the server card and the
/// voice card.
tree: Entity<ChannelTree>,
/// The hold-to-talk button is held down.
holding: bool,
counters: Counters,
_subscriptions: Vec<Subscription>,
}
impl Sidebar {
/// A sidebar that follows the server on screen and the voice state in
/// `app`, with `tree` between its cards.
pub fn new(app: &Entity<AppState>, tree: Entity<ChannelTree>, cx: &mut Context<Self>) -> Self {
let (view, counters, signals) = {
let state = app.read(cx);
(SidebarView::of(state), state.counters().clone(), state.signals().clone())
};
let subscriptions =
signals.watch(app, &[Area::Servers, Area::Toolbar], cx, |this: &mut Self, app, cx| {
let state = app.read(cx);
let view = SidebarView::of(state);
// The button goes away when voice leaves `Connected`, transmit
// leaves push-to-talk, or another server is shown; and a drop
// and reconnect inside one batch ends the hold in `AppState`
// while `view.voice_connected` stays true. Keep `holding` in
// sync with the root state's own button hold (this observer
// only sets its own fields).
let same_server =
view.server.as_ref().map(|s| s.id) == this.view.server.as_ref().map(|s| s.id);
let held_here = view
.server
.as_ref()
.is_some_and(|s| state.button_held() == Some(i64::from(s.id)));
if !view.voice_connected || !view.hold_to_talk || !same_server || !held_here {
this.holding = false;
}
if view != this.view {
this.view = view;
cx.notify();
}
});
Self { view, tree, holding: false, counters, _subscriptions: subscriptions }
}
/// What it shows now.
pub fn view(&self) -> &SidebarView {
&self.view
}
/// Whether the hold-to-talk button is currently held down.
#[cfg(test)]
pub(crate) fn is_holding(&self) -> bool {
self.holding
}
/// Let go of the hold-to-talk button if it is held (the window lost the
/// focus: the release will not come to it): whether it was held. The caller
/// tells the session.
pub fn release(&mut self) -> bool {
std::mem::take(&mut self.holding)
}
/// The hold-to-talk button was released, if it was held.
fn let_go(&mut self, _: &MouseUpEvent, window: &mut Window, cx: &mut Context<Self>) {
if std::mem::take(&mut self.holding) {
window.dispatch_action(Box::new(PushToTalk { on: false }), cx);
}
}
}
/// The server's name, its icon and how many are there, over its banner when it
/// has one (`ServerHeader` of `channels.slint`: the picture covers the card,
/// the surface veil of `banner-picture.slint` lies over it, and the stats read
/// in the text colour instead of the secondary one).
fn server_card(theme: &VoelinTheme, view: &SidebarView, item: &ServerItem) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let stats = if view.stats.is_empty() { item.address.to_string() } else { view.stats.clone() };
let banner = PictureKey::of(&view.server_banner);
let ink = if banner.is_some() { c.text } else { c.text_muted };
card(theme, 0xff)
.id("sidebar-server")
.debug_selector(|| "sidebar-server".into())
.relative()
.overflow_hidden()
.p(px(m.space_3))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.when_some(banner, |card, key| {
card.child(
div()
.id("sidebar-server-banner")
.debug_selector(|| "sidebar-server-banner".into())
.absolute()
.top(px(0.0))
.left(px(0.0))
.size_full()
// The picture covers the card and is cropped to it, not past
// its border.
.overflow_hidden()
.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
)
.child(div().absolute().top(px(0.0)).left(px(0.0)).size_full().bg(banner_scrim(theme)))
})
.child(
Avatar::new("sidebar-server-avatar", 40.0, &item.initials, item.tint)
.image(item.icon.clone())
.square(),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.truncate()
.text_size(px(m.font_lg))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(item.name.to_string()),
)
.child(
div().truncate().text_size(px(m.font_sm)).text_color(hsla(ink)).child(stats),
),
)
}
/// How our voice is sent, in words, for the modes that have no button.
fn transmit_words(mode: TransmitMode) -> &'static str {
match mode {
TransmitMode::PushToTalk => "Push to talk",
TransmitMode::VoiceActivation => "Voice activity",
TransmitMode::Continuous => "Open microphone",
}
}
/// "Voice Connected" and our channel, disconnect, and Hold to talk in the
/// push-to-talk mode (the other modes say themselves).
fn voice_card(
theme: &VoelinTheme,
view: &SidebarView,
cx: &mut Context<Sidebar>,
) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let (dot, words) = if view.voice_connected {
(c.success, "Voice Connected")
} else {
(c.warning, "Connecting…")
};
let talking = view.transmitting;
card(theme, 0xff)
.id("sidebar-voice")
.debug_selector(|| "sidebar-voice".into())
.p(px(m.space_3))
.flex()
.flex_col()
.gap(px(m.space_3))
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(div().size(px(10.0)).flex_none().rounded(px(5.0)).bg(hsla(dot)))
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.text_size(px(m.font_sm))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(dot))
.child(words),
)
.when(!view.own_channel.is_empty(), |column| {
column.child(
div()
.truncate()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(view.own_channel.clone()),
)
}),
)
.when(view.voice_connected && !view.own_channel.is_empty(), |row| {
row.child(
IconButton::new("voice-invite", "link", "Copy an invite to this channel")
.size(32.0)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(Invite), cx);
}),
)
})
.child(
IconButton::new("voice-disconnect", "phone-off", "Disconnect")
.size(32.0)
.tint(c.danger)
.on_click(|_, window, cx| {
window.dispatch_action(Box::new(DisconnectVoice), cx);
}),
),
)
.when(view.voice_connected && !view.hold_to_talk, |card| {
card.child(
div()
.id("transmit-mode")
.debug_selector(|| "transmit-mode".into())
.h(px(m.control_height_sm))
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_2))
.child(icon("mic", m.icon_sm, c.text_muted))
.child(
div()
.text_size(px(m.font_sm))
.text_color(hsla(c.text_muted))
.child(transmit_words(view.transmit)),
),
)
})
.when(view.voice_connected && view.hold_to_talk, |card| {
card.child(
div()
.id("hold-to-talk")
.debug_selector(|| "hold-to-talk".into())
.h(px(m.control_height))
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(m.space_2))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(if talking { c.success } else { c.border }))
.bg(hsla(if talking { c.success.with_alpha(0xcc) } else { c.surface_2 }))
.cursor_pointer()
.hover(move |style| {
style.bg(hsla(if talking { c.success } else { c.surface_3 }))
})
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, _, window, cx| {
this.holding = true;
window.dispatch_action(Box::new(PushToTalk { on: true }), cx);
}),
)
// Let go on the button or off it: the end of what was started.
.on_mouse_up(MouseButton::Left, cx.listener(Sidebar::let_go))
.on_mouse_up_out(MouseButton::Left, cx.listener(Sidebar::let_go))
.child(icon(
"mic",
m.icon_sm,
if talking { c.on_accent } else { c.text_secondary },
))
.child(
div()
.text_size(px(m.font_sm))
.font_weight(FontWeight::MEDIUM)
.text_color(hsla(if talking { c.on_accent } else { c.text_secondary }))
.child(if talking { "Talking…" } else { "Hold to talk" }),
),
)
})
}
/// Who we are, and the buttons for the microphone and the sound.
fn user_card(theme: &VoelinTheme, view: &SidebarView) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let (words, presence) = if view.voice_connected {
("Online", Presence::Online)
} else if view.observing {
("Observing", Presence::Info)
} else {
("Offline", Presence::Offline)
};
let name = if view.nickname.is_empty() {
voelin_platform::APP_NAME.to_owned()
} else {
view.nickname.clone()
};
let (input_muted, output_muted) = (view.input_muted, view.output_muted);
card(theme, 0xb3)
.id("sidebar-user")
.debug_selector(|| "sidebar-user".into())
.min_h(px(60.0))
.p(px(m.space_2))
.flex()
.flex_row()
.items_center()
.gap(px(m.space_2))
.child(
div()
.id("sidebar-profile")
.flex_1()
.min_w_0()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.px(px(m.space_2))
.py(px(m.space_2))
.rounded(px(m.radius_md))
.cursor_pointer()
.hover(|style| style.bg(hsla(c.surface_3)))
.on_click(|_, window, cx| window.dispatch_action(Box::new(OpenSettings), cx))
.child(
Avatar::new("sidebar-own-avatar", 38.0, &name_initials(&name), Rgb(0x2d6bff))
.image(view.own_avatar.clone())
.presence(presence)
.speaking(view.transmitting),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.truncate()
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(c.text))
.child(name),
)
.child(
div()
.truncate()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(words),
),
),
)
.child(
IconButton::new(
"user-mic",
if input_muted { "mic-off" } else { "mic" },
if input_muted { "Microphone off" } else { "Microphone on" },
)
.danger()
.checked(input_muted)
.enabled(view.voice_connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetInputMuted { muted: !input_muted }), cx);
}),
)
.child(
IconButton::new(
"user-sound",
if output_muted { "headphone-off" } else { "headphones" },
if output_muted { "Sound off" } else { "Sound on" },
)
.danger()
.checked(output_muted)
.enabled(view.voice_connected)
.on_click(move |_, window, cx| {
window.dispatch_action(Box::new(SetOutputMuted { muted: !output_muted }), cx);
}),
)
}
/// The initials of a nickname, for the avatar.
fn name_initials(name: &str) -> String {
voelin_ui_vm::avatar::initials(name)
}
impl Render for Sidebar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.panes.sidebar.incr();
let theme = VoelinTheme::global(cx).clone();
let m = &theme.metrics;
let view = &self.view;
panel(&theme)
.id("sidebar")
.w(px(m.sidebar_width))
.h_full()
.flex_none()
.p(px(m.space_3))
.gap(px(m.space_3))
.when_some(view.server.as_ref(), |sidebar, item| {
sidebar.child(server_card(&theme, view, item))
})
// The tree has the room the cards leave, whatever their height.
.child(self.tree.clone().cached(StyleRefinement::default().flex_1().min_h_0().w_full()))
.when(view.voice_connected || view.voice_connecting, |sidebar| {
sidebar.child(voice_card(&theme, view, cx))
})
.child(user_card(&theme, view))
}
}