Skip to content

Commit

Permalink
chore: add docs
Browse files Browse the repository at this point in the history
  • Loading branch information
cyrinux committed Jul 26, 2024
1 parent cf8b7ac commit 7211932
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/bluetooth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ use regex::Regex;
use std::error::Error;
use std::process::Output;

/// Represents actions that can be performed on Bluetooth devices.
#[derive(Debug)]
pub enum BluetoothAction {
ToggleConnect(String),
}

/// Retrieves a list of paired Bluetooth devices and their connection status.
pub fn get_paired_bluetooth_devices(
command_runner: &dyn CommandRunner,
) -> Result<Vec<BluetoothAction>, Box<dyn Error>> {
Expand All @@ -23,6 +25,7 @@ pub fn get_paired_bluetooth_devices(
}
}

/// Parses the output of `bluetoothctl devices` command to retrieve a list of Bluetooth devices.
fn parse_bluetooth_devices(
output: &Output,
connected_devices: &[String],
Expand All @@ -35,6 +38,7 @@ fn parse_bluetooth_devices(
Ok(devices)
}

/// Parses a line of Bluetooth device information and returns a `BluetoothAction` if valid.
fn parse_bluetooth_device(line: String, connected_devices: &[String]) -> Option<BluetoothAction> {
// Define a regex pattern for matching MAC addresses and device names
// Check if the line matches the pattern and extract captures
Expand Down Expand Up @@ -63,6 +67,7 @@ fn parse_bluetooth_device(line: String, connected_devices: &[String]) -> Option<
})
}

/// Handles a Bluetooth action, such as connecting or disconnecting a device.
pub fn handle_bluetooth_action(
action: &BluetoothAction,
connected_devices: &[String],
Expand All @@ -75,6 +80,7 @@ pub fn handle_bluetooth_action(
}
}

/// Connects or disconnects a Bluetooth device based on its current status.
fn connect_to_bluetooth_device(
device: &str,
connected_devices: &[String],
Expand All @@ -101,6 +107,7 @@ fn connect_to_bluetooth_device(
}
}

/// Extracts the MAC address from the given device string.
fn extract_device_address(device: &str) -> Option<String> {
Regex::new(r"([0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2}){5})$")
.ok()?
Expand All @@ -109,6 +116,7 @@ fn extract_device_address(device: &str) -> Option<String> {
.map(|m| m.as_str().to_string())
}

/// Retrieves a list of currently connected Bluetooth devices.
pub fn get_connected_devices(
command_runner: &dyn CommandRunner,
) -> Result<Vec<String>, Box<dyn Error>> {
Expand Down
6 changes: 6 additions & 0 deletions src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ use std::error::Error;
use std::io::{BufRead, BufReader};
use std::process::{Command, Output, Stdio};

/// Trait for running shell commands.
pub trait CommandRunner {
/// Runs a shell command with the specified arguments.
fn run_command(&self, command: &str, args: &[&str]) -> Result<Output, std::io::Error>;
}

/// Struct for running real shell commands.
pub struct RealCommandRunner;

impl CommandRunner for RealCommandRunner {
Expand All @@ -14,16 +17,19 @@ impl CommandRunner for RealCommandRunner {
}
}

/// Checks if a command is installed on the system.
pub fn is_command_installed(cmd: &str) -> bool {
which::which(cmd).is_ok()
}

/// Reads the output of a command and returns it as a vector of lines.
pub fn read_output_lines(output: &Output) -> Result<Vec<String>, Box<dyn Error>> {
Ok(BufReader::new(output.stdout.as_slice())
.lines()
.collect::<Result<Vec<String>, _>>()?)
}

/// Executes a command and returns whether it was successful.
pub fn execute_command(command: &str, args: &[&str]) -> bool {
Command::new(command)
.args(args)
Expand Down
8 changes: 8 additions & 0 deletions src/iwd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use regex::Regex;
use std::error::Error;
use std::io::{BufRead, BufReader};

/// Retrieves available Wi-Fi networks using IWD.
pub fn get_iwd_networks(
interface: &str,
command_runner: &dyn CommandRunner,
Expand All @@ -31,6 +32,7 @@ pub fn get_iwd_networks(
Ok(actions)
}

/// Fetches raw Wi-Fi network data from IWD.
fn fetch_iwd_networks(
interface: &str,
command_runner: &dyn CommandRunner,
Expand All @@ -50,6 +52,7 @@ fn fetch_iwd_networks(
}
}

/// Parses the raw Wi-Fi network data into a structured format.
fn parse_iwd_networks(
actions: &mut Vec<WifiAction>,
networks: Vec<String>,
Expand Down Expand Up @@ -78,6 +81,7 @@ fn parse_iwd_networks(
Ok(())
}

/// Connects to a Wi-Fi network using IWD.
pub fn connect_to_iwd_wifi(
interface: &str,
action: &str,
Expand All @@ -96,6 +100,7 @@ pub fn connect_to_iwd_wifi(
}
}

/// Attempts to connect to a Wi-Fi network, optionally using a password.
fn attempt_connection(
interface: &str,
ssid: &str,
Expand All @@ -121,6 +126,7 @@ fn attempt_connection(
}
}

/// Disconnects from a Wi-Fi network.
pub fn disconnect_iwd_wifi(
interface: &str,
command_runner: &dyn CommandRunner,
Expand All @@ -131,6 +137,7 @@ pub fn disconnect_iwd_wifi(
Ok(status.success())
}

/// Checks if IWD is currently connected to a network.
pub fn is_iwd_connected(
command_runner: &dyn CommandRunner,
interface: &str,
Expand All @@ -146,6 +153,7 @@ pub fn is_iwd_connected(
Ok(false)
}

/// Checks if a Wi-Fi network is known (i.e., previously connected).
pub fn is_known_network(
ssid: &str,
command_runner: &dyn CommandRunner,
Expand Down
19 changes: 19 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use tailscale::{
is_tailscale_enabled, TailscaleAction,
};

/// Command-line arguments structure for the application.
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
Expand All @@ -42,6 +43,7 @@ struct Args {
no_tailscale: bool,
}

/// Configuration structure for the application.
#[derive(Debug, Deserialize, Serialize)]
struct Config {
#[serde(default)]
Expand All @@ -50,12 +52,14 @@ struct Config {
dmenu_args: String,
}

/// Custom action structure for user-defined actions.
#[derive(Debug, Deserialize, Serialize)]
struct CustomAction {
display: String,
cmd: String,
}

/// Enum representing different types of actions that can be performed.
#[derive(Debug)]
enum ActionType {
Bluetooth(BluetoothAction),
Expand All @@ -65,20 +69,23 @@ enum ActionType {
Wifi(WifiAction),
}

/// Enum representing system-related actions.
#[derive(Debug)]
enum SystemAction {
EditConnections,
RfkillBlock,
RfkillUnblock,
}

/// Enum representing Wi-Fi-related actions.
#[derive(Debug)]
enum WifiAction {
Connect,
Disconnect,
Network(String),
}

/// Formats an entry for display in the menu.
pub fn format_entry(action: &str, icon: &str, text: &str) -> String {
if icon.is_empty() {
format!("{action:<10}- {text}")
Expand All @@ -87,6 +94,7 @@ pub fn format_entry(action: &str, icon: &str, text: &str) -> String {
}
}

/// Returns the default configuration as a string.
fn get_default_config() -> &'static str {
r#"
dmenu_cmd = "dmenu"
Expand All @@ -98,6 +106,7 @@ cmd = "notify-send 'hello' 'world'"
"#
}

/// Main function for the application.
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let args = Args::parse();
Expand Down Expand Up @@ -256,11 +265,13 @@ async fn main() -> Result<(), Box<dyn Error>> {
Ok(())
}

/// Gets the configuration file path.
fn get_config_path() -> Result<PathBuf, Box<dyn Error>> {
let config_dir = config_dir().ok_or("Failed to find config directory")?;
Ok(config_dir.join("network-dmenu").join("config.toml"))
}

/// Creates a default configuration file if it doesn't exist.
fn create_default_config_if_missing() -> Result<(), Box<dyn Error>> {
let config_path = get_config_path()?;

Expand All @@ -274,13 +285,15 @@ fn create_default_config_if_missing() -> Result<(), Box<dyn Error>> {
Ok(())
}

/// Reads and returns the configuration.
fn get_config() -> Result<Config, Box<dyn Error>> {
let config_path = get_config_path()?;
let config_content = fs::read_to_string(config_path)?;
let config = toml::from_str(&config_content)?;
Ok(config)
}

/// Retrieves the list of actions based on the command-line arguments and configuration.
fn get_actions(
args: &Args,
command_runner: &dyn CommandRunner,
Expand Down Expand Up @@ -360,11 +373,13 @@ fn get_actions(
Ok(actions)
}

/// Handles a custom action by executing its command.
fn handle_custom_action(action: &CustomAction) -> Result<bool, Box<dyn Error>> {
let status = Command::new("sh").arg("-c").arg(&action.cmd).status()?;
Ok(status.success())
}

/// Handles a system action.
fn handle_system_action(action: &SystemAction) -> Result<bool, Box<dyn Error>> {
match action {
SystemAction::RfkillBlock => {
Expand All @@ -382,6 +397,7 @@ fn handle_system_action(action: &SystemAction) -> Result<bool, Box<dyn Error>> {
}
}

/// Parses a Wi-Fi action string to extract the SSID and security type.
fn parse_wifi_action(action: &str) -> Result<(&str, &str), Box<dyn Error>> {
let emoji_pos = action
.char_indices()
Expand All @@ -402,6 +418,7 @@ fn parse_wifi_action(action: &str) -> Result<(&str, &str), Box<dyn Error>> {
Ok((ssid, security))
}

/// Handles a Wi-Fi action, such as connecting or disconnecting.
async fn handle_wifi_action(
action: &WifiAction,
wifi_interface: &str,
Expand Down Expand Up @@ -437,6 +454,7 @@ async fn handle_wifi_action(
}
}

/// Sets and handles the selected action.
async fn set_action(
wifi_interface: &str,
action: ActionType,
Expand All @@ -458,6 +476,7 @@ async fn set_action(
}
}

/// Sends a notification about the Wi-Fi connection.
fn notify_connection(ssid: &str) -> Result<(), Box<dyn Error>> {
Notification::new()
.summary("Wi-Fi")
Expand Down
8 changes: 8 additions & 0 deletions src/networkmanager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use regex::Regex;
use std::error::Error;
use std::io::{BufRead, BufReader};

/// Retrieves available Wi-Fi networks using NetworkManager.
pub fn get_nm_wifi_networks(
command_runner: &dyn CommandRunner,
) -> Result<Vec<WifiAction>, Box<dyn Error>> {
Expand Down Expand Up @@ -32,6 +33,7 @@ pub fn get_nm_wifi_networks(
Ok(actions)
}

/// Fetches raw Wi-Fi network data from NetworkManager.
fn fetch_wifi_lines(
command_runner: &dyn CommandRunner,
) -> Result<Option<Vec<String>>, Box<dyn Error>> {
Expand All @@ -56,6 +58,7 @@ fn fetch_wifi_lines(
}
}

/// Parses the raw Wi-Fi network data into a structured format.
fn parse_wifi_lines(actions: &mut Vec<WifiAction>, wifi_lines: Vec<String>) {
wifi_lines.into_iter().for_each(|line| {
let parts: Vec<&str> = line.split(':').collect();
Expand All @@ -78,6 +81,7 @@ fn parse_wifi_lines(actions: &mut Vec<WifiAction>, wifi_lines: Vec<String>) {
});
}

/// Connects to a Wi-Fi network using NetworkManager.
pub fn connect_to_nm_wifi(
action: &str,
command_runner: &dyn CommandRunner,
Expand All @@ -94,6 +98,7 @@ pub fn connect_to_nm_wifi(
}
}

/// Attempts to connect to a Wi-Fi network, optionally using a password.
fn attempt_connection(
ssid: &str,
password: Option<String>,
Expand All @@ -116,6 +121,7 @@ fn attempt_connection(
}
}

/// Disconnects from a Wi-Fi network.
pub fn disconnect_nm_wifi(
interface: &str,
command_runner: &dyn CommandRunner,
Expand All @@ -126,6 +132,7 @@ pub fn disconnect_nm_wifi(
Ok(status.success())
}

/// Checks if NetworkManager is currently connected to a network.
pub fn is_nm_connected(
command_runner: &dyn CommandRunner,
interface: &str,
Expand All @@ -152,6 +159,7 @@ pub fn is_nm_connected(
Ok(false)
}

/// Checks if a Wi-Fi network is known (i.e., previously connected).
pub fn is_known_network(
ssid: &str,
command_runner: &dyn CommandRunner,
Expand Down
Loading

0 comments on commit 7211932

Please sign in to comment.