mod ui; use std::cell::RefCell; use std::rc::Rc; use std::time::Duration; use crate::ui::slint::MainWindow; use anyhow::Result; use slint::ComponentHandle; use tracing::info; use tracing_subscriber::EnvFilter; use vnox_client::audio::AudioPipeline; use vnox_client::audio::PipelineConfig; use vnox_client::identity; use vnox_client::net; use vnox_client::net::NetCommand; use vnox_client::net::NetHandle; use crate::ui::state::{ConnState, UiState}; pub struct AppState { pub(crate) webhooks: Option>, pub(crate) connection_generation: u64, pub(crate) identity: identity::Identity, pub(crate) net: NetHandle, pub(crate) ui: UiState, pub(crate) audio: Option, pub(crate) voice_channel: Option, pub(crate) last_pipeline_config: Option, } fn main() -> Result<()> { ui::i18n::initialize(); let filter = EnvFilter::try_from_default_env() .unwrap_or_else(|_| EnvFilter::new("info,wgpu=warn,wgpu_hal=warn,naga=warn")); tracing_subscriber::fmt().with_env_filter(filter).init(); let Some(identity) = load_identity()? else { return Ok(()); }; info!("identity: {}", identity.short_id()); let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; let _guard = rt.enter(); let net = net::spawn(identity.clone()); let state = Rc::new(RefCell::new(AppState { webhooks: None, connection_generation: 0, identity, net, ui: UiState::default(), audio: None, voice_channel: None, last_pipeline_config: None, })); { let mut s = state.borrow_mut(); crate::ui::preferences::load(&mut s.ui); s.ui.appearance = crate::ui::appearance::AppearancePreferences::load(); s.ui.vault_enabled = identity::is_vault_encrypted(); let user_id = s.identity.pubkey_hex.clone(); let nickname = s.identity.nickname.clone(); s.ui.user_names.insert(user_id, nickname); } let window = MainWindow::new()?; window.set_address_input(state.borrow().ui.connect_input.as_str().into()); refresh_devices(&window); let webhook_net = state.borrow().net.clone(); state.borrow_mut().webhooks = Some(Rc::new(ui::webhooks::WebhookUi::new(Rc::new( move |command| { let net = webhook_net.clone(); tokio::spawn(async move { net.send(command).await; }); }, ))?)); wire_signals(&window, &state); ui::media::wire(&window, &state)?; let timer = slint::Timer::default(); { let state = state.clone(); let weak = window.as_weak(); timer.start( slint::TimerMode::Repeated, Duration::from_millis(16), move || { if let Some(win) = weak.upgrade() { let mut s = state.borrow_mut(); crate::ui::update::process_net_events(&mut s); let own_id = s.identity.pubkey_hex.clone(); let own_nick = s.identity.nickname.clone(); let own_pubkey = s.identity.pubkey_hex.clone(); crate::ui::bridge::sync_ui(&win, &s.ui, &own_id, &own_nick, &own_pubkey); } }, ); } window.run()?; Ok(()) } fn load_identity() -> Result> { match identity::load_or_generate() { Ok(identity) => Ok(Some(identity)), Err(error) if error.downcast_ref::().is_some() => { let dialog = crate::ui::slint::UnlockWindow::new()?; let appearance = crate::ui::appearance::AppearancePreferences::load(); if let Ok(spec) = appearance.resolve() { crate::ui::appearance::apply_unlock(&dialog, &spec); } ui::i18n::set_language(ui::i18n::current()); let unlocked = Rc::new(RefCell::new(None)); let result = unlocked.clone(); let weak = dialog.as_weak(); dialog.on_unlock(move |passphrase| { if let Some(dialog) = weak.upgrade() { match identity::load_with_passphrase(passphrase.as_str()) { Ok(identity) => { *result.borrow_mut() = Some(identity); let _ = dialog.hide(); } Err(_) => dialog.set_error( crate::ui::i18n::text( "Could not unlock your profile. Check your passphrase.", ) .into(), ), } } }); dialog.run()?; let identity = unlocked.borrow_mut().take(); Ok(identity) } Err(error) => Err(error), } } fn refresh_devices(window: &MainWindow) { let devices = vnox_client::audio::devices::enumerate().unwrap_or_default(); let model = |mut items: Vec| { if items.is_empty() { items.push(crate::ui::i18n::text("Default")); } Rc::new(slint::VecModel::from( items .into_iter() .map(slint::SharedString::from) .collect::>(), )) .into() }; window.set_input_devices(model(devices.input_labels)); window.set_output_devices(model(devices.output_labels)); } fn wire_signals(window: &MainWindow, state: &Rc>) { { let state = state.clone(); let weak = window.as_weak(); window.on_open_webhooks(move || { let s = state.borrow(); let Some(window) = weak.upgrade() else { return }; if let Some(webhooks) = &s.webhooks { let channel = s.ui.active_channel .as_deref() .and_then(|id| s.ui.channels.iter().find(|c| c.id == id)); let scope = vnox_client::webhooks::Scope { connection: s.connection_generation, channel_id: channel.map(|c| c.id.clone()).unwrap_or_default(), channel_name: channel.map(|c| c.name.clone()).unwrap_or_default(), guild_id: channel.and_then(|c| c.guild_id.clone()).unwrap_or_default(), }; if let Err(error) = webhooks.open( &window, scope, matches!(s.ui.conn, ConnState::Connected { .. }), ) { tracing::warn!(%error,"Cannot open webhooks"); } } }); } crate::ui::appearance::wire(window, state, !cfg!(test)); ui::i18n::wire(window, !cfg!(test)); crate::ui::avatar::wire(window, state, !cfg!(test)); { let state = state.clone(); window.on_dismiss_status(move || state.borrow_mut().ui.status_msg = None); } { let state = state.clone(); window.on_input_edited(move |text| state.borrow_mut().ui.remember_draft(text.to_string())); } { let state = state.clone(); window .on_address_edited(move |text| state.borrow_mut().ui.connect_input = text.to_string()); } { let state = state.clone(); window.on_auto_reconnect_changed(move |value| state.borrow_mut().ui.auto_reconnect = value); } { let state = state.clone(); window .on_friends_tab_changed(move |tab| state.borrow_mut().ui.friends_tab = tab.to_string()); } { let state = state.clone(); let weak = window.as_weak(); window.on_open_settings(move || { state.borrow_mut().ui.settings_open = true; if let Some(window) = weak.upgrade() { refresh_devices(&window); } }); } { let state = state.clone(); window.on_show_voice_view(move || state.borrow_mut().ui.showing_voice = true); } { let state = state.clone(); window.on_show_friends_view(move || state.borrow_mut().ui.select_friends()); } { let state = state.clone(); window.on_ptt_held(move |held| state.borrow_mut().ui.ptt_held = held); } { let state = state.clone(); window.on_audio_settings_changed(move |input, output, bitrate, mode, volume| { let mut s = state.borrow_mut(); s.ui.mic_device = input.max(0) as usize; s.ui.output_device = output.max(0) as usize; s.ui.voice_bitrate = bitrate.clamp(8.0, 128.0); s.ui.vad_mode = mode.clamp(0, 2) as usize; s.ui.output_volume = volume.clamp(0.0, 100.0); if let Err(error) = crate::ui::preferences::save(&s.ui) { s.ui.status_msg = Some(ui::i18n::Message::with( "Cannot save audio settings: {error}", vec![("error", error.to_string())], )); } }); } { let state = state.clone(); window.on_channel_selected(move |id| { let id = id.to_string(); let mut s = state.borrow_mut(); let is_voice = s.ui.channels .iter() .any(|c| c.id == id && c.kind == "voice"); if is_voice { s.ui.showing_voice = true; s.ui.status_msg = Some("Joining voice channel…".into()); } else { s.ui.select_text_channel(id.clone()); } let net = s.net.clone(); drop(s); tokio::spawn(async move { net.send(NetCommand::JoinChannel { channel_id: id }).await; }); }); } { let state = state.clone(); window.on_guild_selected(move |idx| { let mut s = state.borrow_mut(); s.ui.active_guild_id = if idx >= 0 { s.ui.guilds .get(idx as usize) .map(|guild| guild.guild_id.clone()) } else { None }; s.ui.browsing_dms = false; let destination = s.ui.channels .iter() .find(|channel| { channel.kind == "text" && (s.ui.active_guild_id.is_none() || channel.guild_id == s.ui.active_guild_id) }) .map(|channel| channel.id.clone()); if let Some(channel_id) = destination { s.ui.select_text_channel(channel_id.clone()); let net = s.net.clone(); tokio::spawn(async move { net.send(NetCommand::JoinChannel { channel_id }).await; }); } else { s.ui.active_dm_id = None; s.ui.active_channel = None; s.ui.showing_voice = false; } }); } { let state = state.clone(); window.on_dm_selected(move |dm_id| { let mut s = state.borrow_mut(); let id = dm_id.to_string(); if s.ui.dm_conversations.iter().any(|c| c.dm_id == id) { s.ui.select_dm(id.clone()); if let Some(dm) = s.ui.dm_conversations.iter_mut().find(|c| c.dm_id == id) { dm.unread_count = 0; } let net = s.net.clone(); tokio::spawn(async move { net.send(NetCommand::DmReadAck { dm_id: id }).await; }); } }); } { let state = state.clone(); window.on_connect(move |addr| { let addr = addr.to_string(); let mut s = state.borrow_mut(); s.ui.conn = ConnState::Connecting; s.ui.connect_input = addr.clone(); s.ui.status_msg = Some("Connecting…".into()); let auto_reconnect = s.ui.auto_reconnect; let net = s.net.clone(); drop(s); tokio::spawn(async move { net.send(NetCommand::Connect { address: addr, auto_reconnect, }) .await; }); }); } { // First trust: remember the confirmed fingerprint, then connect again. let state = state.clone(); window.on_trust_accept(move || { let mut s = state.borrow_mut(); let Some(prompt) = s.ui.trust_prompt.take() else { return; }; if prompt.kind != ui::state::TrustPromptKind::FirstUse { return; } if let Err(error) = s.net.trust().pin(&prompt.address, &prompt.received) { tracing::warn!(%error, "could not save the trusted fingerprint"); s.ui.status_msg = Some("Could not save the trusted fingerprint".into()); return; } s.ui.conn = ConnState::Connecting; s.ui.status_msg = Some("Connecting…".into()); let auto_reconnect = s.ui.auto_reconnect; let net = s.net.clone(); drop(s); tokio::spawn(async move { net.send(NetCommand::Connect { address: prompt.address, auto_reconnect, }) .await; }); }); } { // A blocked change: forgetting is the only way forward and needs a new decision. let state = state.clone(); window.on_trust_forget(move || { let mut s = state.borrow_mut(); let Some(prompt) = s.ui.trust_prompt.take() else { return; }; if let Err(error) = s.net.trust().forget(&prompt.address) { tracing::warn!(%error, "could not forget the server"); } s.ui.status_msg = Some("Server forgotten. Connect again to review its fingerprint.".into()); }); } { let state = state.clone(); window.on_trust_dismiss(move || { state.borrow_mut().ui.trust_prompt = None; }); } { let state = state.clone(); window.on_disconnect(move || { let s = state.borrow(); let net = s.net.clone(); drop(s); tokio::spawn(async move { net.send(NetCommand::Disconnect).await; }); }); } { let state = state.clone(); window.on_send_message(move |ch_id, text| { let ch_id = ch_id.to_string(); let text = text.to_string(); if text.trim().is_empty() { return; } let mut s = state.borrow_mut(); if !matches!(s.ui.conn, ConnState::Connected { .. }) { s.ui.status_msg = Some("Not connected to a server. Your draft has been kept.".into()); return; } if let Some(dm_id) = s.ui.active_dm_id.as_ref() && s.ui.dm_conversations.iter().any(|c| &c.dm_id == dm_id && c.e2ee_enabled) { s.ui.status_msg = Some("Encrypted messaging is temporarily unavailable. Your draft has been kept; the message was not sent.".into()); return; } if let Some(edit_id) = s.ui.editing_message_id.take() { let net = s.net.clone(); s.ui.remember_draft(String::new()); drop(s); tokio::spawn(async move { net.send(NetCommand::MessageEdit { channel_id: ch_id, message_id: edit_id, content: text, }) .await; }); return; } let reply_to = s.ui.replying_to_message.take(); s.ui.replying_to_sender.clear(); s.ui.replying_to_content.clear(); s.ui.remember_draft(String::new()); let net = s.net.clone(); drop(s); if !ch_id.is_empty() { tokio::spawn(async move { net.send(NetCommand::SendChat { channel_id: ch_id, content: text, reply_to, }) .await; }); } else { let s = state.borrow(); if let Some(dm_id) = s.ui.active_dm_id.clone() { let net = s.net.clone(); drop(s); tokio::spawn(async move { net.send(NetCommand::DmSend { dm_id, content: text, }) .await; }); } } }); } { let state = state.clone(); window.on_add_friend(move |user_id| { let user_id = user_id.to_string(); let s = state.borrow(); let net = s.net.clone(); drop(s); tokio::spawn(async move { net.send(NetCommand::FriendRequest { target_user_id: user_id, }) .await; }); }); } { let state = state.clone(); window.on_accept_friend(move |user_id| { let user_id = user_id.to_string(); let s = state.borrow(); let net = s.net.clone(); drop(s); tokio::spawn(async move { net.send(NetCommand::FriendAccept { user_id }).await; }); }); } { let state = state.clone(); window.on_decline_friend(move |user_id| { let user_id = user_id.to_string(); let s = state.borrow(); let net = s.net.clone(); drop(s); tokio::spawn(async move { net.send(NetCommand::FriendDecline { user_id }).await; }); }); } { let state = state.clone(); window.on_remove_friend(move |user_id| { let user_id = user_id.to_string(); let s = state.borrow(); let net = s.net.clone(); drop(s); tokio::spawn(async move { net.send(NetCommand::FriendRemove { user_id }).await; }); }); } { let state = state.clone(); window.on_start_dm(move |user_id| { let user_id = user_id.to_string(); let s = state.borrow(); let net = s.net.clone(); drop(s); tokio::spawn(async move { net.send(NetCommand::DmStart { target_user_id: user_id, }) .await; }); }); } { let state = state.clone(); window.on_toggle_mic(move || { let mut s = state.borrow_mut(); s.ui.mic_enabled = !s.ui.mic_enabled; }); } { let state = state.clone(); window.on_toggle_deafen(move || { let mut s = state.borrow_mut(); s.ui.deafen = !s.ui.deafen; }); } { let state = state.clone(); window.on_leave_voice(move || { let mut s = state.borrow_mut(); let voice_channel = s.ui.voice_target.take(); crate::ui::update::stop_voice(&mut s); s.ui.showing_voice = false; s.ui.ptt_held = false; let net = s.net.clone(); if let Some(channel_id) = voice_channel { tokio::spawn(async move { net.send(NetCommand::LeaveChannel { channel_id }).await; }); } }); } { let state = state.clone(); window.on_add_bookmark(move |addr| { let mut s = state.borrow_mut(); s.ui.connect_input = addr.to_string(); s.ui.add_bookmark_from_input(); }); } { let state = state.clone(); window.on_remove_bookmark(move |address| { let addr = address.to_string(); let mut s = state.borrow_mut(); if let Some(idx) = s.ui.bookmarks.iter().position(|b| b.address == addr) { s.ui.remove_bookmark(idx); } }); } { let state = state.clone(); window.on_load_more(move |_| { state.borrow_mut().ui.status_msg = Some("Earlier history is not available with this protocol version.".into()); }); } { let state = state.clone(); let weak = window.as_weak(); window.on_close_settings(move || { let mut state = state.borrow_mut(); state.ui.settings_open = false; if let Some(window) = weak.upgrade() { crate::ui::appearance::bindings_restore(&window, &state.ui.appearance); } }); } { let state = state.clone(); window.on_set_passphrase(move |pass, confirm| { let mut s = state.borrow_mut(); if pass != confirm { s.ui.settings_passphrase_error = Some("Passphrases do not match".into()); return; } if pass.len() < 8 { s.ui.settings_passphrase_error = Some("Passphrase must be at least 8 characters".into()); return; } s.ui.settings_passphrase_error = None; let identity = s.identity.clone(); drop(s); match identity::save(&identity, Some(pass.as_str())) { Ok(()) => state.borrow_mut().ui.vault_enabled = true, Err(e) => { state.borrow_mut().ui.settings_passphrase_error = Some(ui::i18n::Message::with( "Could not update profile: {error}", vec![("error", e.to_string())], )) } } }); } { let state = state.clone(); window.on_remove_passphrase(move || { let s = state.borrow(); let identity = s.identity.clone(); drop(s); match identity::save(&identity, None) { Ok(()) => state.borrow_mut().ui.vault_enabled = false, Err(e) => { state.borrow_mut().ui.settings_passphrase_error = Some(ui::i18n::Message::with( "Could not update profile: {error}", vec![("error", e.to_string())], )) } } }); } { let state = state.clone(); window.on_export_keyfile(move |pass, confirm| { let mut s = state.borrow_mut(); if pass != confirm { s.ui.settings_export_error = Some("Passphrases do not match".into()); return; } let passphrase = if pass.is_empty() { None } else { Some(pass.as_str()) }; let identity = s.identity.clone(); drop(s); match identity::export_keyfile(&identity, passphrase) { Ok(json) => { let mut s = state.borrow_mut(); s.ui.settings_export_output = Some(json); s.ui.settings_export_error = None; } Err(e) => { let mut s = state.borrow_mut(); s.ui.settings_export_error = Some(ui::i18n::Message::with( "Could not update profile: {error}", vec![("error", e.to_string())], )); } } }); } { let state = state.clone(); window.on_import_keyfile(move |input, pass| { let input = input.to_string(); let passphrase = if pass.is_empty() { None } else { Some(pass.as_str()) }; let mut s = state.borrow_mut(); match identity::import_keyfile(&input, passphrase) { Ok(identity) => { if let Err(e) = identity::save(&identity, None) { s.ui.settings_import_error = Some(ui::i18n::Message::with( "Could not update profile: {error}", vec![("error", e.to_string())], )); } else { s.ui.settings_import_error = None; s.ui.vault_enabled = false; s.ui.status_msg = Some("Profile imported. Restart Vnox to use your new keys.".into()); } } Err(e) => { s.ui.settings_import_error = Some(ui::i18n::Message::with( "Could not update profile: {error}", vec![("error", e.to_string())], )); } } }); } { let state = state.clone(); window.on_react(move |msg_id, emoji| { let msg_id = msg_id.to_string(); let emoji = emoji.to_string(); let s = state.borrow(); let ch_id = s.ui.active_channel.clone().unwrap_or_default(); let net = s.net.clone(); drop(s); tokio::spawn(async move { net.send(NetCommand::ReactionAdd { channel_id: ch_id, message_id: msg_id, emoji, }) .await; }); }); } { let state = state.clone(); window.on_reply_to_msg(move |msg_id| { let msg_id = msg_id.to_string(); let mut s = state.borrow_mut(); s.ui.replying_to_message = Some(msg_id.clone()); if let Some(ch_id) = s.ui.active_channel.clone() && let Some(msgs) = s.ui.messages.get(&ch_id) && let Some(m) = msgs.iter().find(|m| m.message_id == msg_id) { let sender = m.sender_id.clone(); let content = m.content.clone(); s.ui.replying_to_sender = s.ui.nick_for(&sender).to_owned(); s.ui.replying_to_content = content; } }); } { let state = state.clone(); window.on_cancel_reply(move || { let mut s = state.borrow_mut(); s.ui.replying_to_message = None; s.ui.replying_to_sender.clear(); s.ui.replying_to_content.clear(); }); } { let state = state.clone(); window.on_edit_msg(move |msg_id| { let msg_id = msg_id.to_string(); let mut s = state.borrow_mut(); if let Some(ch_id) = s.ui.active_channel.clone() && let Some(msgs) = s.ui.messages.get(&ch_id) && let Some(m) = msgs.iter().find(|m| m.message_id == msg_id) { let content = m.content.clone(); s.ui.remember_draft(content); s.ui.editing_message_id = Some(msg_id); } }); } { let state = state.clone(); window.on_delete_msg(move |msg_id| { let msg_id = msg_id.to_string(); let s = state.borrow(); let ch_id = s.ui.active_channel.clone().unwrap_or_default(); let net = s.net.clone(); drop(s); tokio::spawn(async move { net.send(NetCommand::MessageDelete { channel_id: ch_id, message_id: msg_id, }) .await; }); }); } } #[cfg(test)] mod ui_smoke;