Repository: Enitoni/pulseshitter Branch: main Commit: cfce112a0c97 Files: 28 Total size: 119.1 KB Directory structure: gitextract_dx_kp17l/ ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md └── src/ ├── app.rs ├── audio/ │ ├── analysis.rs │ ├── mod.rs │ ├── pulse.rs │ ├── source.rs │ └── system.rs ├── dickcord/ │ ├── bot.rs │ ├── mod.rs │ └── system.rs ├── interface/ │ ├── components/ │ │ ├── mod.rs │ │ └── text_field.rs │ ├── dashboard/ │ │ ├── discord_module.rs │ │ ├── meter.rs │ │ ├── mod.rs │ │ ├── settings_module.rs │ │ ├── source_selector.rs │ │ └── version.rs │ ├── mod.rs │ ├── setup/ │ │ ├── form.rs │ │ └── mod.rs │ ├── splash.rs │ └── view.rs ├── main.rs └── state.rs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ /target /profiling config.ron profile.json /.vscode ================================================ FILE: Cargo.toml ================================================ [package] name = "pulseshitter" version = "3.0.0" edition = "2021" [profile.profiling] inherits = "release" debug = true [profile.release] lto = true codegen-units = 1 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] reqwest = { version = "0.12.4", features = ["json"] } ringbuf = "0.3.3" serde = "1.0.156" serde_json = "1.0.96" ron = "0.8.0" crossbeam = "0.8.2" songbird = "0.3.2" serenity = { version = "0.11.5", default-features = false, features = [ "builder", "cache", "client", "voice", ] } tokio = { version = "1.26.0", features = ["full"] } libpulse-binding = "2.28.1" tui = "0.19" tui-textarea = "0.2.0" crossterm = "0.25" enum-iterator = "1.4.0" regex = "1.7.3" lazy_static = "1.4.0" parking_lot = "0.12" multiversion = "0.7.1" strsim = "0.10.0" thiserror = "1.0.56" ================================================ FILE: LICENSE ================================================ Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. ================================================ FILE: README.md ================================================ # pulseshitter [![License](https://img.shields.io/github/license/Enitoni/pulseshitter.svg?style=flat)](https://github.com/Enitoni/pulseshitter/blob/main/LICENSE) ![Screenshot of pulseshitter](preview.gif) pulseshitter is a shitty solution to a shitty problem. you see, it all started back in 2015, when discord announced discord, an instant messaging social platform for gamers, until they decided that it was for everyone too. however, they clearly don't support everyone because they hate us blessed linux users. to this day, discord still [doesn't support](https://support.discord.com/hc/en-us/community/posts/360050971374-Linux-Screen-Share-Sound-Support) sharing audio via screen sharing on linux. ## what is this? this overengineered project is a workaround to make it possible to share audio via a **bot**. ***it does not pipe your audio through your microphone.*** this has two advantages: - other people can mute your stream without muting you - the audio is stereo (WIDE) ## features - shits your audio into a voice channel - based text-based user interface - automatically reconnects to an application when parec stops streaming it (it does that a lot) - cool good sound meter™️ - follows you around so you can always bother your friends - says fuck you to discord (fuck you discord) - 🚀 blazingly fa-- ## caveats - you need a bot in a server to use it - linux audio sources are very inconsistent so it's not guaranteed it will reconnect properly, or even show a meaningful name, but you can always just select the app you want to stream again ## usage ### prerequisites - [linux](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git) (duh) - [pulseaudio](https://www.freedesktop.org/wiki/Software/PulseAudio/) or [pipewire](https://pipewire.org) - [discord bot](https://google.com/search?q=discord+bot+token+generator) [download latest release](https://github.com/Enitoni/pulseshitter/releases/latest) and run the binary in your terminal. you can also add it to path for easy access. ```shell ./pulseshitter ``` ---- ## faq (you) ### Is this a joke? Parts of this README, yes. The project itself, no. It's actually something I worked really hard on and it is actually a successor to [pulsecord](https://github.com/itsMapleLeaf/pulsecord) which my friend was using. It had some issues, and that's what led to this project. ### Why can't I stream Spotify? Spotify streaming is disabled by default due to me not wanting to get in trouble for distributing a binary that allows you to bypass the measures Discord has in place to stop you from streaming Spotify through their service. You can enable it by compiling the project yourself with the `ALLOW_SPOTIFY_STREAMING` environment variable set to `true`. ### Are you open to suggestions/bug reports? Yes. Please make a GitHub issue if you want to report a bug or suggest a feature. --- ## build ### prerequisites - [rust](https://www.rust-lang.org/) - pulseaudio / pipewire - libopus compile it by typing this in your terminal: ```shell cargo build --release ``` then you're done (wow!) ## license [MPL-2 license](https://www.mozilla.org/en-US/MPL/2.0/) (very original do not steal) ================================================ FILE: src/app.rs ================================================ use crate::{ audio::{pulse::PulseClientError, AudioSystem, Source}, dickcord::{self, DiscordSystem}, interface::{Dashboard, Interface, Setup, Splash}, state::{Config, ReadOnlyConfig}, }; use crossbeam::channel::{unbounded, Receiver, Sender}; use parking_lot::Mutex; use reqwest::ClientBuilder; use serde::Deserialize; use std::{sync::Arc, thread}; use thiserror::Error; use tokio::runtime::{Builder, Runtime}; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); const LATEST_RELEASE_URL: &str = "https://api.github.com/repos/enitoni/pulseshitter/releases/latest"; pub struct App { rt: Arc, interface: Interface, audio: Arc, discord: Arc, events: Sender, state: Arc>, config: Arc>>, update_available: Arc>>, } #[derive(Clone)] pub struct AppContext { events: Sender, audio: Arc, discord: Arc, config: Arc>>, update_available: Arc>>, } #[derive(Debug, Clone)] enum AppState { Exiting, Idle, } #[derive(Error, Debug)] pub enum AppError { #[error(transparent)] PulseClient(#[from] PulseClientError), } #[derive(Debug, Clone)] pub enum AppAction { SetConfig(Config), SetAudioSource(Source), ToggleScreenshareOnly, ToggleMeter, StopStream, RedoSetup, Exit, } #[allow(clippy::large_enum_variant)] pub enum AppEvent { DiscordStateUpdate(dickcord::State), Action(AppAction), } impl App { pub fn new() -> Result, AppError> { let rt: Arc<_> = Builder::new_multi_thread() .worker_threads(1) .max_blocking_threads(1) .enable_all() .thread_name("pulseshitter-async") .build() .unwrap() .into(); let (sender, receiver) = unbounded(); let config = Config::restore(); let audio = AudioSystem::new().map_err(AppError::PulseClient)?; let discord = DiscordSystem::new(rt.clone(), sender.clone(), audio.stream()); let interface = Interface::new(Splash, sender.clone()); let app = Arc::new(Self { rt, audio, discord, interface, events: sender, state: Arc::new(AppState::Idle.into()), config: Arc::new(Mutex::new(config)), update_available: Default::default(), }); spawn_poll_thread(app.clone(), receiver); app.check_for_update(); app.restore(); Ok(app) } pub fn run_tui(&self) { let result = self.interface.run(); if let Err(err) = result { eprintln!("Render error: {}", err) } } fn restore(&self) { let config = Config::restore(); if let Some(config) = config { self.discord.connect(&config); self.interface.set_view(Dashboard::new(self.context())) } else { self.interface.set_view(Setup::new(self.context())) } } fn context(&self) -> AppContext { AppContext { events: self.events.clone(), audio: self.audio.clone(), discord: self.discord.clone(), config: self.config.clone(), update_available: self.update_available.clone(), } } fn exit(&self) { self.set_state(AppState::Exiting); if let dickcord::State::Connected(_, _) = self.discord.state() { self.discord.disconnect(); } else { self.interface.stop(); } } fn handle_event(&self, event: AppEvent) { match event { AppEvent::Action(action) => self.handle_action(action), AppEvent::DiscordStateUpdate(new_state) => self.handle_discord_state_update(new_state), } } fn handle_discord_state_update(&self, new_state: dickcord::State) { if let dickcord::State::Connected(_, _) = new_state { self.save_config(); self.interface.set_view(Dashboard::new(self.context())) } if let dickcord::State::Idle = new_state { if let AppState::Exiting = self.state() { self.interface.stop(); } } } fn handle_action(&self, action: AppAction) { match action { AppAction::SetConfig(config) => { self.discord.connect(&config); self.set_config(config); } AppAction::RedoSetup => { self.discord.disconnect(); self.interface.set_view(Setup::new(self.context())); } AppAction::ToggleScreenshareOnly => { self.edit_config(|config| { config.screen_share_only = !config.screen_share_only; }); self.discord.set_config(self.read_only_config()); } AppAction::ToggleMeter => { self.edit_config(|config| { config.show_meter = !config.show_meter; }); } AppAction::SetAudioSource(source) => { self.audio.select(Some(source.clone())); self.discord.announce_source_streaming(Some(source)); } AppAction::StopStream => { self.audio.select(None); self.discord.announce_source_streaming(None); } AppAction::Exit => self.exit(), } } fn set_state(&self, state: AppState) { *self.state.lock() = state; } fn state(&self) -> AppState { self.state.lock().clone() } fn set_config(&self, config: Config) { let mut previous_config = self.config.lock(); *previous_config = Some(config); } fn save_config(&self) { let config = self.config.lock(); if let Some(config) = config.as_ref() { config.save(); } } fn edit_config(&self, cb: impl FnOnce(&mut Config)) { let mut config = self.config.lock(); if let Some(config) = config.as_mut() { cb(config); config.save(); } } fn read_only_config(&self) -> ReadOnlyConfig { let config = self.config.lock(); config .as_ref() .expect("Config is set when config() is called on AppContext") .read_only() } fn check_for_update(&self) { let update_available = self.update_available.clone(); self.rt.spawn(async move { let new_version = fetch_update().await; if let Some(new_version) = new_version { *update_available.lock() = Some(new_version); } }); } } fn spawn_poll_thread(app: Arc, receiver: Receiver) { let run = move || loop { if let Ok(event) = receiver.recv() { app.handle_event(event) } }; thread::Builder::new() .name("pulseshitter-polling".to_string()) .spawn(run) .unwrap(); } impl AppContext { pub fn dispatch_action(&self, action: AppAction) { self.events.send(AppEvent::Action(action)).unwrap() } pub fn sources(&self) -> Vec { self.audio.sources() } pub fn current_source(&self) -> Option { self.audio.current_source() } pub fn selected_source(&self) -> Option { self.audio.selected_source() } pub fn meter_value_ranged(&self) -> (f32, f32) { self.audio.meter_value_ranged() } pub fn discord_state(&self) -> dickcord::State { self.discord.state() } pub fn config(&self) -> ReadOnlyConfig { let config = self.config.lock(); config .as_ref() .expect("Config is set when config() is called on AppContext") .read_only() } pub fn update_available(&self) -> Option { self.update_available.lock().clone() } } #[derive(Debug, Deserialize)] struct LatestRelease { tag_name: String, } async fn fetch_update() -> Option { let client = ClientBuilder::new() .user_agent("enitoni/pulseshitter") .build() .unwrap(); let release: LatestRelease = client .get(LATEST_RELEASE_URL) .send() .await .ok()? .json() .await .ok()?; if release.tag_name != format!("v{}", VERSION) { return Some(release.tag_name); } None } ================================================ FILE: src/audio/analysis.rs ================================================ use std::{sync::Arc, thread, time::Duration}; use crossbeam::atomic::AtomicCell; use multiversion::multiversion; use parking_lot::Mutex; use crate::interface::TARGET_FPS; use super::{Sample, SAMPLE_IN_BYTES, SAMPLE_RATE}; /// Measures dBFS of a single channel pub struct Meter { window_size: AtomicCell, current_value: AtomicCell, buffer: Mutex>, } impl Meter { const DEFAULT_WINDOW_SIZE: usize = SAMPLE_RATE / 24; const DB_RANGE: f32 = 100.; /// The smoothing modifiers. Higher values equals less smoothing. const MAX_SMOOTHING: f32 = 0.1 / 2.; const MIN_SMOOTHING: f32 = 0.2; /// The minimum smoothing boundary const SMOOTHING_BOUNDARY: f32 = 0.5; pub fn new() -> Self { Self { window_size: Self::DEFAULT_WINDOW_SIZE.into(), current_value: Default::default(), buffer: Default::default(), } } pub fn write(&self, buf: &[u8]) { let mut buffer = self.buffer.lock(); let window_size = self.window_size.load(); let samples = raw_samples_from_bytes(buf); buffer.extend_from_slice(&samples); let overflow = buffer.len() as isize + -(window_size as isize); let overflow = overflow.max(0) as usize; if overflow > 0 { buffer.drain(..overflow); } } pub fn drain(&self, amount: usize) { let mut buffer = self.buffer.lock(); buffer.extend(vec![0.; amount]); buffer.drain(..amount); } pub fn process(&self) { process_multiversioned(self) } pub fn value(&self) -> f32 { self.current_value.load() } pub fn dbfs(&self) -> f32 { self.value().log10() * 20. } pub fn value_ranged(&self) -> f32 { let ranged = (Self::DB_RANGE + self.dbfs()) / Self::DB_RANGE; ranged.max(0.).powf(2.) } } #[multiversion(targets("x86_64+avx2"))] fn process_multiversioned(meter: &Meter) { let buffer = meter.buffer.lock(); let current_value = meter.current_value.load(); let max_value = buffer .iter() .fold(0f32, |acc, x| faster_max(acc, (*x).abs())); let difference = (current_value - max_value).abs(); if max_value > current_value { meter.current_value.store(max_value); } else { let max_smoothing = (1. - Meter::MAX_SMOOTHING) + Meter::MAX_SMOOTHING * Meter::SMOOTHING_BOUNDARY; let min_smoothing = (1. - Meter::MIN_SMOOTHING) + Meter::MIN_SMOOTHING * Meter::SMOOTHING_BOUNDARY; let flipped_difference = (-difference) + 1.; let smoothing_factor = flipped_difference * max_value.powf(0.1); let smoothing = min_smoothing + (max_smoothing - min_smoothing) * smoothing_factor; let result = current_value * smoothing; meter.current_value.store(result); } } pub struct StereoMeter { left: Meter, right: Meter, } impl StereoMeter { pub fn new() -> Self { Self { left: Meter::new(), right: Meter::new(), } } pub fn write(&self, buf: &[u8]) { let samples = buf.chunks_exact(SAMPLE_IN_BYTES * 2); let mut left = vec![]; let mut right = vec![]; for chunk in samples { left.extend_from_slice(&chunk[..SAMPLE_IN_BYTES]); right.extend_from_slice(&chunk[SAMPLE_IN_BYTES..]); } self.left.write(&left); self.right.write(&right); } pub fn process(&self) { self.left.process(); self.right.process(); } pub fn drain(&self, amount: usize) { self.left.drain(amount); self.right.drain(amount); } pub fn value_ranged(&self) -> (f32, f32) { (self.left.value_ranged(), self.right.value_ranged()) } } impl Default for StereoMeter { fn default() -> Self { Self::new() } } fn faster_max(a: f32, b: f32) -> f32 { if a > b { a } else { b } } /// Converts a slice of bytes into a vec of [Sample]. pub fn raw_samples_from_bytes(bytes: &[u8]) -> Vec { bytes .chunks_exact(SAMPLE_IN_BYTES) .map(|b| { let arr: [u8; SAMPLE_IN_BYTES] = [b[0], b[1], b[2], b[3]]; Sample::from_le_bytes(arr) }) .collect() } pub fn spawn_analysis_thread(meter: Arc) { let run = move || { let tick_rate = 1. / TARGET_FPS as f32; let samples_to_drain = (SAMPLE_RATE as f32 * tick_rate) as usize; loop { let meter = meter.clone(); meter.process(); meter.drain(samples_to_drain); thread::sleep(Duration::from_secs_f32(tick_rate)); } }; thread::Builder::new() .name("audio-analysis".to_string()) .spawn(run) .unwrap(); } ================================================ FILE: src/audio/mod.rs ================================================ mod analysis; pub mod pulse; mod source; mod system; use std::sync::Arc; use parking_lot::Mutex; use ringbuf::{HeapConsumer, HeapProducer}; pub use source::*; pub use system::*; pub type Sample = f32; pub type AudioProducer = Arc>>; pub type AudioConsumer = Arc>>; pub const SAMPLE_RATE: usize = 48000; pub const SAMPLE_IN_BYTES: usize = 4; pub const LATENCY_IN_SECONDS: f32 = 0.05; pub const BUFFER_SIZE: usize = (SAMPLE_IN_BYTES * 2) * (SAMPLE_RATE as f32 * LATENCY_IN_SECONDS) as usize; ================================================ FILE: src/audio/pulse.rs ================================================ // TODO: Remove this once the dead code is used #![allow(unused)] use std::{ sync::{mpsc, Arc}, thread, time::Duration, }; use thiserror::Error; use crate::audio::SAMPLE_RATE; use crossbeam::channel::{unbounded, Receiver, Sender}; use libpulse_binding::{ callbacks::ListResult, context::{ introspect::Introspector, subscribe::{Facility, InterestMaskSet, Operation}, Context, FlagSet as ContextFlagSet, State, }, def::BufferAttr, error::Code, mainloop::standard::{IterateResult, Mainloop}, proplist::{properties, Proplist}, sample::{Format, Spec}, stream::{FlagSet as StreamFlagSet, PeekResult, State as StreamState, Stream}, volume::Volume, }; use parking_lot::{Mutex, RwLock}; use super::BUFFER_SIZE; /// Abstracts connections and interfacing with pulseaudio pub struct PulseClient { context: Arc>, introspector: Introspector, props: Proplist, spec: Spec, pub(super) events: Receiver, event_sender: Sender, } impl PulseClient { pub fn new() -> Result { let spec = Spec { format: Format::F32le, channels: 2, rate: SAMPLE_RATE as u32, }; let mut proplist = Proplist::new().ok_or(PulseClientError::Fatal( "Failed to create proplist".to_string(), ))?; let props = proplist.clone(); proplist .set_str(properties::APPLICATION_NAME, "pulseshitter") .and_then(|_| { proplist.set_str(properties::APPLICATION_VERSION, env!("CARGO_PKG_VERSION")) }) .map_err(|_| { PulseClientError::Fatal("Failed to set proplist properties".to_string()) })?; let (context_sender, context_rec) = mpsc::channel(); thread::spawn(move || { let (context, mut mainloop) = match Self::setup_mainloop(proplist) { Ok(tuple) => tuple, Err(e) => { context_sender.send(Err(e)).unwrap(); return; } }; context_sender.send(Ok(context)).unwrap(); mainloop.run().unwrap(); }); let context = context_rec .recv_timeout(Duration::from_millis(1000)) .map_err(|_| PulseClientError::Fatal("Did not receive context".to_string()))??; let introspector = context.introspect(); let (sender, receiver) = unbounded(); let client = Self { event_sender: sender, events: receiver, context: Mutex::new(context).into(), introspector, props, spec, }; Ok(client) } fn setup_mainloop(proplist: Proplist) -> Result<(Context, Mainloop), PulseClientError> { let mut mainloop = Mainloop::new().ok_or(PulseClientError::Fatal( "Failed to create mainloop".to_string(), ))?; let mut context = Context::new_with_proplist(&mainloop, "pulseshitter", &proplist).ok_or( PulseClientError::Fatal("Failed to create context".to_string()), )?; context .connect(None, ContextFlagSet::NOFLAGS, None) .map_err(|_| PulseClientError::ConnectionFailed)?; loop { match mainloop.iterate(false) { IterateResult::Quit(_) | IterateResult::Err(_) => { return Err(PulseClientError::Fatal( "Failed mainloop iterate state".to_string(), )); } IterateResult::Success(_) => {} } match context.get_state() { State::Ready => { break; } State::Failed | State::Terminated => { return Err(PulseClientError::Fatal( "Context state failed/terminated".to_string(), )); } _ => {} } } Ok((context, mainloop)) } pub fn subscribe_to_events(&self) { let mut context = self.context.lock(); let sender = self.event_sender.clone(); // Set up the callback that will handle events. context.set_subscribe_callback(Some(Box::new(move |facility_opt, operation, index| { if let Some(Facility::SinkInput) = facility_opt { sender .send(PulseClientEvent::SinkInput { index, operation: operation.expect("SinkEvent always has an operation"), }) .expect("Send event") } }))); // Subscribe to all relevant events. context.subscribe( InterestMaskSet::SINK_INPUT | InterestMaskSet::SOURCE, |success| { if !success { eprintln!("Failed to subscribe to sink and source events"); } }, ); } pub fn sink_inputs(&self) -> Result, PulseClientError> { let (sender, receiver) = mpsc::channel(); self.introspector.get_sink_input_info_list({ move |list| match list { ListResult::End => sender.send(ListResult::End).unwrap(), ListResult::Error => sender.send(ListResult::Error).unwrap(), ListResult::Item(item) => { let volume = item.volume.max().0 as f32 / Volume::NORMAL.0 as f32; let sink_input = SinkInput { index: item.index, props: item.proplist.clone(), sink: item.sink, name: item .name .clone() .map(|n| n.to_string()) .unwrap_or("Unknown".to_string()), volume, }; sender.send(ListResult::Item(sink_input)).unwrap(); } } }); let mut result = vec![]; loop { match receiver.recv().unwrap() { ListResult::End => break, ListResult::Item(x) => result.push(x), ListResult::Error => return Err(PulseClientError::ListError), } } Ok(result) } pub fn record(&self, sink_input: &SinkInput) -> Result { let props = self.props.clone(); let stream = SinkInputStream::new( self.context.clone(), self.event_sender.clone(), props, &self.spec, ); stream.connect_to_sink_input(sink_input)?; stream.set_event_callbacks(); Ok(stream) } } impl Drop for PulseClient { fn drop(&mut self) { self.context.lock().disconnect(); } } #[derive(Error, Debug)] pub enum PulseClientError { #[error("cannot connect to a pulseaudio-compliant server")] ConnectionFailed, #[error("list fetching failed")] ListError, #[error("fatal pulseaudio error: {0}")] Fatal(String), } pub enum PulseClientEvent { SinkInput { index: u32, operation: Operation }, Audio(Vec), } #[derive(Debug, Clone)] pub struct SinkInput { pub(super) name: String, pub(super) index: u32, pub(super) sink: u32, pub(super) volume: f32, pub(super) props: Proplist, } /// Represents a stream of audio from a sink input #[derive(Clone)] pub struct SinkInputStream { context: Arc>, stream: Arc>, status: Arc>, event_sender: Sender, } impl SinkInputStream { fn new( context: Arc>, event_sender: Sender, mut props: Proplist, spec: &Spec, ) -> Self { let stream = { let mut context = context.lock(); let stream = Stream::new_with_proplist( &mut context, "pulseshitter-stream", spec, None, &mut props, ) .expect("Creates stream"); Arc::new(Mutex::new(stream)) }; Self { context, stream, event_sender, status: Default::default(), } } fn set_event_callbacks(&self) { let context = self.context.clone(); let mut locked_stream = self.stream.lock(); locked_stream.set_state_callback(Some(Box::new({ let stream = self.stream.clone(); let status = self.status.clone(); move || { let mut status = status.write(); match stream.lock().get_state() { StreamState::Ready => *status = SinkInputStreamStatus::Connected, StreamState::Unconnected | StreamState::Creating => { *status = SinkInputStreamStatus::Connecting } StreamState::Terminated => *status = SinkInputStreamStatus::Terminated, StreamState::Failed => { let err: Code = context.lock().errno().try_into().unwrap_or(Code::Unknown); match err { Code::Timeout => *status = SinkInputStreamStatus::TimedOut, x => { *status = SinkInputStreamStatus::Failed( x.to_string().unwrap_or_else(|| "Unknown".to_string()), ) } } } } } }))); locked_stream.set_read_callback(Some(Box::new({ let stream = self.stream.clone(); let sender = self.event_sender.clone(); move |_| { let mut stream = stream.lock(); match stream.peek() { Ok(result) => match result { PeekResult::Empty => {} PeekResult::Hole(_) => stream.discard().expect("Discards if hole"), PeekResult::Data(data) => { sender .send(PulseClientEvent::Audio(data.to_vec())) .expect("Sends audio"); //producer.lock().push_slice(data); stream.discard().expect("Discards after data"); } }, Err(_) => { unimplemented!() } } } }))); locked_stream.set_suspended_callback(Some(Box::new({ let stream = self.stream.clone(); let status = self.status.clone(); move || { let stream = stream.lock(); let mut status = status.write(); if stream.is_suspended().unwrap_or_default() { *status = SinkInputStreamStatus::Suspended } else { *status = SinkInputStreamStatus::Connected } } }))); } fn connect_to_sink_input(&self, sink_input: &SinkInput) -> Result<(), PulseClientError> { let mut stream = self.stream.lock(); stream .set_monitor_stream(sink_input.index) .expect("Sets monitor stream"); *self.status.write() = SinkInputStreamStatus::Connecting; stream .connect_record( Some(sink_input.sink.to_string().as_str()), Some(&BufferAttr { maxlength: std::u32::MAX, tlength: 0, prebuf: 0, minreq: 0, fragsize: (BUFFER_SIZE / 2) as u32, }), StreamFlagSet::DONT_MOVE, ) .expect("Connects stream for recording"); Ok(()) } pub fn status(&self) -> SinkInputStreamStatus { self.status.read().clone() } } impl Drop for SinkInputStream { fn drop(&mut self) { let mut stream = self.stream.lock(); stream.set_suspended_callback(None); stream.set_read_callback(None); stream.set_event_callback(None); stream.set_state_callback(None); if let StreamState::Ready = stream.get_state() { stream.disconnect().unwrap_or_else(|e| { eprintln!("Failed to disconnect stream: {}", e); }) } } } #[derive(Debug, Default, Clone)] pub enum SinkInputStreamStatus { #[default] Idle, TimedOut, Connected, Suspended, Terminated, Connecting, Failed(String), } ================================================ FILE: src/audio/source.rs ================================================ // TODO: Remove this once the dead code is used #![allow(unused)] use super::pulse::{PulseClient, SinkInput}; use crossbeam::atomic::AtomicCell; use lazy_static::lazy_static; use libpulse_binding::context::subscribe::Operation; use parking_lot::{Mutex, RwLock}; use regex::Regex; use std::{ fmt::Display, sync::Arc, time::{Duration, Instant}, }; use strsim::jaro; /// Due to Discord having an agreement with Spotify, you cannot actually stream Spotify audio on Discord /// without it pausing your Spotify playback after a few seconds when it detects you may be doing this. /// /// Because of this, pulseshitter is technically a workaround, as there is no way for Discord to detect that you may be streaming Spotify through it. /// In order to be on the safe side regarding TOS and legal matters, Spotify streaming is disabled by default. /// /// If you don't care about this, you can compile pulseshitter with the environment variable below present to enable it anyway. const ALLOW_SPOTIFY_STREAMING: Option<&'static str> = option_env!("ALLOW_SPOTIFY_STREAMING"); const SPOTIFY_NAME: &str = "Spotify"; // These are words commonly used in vague source names that is not useful to the user const VAGUE_WORDS: [&str; 10] = [ "play", "audio", "voice", "stream", "driver", "webrtc", "engine", "playback", "callback", "alsa", ]; /// Keeps track of active sources and diffing pub struct SourceSelector { client: Arc, current_source: Mutex>, /// The source the user selected. /// Not to be confused with current source which is what is currently being streamed. selected_source: Mutex>, stored_sources: Mutex>, } impl SourceSelector { pub fn new(client: Arc) -> Self { let sources: Vec = client .sink_inputs() .expect("Gets sink inputs") .into_iter() .map(|f| f.into()) .collect(); Self { client, stored_sources: sources.into(), current_source: Default::default(), selected_source: Default::default(), } } pub fn sources(&self) -> Vec { self.stored_sources .lock() .clone() .into_iter() .filter(|s| { ALLOW_SPOTIFY_STREAMING.is_some() || s.name().to_uppercase() != SPOTIFY_NAME.to_uppercase() }) .collect() } pub fn current_source(&self) -> Option { self.current_source.lock().clone().filter(|s| s.available()) } pub fn selected_source(&self) -> Option { self.selected_source.lock().clone() } pub(super) fn select(&self, source: Option) { match source { Some(x) => { *self.current_source.lock() = Some(x.clone()); *self.selected_source.lock() = Some(x.clone()); } None => { *self.current_source.lock() = None; *self.selected_source.lock() = None; } } } pub fn handle_sink_input_event(&self, index: u32, operation: Operation) { let mut current_sources = self.stored_sources.lock(); let new_sources: Vec = self .client .sink_inputs() .unwrap_or_default() .into_iter() .map(|f| f.into()) .collect(); let source = new_sources .into_iter() .find(|x| x.sink_input().index == index); let existing_source = current_sources .iter() .find(|x| x.sink_input().index == index); match operation { Operation::New => { let selected_source = self.selected_source(); if let Some(new_source) = source { let new_as_selected = selected_source .filter(|s| !s.available() && s.compare(&new_source).is_similar_enough()); if let Some(selected) = new_as_selected { selected.update(new_source); } else { current_sources.push(new_source); } } } Operation::Changed => { source.and_then(|s| existing_source.map(|e| e.update(s))); } Operation::Removed => { if let Some(e) = existing_source { e.remove() } } } current_sources.retain(|s| !s.is_dead()); } } /// A sink input simplified for ease of use #[derive(Debug, Clone)] pub struct Source { kind: SourceKind, sink_input: Arc>, /// The best fitting name for this source name: Arc>, /// The binary that spawned the associated sink input application: String, /// This will be false when listing applications from pulsectl does not include this source available: Arc>, age: Arc>, /// Volume of the sink input, used for normalization volume: Arc>, } #[derive(Debug)] enum SourceComparison { Exact, Partial(f64), None, } impl Source { /// How long should a source persist for after it is unavailable const MAX_LIFESPAN: Duration = Duration::from_secs(60); fn update(&self, incoming: Source) { self.age.store(Instant::now()); self.name.write().clone_from(&incoming.name.read()); *self.sink_input.lock() = incoming.sink_input.lock().clone(); self.volume.store(incoming.volume.load()); self.available.store(true); } /// Checks to see how similar this source is to an old one fn compare(&self, rhs: &Source) -> SourceComparison { // It is unlikely that there will ever be conflicts, so if the indices match, this is most likely the same source. let is_same_index = self.index() == rhs.index(); let is_same_name = *self.name.read() == *rhs.name.read(); if is_same_index || is_same_name { return SourceComparison::Exact; } if self.application != rhs.application { return SourceComparison::None; } let score = jaro(&self.name.read(), &rhs.name.read()); SourceComparison::Partial(score) } fn remove(&self) { self.available.store(false); } fn is_dead(&self) -> bool { !self.available() && self.age.load().elapsed() >= Self::MAX_LIFESPAN } pub fn sink_input(&self) -> SinkInput { self.sink_input.lock().clone() } pub fn index(&self) -> u32 { self.sink_input.lock().index } pub fn available(&self) -> bool { self.available.load() } pub fn volume(&self) -> f32 { self.volume.load() } pub fn name(&self) -> String { self.name.read().clone() } } impl SourceComparison { fn is_similar_enough(&self) -> bool { match self { SourceComparison::Partial(score) => *score > 0.3, SourceComparison::Exact => true, SourceComparison::None => false, } } } /// When apps like browsers have multiple tabs, there is no way to differentiate the source from each one without covering these edge cases. /// That is the purpose of this enum. #[derive(Debug, Clone, Copy, PartialEq)] pub enum SourceKind { Standalone, BrowserTab(BrowserKind), } impl SourceKind { fn parse>(candidates: &[T]) -> Self { candidates .iter() .map(AsRef::as_ref) .map(BrowserKind::parse) .find_map(|k| k.map(Into::into)) .unwrap_or(Self::Standalone) } fn determine_name>(&self, candidates: &[T]) -> String { match self { SourceKind::BrowserTab(b) => b.determine_tab_name(candidates), SourceKind::Standalone => candidates .iter() .map(AsRef::as_ref) .map(ToOwned::to_owned) .next() .unwrap_or_else(|| "Unidentifiable audio source".to_string()), } } } /// Currently supported Browser edgecases #[derive(Debug, Clone, Copy, PartialEq)] pub enum BrowserKind { Firefox, Chrome, } impl BrowserKind { const FIREFOX: &'static str = "Firefox"; const CHROME: &'static str = "Chrome"; fn parse>(name: T) -> Option { match name.as_ref().to_uppercase() { x if x == Self::FIREFOX.to_uppercase() => Self::Firefox.into(), x if x == Self::CHROME.to_uppercase() => Self::Chrome.into(), _ => None, } } fn determine_tab_name>(&self, candidates: &[T]) -> String { let browser_name = self.to_string(); candidates .iter() .map(AsRef::as_ref) .map(ToOwned::to_owned) .find(|c| c.to_uppercase() != browser_name.to_uppercase()) .unwrap_or_else(|| format!("Unidentifiable {} Tab", browser_name)) } } impl Display for BrowserKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let name = match self { Self::Firefox => Self::FIREFOX, Self::Chrome => Self::CHROME, }; write!(f, "{}", name) } } impl From for SourceKind { fn from(value: BrowserKind) -> Self { Self::BrowserTab(value) } } impl From for Source { fn from(raw: SinkInput) -> Self { let mut name_candidates: Vec<_> = [ Some(raw.name.clone()), raw.props.get_str("application.process.binary"), raw.props.get_str("application.name"), raw.props.get_str("media.name"), raw.props.get_str("node.name"), ] .into_iter() .flatten() .filter_map(|s| { let score = calculate_name_quality(&s); if score > 1 { Some((s, score)) } else { None } }) .collect(); name_candidates.sort_by(|(_, a), (_, b)| b.cmp(a)); let name_candidates: Vec<_> = name_candidates.into_iter().map(|(s, _)| s).collect(); let kind = SourceKind::parse(&name_candidates); let name = kind.determine_name(&name_candidates); let application = raw .props .get_str("application.process.binary") .or_else(|| raw.props.get_str("application.name")) .unwrap_or_else(|| "Unknown app".to_string()); let volume = AtomicCell::new(raw.volume); Self { kind, application, volume: volume.into(), name: RwLock::new(name).into(), sink_input: Mutex::new(raw).into(), available: AtomicCell::new(true).into(), age: AtomicCell::new(Instant::now()).into(), } } } lazy_static! { static ref WORD_SPLIT_REGEX: Regex = Regex::new(r"([^.,\-_\sA-Z]+)|([^.,\-_\sa-z][^.\sA-Z]+)").unwrap(); } fn str_is_doublecase(str: &str) -> bool { str.chars().filter(|c| c.is_lowercase()).count() < str.len() } fn calculate_name_quality(str: &str) -> i32 { let mut score = 0; score += str_is_doublecase(str) as i32; let words: Vec<_> = WORD_SPLIT_REGEX .find_iter(str) .map(|m| m.as_str()) .collect(); score += words.into_iter().fold(0, |acc, w| { let is_vague = VAGUE_WORDS .iter() .any(|word| w.to_uppercase() == word.to_uppercase()); if is_vague { acc - 1 } else { acc + 1 } }); score } ================================================ FILE: src/audio/system.rs ================================================ use std::{ io::{Read, Seek}, sync::Arc, thread, }; use parking_lot::Mutex; use ringbuf::HeapRb; use songbird::input::{reader::MediaSource, Codec, Container, Input, Reader}; use super::{ analysis::{raw_samples_from_bytes, spawn_analysis_thread, StereoMeter}, pulse::{PulseClient, PulseClientError, PulseClientEvent, SinkInputStream}, source::{Source, SourceSelector}, AudioConsumer, AudioProducer, BUFFER_SIZE, SAMPLE_IN_BYTES, }; /// Manages all audio related stuff pub struct AudioSystem { client: Arc, selector: Arc, stream: Arc>>, producer: AudioProducer, consumer: AudioConsumer, meter: Arc, } impl AudioSystem { pub fn new() -> Result, PulseClientError> { let client = Arc::new(PulseClient::new()?); client.subscribe_to_events(); let selector = Arc::new(SourceSelector::new(client.clone())); let (audio_producer, audio_consumer) = HeapRb::new(BUFFER_SIZE).split(); let audio = Arc::new(Self { client, selector, stream: Default::default(), meter: StereoMeter::new().into(), producer: Mutex::new(audio_producer).into(), consumer: Mutex::new(audio_consumer).into(), }); spawn_analysis_thread(audio.meter.clone()); spawn_event_thread(audio.clone()); Ok(audio) } pub fn select(&self, source: Option) { self.selector.select(source); self.refresh_stream(); } pub fn stream(&self) -> AudioStream { AudioStream(self.consumer.clone()) } pub fn sources(&self) -> Vec { self.selector.sources() } pub fn current_source(&self) -> Option { self.selector.current_source() } pub fn selected_source(&self) -> Option { self.selector.selected_source() } pub fn meter_value_ranged(&self) -> (f32, f32) { self.meter.value_ranged() } fn refresh_stream(&self) { let current_source = self.selector.current_source(); if let Some(source) = current_source { let stream = self .client .record(&source.sink_input()) .expect("Creates recording stream"); *self.stream.lock() = Some(stream); } else { *self.stream.lock() = None; } } } fn spawn_event_thread(audio: Arc) { let run = move || { let events = audio.client.events.clone(); let mut producer = audio.producer.lock(); loop { match events.recv().unwrap() { PulseClientEvent::SinkInput { index, operation } => { let old_id = audio .selector .current_source() .map(|s| s.index()) .unwrap_or_default(); audio.selector.handle_sink_input_event(index, operation); let new_id = audio .selector .current_source() .map(|s| s.index()) .unwrap_or_default(); if new_id != old_id { audio.refresh_stream(); } } PulseClientEvent::Audio(data) => { let current_source_volume = audio .selector .current_source() .map(|s| s.volume()) .unwrap_or(1.); let normalized_bytes = normalize_volume(&data, current_source_volume); producer.push_slice(&normalized_bytes); audio.meter.write(&normalized_bytes); } }; } }; thread::Builder::new() .name("audio-events".to_string()) .spawn(run) .unwrap(); } #[derive(Clone)] pub struct AudioStream(AudioConsumer); impl AudioStream { pub fn into_input(self) -> Input { // Clear the stream to minimize latency self.0.lock().clear(); Input::new( true, Reader::Extension(Box::new(self)), Codec::FloatPcm, Container::Raw, None, ) } } impl Read for AudioStream { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { let mut consumer = self.0.lock(); let stereo = SAMPLE_IN_BYTES * 2; let safe_length = buf.len() / stereo * stereo; consumer .read_exact(&mut buf[..safe_length]) .unwrap_or_default(); Ok(safe_length) } } impl Seek for AudioStream { fn seek(&mut self, _: std::io::SeekFrom) -> std::io::Result { unreachable!() } } impl MediaSource for AudioStream { fn byte_len(&self) -> Option { None } fn is_seekable(&self) -> bool { false } } fn normalize_volume(bytes: &[u8], incoming_volume: f32) -> Vec { let reciprocal = 1. / incoming_volume; let db_loudness = 10. * reciprocal.log(3.); let signal_factor = 10f32.powf(db_loudness / 20.); raw_samples_from_bytes(bytes) .into_iter() .map(|s| s * signal_factor) .flat_map(|s| s.to_le_bytes()) .collect() } ================================================ FILE: src/dickcord/bot.rs ================================================ use super::TargetUser; use crate::{audio::AudioStream, state::Config}; use crossbeam::channel::{unbounded, Receiver, Sender}; use serenity::{ async_trait, client::{bridge::gateway::ShardManager, Context as SerenityContext, EventHandler}, futures::future::{join_all, try_join_all}, model::{ channel::{ChannelType, GuildChannel}, event::ResumedEvent, gateway::{Activity, GatewayIntents, Ready}, guild::Member, id::UserId, user::CurrentUser, voice::VoiceState, }, Client, }; use songbird::{error::JoinError, Call, SerenityInit}; use std::sync::Arc; use tokio::{runtime::Runtime, sync::Mutex}; type ConnectedToChannel = Arc>>; /// The bot handling logic pub struct Bot { event_sender: Sender, event_receiver: Receiver, /// The user the bot should follow target_user: TargetUser, shard_manager: Arc>, context: Arc>>, connected_to_channel: ConnectedToChannel, } /// The event handler for the Serenity client pub struct BotHandler { event_sender: Sender, context: Arc>>, target_user: TargetUser, connected_to_channel: ConnectedToChannel, } #[derive(Clone)] pub enum BotEvent { /// Bot has connected to Discord Connected(CurrentUser), /// Disconnected from Discord, either by an error or intentionally Reconnected, /// Joining a voice channel Joining(GuildChannel), /// Successfully joined a voice channel Joined(GuildChannel), /// Disconnected from voice channel Left, /// The user the bot is following connected or disconnected from a channel TargetUserMoved(Option), // The user the bot is following started or stopped a live stream TargetUserStreamStateChanged(bool), /// Something bad happened, duh. ClientError(String), /// An error occurred with the voice connection VoiceError(String), } impl Bot { pub fn new(rt: Arc, config: &Config) -> Self { let (event_sender, event_receiver) = unbounded(); let connected_to_channel = ConnectedToChannel::default(); let target_user = config.user_id; let context = Arc::new(Mutex::new(None)); let event_handler = BotHandler { context: context.clone(), event_sender: event_sender.clone(), connected_to_channel: connected_to_channel.clone(), target_user, }; let mut client = rt.block_on(async move { Client::builder(&config.bot_token, intents()) .register_songbird() .event_handler(event_handler) .await .expect("client is created") }); let shard_manager = client.shard_manager.clone(); let inner_event_sender = event_sender.clone(); rt.spawn(async move { if let Err(e) = client.start().await { inner_event_sender .send(BotEvent::ClientError(e.to_string())) .unwrap(); } }); Self { context, target_user, event_sender, shard_manager, event_receiver, connected_to_channel, } } pub async fn set_streaming_status(&self, name: Option) { let context = self.context().await; if let Some(name) = name { context .set_activity(Activity::streaming( name, "https://github.com/Enitoni/pulseshitter", )) .await; } else { context.reset_presence().await } } pub async fn attempt_join_and_stream(&self, audio: AudioStream) { let channel = self.locate_target_user_channel().await; let call = match channel { Some(c) => self.connect_to_channel(&c).await, None => None, }; if let Some(call) = call { self.stream_call_audio(call, audio).await; } } pub fn poll(&self) -> BotEvent { self.event_receiver.recv().unwrap() } pub async fn connect_to_channel(&self, channel: &GuildChannel) -> Option>> { let context = self.context().await; let manager = songbird::get(&context) .await .expect("get songbird instance"); self.event_sender .send(BotEvent::Joining(channel.clone())) .unwrap(); let (handler, result) = manager.join(channel.guild_id, channel.id).await; match result { Err(x) => { self.event_sender .send(BotEvent::VoiceError(x.to_string())) .unwrap(); None } Ok(_) => { let _ = self .connected_to_channel .lock() .await .insert(channel.clone()); self.event_sender .send(BotEvent::Joined(channel.clone())) .unwrap(); Some(handler) } } } pub async fn disconnect_from_channel(&self) -> Result<(), JoinError> { let context = self.context().await; let manager = songbird::get(&context).await.unwrap(); if let Some(channel) = self.connected_to_channel.lock().await.take() { return manager.remove(channel.guild_id).await; } self.event_sender.send(BotEvent::Left).unwrap(); Ok(()) } pub async fn stream_call_audio(&self, call: Arc>, audio: AudioStream) { call.lock().await.play_only_source(audio.into_input()); } /// Finds the channel the target user is in, if any pub async fn locate_target_user_channel(&self) -> Option { let context = self.context().await; let members_in_channels = self.all_members_in_channels(&context).await; members_in_channels .into_iter() .find_map(|(members, guild_channel)| { members .into_iter() .find(|m| m.user.id == self.target_user) .map(|_| guild_channel) }) } pub async fn is_target_user_streaming(&self) -> bool { let context = self.context().await; let channel = self.locate_target_user_channel().await; let voice_states = channel .map(|c| c.guild_id) .and_then(|id| context.cache.guild(id)) .map(|guild| guild.voice_states); if let Some(voice_states) = voice_states { let user_id = UserId(self.target_user); return voice_states .get(&user_id) .and_then(|v| v.self_stream) .unwrap_or_default(); } false } async fn all_members_in_channels( &self, context: &SerenityContext, ) -> Vec<(Vec, GuildChannel)> { let channels = self.all_channels(context).await; let member_futures = channels .into_iter() .map(|c| async { (c.members(context).await, c) }); join_all(member_futures) .await .into_iter() .flat_map(|(member, guild)| member.map(|m| (m, guild))) .collect() } async fn all_channels(&self, context: &SerenityContext) -> Vec { let guilds = context.cache.guilds(); let channel_futures = guilds.into_iter().map(|g| g.channels(context)); try_join_all(channel_futures) .await .unwrap_or_default() .into_iter() .flat_map(|h| h.into_values()) .filter(|c| matches!(c.kind, ChannelType::Voice)) .collect() } async fn context(&self) -> SerenityContext { self.context .lock() .await .clone() .expect("context() is not called before initialization") } pub async fn stop(&self) { let mut manager = self.shard_manager.lock().await; let context = self.context.lock().await.clone(); if let Some(context) = context { let _ = self.disconnect_from_channel().await; context.invisible().await } manager.shutdown_all().await } } #[async_trait] impl EventHandler for BotHandler { async fn ready(&self, context: SerenityContext, ready: Ready) { *self.context.lock().await = Some(context.clone()); self.event_sender .send(BotEvent::Connected(ready.user.clone())) .unwrap(); } async fn resume(&self, _context: SerenityContext, _resumed: ResumedEvent) { self.event_sender.send(BotEvent::Reconnected).unwrap() } async fn voice_state_update( &self, context: SerenityContext, old: Option, new: VoiceState, ) { if new.user_id != self.target_user { return; } let has_changed = old .as_ref() .map(|o| o.channel_id != new.channel_id) .unwrap_or_default(); let old_stream_state = old.and_then(|o| o.self_stream).unwrap_or_default(); let new_stream_state = new.self_stream.unwrap_or_default(); if old_stream_state != new_stream_state { self.event_sender .send(BotEvent::TargetUserStreamStateChanged(new_stream_state)) .unwrap(); } if !has_changed { return; } let connected_to_channel = self.connected_to_channel.lock().await; let new_channel = new .channel_id .filter(|x| Some(*x) != connected_to_channel.as_ref().map(|x| x.id)); if let Some(channel_id) = new_channel { let channel = context.cache.guild_channel(channel_id); self.event_sender .send(BotEvent::TargetUserMoved(channel)) .unwrap(); } else { self.event_sender .send(BotEvent::TargetUserMoved(None)) .unwrap(); } } } fn intents() -> GatewayIntents { GatewayIntents::GUILDS | GatewayIntents::GUILD_MEMBERS | GatewayIntents::DIRECT_MESSAGES | GatewayIntents::GUILD_VOICE_STATES } ================================================ FILE: src/dickcord/mod.rs ================================================ mod bot; mod system; pub use bot::*; pub use system::*; type TargetUser = u64; ================================================ FILE: src/dickcord/system.rs ================================================ use crate::{ app::AppEvent, audio::{AudioStream, Source}, state::{Config, ReadOnlyConfig}, }; use super::{Bot, BotEvent}; use crossbeam::{atomic::AtomicCell, channel::Sender}; use parking_lot::Mutex; use serenity::model::{channel::GuildChannel, user::CurrentUser}; use std::{sync::Arc, thread, time::Duration}; use tokio::runtime::Runtime; /// Manages all discord related things pub struct DiscordSystem { rt: Arc, app_events: Sender, bot: Mutex>>, state: Mutex, is_streaming: AtomicCell, config: Mutex>, stream: AudioStream, } #[allow(clippy::large_enum_variant)] #[derive(Debug, Default, Clone)] pub enum State { #[default] Idle, Connecting, Connected(CurrentUser, VoiceState), Error(String), } #[derive(Debug, Default, Clone)] pub enum VoiceState { #[default] Idle, Joining(GuildChannel), Active(GuildChannel), Error(String), } impl DiscordSystem { pub fn new(rt: Arc, app_events: Sender, stream: AudioStream) -> Arc { let system = Arc::new(Self { rt, stream, bot: Default::default(), state: Default::default(), is_streaming: Default::default(), config: Default::default(), app_events, }); spawn_discord_event_thread(system.clone()); system } pub fn connect(&self, config: &Config) { let bot = Bot::new(self.rt.clone(), config).into(); *self.bot.lock() = Some(bot); *self.config.lock() = Some(config.read_only()); self.set_state(State::Connecting); } pub fn disconnect(&self) { let bot = self.bot.lock().take(); if let Some(bot) = bot { self.rt.block_on(async move { bot.stop().await }); } self.set_state(State::Idle); } pub fn announce_source_streaming(&self, source: Option) { let bot = self.bot_unwrapped(); let name = source.map(|s| s.name()); self.rt .spawn(async move { bot.set_streaming_status(name).await }); } pub fn state(&self) -> State { self.state.lock().clone() } fn stream_on_demand(&self) { let audio = self.stream.clone(); let config = self.config_unwrapped(); let state = self.state.lock().clone(); let bot = self.bot_unwrapped(); if config.screen_share_only { let is_streaming = self.is_streaming.load(); if state.is_connected() && !is_streaming { self.set_voice_state(VoiceState::Idle); self.rt .spawn(async move { bot.disconnect_from_channel().await.ok() }); return; } if !is_streaming { return; } } self.rt .spawn(async move { bot.attempt_join_and_stream(audio).await }); } fn set_state(&self, new_state: State) { *self.state.lock() = new_state.clone(); self.app_events .send(AppEvent::DiscordStateUpdate(new_state)) .unwrap(); } fn set_voice_state(&self, new_voice_state: VoiceState) { self.state.lock().set_voice_state(new_voice_state) } fn handle_event(&self, event: BotEvent) { match event { BotEvent::Connected(user) => self.handle_connected(user), BotEvent::Joined(channel) => self.handle_joined(channel), BotEvent::Joining(channel) => self.handle_joining(channel), BotEvent::Left => self.handle_left(), BotEvent::ClientError(error) => self.handle_client_error(error), BotEvent::VoiceError(error) => self.handle_voice_error(error), BotEvent::TargetUserMoved(new_channel) => self.handle_target_user_moved(new_channel), BotEvent::TargetUserStreamStateChanged(new_state) => { self.handle_target_user_stream_state_changed(new_state) } BotEvent::Reconnected => {} } } fn handle_connected(&self, user: CurrentUser) { self.set_state(State::Connected(user, VoiceState::Idle)); let bot = self.bot_unwrapped(); let is_streaming = self .rt .block_on(async move { bot.is_target_user_streaming().await }); self.is_streaming.store(is_streaming); self.stream_on_demand(); } fn handle_client_error(&self, error: String) { self.set_state(State::Error(error)) } fn handle_joining(&self, channel: GuildChannel) { self.set_voice_state(VoiceState::Joining(channel)) } fn handle_joined(&self, channel: GuildChannel) { self.set_voice_state(VoiceState::Active(channel)) } fn handle_left(&self) { self.set_voice_state(VoiceState::Idle) } fn handle_voice_error(&self, error: String) { self.set_voice_state(VoiceState::Error(error)) } fn handle_target_user_moved(&self, new_channel: Option) { if let Some(new_channel) = new_channel { self.set_voice_state(VoiceState::Active(new_channel)); self.stream_on_demand(); } else { self.set_voice_state(VoiceState::Idle); let bot = self.bot_unwrapped(); self.rt.spawn(async move { bot.disconnect_from_channel().await.ok(); }); } } fn handle_target_user_stream_state_changed(&self, new_state: bool) { self.is_streaming.store(new_state); self.stream_on_demand(); } fn bot_unwrapped(&self) -> Arc { self.bot .lock() .clone() .expect("bot_unwrapped() is not called when there is not a bot") } pub fn set_config(&self, config: ReadOnlyConfig) { *self.config.lock() = Some(config); self.stream_on_demand(); } fn config_unwrapped(&self) -> ReadOnlyConfig { self.config .lock() .clone() .expect("config_unwrapped() is not called when there is not a config") } } impl State { fn set_voice_state(&mut self, new_state: VoiceState) { match self { Self::Connected(user, _) => *self = Self::Connected(user.clone(), new_state), _ => { eprintln!("set_voice_state() was called when not connected.") } } } fn is_connected(&self) -> bool { matches!(self, Self::Connected(_, _)) } } fn spawn_discord_event_thread(discord: Arc) { let run = move || loop { let bot = discord.bot.lock().clone(); let event = bot.map(|b| b.poll()); if let Some(event) = event { discord.handle_event(event) } else { thread::sleep(Duration::from_millis(1)) } }; thread::Builder::new() .name("discord-events".to_string()) .spawn(run) .unwrap(); } ================================================ FILE: src/interface/components/mod.rs ================================================ mod text_field; pub use text_field::*; ================================================ FILE: src/interface/components/text_field.rs ================================================ use crossterm::event::Event; use tui::{ buffer::Buffer, layout::{Constraint, Direction, Layout, Rect}, style::{Modifier, Style}, widgets::{Paragraph, Widget}, }; use tui_textarea::TextArea; use crate::interface::View; pub struct TextField { label: String, area: TextArea<'static>, } impl TextField { pub fn new(label: &str) -> Self { let label = label.to_string(); let area = TextArea::new(vec!["".to_string()]); let mut result = Self { label, area }; result.blur(); result } pub fn focus(&mut self) { self.area .set_cursor_style(Style::default().add_modifier(Modifier::REVERSED)); self.area .set_cursor_line_style(Style::default().add_modifier(Modifier::UNDERLINED)); } pub fn blur(&mut self) { self.area.set_cursor_style(Style::reset()); self.area.set_cursor_line_style(Style::reset()); } pub fn value(&self) -> String { self.area.lines()[0].to_string() } } impl View for TextField { fn render(&self, area: Rect, buf: &mut Buffer) { let text = Paragraph::new(self.label.clone()).style(Style::default().add_modifier(Modifier::BOLD)); let chunks = Layout::default() .direction(Direction::Vertical) .constraints([Constraint::Length(1), Constraint::Length(1)]) .split(area); text.render(chunks[0], buf); self.area.widget().render(chunks[1], buf); } fn handle_event(&mut self, event: Event) { if let Event::Key(key) = event { self.area.input(key); } } } ================================================ FILE: src/interface/dashboard/discord_module.rs ================================================ use tui::{ buffer::Buffer, layout::{Constraint, Direction, Layout, Rect}, style::{Color, Style}, widgets::{Block, Borders, Paragraph, Widget, Wrap}, }; use crate::{ app::AppContext, dickcord::{State, VoiceState}, interface::View, }; pub struct DiscordModule { context: AppContext, } impl DiscordModule { pub fn new(context: AppContext) -> Self { Self { context } } } impl View for DiscordModule { fn render(&self, area: Rect, buf: &mut Buffer) { let block = Block::default() .border_style(Style::default().fg(Color::DarkGray)) .title("─ Discord ") .borders(Borders::all()); let block_inner = { let area = block.inner(area); tui::layout::Rect::new( area.left() + 2, area.top() + 1, area.width - 2, area.height - 1, ) }; let chunks = Layout::default() .direction(Direction::Vertical) .constraints([Constraint::Length(1), Constraint::Length(1)]) .split(block_inner); block.render(area, buf); let state = self.context.discord_state(); if let State::Error(err) = &state { let paragraph = Paragraph::new(format!("⚠ An error occurred! {}", err)) .style(Style::default().fg(Color::Red)) .wrap(Wrap { trim: false }); paragraph.render(block_inner, buf); } if let State::Connecting = &state { let paragraph = Paragraph::new("Logging in, please wait...") .style(Style::default().fg(Color::Yellow)); paragraph.render(chunks[0], buf); } if let State::Connected(user, voice_state) = state { let paragraph = Paragraph::new(format!("● {}", user.name)).style(Style::default().fg(Color::Green)); paragraph.render(chunks[0], buf); if let VoiceState::Idle = &voice_state { let paragraph = Paragraph::new("└ Inactive").style(Style::default().fg(Color::DarkGray)); paragraph.render(chunks[1], buf); } if let VoiceState::Joining(channel) = &voice_state { let paragraph = Paragraph::new(format!("└ Joining {}...", channel.name())) .style(Style::default().fg(Color::Yellow)); paragraph.render(chunks[1], buf); } if let VoiceState::Active(channel) = &voice_state { let paragraph = Paragraph::new(format!("└ 🔊\u{FE0E} {}", channel.name())) .style(Style::default().fg(Color::Green)); paragraph.render(chunks[1], buf); } } } } ================================================ FILE: src/interface/dashboard/meter.rs ================================================ use tui::{ layout::{Constraint, Direction, Layout, Rect}, style::{Color, Style}, }; use crate::{app::AppContext, interface::View}; pub struct Meter { context: AppContext, } impl Meter { pub fn new(context: AppContext) -> Self { Self { context } } fn render_meter(&self, value: f32, area: tui::layout::Rect, buf: &mut tui::buffer::Buffer) { let value = value.min(1.); let bar_width = area.width as f32 * value; let amount_of_full_characters = bar_width.floor() as usize; let partial = bar_width - amount_of_full_characters as f32; let partial_index = (BAR_PARTIALS.len() - 1) as f32 * partial; let partial_symbol = BAR_PARTIALS[partial_index as usize]; buf.set_string( area.x + amount_of_full_characters as u16, area.y, partial_symbol, Style::default(), ); buf.set_string( area.x, area.y, BAR_PARTIALS[8].repeat(amount_of_full_characters), Style::default(), ); let mut bar_area = Rect::new(area.x, area.y, area.width, 1); buf.set_style( bar_area, Style::default() .fg(Color::Rgb(82, 224, 45)) .bg(Color::Rgb(10, 17, 9)), ); let yellow_size = (area.width as f32 * 0.4) as u16; bar_area.width = yellow_size; bar_area.x = area.width - yellow_size; buf.set_style( bar_area, Style::default() .fg(Color::Rgb(255, 240, 85)) .bg(Color::Rgb(17, 16, 9)), ); let red_size = (area.width as f32 * 0.1) as u16; bar_area.width = red_size; bar_area.x = (area.width - red_size) + 2; buf.set_style( bar_area, Style::default() .bg(Color::Rgb(17, 10, 9)) .fg(Color::Rgb(199, 54, 28)), ); } } impl View for Meter { fn render(&self, area: Rect, buf: &mut tui::buffer::Buffer) { let (left, right) = self.context.meter_value_ranged(); let chunks = Layout::default() .direction(Direction::Vertical) .constraints([Constraint::Length(2), Constraint::Length(1)]) .split(area); self.render_meter(left, chunks[0], buf); self.render_meter(right, chunks[1], buf); } } const BAR_PARTIALS: [&str; 9] = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"]; ================================================ FILE: src/interface/dashboard/mod.rs ================================================ use crossterm::event::{Event, KeyCode}; use enum_iterator::{next_cycle, Sequence}; use tui::{ buffer::Buffer, layout::{Alignment, Constraint, Direction, Layout, Rect}, style::{Color, Style}, widgets::{Paragraph, Widget, Wrap}, }; mod source_selector; use source_selector::*; mod meter; use meter::*; mod discord_module; use discord_module::*; mod settings_module; use settings_module::*; mod version; use version::*; use crate::app::AppContext; use super::{View, LOGO}; pub struct Dashboard { content: Content, version: Version, } pub struct Content { context: AppContext, selector_module: SourceSelector, discord_module: DiscordModule, settings_module: SettingsModule, focused_module: FocusedModule, meter: Meter, } #[derive(Debug, Default, PartialEq, Sequence)] enum FocusedModule { #[default] SourceSelector, SettingsModule, } impl Dashboard { pub fn new(context: AppContext) -> Self { let mut selector_module = SourceSelector::new(context.clone()); selector_module.focus(); Self { version: Version::new(context.clone()), content: Content { selector_module, discord_module: DiscordModule::new(context.clone()), settings_module: SettingsModule::new(context.clone()), focused_module: Default::default(), meter: Meter::new(context.clone()), context, }, } } } impl View for Dashboard { fn render(&self, area: Rect, buf: &mut Buffer) { let is_big_enough = area.width >= 70 && area.height >= 29; if !is_big_enough { let text = "Please resize your terminal window."; let centered_y = area.height / 2; let centered_area = Rect::new(area.x, centered_y, area.width, area.height - centered_y); let notice = Paragraph::new(text) .alignment(Alignment::Center) .wrap(Wrap { trim: false }); notice.render(centered_area, buf); return; } let chunks = Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Length(4), Constraint::Length(area.height.saturating_sub(6)), Constraint::Length(2), ]) .horizontal_margin(1) .split(area); let logo = Paragraph::new(LOGO).alignment(Alignment::Center); let footer_style = Style::default().fg(Color::DarkGray); let copyright = Paragraph::new("© 2024 Enitoni, Some rights reserved.") .alignment(Alignment::Left) .style(footer_style); let footer_chunks = Layout::default() .direction(Direction::Horizontal) .constraints([Constraint::Percentage(50), Constraint::Percentage(50)]) .horizontal_margin(1) .split(chunks[2]); logo.render(chunks[0], buf); self.content.render(chunks[1], buf); copyright.render(footer_chunks[0], buf); self.version.render(footer_chunks[1], buf); } fn handle_event(&mut self, event: crossterm::event::Event) { self.content.handle_event(event) } } impl Content { fn cycle_focus(&mut self) { self.focused_module = next_cycle(&self.focused_module).expect("Implements sequence"); self.selector_module.blur(); self.settings_module.blur(); match self.focused_module { FocusedModule::SourceSelector => self.selector_module.focus(), FocusedModule::SettingsModule => self.settings_module.focus(), } } } impl View for Content { fn render(&self, area: Rect, buf: &mut Buffer) { let config = self.context.config(); let mut chunk_constraints = vec![Constraint::Length(area.height.saturating_sub(5))]; if config.show_meter { chunk_constraints.push(Constraint::Length(4)) } let chunks = Layout::default() .direction(Direction::Vertical) .constraints(chunk_constraints) .split(area); let main_chunks = Layout::default() .direction(Direction::Horizontal) .constraints([ Constraint::Length(area.width.saturating_sub(38)), Constraint::Length(38), ]) .split(chunks[0]); let sidebar_area = main_chunks[1]; let sidebar_area = tui::layout::Rect::new( sidebar_area.x + 1, sidebar_area.y, sidebar_area.width.saturating_sub(1), sidebar_area.height, ); let sidebar_chunks = Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Length(6), Constraint::Length(sidebar_area.height.saturating_sub(7)), ]) .split(sidebar_area); self.selector_module.render(main_chunks[0], buf); self.settings_module.render(sidebar_chunks[1], buf); self.discord_module.render(sidebar_chunks[0], buf); if config.show_meter { let mut meter_area = chunks[1]; meter_area.x += 1; meter_area.y += 1; meter_area.width -= 1; self.meter.render(meter_area, buf); } } fn handle_event(&mut self, event: Event) { if let Event::Key(key) = event { if key.code == KeyCode::Tab || key.code == KeyCode::Right || key.code == KeyCode::Left { self.cycle_focus(); return; } } match self.focused_module { FocusedModule::SourceSelector => self.selector_module.handle_event(event), FocusedModule::SettingsModule => self.settings_module.handle_event(event), } } } ================================================ FILE: src/interface/dashboard/settings_module.rs ================================================ use crossterm::event::{Event, KeyCode}; use tui::{ buffer::Buffer, layout::{Constraint, Direction, Layout, Rect}, style::{Color, Style}, widgets::{Block, Borders, Paragraph, Widget}, }; use crate::{ app::{AppAction, AppContext}, interface::View, }; struct Option { context: AppContext, action: AppAction, paragraph: String, kind: OptionKind, focused: bool, } enum OptionKind { Switch(bool), Button, } pub struct SettingsModule { options: Vec