Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

refactor: move `shell_exec` command to `common` dir; move out platform calls

Lars Berger433f1bb16513
diff --git a/packages/wm/src/app_command.rs b/packages/wm/src/app_command.rs
index 11bf2068..78bcf985 100644
--- a/packages/wm/src/app_command.rs
+++ b/packages/wm/src/app_command.rs
@@ -6,11 +6,11 @@ use serde::{Deserialize, Deserializer};
use tracing::Level;
use crate::{
- common::{Direction, LengthValue, ResizeDimension},
+ common::{
+ commands::shell_exec, Direction, LengthValue, ResizeDimension,
+ },
containers::{
- commands::{shell_exec, toggle_tiling_direction},
- traits::CommonGetters,
- Container,
+ commands::toggle_tiling_direction, traits::CommonGetters, Container,
},
user_config::{FloatingStateConfig, FullscreenStateConfig, UserConfig},
windows::{
diff --git a/packages/wm/src/common/commands/mod.rs b/packages/wm/src/common/commands/mod.rs
index 93d10d62..eddc5626 100644
--- a/packages/wm/src/common/commands/mod.rs
+++ b/packages/wm/src/common/commands/mod.rs
@@ -1,3 +1,5 @@
+mod shell_exec;
mod sync_native_focus;
+pub use shell_exec::*;
pub use sync_native_focus::*;
diff --git a/packages/wm/src/common/commands/shell_exec.rs b/packages/wm/src/common/commands/shell_exec.rs
new file mode 100644
index 00000000..d7fa81b7
--- /dev/null
+++ b/packages/wm/src/common/commands/shell_exec.rs
@@ -0,0 +1,13 @@
+use tracing::info;
+
+use crate::common::platform::Platform;
+
+pub fn shell_exec(command: &str) -> anyhow::Result<()> {
+ let (program, args) = Platform::parse_command(command)?;
+ info!("Parsed command program: '{}', args: '{}'.", program, args);
+
+ Platform::run_command(&program, &args)?;
+ info!("Command executed successfully: {}.", command);
+
+ Ok(())
+}
diff --git a/packages/wm/src/common/platform/platform.rs b/packages/wm/src/common/platform/platform.rs
index 0f10b808..fa1ac0b8 100644
--- a/packages/wm/src/common/platform/platform.rs
+++ b/packages/wm/src/common/platform/platform.rs
@@ -1,13 +1,19 @@
+use std::path::Path;
use std::sync::Arc;
-use anyhow::bail;
+use anyhow::{bail, Context};
use tokio::sync::{oneshot, Mutex};
use tracing::warn;
-use windows::core::w;
+use windows::core::{w, PCWSTR};
+use windows::Win32::System::Environment::ExpandEnvironmentStringsW;
+use windows::Win32::UI::Shell::{
+ ShellExecuteExW, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS,
+ SHELLEXECUTEINFOW,
+};
use windows::Win32::UI::WindowsAndMessaging::{
CreateWindowExW, DestroyWindow, DispatchMessageW, GetMessageW,
RegisterClassW, SetCursorPos, TranslateMessage, CS_HREDRAW, CS_VREDRAW,
- CW_USEDEFAULT, MSG, WNDCLASSW, WNDPROC, WS_OVERLAPPEDWINDOW,
+ CW_USEDEFAULT, MSG, SW_NORMAL, WNDCLASSW, WNDPROC, WS_OVERLAPPEDWINDOW,
};
use windows::Win32::UI::{
HiDpi::{
@@ -17,7 +23,6 @@ use windows::Win32::UI::{
WindowsAndMessaging::{GetDesktopWindow, GetForegroundWindow},
};
-use crate::common::Rect;
use crate::user_config::UserConfig;
use super::{
@@ -30,17 +35,20 @@ pub type WindowProcedure = WNDPROC;
pub struct Platform;
impl Platform {
+ /// Gets the `NativeWindow` instance of the currently focused window.
pub fn foreground_window() -> NativeWindow {
let handle = unsafe { GetForegroundWindow() };
NativeWindow::new(handle)
}
+ /// Gets the `NativeWindow` instance of the desktop window.
pub fn desktop_window() -> NativeWindow {
let handle = unsafe { GetDesktopWindow() };
NativeWindow::new(handle)
}
- /// Monitors sorted from left-to-right, top-to-bottom.
+ /// Gets a vector of available monitors as `NativeMonitor` instances
+ /// sorted from left-to-right and top-to-bottom.
///
/// Note that this also ensures that the `NativeMonitor` instances have
/// valid position values.
@@ -78,6 +86,10 @@ impl Platform {
native_monitor::nearest_monitor(window.handle)
}
+ /// Gets a vector of "manageable" windows as `NativeWindow` instances.
+ ///
+ /// Manageable windows are visible windows that the WM is most likely
+ /// able to manage.
pub fn manageable_windows() -> anyhow::Result<Vec<NativeWindow>> {
Ok(
native_window::available_windows()?
@@ -87,16 +99,20 @@ impl Platform {
)
}
+ /// Creates a new `EventListener` for the specified user config.
pub async fn new_event_listener(
config: &Arc<Mutex<UserConfig>>,
) -> anyhow::Result<EventListener> {
EventListener::start(config).await
}
+ /// Creates a new `SingleInstance`.
pub fn new_single_instance() -> anyhow::Result<SingleInstance> {
SingleInstance::new()
}
+ /// Sets the DPI awareness for the current process to per-monitor
+ /// awareness (v2).
pub fn set_dpi_awareness() -> anyhow::Result<()> {
unsafe {
SetProcessDpiAwarenessContext(
@@ -107,6 +123,7 @@ impl Platform {
Ok(())
}
+ /// Sets the cursor position to the specified coordinates.
pub fn set_cursor_pos(x: i32, y: i32) -> anyhow::Result<()> {
unsafe {
SetCursorPos(x, y)?;
@@ -115,7 +132,10 @@ impl Platform {
Ok(())
}
- /// Creates a message window and starts a message loop.
+ /// Spawns a hidden message window and starts a message loop.
+ ///
+ /// This function will block until the message loop is aborted via the
+ /// `abort_rx` channel.
pub unsafe fn create_message_loop(
mut abort_rx: oneshot::Receiver<()>,
window_procedure: WindowProcedure,
@@ -169,4 +189,138 @@ impl Platform {
Ok(handle)
}
+
+ /// Parses a command string into a program name/path and arguments. This
+ /// also expands any environment variables found in the command string if
+ /// they are wrapped in `%` characters. If the command string is a path, a
+ /// file extension is required.
+ ///
+ /// This is similar to the `SHEvaluateSystemCommandTemplate` function. It
+ /// also parses program name/path and arguments, but can't handle `/` as
+ /// file path delimiters and it errors for certain programs (e.g. `code`).
+ ///
+ /// Returns a tuple containing the program name/path and arguments.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let (prog, args) = parse_command("code .")?;
+ /// assert_eq!(prog, "code");
+ /// assert_eq!(args, ".");
+ ///
+ /// let (prog, args) = parse_command(
+ /// r#"C:\Program Files\Git\git-bash --cd=C:\Users\larsb\.glaze-wm"#,
+ /// )?;
+ /// assert_eq!(prog, r#"C:\Program Files\Git\git-bash"#);
+ /// assert_eq!(args, r#"--cd=C:\Users\larsb\.glaze-wm"#);
+ /// ```
+ pub fn parse_command(command: &str) -> anyhow::Result<(String, String)> {
+ // Expand environment variables in the command string.
+ let expanded_command = {
+ let wide_command = to_wide(command);
+ let size = unsafe {
+ ExpandEnvironmentStringsW(PCWSTR(wide_command.as_ptr()), None)
+ };
+
+ if size == 0 {
+ anyhow::bail!(
+ "Failed to expand environment strings in command '{}'.",
+ command
+ );
+ }
+
+ let mut buffer = vec![0; size as usize];
+ let size = unsafe {
+ ExpandEnvironmentStringsW(
+ PCWSTR(wide_command.as_ptr()),
+ Some(&mut buffer),
+ )
+ };
+
+ // The size includes the null terminator, so we need to subtract one.
+ String::from_utf16_lossy(&buffer[..(size - 1) as usize])
+ };
+
+ let command_parts: Vec<&str> =
+ expanded_command.trim().split_whitespace().collect();
+
+ // If the command starts with double quotes, then the program name/path
+ // is wrapped in double quotes (e.g. `"C:\path\to\app.exe" --flag`).
+ if command.starts_with("\"") {
+ // Find the closing double quote.
+ let (closing_index, _) =
+ command.match_indices('"').nth(2).with_context(|| {
+ format!("Command doesn't have an ending `\"`: '{}'.", command)
+ })?;
+
+ return Ok((
+ command[1..closing_index].to_string(),
+ command[closing_index + 1..].trim().to_string(),
+ ));
+ }
+
+ // The first part is the program name if it doesn't contain a slash or
+ // backslash.
+ if let Some(first_part) = command_parts.first() {
+ if !first_part.contains(&['/', '\\'][..]) {
+ let args = command_parts[1..].join(" ");
+ return Ok((first_part.to_string(), args));
+ }
+ }
+
+ let mut cumulative_path = Vec::new();
+
+ // Lastly, iterate over the command until a valid file path is found.
+ for (part_index, &part) in command_parts.iter().enumerate() {
+ cumulative_path.push(part);
+
+ if Path::new(&cumulative_path.join(" ")).is_file() {
+ return Ok((
+ cumulative_path.join(" "),
+ command_parts[part_index + 1..].join(" "),
+ ));
+ }
+ }
+
+ anyhow::bail!("Program path is not valid for command '{}'.", command)
+ }
+
+ /// Runs the specified program with the given arguments.
+ pub fn run_command(program: &str, args: &str) -> anyhow::Result<()> {
+ let home_dir = home::home_dir()
+ .context("Unable to get home directory.")?
+ .to_str()
+ .context("Invalid home directory.")?
+ .to_owned();
+
+ // Inlining the wide variables within the `SHELLEXECUTEINFOW` struct
+ // causes issues where the pointer is dropped while `ShellExecuteExW` is
+ // using it. This is likely a `windows-rs` bug, and we can avoid it by
+ // keeping separate variables for the wide strings.
+ let program_wide = to_wide(&program);
+ let args_wide = to_wide(&args);
+ let home_dir_wide = to_wide(&home_dir);
+
+ // Using the built-in `Command::new` function in Rust launches the
+ // program as a subprocess. This prevents Windows from cleaning up
+ // handles held by our process (e.g. the IPC server port) until the
+ // subprocess exits.
+ let mut exec_info = SHELLEXECUTEINFOW {
+ cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
+ lpFile: PCWSTR(program_wide.as_ptr()),
+ lpParameters: PCWSTR(args_wide.as_ptr()),
+ lpDirectory: PCWSTR(home_dir_wide.as_ptr()),
+ nShow: SW_NORMAL.0 as _,
+ fMask: SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC,
+ ..Default::default()
+ };
+
+ unsafe { ShellExecuteExW(&mut exec_info) }?;
+ Ok(())
+ }
+}
+
+/// Utility function to convert a string to a null-terminated wide string.
+fn to_wide(string: &str) -> Vec<u16> {
+ string.encode_utf16().chain(Some(0)).collect()
}
diff --git a/packages/wm/src/containers/commands/exec_process.rs b/packages/wm/src/containers/commands/exec_process.rs
deleted file mode 100644
index 89828e1c..00000000
--- a/packages/wm/src/containers/commands/exec_process.rs
+++ /dev/null
@@ -1,154 +0,0 @@
-use std::path::Path;
-
-use anyhow::Context;
-use tracing::info;
-use windows::{
- core::PCWSTR,
- Win32::{
- System::Environment::ExpandEnvironmentStringsW,
- UI::{
- Shell::{
- ShellExecuteExW, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS,
- SHELLEXECUTEINFOW,
- },
- WindowsAndMessaging::SW_NORMAL,
- },
- },
-};
-
-pub fn shell_exec(command: &str) -> anyhow::Result<()> {
- let (program, args) = parse_command(command)?;
- info!("Parsed command program: '{}', args: '{}'.", program, args);
-
- let home_dir = home::home_dir()
- .context("Unable to get home directory.")?
- .to_str()
- .context("Invalid home directory.")?
- .to_owned();
-
- // Inlining the wide variables within the `SHELLEXECUTEINFOW` struct
- // causes issues where the pointer is dropped while `ShellExecuteExW` is
- // using it. This is likely a `windows-rs` bug, and we can avoid it by
- // keeping separate variables for the wide strings.
- let program_wide = to_wide(&program);
- let args_wide = to_wide(&args);
- let home_dir_wide = to_wide(&home_dir);
-
- // Using the built-in `Command::new` function in Rust launches the
- // program as a subprocess. This prevents Windows from cleaning up
- // handles held by our process (e.g. the IPC server port) until the
- // subprocess exits.
- let mut exec_info = SHELLEXECUTEINFOW {
- cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
- lpFile: PCWSTR(program_wide.as_ptr()),
- lpParameters: PCWSTR(args_wide.as_ptr()),
- lpDirectory: PCWSTR(home_dir_wide.as_ptr()),
- nShow: SW_NORMAL.0 as _,
- fMask: SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC,
- ..Default::default()
- };
-
- unsafe { ShellExecuteExW(&mut exec_info) }?;
- info!("Command executed successfully: {}.", command);
-
- Ok(())
-}
-
-/// Parses a command string into a program name/path and arguments. This
-/// also expands any environment variables found in the command string if
-/// they are wrapped in `%` characters. If the command string is a path, a
-/// file extension is required.
-///
-/// This is similar to the `SHEvaluateSystemCommandTemplate` function. It
-/// also parses program name/path and arguments, but can't handle `/` as
-/// file path delimiters and it errors for certain programs (e.g. `code`).
-///
-/// Returns a tuple containing the program name/path and arguments.
-///
-/// # Examples
-///
-/// ```
-/// let (prog, args) = parse_command("code .")?;
-/// assert_eq!(prog, "code");
-/// assert_eq!(args, ".");
-///
-/// let (prog, args) = parse_command(
-/// r#"C:\Program Files\Git\git-bash --cd=C:\Users\larsb\.glaze-wm"#,
-/// )?;
-/// assert_eq!(prog, r#"C:\Program Files\Git\git-bash"#);
-/// assert_eq!(args, r#"--cd=C:\Users\larsb\.glaze-wm"#);
-/// ```
-fn parse_command(command: &str) -> anyhow::Result<(String, String)> {
- // Expand environment variables in the command string.
- let expanded_command = {
- let wide_command = to_wide(command);
- let size = unsafe {
- ExpandEnvironmentStringsW(PCWSTR(wide_command.as_ptr()), None)
- };
-
- if size == 0 {
- anyhow::bail!(
- "Failed to expand environment strings in command '{}'.",
- command
- );
- }
-
- let mut buffer = vec![0; size as usize];
- let size = unsafe {
- ExpandEnvironmentStringsW(
- PCWSTR(wide_command.as_ptr()),
- Some(&mut buffer),
- )
- };
-
- // The size includes the null terminator, so we need to subtract one.
- String::from_utf16_lossy(&buffer[..(size - 1) as usize])
- };
-
- let command_parts: Vec<&str> =
- expanded_command.trim().split_whitespace().collect();
-
- // If the command starts with double quotes, then the program name/path
- // is wrapped in double quotes (e.g. `"C:\path\to\app.exe" --flag`).
- if command.starts_with("\"") {
- // Find the closing double quote.
- let (closing_index, _) =
- command.match_indices('"').nth(2).with_context(|| {
- format!("Command doesn't have an ending `\"`: '{}'.", command)
- })?;
-
- return Ok((
- command[1..closing_index].to_string(),
- command[closing_index + 1..].trim().to_string(),
- ));
- }
-
- // The first part is the program name if it doesn't contain a slash or
- // backslash.
- if let Some(first_part) = command_parts.first() {
- if !first_part.contains(&['/', '\\'][..]) {
- let args = command_parts[1..].join(" ");
- return Ok((first_part.to_string(), args));
- }
- }
-
- let mut cumulative_path = Vec::new();
-
- // Lastly, iterate over the command until a valid file path is found.
- for (part_index, &part) in command_parts.iter().enumerate() {
- cumulative_path.push(part);
-
- if Path::new(&cumulative_path.join(" ")).is_file() {
- return Ok((
- cumulative_path.join(" "),
- command_parts[part_index + 1..].join(" "),
- ));
- }
- }
-
- anyhow::bail!("Program path is not valid for command '{}'.", command)
-}
-
-fn to_wide(string: &str) -> Vec<u16> {
- string.encode_utf16().chain(Some(0)).collect()
-}
diff --git a/packages/wm/src/containers/commands/mod.rs b/packages/wm/src/containers/commands/mod.rs
index 6ec0b014..43722a11 100644
--- a/packages/wm/src/containers/commands/mod.rs
+++ b/packages/wm/src/containers/commands/mod.rs
@@ -1,7 +1,6 @@
mod attach_container;
mod center_cursor_on_container;
mod detach_container;
-mod exec_process;
mod flatten_split_container;
mod move_container_within_tree;
mod redraw;
@@ -14,7 +13,6 @@ mod toggle_tiling_direction;
pub use attach_container::*;
pub use center_cursor_on_container::*;
pub use detach_container::*;
-pub use exec_process::*;
pub use flatten_split_container::*;
pub use move_container_within_tree::*;
pub use redraw::*;