GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: remove `cli` mod; add `app_command` mod with parsing for start, query, and cmd
Lars Berger9e6330996763
diff --git a/packages/wm/src/app_command.rs b/packages/wm/src/app_command.rsnew file mode 100644index 00000000..d42446a6--- /dev/null+++ b/packages/wm/src/app_command.rs@@ -0,0 +1,177 @@+use std::path::PathBuf;++use clap::{Args, Parser, Subcommand};+use tracing::Level;++use crate::{+ common::{Direction, LengthValue, TilingDirection},+ windows::WindowState,+};++#[derive(Parser, Debug)]+#[clap(author, version, about, long_about = None)]+pub enum AppCommand {+ /// Starts the window manager.+ Start {+ /// Custom path to user config file.+ ///+ /// The default path is `%userprofile%/.glzr/glazewm/config.yaml`+ #[clap(short = 'c', long = "config", value_hint = clap::ValueHint::FilePath)]+ config_path: Option<PathBuf>,++ #[clap(flatten)]+ verbosity: Verbosity,+ },++ /// Prints the window manager's state.+ ///+ /// Requires an already running instance of the window manager.+ Query {+ #[clap(subcommand)]+ command: QueryCommand,+ },++ /// Invokes a window manager command.+ ///+ /// Requires an already running instance of the window manager.+ Cmd {+ #[clap(subcommand)]+ command: InvokeCommand,+ },+}++impl AppCommand {+ /// Parses `AppCommand` from command line arguments.+ ///+ /// Defaults to `AppCommand::Start` if no arguments are provided.+ pub fn parse_with_default() -> Self {+ let args = std::env::args().skip(1);++ match args.len() == 0 {+ true => AppCommand::Start {+ config_path: None,+ verbosity: Verbosity {+ verbose: false,+ quiet: false,+ },+ },+ false => AppCommand::parse(),+ }+ }+}++/// Verbosity flags to be used with `#[command(flatten)]`.+#[derive(Args, Debug)]+#[clap(about = None, long_about = None)]+pub struct Verbosity {+ /// Enables verbose logging.+ #[clap(short = 'v', long, action)]+ verbose: bool,++ /// Disables logging.+ #[clap(short = 'q', long, action, conflicts_with = "verbose")]+ quiet: bool,+}++impl Verbosity {+ /// Gets the log level based on the verbosity flags.+ pub fn level(&self) -> Level {+ match (self.verbose, self.quiet) {+ (true, _) => Level::DEBUG,+ (_, true) => Level::ERROR,+ _ => Level::INFO,+ }+ }+}++#[derive(Subcommand, Debug)]+#[clap(rename_all = "snake_case")]+pub enum QueryCommand {+ /// Prints all windows.+ Windows,+ /// Prints all monitors.+ Monitors,+ /// Prints the active binding modes.+ BindingMode,+ /// Prints the focused container (either a window or an empty workspace).+ Focused,+}++#[derive(Subcommand, Debug)]+#[clap(rename_all = "snake_case")]+pub enum InvokeCommand {+ CloseWindow,+ DisableBindingMode {+ #[clap(long)]+ name: String,+ },+ Exec {+ #[clap(long, num_args = 1..)]+ command: Vec<String>,+ },+ ExitWm,+ EnableBindingMode {+ #[clap(long)]+ name: String,+ },+ Focus {+ #[clap(long = "dir")]+ direction: Direction,+ },+ FocusWorkspace {+ #[clap(long, group = "focus_workspace")]+ name: Option<String>,++ #[clap(long, group = "focus_workspace")]+ next: bool,++ #[clap(long, group = "focus_workspace")]+ prev: bool,++ #[clap(long, group = "focus_workspace")]+ recent: bool,+ },+ IgnoreWindow,+ MoveWindow {+ #[clap(long = "dir")]+ direction: Direction,+ },+ MoveWindowToWorkspace {+ #[clap(long)]+ name: String,+ },+ MoveWorkspace {+ #[clap(long = "dir")]+ direction: Direction,+ },+ Redraw,+ ReloadConfig,+ ResizeWindow {+ #[clap(long)]+ width: Option<LengthValue>,++ #[clap(long)]+ height: Option<LengthValue>,+ },+ SetTilingDirection {+ #[clap(long = "tiling_dir")]+ tiling_direction: TilingDirection,+ },+ SetWindowBorders {+ #[clap(long)]+ width: Option<LengthValue>,++ #[clap(long)]+ height: Option<LengthValue>,+ },+ SetWindowState {+ #[clap(long)]+ state: WindowState,+ },+ ToggleFocusMode,+ ToggleTilingDirection,+ ToggleWindowState {+ #[clap(long)]+ state: WindowState,+ },+}diff --git a/packages/wm/src/cli.rs b/packages/wm/src/cli.rsdeleted file mode 100644index 8f8a4397..00000000--- a/packages/wm/src/cli.rs+++ /dev/null@@ -1,29 +0,0 @@-use clap::{Parser, Subcommand};--#[derive(Parser, Debug)]-#[clap(author, version, about, long_about = None, arg_required_else_help = true)]-pub struct Cli {- #[command(subcommand)]- pub command: CliCommand,-}--#[derive(Subcommand, Debug)]-pub enum CliCommand {- /// Starts the window manager.- Start {- /// Custom path to user config file.- #[clap(short, long)]- config_path: Option<String>,- },-- /// Queries the window manager's state.- Query {- windows: bool,- monitors: bool,- binding_mode: bool,- focused_container: bool,- },-- /// Runs a window manager command.- Cmd {},-}diff --git a/packages/wm/src/common/direction.rs b/packages/wm/src/common/direction.rsindex 051f3880..f5ce6442 100644--- a/packages/wm/src/common/direction.rs+++ b/packages/wm/src/common/direction.rs@@ -1,4 +1,6 @@-use anyhow::{bail, Result};+use std::str::FromStr;++use anyhow::bail;#[derive(Clone, Debug)]pub enum Direction {@@ -23,6 +25,10 @@ impl Direction {Direction::Down => Direction::Up,}}+}++impl FromStr for Direction {+ type Err = anyhow::Error;/// Parses a string into a direction.///@@ -30,7 +36,7 @@ impl Direction {/// ```/// Direction::from_str("left") // Direction::Left/// ```- pub fn from_str(unparsed: &str) -> Result<Direction> {+ fn from_str(unparsed: &str) -> anyhow::Result<Self> {match unparsed {"left" => Ok(Direction::Left),"right" => Ok(Direction::Right),diff --git a/packages/wm/src/common/rect_delta.rs b/packages/wm/src/common/rect_delta.rsindex ef503ce4..3955c780 100644--- a/packages/wm/src/common/rect_delta.rs+++ b/packages/wm/src/common/rect_delta.rs@@ -1,4 +1,6 @@-use anyhow::{bail, Result};+use std::str::FromStr;++use anyhow::bail;use serde::{Deserialize, Deserializer};use super::LengthValue;@@ -32,8 +34,18 @@ impl RectDelta {bottom,}}+}++impl FromStr for RectDelta {+ type Err = anyhow::Error;- pub fn from_str(unparsed: &str) -> Result<Self> {+ /// Parses a string into a rect delta.+ ///+ /// Example:+ /// ```+ /// RectDelta::from_str("5px 10px 5px") // RectDelta { left: 5px, top: 10px, right: 5px, bottom: 10px }+ /// ```+ fn from_str(unparsed: &str) -> anyhow::Result<Self> {let parts: Vec<&str> = unparsed.split_whitespace().collect();match parts.len() {diff --git a/packages/wm/src/common/tiling_direction.rs b/packages/wm/src/common/tiling_direction.rsindex 9bf90628..ae98344a 100644--- a/packages/wm/src/common/tiling_direction.rs+++ b/packages/wm/src/common/tiling_direction.rs@@ -1,4 +1,6 @@-use anyhow::{bail, Result};+use std::str::FromStr;++use anyhow::bail;use super::Direction;@@ -29,20 +31,24 @@ impl TilingDirection {/// ```/// TilingDirection::from_direction(Direction::Left) // TilingDirection::Horizontal/// ```- pub fn from_direction(&self, direction: Direction) -> TilingDirection {+ pub fn from_direction(direction: Direction) -> TilingDirection {match direction {Direction::Left | Direction::Right => TilingDirection::Horizontal,Direction::Up | Direction::Down => TilingDirection::Vertical,}}+}++impl FromStr for TilingDirection {+ type Err = anyhow::Error;- /// Parse a string into a tiling direction.+ /// Parses a string into a tiling direction.////// Example:/// ```/// TilingDirection::from_str("horizontal") // TilingDirection::Horizontal/// ```- pub fn from_str(unparsed: &str) -> Result<TilingDirection> {+ fn from_str(unparsed: &str) -> anyhow::Result<Self> {match unparsed {"horizontal" => Ok(TilingDirection::Horizontal),"vertical" => Ok(TilingDirection::Vertical),diff --git a/packages/wm/src/common/units.rs b/packages/wm/src/common/units.rsindex 98e5d58f..09ec53bc 100644--- a/packages/wm/src/common/units.rs+++ b/packages/wm/src/common/units.rs@@ -1,6 +1,6 @@use std::str::FromStr;-use anyhow::{bail, Context, Result};+use anyhow::{bail, Context};use regex::Regex;use serde::{Deserialize, Deserializer};@@ -24,39 +24,49 @@ impl LengthValue {}}+ pub fn to_pixels(&self, total: i32) -> i32 {+ match self.unit {+ LengthUnit::Pixel => self.amount as i32,+ LengthUnit::Percentage => {+ (self.amount / 100.0 * total as f32) as i32+ }+ }+ }+}++impl FromStr for LengthValue {+ type Err = anyhow::Error;+/// Parses a string containing a number followed by a unit (`px`, `%`).////// Example:/// ```/// LengthValue::from_str("100px") // { amount: 100.0, unit: LengthUnit::Pixel }/// ```- pub fn from_str(unparsed: &str) -> Result<LengthValue> {+ fn from_str(unparsed: &str) -> anyhow::Result<Self> {let units_regex = Regex::new(r"(\d+)(%|ppt|px)?")?;+ let err_msg = format!(+ "Not a valid length value '{}'. Must be of format '10px' or '10%'.",+ unparsed+ );+let captures = units_regex.captures(unparsed)- .context("Invalid length value.")?;+ .context(err_msg.to_string())?;- let amount = f32::from_str(&captures[1])?;+ let amount =+ f32::from_str(&captures[1]).context(err_msg.to_string())?;let unit_str = captures.get(2).map_or("", |m| m.as_str());let unit = match unit_str {"px" | "" => LengthUnit::Pixel,"%" => LengthUnit::Percentage,- _ => bail!("Not a valid unit '{}'.", unit_str),+ _ => bail!(err_msg),};Ok(LengthValue { amount, unit })}-- pub fn to_pixels(&self, total: i32) -> i32 {- match self.unit {- LengthUnit::Pixel => self.amount as i32,- LengthUnit::Percentage => {- (self.amount / 100.0 * total as f32) as i32- }- }- }}impl<'de> Deserialize<'de> for LengthValue {diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rsindex 6101f11a..b85b6ca4 100644--- a/packages/wm/src/main.rs+++ b/packages/wm/src/main.rs@@ -1,50 +1,49 @@-use std::{env, sync::Arc};--use anyhow::{Context, Result};use clap::Parser;-use common::platform::Platform;-use ipc_client::IpcClient;--use ipc_server::IpcServer;-use tokio::{- process::Command,- sync::{mpsc, Mutex},-};-use tracing::{info, level_filters::LevelFilter};-use tracing_subscriber::EnvFilter;-use user_config::UserConfig;-use wm::WindowManager;--use crate::cli::{Cli, CliCommand};--mod cli;+use tracing::info;++use crate::app_command::AppCommand;++mod app_command;mod common;-mod containers;-mod ipc_server;-mod monitors;-mod user_config;+// mod containers;+// mod ipc_server;+// mod monitors;+// mod user_config;mod windows;-mod wm;-mod wm_command;-mod wm_event;-mod wm_state;-mod workspaces;+// mod wm;+// mod wm_command;+// mod wm_event;+// mod wm_state;+// mod workspaces;#[tokio::main]async fn main() {- // TODO: Take log level and config path from `start` command arguments.- tracing_subscriber::fmt()- .with_env_filter(- EnvFilter::from_env("LOG_LEVEL")- .add_directive(LevelFilter::INFO.into()),- )- .init();-- let config_path = None;-- if let Err(err) = start_wm(config_path).await {- eprintln!("Failed to start GlazeWM: {}", err);+ let app_command = AppCommand::parse_with_default();++ match app_command {+ AppCommand::Start {+ config_path,+ verbosity,+ } => {+ tracing_subscriber::fmt()+ .with_max_level(verbosity.level())+ .init();++ info!(+ "Starting WM with log level {:?}.",+ verbosity.level().to_string()+ );++ // start_wm(config_path).await?;+ }+ _ => todo!(),}++ // let config_path = None;++ // if let Err(err) = start_wm(config_path).await {+ // eprintln!("Failed to start GlazeWM: {}", err);+ // }}async fn start_wm(config_path: Option<String>) -> Result<()> {diff --git a/packages/wm/src/windows/window_state.rs b/packages/wm/src/windows/window_state.rsindex 1b9891dc..ba7fd7e2 100644--- a/packages/wm/src/windows/window_state.rs+++ b/packages/wm/src/windows/window_state.rs@@ -1,3 +1,7 @@+use std::str::FromStr;++use anyhow::bail;+#[derive(Clone, Debug)]pub enum WindowState {Floating,@@ -6,3 +10,22 @@ pub enum WindowState {Minimized,Tiling,}++impl FromStr for WindowState {+ type Err = anyhow::Error;++ fn from_str(unparsed: &str) -> anyhow::Result<Self> {+ match unparsed {+ "floating" => Ok(WindowState::Floating),+ "fullscreen" => Ok(WindowState::Fullscreen),+ "maximized" => Ok(WindowState::Maximized),+ "minimized" => Ok(WindowState::Minimized),+ "tiling" => Ok(WindowState::Tiling),+ _ => bail!(+ "Not a valid window state '{}'. Must be one of the following: \+ 'floating', 'fullscreen', 'maximized', 'minimized', or 'tiling'.",+ unparsed+ ),+ }+ }+}diff --git a/resources/sample-config.yaml b/resources/sample-config.yamlindex 7e97d58a..c126e3ba 100644--- a/resources/sample-config.yaml+++ b/resources/sample-config.yaml@@ -158,37 +158,37 @@ keybindings:# Launch CMD terminal (alternatively `exec wt` or `exec %ProgramFiles%/Git/git-bash.exe`# to start Windows Terminal and Git Bash respectively.- - commands: ['exec --command "cmd"']+ - commands: ['exec --command cmd']bindings: ['Alt+Enter']# Focus the workspace that last had focus.- - commands: ['focus_workspace --recent']+ - commands: ['focus --recent-workspace']bindings: ['Alt+Y']# Focus the next/previous workspace defined in `workspaces` config.- - commands: ['focus_workspace --next']+ - commands: ['focus --next-workspace']bindings: ['Alt+T']- - commands: ['focus_workspace --prev']+ - commands: ['focus --prev-workspace']bindings: ['Alt+Shift+T']# Change focus to a workspace defined in `workspaces` config.- - commands: ['focus_workspace --name 1']+ - commands: ['focus --workspace 1']bindings: ['Alt+1']- - commands: ['focus_workspace --name 2']+ - commands: ['focus --workspace 2']bindings: ['Alt+2']- - commands: ['focus_workspace --name 3']+ - commands: ['focus --workspace 3']bindings: ['Alt+3']- - commands: ['focus_workspace --name 4']+ - commands: ['focus --workspace 4']bindings: ['Alt+4']- - commands: ['focus_workspace --name 5']+ - commands: ['focus --workspace 5']bindings: ['Alt+5']- - commands: ['focus_workspace --name 6']+ - commands: ['focus --workspace 6']bindings: ['Alt+6']- - commands: ['focus_workspace --name 7']+ - commands: ['focus --workspace 7']bindings: ['Alt+7']- - commands: ['focus_workspace --name 8']+ - commands: ['focus --workspace 8']bindings: ['Alt+8']- - commands: ['focus_workspace --name 9']+ - commands: ['focus --workspace 9']bindings: ['Alt+9']# Move focused workspace to a monitor in a given direction.@@ -202,21 +202,21 @@ keybindings:bindings: ['Alt+S']# Move focused window to a workspace defined in `workspaces` config.- - commands: ['move_window_to_workspace --name 1', 'focus_workspace --name 1']+ - commands: ['move_window --workspace 1', 'focus --workspace 1']bindings: ['Alt+Shift+1']- - commands: ['move_window_to_workspace --name 2', 'focus_workspace --name 2']+ - commands: ['move_window --workspace 2', 'focus --workspace 2']bindings: ['Alt+Shift+2']- - commands: ['move_window_to_workspace --name 3', 'focus_workspace --name 3']+ - commands: ['move_window --workspace 3', 'focus --workspace 3']bindings: ['Alt+Shift+3']- - commands: ['move_window_to_workspace --name 4', 'focus_workspace --name 4']+ - commands: ['move_window --workspace 4', 'focus --workspace 4']bindings: ['Alt+Shift+4']- - commands: ['move_window_to_workspace --name 5', 'focus_workspace --name 5']+ - commands: ['move_window --workspace 5', 'focus --workspace 5']bindings: ['Alt+Shift+5']- - commands: ['move_window_to_workspace --name 6', 'focus_workspace --name 6']+ - commands: ['move_window --workspace 6', 'focus --workspace 6']bindings: ['Alt+Shift+6']- - commands: ['move_window_to_workspace --name 7', 'focus_workspace --name 7']+ - commands: ['move_window --workspace 7', 'focus --workspace 7']bindings: ['Alt+Shift+7']- - commands: ['move_window_to_workspace --name 8', 'focus_workspace --name 8']+ - commands: ['move_window --workspace 8', 'focus --workspace 8']bindings: ['Alt+Shift+8']- - commands: ['move_window_to_workspace --name 9', 'focus_workspace --name 9']+ - commands: ['move_window --workspace 9', 'focus --workspace 9']bindings: ['Alt+Shift+9']