├── .envrc ├── .gitignore ├── .github ├── FUNDING.yml └── workflows │ ├── ci.yaml │ └── release.yaml ├── Cross.toml ├── bluetui.desktop ├── src ├── ui.rs ├── lib.rs ├── spinner.rs ├── cli.rs ├── rfkill.rs ├── string_ref.rs ├── favorite.rs ├── tui.rs ├── requests.rs ├── requests │ ├── display_pin_code.rs │ ├── display_passkey.rs │ ├── confirmation.rs │ ├── enter_pin_code.rs │ └── enter_passkey.rs ├── notification.rs ├── event.rs ├── main.rs ├── agent.rs ├── config.rs ├── bluetooth.rs ├── help.rs ├── app.rs └── handler.rs ├── .pre-commit-config.yaml ├── package.nix ├── Cargo.toml ├── flake.nix ├── Release.md ├── assets └── bluetui-logo-anim.svg ├── flake.lock ├── Readme.md └── LICENSE /.envrc: -------------------------------------------------------------------------------- 1 | use flake 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | .direnv/ 3 | result 4 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: pythops 4 | -------------------------------------------------------------------------------- /Cross.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | pre-build = [ 3 | "dpkg --add-architecture $CROSS_DEB_ARCH", 4 | "apt update && apt install -y libdbus-1-dev:$CROSS_DEB_ARCH pkg-config:$CROSS_DEB_ARCH ", 5 | ] 6 | -------------------------------------------------------------------------------- /bluetui.desktop: -------------------------------------------------------------------------------- 1 | [Desktop Entry] 2 | Name=Bluetui 3 | GenericName=Bluetooth Manager 4 | Comment=Manage bluethooth devices 5 | Exec=bluetui 6 | Terminal=true 7 | Type=Application 8 | Keywords=bluetooth 9 | Categories=Utility;Settings;ConsoleOnly 10 | StartupNotify=false 11 | -------------------------------------------------------------------------------- /src/ui.rs: -------------------------------------------------------------------------------- 1 | use ratatui::Frame; 2 | 3 | use crate::app::App; 4 | 5 | pub fn render(app: &mut App, frame: &mut Frame) { 6 | app.render(frame); 7 | 8 | for (index, notification) in app.notifications.iter().enumerate() { 9 | notification.render(index, frame, app.area(frame)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod agent; 2 | pub mod app; 3 | pub mod bluetooth; 4 | pub mod cli; 5 | pub mod config; 6 | pub mod event; 7 | pub mod favorite; 8 | pub mod handler; 9 | mod help; 10 | pub mod notification; 11 | pub mod requests; 12 | pub mod rfkill; 13 | pub mod spinner; 14 | pub mod string_ref; 15 | pub mod tui; 16 | pub mod ui; 17 | -------------------------------------------------------------------------------- /src/spinner.rs: -------------------------------------------------------------------------------- 1 | static SPINNER_CHARS: &[char] = &['⦾', '⦿']; 2 | 3 | #[derive(Default, Clone, Copy, Debug)] 4 | pub struct Spinner { 5 | pub active: bool, 6 | pub index: usize, 7 | } 8 | 9 | impl Spinner { 10 | pub fn draw(&self) -> char { 11 | SPINNER_CHARS[self.index] 12 | } 13 | 14 | pub fn update(&mut self) { 15 | self.index += 1; 16 | self.index %= SPINNER_CHARS.len(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | fail_fast: true 3 | repos: 4 | - repo: local 5 | hooks: 6 | - id: cargo-fmt 7 | name: cargo fmt 8 | entry: cargo fmt --all -- 9 | language: system 10 | types: [rust] 11 | - id: clippy 12 | name: clippy 13 | entry: | 14 | cargo clippy --workspace --all-targets --all-features -- -D warnings 15 | language: system 16 | pass_filenames: false 17 | -------------------------------------------------------------------------------- /src/cli.rs: -------------------------------------------------------------------------------- 1 | use std::path::PathBuf; 2 | 3 | use clap::{Command, arg, crate_description, crate_name, crate_version, value_parser}; 4 | 5 | pub fn cli() -> Command { 6 | Command::new(crate_name!()) 7 | .about(crate_description!()) 8 | .version(crate_version!()) 9 | .arg( 10 | arg!(--config ) 11 | .short('c') 12 | .id("config") 13 | .required(false) 14 | .help("Config file path") 15 | .value_parser(value_parser!(PathBuf)), 16 | ) 17 | } 18 | -------------------------------------------------------------------------------- /package.nix: -------------------------------------------------------------------------------- 1 | { 2 | lib, 3 | rustPlatform, 4 | dbus, 5 | pkg-config, 6 | }: 7 | let 8 | cargo = lib.importTOML ./Cargo.toml; 9 | in 10 | rustPlatform.buildRustPackage { 11 | pname = cargo.package.name; 12 | version = cargo.package.version; 13 | src = ./.; 14 | cargoLock.lockFile = ./Cargo.lock; 15 | 16 | buildInputs = [dbus]; 17 | nativeBuildInputs = [pkg-config]; 18 | 19 | meta = { 20 | description = cargo.package.description; 21 | homepage = cargo.package.homepage; 22 | license = lib.licenses.gpl3Only; 23 | maintainers = with lib.maintainers; [samuel-martineau]; 24 | }; 25 | } 26 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | name: CI 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - "*" 8 | jobs: 9 | test: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: dtolnay/rust-toolchain@stable 14 | with: 15 | toolchain: stable 16 | components: clippy rustfmt 17 | 18 | - name: Setup the build env 19 | run: | 20 | sudo apt update 21 | sudo apt install -y libdbus-1-dev pkg-config 22 | 23 | - name: Linting 24 | run: | 25 | cargo clippy --workspace --all-features -- -D warnings 26 | cargo fmt --all -- --check 27 | 28 | - name: Debug builds 29 | run: cargo build 30 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bluetui" 3 | version = "0.8.0" 4 | authors = ["Badr Badri "] 5 | license = "GPL-3.0" 6 | edition = "2024" 7 | description = "TUI for managing bluetooth on Linux" 8 | readme = "Readme.md" 9 | homepage = "https://github.com/pythops/bluetui" 10 | repository = "https://github.com/pythops/bluetui" 11 | 12 | [dependencies] 13 | async-channel = "2" 14 | bluer = { version = "0.17", features = ["full"] } 15 | crossterm = { version = "0.29", default-features = false, features = [ 16 | "event-stream", 17 | ] } 18 | futures = "0.3" 19 | ratatui = "0.29" 20 | tokio = { version = "1", features = ["full"] } 21 | dirs = "6" 22 | toml = "0.9" 23 | serde = { version = "1", features = ["derive"] } 24 | clap = { version = "4", features = ["derive", "cargo"] } 25 | tui-input = "0.12" 26 | anyhow = "1" 27 | 28 | [profile.release] 29 | strip = true 30 | codegen-units = 1 31 | lto = "fat" 32 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | inputs = { 3 | nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; 4 | flake-utils.url = "github:numtide/flake-utils"; 5 | rust-overlay = { 6 | url = "github:oxalica/rust-overlay"; 7 | inputs.nixpkgs.follows = "nixpkgs"; 8 | }; 9 | }; 10 | 11 | outputs = { 12 | self, 13 | nixpkgs, 14 | flake-utils, 15 | rust-overlay, 16 | ... 17 | }: 18 | flake-utils.lib.eachDefaultSystem ( 19 | system: let 20 | overlays = [(import rust-overlay)]; 21 | pkgs = import nixpkgs {inherit system overlays;}; 22 | bluetui = pkgs.callPackage ./package.nix {}; 23 | in { 24 | devShells.default = pkgs.mkShell { 25 | buildInputs = with pkgs; [ 26 | dbus 27 | pkg-config 28 | rust-bin.stable.latest.default 29 | self.packages.${system}.default 30 | ]; 31 | }; 32 | packages = { 33 | default = bluetui; 34 | inherit bluetui; 35 | }; 36 | legacyPackages = pkgs.extend(final: prev: { 37 | bluetui = final.callPackage ./package.nix {}; 38 | }); 39 | } 40 | ); 41 | } 42 | -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Release 3 | on: 4 | push: 5 | tags: 6 | - "v*" 7 | jobs: 8 | build: 9 | permissions: 10 | contents: write 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: cargo-bins/cargo-binstall@main 15 | - uses: dtolnay/rust-toolchain@stable 16 | with: 17 | toolchain: stable 18 | 19 | - name: Setup the build env 20 | run: | 21 | sudo apt-get update && \ 22 | sudo apt-get install -y \ 23 | podman \ 24 | qemu-user-static\ 25 | pkg-config \ 26 | libdbus-1-dev && \ 27 | cargo binstall --no-confirm cross 28 | 29 | - name: Build for x86_64 linux gnu 30 | run: | 31 | cargo build --release 32 | cp target/release/bluetui bluetui-x86_64-linux-gnu 33 | 34 | - name: Build for aarch64 linux gnu 35 | run: | 36 | CROSS_CONTAINER_ENGINE=podman cross build --target aarch64-unknown-linux-gnu --release 37 | cp target/aarch64-unknown-linux-gnu/release/bluetui bluetui-aarch64-linux-gnu 38 | 39 | - name: Release 40 | uses: softprops/action-gh-release@v1 41 | with: 42 | body: | 43 | [Release.md](${{ github.server_url }}/${{ github.repository }}/blob/master/Release.md) 44 | files: "bluetui*" 45 | env: 46 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 47 | -------------------------------------------------------------------------------- /src/rfkill.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | 3 | use crate::app::AppResult; 4 | 5 | pub fn check() -> AppResult<()> { 6 | if let Ok(entries) = fs::read_dir("/sys/class/rfkill/") { 7 | for entry in entries { 8 | let entry = entry?; 9 | let entry_path = entry.path(); 10 | 11 | if let Some(_file_name) = entry_path.file_name() { 12 | let name = fs::read_to_string(entry_path.join("type"))?; 13 | 14 | if name.trim() == "bluetooth" { 15 | let state_path = entry_path.join("state"); 16 | let state = fs::read_to_string(state_path)?.trim().parse::()?; 17 | 18 | // https://www.kernel.org/doc/Documentation/ABI/stable/sysfs-class-rfkill 19 | match state { 20 | 0 => { 21 | eprintln!( 22 | r#" 23 | The bluetooth device is soft blocked 24 | Run the following command to unblock it 25 | $ sudo rfkill unblock bluetooth 26 | "# 27 | ); 28 | std::process::exit(1); 29 | } 30 | 2 => { 31 | eprintln!("The bluetooth device is hard blocked"); 32 | std::process::exit(1); 33 | } 34 | _ => {} 35 | } 36 | break; 37 | } 38 | } 39 | } 40 | } 41 | Ok(()) 42 | } 43 | -------------------------------------------------------------------------------- /src/string_ref.rs: -------------------------------------------------------------------------------- 1 | #[derive(Clone)] 2 | pub enum StringRef { 3 | Owned(String), 4 | Static(&'static str), 5 | } 6 | 7 | impl StringRef { 8 | pub fn as_str(&self) -> &str { 9 | match self { 10 | StringRef::Owned(s) => s.as_str(), 11 | StringRef::Static(s) => s, 12 | } 13 | } 14 | } 15 | 16 | impl From for StringRef { 17 | fn from(s: String) -> Self { 18 | StringRef::Owned(s) 19 | } 20 | } 21 | 22 | impl From<&'static str> for StringRef { 23 | fn from(s: &'static str) -> Self { 24 | StringRef::Static(s) 25 | } 26 | } 27 | 28 | impl From for StringRef { 29 | fn from(err: bluer::Error) -> Self { 30 | StringRef::Owned(err.to_string()) 31 | } 32 | } 33 | 34 | impl From for StringRef { 35 | fn from(err: anyhow::Error) -> Self { 36 | StringRef::Owned(err.to_string()) 37 | } 38 | } 39 | 40 | impl AsRef for StringRef { 41 | fn as_ref(&self) -> &str { 42 | self.as_str() 43 | } 44 | } 45 | 46 | impl std::fmt::Display for StringRef { 47 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 48 | write!(f, "{}", self.as_str()) 49 | } 50 | } 51 | 52 | impl std::fmt::Debug for StringRef { 53 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 54 | match self { 55 | StringRef::Owned(s) => write!(f, "StringRef::Owned({:?})", s), 56 | StringRef::Static(s) => write!(f, "StringRef::Static({:?})", s), 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/favorite.rs: -------------------------------------------------------------------------------- 1 | use crate::app::AppResult; 2 | use anyhow::Context; 3 | use bluer::Address; 4 | use clap::crate_name; 5 | use std::str::FromStr; 6 | use tokio::io::{AsyncBufReadExt, BufReader}; 7 | 8 | pub async fn read_favorite_devices_from_disk() -> AppResult> { 9 | let data_dir = dirs::data_dir() 10 | .context("unable to find data_dir")? 11 | .join(crate_name!()); 12 | 13 | let file = tokio::fs::File::open(data_dir.join("favorites.txt")) 14 | .await 15 | .context("unable to open favorites file")?; 16 | 17 | let mut lines = BufReader::new(file).lines(); 18 | 19 | let mut favorite_devices = Vec::new(); 20 | 21 | while let Some(line) = lines.next_line().await? { 22 | if let Ok(addr) = Address::from_str(&line) { 23 | favorite_devices.push(addr); 24 | } 25 | } 26 | 27 | Ok(favorite_devices) 28 | } 29 | 30 | pub fn save_favorite_devices_to_disk(favorite_devices: &[Address]) -> AppResult<()> { 31 | let data_dir = dirs::data_dir() 32 | .context("unable to find data_dir")? 33 | .join(crate_name!()); 34 | 35 | let file_path = data_dir.join("favorites.txt"); 36 | 37 | let contents = favorite_devices 38 | .iter() 39 | .map(Address::to_string) 40 | .collect::>() 41 | .join("\n"); 42 | 43 | if !data_dir.exists() { 44 | std::fs::create_dir_all(data_dir) 45 | .context("unable to create parent dir(s) to favorites file")?; 46 | } 47 | 48 | std::fs::write(file_path, contents).context("error writing favorites file")?; 49 | 50 | Ok(()) 51 | } 52 | -------------------------------------------------------------------------------- /src/tui.rs: -------------------------------------------------------------------------------- 1 | use crate::app::{App, AppResult}; 2 | use crate::event::EventHandler; 3 | use crate::ui; 4 | use crossterm::event::{DisableMouseCapture, EnableMouseCapture}; 5 | use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen}; 6 | use ratatui::Terminal; 7 | use ratatui::backend::Backend; 8 | use std::io; 9 | use std::panic; 10 | 11 | #[derive(Debug)] 12 | pub struct Tui { 13 | terminal: Terminal, 14 | pub events: EventHandler, 15 | } 16 | 17 | impl Tui { 18 | pub fn new(terminal: Terminal, events: EventHandler) -> Self { 19 | Self { terminal, events } 20 | } 21 | 22 | pub fn init(&mut self) -> AppResult<()> { 23 | terminal::enable_raw_mode()?; 24 | crossterm::execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture)?; 25 | 26 | let panic_hook = panic::take_hook(); 27 | panic::set_hook(Box::new(move |panic| { 28 | Self::reset().expect("failed to reset the terminal"); 29 | panic_hook(panic); 30 | })); 31 | 32 | self.terminal.hide_cursor()?; 33 | self.terminal.clear()?; 34 | Ok(()) 35 | } 36 | 37 | pub fn draw(&mut self, app: &mut App) -> AppResult<()> { 38 | self.terminal.draw(|frame| ui::render(app, frame))?; 39 | Ok(()) 40 | } 41 | 42 | fn reset() -> AppResult<()> { 43 | terminal::disable_raw_mode()?; 44 | crossterm::execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture)?; 45 | Ok(()) 46 | } 47 | 48 | pub fn exit(&mut self) -> AppResult<()> { 49 | Self::reset()?; 50 | self.terminal.show_cursor()?; 51 | Ok(()) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Release.md: -------------------------------------------------------------------------------- 1 | ## v0.8.0 - 2025-11-13 2 | 3 | - Implement the rest of the auth methods 4 | - Add default icon to the devices that do not have one 5 | - Layout adjustements 6 | - Connect and trust automatically the new pair devices 7 | 8 | ## v0.7.2 - 2025-11-03 9 | 10 | - Align icons 11 | - Ability to customize the layout 12 | - Ability to set the width for the window 13 | 14 | ## v0.7.1 - 2025-10-22 15 | 16 | - Make helper banner responsive 17 | - Fix display issue on light theme terminal 18 | - Update the layout to center the content 19 | 20 | ## v0.7 - 2025-10-21 21 | 22 | - Use help banner instead of the popup 23 | - Fix crash when rfkill dir is not present 24 | - Add h/l nav controls 25 | - Add BackTab key handler 26 | 27 | ## v0.6 - 2024-12-21 28 | 29 | ### Updated 30 | 31 | - The layout has been reorgonized to show paired devices section on the top 32 | 33 | ### Fix 34 | 35 | - fg color is fixed for light mode 36 | 37 | ## v0.5.1 - 29/07/2024 38 | 39 | ### Added 40 | 41 | - Detect when the device is soft/hard blocked 42 | - Add `q` to quit 43 | 44 | ## v0.5 - 11/07/2024 45 | 46 | ### Added 47 | 48 | - Rename paired devices 49 | - Support light background 50 | 51 | ## v0.4 - 15/03/2024 52 | 53 | ### Added 54 | 55 | - Add scrollbars by [@orhun](https://github.com/orhun/) 56 | - Custom keybindings 57 | 58 | ## v0.3 - 06/03/2024 59 | 60 | ### Added 61 | 62 | - Show battery percentage 63 | - Colorful layout 64 | 65 | ### Updated 66 | 67 | - Update the main layout 68 | 69 | ## v0.2 - 25/02/2024 70 | 71 | ### Added 72 | 73 | - Handle pairing confirmation request 74 | 75 | ### Updated 76 | 77 | - notification layout 78 | - notification ttl is set to 1 second 79 | 80 | ## v0.1 - 22/02/2024 81 | 82 | First release 🎉 83 | -------------------------------------------------------------------------------- /assets/bluetui-logo-anim.svg: -------------------------------------------------------------------------------- 1 | 2 | 7 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/requests.rs: -------------------------------------------------------------------------------- 1 | use std::{borrow::Cow, fmt::Write}; 2 | 3 | use crate::requests::{ 4 | confirmation::Confirmation, display_passkey::DisplayPasskey, display_pin_code::DisplayPinCode, 5 | enter_passkey::EnterPasskey, enter_pin_code::EnterPinCode, 6 | }; 7 | 8 | pub mod confirmation; 9 | pub mod display_passkey; 10 | pub mod display_pin_code; 11 | pub mod enter_passkey; 12 | pub mod enter_pin_code; 13 | 14 | #[derive(Debug, Default)] 15 | pub struct Requests { 16 | pub confirmation: Option, 17 | pub enter_pin_code: Option, 18 | pub enter_passkey: Option, 19 | pub display_pin_code: Option, 20 | pub display_passkey: Option, 21 | } 22 | 23 | impl Requests { 24 | pub fn init_confirmation(&mut self, req: Confirmation) { 25 | self.confirmation = Some(req); 26 | } 27 | pub fn init_enter_pin_code(&mut self, req: EnterPinCode) { 28 | self.enter_pin_code = Some(req); 29 | } 30 | pub fn init_enter_passkey(&mut self, req: EnterPasskey) { 31 | self.enter_passkey = Some(req); 32 | } 33 | pub fn init_display_pin_code(&mut self, req: DisplayPinCode) { 34 | self.display_pin_code = Some(req); 35 | } 36 | pub fn init_display_passkey(&mut self, req: DisplayPasskey) { 37 | self.display_passkey = Some(req); 38 | } 39 | } 40 | 41 | fn pad_str<'a>(input: &'a str, length: usize) -> Cow<'a, str> { 42 | let current_length = input.chars().count(); 43 | if current_length >= length { 44 | Cow::Borrowed(input) 45 | } else { 46 | let mut s = String::with_capacity(length); 47 | write!(&mut s, "{: String { 53 | let current_length = input.chars().count(); 54 | if current_length >= length { 55 | input 56 | } else { 57 | let mut s = String::with_capacity(length); 58 | write!(&mut s, "{: Self { 22 | Self { 23 | adapter, 24 | device, 25 | pin_code, 26 | } 27 | } 28 | 29 | pub async fn submit(&mut self, agent: &AuthAgent) -> AppResult<()> { 30 | agent.tx_display_pin_code.send(()).await?; 31 | agent 32 | .event_sender 33 | .send(crate::event::Event::DisplayPinCodeSeen)?; 34 | Ok(()) 35 | } 36 | 37 | pub fn render(&self, frame: &mut Frame, area: Rect) { 38 | let block = Layout::default() 39 | .direction(Direction::Vertical) 40 | .constraints([ 41 | Constraint::Fill(1), 42 | Constraint::Length(10), 43 | Constraint::Fill(1), 44 | ]) 45 | .margin(2) 46 | .split(area)[1]; 47 | 48 | let block = Layout::default() 49 | .direction(Direction::Horizontal) 50 | .constraints([ 51 | Constraint::Fill(1), 52 | Constraint::Max(60), 53 | Constraint::Fill(1), 54 | ]) 55 | .margin(1) 56 | .split(block)[1]; 57 | 58 | let message = vec![ 59 | Line::from(format!("Pin Code for the device {} ", self.device)).centered(), 60 | Line::from(""), 61 | Line::from(self.pin_code.clone()) 62 | .centered() 63 | .bold() 64 | .bg(Color::DarkGray), 65 | ]; 66 | 67 | let message = Paragraph::new(message).centered(); 68 | 69 | frame.render_widget(Clear, block); 70 | 71 | frame.render_widget( 72 | Block::new() 73 | .borders(Borders::ALL) 74 | .border_type(BorderType::Thick) 75 | .border_style(Style::default().fg(Color::Green)), 76 | block, 77 | ); 78 | frame.render_widget( 79 | message, 80 | block.inner(Margin { 81 | horizontal: 0, 82 | vertical: 2, 83 | }), 84 | ); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/requests/display_passkey.rs: -------------------------------------------------------------------------------- 1 | use ratatui::{ 2 | Frame, 3 | layout::{Constraint, Direction, Layout, Margin, Rect}, 4 | style::{Color, Style, Stylize}, 5 | text::{Line, Span}, 6 | widgets::{Block, BorderType, Borders, Clear, Paragraph}, 7 | }; 8 | 9 | use bluer::Address; 10 | 11 | use crate::{agent::AuthAgent, app::AppResult}; 12 | 13 | #[derive(Debug, Clone)] 14 | pub struct DisplayPasskey { 15 | pub adapter: String, 16 | pub device: Address, 17 | pub passkey: u32, 18 | pub entered: u16, 19 | } 20 | 21 | impl DisplayPasskey { 22 | pub fn new(adapter: String, device: Address, passkey: u32, entered: u16) -> Self { 23 | Self { 24 | adapter, 25 | device, 26 | passkey, 27 | entered, 28 | } 29 | } 30 | 31 | pub async fn cancel(&mut self, agent: &AuthAgent) -> AppResult<()> { 32 | agent.tx_cancel.send(()).await?; 33 | agent 34 | .event_sender 35 | .send(crate::event::Event::DisplayPasskeyCanceled)?; 36 | Ok(()) 37 | } 38 | 39 | pub fn render(&self, frame: &mut Frame, area: Rect) { 40 | let block = Layout::default() 41 | .direction(Direction::Vertical) 42 | .constraints([ 43 | Constraint::Fill(1), 44 | Constraint::Length(12), 45 | Constraint::Fill(1), 46 | ]) 47 | .margin(2) 48 | .split(area)[1]; 49 | 50 | let block = Layout::default() 51 | .direction(Direction::Horizontal) 52 | .constraints([ 53 | Constraint::Fill(1), 54 | Constraint::Max(70), 55 | Constraint::Fill(1), 56 | ]) 57 | .margin(1) 58 | .split(block)[1]; 59 | 60 | let message = vec![ 61 | Line::from(format!("Authentication for the device {}", self.device)).centered(), 62 | Line::from(""), 63 | Line::from(vec![Span::from( 64 | "Enter the following passkey on the remote device", 65 | )]) 66 | .centered(), 67 | Line::from(""), 68 | Line::from(self.passkey.to_string()) 69 | .bold() 70 | .bg(Color::DarkGray), 71 | ]; 72 | 73 | let message = Paragraph::new(message).centered(); 74 | 75 | frame.render_widget(Clear, block); 76 | 77 | frame.render_widget( 78 | Block::new() 79 | .borders(Borders::ALL) 80 | .border_type(BorderType::Thick) 81 | .border_style(Style::default().fg(Color::Green)), 82 | block, 83 | ); 84 | frame.render_widget( 85 | message, 86 | block.inner(Margin { 87 | horizontal: 0, 88 | vertical: 2, 89 | }), 90 | ); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/notification.rs: -------------------------------------------------------------------------------- 1 | use ratatui::{ 2 | Frame, 3 | layout::{Alignment, Constraint, Direction, Layout, Rect}, 4 | style::{Color, Modifier, Style}, 5 | text::{Line, Text}, 6 | widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, 7 | }; 8 | use tokio::sync::mpsc::UnboundedSender; 9 | 10 | use crate::{app::AppResult, event::Event, string_ref::StringRef}; 11 | 12 | #[derive(Debug, Clone)] 13 | pub struct Notification { 14 | pub message: StringRef, 15 | pub level: NotificationLevel, 16 | pub ttl: u16, 17 | } 18 | 19 | #[derive(Debug, Clone)] 20 | pub enum NotificationLevel { 21 | Error, 22 | Warning, 23 | Info, 24 | } 25 | 26 | impl Notification { 27 | pub fn render(&self, index: usize, frame: &mut Frame, area: Rect) { 28 | let (color, title) = match self.level { 29 | NotificationLevel::Info => (Color::Green, "Info"), 30 | NotificationLevel::Warning => (Color::Yellow, "Warning"), 31 | NotificationLevel::Error => (Color::Red, "Error"), 32 | }; 33 | 34 | let mut text = Text::from(vec![ 35 | Line::from(title).style(Style::new().fg(color).add_modifier(Modifier::BOLD)), 36 | ]); 37 | 38 | text.extend(Text::from(self.message.as_str())); 39 | 40 | let notification_height = text.height() as u16 + 2; 41 | let notification_width = text.width() as u16 + 4; 42 | 43 | let block = Paragraph::new(text) 44 | .alignment(Alignment::Center) 45 | .wrap(Wrap { trim: false }) 46 | .block( 47 | Block::default() 48 | .borders(Borders::ALL) 49 | .style(Style::default()) 50 | .border_type(BorderType::Thick) 51 | .border_style(Style::default().fg(color)), 52 | ); 53 | 54 | let area = notification_rect(index as u16, notification_height, notification_width, area); 55 | 56 | frame.render_widget(Clear, area); 57 | frame.render_widget(block, area); 58 | } 59 | pub fn send( 60 | message: StringRef, 61 | level: NotificationLevel, 62 | sender: UnboundedSender, 63 | ) -> AppResult<()> { 64 | let notif = Notification { 65 | message, 66 | level, 67 | ttl: 2, 68 | }; 69 | 70 | sender.send(Event::Notification(notif))?; 71 | 72 | Ok(()) 73 | } 74 | } 75 | 76 | pub fn notification_rect(offset: u16, height: u16, width: u16, r: Rect) -> Rect { 77 | let popup_layout = Layout::default() 78 | .direction(Direction::Vertical) 79 | .constraints( 80 | [ 81 | Constraint::Length(height * offset), 82 | Constraint::Length(height), 83 | Constraint::Min(1), 84 | ] 85 | .as_ref(), 86 | ) 87 | .split(r); 88 | 89 | Layout::default() 90 | .direction(Direction::Horizontal) 91 | .constraints( 92 | [ 93 | Constraint::Min(1), 94 | Constraint::Length(width), 95 | Constraint::Length(2), 96 | ] 97 | .as_ref(), 98 | ) 99 | .split(popup_layout[1])[1] 100 | } 101 | -------------------------------------------------------------------------------- /src/event.rs: -------------------------------------------------------------------------------- 1 | use anyhow::anyhow; 2 | use bluer::Address; 3 | use std::time::Duration; 4 | 5 | use crossterm::event::{Event as CrosstermEvent, KeyEvent, MouseEvent}; 6 | use futures::{FutureExt, StreamExt}; 7 | use tokio::sync::mpsc; 8 | 9 | use crate::{ 10 | app::AppResult, 11 | notification::Notification, 12 | requests::{ 13 | confirmation::Confirmation, display_passkey::DisplayPasskey, 14 | display_pin_code::DisplayPinCode, enter_passkey::EnterPasskey, 15 | enter_pin_code::EnterPinCode, 16 | }, 17 | }; 18 | 19 | #[derive(Clone, Debug)] 20 | pub enum Event { 21 | Tick, 22 | Key(KeyEvent), 23 | Mouse(MouseEvent), 24 | Resize(u16, u16), 25 | Notification(Notification), 26 | NewPairedDevice(Address), 27 | ToggleFavorite(Address), 28 | FailedPairing(Address), 29 | RequestConfirmation(Confirmation), 30 | ConfirmationSubmitted, 31 | RequestEnterPinCode(EnterPinCode), 32 | PinCodeSumitted, 33 | RequestEnterPasskey(EnterPasskey), 34 | RequestDisplayPinCode(DisplayPinCode), 35 | DisplayPinCodeSeen, 36 | PasskeySumitted, 37 | RequestDisplayPasskey(DisplayPasskey), 38 | DisplayPasskeyCanceled, 39 | } 40 | 41 | #[allow(dead_code)] 42 | #[derive(Debug)] 43 | pub struct EventHandler { 44 | pub sender: mpsc::UnboundedSender, 45 | pub receiver: mpsc::UnboundedReceiver, 46 | handler: tokio::task::JoinHandle<()>, 47 | } 48 | 49 | impl EventHandler { 50 | pub fn new(tick_rate: u64) -> Self { 51 | let tick_rate = Duration::from_millis(tick_rate); 52 | let (sender, receiver) = mpsc::unbounded_channel(); 53 | let _sender = sender.clone(); 54 | let handler = tokio::spawn(async move { 55 | let mut reader = crossterm::event::EventStream::new(); 56 | let mut tick = tokio::time::interval(tick_rate); 57 | loop { 58 | let tick_delay = tick.tick(); 59 | let crossterm_event = reader.next().fuse(); 60 | tokio::select! { 61 | _ = tick_delay => { 62 | _sender.send(Event::Tick).unwrap(); 63 | } 64 | Some(Ok(evt)) = crossterm_event => { 65 | match evt { 66 | CrosstermEvent::Key(key) => { 67 | if key.kind == crossterm::event::KeyEventKind::Press { 68 | _sender.send(Event::Key(key)).unwrap(); 69 | } 70 | }, 71 | CrosstermEvent::Mouse(mouse) => { 72 | _sender.send(Event::Mouse(mouse)).unwrap(); 73 | }, 74 | CrosstermEvent::Resize(x, y) => { 75 | _sender.send(Event::Resize(x, y)).unwrap(); 76 | }, 77 | CrosstermEvent::FocusLost => { 78 | }, 79 | CrosstermEvent::FocusGained => { 80 | }, 81 | CrosstermEvent::Paste(_) => { 82 | }, 83 | } 84 | } 85 | }; 86 | } 87 | }); 88 | Self { 89 | sender, 90 | receiver, 91 | handler, 92 | } 93 | } 94 | 95 | pub async fn next(&mut self) -> AppResult { 96 | self.receiver 97 | .recv() 98 | .await 99 | .ok_or(anyhow!("This is an IO error")) 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

TUI for managing bluetooth on Linux

4 | 5 |
6 | 7 | ## 💡 Prerequisites 8 | 9 | A Linux based OS with [bluez](https://www.bluez.org/) installed. 10 | 11 | > [!NOTE] 12 | > You might need to install [nerdfonts](https://www.nerdfonts.com/) for the icons to be displayed correctly. 13 | 14 | ## 🚀 Installation 15 | 16 | ### 📥 Binary release 17 | 18 | You can download the pre-built binaries from the release page [release page](https://github.com/pythops/bluetui/releases) 19 | 20 | ### 📦 crates.io 21 | 22 | You can install `bluetui` from [crates.io](https://crates.io/crates/bluetui) 23 | 24 | ```shell 25 | cargo install bluetui 26 | ``` 27 | 28 | ### 🐧 Arch Linux 29 | 30 | You can install `bluetui` from the [extra repository](https://archlinux.org/packages/extra/x86_64/bluetui/): 31 | 32 | ```shell 33 | pacman -S bluetui 34 | ``` 35 | 36 | ### 🐧 Gentoo 37 | 38 | You can install `bluetui` from the [lamdness Gentoo Overlay](https://gpo.zugaina.org/net-wireless/bluetui): 39 | 40 | ```sh 41 | sudo eselect repository enable lamdness 42 | sudo emaint -r lamdness sync 43 | sudo emerge -av net-wireless/bluetui 44 | ``` 45 | 46 | ### 🧰 X-CMD 47 | 48 | If you are a user of [x-cmd](https://x-cmd.com), you can run: 49 | 50 | ```shell 51 | x install bluetui 52 | ``` 53 | 54 | ### ⚒️ Build from source 55 | 56 | Run the following command: 57 | 58 | ```shell 59 | git clone https://github.com/pythops/bluetui 60 | cd bluetui 61 | cargo build --release 62 | ``` 63 | 64 | This will produce an executable file at `target/release/bluetui` that you can copy to a directory in your `$PATH`. 65 | 66 | ## 🪄 Usage 67 | 68 | ### Global 69 | 70 | `Tab` or `l`: Scroll down between different sections. 71 | 72 | `shift+Tab` or `h`: Scroll up between different sections. 73 | 74 | `j` or `Down` : Scroll down. 75 | 76 | `k` or `Up`: Scroll up. 77 | 78 | `s`: Start/Stop scanning. 79 | 80 | `ctrl+c` or `q`: Quit the app. (Note: `` can also quit if `esc_quit = true` is set in config) 81 | 82 | ### Adapters 83 | 84 | `p`: Enable/Disable the pairing. 85 | 86 | `o`: Power on/off the adapter. 87 | 88 | `d`: Enable/Disable the discovery. 89 | 90 | ### Paired devices 91 | 92 | `u`: Unpair the device. 93 | 94 | `Space or Enter`: Connect/Disconnect the device. 95 | 96 | `t`: Trust/Untrust the device. 97 | 98 | `f`: Favorite/Unfavorite the device. 99 | 100 | `e`: Rename the device. 101 | 102 | ### New devices 103 | 104 | `Space or Enter`: Pair the device. 105 | 106 | ## Config 107 | 108 | Keybindings can be customized in the default config file location `$HOME/.config/bluetui/config.toml` or from a custom path with `-c` 109 | 110 | ```toml 111 | # Possible values: "Legacy", "Start", "End", "Center", "SpaceAround", "SpaceBetween" 112 | layout = "SpaceAround" 113 | 114 | # Window width 115 | # Possible values: "auto" or a positive integer 116 | width = "auto" 117 | 118 | toggle_scanning = "s" 119 | esc_quit = false # Set to true to enable Esc key to quit the app 120 | 121 | [adapter] 122 | toggle_pairing = "p" 123 | toggle_power = "o" 124 | toggle_discovery = "d" 125 | 126 | [paired_device] 127 | unpair = "u" 128 | toggle_trust = "t" 129 | toggle_favorite = "f" 130 | rename = "e" 131 | ``` 132 | 133 | ## Contributing 134 | 135 | - No AI slop. 136 | - Only submit a pull request after having a prior issue or discussion. 137 | - Keep PRs small and focused. 138 | 139 | ## 🎁 Note 140 | 141 | If you like `bluetui` and you are looking for a TUI to manage WiFi, checkout out [impala](https://github.com/pythops/impala) 142 | 143 | ## ⚖️ License 144 | 145 | GPLv3 146 | 147 | ## ✍️ Credits 148 | 149 | Bluetui logo: [Marco Bulgarelli](https://github.com/Bugg4) 150 | -------------------------------------------------------------------------------- /src/requests/confirmation.rs: -------------------------------------------------------------------------------- 1 | use ratatui::{ 2 | Frame, 3 | layout::{Constraint, Direction, Layout, Rect}, 4 | style::{Color, Style, Stylize}, 5 | text::{Line, Span, Text}, 6 | widgets::{Block, BorderType, Borders, Clear}, 7 | }; 8 | 9 | use bluer::Address; 10 | 11 | use crate::{agent::AuthAgent, app::AppResult}; 12 | 13 | #[derive(Debug, Clone)] 14 | pub struct Confirmation { 15 | pub adapter: String, 16 | pub device: Address, 17 | pub passkey: u32, 18 | confirmed: bool, 19 | } 20 | 21 | impl Confirmation { 22 | pub fn new(adapter: String, device: Address, passkey: u32) -> Self { 23 | Self { 24 | adapter, 25 | device, 26 | passkey, 27 | confirmed: true, 28 | } 29 | } 30 | 31 | pub async fn submit(&mut self, agent: &AuthAgent) -> AppResult<()> { 32 | agent.tx_request_confirmation.send(self.confirmed).await?; 33 | agent 34 | .event_sender 35 | .send(crate::event::Event::ConfirmationSubmitted)?; 36 | Ok(()) 37 | } 38 | 39 | pub async fn cancel(&mut self, agent: &AuthAgent) -> AppResult<()> { 40 | agent.tx_cancel.send(()).await?; 41 | agent 42 | .event_sender 43 | .send(crate::event::Event::ConfirmationSubmitted)?; 44 | Ok(()) 45 | } 46 | 47 | pub fn toggle_select(&mut self) { 48 | self.confirmed = !self.confirmed; 49 | } 50 | 51 | pub fn render(&self, frame: &mut Frame, area: Rect) { 52 | let block = Layout::default() 53 | .direction(Direction::Vertical) 54 | .constraints([ 55 | Constraint::Fill(1), 56 | Constraint::Length(8), 57 | Constraint::Fill(1), 58 | ]) 59 | .split(area); 60 | 61 | let block = Layout::default() 62 | .direction(Direction::Horizontal) 63 | .constraints([ 64 | Constraint::Fill(1), 65 | Constraint::Max(70), 66 | Constraint::Fill(1), 67 | ]) 68 | .split(block[1])[1]; 69 | 70 | let (message_block, choices_block) = { 71 | let chunks = Layout::default() 72 | .direction(Direction::Vertical) 73 | .constraints( 74 | [ 75 | Constraint::Length(1), 76 | Constraint::Length(3), 77 | Constraint::Length(1), 78 | Constraint::Length(2), 79 | Constraint::Length(1), 80 | ] 81 | .as_ref(), 82 | ) 83 | .split(block); 84 | 85 | (chunks[1], chunks[3]) 86 | }; 87 | 88 | let message = Text::from(vec![ 89 | Line::from(vec![ 90 | Span::from("Authentication required for the device "), 91 | Span::from(self.device.to_string()), 92 | ]) 93 | .centered(), 94 | Line::from(""), 95 | Line::from(vec![ 96 | Span::from("Confirm Passkey "), 97 | Span::styled( 98 | format!("{:06}", self.passkey), 99 | Style::new().bg(Color::DarkGray).bold(), 100 | ), 101 | ]) 102 | .centered(), 103 | ]); 104 | 105 | let choice = { 106 | if self.confirmed { 107 | Line::from(vec![ 108 | Span::from("No").style(Style::default()), 109 | Span::from(" "), 110 | Span::from("Yes") 111 | .style(Style::default().bg(Color::Blue)) 112 | .bold(), 113 | ]) 114 | } else { 115 | Line::from(vec![ 116 | Span::from("No") 117 | .style(Style::default().bg(Color::Blue)) 118 | .bold(), 119 | Span::from(" "), 120 | Span::from("Yes").style(Style::default()), 121 | ]) 122 | } 123 | }; 124 | 125 | frame.render_widget(Clear, block); 126 | 127 | frame.render_widget( 128 | Block::new() 129 | .borders(Borders::ALL) 130 | .border_type(BorderType::Thick) 131 | .border_style(Style::default().fg(Color::Green)), 132 | block, 133 | ); 134 | frame.render_widget(message, message_block); 135 | frame.render_widget(choice.centered(), choices_block); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use bluetui::{ 2 | app::{App, AppResult}, 3 | cli, 4 | config::Config, 5 | event::{Event, EventHandler}, 6 | handler::handle_key_events, 7 | rfkill, 8 | tui::Tui, 9 | }; 10 | use ratatui::{Terminal, backend::CrosstermBackend}; 11 | use std::{io, path::PathBuf, process::exit, sync::Arc}; 12 | 13 | #[tokio::main] 14 | async fn main() -> AppResult<()> { 15 | let args = cli::cli().get_matches(); 16 | 17 | let config_file_path = if let Some(config) = args.get_one::("config") { 18 | if config.exists() { 19 | Some(config.to_owned()) 20 | } else { 21 | eprintln!("Config file not found"); 22 | exit(1); 23 | } 24 | } else { 25 | None 26 | }; 27 | 28 | rfkill::check()?; 29 | 30 | let config = Arc::new(Config::new(config_file_path)); 31 | 32 | let backend = CrosstermBackend::new(io::stdout()); 33 | let terminal = Terminal::new(backend)?; 34 | let events = EventHandler::new(1_000); 35 | let mut tui = Tui::new(terminal, events); 36 | 37 | tui.init()?; 38 | 39 | let mut app = App::new(config.clone(), tui.events.sender.clone()).await?; 40 | 41 | while app.running { 42 | tui.draw(&mut app)?; 43 | match tui.events.next().await? { 44 | Event::Tick => app.tick().await?, 45 | Event::Key(key_event) => { 46 | handle_key_events( 47 | key_event, 48 | &mut app, 49 | tui.events.sender.clone(), 50 | config.clone(), 51 | ) 52 | .await? 53 | } 54 | Event::Notification(notification) => { 55 | app.notifications.push(notification); 56 | } 57 | Event::NewPairedDevice(address) => { 58 | if let Some(req) = &app.requests.display_passkey 59 | && req.device == address 60 | { 61 | app.requests.display_passkey = None; 62 | } 63 | 64 | app.focused_block = bluetui::app::FocusedBlock::PairedDevices; 65 | } 66 | 67 | Event::ToggleFavorite(address) => { 68 | if let Some(pos) = app 69 | .favorite_devices 70 | .iter() 71 | .position(|favorite| *favorite == address) 72 | { 73 | app.favorite_devices.swap_remove(pos); 74 | } else { 75 | app.favorite_devices.push(address); 76 | } 77 | } 78 | 79 | Event::RequestConfirmation(request) => { 80 | app.requests.init_confirmation(request); 81 | app.focused_block = bluetui::app::FocusedBlock::RequestConfirmation; 82 | } 83 | 84 | Event::ConfirmationSubmitted => { 85 | app.requests.confirmation = None; 86 | app.focused_block = bluetui::app::FocusedBlock::PairedDevices; 87 | } 88 | 89 | Event::RequestEnterPinCode(request) => { 90 | app.requests.init_enter_pin_code(request); 91 | app.focused_block = bluetui::app::FocusedBlock::EnterPinCode; 92 | } 93 | 94 | Event::PinCodeSumitted => { 95 | app.requests.enter_pin_code = None; 96 | app.focused_block = bluetui::app::FocusedBlock::PairedDevices; 97 | } 98 | 99 | Event::RequestEnterPasskey(request) => { 100 | app.requests.init_enter_passkey(request); 101 | app.focused_block = bluetui::app::FocusedBlock::EnterPasskey; 102 | } 103 | 104 | Event::PasskeySumitted => { 105 | app.requests.enter_passkey = None; 106 | app.focused_block = bluetui::app::FocusedBlock::PairedDevices; 107 | } 108 | 109 | Event::RequestDisplayPinCode(request) => { 110 | app.requests.init_display_pin_code(request); 111 | app.focused_block = bluetui::app::FocusedBlock::DisplayPinCode; 112 | } 113 | 114 | Event::DisplayPinCodeSeen => { 115 | app.requests.display_pin_code = None; 116 | app.focused_block = bluetui::app::FocusedBlock::PairedDevices; 117 | } 118 | 119 | Event::RequestDisplayPasskey(request) => { 120 | app.requests.init_display_passkey(request); 121 | app.focused_block = bluetui::app::FocusedBlock::DisplayPasskey; 122 | } 123 | 124 | Event::DisplayPasskeyCanceled => { 125 | app.requests.display_passkey = None; 126 | app.focused_block = bluetui::app::FocusedBlock::PairedDevices; 127 | } 128 | 129 | Event::FailedPairing(address) => { 130 | if let Some(req) = &app.requests.display_passkey 131 | && req.device == address 132 | { 133 | app.requests.display_passkey = None; 134 | } 135 | 136 | app.focused_block = bluetui::app::FocusedBlock::PairedDevices; 137 | } 138 | 139 | Event::Mouse(_) | Event::Resize(_, _) => {} 140 | } 141 | } 142 | 143 | tui.exit()?; 144 | Ok(()) 145 | } 146 | -------------------------------------------------------------------------------- /src/agent.rs: -------------------------------------------------------------------------------- 1 | use async_channel::{Receiver, Sender}; 2 | use tokio::sync::mpsc::UnboundedSender; 3 | 4 | use bluer::agent::{ 5 | DisplayPasskey, DisplayPinCode, ReqError, ReqResult, RequestConfirmation, RequestPasskey, 6 | RequestPinCode, 7 | }; 8 | 9 | use crate::{ 10 | event::Event, 11 | requests::{ 12 | confirmation::Confirmation, enter_passkey::EnterPasskey, enter_pin_code::EnterPinCode, 13 | }, 14 | }; 15 | 16 | #[derive(Debug, Clone)] 17 | pub struct AuthAgent { 18 | pub event_sender: UnboundedSender, 19 | pub tx_cancel: Sender<()>, 20 | pub rx_cancel: Receiver<()>, 21 | pub tx_pin_code: Sender, 22 | pub rx_pin_code: Receiver, 23 | pub tx_display_pin_code: Sender<()>, 24 | pub rx_display_pin_code: Receiver<()>, 25 | pub tx_display_passkey: Sender<()>, 26 | pub rx_display_passkey: Receiver<()>, 27 | pub tx_passkey: Sender, 28 | pub rx_passkey: Receiver, 29 | pub tx_request_confirmation: Sender, 30 | pub rx_request_confirmation: Receiver, 31 | } 32 | 33 | impl AuthAgent { 34 | pub fn new(sender: UnboundedSender) -> Self { 35 | let (tx_passkey, rx_passkey) = async_channel::unbounded(); 36 | let (tx_display_passkey, rx_display_passkey) = async_channel::unbounded(); 37 | 38 | let (tx_pin_code, rx_pin_code) = async_channel::unbounded(); 39 | let (tx_display_pin_code, rx_display_pin_code) = async_channel::unbounded(); 40 | 41 | let (tx_request_confirmation, rx_request_confirmation) = async_channel::unbounded(); 42 | let (tx_cancel, rx_cancel) = async_channel::unbounded(); 43 | 44 | Self { 45 | event_sender: sender, 46 | tx_cancel, 47 | rx_cancel, 48 | tx_pin_code, 49 | rx_pin_code, 50 | tx_display_pin_code, 51 | rx_display_pin_code, 52 | tx_display_passkey, 53 | rx_display_passkey, 54 | tx_passkey, 55 | rx_passkey, 56 | tx_request_confirmation, 57 | rx_request_confirmation, 58 | } 59 | } 60 | } 61 | 62 | pub async fn request_confirmation(request: RequestConfirmation, agent: AuthAgent) -> ReqResult<()> { 63 | agent 64 | .event_sender 65 | .send(Event::RequestConfirmation(Confirmation::new( 66 | request.adapter, 67 | request.device, 68 | request.passkey, 69 | ))) 70 | .unwrap(); 71 | 72 | tokio::select! { 73 | r = agent.rx_request_confirmation.recv() => { 74 | match r { 75 | Ok(v) => { 76 | match v { 77 | true => Ok(()), 78 | false => Err(ReqError::Rejected) 79 | } 80 | } 81 | Err(_) => { 82 | Err(ReqError::Canceled) 83 | } 84 | } 85 | 86 | } 87 | 88 | _ = agent.rx_cancel.recv() => { 89 | Err(ReqError::Canceled) 90 | } 91 | 92 | } 93 | } 94 | 95 | pub async fn request_pin_code(request: RequestPinCode, agent: AuthAgent) -> ReqResult { 96 | agent 97 | .event_sender 98 | .send(Event::RequestEnterPinCode(EnterPinCode::new( 99 | request.adapter, 100 | request.device, 101 | ))) 102 | .unwrap(); 103 | 104 | tokio::select! { 105 | r = agent.rx_pin_code.recv() => { 106 | match r { 107 | Ok(v) => Ok(v), 108 | Err(_) => Err(ReqError::Canceled) 109 | } 110 | 111 | } 112 | 113 | _ = agent.rx_cancel.recv() => { 114 | Err(ReqError::Canceled) 115 | } 116 | 117 | } 118 | } 119 | 120 | pub async fn request_passkey(request: RequestPasskey, agent: AuthAgent) -> ReqResult { 121 | agent 122 | .event_sender 123 | .send(Event::RequestEnterPasskey(EnterPasskey::new( 124 | request.adapter, 125 | request.device, 126 | ))) 127 | .unwrap(); 128 | 129 | tokio::select! { 130 | r = agent.rx_passkey.recv() => { 131 | match r { 132 | Ok(v) => Ok(v), 133 | Err(_) => Err(ReqError::Canceled) 134 | } 135 | } 136 | 137 | _ = agent.rx_cancel.recv() => { 138 | Err(ReqError::Canceled) 139 | } 140 | 141 | } 142 | } 143 | 144 | pub async fn display_pin_code(request: DisplayPinCode, agent: AuthAgent) -> ReqResult<()> { 145 | agent 146 | .event_sender 147 | .send(Event::RequestDisplayPinCode( 148 | crate::requests::display_pin_code::DisplayPinCode::new( 149 | request.adapter, 150 | request.device, 151 | request.pincode, 152 | ), 153 | )) 154 | .unwrap(); 155 | 156 | tokio::select! { 157 | _ = agent.rx_display_pin_code.recv() => { 158 | Ok(()) 159 | } 160 | 161 | _ = agent.rx_cancel.recv() => { 162 | Err(ReqError::Canceled) 163 | } 164 | } 165 | } 166 | 167 | pub async fn display_passkey(request: DisplayPasskey, agent: AuthAgent) -> ReqResult<()> { 168 | let _ = agent.event_sender.send(Event::RequestDisplayPasskey( 169 | crate::requests::display_passkey::DisplayPasskey::new( 170 | request.adapter, 171 | request.device, 172 | request.passkey, 173 | request.entered, 174 | ), 175 | )); 176 | 177 | tokio::select! { 178 | _ = agent.rx_display_passkey.recv() => { 179 | Ok(()) 180 | } 181 | 182 | _ = agent.rx_cancel.recv() => { 183 | let _ = agent.event_sender.send(Event::DisplayPasskeyCanceled); 184 | Err(ReqError::Canceled) 185 | } 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | use std::{path::PathBuf, process::exit}; 3 | 4 | use ratatui::layout::Flex; 5 | use toml; 6 | 7 | use dirs; 8 | use serde::{ 9 | Deserialize, Deserializer, 10 | de::{self, Unexpected, Visitor}, 11 | }; 12 | 13 | #[derive(Deserialize, Debug)] 14 | pub struct Config { 15 | #[serde(default = "default_layout", deserialize_with = "deserialize_layout")] 16 | pub layout: Flex, 17 | 18 | #[serde(default = "Width::default")] 19 | pub width: Width, 20 | 21 | #[serde(default = "default_toggle_scanning")] 22 | pub toggle_scanning: char, 23 | 24 | #[serde(default = "default_esc_quit")] 25 | pub esc_quit: bool, 26 | 27 | #[serde(default)] 28 | pub adapter: Adapter, 29 | 30 | #[serde(default)] 31 | pub paired_device: PairedDevice, 32 | } 33 | 34 | #[derive(Debug, Default)] 35 | pub enum Width { 36 | #[default] 37 | Auto, 38 | Size(u16), 39 | } 40 | 41 | struct WidthVisitor; 42 | 43 | impl<'de> Visitor<'de> for WidthVisitor { 44 | type Value = Width; 45 | 46 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 47 | formatter.write_str("the string \"auto\" or a positive integer (u16)") 48 | } 49 | 50 | fn visit_str(self, value: &str) -> Result 51 | where 52 | E: de::Error, 53 | { 54 | match value { 55 | "auto" => Ok(Width::Auto), 56 | _ => value 57 | .parse::() 58 | .map(Width::Size) 59 | .map_err(|_| de::Error::invalid_value(Unexpected::Str(value), &self)), 60 | } 61 | } 62 | 63 | fn visit_u64(self, value: u64) -> Result 64 | where 65 | E: de::Error, 66 | { 67 | match u16::try_from(value) { 68 | Ok(v) => Ok(Width::Size(v)), 69 | Err(_) => Err(de::Error::invalid_value(Unexpected::Unsigned(value), &self)), 70 | } 71 | } 72 | 73 | fn visit_i64(self, value: i64) -> Result 74 | where 75 | E: de::Error, 76 | { 77 | match u16::try_from(value) { 78 | Ok(v) => Ok(Width::Size(v)), 79 | Err(_) => Err(de::Error::invalid_value(Unexpected::Signed(value), &self)), 80 | } 81 | } 82 | } 83 | 84 | impl<'de> Deserialize<'de> for Width { 85 | fn deserialize(deserializer: D) -> Result 86 | where 87 | D: Deserializer<'de>, 88 | { 89 | deserializer.deserialize_any(WidthVisitor) 90 | } 91 | } 92 | 93 | #[derive(Deserialize, Debug)] 94 | pub struct Adapter { 95 | #[serde(default = "default_toggle_adapter_pairing")] 96 | pub toggle_pairing: char, 97 | 98 | #[serde(default = "default_toggle_adapter_power")] 99 | pub toggle_power: char, 100 | 101 | #[serde(default = "default_toggle_adapter_discovery")] 102 | pub toggle_discovery: char, 103 | } 104 | 105 | impl Default for Adapter { 106 | fn default() -> Self { 107 | Self { 108 | toggle_pairing: 'p', 109 | toggle_power: 'o', 110 | toggle_discovery: 'd', 111 | } 112 | } 113 | } 114 | 115 | #[derive(Deserialize, Debug)] 116 | pub struct PairedDevice { 117 | #[serde(default = "default_unpair_device")] 118 | pub unpair: char, 119 | 120 | #[serde(default = "default_toggle_device_trust")] 121 | pub toggle_trust: char, 122 | 123 | #[serde(default = "default_toggle_device_favorite")] 124 | pub toggle_favorite: char, 125 | 126 | #[serde(default = "default_set_new_name")] 127 | pub rename: char, 128 | } 129 | 130 | impl Default for PairedDevice { 131 | fn default() -> Self { 132 | Self { 133 | unpair: 'u', 134 | toggle_trust: 't', 135 | toggle_favorite: 'f', 136 | rename: 'e', 137 | } 138 | } 139 | } 140 | 141 | fn deserialize_layout<'de, D>(deserializer: D) -> Result 142 | where 143 | D: Deserializer<'de>, 144 | { 145 | let s = String::deserialize(deserializer)?; 146 | 147 | match s.as_str() { 148 | "Legacy" => Ok(Flex::Legacy), 149 | "Start" => Ok(Flex::Start), 150 | "End" => Ok(Flex::End), 151 | "Center" => Ok(Flex::Center), 152 | "SpaceAround" => Ok(Flex::SpaceAround), 153 | "SpaceBetween" => Ok(Flex::SpaceBetween), 154 | _ => { 155 | eprintln!("Wrong config: unknown layout variant {}", s); 156 | eprintln!( 157 | "The possible values are: Legacy, Start, End, Center, SpaceAround, SpaceBetween" 158 | ); 159 | std::process::exit(1); 160 | } 161 | } 162 | } 163 | 164 | fn default_layout() -> Flex { 165 | Flex::SpaceAround 166 | } 167 | 168 | fn default_set_new_name() -> char { 169 | 'e' 170 | } 171 | 172 | fn default_toggle_scanning() -> char { 173 | 's' 174 | } 175 | 176 | fn default_esc_quit() -> bool { 177 | false 178 | } 179 | 180 | fn default_toggle_adapter_pairing() -> char { 181 | 'p' 182 | } 183 | 184 | fn default_toggle_adapter_power() -> char { 185 | 'o' 186 | } 187 | 188 | fn default_toggle_adapter_discovery() -> char { 189 | 'd' 190 | } 191 | 192 | fn default_unpair_device() -> char { 193 | 'u' 194 | } 195 | 196 | fn default_toggle_device_trust() -> char { 197 | 't' 198 | } 199 | 200 | fn default_toggle_device_favorite() -> char { 201 | 'f' 202 | } 203 | 204 | impl Config { 205 | pub fn new(config_file_path: Option) -> Self { 206 | let conf_path = config_file_path.unwrap_or( 207 | dirs::config_dir() 208 | .unwrap() 209 | .join("bluetui") 210 | .join("config.toml"), 211 | ); 212 | 213 | let config = std::fs::read_to_string(conf_path).unwrap_or_default(); 214 | let app_config: Config = match toml::from_str(&config) { 215 | Ok(c) => c, 216 | Err(e) => { 217 | eprintln!("{}", e); 218 | exit(1); 219 | } 220 | }; 221 | 222 | app_config 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /src/bluetooth.rs: -------------------------------------------------------------------------------- 1 | use std::sync::{Arc, atomic::AtomicBool}; 2 | 3 | use bluer::{Adapter, Address, Session}; 4 | 5 | use bluer::Device as BTDevice; 6 | 7 | use crate::app::AppResult; 8 | 9 | #[derive(Debug, Clone)] 10 | pub struct Controller { 11 | pub adapter: Arc, 12 | pub name: String, 13 | pub alias: String, 14 | pub is_powered: bool, 15 | pub is_pairable: bool, 16 | pub is_discoverable: bool, 17 | pub is_scanning: Arc, 18 | pub paired_devices: Vec, 19 | pub new_devices: Vec, 20 | } 21 | 22 | #[derive(Debug, Clone)] 23 | pub struct Device { 24 | device: BTDevice, 25 | pub addr: Address, 26 | pub icon: &'static str, 27 | pub alias: String, 28 | pub is_paired: bool, 29 | pub is_favorite: bool, 30 | pub is_trusted: bool, 31 | pub is_connected: bool, 32 | pub battery_percentage: Option, 33 | } 34 | 35 | impl Device { 36 | pub async fn set_alias(&self, alias: String) -> AppResult<()> { 37 | self.device.set_alias(alias).await?; 38 | Ok(()) 39 | } 40 | 41 | // https://specifications.freedesktop.org/icon-naming/latest/ 42 | pub fn get_icon(name: &str) -> &'static str { 43 | match name { 44 | "audio-card" => "󰓃 ", 45 | "audio-input-microphone" => " ", 46 | "audio-headphones" | "audio-headset" => "󰋋 ", 47 | "battery" => "󰂀 ", 48 | "camera-photo" => "󰻛 ", 49 | "computer" => " ", 50 | "input-keyboard" => "󰌌 ", 51 | "input-mouse" => "󰍽 ", 52 | "input-gaming" => "󰊴 ", 53 | "phone" => "󰏲 ", 54 | _ => "󰾰 ", 55 | } 56 | } 57 | } 58 | 59 | impl Controller { 60 | pub async fn get_all( 61 | session: Arc, 62 | favorite_devices: &[Address], 63 | ) -> AppResult> { 64 | let mut controllers: Vec = Vec::new(); 65 | 66 | // let session = bluer::Session::new().await?; 67 | let adapter_names = session.adapter_names().await?; 68 | for adapter_name in adapter_names { 69 | if let Ok(adapter) = session.adapter(&adapter_name) { 70 | let name = adapter.name().to_owned(); 71 | let alias = adapter.alias().await?; 72 | let is_powered = adapter.is_powered().await?; 73 | let is_pairable = adapter.is_pairable().await?; 74 | let is_discoverable = adapter.is_discoverable().await?; 75 | let is_scanning = adapter.is_discovering().await?; 76 | 77 | let (paired_devices, new_devices) = 78 | Controller::get_all_devices(&adapter, favorite_devices).await?; 79 | 80 | let controller = Controller { 81 | adapter: Arc::new(adapter), 82 | name, 83 | alias, 84 | is_powered, 85 | is_pairable, 86 | is_discoverable, 87 | is_scanning: Arc::new(AtomicBool::new(is_scanning)), 88 | paired_devices, 89 | new_devices, 90 | }; 91 | 92 | controllers.push(controller); 93 | } 94 | } 95 | 96 | Ok(controllers) 97 | } 98 | 99 | pub async fn get_all_devices( 100 | adapter: &Adapter, 101 | favorite_devices: &[Address], 102 | ) -> AppResult<(Vec, Vec)> { 103 | let mut paired_devices: Vec = Vec::new(); 104 | let mut new_devices: Vec = Vec::new(); 105 | let mut devices_without_aliases: Vec = Vec::new(); 106 | 107 | let connected_devices_addresses = adapter.device_addresses().await?; 108 | for addr in connected_devices_addresses { 109 | let device = adapter.device(addr)?; 110 | 111 | let alias = device.alias().await?; 112 | let icon = Device::get_icon(device.icon().await?.unwrap_or("-".to_string()).as_str()); 113 | let is_paired = device.is_paired().await?; 114 | let is_trusted = device.is_trusted().await?; 115 | let is_connected = device.is_connected().await?; 116 | let is_favorite = favorite_devices.contains(&addr); 117 | let battery_percentage = device.battery_percentage().await?; 118 | 119 | let dev = Device { 120 | device, 121 | addr, 122 | alias, 123 | icon, 124 | is_paired, 125 | is_trusted, 126 | is_connected, 127 | is_favorite, 128 | battery_percentage, 129 | }; 130 | 131 | if dev.is_paired { 132 | paired_devices.push(dev); 133 | } else { 134 | match is_mac_addr(&dev.alias) { 135 | // most device names without aliases may default to their mac addresses, but we should not 136 | // assume that to be 100% the case 137 | true => devices_without_aliases.push(dev), 138 | false => new_devices.push(dev), 139 | } 140 | } 141 | } 142 | 143 | paired_devices.sort_by_key(|i| (!i.is_favorite, i.addr)); 144 | new_devices.sort_by(|a, b| a.alias.cmp(&b.alias)); 145 | devices_without_aliases.sort_by_key(|i| i.addr); 146 | new_devices.extend(devices_without_aliases); 147 | 148 | Ok((paired_devices, new_devices)) 149 | } 150 | } 151 | 152 | fn is_mac_addr(s: &str) -> bool { 153 | if s.len() != 17 { 154 | return false; 155 | } 156 | let mut chars = s.chars(); 157 | for _ in 0..5 { 158 | // Matches [A-Fa-f0-9][A-Fa-f0-9]- 159 | if !(matches!(chars.next(), Some(c) if c.is_ascii_hexdigit()) 160 | && matches!(chars.next(), Some(c) if c.is_ascii_hexdigit()) 161 | && matches!(chars.next(), Some('-'))) 162 | { 163 | return false; 164 | } 165 | } 166 | // Matches [A-Fa-f0-9][A-Fa-f0-9]$ 167 | matches!(chars.next(), Some(c) if c.is_ascii_hexdigit()) 168 | && matches!(chars.next(), Some(c) if c.is_ascii_hexdigit()) 169 | && chars.next().is_none() 170 | } 171 | -------------------------------------------------------------------------------- /src/requests/enter_pin_code.rs: -------------------------------------------------------------------------------- 1 | use crossterm::event::{KeyCode, KeyEvent}; 2 | 3 | use ratatui::{ 4 | Frame, 5 | layout::{Constraint, Direction, Layout, Rect}, 6 | style::{Color, Style, Stylize}, 7 | text::{Line, Span, Text}, 8 | widgets::{Block, BorderType, Borders, Clear, List}, 9 | }; 10 | 11 | use bluer::Address; 12 | use tui_input::{Input, backend::crossterm::EventHandler}; 13 | 14 | use crate::{ 15 | agent::AuthAgent, 16 | app::AppResult, 17 | event::Event, 18 | requests::{pad_str, pad_string}, 19 | }; 20 | 21 | #[derive(Debug, Clone, PartialEq, Default)] 22 | pub enum FocusedSection { 23 | #[default] 24 | Input, 25 | Submit, 26 | } 27 | 28 | #[derive(Debug, Clone)] 29 | pub struct EnterPinCode { 30 | pub adapter: String, 31 | pub device: Address, 32 | focused_section: FocusedSection, 33 | pin_code: UserInputField, 34 | } 35 | 36 | #[derive(Debug, Clone, Default)] 37 | struct UserInputField { 38 | field: Input, 39 | error: Option, 40 | } 41 | 42 | impl EnterPinCode { 43 | pub fn new(adapter: String, device: Address) -> Self { 44 | Self { 45 | adapter, 46 | device, 47 | focused_section: FocusedSection::default(), 48 | pin_code: UserInputField::default(), 49 | } 50 | } 51 | 52 | pub async fn submit(&mut self, agent: &AuthAgent) -> AppResult<()> { 53 | self.validate(); 54 | 55 | if self.pin_code.error.is_some() { 56 | return Ok(()); 57 | } 58 | 59 | agent 60 | .tx_pin_code 61 | .send(self.pin_code.field.value().to_string()) 62 | .await?; 63 | 64 | agent.event_sender.send(Event::PinCodeSumitted)?; 65 | Ok(()) 66 | } 67 | 68 | pub async fn cancel(&mut self, agent: &AuthAgent) -> AppResult<()> { 69 | agent.tx_cancel.send(()).await?; 70 | agent.event_sender.send(Event::PinCodeSumitted)?; 71 | Ok(()) 72 | } 73 | 74 | pub fn validate(&mut self) { 75 | self.pin_code.error = None; 76 | if self.pin_code.field.value().is_empty() { 77 | self.pin_code.error = Some("Required field.".to_string()); 78 | return; 79 | } 80 | 81 | if self.pin_code.field.value().len() > 16 { 82 | self.pin_code.error = 83 | Some("Pin Code should be a string of 1-16 characters length".to_string()); 84 | } 85 | } 86 | 87 | pub async fn handle_key_events( 88 | &mut self, 89 | key_event: KeyEvent, 90 | agent: &AuthAgent, 91 | ) -> AppResult<()> { 92 | match key_event.code { 93 | KeyCode::Tab | KeyCode::BackTab => { 94 | if self.focused_section == FocusedSection::Input { 95 | self.focused_section = FocusedSection::Submit; 96 | } else { 97 | self.focused_section = FocusedSection::Input; 98 | } 99 | } 100 | _ => match self.focused_section { 101 | FocusedSection::Submit => { 102 | if let KeyCode::Enter = key_event.code { 103 | self.submit(agent).await?; 104 | } 105 | } 106 | 107 | _ => { 108 | self.pin_code 109 | .field 110 | .handle_event(&crossterm::event::Event::Key(key_event)); 111 | } 112 | }, 113 | } 114 | 115 | Ok(()) 116 | } 117 | 118 | pub fn render(&self, frame: &mut Frame, area: Rect) { 119 | let layout = Layout::default() 120 | .direction(Direction::Vertical) 121 | .constraints([ 122 | Constraint::Fill(1), 123 | Constraint::Length(8), 124 | Constraint::Fill(1), 125 | ]) 126 | .split(area); 127 | 128 | let block = Layout::default() 129 | .direction(Direction::Horizontal) 130 | .constraints([ 131 | Constraint::Fill(1), 132 | Constraint::Max(70), 133 | Constraint::Fill(1), 134 | ]) 135 | .split(layout[1])[1]; 136 | 137 | let (message_block, input_block, submit_block) = { 138 | let chunks = Layout::default() 139 | .direction(Direction::Vertical) 140 | .constraints( 141 | [ 142 | Constraint::Length(1), 143 | Constraint::Length(1), // message 144 | Constraint::Length(1), 145 | Constraint::Length(3), // input 146 | Constraint::Length(1), 147 | Constraint::Length(1), // enter 148 | Constraint::Length(1), 149 | ] 150 | .as_ref(), 151 | ) 152 | .split(block); 153 | 154 | (chunks[1], chunks[3], chunks[5]) 155 | }; 156 | 157 | let input_block = Layout::default() 158 | .direction(Direction::Horizontal) 159 | .constraints([Constraint::Max(5), Constraint::Fill(1), Constraint::Max(5)].as_ref()) 160 | .flex(ratatui::layout::Flex::Center) 161 | .split(input_block)[1]; 162 | 163 | let message = Text::from(format!( 164 | "Enter the PIN Code for the device {} on {}", 165 | self.device, self.adapter, 166 | )) 167 | .centered(); 168 | 169 | let items = vec![ 170 | Line::from(vec![ 171 | { 172 | if self.focused_section == FocusedSection::Input { 173 | Span::from("Pin Code").green().bold() 174 | } else { 175 | Span::from("Pin Code") 176 | } 177 | }, 178 | Span::from(" "), 179 | Span::from(pad_string(format!(" {}", self.pin_code.field.value()), 60)) 180 | .bg(Color::DarkGray), 181 | ]), 182 | Line::from(vec![Span::from(pad_str(" ", 10)), { 183 | if let Some(error) = &self.pin_code.error { 184 | Span::from(pad_str(error, 60)) 185 | } else { 186 | Span::from("") 187 | } 188 | }]) 189 | .red(), 190 | ]; 191 | 192 | let user_input = List::new(items); 193 | 194 | let submit = if self.focused_section == FocusedSection::Submit { 195 | Text::from("Submit").centered().bold().green() 196 | } else { 197 | Text::from("Submit").centered() 198 | }; 199 | 200 | frame.render_widget(Clear, block); 201 | 202 | frame.render_widget( 203 | Block::new() 204 | .borders(Borders::ALL) 205 | .border_type(BorderType::Thick) 206 | .border_style(Style::default().fg(Color::Green)), 207 | block, 208 | ); 209 | 210 | frame.render_widget(message, message_block); 211 | frame.render_widget(user_input, input_block); 212 | frame.render_widget(submit, submit_block); 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /src/requests/enter_passkey.rs: -------------------------------------------------------------------------------- 1 | use crossterm::event::{KeyCode, KeyEvent}; 2 | 3 | use ratatui::{ 4 | Frame, 5 | layout::{Constraint, Direction, Layout, Rect}, 6 | style::{Color, Style, Stylize}, 7 | text::{Line, Span, Text}, 8 | widgets::{Block, BorderType, Borders, Clear, List}, 9 | }; 10 | 11 | use bluer::Address; 12 | use tui_input::{Input, backend::crossterm::EventHandler}; 13 | 14 | use crate::{ 15 | agent::AuthAgent, 16 | app::AppResult, 17 | event::Event, 18 | requests::{pad_str, pad_string}, 19 | }; 20 | 21 | #[derive(Debug, Clone, PartialEq, Default)] 22 | pub enum FocusedSection { 23 | #[default] 24 | Input, 25 | Submit, 26 | } 27 | 28 | #[derive(Debug, Clone)] 29 | pub struct EnterPasskey { 30 | pub adapter: String, 31 | pub device: Address, 32 | focused_section: FocusedSection, 33 | passkey: UserInputField, 34 | } 35 | 36 | #[derive(Debug, Clone, Default)] 37 | struct UserInputField { 38 | field: Input, 39 | error: Option, 40 | } 41 | 42 | impl EnterPasskey { 43 | pub fn new(adapter: String, device: Address) -> Self { 44 | Self { 45 | adapter, 46 | device, 47 | focused_section: FocusedSection::default(), 48 | passkey: UserInputField::default(), 49 | } 50 | } 51 | 52 | pub async fn submit(&mut self, agent: &AuthAgent) -> AppResult<()> { 53 | self.validate(); 54 | 55 | if self.passkey.error.is_some() { 56 | return Ok(()); 57 | } 58 | 59 | agent 60 | .tx_passkey 61 | .send(self.passkey.field.value().parse::().unwrap()) 62 | .await?; 63 | 64 | agent.event_sender.send(Event::PasskeySumitted)?; 65 | Ok(()) 66 | } 67 | 68 | pub async fn cancel(&mut self, agent: &AuthAgent) -> AppResult<()> { 69 | agent.tx_cancel.send(()).await?; 70 | agent.event_sender.send(Event::PasskeySumitted)?; 71 | Ok(()) 72 | } 73 | 74 | pub fn validate(&mut self) { 75 | self.passkey.error = None; 76 | if self.passkey.field.value().is_empty() { 77 | self.passkey.error = Some("Required field.".to_string()); 78 | return; 79 | } 80 | 81 | if self.passkey.field.value().len() > 6 { 82 | self.passkey.error = 83 | Some("Passkey should be a numeric value between 0-999999".to_string()); 84 | return; 85 | } 86 | 87 | if self.passkey.field.value().parse::().is_err() { 88 | self.passkey.error = 89 | Some("Passkey should be a numeric value between 0-999999".to_string()); 90 | } 91 | } 92 | 93 | pub async fn handle_key_events( 94 | &mut self, 95 | key_event: KeyEvent, 96 | agent: &AuthAgent, 97 | ) -> AppResult<()> { 98 | match key_event.code { 99 | KeyCode::Tab | KeyCode::BackTab => { 100 | if self.focused_section == FocusedSection::Input { 101 | self.focused_section = FocusedSection::Submit; 102 | } else { 103 | self.focused_section = FocusedSection::Input; 104 | } 105 | } 106 | _ => match self.focused_section { 107 | FocusedSection::Submit => { 108 | if let KeyCode::Enter = key_event.code { 109 | self.submit(agent).await?; 110 | } 111 | } 112 | 113 | _ => { 114 | self.passkey 115 | .field 116 | .handle_event(&crossterm::event::Event::Key(key_event)); 117 | } 118 | }, 119 | } 120 | 121 | Ok(()) 122 | } 123 | 124 | pub fn render(&self, frame: &mut Frame, area: Rect) { 125 | let layout = Layout::default() 126 | .direction(Direction::Vertical) 127 | .constraints([ 128 | Constraint::Fill(1), 129 | Constraint::Length(8), 130 | Constraint::Fill(1), 131 | ]) 132 | .split(area); 133 | 134 | let block = Layout::default() 135 | .direction(Direction::Horizontal) 136 | .constraints([ 137 | Constraint::Fill(1), 138 | Constraint::Max(70), 139 | Constraint::Fill(1), 140 | ]) 141 | .split(layout[1])[1]; 142 | 143 | let (message_block, input_block, submit_block) = { 144 | let chunks = Layout::default() 145 | .direction(Direction::Vertical) 146 | .constraints( 147 | [ 148 | Constraint::Length(1), 149 | Constraint::Length(1), // message 150 | Constraint::Length(1), 151 | Constraint::Length(3), // input 152 | Constraint::Length(1), 153 | Constraint::Length(1), // enter 154 | Constraint::Length(1), 155 | ] 156 | .as_ref(), 157 | ) 158 | .split(block); 159 | 160 | (chunks[1], chunks[3], chunks[5]) 161 | }; 162 | 163 | let input_block = Layout::default() 164 | .direction(Direction::Horizontal) 165 | .constraints([Constraint::Max(5), Constraint::Fill(1), Constraint::Max(5)].as_ref()) 166 | .flex(ratatui::layout::Flex::Center) 167 | .split(input_block)[1]; 168 | 169 | let message = Text::from(format!( 170 | "Enter the Passkey for the device {} on {}", 171 | self.device, self.adapter, 172 | )) 173 | .centered(); 174 | 175 | let items = vec![ 176 | Line::from(vec![ 177 | { 178 | if self.focused_section == FocusedSection::Input { 179 | Span::from("Passkey").green().bold() 180 | } else { 181 | Span::from("Passkey") 182 | } 183 | }, 184 | Span::from(" "), 185 | Span::from(pad_string(format!(" {}", self.passkey.field.value()), 60)) 186 | .bg(Color::DarkGray), 187 | ]), 188 | Line::from(vec![Span::from(pad_str(" ", 9)), { 189 | if let Some(error) = &self.passkey.error { 190 | Span::from(pad_str(error, 60)) 191 | } else { 192 | Span::from("") 193 | } 194 | }]) 195 | .red(), 196 | ]; 197 | 198 | let user_input = List::new(items); 199 | 200 | let submit = if self.focused_section == FocusedSection::Submit { 201 | Text::from("Submit").centered().bold().green() 202 | } else { 203 | Text::from("Submit").centered() 204 | }; 205 | 206 | frame.render_widget(Clear, block); 207 | 208 | frame.render_widget( 209 | Block::new() 210 | .borders(Borders::ALL) 211 | .border_type(BorderType::Thick) 212 | .border_style(Style::default().fg(Color::Green)), 213 | block, 214 | ); 215 | 216 | frame.render_widget(message, message_block); 217 | frame.render_widget(user_input, input_block); 218 | frame.render_widget(submit, submit_block); 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /src/help.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use ratatui::{ 4 | Frame, 5 | layout::Rect, 6 | style::Stylize, 7 | text::{Line, Span}, 8 | widgets::Paragraph, 9 | }; 10 | 11 | use crate::{app::FocusedBlock, config::Config}; 12 | 13 | pub struct Help; 14 | 15 | impl Help { 16 | pub fn render( 17 | frame: &mut Frame, 18 | area: Rect, 19 | focused_block: FocusedBlock, 20 | rendering_block: Rect, 21 | config: Arc, 22 | ) { 23 | let help = match focused_block { 24 | FocusedBlock::PairedDevices => { 25 | if area.width > 120 { 26 | vec![Line::from(vec![ 27 | Span::from("k,").bold(), 28 | Span::from(" Up"), 29 | Span::from(" | "), 30 | Span::from("j,").bold(), 31 | Span::from(" Down"), 32 | Span::from(" | "), 33 | Span::from("s").bold(), 34 | Span::from(" Scan on/off"), 35 | Span::from(" | "), 36 | Span::from(config.paired_device.unpair.to_string()).bold(), 37 | Span::from(" Unpair"), 38 | Span::from(" | "), 39 | Span::from("󱁐 or ↵ ").bold(), 40 | Span::from(" Dis/Connect"), 41 | Span::from(" | "), 42 | Span::from(config.paired_device.toggle_trust.to_string()).bold(), 43 | Span::from(" Un/Trust"), 44 | Span::from(" | "), 45 | Span::from(config.paired_device.toggle_favorite.to_string()).bold(), 46 | Span::from(" Un/Favorite"), 47 | Span::from(" | "), 48 | Span::from(config.paired_device.rename.to_string()).bold(), 49 | Span::from(" Rename"), 50 | Span::from(" | "), 51 | Span::from("⇄").bold(), 52 | Span::from(" Nav"), 53 | ])] 54 | } else { 55 | vec![ 56 | Line::from(vec![ 57 | Span::from("󱁐 or ↵ ").bold(), 58 | Span::from(" Dis/Connect"), 59 | Span::from(" | "), 60 | Span::from("s").bold(), 61 | Span::from(" Scan on/off"), 62 | Span::from(" | "), 63 | Span::from(config.paired_device.unpair.to_string()).bold(), 64 | Span::from(" Unpair"), 65 | Span::from(" | "), 66 | Span::from(config.paired_device.toggle_favorite.to_string()).bold(), 67 | Span::from(" Un/Favorite"), 68 | ]), 69 | Line::from(vec![ 70 | Span::from(config.paired_device.toggle_trust.to_string()).bold(), 71 | Span::from(" Un/Trust"), 72 | Span::from(" | "), 73 | Span::from(config.paired_device.rename.to_string()).bold(), 74 | Span::from(" Rename"), 75 | Span::from(" | "), 76 | Span::from("k,").bold(), 77 | Span::from(" Up"), 78 | Span::from(" | "), 79 | Span::from("j,").bold(), 80 | Span::from(" Down"), 81 | Span::from(" | "), 82 | Span::from("⇄").bold(), 83 | Span::from(" Nav"), 84 | ]), 85 | ] 86 | } 87 | } 88 | FocusedBlock::NewDevices => vec![Line::from(vec![ 89 | Span::from("k,").bold(), 90 | Span::from(" Up"), 91 | Span::from(" | "), 92 | Span::from("j,").bold(), 93 | Span::from(" Down"), 94 | Span::from(" | "), 95 | Span::from("󱁐 or ↵ ").bold(), 96 | Span::from(" Pair"), 97 | Span::from(" | "), 98 | Span::from("s").bold(), 99 | Span::from(" Scan on/off"), 100 | Span::from(" | "), 101 | Span::from("⇄").bold(), 102 | Span::from(" Nav"), 103 | ])], 104 | FocusedBlock::Adapter => { 105 | if area.width > 80 { 106 | vec![Line::from(vec![ 107 | Span::from("s").bold(), 108 | Span::from(" Scan on/off"), 109 | Span::from(" | "), 110 | Span::from(config.adapter.toggle_pairing.to_string()).bold(), 111 | Span::from(" Pairing on/off"), 112 | Span::from(" | "), 113 | Span::from(config.adapter.toggle_power.to_string()).bold(), 114 | Span::from(" Power on/off"), 115 | Span::from(" | "), 116 | Span::from(config.adapter.toggle_discovery.to_string()).bold(), 117 | Span::from(" Discovery on/off"), 118 | Span::from(" | "), 119 | Span::from("⇄").bold(), 120 | Span::from(" Nav"), 121 | ])] 122 | } else { 123 | vec![ 124 | Line::from(vec![ 125 | Span::from("s").bold(), 126 | Span::from(" Scan on/off"), 127 | Span::from(" | "), 128 | Span::from(config.adapter.toggle_pairing.to_string()).bold(), 129 | Span::from(" Pairing on/off"), 130 | ]), 131 | Line::from(vec![ 132 | Span::from(config.adapter.toggle_power.to_string()).bold(), 133 | Span::from(" Power on/off"), 134 | Span::from(" | "), 135 | Span::from(config.adapter.toggle_discovery.to_string()).bold(), 136 | Span::from(" Discovery on/off"), 137 | Span::from(" | "), 138 | Span::from("⇄").bold(), 139 | Span::from(" Nav"), 140 | ]), 141 | ] 142 | } 143 | } 144 | FocusedBlock::SetDeviceAliasBox => { 145 | vec![Line::from(vec![ 146 | Span::from("󱊷 ").bold(), 147 | Span::from(" Discard"), 148 | Span::from(" | "), 149 | Span::from("↵ ").bold(), 150 | Span::from(" Apply"), 151 | ])] 152 | } 153 | FocusedBlock::RequestConfirmation => { 154 | vec![Line::from(vec![ 155 | Span::from("↵ ").bold(), 156 | Span::from(" Ok"), 157 | Span::from(" | "), 158 | Span::from("󱊷 ").bold(), 159 | Span::from(" Discard"), 160 | Span::from(" | "), 161 | Span::from("⇄").bold(), 162 | Span::from(" Nav"), 163 | ])] 164 | } 165 | FocusedBlock::EnterPinCode | FocusedBlock::EnterPasskey => { 166 | vec![Line::from(vec![ 167 | Span::from("󱊷 ").bold(), 168 | Span::from(" Discard"), 169 | Span::from(" | "), 170 | Span::from("⇄").bold(), 171 | Span::from(" Nav"), 172 | Span::from(" | "), 173 | Span::from("↵ ").bold(), 174 | Span::from(" Submit"), 175 | ])] 176 | } 177 | FocusedBlock::DisplayPinCode => { 178 | vec![Line::from(vec![ 179 | Span::from(" 󱊷 or ↵ ").bold(), 180 | Span::from(" Ok"), 181 | ])] 182 | } 183 | FocusedBlock::DisplayPasskey => { 184 | vec![Line::from(vec![ 185 | Span::from(" 󱊷 ").bold(), 186 | Span::from(" Discard"), 187 | ])] 188 | } 189 | }; 190 | let help = Paragraph::new(help).centered().blue(); 191 | frame.render_widget(help, rendering_block); 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/app.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | agent::{ 3 | display_passkey, display_pin_code, request_confirmation, request_passkey, request_pin_code, 4 | }, 5 | event::Event, 6 | help::Help, 7 | }; 8 | use bluer::{ 9 | Address, Session, 10 | agent::{Agent, AgentHandle}, 11 | }; 12 | use futures::FutureExt; 13 | use ratatui::{ 14 | Frame, 15 | layout::{Alignment, Constraint, Direction, Layout, Margin, Rect}, 16 | style::{Color, Modifier, Style, Stylize}, 17 | text::{Line, Span}, 18 | widgets::{ 19 | Block, BorderType, Borders, Cell, Clear, Padding, Paragraph, Row, Scrollbar, 20 | ScrollbarOrientation, ScrollbarState, Table, TableState, 21 | }, 22 | }; 23 | use tokio::sync::mpsc::UnboundedSender; 24 | use tui_input::Input; 25 | 26 | use crate::{ 27 | agent::AuthAgent, 28 | bluetooth::Controller, 29 | config::{Config, Width}, 30 | favorite::{read_favorite_devices_from_disk, save_favorite_devices_to_disk}, 31 | notification::Notification, 32 | requests::Requests, 33 | spinner::Spinner, 34 | }; 35 | use std::sync::{Arc, atomic::Ordering}; 36 | 37 | pub type AppResult = anyhow::Result; 38 | 39 | const STAR_SYMBOL: &str = "★"; 40 | 41 | #[derive(Debug, Clone, Copy, PartialEq)] 42 | pub enum FocusedBlock { 43 | Adapter, 44 | PairedDevices, 45 | NewDevices, 46 | SetDeviceAliasBox, 47 | RequestConfirmation, 48 | EnterPinCode, 49 | EnterPasskey, 50 | DisplayPinCode, 51 | DisplayPasskey, 52 | } 53 | 54 | #[derive(Debug)] 55 | pub struct App { 56 | pub running: bool, 57 | pub session: Arc, 58 | pub agent: AgentHandle, 59 | pub spinner: Spinner, 60 | pub notifications: Vec, 61 | pub controllers: Vec, 62 | pub controller_state: TableState, 63 | pub paired_devices_state: TableState, 64 | pub favorite_devices: Vec
, 65 | pub new_devices_state: TableState, 66 | pub focused_block: FocusedBlock, 67 | pub new_alias: Input, 68 | pub config: Arc, 69 | pub requests: Requests, 70 | pub auth_agent: AuthAgent, 71 | } 72 | 73 | impl App { 74 | pub async fn new(config: Arc, sender: UnboundedSender) -> AppResult { 75 | let session = Arc::new(bluer::Session::new().await?); 76 | 77 | let auth_agent = AuthAgent::new(sender.clone()); 78 | 79 | let agent = Agent { 80 | request_default: false, 81 | request_confirmation: Some(Box::new({ 82 | let auth_agent = auth_agent.clone(); 83 | move |request| request_confirmation(request, auth_agent.clone()).boxed() 84 | })), 85 | request_pin_code: Some(Box::new({ 86 | let auth_agent = auth_agent.clone(); 87 | move |request| request_pin_code(request, auth_agent.clone()).boxed() 88 | })), 89 | request_passkey: Some(Box::new({ 90 | let auth_agent = auth_agent.clone(); 91 | move |request| request_passkey(request, auth_agent.clone()).boxed() 92 | })), 93 | display_pin_code: Some(Box::new({ 94 | let auth_agent = auth_agent.clone(); 95 | move |request| display_pin_code(request, auth_agent.clone()).boxed() 96 | })), 97 | display_passkey: Some(Box::new({ 98 | let auth_agent = auth_agent.clone(); 99 | move |request| display_passkey(request, auth_agent.clone()).boxed() 100 | })), 101 | ..Default::default() 102 | }; 103 | 104 | let favorite_devices = read_favorite_devices_from_disk().await.unwrap_or_default(); 105 | 106 | let handle = session.register_agent(agent).await?; 107 | let controllers: Vec = 108 | Controller::get_all(session.clone(), &favorite_devices).await?; 109 | 110 | let mut controller_state = TableState::default(); 111 | if controllers.is_empty() { 112 | controller_state.select(None); 113 | } else { 114 | controller_state.select(Some(0)); 115 | } 116 | 117 | Ok(Self { 118 | running: true, 119 | session, 120 | agent: handle, 121 | spinner: Spinner::default(), 122 | notifications: Vec::new(), 123 | controllers, 124 | controller_state, 125 | paired_devices_state: TableState::default(), 126 | favorite_devices, 127 | new_devices_state: TableState::default(), 128 | focused_block: FocusedBlock::PairedDevices, 129 | new_alias: Input::default(), 130 | config, 131 | requests: Requests::default(), 132 | auth_agent, 133 | }) 134 | } 135 | 136 | pub fn reset_devices_state(&mut self) { 137 | if let Some(selected_controller) = self.controller_state.selected() { 138 | let controller = &self.controllers[selected_controller]; 139 | if !controller.paired_devices.is_empty() { 140 | self.paired_devices_state.select(Some(0)); 141 | } else { 142 | self.paired_devices_state.select(None); 143 | } 144 | 145 | if !controller.new_devices.is_empty() { 146 | self.new_devices_state.select(Some(0)); 147 | } else { 148 | self.new_devices_state.select(None); 149 | } 150 | } 151 | } 152 | 153 | pub fn area(&self, frame: &Frame) -> Rect { 154 | match self.config.width { 155 | Width::Size(v) => { 156 | if v < frame.area().width { 157 | let area = Layout::default() 158 | .direction(Direction::Horizontal) 159 | .constraints([Constraint::Length(v), Constraint::Fill(1)]) 160 | .split(frame.area()); 161 | 162 | area[0] 163 | } else { 164 | frame.area() 165 | } 166 | } 167 | _ => frame.area(), 168 | } 169 | } 170 | 171 | pub fn render_set_alias(&mut self, frame: &mut Frame, area: Rect) { 172 | let block = Layout::default() 173 | .direction(Direction::Vertical) 174 | .constraints([ 175 | Constraint::Fill(1), 176 | Constraint::Length(6), 177 | Constraint::Fill(1), 178 | ]) 179 | .split(area); 180 | 181 | let block = Layout::default() 182 | .direction(Direction::Horizontal) 183 | .constraints([ 184 | Constraint::Fill(1), 185 | Constraint::Max(70), 186 | Constraint::Fill(1), 187 | ]) 188 | .split(block[1])[1]; 189 | 190 | let (text_block, alias_block) = { 191 | let chunks = Layout::default() 192 | .direction(Direction::Vertical) 193 | .constraints( 194 | [ 195 | Constraint::Length(1), 196 | Constraint::Length(3), 197 | Constraint::Length(1), 198 | Constraint::Length(2), 199 | ] 200 | .as_ref(), 201 | ) 202 | .split(block); 203 | 204 | let area1 = Layout::default() 205 | .direction(Direction::Horizontal) 206 | .constraints( 207 | [ 208 | Constraint::Length(1), 209 | Constraint::Fill(1), 210 | Constraint::Length(1), 211 | ] 212 | .as_ref(), 213 | ) 214 | .split(chunks[1]); 215 | 216 | let area2 = Layout::default() 217 | .direction(Direction::Horizontal) 218 | .constraints( 219 | [ 220 | Constraint::Percentage(20), 221 | Constraint::Fill(1), 222 | Constraint::Percentage(20), 223 | ] 224 | .as_ref(), 225 | ) 226 | .split(chunks[2]); 227 | 228 | (area1[1], area2[1]) 229 | }; 230 | 231 | frame.render_widget(Clear, block); 232 | frame.render_widget( 233 | Block::new() 234 | .borders(Borders::ALL) 235 | .border_type(BorderType::Thick) 236 | .style(Style::default().green()) 237 | .border_style(Style::default().fg(Color::Green)), 238 | block, 239 | ); 240 | 241 | if let Some(selected_controller) = self.controller_state.selected() { 242 | let controller = &self.controllers[selected_controller]; 243 | if let Some(index) = self.paired_devices_state.selected() { 244 | let name = controller.paired_devices[index].alias.as_str(); 245 | 246 | let text = Line::from(vec![ 247 | Span::from("Enter the new name for "), 248 | Span::styled( 249 | name, 250 | Style::default().add_modifier(Modifier::BOLD | Modifier::ITALIC), 251 | ), 252 | ]); 253 | 254 | let msg = Paragraph::new(text) 255 | .alignment(Alignment::Center) 256 | .style(Style::default().fg(Color::White)) 257 | .block(Block::new().padding(Padding::horizontal(2))); 258 | 259 | let alias = Paragraph::new(self.new_alias.value()) 260 | .alignment(Alignment::Left) 261 | .style(Style::default().fg(Color::White)) 262 | .block( 263 | Block::new() 264 | .bg(Color::DarkGray) 265 | .padding(Padding::horizontal(2)), 266 | ); 267 | 268 | frame.render_widget(msg, text_block); 269 | frame.render_widget(alias, alias_block); 270 | } 271 | } 272 | } 273 | 274 | pub fn render(&mut self, frame: &mut Frame) { 275 | if let Some(selected_controller_index) = self.controller_state.selected() { 276 | let selected_controller = &self.controllers[selected_controller_index]; 277 | // Layout 278 | let render_new_devices = selected_controller.is_scanning.load(Ordering::Relaxed); 279 | 280 | if !render_new_devices && self.focused_block == FocusedBlock::NewDevices { 281 | self.focused_block = FocusedBlock::PairedDevices; 282 | } 283 | 284 | let adapter_block_height = self.controllers.len() as u16 + 4; 285 | 286 | let paired_devices_block_height = selected_controller.paired_devices.len() as u16 + 4; 287 | 288 | let (paired_devices_block, new_devices_block, controller_block, help_block) = { 289 | let chunks = Layout::default() 290 | .direction(Direction::Vertical) 291 | .constraints(if render_new_devices { 292 | [ 293 | Constraint::Length(paired_devices_block_height), 294 | Constraint::Fill(1), 295 | Constraint::Length(adapter_block_height), 296 | Constraint::Length(2), 297 | ] 298 | } else { 299 | [ 300 | Constraint::Fill(1), 301 | Constraint::Length(0), 302 | Constraint::Length(adapter_block_height), 303 | Constraint::Length(2), 304 | ] 305 | }) 306 | .margin(1) 307 | .split(self.area(frame)); 308 | (chunks[0], chunks[1], chunks[2], chunks[3]) 309 | }; 310 | 311 | //Adapters 312 | let rows: Vec = self 313 | .controllers 314 | .iter() 315 | .map(|controller| { 316 | Row::new(vec![ 317 | controller.name.to_string(), 318 | controller.alias.to_string(), 319 | { 320 | if controller.is_powered { 321 | "On".to_string() 322 | } else { 323 | "Off".to_string() 324 | } 325 | }, 326 | controller.is_pairable.to_string(), 327 | controller.is_discoverable.to_string(), 328 | ]) 329 | }) 330 | .collect(); 331 | 332 | let widths = [ 333 | Constraint::Length(10), 334 | Constraint::Length(10), 335 | Constraint::Length(5), 336 | Constraint::Length(8), 337 | Constraint::Length(12), 338 | ]; 339 | 340 | let rows_len = rows.len(); 341 | 342 | let controller_table = Table::new(rows, widths) 343 | .header({ 344 | if self.focused_block == FocusedBlock::Adapter { 345 | Row::new(vec![ 346 | Cell::from("Name").style(Style::default().fg(Color::Yellow)), 347 | Cell::from("Alias").style(Style::default().fg(Color::Yellow)), 348 | Cell::from("Power").style(Style::default().fg(Color::Yellow)), 349 | Cell::from("Pairable").style(Style::default().fg(Color::Yellow)), 350 | Cell::from("Discoverable").style(Style::default().fg(Color::Yellow)), 351 | ]) 352 | .style(Style::new().bold()) 353 | .bottom_margin(1) 354 | } else { 355 | Row::new(vec![ 356 | Cell::from("Name"), 357 | Cell::from("Alias"), 358 | Cell::from("Power"), 359 | Cell::from("Pairable"), 360 | Cell::from("Discoverable"), 361 | ]) 362 | .bottom_margin(1) 363 | } 364 | }) 365 | .block( 366 | Block::default() 367 | .title(" Adapter ") 368 | .title_style({ 369 | if self.focused_block == FocusedBlock::Adapter { 370 | Style::default().bold() 371 | } else { 372 | Style::default() 373 | } 374 | }) 375 | .borders(Borders::ALL) 376 | .border_style({ 377 | if self.focused_block == FocusedBlock::Adapter { 378 | Style::default().fg(Color::Green) 379 | } else { 380 | Style::default() 381 | } 382 | }) 383 | .border_type({ 384 | if self.focused_block == FocusedBlock::Adapter { 385 | BorderType::Thick 386 | } else { 387 | BorderType::default() 388 | } 389 | }), 390 | ) 391 | .flex(self.config.layout) 392 | .row_highlight_style(if self.focused_block == FocusedBlock::Adapter { 393 | Style::default().bg(Color::DarkGray).fg(Color::White) 394 | } else { 395 | Style::default() 396 | }); 397 | 398 | frame.render_stateful_widget( 399 | controller_table, 400 | controller_block, 401 | &mut self.controller_state.clone(), 402 | ); 403 | 404 | if rows_len > controller_block.height.saturating_sub(4) as usize { 405 | let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight) 406 | .begin_symbol(Some("↑")) 407 | .end_symbol(Some("↓")); 408 | let mut scrollbar_state = 409 | ScrollbarState::new(self.controllers.len()).position(selected_controller_index); 410 | frame.render_stateful_widget( 411 | scrollbar, 412 | controller_block.inner(Margin { 413 | vertical: 1, 414 | horizontal: 0, 415 | }), 416 | &mut scrollbar_state, 417 | ); 418 | } 419 | 420 | //Paired devices 421 | let rows: Vec = selected_controller 422 | .paired_devices 423 | .iter() 424 | .map(|d| { 425 | Row::new(vec![ 426 | if d.is_favorite { 427 | STAR_SYMBOL.to_string() 428 | } else { 429 | "".to_string() 430 | }, 431 | format!("{} {}", &d.icon, &d.alias), 432 | d.is_trusted.to_string(), 433 | d.is_connected.to_string(), 434 | { 435 | if let Some(battery_percentage) = d.battery_percentage { 436 | match battery_percentage { 437 | n if n >= 90 => { 438 | format!("{battery_percentage}% 󰥈 ") 439 | } 440 | n if (80..90).contains(&n) => { 441 | format!("{battery_percentage}% 󰥅 ") 442 | } 443 | n if (70..80).contains(&n) => { 444 | format!("{battery_percentage}% 󰥄 ") 445 | } 446 | n if (60..70).contains(&n) => { 447 | format!("{battery_percentage}% 󰥃 ") 448 | } 449 | n if (50..60).contains(&n) => { 450 | format!("{battery_percentage}% 󰥂 ") 451 | } 452 | n if (40..50).contains(&n) => { 453 | format!("{battery_percentage}% 󰥁 ") 454 | } 455 | n if (30..40).contains(&n) => { 456 | format!("{battery_percentage}% 󰥀 ") 457 | } 458 | n if (20..30).contains(&n) => { 459 | format!("{battery_percentage}% 󰤿 ") 460 | } 461 | n if (10..20).contains(&n) => { 462 | format!("{battery_percentage}% 󰤾 ") 463 | } 464 | _ => { 465 | format!("{battery_percentage}% 󰤾 ") 466 | } 467 | } 468 | } else { 469 | String::new() 470 | } 471 | }, 472 | ]) 473 | }) 474 | .collect(); 475 | let rows_len = rows.len(); 476 | 477 | if rows_len > 0 478 | && self.focused_block == FocusedBlock::PairedDevices 479 | && self.paired_devices_state.selected().is_none() 480 | { 481 | self.paired_devices_state.select(Some(0)); 482 | } 483 | 484 | let show_battery_column = selected_controller 485 | .paired_devices 486 | .iter() 487 | .any(|device| device.battery_percentage.is_some()); 488 | 489 | let mut widths = vec![ 490 | Constraint::Length(1), 491 | Constraint::Max(25), 492 | Constraint::Length(7), 493 | Constraint::Length(9), 494 | ]; 495 | 496 | if show_battery_column { 497 | widths.push(Constraint::Length(10)); 498 | } 499 | 500 | let paired_devices_table = Table::new(rows, widths) 501 | .header({ 502 | if show_battery_column { 503 | if self.focused_block == FocusedBlock::PairedDevices { 504 | Row::new(vec![ 505 | Cell::from("").style(Style::default().fg(Color::Yellow)), 506 | Cell::from("Name").style(Style::default().fg(Color::Yellow)), 507 | Cell::from("Trusted").style(Style::default().fg(Color::Yellow)), 508 | Cell::from("Connected").style(Style::default().fg(Color::Yellow)), 509 | Cell::from("Battery").style(Style::default().fg(Color::Yellow)), 510 | ]) 511 | .style(Style::new().bold()) 512 | .bottom_margin(1) 513 | } else { 514 | Row::new(vec![ 515 | Cell::from(""), 516 | Cell::from("Name"), 517 | Cell::from("Trusted"), 518 | Cell::from("Connected"), 519 | Cell::from("Battery"), 520 | ]) 521 | .bottom_margin(1) 522 | } 523 | } else if self.focused_block == FocusedBlock::PairedDevices { 524 | Row::new(vec![ 525 | Cell::from("").style(Style::default().fg(Color::Yellow)), 526 | Cell::from("Name").style(Style::default().fg(Color::Yellow)), 527 | Cell::from("Trusted").style(Style::default().fg(Color::Yellow)), 528 | Cell::from("Connected").style(Style::default().fg(Color::Yellow)), 529 | ]) 530 | .style(Style::new().bold()) 531 | .bottom_margin(1) 532 | } else { 533 | Row::new(vec![ 534 | Cell::from(""), 535 | Cell::from("Name"), 536 | Cell::from("Trusted"), 537 | Cell::from("Connected"), 538 | ]) 539 | .style(Style::new().bold()) 540 | .bottom_margin(1) 541 | } 542 | }) 543 | .block( 544 | Block::default() 545 | .title(" Paired Devices ") 546 | .title_style({ 547 | if self.focused_block == FocusedBlock::PairedDevices { 548 | Style::default().bold() 549 | } else { 550 | Style::default() 551 | } 552 | }) 553 | .borders(Borders::ALL) 554 | .border_style({ 555 | if self.focused_block == FocusedBlock::PairedDevices { 556 | Style::default().fg(Color::Green) 557 | } else { 558 | Style::default() 559 | } 560 | }) 561 | .border_type({ 562 | if self.focused_block == FocusedBlock::PairedDevices { 563 | BorderType::Thick 564 | } else { 565 | BorderType::default() 566 | } 567 | }), 568 | ) 569 | .flex(self.config.layout) 570 | .row_highlight_style(if self.focused_block == FocusedBlock::PairedDevices { 571 | Style::default().bg(Color::DarkGray).fg(Color::White) 572 | } else { 573 | Style::default() 574 | }); 575 | 576 | frame.render_stateful_widget( 577 | paired_devices_table, 578 | paired_devices_block, 579 | &mut self.paired_devices_state.clone(), 580 | ); 581 | 582 | if rows_len > paired_devices_block.height.saturating_sub(4) as usize { 583 | let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight) 584 | .begin_symbol(Some("↑")) 585 | .end_symbol(Some("↓")); 586 | let mut scrollbar_state = ScrollbarState::new(rows_len) 587 | .position(self.paired_devices_state.selected().unwrap_or_default()); 588 | frame.render_stateful_widget( 589 | scrollbar, 590 | paired_devices_block.inner(Margin { 591 | vertical: 1, 592 | horizontal: 0, 593 | }), 594 | &mut scrollbar_state, 595 | ); 596 | } 597 | 598 | //New devices 599 | 600 | if render_new_devices { 601 | let rows: Vec = selected_controller 602 | .new_devices 603 | .iter() 604 | .map(|d| { 605 | Row::new(vec![ 606 | d.addr.to_string(), 607 | format!("{} {}", &d.icon, &d.alias), 608 | ]) 609 | }) 610 | .collect(); 611 | let rows_len = rows.len(); 612 | 613 | let widths = [Constraint::Length(20), Constraint::Length(20)]; 614 | 615 | let new_devices_table = Table::new(rows, widths) 616 | .header({ 617 | if self.focused_block == FocusedBlock::NewDevices { 618 | Row::new(vec![ 619 | Cell::from(Line::from("Address").fg(Color::Yellow).centered()), 620 | Cell::from(Line::from("Name").fg(Color::Yellow).centered()), 621 | ]) 622 | .style(Style::new().bold()) 623 | .bottom_margin(1) 624 | } else { 625 | Row::new(vec![ 626 | Cell::from(Line::from("Address").centered()), 627 | Cell::from(Line::from("Name").centered()), 628 | ]) 629 | .bottom_margin(1) 630 | } 631 | }) 632 | .block( 633 | Block::default() 634 | .padding(Padding::horizontal(1)) 635 | .title({ 636 | if selected_controller.is_scanning.load(Ordering::Relaxed) { 637 | format!(" Scanning {} ", self.spinner.draw()) 638 | } else { 639 | String::from(" Discovered devices ") 640 | } 641 | }) 642 | .title_style({ 643 | if self.focused_block == FocusedBlock::NewDevices { 644 | Style::default().bold() 645 | } else { 646 | Style::default() 647 | } 648 | }) 649 | .borders(Borders::ALL) 650 | .border_style({ 651 | if self.focused_block == FocusedBlock::NewDevices { 652 | Style::default().fg(Color::Green) 653 | } else { 654 | Style::default() 655 | } 656 | }) 657 | .border_type({ 658 | if self.focused_block == FocusedBlock::NewDevices { 659 | BorderType::Thick 660 | } else { 661 | BorderType::default() 662 | } 663 | }), 664 | ) 665 | .flex(self.config.layout) 666 | .row_highlight_style(if self.focused_block == FocusedBlock::NewDevices { 667 | Style::default().bg(Color::DarkGray).fg(Color::White) 668 | } else { 669 | Style::default() 670 | }); 671 | 672 | let mut state = self.new_devices_state.clone(); 673 | if self.focused_block == FocusedBlock::NewDevices && state.selected().is_none() { 674 | state.select(Some(0)); 675 | } 676 | 677 | frame.render_stateful_widget(new_devices_table, new_devices_block, &mut state); 678 | 679 | if rows_len > new_devices_block.height.saturating_sub(4) as usize { 680 | let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight) 681 | .begin_symbol(Some("↑")) 682 | .end_symbol(Some("↓")); 683 | let mut scrollbar_state = ScrollbarState::new(rows_len) 684 | .position(state.selected().unwrap_or_default()); 685 | frame.render_stateful_widget( 686 | scrollbar, 687 | new_devices_block.inner(Margin { 688 | vertical: 1, 689 | horizontal: 0, 690 | }), 691 | &mut scrollbar_state, 692 | ); 693 | } 694 | } 695 | 696 | // 697 | let area = self.area(frame); 698 | 699 | // Help 700 | Help::render( 701 | frame, 702 | area, 703 | self.focused_block, 704 | help_block, 705 | self.config.clone(), 706 | ); 707 | 708 | // Pairing confirmation 709 | 710 | // Set alias popup 711 | if self.focused_block == FocusedBlock::SetDeviceAliasBox { 712 | self.render_set_alias(frame, area); 713 | } 714 | 715 | // Request Confirmation 716 | if let Some(req) = &self.requests.confirmation { 717 | req.render(frame, area); 718 | } 719 | 720 | // Request to enter pin code 721 | 722 | if let Some(req) = &self.requests.enter_pin_code { 723 | req.render(frame, area); 724 | } 725 | 726 | // Request passkey 727 | if let Some(req) = &self.requests.enter_passkey { 728 | req.render(frame, area); 729 | } 730 | 731 | // Display Pin Code 732 | if let Some(req) = &self.requests.display_pin_code { 733 | req.render(frame, area); 734 | } 735 | 736 | // Display Passkey 737 | if let Some(req) = &self.requests.display_passkey { 738 | req.render(frame, area); 739 | } 740 | } 741 | } 742 | 743 | pub async fn tick(&mut self) -> AppResult<()> { 744 | self.notifications.retain(|n| n.ttl > 0); 745 | self.notifications.iter_mut().for_each(|n| n.ttl -= 1); 746 | 747 | if self.spinner.active { 748 | self.spinner.update(); 749 | } 750 | self.refresh().await?; 751 | Ok(()) 752 | } 753 | 754 | pub async fn refresh(&mut self) -> AppResult<()> { 755 | let refreshed_controllers = 756 | Controller::get_all(self.session.clone(), &self.favorite_devices).await?; 757 | 758 | // Remove unplugged adapters in a single pass 759 | let mut adapter_removed = false; 760 | self.controllers.retain(|controller| { 761 | let should_retain = refreshed_controllers 762 | .iter() 763 | .any(|c| c.name == controller.name); 764 | 765 | if !should_retain { 766 | adapter_removed = true; 767 | } 768 | 769 | should_retain 770 | }); 771 | 772 | // Update selection after removal 773 | if adapter_removed { 774 | if !self.controllers.is_empty() { 775 | let i = match self.controller_state.selected() { 776 | Some(i) => { 777 | if i > 0 { 778 | (i - 1).min(self.controllers.len() - 1) 779 | } else { 780 | 0 781 | } 782 | } 783 | None => 0, 784 | }; 785 | self.controller_state.select(Some(i)); 786 | } else { 787 | self.controller_state.select(None); 788 | } 789 | } 790 | 791 | for refreshed_controller in refreshed_controllers { 792 | if let Some(controller) = self 793 | .controllers 794 | .iter_mut() 795 | .find(|c| c.name == refreshed_controller.name) 796 | { 797 | // Prepare to check if the paired devices list is shrinking 798 | let old_paired_count = controller.paired_devices.len(); 799 | let new_paired_count = refreshed_controller.paired_devices.len(); 800 | 801 | // Update existing adapters 802 | controller.alias = refreshed_controller.alias; 803 | controller.is_powered = refreshed_controller.is_powered; 804 | controller.is_pairable = refreshed_controller.is_pairable; 805 | controller.is_discoverable = refreshed_controller.is_discoverable; 806 | controller.paired_devices = refreshed_controller.paired_devices; 807 | controller.new_devices = refreshed_controller.new_devices; 808 | 809 | // Update selection if paired devices list shrank 810 | if new_paired_count < old_paired_count 811 | && let Some(selected_index) = self.paired_devices_state.selected() 812 | { 813 | // Check if selected index is now out of bounds and update the index if required 814 | if new_paired_count == 0 { 815 | self.paired_devices_state.select(None); 816 | } else if selected_index >= new_paired_count && new_paired_count > 0 { 817 | self.paired_devices_state 818 | .select(Some(new_paired_count.saturating_sub(1))); 819 | } 820 | } 821 | } else { 822 | // Add new detected adapters 823 | self.controllers.push(refreshed_controller); 824 | } 825 | } 826 | 827 | Ok(()) 828 | } 829 | 830 | pub fn quit(&mut self) { 831 | // TODO: use env_logger error!() 832 | let _ = save_favorite_devices_to_disk(&self.favorite_devices); 833 | self.running = false; 834 | } 835 | } 836 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /src/handler.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | use std::sync::atomic::Ordering; 3 | 4 | use crate::app::FocusedBlock; 5 | use crate::app::{App, AppResult}; 6 | use crate::config::Config; 7 | use crate::event::Event; 8 | use crate::notification::{Notification, NotificationLevel}; 9 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; 10 | use futures::StreamExt; 11 | use tokio::sync::mpsc::UnboundedSender; 12 | 13 | use tui_input::backend::crossterm::EventHandler; 14 | 15 | async fn toggle_connect(app: &mut App, sender: UnboundedSender) { 16 | if let Some(selected_controller) = app.controller_state.selected() { 17 | let controller = &app.controllers[selected_controller]; 18 | if let Some(index) = app.paired_devices_state.selected() { 19 | let addr = controller.paired_devices[index].addr; 20 | match controller.adapter.device(addr) { 21 | Ok(device) => { 22 | tokio::spawn(async move { 23 | match device.is_connected().await { 24 | Ok(is_connected) => { 25 | if is_connected { 26 | match device.disconnect().await { 27 | Ok(_) => { 28 | let _ = Notification::send( 29 | "Device disconnected".into(), 30 | NotificationLevel::Info, 31 | sender.clone(), 32 | ); 33 | } 34 | Err(e) => { 35 | let _ = Notification::send( 36 | e.into(), 37 | NotificationLevel::Error, 38 | sender.clone(), 39 | ); 40 | } 41 | } 42 | } else { 43 | match device.connect().await { 44 | Ok(_) => { 45 | let _ = Notification::send( 46 | "Device connected".into(), 47 | NotificationLevel::Info, 48 | sender.clone(), 49 | ); 50 | } 51 | Err(e) => { 52 | let _ = Notification::send( 53 | e.into(), 54 | NotificationLevel::Error, 55 | sender.clone(), 56 | ); 57 | } 58 | } 59 | } 60 | } 61 | Err(e) => { 62 | let _ = Notification::send( 63 | e.into(), 64 | NotificationLevel::Error, 65 | sender.clone(), 66 | ); 67 | } 68 | } 69 | }); 70 | } 71 | Err(e) => { 72 | let _ = Notification::send(e.into(), NotificationLevel::Error, sender.clone()); 73 | } 74 | } 75 | } 76 | } 77 | } 78 | 79 | async fn pair(app: &mut App, sender: UnboundedSender) { 80 | if let Some(selected_controller) = app.controller_state.selected() { 81 | let controller = &app.controllers[selected_controller]; 82 | if let Some(index) = app.new_devices_state.selected() { 83 | let addr = controller.new_devices[index].addr; 84 | match controller.adapter.device(addr) { 85 | Ok(device) => match device.alias().await { 86 | Ok(device_name) => { 87 | let _ = Notification::send( 88 | format!("Start pairing with the device {device_name}").into(), 89 | NotificationLevel::Info, 90 | sender.clone(), 91 | ); 92 | 93 | tokio::spawn(async move { 94 | match device.pair().await { 95 | Ok(_) => { 96 | let _ = Notification::send( 97 | "Device paired".into(), 98 | NotificationLevel::Info, 99 | sender.clone(), 100 | ); 101 | 102 | let _ = sender.send(Event::NewPairedDevice(device.address())); 103 | match device.set_trusted(true).await { 104 | Ok(_) => { 105 | let _ = Notification::send( 106 | "Device trusted".into(), 107 | NotificationLevel::Info, 108 | sender.clone(), 109 | ); 110 | } 111 | Err(e) => { 112 | let _ = Notification::send( 113 | e.into(), 114 | NotificationLevel::Error, 115 | sender.clone(), 116 | ); 117 | } 118 | }; 119 | match device.connect().await { 120 | Ok(_) => { 121 | let _ = Notification::send( 122 | "Device connected".into(), 123 | NotificationLevel::Info, 124 | sender.clone(), 125 | ); 126 | } 127 | Err(e) => { 128 | let _ = Notification::send( 129 | e.into(), 130 | NotificationLevel::Error, 131 | sender.clone(), 132 | ); 133 | } 134 | }; 135 | } 136 | Err(e) => { 137 | let _ = Notification::send( 138 | e.into(), 139 | NotificationLevel::Error, 140 | sender.clone(), 141 | ); 142 | let _ = sender.send(Event::FailedPairing(device.address())); 143 | } 144 | } 145 | }); 146 | } 147 | Err(e) => { 148 | let _ = 149 | Notification::send(e.into(), NotificationLevel::Error, sender.clone()); 150 | } 151 | }, 152 | Err(e) => { 153 | let _ = Notification::send(e.into(), NotificationLevel::Error, sender.clone()); 154 | } 155 | } 156 | } 157 | } 158 | } 159 | 160 | pub async fn handle_key_events( 161 | key_event: KeyEvent, 162 | app: &mut App, 163 | sender: UnboundedSender, 164 | config: Arc, 165 | ) -> AppResult<()> { 166 | match app.focused_block { 167 | FocusedBlock::SetDeviceAliasBox => match key_event.code { 168 | KeyCode::Enter => { 169 | if let Some(selected_controller) = app.controller_state.selected() { 170 | let controller = &app.controllers[selected_controller]; 171 | if let Some(index) = app.paired_devices_state.selected() { 172 | let device = &controller.paired_devices[index]; 173 | match device.set_alias(app.new_alias.value().into()).await { 174 | Ok(_) => { 175 | Notification::send( 176 | "Set New Alias".into(), 177 | NotificationLevel::Info, 178 | sender, 179 | )?; 180 | } 181 | Err(e) => { 182 | Notification::send(e.into(), NotificationLevel::Error, sender)?; 183 | } 184 | } 185 | app.focused_block = FocusedBlock::PairedDevices; 186 | app.new_alias.reset(); 187 | } 188 | } 189 | } 190 | 191 | KeyCode::Esc => { 192 | app.focused_block = FocusedBlock::PairedDevices; 193 | app.new_alias.reset(); 194 | } 195 | _ => { 196 | app.new_alias 197 | .handle_event(&crossterm::event::Event::Key(key_event)); 198 | } 199 | }, 200 | FocusedBlock::RequestConfirmation => match key_event.code { 201 | KeyCode::Tab => { 202 | if let Some(confirmation) = &mut app.requests.confirmation { 203 | confirmation.toggle_select(); 204 | } 205 | } 206 | KeyCode::Esc => { 207 | if let Some(confirmation) = &mut app.requests.confirmation { 208 | confirmation.cancel(&app.auth_agent).await?; 209 | } 210 | } 211 | KeyCode::Enter => { 212 | if let Some(confirmation) = &mut app.requests.confirmation { 213 | confirmation.submit(&app.auth_agent).await?; 214 | } 215 | } 216 | 217 | _ => {} 218 | }, 219 | FocusedBlock::EnterPinCode => { 220 | if let Some(req) = &mut app.requests.enter_pin_code { 221 | match key_event.code { 222 | KeyCode::Esc => { 223 | req.cancel(&app.auth_agent).await?; 224 | } 225 | 226 | _ => { 227 | req.handle_key_events(key_event, &app.auth_agent).await?; 228 | } 229 | } 230 | } 231 | } 232 | FocusedBlock::EnterPasskey => { 233 | if let Some(req) = &mut app.requests.enter_passkey { 234 | match key_event.code { 235 | KeyCode::Esc => { 236 | req.cancel(&app.auth_agent).await?; 237 | } 238 | 239 | _ => { 240 | req.handle_key_events(key_event, &app.auth_agent).await?; 241 | } 242 | } 243 | } 244 | } 245 | FocusedBlock::DisplayPinCode => { 246 | if let Some(req) = &mut app.requests.display_pin_code 247 | && let KeyCode::Esc | KeyCode::Enter = key_event.code 248 | { 249 | req.submit(&app.auth_agent).await?; 250 | } 251 | } 252 | FocusedBlock::DisplayPasskey => { 253 | if let Some(req) = &mut app.requests.display_passkey 254 | && key_event.code == KeyCode::Esc 255 | { 256 | req.cancel(&app.auth_agent).await?; 257 | } 258 | } 259 | 260 | _ => { 261 | match key_event.code { 262 | // Exit the app 263 | KeyCode::Char('c') if key_event.modifiers == KeyModifiers::CONTROL => { 264 | app.quit(); 265 | } 266 | 267 | KeyCode::Char('q') => { 268 | app.quit(); 269 | } 270 | 271 | KeyCode::Esc if app.config.esc_quit => { 272 | app.quit(); 273 | } 274 | 275 | // Switch focus 276 | KeyCode::Tab | KeyCode::Char('l') => match app.focused_block { 277 | FocusedBlock::Adapter => { 278 | app.focused_block = FocusedBlock::PairedDevices; 279 | app.reset_devices_state(); 280 | } 281 | FocusedBlock::PairedDevices => { 282 | if let Some(selected_controller) = app.controller_state.selected() { 283 | let controller = &app.controllers[selected_controller]; 284 | if controller.is_scanning.load(Ordering::Relaxed) { 285 | app.focused_block = FocusedBlock::NewDevices; 286 | } else { 287 | app.focused_block = FocusedBlock::Adapter; 288 | } 289 | } 290 | } 291 | FocusedBlock::NewDevices => { 292 | app.focused_block = FocusedBlock::Adapter; 293 | app.new_devices_state.select(None); 294 | } 295 | _ => {} 296 | }, 297 | 298 | KeyCode::BackTab | KeyCode::Char('h') => match app.focused_block { 299 | FocusedBlock::Adapter => { 300 | if let Some(selected_controller) = app.controller_state.selected() { 301 | let controller = &app.controllers[selected_controller]; 302 | if controller.is_scanning.load(Ordering::Relaxed) { 303 | app.focused_block = FocusedBlock::NewDevices; 304 | } else { 305 | app.focused_block = FocusedBlock::PairedDevices; 306 | } 307 | app.reset_devices_state(); 308 | } 309 | } 310 | FocusedBlock::PairedDevices => { 311 | app.focused_block = FocusedBlock::Adapter; 312 | app.paired_devices_state.select(None); 313 | } 314 | FocusedBlock::NewDevices => { 315 | app.focused_block = FocusedBlock::PairedDevices; 316 | app.new_devices_state.select(None); 317 | } 318 | _ => {} 319 | }, 320 | 321 | // scroll down 322 | KeyCode::Char('j') | KeyCode::Down => match app.focused_block { 323 | FocusedBlock::Adapter => { 324 | if !app.controllers.is_empty() { 325 | let i = match app.controller_state.selected() { 326 | Some(i) => { 327 | if i < app.controllers.len() - 1 { 328 | i + 1 329 | } else { 330 | i 331 | } 332 | } 333 | None => 0, 334 | }; 335 | 336 | app.controller_state.select(Some(i)); 337 | } 338 | } 339 | 340 | FocusedBlock::PairedDevices => { 341 | if let Some(selected_controller) = app.controller_state.selected() { 342 | let controller = &mut app.controllers[selected_controller]; 343 | 344 | if !controller.paired_devices.is_empty() { 345 | let i = match app.paired_devices_state.selected() { 346 | Some(i) => { 347 | if i < controller.paired_devices.len() - 1 { 348 | i + 1 349 | } else { 350 | i 351 | } 352 | } 353 | None => 0, 354 | }; 355 | 356 | app.paired_devices_state.select(Some(i)); 357 | } 358 | } 359 | } 360 | 361 | FocusedBlock::NewDevices => { 362 | if let Some(selected_controller) = app.controller_state.selected() { 363 | let controller = &mut app.controllers[selected_controller]; 364 | 365 | if !controller.new_devices.is_empty() { 366 | let i = match app.new_devices_state.selected() { 367 | Some(i) => { 368 | if i < controller.new_devices.len() - 1 { 369 | i + 1 370 | } else { 371 | i 372 | } 373 | } 374 | None => 0, 375 | }; 376 | 377 | app.new_devices_state.select(Some(i)); 378 | } 379 | } 380 | } 381 | 382 | _ => {} 383 | }, 384 | 385 | // scroll up 386 | KeyCode::Char('k') | KeyCode::Up => match app.focused_block { 387 | FocusedBlock::Adapter => { 388 | if !app.controllers.is_empty() { 389 | let i = match app.controller_state.selected() { 390 | Some(i) => i.saturating_sub(1), 391 | None => 0, 392 | }; 393 | 394 | app.controller_state.select(Some(i)); 395 | } 396 | } 397 | 398 | FocusedBlock::PairedDevices => { 399 | if let Some(selected_controller) = app.controller_state.selected() { 400 | let controller = &mut app.controllers[selected_controller]; 401 | if !controller.paired_devices.is_empty() { 402 | let i = match app.paired_devices_state.selected() { 403 | Some(i) => i.saturating_sub(1), 404 | None => 0, 405 | }; 406 | app.paired_devices_state.select(Some(i)); 407 | } 408 | } 409 | } 410 | 411 | FocusedBlock::NewDevices => { 412 | if let Some(selected_controller) = app.controller_state.selected() { 413 | let controller = &mut app.controllers[selected_controller]; 414 | if !controller.new_devices.is_empty() { 415 | let i = match app.new_devices_state.selected() { 416 | Some(i) => i.saturating_sub(1), 417 | None => 0, 418 | }; 419 | app.new_devices_state.select(Some(i)); 420 | } 421 | } 422 | } 423 | _ => {} 424 | }, 425 | 426 | // Start/Stop Scan 427 | KeyCode::Char(c) if c == config.toggle_scanning => { 428 | if let Some(selected_controller) = app.controller_state.selected() { 429 | let controller = &app.controllers[selected_controller]; 430 | 431 | if controller.is_scanning.load(Ordering::Relaxed) { 432 | controller 433 | .is_scanning 434 | .store(false, std::sync::atomic::Ordering::Relaxed); 435 | 436 | Notification::send( 437 | "Scanning stopped".into(), 438 | NotificationLevel::Info, 439 | sender, 440 | )?; 441 | 442 | app.spinner.active = false; 443 | } else { 444 | controller 445 | .is_scanning 446 | .store(true, std::sync::atomic::Ordering::Relaxed); 447 | app.spinner.active = true; 448 | let adapter = controller.adapter.clone(); 449 | let is_scanning = controller.is_scanning.clone(); 450 | tokio::spawn(async move { 451 | let _ = Notification::send( 452 | "Scanning started".into(), 453 | NotificationLevel::Info, 454 | sender.clone(), 455 | ); 456 | 457 | match adapter.discover_devices().await { 458 | Ok(mut discover) => { 459 | while let Some(_evt) = discover.next().await { 460 | if !is_scanning.load(Ordering::Relaxed) { 461 | break; 462 | } 463 | } 464 | } 465 | Err(e) => { 466 | let _ = Notification::send( 467 | e.into(), 468 | NotificationLevel::Error, 469 | sender.clone(), 470 | ); 471 | } 472 | } 473 | }); 474 | } 475 | } 476 | } 477 | 478 | _ => { 479 | match app.focused_block { 480 | FocusedBlock::PairedDevices => { 481 | match key_event.code { 482 | // Unpair 483 | KeyCode::Char(c) if c == config.paired_device.unpair => { 484 | if let Some(selected_controller) = 485 | app.controller_state.selected() 486 | { 487 | let controller = &app.controllers[selected_controller]; 488 | if let Some(index) = app.paired_devices_state.selected() { 489 | let addr = controller.paired_devices[index].addr; 490 | match controller.adapter.remove_device(addr).await { 491 | Ok(_) => { 492 | let _ = Notification::send( 493 | "Device unpaired".into(), 494 | NotificationLevel::Info, 495 | sender.clone(), 496 | ); 497 | } 498 | Err(e) => { 499 | let _ = Notification::send( 500 | e.into(), 501 | NotificationLevel::Error, 502 | sender.clone(), 503 | ); 504 | } 505 | } 506 | } 507 | } 508 | } 509 | 510 | // Connect / Disconnect 511 | KeyCode::Enter => toggle_connect(app, sender).await, 512 | KeyCode::Char(' ') => toggle_connect(app, sender).await, 513 | 514 | // Trust / Untrust 515 | KeyCode::Char(c) if c == config.paired_device.toggle_trust => { 516 | if let Some(selected_controller) = 517 | app.controller_state.selected() 518 | { 519 | let controller = &app.controllers[selected_controller]; 520 | if let Some(index) = app.paired_devices_state.selected() { 521 | let addr = controller.paired_devices[index].addr; 522 | match controller.adapter.device(addr) { 523 | Ok(device) => { 524 | tokio::spawn(async move { 525 | match device.is_trusted().await { 526 | Ok(is_trusted) => { 527 | if is_trusted { 528 | match device 529 | .set_trusted(false) 530 | .await 531 | { 532 | Ok(_) => { 533 | let _ = Notification::send( 534 | "Device untrusted" 535 | .into(), 536 | NotificationLevel::Info, 537 | sender.clone(), 538 | ); 539 | } 540 | Err(e) => { 541 | let _ = Notification::send( 542 | e.into(), 543 | NotificationLevel::Error, 544 | sender.clone(), 545 | ); 546 | } 547 | } 548 | } else { 549 | match device 550 | .set_trusted(true) 551 | .await 552 | { 553 | Ok(_) => { 554 | let _ = Notification::send( 555 | "Device trusted" 556 | .into(), 557 | NotificationLevel::Info, 558 | sender.clone(), 559 | ); 560 | } 561 | 562 | Err(e) => { 563 | let _ = Notification::send( 564 | e.into(), 565 | NotificationLevel::Error, 566 | sender.clone(), 567 | ); 568 | } 569 | } 570 | } 571 | } 572 | Err(e) => { 573 | let _ = Notification::send( 574 | e.into(), 575 | NotificationLevel::Error, 576 | sender.clone(), 577 | ); 578 | } 579 | } 580 | }); 581 | } 582 | Err(e) => { 583 | let _ = Notification::send( 584 | e.into(), 585 | NotificationLevel::Error, 586 | sender.clone(), 587 | ); 588 | } 589 | } 590 | } 591 | } 592 | } 593 | 594 | // Favorite / Unfavorite 595 | KeyCode::Char(c) if c == config.paired_device.toggle_favorite => { 596 | if let Some(selected_controller) = 597 | app.controller_state.selected() 598 | { 599 | let controller = &app.controllers[selected_controller]; 600 | if let Some(index) = app.paired_devices_state.selected() { 601 | let address = controller.paired_devices[index].addr; 602 | let _ = sender.send(Event::ToggleFavorite(address)); 603 | } 604 | } 605 | } 606 | 607 | KeyCode::Char(c) if c == config.paired_device.rename => { 608 | app.focused_block = FocusedBlock::SetDeviceAliasBox; 609 | } 610 | 611 | _ => {} 612 | } 613 | } 614 | 615 | FocusedBlock::Adapter => { 616 | match key_event.code { 617 | // toggle pairing 618 | KeyCode::Char(c) if c == config.adapter.toggle_pairing => { 619 | if let Some(selected_controller) = 620 | app.controller_state.selected() 621 | { 622 | let adapter = &app.controllers[selected_controller].adapter; 623 | tokio::spawn({ 624 | let adapter = adapter.clone(); 625 | async move { 626 | match adapter.is_pairable().await { 627 | Ok(is_pairable) => { 628 | if is_pairable { 629 | match adapter.set_pairable(false).await 630 | { 631 | Ok(_) => { 632 | let _ = Notification::send( 633 | "Adapter unpairable".into(), 634 | NotificationLevel::Info, 635 | sender.clone(), 636 | ); 637 | } 638 | Err(e) => { 639 | let _ = Notification::send( 640 | e.into(), 641 | NotificationLevel::Error, 642 | sender.clone(), 643 | ); 644 | } 645 | } 646 | } else { 647 | match adapter.set_pairable(true).await { 648 | Ok(_) => { 649 | let _ = Notification::send( 650 | "Adapter pairable".into(), 651 | NotificationLevel::Info, 652 | sender.clone(), 653 | ); 654 | } 655 | Err(e) => { 656 | let _ = Notification::send( 657 | e.into(), 658 | NotificationLevel::Error, 659 | sender.clone(), 660 | ); 661 | } 662 | } 663 | } 664 | } 665 | Err(e) => { 666 | let _ = Notification::send( 667 | e.into(), 668 | NotificationLevel::Error, 669 | sender.clone(), 670 | ); 671 | } 672 | } 673 | } 674 | }); 675 | } 676 | } 677 | 678 | // toggle power 679 | KeyCode::Char(c) if c == config.adapter.toggle_power => { 680 | if let Some(selected_controller) = 681 | app.controller_state.selected() 682 | { 683 | let adapter = &app.controllers[selected_controller].adapter; 684 | tokio::spawn({ 685 | let adapter = adapter.clone(); 686 | async move { 687 | match adapter.is_powered().await { 688 | Ok(is_powered) => { 689 | if is_powered { 690 | match adapter.set_powered(false).await { 691 | Ok(_) => { 692 | let _ = Notification::send( 693 | "Adapter powered off" 694 | .into(), 695 | NotificationLevel::Info, 696 | sender.clone(), 697 | ); 698 | } 699 | Err(e) => { 700 | let _ = Notification::send( 701 | e.into(), 702 | NotificationLevel::Error, 703 | sender.clone(), 704 | ); 705 | } 706 | } 707 | } else { 708 | match adapter.set_powered(true).await { 709 | Ok(_) => { 710 | let _ = Notification::send( 711 | "Adapter powered on".into(), 712 | NotificationLevel::Info, 713 | sender.clone(), 714 | ); 715 | } 716 | Err(e) => { 717 | let _ = Notification::send( 718 | e.into(), 719 | NotificationLevel::Error, 720 | sender.clone(), 721 | ); 722 | } 723 | } 724 | } 725 | } 726 | Err(e) => { 727 | let _ = Notification::send( 728 | e.into(), 729 | NotificationLevel::Error, 730 | sender.clone(), 731 | ); 732 | } 733 | } 734 | } 735 | }); 736 | } 737 | } 738 | 739 | // toggle discovery 740 | KeyCode::Char(c) if c == config.adapter.toggle_discovery => { 741 | if let Some(selected_controller) = 742 | app.controller_state.selected() 743 | { 744 | let adapter = &app.controllers[selected_controller].adapter; 745 | tokio::spawn({ 746 | let adapter = adapter.clone(); 747 | async move { 748 | match adapter.is_discoverable().await { 749 | Ok(is_discoverable) => { 750 | if is_discoverable { 751 | match adapter 752 | .set_discoverable(false) 753 | .await 754 | { 755 | Ok(_) => { 756 | let _ = Notification::send( 757 | "Adapter undiscoverable" 758 | .into(), 759 | NotificationLevel::Info, 760 | sender.clone(), 761 | ); 762 | } 763 | Err(e) => { 764 | let _ = Notification::send( 765 | e.into(), 766 | NotificationLevel::Error, 767 | sender.clone(), 768 | ); 769 | } 770 | } 771 | } else { 772 | match adapter 773 | .set_discoverable(true) 774 | .await 775 | { 776 | Ok(_) => { 777 | let _ = Notification::send( 778 | "Adapter discoverable" 779 | .into(), 780 | NotificationLevel::Info, 781 | sender.clone(), 782 | ); 783 | } 784 | Err(e) => { 785 | let _ = Notification::send( 786 | e.into(), 787 | NotificationLevel::Error, 788 | sender.clone(), 789 | ); 790 | } 791 | } 792 | } 793 | } 794 | Err(e) => { 795 | let _ = Notification::send( 796 | e.into(), 797 | NotificationLevel::Error, 798 | sender.clone(), 799 | ); 800 | } 801 | } 802 | } 803 | }); 804 | } 805 | } 806 | 807 | _ => {} 808 | } 809 | } 810 | 811 | FocusedBlock::NewDevices => { 812 | // Pair new device 813 | match key_event.code { 814 | KeyCode::Enter => pair(app, sender).await, 815 | KeyCode::Char(' ') => pair(app, sender).await, 816 | _ => {} 817 | } 818 | } 819 | 820 | _ => {} 821 | } 822 | } 823 | } 824 | } 825 | } 826 | 827 | Ok(()) 828 | } 829 | --------------------------------------------------------------------------------