Full Code of Enitoni/pulseshitter for AI

main cfce112a0c97 cached
28 files
119.1 KB
27.7k tokens
285 symbols
1 requests
Download .txt
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<Runtime>,
    interface: Interface,
    audio: Arc<AudioSystem>,
    discord: Arc<DiscordSystem>,

    events: Sender<AppEvent>,
    state: Arc<Mutex<AppState>>,

    config: Arc<Mutex<Option<Config>>>,
    update_available: Arc<Mutex<Option<String>>>,
}

#[derive(Clone)]
pub struct AppContext {
    events: Sender<AppEvent>,
    audio: Arc<AudioSystem>,
    discord: Arc<DiscordSystem>,
    config: Arc<Mutex<Option<Config>>>,
    update_available: Arc<Mutex<Option<String>>>,
}

#[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<Arc<Self>, 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<App>, receiver: Receiver<AppEvent>) {
    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<Source> {
        self.audio.sources()
    }

    pub fn current_source(&self) -> Option<Source> {
        self.audio.current_source()
    }

    pub fn selected_source(&self) -> Option<Source> {
        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<String> {
        self.update_available.lock().clone()
    }
}

#[derive(Debug, Deserialize)]
struct LatestRelease {
    tag_name: String,
}

async fn fetch_update() -> Option<String> {
    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<usize>,

    current_value: AtomicCell<f32>,

    buffer: Mutex<Vec<f32>>,
}

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<Sample> {
    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<StereoMeter>) {
    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<Mutex<HeapProducer<u8>>>;
pub type AudioConsumer = Arc<Mutex<HeapConsumer<u8>>>;

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<Mutex<Context>>,
    introspector: Introspector,
    props: Proplist,
    spec: Spec,

    pub(super) events: Receiver<PulseClientEvent>,
    event_sender: Sender<PulseClientEvent>,
}

impl PulseClient {
    pub fn new() -> Result<Self, PulseClientError> {
        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<Vec<SinkInput>, 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<SinkInputStream, PulseClientError> {
        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<u8>),
}

#[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<Mutex<Context>>,
    stream: Arc<Mutex<Stream>>,

    status: Arc<RwLock<SinkInputStreamStatus>>,
    event_sender: Sender<PulseClientEvent>,
}

impl SinkInputStream {
    fn new(
        context: Arc<Mutex<Context>>,
        event_sender: Sender<PulseClientEvent>,
        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<PulseClient>,
    current_source: Mutex<Option<Source>>,

    /// The source the user selected.
    /// Not to be confused with current source which is what is currently being streamed.
    selected_source: Mutex<Option<Source>>,
    stored_sources: Mutex<Vec<Source>>,
}

impl SourceSelector {
    pub fn new(client: Arc<PulseClient>) -> Self {
        let sources: Vec<Source> = 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<Source> {
        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<Source> {
        self.current_source.lock().clone().filter(|s| s.available())
    }

    pub fn selected_source(&self) -> Option<Source> {
        self.selected_source.lock().clone()
    }

    pub(super) fn select(&self, source: Option<Source>) {
        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<Source> = 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<Mutex<SinkInput>>,

    /// The best fitting name for this source
    name: Arc<RwLock<String>>,

    /// 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<AtomicCell<bool>>,
    age: Arc<AtomicCell<Instant>>,

    /// Volume of the sink input, used for normalization
    volume: Arc<AtomicCell<f32>>,
}

#[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<T: AsRef<str>>(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<T: AsRef<str>>(&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<T: AsRef<str>>(name: T) -> Option<Self> {
        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<T: AsRef<str>>(&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<BrowserKind> for SourceKind {
    fn from(value: BrowserKind) -> Self {
        Self::BrowserTab(value)
    }
}

impl From<SinkInput> 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<PulseClient>,

    selector: Arc<SourceSelector>,
    stream: Arc<Mutex<Option<SinkInputStream>>>,

    producer: AudioProducer,
    consumer: AudioConsumer,

    meter: Arc<StereoMeter>,
}

impl AudioSystem {
    pub fn new() -> Result<Arc<Self>, 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<Source>) {
        self.selector.select(source);
        self.refresh_stream();
    }

    pub fn stream(&self) -> AudioStream {
        AudioStream(self.consumer.clone())
    }

    pub fn sources(&self) -> Vec<Source> {
        self.selector.sources()
    }

    pub fn current_source(&self) -> Option<Source> {
        self.selector.current_source()
    }

    pub fn selected_source(&self) -> Option<Source> {
        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<AudioSystem>) {
    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<usize> {
        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<u64> {
        unreachable!()
    }
}

impl MediaSource for AudioStream {
    fn byte_len(&self) -> Option<u64> {
        None
    }

    fn is_seekable(&self) -> bool {
        false
    }
}

fn normalize_volume(bytes: &[u8], incoming_volume: f32) -> Vec<u8> {
    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<Mutex<Option<GuildChannel>>>;

/// The bot handling logic
pub struct Bot {
    event_sender: Sender<BotEvent>,
    event_receiver: Receiver<BotEvent>,

    /// The user the bot should follow
    target_user: TargetUser,

    shard_manager: Arc<Mutex<ShardManager>>,
    context: Arc<Mutex<Option<SerenityContext>>>,

    connected_to_channel: ConnectedToChannel,
}

/// The event handler for the Serenity client
pub struct BotHandler {
    event_sender: Sender<BotEvent>,
    context: Arc<Mutex<Option<SerenityContext>>>,

    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<GuildChannel>),
    // 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<Runtime>, 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<String>) {
        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<Arc<Mutex<Call>>> {
        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<Mutex<Call>>, 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<GuildChannel> {
        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<Member>, 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<GuildChannel> {
        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<VoiceState>,
        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<Runtime>,
    app_events: Sender<AppEvent>,

    bot: Mutex<Option<Arc<Bot>>>,
    state: Mutex<State>,
    is_streaming: AtomicCell<bool>,

    config: Mutex<Option<ReadOnlyConfig>>,
    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<Runtime>, app_events: Sender<AppEvent>, stream: AudioStream) -> Arc<Self> {
        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<Source>) {
        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<GuildChannel>) {
        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<Bot> {
        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<DiscordSystem>) {
    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<Option>,
    selected_option: usize,
    focused: bool,
}

impl SettingsModule {
    pub fn new(context: AppContext) -> Self {
        let config = context.config();

        Self {
            options: vec![
                Option::new(
                    context.clone(),
                    "Show Meter".to_owned(),
                    OptionKind::Switch(config.show_meter),
                    AppAction::ToggleMeter,
                ),
                Option::new(
                    context.clone(),
                    "Screenshare Only".to_owned(),
                    OptionKind::Switch(config.screen_share_only),
                    AppAction::ToggleScreenshareOnly,
                ),
                Option::new(
                    context.clone(),
                    "Redo Setup".to_owned(),
                    OptionKind::Button,
                    AppAction::RedoSetup,
                ),
            ],
            focused: false,
            selected_option: 0,
        }
    }

    fn navigate(&mut self, amount: isize) {
        let new_index =
            ((self.selected_option) as isize + amount).rem_euclid(self.options.len() as isize);

        self.selected_option = new_index as usize;
        self.update_focus_states()
    }

    fn update_focus_states(&mut self) {
        for option in self.options.iter_mut() {
            option.blur();
        }

        if self.focused {
            self.options[self.selected_option].focus();
        }
    }

    pub fn focus(&mut self) {
        self.focused = true;
        self.update_focus_states();
    }

    pub fn blur(&mut self) {
        self.focused = false;
        self.update_focus_states();
    }
}

impl View for SettingsModule {
    fn render(&self, area: Rect, buf: &mut Buffer) {
        let block = Block::default()
            .border_style(Style::default().fg(Color::DarkGray))
            .title("─ Settings ")
            .borders(Borders::all());

        let block_inner = {
            let area = block.inner(area);
            Rect::new(
                area.left() + 2,
                area.top() + 1,
                area.width - 3,
                area.height - 1,
            )
        };

        let calculated_constraints: Vec<_> =
            self.options.iter().map(|_| Constraint::Length(1)).collect();

        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints(calculated_constraints)
            .split(block_inner);

        block.render(area, buf);

        for (index, option) in self.options.iter().enumerate() {
            option.render(chunks[index], buf);
        }
    }

    fn handle_event(&mut self, event: Event) {
        if let Event::Key(key) = event {
            match key.code {
                KeyCode::Up => self.navigate(-1),
                KeyCode::Down => self.navigate(1),
                _ => {}
            };
        }

        self.options[self.selected_option].handle_event(event);
    }
}

impl Option {
    fn new(context: AppContext, name: String, kind: OptionKind, action: AppAction) -> Self {
        Self {
            context,
            paragraph: name,
            focused: false,
            action,
            kind,
        }
    }

    fn toggle_if_switch(&mut self) {
        if let OptionKind::Switch(is_selected) = &self.kind {
            self.kind = OptionKind::Switch(!is_selected);
        }
    }

    fn focus(&mut self) {
        self.focused = true;
    }

    fn blur(&mut self) {
        self.focused = false;
    }
}

impl View for Option {
    fn render(&self, area: Rect, buf: &mut Buffer) {
        let chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Length(area.width - 3), Constraint::Length(3)])
            .split(area);

        let focus_symbol = if self.focused {
            FOCUS_SYMBOL
        } else {
            IDLE_SYMBOL
        };

        let paragraph = Paragraph::new(format!("{} {}", focus_symbol, self.paragraph));
        paragraph.render(chunks[0], buf);

        if let OptionKind::Switch(is_selected) = &self.kind {
            let symbol = if *is_selected { "ON" } else { "OFF" };

            let paragraph = Paragraph::new(symbol).style(if *is_selected {
                Style::default().fg(Color::Green)
            } else {
                Style::default().fg(Color::DarkGray)
            });

            paragraph.render(chunks[1], buf);
        }
    }

    fn handle_event(&mut self, event: Event) {
        if let Event::Key(key) = event {
            if key.code == KeyCode::Enter {
                self.toggle_if_switch();
                self.context.dispatch_action(self.action.clone());
            }
        }
    }
}

const IDLE_SYMBOL: &str = "○";
const FOCUS_SYMBOL: &str = "●";


================================================
FILE: src/interface/dashboard/source_selector.rs
================================================
use crossterm::event::{Event, KeyCode};
use parking_lot::Mutex;
use tui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Style},
    widgets::{Block, Borders, Paragraph, Widget},
};

use crate::{
    app::{AppAction, AppContext},
    dickcord,
    interface::View,
};

pub struct SourceSelector {
    context: AppContext,
    selected_index: Mutex<usize>,
    focused: bool,
}

impl SourceSelector {
    pub fn new(context: AppContext) -> Self {
        Self {
            context,
            selected_index: Default::default(),
            focused: false,
        }
    }

    pub fn navigate(&mut self, amount: isize) {
        let mut selected_index = self.selected_index.lock();
        let app_length = self.context.sources().len() as isize;

        let new_index = ((*selected_index) as isize + amount).rem_euclid(app_length);
        *selected_index = new_index as usize;
    }

    pub fn select(&self) {
        let selected_source = self.context.current_source();
        let selected_index = self.selected_index.lock();
        let sources = self.context.sources();

        if let Some(source) = sources.get(*selected_index) {
            let selected_app_index = selected_source
                .as_ref()
                .map(|a| a.index())
                .unwrap_or_default();

            // Stop the stream if pressing play on the same one
            if source.index() == selected_app_index {
                self.context.dispatch_action(AppAction::StopStream);
            } else {
                self.context
                    .dispatch_action(AppAction::SetAudioSource(source.to_owned()));
            }
        }
    }

    pub fn focus(&mut self) {
        self.focused = true;
    }

    pub fn blur(&mut self) {
        self.focused = false;
    }
}

impl View for SourceSelector {
    fn render(&self, area: Rect, buf: &mut Buffer) {
        let block = Block::default()
            .title("─ Sources ")
            .border_style(Style::default().fg(Color::DarkGray))
            .borders(Borders::all());

        // Add margins
        let block_inner = {
            let area = block.inner(area);
            tui::layout::Rect::new(area.left() + 2, area.top() + 1, area.width - 2, area.height)
        };

        block.render(area, buf);

        let sources = self.context.sources();

        let selected_index = self.selected_index.lock();

        let selected_source = self.context.selected_source();
        let current_source = self.context.current_source();

        let discord_state = self.context.discord_state();
        let is_discord_ready = matches!(discord_state, dickcord::State::Connected(_, _));

        let top = block_inner.top();

        for (index, source) in sources.iter().enumerate() {
            let is_over = *selected_index == index;

            let is_active = current_source
                .as_ref()
                .map(|f| f.index() == source.index())
                .unwrap_or_default();

            let is_selected = selected_source
                .as_ref()
                .map(|f| f.index() == source.index())
                .unwrap_or_default();

            let paragraph_area = tui::layout::Rect::new(
                block_inner.left(),
                top + index as u16,
                block_inner.width,
                1,
            );

            let symbol = if !is_discord_ready || !self.focused {
                IDLE_SYMBOL
            } else if is_over {
                HOVER_SYMBOL
            } else if is_selected {
                ACTIVE_SYMBOL
            } else {
                IDLE_SYMBOL
            };

            let color = if !is_discord_ready {
                DISABLE_COLOR
            } else if is_active {
                ACTIVE_COLOR
            } else if source.available() {
                IDLE_COLOR
            } else {
                UNAVAILABLE_COLOR
            };

            let paragraph = Paragraph::new(format!("{} {}", symbol, source.name()))
                .style(Style::default().fg(color));

            paragraph.render(paragraph_area, buf);
        }
    }

    fn handle_event(&mut self, event: Event) {
        {
            let discord_state = self.context.discord_state();

            // Prevent selecting app before discord connects
            if !matches!(discord_state, dickcord::State::Connected(_, _)) {
                return;
            }
        }

        if let Event::Key(key) = event {
            match key.code {
                KeyCode::Up => self.navigate(-1),
                KeyCode::Down => self.navigate(1),
                KeyCode::Enter => self.select(),
                _ => {}
            }
        }
    }
}

const IDLE_SYMBOL: &str = "○";
const HOVER_SYMBOL: &str = "●";
const ACTIVE_SYMBOL: &str = "►";

const ACTIVE_COLOR: Color = Color::Green;
const IDLE_COLOR: Color = Color::Reset;
const DISABLE_COLOR: Color = Color::DarkGray;
const UNAVAILABLE_COLOR: Color = Color::Yellow;


================================================
FILE: src/interface/dashboard/version.rs
================================================
use tui::{
    buffer::Buffer,
    layout::{Alignment, Rect},
    style::{Color, Style},
    widgets::{Paragraph, Widget},
};

use crate::{
    app::{AppContext, VERSION},
    interface::View,
};

pub struct Version {
    context: AppContext,
}

impl Version {
    pub fn new(context: AppContext) -> Self {
        Self { context }
    }
}

impl View for Version {
    fn render(&self, area: Rect, buf: &mut Buffer) {
        let new_update = self.context.update_available();

        if let Some(new_update) = new_update {
            Paragraph::new(format!("Update available! v{} > {}", VERSION, new_update))
                .alignment(Alignment::Right)
                .style(Style::default().fg(Color::Green))
                .render(area, buf);

            return;
        }

        Paragraph::new(format!("v{}", VERSION))
            .alignment(Alignment::Right)
            .style(Style::default().fg(Color::DarkGray))
            .render(area, buf);
    }
}


================================================
FILE: src/interface/mod.rs
================================================
use std::{
    io, thread,
    time::{Duration, Instant},
};

mod components;
pub use components::*;

mod view;
pub use view::*;

mod splash;
pub use splash::*;

mod dashboard;
pub use dashboard::*;

mod setup;
pub use setup::*;

use crossbeam::{
    atomic::AtomicCell,
    channel::{unbounded, Receiver, Sender},
};
use crossterm::{
    event::{read, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyModifiers},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use parking_lot::Mutex;
use tui::{backend::CrosstermBackend, Terminal};

use crate::app::{AppAction, AppEvent};

pub const TARGET_FPS: u32 = 144;
pub const MS_PER_FRAME: f32 = 1000. / TARGET_FPS as f32;

pub const LOGO: &str = "
█▀█ █░█ █░░ █▀ █▀▀ █▀ █░█ █ ▀█▀ ▀█▀ █▀▀ █▀█
█▀▀ █▄█ █▄▄ ▄█ ██▄ ▄█ █▀█ █ ░█░ ░█░ ██▄ █▀▄
";

/// Handles rendering logic
pub struct Interface {
    view: Mutex<BoxedView>,
    exiting: AtomicCell<bool>,
    sender: Sender<AppEvent>,
}

impl Interface {
    pub fn new<V>(view: V, sender: Sender<AppEvent>) -> Self
    where
        V: View + Sync + Send + 'static,
    {
        Self {
            view: Mutex::new(BoxedView::new(view)),
            exiting: false.into(),
            sender,
        }
    }

    pub fn set_view<V>(&self, view: V)
    where
        V: View + Sync + Send + 'static,
    {
        *self.view.lock() = BoxedView::new(view)
    }

    /// Renders the TUI until exit
    pub fn run(&self) -> Result<(), io::Error> {
        enable_raw_mode()?;

        let mut stdout = io::stdout();
        execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;

        let backend = CrosstermBackend::new(stdout);
        let events = spawn_event_loop();

        let mut terminal = Terminal::new(backend)?;

        'ui: loop {
            let frame_now = Instant::now();
            let mut view = self.view.lock();

            let result = terminal.draw(|f| f.render_widget(&*view, f.size()));

            if let Err(err) = result {
                eprintln!("Failed to draw: {:?}", err);
                break;
            };

            if self.exiting.load() {
                break 'ui;
            }

            while let Ok(event) = events.try_recv() {
                if let Event::Key(key) = &event {
                    if key.modifiers == KeyModifiers::CONTROL && key.code == KeyCode::Char('c') {
                        self.sender.send(AppEvent::Action(AppAction::Exit)).unwrap();
                        continue;
                    }
                }

                view.handle_event(event);
            }

            let elapsed = frame_now.elapsed().as_secs_f32();
            let remainder = (MS_PER_FRAME / 1000.) - elapsed;

            let sleep_duration = Duration::from_secs_f32(remainder.max(0.));

            drop(view);
            thread::sleep(sleep_duration);
        }

        disable_raw_mode()?;
        execute!(
            terminal.backend_mut(),
            LeaveAlternateScreen,
            DisableMouseCapture
        )?;
        terminal.show_cursor()?;

        Ok(())
    }

    pub fn stop(&self) {
        self.exiting.store(true)
    }
}

fn spawn_event_loop() -> Receiver<Event> {
    let (sender, receiver) = unbounded();

    let run = move || loop {
        match read() {
            Ok(event) => {
                if matches!(event, Event::Key(_)) {
                    sender.send(event).expect("Send");
                }
            }
            Err(err) => eprintln!("{:?}", err),
        };
    };

    thread::Builder::new()
        .name("tui-events".to_string())
        .spawn(run)
        .unwrap();

    receiver
}


================================================
FILE: src/interface/setup/form.rs
================================================
use crossterm::event::{Event, KeyCode};
use enum_iterator::{next_cycle, Sequence};
use tui::{
    buffer::Buffer,
    layout::{Constraint, Direction, Layout, Rect},
};

use crate::interface::{TextField, View};

#[derive(Default, PartialEq, Sequence)]
pub enum SelectedField {
    #[default]
    BotToken,
    UserId,
}

pub struct Form {
    selected_field: SelectedField,
    bot_token: TextField,
    user_id: TextField,
}

impl Form {
    pub fn new() -> Self {
        let mut bot_token = TextField::new("Bot Token");
        let user_id = TextField::new("User ID");

        bot_token.focus();

        Self {
            selected_field: Default::default(),
            bot_token,
            user_id,
        }
    }

    fn cycle_selection(&mut self) {
        self.selected_field = next_cycle(&self.selected_field).expect("Implements sequence");

        let (focus, blur) = match self.selected_field {
            SelectedField::BotToken => (&mut self.bot_token, &mut self.user_id),
            SelectedField::UserId => (&mut self.user_id, &mut self.bot_token),
        };

        focus.focus();
        blur.blur();
    }

    pub fn current_selection(&self) -> &SelectedField {
        &self.selected_field
    }

    pub fn current_values(&self) -> (String, String) {
        let bot_token = self.bot_token.value();
        let user_id = self.user_id.value();

        (bot_token, user_id)
    }
}

impl View for Form {
    fn render(&self, area: Rect, buf: &mut Buffer) {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(3), Constraint::Length(4)])
            .split(area);

        self.bot_token.render(chunks[0], buf);
        self.user_id.render(chunks[1], buf);
    }

    fn handle_event(&mut self, event: crossterm::event::Event) {
        if let Event::Key(key) = event {
            if key.code == KeyCode::Tab || key.code == KeyCode::Enter {
                self.cycle_selection();
                return;
            }
        }

        match self.selected_field {
            SelectedField::BotToken => self.bot_token.handle_event(event),
            SelectedField::UserId => self.user_id.handle_event(event),
        };
    }
}


================================================
FILE: src/interface/setup/mod.rs
================================================
use crossterm::event::{Event, KeyCode};
use form::{Form, SelectedField};
use tui::{
    buffer::Buffer,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Span, Spans},
    widgets::{Block, Borders, Paragraph, Widget, Wrap},
};

use crate::{
    app::{AppAction, AppContext},
    dickcord::State as DiscordState,
    state::Config,
};

use super::View;
mod form;

pub struct Setup {
    context: AppContext,
    form: Form,
}

impl Setup {
    pub fn new(context: AppContext) -> Self {
        Self {
            context,
            form: Form::new(),
        }
    }

    fn is_valid(&self) -> bool {
        let (bot_token, user_id) = self.form.current_values();
        !(bot_token.is_empty()) && !(user_id.is_empty())
    }
}

impl View for Setup {
    fn render(&self, area: Rect, buf: &mut Buffer) {
        let outer_margin = Layout::default()
            .constraints([Constraint::Percentage(100)])
            .margin(2)
            .vertical_margin(1)
            .split(area);

        let block = Block::default()
            .title("─ Setup ")
            .borders(Borders::all())
            .border_style(Style::default().fg(Color::DarkGray));

        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(7),
                Constraint::Length(3),
                Constraint::Percentage(100),
            ])
            .margin(1)
            .horizontal_margin(2)
            .split(block.inner(outer_margin[0]));

        let discord_state = self.context.discord_state();

        let status_text = match &discord_state {
            DiscordState::Idle => {
                "Press tab to switch between fields. Press enter to connect when you're done."
                    .to_string()
            }
            DiscordState::Connecting => "Connecting...".to_string(),
            DiscordState::Connected(_, _) => "Connected!".to_string(),
            DiscordState::Error(error) => error.to_string(),
        };

        let status_color = match &discord_state {
            DiscordState::Idle => Color::DarkGray,
            DiscordState::Connecting => Color::Yellow,
            DiscordState::Connected(_, _) => Color::Green,
            DiscordState::Error(_) => Color::Red,
        };

        let status_text = Paragraph::new(status_text).style(Style::default().fg(status_color));

        let help_text = match self.form.current_selection() {
            SelectedField::BotToken => get_bot_token_help(),
            SelectedField::UserId => get_user_id_help(),
        };

        self.form.render(chunks[0], buf);
        status_text.render(chunks[1], buf);
        help_text.render(chunks[2], buf);
        block.render(outer_margin[0], buf);
    }

    fn handle_event(&mut self, event: Event) {
        let discord_state = self.context.discord_state();

        // Don't allow the user to input while we're connecting
        if !matches!(discord_state, DiscordState::Idle | DiscordState::Error(_)) {
            return;
        }

        // Handle submission
        if let Event::Key(key) = event {
            if key.code == KeyCode::Enter && self.is_valid() {
                let (bot_token, user_id) = self.form.current_values();
                let safe_user_id = user_id.parse().unwrap_or_default();

                let new_config = Config::new(bot_token, safe_user_id);
                self.context
                    .dispatch_action(AppAction::SetConfig(new_config));

                return;
            }
        }

        // Otherwise, handle the form events
        self.form.handle_event(event);
    }
}

fn get_bot_token_help() -> Paragraph<'static> {
    let bold = Style::default().add_modifier(Modifier::BOLD);

    let spans = vec![
        Spans::from(vec![
            Span::raw("Required to connect to Discord with a bot. "),
            Span::styled(
                "Make sure \"Server Members Intent\" is enabled in the Bot settings.",
                bold,
            ),
        ]),
        Spans::default(),
        Spans::from(vec![
            Span::raw("If you don't have a bot token at hand, visit https://discord.com/developers/applications/ , Create a new bot by pressing \"New Application\" on the top right of the page, on the application settings page, on the left sidebar go to \"Bot\". Click \"Reset Token\", Discord will generate a bot token pulseshitter can use; copy it, keep it secured, don't lose it. Scroll down, "),
            Span::styled("enable \"Server Members Intent\"", bold),
            Span::raw(", then Save Changes.")
        ]),
        Spans::default(),
        Spans::from(Span::raw("You will need a link to invite your bot into the servers you need to use. On the sidebar, head over to \"OAuth2 > URL Generator.\" Under \"Scopes\" select \"bot\", under \"Bot Permissions\" select \"Connect\" and \"Speak.\" At the bottom, copy the Generated URL and visit it in your browser to invite your bot to your server"))
    ];

    Paragraph::new(spans).wrap(Wrap { trim: false })
}

fn get_user_id_help() -> Paragraph<'static> {
    let spans = vec![
        Spans::from(Span::raw("pulseshitter will automatically join all voice channels this user joins. This should be your own user ID. ")),
        Spans::default(),
        Spans::from(Span::raw("To get your user ID, right click yourself in any server's user list or in a message, then click \"Copy ID.\"")),
        Spans::default(),
        Spans::from(Span::raw("If there's no \"Copy ID\" option, go to Settings > Advanced and enable \"Developer Mode\" and try again."))
    ];

    Paragraph::new(spans).wrap(Wrap { trim: false })
}


================================================
FILE: src/interface/splash.rs
================================================
use tui::{
    layout::Alignment,
    widgets::{Paragraph, Widget},
};

use super::{View, LOGO};
pub struct Splash;

impl View for Splash {
    fn render(&self, area: tui::layout::Rect, buf: &mut tui::buffer::Buffer) {
        let logo = Paragraph::new(LOGO).alignment(Alignment::Center);
        logo.render(area, buf);
    }
}


================================================
FILE: src/interface/view.rs
================================================
use crossterm::event::Event;
use tui::{buffer::Buffer, layout::Rect, widgets::Widget};

pub trait View {
    fn handle_event(&mut self, _event: Event) {}

    fn render(&self, area: Rect, buf: &mut Buffer);
}

pub struct BoxedView {
    view: Box<dyn View + Sync + Send>,
}

impl BoxedView {
    pub fn new<V>(view: V) -> Self
    where
        V: View + Sync + Send + 'static,
    {
        Self {
            view: Box::new(view),
        }
    }
}

impl Widget for &BoxedView {
    fn render(self, area: tui::layout::Rect, buf: &mut tui::buffer::Buffer) {
        self.view.render(area, buf)
    }
}

impl View for BoxedView {
    fn render(&self, area: tui::layout::Rect, buf: &mut tui::buffer::Buffer) {
        self.view.render(area, buf)
    }

    fn handle_event(&mut self, event: Event) {
        self.view.handle_event(event)
    }
}


================================================
FILE: src/main.rs
================================================
use app::App;

mod app;
mod audio;
mod dickcord;
mod interface;
mod state;

fn main() {
    let app = App::new();

    match app {
        Ok(app) => app.run_tui(),
        Err(err) => {
            eprintln!("pulseshitter failed to start. please verify that you have all the required components installed.");
            eprintln!("error: {}", err);
        }
    }
}


================================================
FILE: src/state.rs
================================================
use serde::{Deserialize, Serialize};
use std::env;
use std::io::Write;
use std::{fs::File, io::Read};

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Config {
    pub bot_token: String,
    pub user_id: u64,

    pub show_meter: bool,
    pub screen_share_only: bool,
}

#[derive(Debug, Clone)]
pub struct ReadOnlyConfig {
    pub bot_token: String,
    pub user_id: u64,
    pub show_meter: bool,
    pub screen_share_only: bool,
}

impl Config {
    fn path() -> String {
        let config_dir = env::var("XDG_CONFIG_HOME")
            .or_else(|_| env::var("HOME").map(|path| path + "/.config"))
            .unwrap_or_else(|_| ".".to_string());

        format!("{}/pulseshitter-config.ron", config_dir)
    }

    pub fn new(bot_token: String, user_id: u64) -> Self {
        Self {
            bot_token,
            user_id,
            show_meter: true,
            screen_share_only: false,
        }
    }

    pub fn restore() -> Option<Self> {
        File::open(Self::path())
            .ok()
            .and_then(|mut file| {
                let mut contents = String::new();
                file.read_to_string(&mut contents).map(|_| contents).ok()
            })
            .and_then(|content| ron::from_str(&content).ok())
    }

    pub fn save(&self) {
        match ron::to_string(self) {
            Ok(result) => {
                File::create(Self::path())
                    .ok()
                    .and_then(|mut f| write!(f, "{}", result).ok());
            }
            Err(err) => eprintln!("Config save failed: {:?}", err),
        }
    }

    pub fn read_only(&self) -> ReadOnlyConfig {
        ReadOnlyConfig {
            bot_token: self.bot_token.clone(),
            user_id: self.user_id,
            show_meter: self.show_meter,
            screen_share_only: self.screen_share_only,
        }
    }
}
Download .txt
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
Download .txt
SYMBOL INDEX (285 symbols across 23 files)

FILE: src/app.rs
  constant VERSION (line 15) | pub const VERSION: &str = env!("CARGO_PKG_VERSION");
  constant LATEST_RELEASE_URL (line 16) | const LATEST_RELEASE_URL: &str =
  type App (line 19) | pub struct App {
    method new (line 71) | pub fn new() -> Result<Arc<Self>, AppError> {
    method run_tui (line 106) | pub fn run_tui(&self) {
    method restore (line 114) | fn restore(&self) {
    method context (line 125) | fn context(&self) -> AppContext {
    method exit (line 135) | fn exit(&self) {
    method handle_event (line 145) | fn handle_event(&self, event: AppEvent) {
    method handle_discord_state_update (line 152) | fn handle_discord_state_update(&self, new_state: dickcord::State) {
    method handle_action (line 165) | fn handle_action(&self, action: AppAction) {
    method set_state (line 199) | fn set_state(&self, state: AppState) {
    method state (line 203) | fn state(&self) -> AppState {
    method set_config (line 207) | fn set_config(&self, config: Config) {
    method save_config (line 212) | fn save_config(&self) {
    method edit_config (line 220) | fn edit_config(&self, cb: impl FnOnce(&mut Config)) {
    method read_only_config (line 229) | fn read_only_config(&self) -> ReadOnlyConfig {
    method check_for_update (line 238) | fn check_for_update(&self) {
  type AppContext (line 33) | pub struct AppContext {
    method dispatch_action (line 265) | pub fn dispatch_action(&self, action: AppAction) {
    method sources (line 269) | pub fn sources(&self) -> Vec<Source> {
    method current_source (line 273) | pub fn current_source(&self) -> Option<Source> {
    method selected_source (line 277) | pub fn selected_source(&self) -> Option<Source> {
    method meter_value_ranged (line 281) | pub fn meter_value_ranged(&self) -> (f32, f32) {
    method discord_state (line 285) | pub fn discord_state(&self) -> dickcord::State {
    method config (line 289) | pub fn config(&self) -> ReadOnlyConfig {
    method update_available (line 298) | pub fn update_available(&self) -> Option<String> {
  type AppState (line 42) | enum AppState {
  type AppError (line 48) | pub enum AppError {
  type AppAction (line 54) | pub enum AppAction {
  type AppEvent (line 65) | pub enum AppEvent {
  function spawn_poll_thread (line 251) | fn spawn_poll_thread(app: Arc<App>, receiver: Receiver<AppEvent>) {
  type LatestRelease (line 304) | struct LatestRelease {
  function fetch_update (line 308) | async fn fetch_update() -> Option<String> {

FILE: src/audio/analysis.rs
  type Meter (line 12) | pub struct Meter {
    constant DEFAULT_WINDOW_SIZE (line 21) | const DEFAULT_WINDOW_SIZE: usize = SAMPLE_RATE / 24;
    constant DB_RANGE (line 22) | const DB_RANGE: f32 = 100.;
    constant MAX_SMOOTHING (line 25) | const MAX_SMOOTHING: f32 = 0.1 / 2.;
    constant MIN_SMOOTHING (line 26) | const MIN_SMOOTHING: f32 = 0.2;
    constant SMOOTHING_BOUNDARY (line 29) | const SMOOTHING_BOUNDARY: f32 = 0.5;
    method new (line 31) | pub fn new() -> Self {
    method write (line 39) | pub fn write(&self, buf: &[u8]) {
    method drain (line 55) | pub fn drain(&self, amount: usize) {
    method process (line 62) | pub fn process(&self) {
    method value (line 66) | pub fn value(&self) -> f32 {
    method dbfs (line 70) | pub fn dbfs(&self) -> f32 {
    method value_ranged (line 74) | pub fn value_ranged(&self) -> f32 {
  function process_multiversioned (line 81) | fn process_multiversioned(meter: &Meter) {
  type StereoMeter (line 110) | pub struct StereoMeter {
    method new (line 116) | pub fn new() -> Self {
    method write (line 123) | pub fn write(&self, buf: &[u8]) {
    method process (line 138) | pub fn process(&self) {
    method drain (line 143) | pub fn drain(&self, amount: usize) {
    method value_ranged (line 148) | pub fn value_ranged(&self) -> (f32, f32) {
  method default (line 154) | fn default() -> Self {
  function faster_max (line 159) | fn faster_max(a: f32, b: f32) -> f32 {
  function raw_samples_from_bytes (line 168) | pub fn raw_samples_from_bytes(bytes: &[u8]) -> Vec<Sample> {
  function spawn_analysis_thread (line 178) | pub fn spawn_analysis_thread(meter: Arc<StereoMeter>) {

FILE: src/audio/mod.rs
  type Sample (line 13) | pub type Sample = f32;
  type AudioProducer (line 15) | pub type AudioProducer = Arc<Mutex<HeapProducer<u8>>>;
  type AudioConsumer (line 16) | pub type AudioConsumer = Arc<Mutex<HeapConsumer<u8>>>;
  constant SAMPLE_RATE (line 18) | pub const SAMPLE_RATE: usize = 48000;
  constant SAMPLE_IN_BYTES (line 19) | pub const SAMPLE_IN_BYTES: usize = 4;
  constant LATENCY_IN_SECONDS (line 21) | pub const LATENCY_IN_SECONDS: f32 = 0.05;
  constant BUFFER_SIZE (line 22) | pub const BUFFER_SIZE: usize =

FILE: src/audio/pulse.rs
  type PulseClient (line 33) | pub struct PulseClient {
    method new (line 44) | pub fn new() -> Result<Self, PulseClientError> {
    method setup_mainloop (line 100) | fn setup_mainloop(proplist: Proplist) -> Result<(Context, Mainloop), P...
    method subscribe_to_events (line 138) | pub fn subscribe_to_events(&self) {
    method sink_inputs (line 165) | pub fn sink_inputs(&self) -> Result<Vec<SinkInput>, PulseClientError> {
    method record (line 205) | pub fn record(&self, sink_input: &SinkInput) -> Result<SinkInputStream...
  method drop (line 222) | fn drop(&mut self) {
  type PulseClientError (line 228) | pub enum PulseClientError {
  type PulseClientEvent (line 237) | pub enum PulseClientEvent {
  type SinkInput (line 243) | pub struct SinkInput {
  type SinkInputStream (line 253) | pub struct SinkInputStream {
    method new (line 262) | fn new(
    method set_event_callbacks (line 291) | fn set_event_callbacks(&self) {
    method connect_to_sink_input (line 368) | fn connect_to_sink_input(&self, sink_input: &SinkInput) -> Result<(), ...
    method status (line 394) | pub fn status(&self) -> SinkInputStreamStatus {
  method drop (line 400) | fn drop(&mut self) {
  type SinkInputStreamStatus (line 417) | pub enum SinkInputStreamStatus {

FILE: src/audio/source.rs
  constant ALLOW_SPOTIFY_STREAMING (line 24) | const ALLOW_SPOTIFY_STREAMING: Option<&'static str> = option_env!("ALLOW...
  constant SPOTIFY_NAME (line 25) | const SPOTIFY_NAME: &str = "Spotify";
  constant VAGUE_WORDS (line 28) | const VAGUE_WORDS: [&str; 10] = [
  type SourceSelector (line 34) | pub struct SourceSelector {
    method new (line 45) | pub fn new(client: Arc<PulseClient>) -> Self {
    method sources (line 61) | pub fn sources(&self) -> Vec<Source> {
    method current_source (line 73) | pub fn current_source(&self) -> Option<Source> {
    method selected_source (line 77) | pub fn selected_source(&self) -> Option<Source> {
    method select (line 81) | pub(super) fn select(&self, source: Option<Source>) {
    method handle_sink_input_event (line 94) | pub fn handle_sink_input_event(&self, index: u32, operation: Operation) {
  type Source (line 144) | pub struct Source {
    constant MAX_LIFESPAN (line 171) | const MAX_LIFESPAN: Duration = Duration::from_secs(60);
    method update (line 173) | fn update(&self, incoming: Source) {
    method compare (line 184) | fn compare(&self, rhs: &Source) -> SourceComparison {
    method remove (line 201) | fn remove(&self) {
    method is_dead (line 205) | fn is_dead(&self) -> bool {
    method sink_input (line 209) | pub fn sink_input(&self) -> SinkInput {
    method index (line 213) | pub fn index(&self) -> u32 {
    method available (line 217) | pub fn available(&self) -> bool {
    method volume (line 221) | pub fn volume(&self) -> f32 {
    method name (line 225) | pub fn name(&self) -> String {
    method from (line 320) | fn from(raw: SinkInput) -> Self {
  type SourceComparison (line 163) | enum SourceComparison {
    method is_similar_enough (line 231) | fn is_similar_enough(&self) -> bool {
  type SourceKind (line 243) | pub enum SourceKind {
    method parse (line 249) | fn parse<T: AsRef<str>>(candidates: &[T]) -> Self {
    method determine_name (line 258) | fn determine_name<T: AsRef<str>>(&self, candidates: &[T]) -> String {
    method from (line 314) | fn from(value: BrowserKind) -> Self {
  type BrowserKind (line 273) | pub enum BrowserKind {
    constant FIREFOX (line 279) | const FIREFOX: &'static str = "Firefox";
    constant CHROME (line 280) | const CHROME: &'static str = "Chrome";
    method parse (line 282) | fn parse<T: AsRef<str>>(name: T) -> Option<Self> {
    method determine_tab_name (line 290) | fn determine_tab_name<T: AsRef<str>>(&self, candidates: &[T]) -> String {
  method fmt (line 303) | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  function str_is_doublecase (line 372) | fn str_is_doublecase(str: &str) -> bool {
  function calculate_name_quality (line 376) | fn calculate_name_quality(str: &str) -> i32 {

FILE: src/audio/system.rs
  type AudioSystem (line 19) | pub struct AudioSystem {
    method new (line 32) | pub fn new() -> Result<Arc<Self>, PulseClientError> {
    method select (line 54) | pub fn select(&self, source: Option<Source>) {
    method stream (line 59) | pub fn stream(&self) -> AudioStream {
    method sources (line 63) | pub fn sources(&self) -> Vec<Source> {
    method current_source (line 67) | pub fn current_source(&self) -> Option<Source> {
    method selected_source (line 71) | pub fn selected_source(&self) -> Option<Source> {
    method meter_value_ranged (line 75) | pub fn meter_value_ranged(&self) -> (f32, f32) {
    method refresh_stream (line 79) | fn refresh_stream(&self) {
  function spawn_event_thread (line 95) | fn spawn_event_thread(audio: Arc<AudioSystem>) {
  type AudioStream (line 144) | pub struct AudioStream(AudioConsumer);
    method into_input (line 147) | pub fn into_input(self) -> Input {
  method read (line 162) | fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
  method seek (line 177) | fn seek(&mut self, _: std::io::SeekFrom) -> std::io::Result<u64> {
  method byte_len (line 183) | fn byte_len(&self) -> Option<u64> {
  method is_seekable (line 187) | fn is_seekable(&self) -> bool {
  function normalize_volume (line 192) | fn normalize_volume(bytes: &[u8], incoming_volume: f32) -> Vec<u8> {

FILE: src/dickcord/bot.rs
  type ConnectedToChannel (line 23) | type ConnectedToChannel = Arc<Mutex<Option<GuildChannel>>>;
  type Bot (line 26) | pub struct Bot {
    method new (line 71) | pub fn new(rt: Arc<Runtime>, config: &Config) -> Self {
    method set_streaming_status (line 114) | pub async fn set_streaming_status(&self, name: Option<String>) {
    method attempt_join_and_stream (line 129) | pub async fn attempt_join_and_stream(&self, audio: AudioStream) {
    method poll (line 142) | pub fn poll(&self) -> BotEvent {
    method connect_to_channel (line 146) | pub async fn connect_to_channel(&self, channel: &GuildChannel) -> Opti...
    method disconnect_from_channel (line 182) | pub async fn disconnect_from_channel(&self) -> Result<(), JoinError> {
    method stream_call_audio (line 195) | pub async fn stream_call_audio(&self, call: Arc<Mutex<Call>>, audio: A...
    method locate_target_user_channel (line 200) | pub async fn locate_target_user_channel(&self) -> Option<GuildChannel> {
    method is_target_user_streaming (line 214) | pub async fn is_target_user_streaming(&self) -> bool {
    method all_members_in_channels (line 235) | async fn all_members_in_channels(
    method all_channels (line 252) | async fn all_channels(&self, context: &SerenityContext) -> Vec<GuildCh...
    method context (line 265) | async fn context(&self) -> SerenityContext {
    method stop (line 273) | pub async fn stop(&self) {
  type BotHandler (line 40) | pub struct BotHandler {
  type BotEvent (line 49) | pub enum BotEvent {
  method ready (line 288) | async fn ready(&self, context: SerenityContext, ready: Ready) {
  method resume (line 296) | async fn resume(&self, _context: SerenityContext, _resumed: ResumedEvent) {
  method voice_state_update (line 300) | async fn voice_state_update(
  function intents (line 348) | fn intents() -> GatewayIntents {

FILE: src/dickcord/mod.rs
  type TargetUser (line 7) | type TargetUser = u64;

FILE: src/dickcord/system.rs
  type DiscordSystem (line 15) | pub struct DiscordSystem {
    method new (line 47) | pub fn new(rt: Arc<Runtime>, app_events: Sender<AppEvent>, stream: Aud...
    method connect (line 62) | pub fn connect(&self, config: &Config) {
    method disconnect (line 71) | pub fn disconnect(&self) {
    method announce_source_streaming (line 81) | pub fn announce_source_streaming(&self, source: Option<Source>) {
    method state (line 89) | pub fn state(&self) -> State {
    method stream_on_demand (line 93) | fn stream_on_demand(&self) {
    method set_state (line 119) | fn set_state(&self, new_state: State) {
    method set_voice_state (line 127) | fn set_voice_state(&self, new_voice_state: VoiceState) {
    method handle_event (line 131) | fn handle_event(&self, event: BotEvent) {
    method handle_connected (line 147) | fn handle_connected(&self, user: CurrentUser) {
    method handle_client_error (line 159) | fn handle_client_error(&self, error: String) {
    method handle_joining (line 163) | fn handle_joining(&self, channel: GuildChannel) {
    method handle_joined (line 167) | fn handle_joined(&self, channel: GuildChannel) {
    method handle_left (line 171) | fn handle_left(&self) {
    method handle_voice_error (line 175) | fn handle_voice_error(&self, error: String) {
    method handle_target_user_moved (line 179) | fn handle_target_user_moved(&self, new_channel: Option<GuildChannel>) {
    method handle_target_user_stream_state_changed (line 192) | fn handle_target_user_stream_state_changed(&self, new_state: bool) {
    method bot_unwrapped (line 197) | fn bot_unwrapped(&self) -> Arc<Bot> {
    method set_config (line 204) | pub fn set_config(&self, config: ReadOnlyConfig) {
    method config_unwrapped (line 209) | fn config_unwrapped(&self) -> ReadOnlyConfig {
  type State (line 29) | pub enum State {
    method set_voice_state (line 218) | fn set_voice_state(&mut self, new_state: VoiceState) {
    method is_connected (line 227) | fn is_connected(&self) -> bool {
  type VoiceState (line 38) | pub enum VoiceState {
  function spawn_discord_event_thread (line 232) | fn spawn_discord_event_thread(discord: Arc<DiscordSystem>) {

FILE: src/interface/components/text_field.rs
  type TextField (line 12) | pub struct TextField {
    method new (line 18) | pub fn new(label: &str) -> Self {
    method focus (line 28) | pub fn focus(&mut self) {
    method blur (line 36) | pub fn blur(&mut self) {
    method value (line 41) | pub fn value(&self) -> String {
  method render (line 47) | fn render(&self, area: Rect, buf: &mut Buffer) {
  method handle_event (line 60) | fn handle_event(&mut self, event: Event) {

FILE: src/interface/dashboard/discord_module.rs
  type DiscordModule (line 14) | pub struct DiscordModule {
    method new (line 19) | pub fn new(context: AppContext) -> Self {
  method render (line 25) | fn render(&self, area: Rect, buf: &mut Buffer) {

FILE: src/interface/dashboard/meter.rs
  type Meter (line 8) | pub struct Meter {
    method new (line 13) | pub fn new(context: AppContext) -> Self {
    method render_meter (line 17) | fn render_meter(&self, value: f32, area: tui::layout::Rect, buf: &mut ...
  method render (line 76) | fn render(&self, area: Rect, buf: &mut tui::buffer::Buffer) {
  constant BAR_PARTIALS (line 89) | const BAR_PARTIALS: [&str; 9] = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉",...

FILE: src/interface/dashboard/mod.rs
  type Dashboard (line 29) | pub struct Dashboard {
    method new (line 51) | pub fn new(context: AppContext) -> Self {
  type Content (line 34) | pub struct Content {
    method cycle_focus (line 124) | fn cycle_focus(&mut self) {
  type FocusedModule (line 44) | enum FocusedModule {
  method render (line 70) | fn render(&self, area: Rect, buf: &mut Buffer) {
  method handle_event (line 118) | fn handle_event(&mut self, event: crossterm::event::Event) {
  method render (line 138) | fn render(&self, area: Rect, buf: &mut Buffer) {
  method handle_event (line 190) | fn handle_event(&mut self, event: Event) {

FILE: src/interface/dashboard/settings_module.rs
  type Option (line 14) | struct Option {
    method new (line 138) | fn new(context: AppContext, name: String, kind: OptionKind, action: Ap...
    method toggle_if_switch (line 148) | fn toggle_if_switch(&mut self) {
    method focus (line 154) | fn focus(&mut self) {
    method blur (line 158) | fn blur(&mut self) {
  type OptionKind (line 22) | enum OptionKind {
  type SettingsModule (line 27) | pub struct SettingsModule {
    method new (line 34) | pub fn new(context: AppContext) -> Self {
    method navigate (line 63) | fn navigate(&mut self, amount: isize) {
    method update_focus_states (line 71) | fn update_focus_states(&mut self) {
    method focus (line 81) | pub fn focus(&mut self) {
    method blur (line 86) | pub fn blur(&mut self) {
  method render (line 93) | fn render(&self, area: Rect, buf: &mut Buffer) {
  method handle_event (line 124) | fn handle_event(&mut self, event: Event) {
  method render (line 164) | fn render(&self, area: Rect, buf: &mut Buffer) {
  method handle_event (line 192) | fn handle_event(&mut self, event: Event) {
  constant IDLE_SYMBOL (line 202) | const IDLE_SYMBOL: &str = "○";
  constant FOCUS_SYMBOL (line 203) | const FOCUS_SYMBOL: &str = "●";

FILE: src/interface/dashboard/source_selector.rs
  type SourceSelector (line 16) | pub struct SourceSelector {
    method new (line 23) | pub fn new(context: AppContext) -> Self {
    method navigate (line 31) | pub fn navigate(&mut self, amount: isize) {
    method select (line 39) | pub fn select(&self) {
    method focus (line 60) | pub fn focus(&mut self) {
    method blur (line 64) | pub fn blur(&mut self) {
  method render (line 70) | fn render(&self, area: Rect, buf: &mut Buffer) {
  method handle_event (line 143) | fn handle_event(&mut self, event: Event) {
  constant IDLE_SYMBOL (line 164) | const IDLE_SYMBOL: &str = "○";
  constant HOVER_SYMBOL (line 165) | const HOVER_SYMBOL: &str = "●";
  constant ACTIVE_SYMBOL (line 166) | const ACTIVE_SYMBOL: &str = "►";
  constant ACTIVE_COLOR (line 168) | const ACTIVE_COLOR: Color = Color::Green;
  constant IDLE_COLOR (line 169) | const IDLE_COLOR: Color = Color::Reset;
  constant DISABLE_COLOR (line 170) | const DISABLE_COLOR: Color = Color::DarkGray;
  constant UNAVAILABLE_COLOR (line 171) | const UNAVAILABLE_COLOR: Color = Color::Yellow;

FILE: src/interface/dashboard/version.rs
  type Version (line 13) | pub struct Version {
    method new (line 18) | pub fn new(context: AppContext) -> Self {
  method render (line 24) | fn render(&self, area: Rect, buf: &mut Buffer) {

FILE: src/interface/mod.rs
  constant TARGET_FPS (line 35) | pub const TARGET_FPS: u32 = 144;
  constant MS_PER_FRAME (line 36) | pub const MS_PER_FRAME: f32 = 1000. / TARGET_FPS as f32;
  constant LOGO (line 38) | pub const LOGO: &str = "
  type Interface (line 44) | pub struct Interface {
    method new (line 51) | pub fn new<V>(view: V, sender: Sender<AppEvent>) -> Self
    method set_view (line 62) | pub fn set_view<V>(&self, view: V)
    method run (line 70) | pub fn run(&self) -> Result<(), io::Error> {
    method stop (line 127) | pub fn stop(&self) {
  function spawn_event_loop (line 132) | fn spawn_event_loop() -> Receiver<Event> {

FILE: src/interface/setup/form.rs
  type SelectedField (line 11) | pub enum SelectedField {
  type Form (line 17) | pub struct Form {
    method new (line 24) | pub fn new() -> Self {
    method cycle_selection (line 37) | fn cycle_selection(&mut self) {
    method current_selection (line 49) | pub fn current_selection(&self) -> &SelectedField {
    method current_values (line 53) | pub fn current_values(&self) -> (String, String) {
  method render (line 62) | fn render(&self, area: Rect, buf: &mut Buffer) {
  method handle_event (line 72) | fn handle_event(&mut self, event: crossterm::event::Event) {

FILE: src/interface/setup/mod.rs
  type Setup (line 20) | pub struct Setup {
    method new (line 26) | pub fn new(context: AppContext) -> Self {
    method is_valid (line 33) | fn is_valid(&self) -> bool {
  method render (line 40) | fn render(&self, area: Rect, buf: &mut Buffer) {
  method handle_event (line 95) | fn handle_event(&mut self, event: Event) {
  function get_bot_token_help (line 122) | fn get_bot_token_help() -> Paragraph<'static> {
  function get_user_id_help (line 146) | fn get_user_id_help() -> Paragraph<'static> {

FILE: src/interface/splash.rs
  type Splash (line 7) | pub struct Splash;
  method render (line 10) | fn render(&self, area: tui::layout::Rect, buf: &mut tui::buffer::Buffer) {

FILE: src/interface/view.rs
  type View (line 4) | pub trait View {
    method handle_event (line 5) | fn handle_event(&mut self, _event: Event) {}
    method render (line 7) | fn render(&self, area: Rect, buf: &mut Buffer);
    method render (line 32) | fn render(&self, area: tui::layout::Rect, buf: &mut tui::buffer::Buffe...
    method handle_event (line 36) | fn handle_event(&mut self, event: Event) {
  type BoxedView (line 10) | pub struct BoxedView {
    method new (line 15) | pub fn new<V>(view: V) -> Self
  method render (line 26) | fn render(self, area: tui::layout::Rect, buf: &mut tui::buffer::Buffer) {

FILE: src/main.rs
  function main (line 9) | fn main() {

FILE: src/state.rs
  type Config (line 7) | pub struct Config {
    method path (line 24) | fn path() -> String {
    method new (line 32) | pub fn new(bot_token: String, user_id: u64) -> Self {
    method restore (line 41) | pub fn restore() -> Option<Self> {
    method save (line 51) | pub fn save(&self) {
    method read_only (line 62) | pub fn read_only(&self) -> ReadOnlyConfig {
  type ReadOnlyConfig (line 16) | pub struct ReadOnlyConfig {
Condensed preview — 28 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (128K chars).
[
  {
    "path": ".gitignore",
    "chars": 51,
    "preview": "/target\n/profiling\nconfig.ron\nprofile.json\n/.vscode"
  },
  {
    "path": "Cargo.toml",
    "chars": 852,
    "preview": "[package]\nname = \"pulseshitter\"\nversion = \"3.0.0\"\nedition = \"2021\"\n\n[profile.profiling]\ninherits = \"release\"\ndebug = tru"
  },
  {
    "path": "LICENSE",
    "chars": 16725,
    "preview": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\""
  },
  {
    "path": "README.md",
    "chars": 3191,
    "preview": "# pulseshitter\n\n[![License](https://img.shields.io/github/license/Enitoni/pulseshitter.svg?style=flat)](https://github.c"
  },
  {
    "path": "src/app.rs",
    "chars": 8631,
    "preview": "use crate::{\n    audio::{pulse::PulseClientError, AudioSystem, Source},\n    dickcord::{self, DiscordSystem},\n    interfa"
  },
  {
    "path": "src/audio/analysis.rs",
    "chars": 4860,
    "preview": "use std::{sync::Arc, thread, time::Duration};\n\nuse crossbeam::atomic::AtomicCell;\nuse multiversion::multiversion;\nuse pa"
  },
  {
    "path": "src/audio/mod.rs",
    "chars": 546,
    "preview": "mod analysis;\npub mod pulse;\nmod source;\nmod system;\n\nuse std::sync::Arc;\n\nuse parking_lot::Mutex;\nuse ringbuf::{HeapCon"
  },
  {
    "path": "src/audio/pulse.rs",
    "chars": 13032,
    "preview": "// TODO: Remove this once the dead code is used\n#![allow(unused)]\n\nuse std::{\n    sync::{mpsc, Arc},\n    thread,\n    tim"
  },
  {
    "path": "src/audio/source.rs",
    "chars": 11839,
    "preview": "// TODO: Remove this once the dead code is used\n#![allow(unused)]\n\nuse super::pulse::{PulseClient, SinkInput};\nuse cross"
  },
  {
    "path": "src/audio/system.rs",
    "chars": 5432,
    "preview": "use std::{\n    io::{Read, Seek},\n    sync::Arc,\n    thread,\n};\n\nuse parking_lot::Mutex;\nuse ringbuf::HeapRb;\nuse songbir"
  },
  {
    "path": "src/dickcord/bot.rs",
    "chars": 10529,
    "preview": "use super::TargetUser;\nuse crate::{audio::AudioStream, state::Config};\nuse crossbeam::channel::{unbounded, Receiver, Sen"
  },
  {
    "path": "src/dickcord/mod.rs",
    "chars": 81,
    "preview": "mod bot;\nmod system;\n\npub use bot::*;\npub use system::*;\n\ntype TargetUser = u64;\n"
  },
  {
    "path": "src/dickcord/system.rs",
    "chars": 7046,
    "preview": "use crate::{\n    app::AppEvent,\n    audio::{AudioStream, Source},\n    state::{Config, ReadOnlyConfig},\n};\n\nuse super::{B"
  },
  {
    "path": "src/interface/components/mod.rs",
    "chars": 39,
    "preview": "mod text_field;\npub use text_field::*;\n"
  },
  {
    "path": "src/interface/components/text_field.rs",
    "chars": 1648,
    "preview": "use crossterm::event::Event;\nuse tui::{\n    buffer::Buffer,\n    layout::{Constraint, Direction, Layout, Rect},\n    style"
  },
  {
    "path": "src/interface/dashboard/discord_module.rs",
    "chars": 2806,
    "preview": "use tui::{\n    buffer::Buffer,\n    layout::{Constraint, Direction, Layout, Rect},\n    style::{Color, Style},\n    widgets"
  },
  {
    "path": "src/interface/dashboard/meter.rs",
    "chars": 2493,
    "preview": "use tui::{\n    layout::{Constraint, Direction, Layout, Rect},\n    style::{Color, Style},\n};\n\nuse crate::{app::AppContext"
  },
  {
    "path": "src/interface/dashboard/mod.rs",
    "chars": 5890,
    "preview": "use crossterm::event::{Event, KeyCode};\nuse enum_iterator::{next_cycle, Sequence};\nuse tui::{\n    buffer::Buffer,\n    la"
  },
  {
    "path": "src/interface/dashboard/settings_module.rs",
    "chars": 5317,
    "preview": "use crossterm::event::{Event, KeyCode};\nuse tui::{\n    buffer::Buffer,\n    layout::{Constraint, Direction, Layout, Rect}"
  },
  {
    "path": "src/interface/dashboard/source_selector.rs",
    "chars": 4966,
    "preview": "use crossterm::event::{Event, KeyCode};\nuse parking_lot::Mutex;\nuse tui::{\n    buffer::Buffer,\n    layout::Rect,\n    sty"
  },
  {
    "path": "src/interface/dashboard/version.rs",
    "chars": 968,
    "preview": "use tui::{\n    buffer::Buffer,\n    layout::{Alignment, Rect},\n    style::{Color, Style},\n    widgets::{Paragraph, Widget"
  },
  {
    "path": "src/interface/mod.rs",
    "chars": 3676,
    "preview": "use std::{\n    io, thread,\n    time::{Duration, Instant},\n};\n\nmod components;\npub use components::*;\n\nmod view;\npub use "
  },
  {
    "path": "src/interface/setup/form.rs",
    "chars": 2236,
    "preview": "use crossterm::event::{Event, KeyCode};\nuse enum_iterator::{next_cycle, Sequence};\nuse tui::{\n    buffer::Buffer,\n    la"
  },
  {
    "path": "src/interface/setup/mod.rs",
    "chars": 5711,
    "preview": "use crossterm::event::{Event, KeyCode};\nuse form::{Form, SelectedField};\nuse tui::{\n    buffer::Buffer,\n    layout::{Con"
  },
  {
    "path": "src/interface/splash.rs",
    "chars": 329,
    "preview": "use tui::{\n    layout::Alignment,\n    widgets::{Paragraph, Widget},\n};\n\nuse super::{View, LOGO};\npub struct Splash;\n\nimp"
  },
  {
    "path": "src/interface/view.rs",
    "chars": 845,
    "preview": "use crossterm::event::Event;\nuse tui::{buffer::Buffer, layout::Rect, widgets::Widget};\n\npub trait View {\n    fn handle_e"
  },
  {
    "path": "src/main.rs",
    "chars": 369,
    "preview": "use app::App;\n\nmod app;\nmod audio;\nmod dickcord;\nmod interface;\nmod state;\n\nfn main() {\n    let app = App::new();\n\n    m"
  },
  {
    "path": "src/state.rs",
    "chars": 1859,
    "preview": "use serde::{Deserialize, Serialize};\nuse std::env;\nuse std::io::Write;\nuse std::{fs::File, io::Read};\n\n#[derive(Debug, D"
  }
]

About this extraction

This page contains the full source code of the Enitoni/pulseshitter GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 28 files (119.1 KB), approximately 27.7k tokens, and a symbol index with 285 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!