Skip to content

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

chore: fix all pedantic clippy lints; add clippy check to lint workflow (#915)

Lars Berger5405c0acf292
diff --git a/.github/workflows/lint-check.yaml b/.github/workflows/lint-check.yaml
index 5ecc4988..616ed9ab 100644
--- a/.github/workflows/lint-check.yaml
+++ b/.github/workflows/lint-check.yaml
@@ -14,12 +14,15 @@ jobs:
- uses: dtolnay/rust-toolchain@21dc36fb71dd22e3317045c0c31a3f4249868b17
with:
toolchain: nightly
- components: rustfmt
+ components: clippy, rustfmt
- uses: swatinem/rust-cache@f0deed1e0edfc6a9be95417288c0e1099b1eeec3
- - name: Check formatting
+ - name: Check formatting (rustfmt)
run: cargo fmt --check
+ - name: Check linting (clippy)
+ run: cargo clippy --all-targets --all-features -- -D warnings
+
- name: Check build
run: cargo build --locked
diff --git a/packages/wm-cli/build.rs b/packages/wm-cli/build.rs
index 2581fd07..6e4ccaac 100644
--- a/packages/wm-cli/build.rs
+++ b/packages/wm-cli/build.rs
@@ -22,13 +22,13 @@ fn main() {
let [major, minor, patch] =
<[u16; 3]>::try_from(version_parts).unwrap_or([0, 0, 0]);
- let version_str = format!("{}.{}.{}.0", major, minor, patch);
+ let version_str = format!("{major}.{minor}.{patch}.0");
res.set("FileVersion", &version_str);
res.set("ProductVersion", &version_str);
- let version_u64 = ((major as u64) << 48)
- | ((minor as u64) << 32)
- | ((patch as u64) << 16);
+ let version_u64 = (u64::from(major) << 48)
+ | (u64::from(minor) << 32)
+ | (u64::from(patch) << 16);
res.set_version_info(VersionInfo::FILEVERSION, version_u64);
res.set_version_info(VersionInfo::PRODUCTVERSION, version_u64);
diff --git a/packages/wm-cli/src/lib.rs b/packages/wm-cli/src/lib.rs
index adf4e6f9..c8598891 100644
--- a/packages/wm-cli/src/lib.rs
+++ b/packages/wm-cli/src/lib.rs
@@ -1,3 +1,6 @@
+#![warn(clippy::all, clippy::pedantic)]
+#![allow(clippy::missing_errors_doc)]
+
use anyhow::Context;
use wm_common::ClientResponseData;
use wm_ipc_client::IpcClient;
diff --git a/packages/wm-cli/src/main.rs b/packages/wm-cli/src/main.rs
index 349dc5ae..eeb31eef 100644
--- a/packages/wm-cli/src/main.rs
+++ b/packages/wm-cli/src/main.rs
@@ -22,7 +22,7 @@ async fn main() -> anyhow::Result<()> {
[exe_dir.join("glazewm.exe"), exe_dir.join("../glazewm.exe")]
.into_iter()
.find(|path| path.exists())
- .and_then(|path| path.to_str().map(|s| s.to_string()))
+ .and_then(|path| path.to_str().map(ToString::to_string))
.context("Failed to resolve path to the main executable.")?;
// UIAccess applications can't be started directly, so we need to use
@@ -32,7 +32,7 @@ async fn main() -> anyhow::Result<()> {
.args(
["/C", "start", "", &main_path]
.into_iter()
- .chain(args.iter().skip(1).map(|s| s.as_str())),
+ .chain(args.iter().skip(1).map(String::as_str)),
)
.spawn()
.context("Failed to start main executable.")?;
diff --git a/packages/wm-common/src/app_command.rs b/packages/wm-common/src/app_command.rs
index e079cc07..0e7b2394 100644
--- a/packages/wm-common/src/app_command.rs
+++ b/packages/wm-common/src/app_command.rs
@@ -69,16 +69,18 @@ impl AppCommand {
/// Parses `AppCommand` from command line arguments.
///
/// Defaults to `AppCommand::Start` if no arguments are provided.
+ #[must_use]
pub fn parse_with_default(args: &Vec<String>) -> Self {
- match args.len() == 1 {
- true => AppCommand::Start {
+ if args.len() == 1 {
+ AppCommand::Start {
config_path: None,
verbosity: Verbosity {
verbose: false,
quiet: false,
},
- },
- false => AppCommand::parse_from(args),
+ }
+ } else {
+ AppCommand::parse_from(args)
}
}
}
@@ -98,6 +100,7 @@ pub struct Verbosity {
impl Verbosity {
/// Gets the log level based on the verbosity flags.
+ #[must_use]
pub fn level(&self) -> Level {
match (self.verbose, self.quiet) {
(true, _) => Level::DEBUG,
@@ -294,6 +297,7 @@ pub struct InvokeAdjustBordersCommand {
#[derive(Args, Clone, Debug, PartialEq, Serialize)]
#[group(required = true, multiple = false)]
+#[allow(clippy::struct_excessive_bools)]
pub struct InvokeFocusCommand {
#[clap(long)]
pub direction: Option<Direction>,
@@ -322,6 +326,7 @@ pub struct InvokeFocusCommand {
#[derive(Args, Clone, Debug, PartialEq, Serialize)]
#[group(required = true, multiple = false)]
+#[allow(clippy::struct_excessive_bools)]
pub struct InvokeMoveCommand {
/// Direction to move the window.
#[clap(long)]
diff --git a/packages/wm-common/src/direction.rs b/packages/wm-common/src/direction.rs
index 7e4afd8a..bfb3b237 100644
--- a/packages/wm-common/src/direction.rs
+++ b/packages/wm-common/src/direction.rs
@@ -21,6 +21,7 @@ impl Direction {
/// let dir = Direction::Left.inverse();
/// assert_eq!(dir, Direction::Right);
/// ```
+ #[must_use]
pub fn inverse(&self) -> Direction {
match self {
Direction::Left => Direction::Right,
diff --git a/packages/wm-common/src/length_value.rs b/packages/wm-common/src/length_value.rs
index 0246c6cb..ccfef57f 100644
--- a/packages/wm-common/src/length_value.rs
+++ b/packages/wm-common/src/length_value.rs
@@ -18,25 +18,31 @@ pub enum LengthUnit {
}
impl LengthValue {
+ #[must_use]
pub fn from_px(px: i32) -> Self {
Self {
+ #[allow(clippy::cast_precision_loss)]
amount: px as f32,
unit: LengthUnit::Pixel,
}
}
+ #[must_use]
pub fn to_px(&self, total_px: i32, scale_factor: Option<f32>) -> i32 {
let scale_factor = scale_factor.unwrap_or(1.0);
+ #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
match self.unit {
LengthUnit::Percentage => (self.amount * total_px as f32) as i32,
LengthUnit::Pixel => (self.amount * scale_factor) as i32,
}
}
+ #[must_use]
pub fn to_percentage(&self, total_px: i32) -> f32 {
match self.unit {
LengthUnit::Percentage => self.amount,
+ #[allow(clippy::cast_precision_loss)]
LengthUnit::Pixel => self.amount / total_px as f32,
}
}
@@ -63,8 +69,7 @@ impl FromStr for LengthValue {
let units_regex = Regex::new(r"([+-]?\d+)(%|px)?")?;
let err_msg = format!(
- "Not a valid length value '{}'. Must be of format '10px' or '10%'.",
- unparsed
+ "Not a valid length value '{unparsed}'. Must be of format '10px' or '10%'."
);
let captures = units_regex
diff --git a/packages/wm-common/src/lib.rs b/packages/wm-common/src/lib.rs
index 2896f847..bd2d01a7 100644
--- a/packages/wm-common/src/lib.rs
+++ b/packages/wm-common/src/lib.rs
@@ -1,3 +1,6 @@
+#![warn(clippy::all, clippy::pedantic)]
+#![allow(clippy::missing_errors_doc)]
+
mod active_drag;
mod app_command;
mod color;
diff --git a/packages/wm-common/src/opacity_value.rs b/packages/wm-common/src/opacity_value.rs
index c4181f6b..b46e7c8a 100644
--- a/packages/wm-common/src/opacity_value.rs
+++ b/packages/wm-common/src/opacity_value.rs
@@ -41,8 +41,7 @@ impl FromStr for OpacityValue {
let units_regex = Regex::new(r"([+-]?)(\d+)(%?)")?;
let err_msg = format!(
- "Not a valid opacity value '{}'. Must be of format '255', '100%', '+10%' or '-128'.",
- unparsed
+ "Not a valid opacity value '{unparsed}'. Must be of format '255', '100%', '+10%' or '-128'."
);
let captures = units_regex
@@ -56,6 +55,7 @@ impl FromStr for OpacityValue {
let unit_str = captures.get(3).map_or("", |m| m.as_str());
+ #[allow(clippy::cast_possible_truncation)]
let amount = captures
.get(2)
.and_then(|amount_str| f32::from_str(amount_str.into()).ok())
@@ -89,9 +89,11 @@ impl<'de> Deserialize<'de> for OpacityValue {
match OpacityValueDe::deserialize(deserializer)? {
OpacityValueDe::Struct { amount, is_delta } => Ok(Self {
+ #[allow(clippy::cast_possible_truncation)]
amount: amount as i16,
is_delta,
}),
+
OpacityValueDe::String(str) => {
Self::from_str(&str).map_err(serde::de::Error::custom)
}
diff --git a/packages/wm-common/src/parsed_config.rs b/packages/wm-common/src/parsed_config.rs
index 73500fe0..9ea4e106 100644
--- a/packages/wm-common/src/parsed_config.rs
+++ b/packages/wm-common/src/parsed_config.rs
@@ -299,6 +299,7 @@ pub enum MatchType {
impl MatchType {
/// Whether the given value is a match for the match type.
+ #[must_use]
pub fn is_match(&self, value: &str) -> bool {
match self {
MatchType::Equals { equals } => value == equals,
diff --git a/packages/wm-common/src/rect.rs b/packages/wm-common/src/rect.rs
index f1e9275b..66308391 100644
--- a/packages/wm-common/src/rect.rs
+++ b/packages/wm-common/src/rect.rs
@@ -20,6 +20,7 @@ pub struct Rect {
impl Rect {
/// Creates a new `Rect` instance from the coordinates of its left, top,
/// right, and bottom edges.
+ #[must_use]
pub fn from_ltrb(left: i32, top: i32, right: i32, bottom: i32) -> Self {
Self {
left,
@@ -30,6 +31,7 @@ impl Rect {
}
/// Creates a new `Rect` instance from its X/Y coordinates and size.
+ #[must_use]
pub fn from_xy(x: i32, y: i32, width: i32, height: i32) -> Self {
Self {
left: x,
@@ -39,26 +41,32 @@ impl Rect {
}
}
+ #[must_use]
pub fn x(&self) -> i32 {
self.left
}
+ #[must_use]
pub fn y(&self) -> i32 {
self.top
}
+ #[must_use]
pub fn width(&self) -> i32 {
self.right - self.left
}
+ #[must_use]
pub fn height(&self) -> i32 {
self.bottom - self.top
}
+ #[must_use]
pub fn translate_to_coordinates(&self, x: i32, y: i32) -> Self {
Self::from_xy(x, y, self.width(), self.height())
}
+ #[must_use]
pub fn translate_to_center(&self, outer_rect: &Rect) -> Self {
Self::translate_to_coordinates(
self,
@@ -67,6 +75,7 @@ impl Rect {
)
}
+ #[must_use]
pub fn translate_in_direction(
&self,
direction: &Direction,
@@ -90,6 +99,7 @@ impl Rect {
/// Returns a new `Rect` that is clamped within the bounds of the given
/// outer rectangle. Attempts to preserve the width and height of the
/// original rectangle.
+ #[must_use]
pub fn clamp(&self, outer_rect: &Rect) -> Self {
Self::from_xy(
self.left.max(outer_rect.left),
@@ -99,6 +109,7 @@ impl Rect {
)
}
+ #[must_use]
pub fn clamp_size(&self, width: i32, height: i32) -> Self {
Self::from_xy(
self.x(),
@@ -108,6 +119,7 @@ impl Rect {
)
}
+ #[must_use]
pub fn center_point(&self) -> Point {
Point {
x: self.left + (self.width() / 2),
@@ -116,6 +128,7 @@ impl Rect {
}
/// Gets the delta between this rect and another rect.
+ #[must_use]
pub fn delta(&self, other: &Rect) -> RectDelta {
RectDelta {
left: LengthValue::from_px(other.left - self.left),
@@ -125,6 +138,7 @@ impl Rect {
}
}
+ #[must_use]
pub fn apply_delta(
&self,
delta: &RectDelta,
@@ -138,6 +152,7 @@ impl Rect {
)
}
+ #[must_use]
pub fn apply_inverse_delta(
&self,
delta: &RectDelta,
@@ -153,6 +168,7 @@ impl Rect {
// Gets whether the x-coordinate overlaps with the x-coordinate of the
// other rect.
+ #[must_use]
pub fn has_overlap_x(&self, other: &Rect) -> bool {
!(self.x() + self.width() <= other.x()
|| other.x() + other.width() <= self.x())
@@ -160,17 +176,20 @@ impl Rect {
// Gets whether the y-coordinate overlaps with the y-coordinate of the
// other rect.
+ #[must_use]
pub fn has_overlap_y(&self, other: &Rect) -> bool {
!(self.y() + self.height() <= other.y()
|| other.y() + other.height() <= self.y())
}
+ #[must_use]
pub fn contains_point(&self, point: &Point) -> bool {
let is_in_x = point.x >= self.left && point.x <= self.right;
let is_in_y = point.y >= self.top && point.y <= self.bottom;
is_in_x && is_in_y
}
+ #[must_use]
pub fn distance_to_point(&self, point: &Point) -> f32 {
let dx = (self.x() - point.x)
.abs()
@@ -180,6 +199,7 @@ impl Rect {
.abs()
.max((self.y() + self.height() - point.y).abs());
+ #[allow(clippy::cast_precision_loss)]
((dx * dx + dy * dy) as f32).sqrt()
}
}
diff --git a/packages/wm-common/src/rect_delta.rs b/packages/wm-common/src/rect_delta.rs
index 99c776ae..09916b76 100644
--- a/packages/wm-common/src/rect_delta.rs
+++ b/packages/wm-common/src/rect_delta.rs
@@ -18,6 +18,7 @@ pub struct RectDelta {
}
impl RectDelta {
+ #[must_use]
pub fn new(
left: LengthValue,
top: LengthValue,
diff --git a/packages/wm-common/src/tiling_direction.rs b/packages/wm-common/src/tiling_direction.rs
index 55582703..0a43d0bc 100644
--- a/packages/wm-common/src/tiling_direction.rs
+++ b/packages/wm-common/src/tiling_direction.rs
@@ -8,8 +8,8 @@ use super::Direction;
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TilingDirection {
- Vertical,
Horizontal,
+ Vertical,
}
impl TilingDirection {
@@ -21,10 +21,11 @@ impl TilingDirection {
/// let dir = TilingDirection::Horizontal.inverse();
/// assert_eq!(dir, TilingDirection::Vertical);
/// ```
- pub fn inverse(&self) -> TilingDirection {
+ #[must_use]
+ pub fn inverse(&self) -> Self {
match self {
- TilingDirection::Horizontal => TilingDirection::Vertical,
- TilingDirection::Vertical => TilingDirection::Horizontal,
+ Self::Horizontal => Self::Vertical,
+ Self::Vertical => Self::Horizontal,
}
}
@@ -37,10 +38,11 @@ impl TilingDirection {
/// let dir = TilingDirection::from_direction(&Direction::Left);
/// assert_eq!(dir, TilingDirection::Horizontal);
/// ```
- pub fn from_direction(direction: &Direction) -> TilingDirection {
+ #[must_use]
+ pub fn from_direction(direction: &Direction) -> Self {
match direction {
- Direction::Left | Direction::Right => TilingDirection::Horizontal,
- Direction::Up | Direction::Down => TilingDirection::Vertical,
+ Direction::Left | Direction::Right => Self::Horizontal,
+ Direction::Up | Direction::Down => Self::Vertical,
}
}
}
@@ -62,8 +64,8 @@ impl FromStr for TilingDirection {
/// ```
fn from_str(unparsed: &str) -> anyhow::Result<Self> {
match unparsed {
- "horizontal" => Ok(TilingDirection::Horizontal),
- "vertical" => Ok(TilingDirection::Vertical),
+ "horizontal" => Ok(Self::Horizontal),
+ "vertical" => Ok(Self::Vertical),
_ => bail!("Not a valid tiling direction: {}", unparsed),
}
}
diff --git a/packages/wm-common/src/utils/memo.rs b/packages/wm-common/src/utils/memo.rs
index a8911f2e..84c833cd 100644
--- a/packages/wm-common/src/utils/memo.rs
+++ b/packages/wm-common/src/utils/memo.rs
@@ -15,7 +15,7 @@ where
T: Clone,
{
fn default() -> Self {
- Memo {
+ Self {
value: Arc::new(Mutex::new(None)),
}
}
@@ -26,12 +26,17 @@ where
T: Clone,
{
/// Creates a new `Memo` instance with `None` as the initial value.
+ #[must_use]
pub fn new() -> Self {
Self::default()
}
/// Retrieves the cached value if it exists, otherwise initializes it
/// using the provided closure.
+ ///
+ /// # Panics
+ ///
+ /// If the internal mutex is poisoned.
pub fn get_or_init<F, R>(
&self,
retriever_fn: F,
@@ -43,18 +48,21 @@ where
{
let mut value_ref = self.value.lock().unwrap();
- value_ref
- .as_ref()
- .map(|value| Ok(value.clone()))
- .unwrap_or_else(|| {
- let value = retriever_fn(arg)?;
- *value_ref = Some(value.clone());
- Ok(value)
- })
+ if let Some(value) = value_ref.as_ref() {
+ Ok(value.clone())
+ } else {
+ let value = retriever_fn(arg)?;
+ *value_ref = Some(value.clone());
+ Ok(value)
+ }
}
/// Refreshes the cached value by generating a new value using the
/// provided closure.
+ ///
+ /// # Panics
+ ///
+ /// If the internal mutex is poisoned.
pub fn update<F, R>(&self, retriever_fn: F, arg: &R) -> anyhow::Result<T>
where
F: FnOnce(&R) -> anyhow::Result<T>,
diff --git a/packages/wm-common/src/window_state.rs b/packages/wm-common/src/window_state.rs
index 784eae04..5ebb2536 100644
--- a/packages/wm-common/src/window_state.rs
+++ b/packages/wm-common/src/window_state.rs
@@ -18,10 +18,11 @@ pub enum WindowState {
}
impl WindowState {
+ #[must_use]
pub fn default_from_config(config: &ParsedConfig) -> Self {
match config.window_behavior.initial_state {
- InitialWindowState::Tiling => WindowState::Tiling,
- InitialWindowState::Floating => WindowState::Floating(
+ InitialWindowState::Tiling => Self::Tiling,
+ InitialWindowState::Floating => Self::Floating(
config.window_behavior.state_defaults.floating.clone(),
),
}
diff --git a/packages/wm-ipc-client/src/lib.rs b/packages/wm-ipc-client/src/lib.rs
index d80560a4..61fc2cf4 100644
--- a/packages/wm-ipc-client/src/lib.rs
+++ b/packages/wm-ipc-client/src/lib.rs
@@ -1,3 +1,5 @@
+#![allow(clippy::missing_errors_doc)]
+
use anyhow::Context;
use futures_util::{SinkExt, StreamExt};
use tokio::net::TcpStream;
@@ -16,7 +18,7 @@ pub struct IpcClient {
impl IpcClient {
pub async fn connect() -> anyhow::Result<Self> {
- let server_addr = format!("ws://127.0.0.1:{}", DEFAULT_IPC_PORT);
+ let server_addr = format!("ws://127.0.0.1:{DEFAULT_IPC_PORT}");
let (stream, _) = connect_async(server_addr)
.await
diff --git a/packages/wm-platform/src/com.rs b/packages/wm-platform/src/com.rs
index a08cf129..4303a480 100644
--- a/packages/wm-platform/src/com.rs
+++ b/packages/wm-platform/src/com.rs
@@ -29,6 +29,7 @@ impl ComInit {
///
/// Panics if COM initialization fails. This is typically only possible
/// if COM is already initialized with an incompatible threading model.
+ #[must_use]
pub fn new() -> Self {
unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }
.expect("Unable to initialize COM.");
@@ -37,6 +38,12 @@ impl ComInit {
}
}
+impl Default for ComInit {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl Drop for ComInit {
fn drop(&mut self) {
unsafe { CoUninitialize() };
diff --git a/packages/wm-platform/src/event_listener.rs b/packages/wm-platform/src/event_listener.rs
index ea30ef83..dbe01184 100644
--- a/packages/wm-platform/src/event_listener.rs
+++ b/packages/wm-platform/src/event_listener.rs
@@ -45,7 +45,7 @@ impl EventListener {
let (event_tx, event_rx) = mpsc::unbounded_channel();
let event_window = EventWindow::new(
- event_tx,
+ &event_tx,
&config.keybindings,
config.general.focus_follows_cursor,
)?;
diff --git a/packages/wm-platform/src/event_window.rs b/packages/wm-platform/src/event_window.rs
index eb67ad9d..90548053 100644
--- a/packages/wm-platform/src/event_window.rs
+++ b/packages/wm-platform/src/event_window.rs
@@ -81,7 +81,7 @@ impl EventWindow {
/// Uses global state (e.g. `PLATFORM_EVENT_TX`) and should thus only
/// ever be instantiated once in the application's lifetime.
pub fn new(
- event_tx: mpsc::UnboundedSender<PlatformEvent>,
+ event_tx: &mpsc::UnboundedSender<PlatformEvent>,
keybindings: &Vec<KeybindingConfig>,
enable_mouse_events: bool,
) -> anyhow::Result<Self> {
@@ -114,6 +114,7 @@ impl EventWindow {
// Register our window to receive mouse events.
unsafe {
+ #[allow(clippy::cast_possible_truncation)]
RegisterRawInputDevices(
&[rid],
std::mem::size_of::<RAWINPUTDEVICE>() as u32,
@@ -183,14 +184,15 @@ pub extern "system" fn event_window_proc(
if let Some(event_tx) = PLATFORM_EVENT_TX.get() {
return match message {
WM_POWERBROADCAST => {
+ #[allow(clippy::cast_possible_truncation)]
match wparam.0 as u32 {
// System is resuming from sleep/hibernation.
PBT_APMRESUMEAUTOMATIC | PBT_APMRESUMESUSPEND => {
- IS_SYSTEM_SUSPENDED.store(false, Ordering::Relaxed)
+ IS_SYSTEM_SUSPENDED.store(false, Ordering::Relaxed);
}
// System is entering sleep/hibernation.
PBT_APMSUSPEND => {
- IS_SYSTEM_SUSPENDED.store(true, Ordering::Relaxed)
+ IS_SYSTEM_SUSPENDED.store(true, Ordering::Relaxed);
}
_ => {}
};
@@ -231,6 +233,7 @@ fn handle_display_change_msg(
wparam: WPARAM,
event_tx: &mpsc::UnboundedSender<PlatformEvent>,
) -> anyhow::Result<()> {
+ #[allow(clippy::cast_possible_truncation)]
let should_emit_event = match message {
WM_SETTINGCHANGE => {
wparam.0 as u32 == SPI_SETWORKAREA.0
@@ -255,13 +258,15 @@ fn handle_input_msg(
event_tx: &mpsc::UnboundedSender<PlatformEvent>,
) -> anyhow::Result<()> {
let mut raw_input: RAWINPUT = unsafe { std::mem::zeroed() };
+ #[allow(clippy::cast_possible_truncation)]
let mut raw_input_size = std::mem::size_of::<RAWINPUT>() as u32;
let res_size = unsafe {
+ #[allow(clippy::cast_possible_truncation)]
GetRawInputData(
HRAWINPUT(lparam.0),
RID_INPUT,
- Some(&mut raw_input as *mut _ as _),
+ Some(std::ptr::from_mut(&mut raw_input).cast()),
&mut raw_input_size,
std::mem::size_of::<RAWINPUTHEADER>() as u32,
)
@@ -303,6 +308,7 @@ fn handle_input_msg(
_ => false,
};
+ #[allow(clippy::cast_possible_truncation)]
let event_time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|dur| dur.as_millis() as u64)?;
@@ -337,5 +343,5 @@ fn handle_input_msg(
/// Checks whether `state` contains all the bits of `mask`.
#[inline]
fn has_mouse_flag(state: u16, mask: u32) -> bool {
- state as u32 & mask == mask
+ u32::from(state) & mask == mask
}
diff --git a/packages/wm-platform/src/keyboard_hook.rs b/packages/wm-platform/src/keyboard_hook.rs
index 68788c05..2c13d738 100644
--- a/packages/wm-platform/src/keyboard_hook.rs
+++ b/packages/wm-platform/src/keyboard_hook.rs
@@ -8,7 +8,27 @@ use tracing::warn;
use windows::Win32::{
Foundation::{LPARAM, LRESULT, WPARAM},
UI::{
- Input::KeyboardAndMouse::*,
+ Input::KeyboardAndMouse::{
+ GetKeyState, GetKeyboardLayout, VkKeyScanExW, VIRTUAL_KEY, VK_0,
+ VK_1, VK_2, VK_3, VK_4, VK_5, VK_6, VK_7, VK_8, VK_9, VK_A, VK_ADD,
+ VK_B, VK_BACK, VK_C, VK_CAPITAL, VK_CONTROL, VK_D, VK_DECIMAL,
+ VK_DELETE, VK_DIVIDE, VK_DOWN, VK_E, VK_END, VK_ESCAPE, VK_F, VK_F1,
+ VK_F10, VK_F11, VK_F12, VK_F13, VK_F14, VK_F15, VK_F16, VK_F17,
+ VK_F18, VK_F19, VK_F2, VK_F20, VK_F21, VK_F22, VK_F23, VK_F24,
+ VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_G, VK_H,
+ VK_HOME, VK_I, VK_INSERT, VK_J, VK_K, VK_L, VK_LCONTROL, VK_LEFT,
+ VK_LMENU, VK_LSHIFT, VK_LWIN, VK_M, VK_MEDIA_NEXT_TRACK,
+ VK_MEDIA_PLAY_PAUSE, VK_MEDIA_PREV_TRACK, VK_MEDIA_STOP, VK_MENU,
+ VK_MULTIPLY, VK_N, VK_NEXT, VK_NUMLOCK, VK_NUMPAD0, VK_NUMPAD1,
+ VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6,
+ VK_NUMPAD7, VK_NUMPAD8, VK_NUMPAD9, VK_O, VK_OEM_1, VK_OEM_2,
+ VK_OEM_3, VK_OEM_4, VK_OEM_5, VK_OEM_6, VK_OEM_7, VK_OEM_COMMA,
+ VK_OEM_MINUS, VK_OEM_PERIOD, VK_OEM_PLUS, VK_P, VK_PRIOR, VK_Q,
+ VK_R, VK_RCONTROL, VK_RETURN, VK_RIGHT, VK_RMENU, VK_RSHIFT,
+ VK_RWIN, VK_S, VK_SCROLL, VK_SHIFT, VK_SNAPSHOT, VK_SPACE,
+ VK_SUBTRACT, VK_T, VK_TAB, VK_U, VK_UP, VK_V, VK_VOLUME_DOWN,
+ VK_VOLUME_MUTE, VK_VOLUME_UP, VK_W, VK_X, VK_Y, VK_Z,
+ },
WindowsAndMessaging::{
CallNextHookEx, SetWindowsHookExW, UnhookWindowsHookEx, HHOOK,
KBDLLHOOKSTRUCT, WH_KEYBOARD_LL, WM_KEYDOWN, WM_SYSKEYDOWN,
@@ -78,6 +98,10 @@ impl KeyboardHook {
/// Starts a keyboard hook on the current thread.
///
/// Assumes that a message loop is currently running.
+ ///
+ /// # Panics
+ ///
+ /// If the internal mutex is poisoned.
pub fn start(&self) -> anyhow::Result<()> {
*self.hook.lock().unwrap() = unsafe {
SetWindowsHookExW(WH_KEYBOARD_LL, Some(keyboard_hook_proc), None, 0)
@@ -86,12 +110,21 @@ impl KeyboardHook {
Ok(())
}
+ /// Updates the keybindings for the keyboard hook.
+ ///
+ /// # Panics
+ ///
+ /// If the internal mutex is poisoned.
pub fn update(&self, keybindings: &Vec<KeybindingConfig>) {
*self.keybindings_by_trigger_key.lock().unwrap() =
Self::keybindings_by_trigger_key(keybindings);
}
/// Stops the low-level keyboard hook.
+ ///
+ /// # Panics
+ ///
+ /// If the internal mutex is poisoned.
pub fn stop(&self) -> anyhow::Result<()> {
unsafe { UnhookWindowsHookEx(*self.hook.lock().unwrap()) }?;
Ok(())
@@ -105,7 +138,7 @@ impl KeyboardHook {
for keybinding in keybindings {
for binding in &keybinding.bindings {
let vk_codes = binding
- .split("+")
+ .split('+')
.filter_map(|key| {
let vk_code = Self::key_to_vk_code(key);
@@ -136,6 +169,7 @@ impl KeyboardHook {
keybinding_map
}
+ #[allow(clippy::too_many_lines)]
fn key_to_vk_code(key: &str) -> Option<u16> {
match key.to_lowercase().as_str() {
"a" => Some(VK_A.0),
@@ -277,7 +311,7 @@ impl KeyboardHook {
// Key is valid if it doesn't require shift or alt to be pressed.
match high_order {
- 0 => Some(low_order as u16),
+ 0 => Some(u16::from(low_order)),
_ => None,
}
}
@@ -407,6 +441,7 @@ extern "system" fn keyboard_hook_proc(
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
+ #[allow(clippy::cast_possible_truncation)]
let should_ignore = code != 0
|| !(wparam.0 as u32 == WM_KEYDOWN
|| wparam.0 as u32 == WM_SYSKEYDOWN);
@@ -422,6 +457,7 @@ extern "system" fn keyboard_hook_proc(
let input = unsafe { *(lparam.0 as *const KBDLLHOOKSTRUCT) };
if let Some(hook) = KEYBOARD_HOOK.get() {
+ #[allow(clippy::cast_possible_truncation)]
let should_block = hook.handle_key_event(input.vkCode as u16);
if should_block {
diff --git a/packages/wm-platform/src/lib.rs b/packages/wm-platform/src/lib.rs
index c50f65a9..2b807d9e 100644
--- a/packages/wm-platform/src/lib.rs
+++ b/packages/wm-platform/src/lib.rs
@@ -1,3 +1,5 @@
+#![warn(clippy::all, clippy::pedantic)]
+#![allow(clippy::missing_errors_doc)]
#![feature(iterator_try_collect)]
#![feature(once_cell_try)]
diff --git a/packages/wm-platform/src/native_monitor.rs b/packages/wm-platform/src/native_monitor.rs
index 55c66bf4..4057659a 100644
--- a/packages/wm-platform/src/native_monitor.rs
+++ b/packages/wm-platform/src/native_monitor.rs
@@ -7,7 +7,7 @@ use windows::{
Graphics::Gdi::{
EnumDisplayDevicesW, EnumDisplayMonitors, GetMonitorInfoW,
MonitorFromWindow, DISPLAY_DEVICEW, DISPLAY_DEVICE_ACTIVE, HDC,
- HMONITOR, MONITORINFOEXW, MONITOR_DEFAULTTONEAREST,
+ HMONITOR, MONITORINFO, MONITORINFOEXW, MONITOR_DEFAULTTONEAREST,
},
UI::{
HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI},
@@ -35,6 +35,7 @@ struct MonitorInfo {
}
impl NativeMonitor {
+ #[must_use]
pub fn new(handle: isize) -> Self {
Self {
handle,
@@ -72,14 +73,19 @@ impl NativeMonitor {
fn monitor_info(&self) -> anyhow::Result<&MonitorInfo> {
self.info.get_or_try_init(|| {
- let mut monitor_info = MONITORINFOEXW::default();
- monitor_info.monitorInfo.cbSize =
- std::mem::size_of::<MONITORINFOEXW>() as u32;
+ let mut monitor_info = MONITORINFOEXW {
+ monitorInfo: MONITORINFO {
+ #[allow(clippy::cast_possible_truncation)]
+ cbSize: std::mem::size_of::<MONITORINFOEXW>() as u32,
+ ..Default::default()
+ },
+ ..Default::default()
+ };
unsafe {
GetMonitorInfoW(
HMONITOR(self.handle),
- &mut monitor_info as *mut _ as _,
+ std::ptr::from_mut(&mut monitor_info).cast(),
)
}
.ok()?;
@@ -87,6 +93,7 @@ impl NativeMonitor {
// Get the display devices associated with the monitor.
let mut display_devices = (0..)
.map_while(|index| {
+ #[allow(clippy::cast_possible_truncation)]
let mut display_device = DISPLAY_DEVICEW {
cb: std::mem::size_of::<DISPLAY_DEVICEW>() as u32,
..Default::default()
@@ -110,25 +117,24 @@ impl NativeMonitor {
.filter(|device| device.StateFlags & DISPLAY_DEVICE_ACTIVE != 0);
// Get the device path and hardware ID from the first valid device.
- let (device_path, hardware_id) = display_devices
- .next()
- .map(|device| {
+ let (device_path, hardware_id) =
+ display_devices.next().map_or((None, None), |device| {
let device_path = String::from_utf16_lossy(&device.DeviceID)
.trim_end_matches('\0')
.to_string();
let hardware_id = device_path
- .split("#")
+ .split('#')
.collect::<Vec<_>>()
.get(1)
- .map(|id| id.to_string());
+ .map(|id| (*id).to_string());
(Some(device_path), hardware_id)
- })
- .unwrap_or((None, None));
+ });
let device_name = String::from_utf16_lossy(&monitor_info.szDevice);
let dpi = monitor_dpi(self.handle)?;
+ #[allow(clippy::cast_precision_loss)]
let scale_factor = dpi as f32 / 96.0;
let rc_monitor = monitor_info.monitorInfo.rcMonitor;
@@ -187,7 +193,7 @@ fn available_monitor_handles() -> anyhow::Result<Vec<isize>> {
HDC::default(),
None,
Some(available_monitor_handles_proc),
- LPARAM(&mut monitors as *mut _ as _),
+ LPARAM(std::ptr::from_mut(&mut monitors) as _),
)
}
.ok()?;
@@ -208,6 +214,7 @@ extern "system" fn available_monitor_handles_proc(
true.into()
}
+#[must_use]
pub fn nearest_monitor(window_handle: isize) -> NativeMonitor {
let handle = unsafe {
MonitorFromWindow(HWND(window_handle), MONITOR_DEFAULTTONEAREST)
diff --git a/packages/wm-platform/src/native_window.rs b/packages/wm-platform/src/native_window.rs
index 7f13de8c..c8fd37b9 100644
--- a/packages/wm-platform/src/native_window.rs
+++ b/packages/wm-platform/src/native_window.rs
@@ -66,6 +66,7 @@ pub struct NativeWindow {
impl NativeWindow {
/// Creates a new `NativeWindow` instance with the given window handle.
+ #[must_use]
pub fn new(handle: isize) -> Self {
Self {
handle,
@@ -94,9 +95,12 @@ impl NativeWindow {
/// Gets the window's title. If the window is invalid, returns an empty
/// string.
+ #[allow(clippy::unnecessary_wraps)]
fn updated_title(&self) -> anyhow::Result<String> {
let mut text: [u16; 512] = [0; 512];
let length = unsafe { GetWindowTextW(HWND(self.handle), &mut text) };
+
+ #[allow(clippy::cast_sign_loss)]
Ok(String::from_utf16_lossy(&text[..length as usize]))
}
@@ -121,7 +125,7 @@ impl NativeWindow {
}?;
let mut buffer = [0u16; 256];
- let mut length = buffer.len() as u32;
+ let mut length = u32::try_from(buffer.len())?;
unsafe {
QueryFullProcessImageNameW(
process_handle,
@@ -137,7 +141,7 @@ impl NativeWindow {
exe_path
.split('\\')
- .last()
+ .next_back()
.map(|file_name| {
file_name.split('.').next().unwrap_or(file_name).to_string()
})
@@ -160,6 +164,7 @@ impl NativeWindow {
return Err(windows::core::Error::from_win32().into());
}
+ #[allow(clippy::cast_sign_loss)]
let class_name = String::from_utf16_lossy(&buffer[..result as usize]);
Ok(class_name)
}
@@ -180,10 +185,11 @@ impl NativeWindow {
let mut cloaked = 0u32;
unsafe {
+ #[allow(clippy::cast_possible_truncation)]
DwmGetWindowAttribute(
HWND(self.handle),
DWMWA_CLOAKED,
- &mut cloaked as *mut u32 as _,
+ std::ptr::from_mut::<u32>(&mut cloaked).cast(),
std::mem::size_of::<u32>() as u32,
)
}?;
@@ -242,6 +248,7 @@ impl NativeWindow {
}
/// Whether the window is minimized.
+ #[allow(clippy::unnecessary_wraps)]
fn updated_is_minimized(&self) -> anyhow::Result<bool> {
Ok(unsafe { IsIconic(HWND(self.handle)) }.as_bool())
}
@@ -261,11 +268,13 @@ impl NativeWindow {
}
/// Whether the window is maximized.
+ #[allow(clippy::unnecessary_wraps)]
fn updated_is_maximized(&self) -> anyhow::Result<bool> {
Ok(unsafe { IsZoomed(HWND(self.handle)) }.as_bool())
}
/// Whether the window has resize handles.
+ #[must_use]
pub fn is_resizable(&self) -> bool {
self.has_window_style(WS_THICKFRAME)
}
@@ -301,12 +310,14 @@ impl NativeWindow {
..Default::default()
},
},
- ..Default::default()
}];
// Bypass restriction for setting the foreground window by sending an
// input to our own process first.
- unsafe { SendInput(&input, std::mem::size_of::<INPUT>() as i32) };
+ #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
+ unsafe {
+ SendInput(&input, std::mem::size_of::<INPUT>() as i32)
+ };
// Set as the foreground window.
unsafe { SetForegroundWindow(HWND(self.handle)) }.ok()?;
@@ -324,10 +335,11 @@ impl NativeWindow {
};
unsafe {
+ #[allow(clippy::cast_possible_truncation)]
DwmSetWindowAttribute(
HWND(self.handle),
DWMWA_BORDER_COLOR,
- &bgr as *const _ as _,
+ std::ptr::from_ref(&bgr).cast(),
std::mem::size_of::<u32>() as u32,
)?;
}
@@ -347,10 +359,11 @@ impl NativeWindow {
};
unsafe {
+ #[allow(clippy::cast_possible_truncation)]
DwmSetWindowAttribute(
HWND(self.handle),
DWMWA_WINDOW_CORNER_PREFERENCE,
- &(corner_preference.0) as *const _ as _,
+ std::ptr::from_ref(&(corner_preference.0)).cast(),
std::mem::size_of::<i32>() as u32,
)?;
}
@@ -364,9 +377,11 @@ impl NativeWindow {
) -> anyhow::Result<()> {
let style = unsafe { GetWindowLongPtrW(HWND(self.handle), GWL_STYLE) };
- let new_style = match visible {
- true => style | (WS_DLGFRAME.0 as isize),
- false => style & !(WS_DLGFRAME.0 as isize),
+ #[allow(clippy::cast_possible_wrap)]
+ let new_style = if visible {
+ style | (WS_DLGFRAME.0 as isize)
+ } else {
+ style & !(WS_DLGFRAME.0 as isize)
};
if new_style != style {
@@ -397,12 +412,13 @@ impl NativeWindow {
pub fn set_opacity(
&self,
- opacity_value: OpacityValue,
+ opacity_value: &OpacityValue,
) -> anyhow::Result<()> {
// Make the window layered if it isn't already.
let ex_style =
unsafe { GetWindowLongPtrW(HWND(self.handle), GWL_EXSTYLE) };
+ #[allow(clippy::cast_possible_wrap)]
if ex_style & WS_EX_LAYERED.0 as isize == 0 {
unsafe {
SetWindowLongPtrW(
@@ -434,14 +450,15 @@ impl NativeWindow {
// Calculate the new opacity value.
let new_opacity = if opacity_value.is_delta {
- previous_opacity as i16 + opacity_value.amount
+ i16::from(previous_opacity) + opacity_value.amount
} else {
opacity_value.amount
};
// Clamp new_opacity to a u8.
+ #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
let new_opacity =
- new_opacity.clamp(u8::MIN as i16, u8::MAX as i16) as u8;
+ new_opacity.clamp(i16::from(u8::MIN), i16::from(u8::MAX)) as u8;
// Set the new opacity if needed.
if new_opacity != previous_opacity {
@@ -482,25 +499,25 @@ impl NativeWindow {
let mut rect = RECT::default();
let dwm_res = unsafe {
+ #[allow(clippy::cast_possible_truncation)]
DwmGetWindowAttribute(
HWND(self.handle),
DWMWA_EXTENDED_FRAME_BOUNDS,
- &mut rect as *mut _ as _,
+ std::ptr::from_mut(&mut rect).cast(),
std::mem::size_of::<RECT>() as u32,
)
};
- match dwm_res {
- Ok(_) => Ok(Rect::from_ltrb(
+ if let Ok(()) = dwm_res {
+ Ok(Rect::from_ltrb(
rect.left,
rect.top,
rect.right,
rect.bottom,
- )),
- _ => {
- warn!("Failed to get window's frame position. Falling back to border position.");
- self.border_position()
- }
+ ))
+ } else {
+ warn!("Failed to get window's frame position. Falling back to border position.");
+ self.border_position()
}
}
@@ -526,7 +543,12 @@ impl NativeWindow {
fn updated_border_position(&self) -> anyhow::Result<Rect> {
let mut rect = RECT::default();
- unsafe { GetWindowRect(HWND(self.handle), &mut rect as *mut _ as _) }?;
+ unsafe {
+ GetWindowRect(
+ HWND(self.handle),
+ std::ptr::from_mut(&mut rect).cast(),
+ )
+ }?;
Ok(Rect::from_ltrb(
rect.left,
@@ -554,18 +576,23 @@ impl NativeWindow {
let current_style =
unsafe { GetWindowLongPtrW(HWND(self.handle), GWL_STYLE) };
- (current_style & style.0 as isize) != 0
+ #[allow(clippy::cast_possible_wrap)]
+ let style = style.0 as isize;
+ (current_style & style) != 0
}
fn has_window_style_ex(&self, style: WINDOW_EX_STYLE) -> bool {
let current_style =
unsafe { GetWindowLongPtrW(HWND(self.handle), GWL_EXSTYLE) };
- (current_style & style.0 as isize) != 0
+ #[allow(clippy::cast_possible_wrap)]
+ let style = style.0 as isize;
+ (current_style & style) != 0
}
pub fn restore_to_position(&self, rect: &Rect) -> anyhow::Result<()> {
let placement = WINDOWPLACEMENT {
+ #[allow(clippy::cast_possible_truncation)]
length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
flags: WPF_ASYNCWINDOWPLACEMENT,
showCmd: SW_RESTORE.0 as u32,
@@ -648,9 +675,9 @@ impl NativeWindow {
/// Adds or removes the window from the native taskbar.
///
- /// Hidden windows (SW_HIDE) cannot be forced to be shown in the taskbar.
- /// Cloaked windows are normally always shown in the taskbar, but can be
- /// manually toggled.
+ /// Hidden windows (`SW_HIDE`) cannot be forced to be shown in the
+ /// taskbar. Cloaked windows are normally always shown in the taskbar,
+ /// but can be manually toggled.
pub fn set_taskbar_visibility(
&self,
visible: bool,
@@ -808,7 +835,7 @@ pub fn available_window_handles() -> anyhow::Result<Vec<isize>> {
unsafe {
EnumWindows(
Some(available_window_handles_proc),
- LPARAM(&mut handles as *mut _ as _),
+ LPARAM(std::ptr::from_mut(&mut handles) as _),
)
}?;
diff --git a/packages/wm-platform/src/platform.rs b/packages/wm-platform/src/platform.rs
index 21f30293..675f9a09 100644
--- a/packages/wm-platform/src/platform.rs
+++ b/packages/wm-platform/src/platform.rs
@@ -26,8 +26,8 @@ use windows::{
CS_VREDRAW, CW_USEDEFAULT, GA_ROOT, MB_ICONERROR, MB_OK,
MB_SYSTEMMODAL, MSG, PM_REMOVE, SPIF_SENDCHANGE,
SPIF_UPDATEINIFILE, SPI_GETANIMATION, SPI_SETANIMATION, SW_HIDE,
- SW_NORMAL, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, WM_QUIT,
- WNDCLASSW, WNDPROC, WS_OVERLAPPEDWINDOW,
+ SW_NORMAL, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, WINDOW_EX_STYLE,
+ WM_QUIT, WNDCLASSW, WNDPROC, WS_OVERLAPPEDWINDOW,
},
},
},
@@ -45,6 +45,7 @@ pub struct Platform;
impl Platform {
/// Gets the `NativeWindow` instance of the currently focused window.
+ #[must_use]
pub fn foreground_window() -> NativeWindow {
let handle = unsafe { GetForegroundWindow() };
NativeWindow::new(handle.0)
@@ -55,6 +56,7 @@ impl Platform {
/// This is the explorer.exe wallpaper window (i.e. "Progman"). If
/// explorer.exe isn't running, then default to the desktop window below
/// the wallpaper window.
+ #[must_use]
pub fn desktop_window() -> NativeWindow {
let handle = match unsafe { GetShellWindow() } {
HWND(0) => unsafe { GetDesktopWindow() },
@@ -99,6 +101,7 @@ impl Platform {
)
}
+ #[must_use]
pub fn nearest_monitor(window: &NativeWindow) -> NativeMonitor {
native_monitor::nearest_monitor(window.handle)
}
@@ -184,7 +187,7 @@ impl Platform {
let handle = unsafe {
CreateWindowExW(
- Default::default(),
+ WINDOW_EX_STYLE::default(),
w!("MessageWindow"),
w!("MessageWindow"),
WS_OVERLAPPEDWINDOW,
@@ -273,6 +276,7 @@ impl Platform {
/// Note that this is a global system setting.
pub fn window_animations_enabled() -> anyhow::Result<bool> {
let mut animation_info = ANIMATIONINFO {
+ #[allow(clippy::cast_possible_truncation)]
cbSize: std::mem::size_of::<ANIMATIONINFO>() as u32,
iMinAnimate: 0,
};
@@ -281,7 +285,7 @@ impl Platform {
SystemParametersInfoW(
SPI_GETANIMATION,
animation_info.cbSize,
- Some(&mut animation_info as *mut _ as _),
+ Some(std::ptr::from_mut(&mut animation_info).cast()),
SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
)
}?;
@@ -296,15 +300,16 @@ impl Platform {
enable: bool,
) -> anyhow::Result<()> {
let mut animation_info = ANIMATIONINFO {
+ #[allow(clippy::cast_possible_truncation)]
cbSize: std::mem::size_of::<ANIMATIONINFO>() as u32,
- iMinAnimate: if enable { 1 } else { 0 },
+ iMinAnimate: i32::from(enable),
};
unsafe {
SystemParametersInfoW(
SPI_SETANIMATION,
animation_info.cbSize,
- Some(&mut animation_info as *mut _ as _),
+ Some(std::ptr::from_mut(&mut animation_info).cast()),
SPIF_UPDATEINIFILE | SPIF_SENDCHANGE,
)
}?;
@@ -382,11 +387,11 @@ impl Platform {
// 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("\"") {
+ 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)
+ format!("Command doesn't have an ending `\"`: '{command}'.")
})?;
return Ok((
@@ -400,7 +405,7 @@ impl Platform {
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));
+ return Ok(((*first_part).to_string(), args));
}
}
@@ -446,6 +451,7 @@ impl Platform {
// handles held by our process (e.g. the IPC server port) until the
// subprocess exits.
let mut exec_info = SHELLEXECUTEINFOW {
+ #[allow(clippy::cast_possible_truncation)]
cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
lpFile: PCWSTR(program_wide.as_ptr()),
lpParameters: PCWSTR(args_wide.as_ptr()),
diff --git a/packages/wm-platform/src/single_instance.rs b/packages/wm-platform/src/single_instance.rs
index dcaa53fc..3a54775e 100644
--- a/packages/wm-platform/src/single_instance.rs
+++ b/packages/wm-platform/src/single_instance.rs
@@ -38,6 +38,7 @@ impl SingleInstance {
}
/// Gets whether there is an active instance of the application.
+ #[must_use]
pub fn is_running() -> bool {
let res = unsafe {
OpenMutexW(SYNCHRONIZATION_ACCESS_RIGHTS::default(), false, APP_GUID)
diff --git a/packages/wm-platform/src/window_event_hook.rs b/packages/wm-platform/src/window_event_hook.rs
index 06d8f7d6..19af532b 100644
--- a/packages/wm-platform/src/window_event_hook.rs
+++ b/packages/wm-platform/src/window_event_hook.rs
@@ -48,9 +48,12 @@ impl WindowEventHook {
Ok(win_event_hook)
}
- /// Starts a window event hook on the current thread.
+ /// Starts a window event hook on the current thread. This assumes that a
+ /// message loop is currently running.
///
- /// Assumes that a message loop is currently running.
+ /// # Panics
+ ///
+ /// If the internal mutex is poisoned.
pub fn start(&self) -> anyhow::Result<()> {
*self.hook_handles.lock().unwrap() = Self::hook_win_events()?;
Ok(())
@@ -141,6 +144,10 @@ impl WindowEventHook {
}
/// Stops the window event hook and unhooks from all window events.
+ ///
+ /// # Panics
+ ///
+ /// If the internal mutex is poisoned.
pub fn stop(&self) -> anyhow::Result<()> {
for hook_handle in self.hook_handles.lock().unwrap().drain(..) {
unsafe { UnhookWinEvent(hook_handle) }.ok()?;
diff --git a/packages/wm-watcher/build.rs b/packages/wm-watcher/build.rs
index 8526fa23..2ecbffb1 100644
--- a/packages/wm-watcher/build.rs
+++ b/packages/wm-watcher/build.rs
@@ -22,13 +22,13 @@ fn main() {
let [major, minor, patch] =
<[u16; 3]>::try_from(version_parts).unwrap_or([0, 0, 0]);
- let version_str = format!("{}.{}.{}.0", major, minor, patch);
+ let version_str = format!("{major}.{minor}.{patch}.0");
res.set("FileVersion", &version_str);
res.set("ProductVersion", &version_str);
- let version_u64 = ((major as u64) << 48)
- | ((minor as u64) << 32)
- | ((patch as u64) << 16);
+ let version_u64 = (u64::from(major) << 48)
+ | (u64::from(minor) << 32)
+ | (u64::from(patch) << 16);
res.set_version_info(VersionInfo::FILEVERSION, version_u64);
res.set_version_info(VersionInfo::PRODUCTVERSION, version_u64);
diff --git a/packages/wm-watcher/src/main.rs b/packages/wm-watcher/src/main.rs
index 116bc39d..0b9d691b 100644
--- a/packages/wm-watcher/src/main.rs
+++ b/packages/wm-watcher/src/main.rs
@@ -6,6 +6,7 @@
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
+#![warn(clippy::all, clippy::pedantic)]
use anyhow::{bail, Context};
use tracing::info;
@@ -31,7 +32,7 @@ async fn main() -> anyhow::Result<()> {
watch_managed_handles(&mut client, &mut managed_handles).await;
match subscribe_res {
- Ok(_) => info!("WM exited successfully. Skipping watcher cleanup."),
+ Ok(()) => info!("WM exited successfully. Skipping watcher cleanup."),
Err(err) => {
info!("Running watcher cleanup. WM exited unexpectedly: {}", err);
diff --git a/packages/wm/build.rs b/packages/wm/build.rs
index c42bdb9e..0b68158b 100644
--- a/packages/wm/build.rs
+++ b/packages/wm/build.rs
@@ -34,7 +34,7 @@ fn main() {
<asmv3:trustInfo>
<security>
<requestedPrivileges>
- <requestedExecutionLevel level="asInvoker" uiAccess="{}" />
+ <requestedExecutionLevel level="asInvoker" uiAccess="{ui_access}" />
</requestedPrivileges>
</security>
</asmv3:trustInfo>
@@ -49,8 +49,7 @@ fn main() {
</windowsSettings>
</asmv3:application>
</assembly>
-"#,
- ui_access
+"#
);
res.set_manifest(&manifest_str);
@@ -72,13 +71,13 @@ fn main() {
let [major, minor, patch] =
<[u16; 3]>::try_from(version_parts).unwrap_or([0, 0, 0]);
- let version_str = format!("{}.{}.{}.0", major, minor, patch);
+ let version_str = format!("{major}.{minor}.{patch}.0");
res.set("FileVersion", &version_str);
res.set("ProductVersion", &version_str);
- let version_u64 = ((major as u64) << 48)
- | ((minor as u64) << 32)
- | ((patch as u64) << 16);
+ let version_u64 = (u64::from(major) << 48)
+ | (u64::from(minor) << 32)
+ | (u64::from(patch) << 16);
res.set_version_info(VersionInfo::FILEVERSION, version_u64);
res.set_version_info(VersionInfo::PRODUCTVERSION, version_u64);
diff --git a/packages/wm/src/commands/container/attach_container.rs b/packages/wm/src/commands/container/attach_container.rs
index 3358b2f4..ee230f3a 100644
--- a/packages/wm/src/commands/container/attach_container.rs
+++ b/packages/wm/src/commands/container/attach_container.rs
@@ -47,6 +47,7 @@ pub fn attach_container(
// Set initial tiling size to 0, and then size up the container
// to the target size.
+ #[allow(clippy::cast_precision_loss)]
let target_size = 1.0 / (tiling_siblings.len() + 1) as f32;
child.set_tiling_size(0.0);
resize_tiling_container(&child, target_size);
diff --git a/packages/wm/src/commands/container/detach_container.rs b/packages/wm/src/commands/container/detach_container.rs
index eaf13d58..5c173c78 100644
--- a/packages/wm/src/commands/container/detach_container.rs
+++ b/packages/wm/src/commands/container/detach_container.rs
@@ -10,6 +10,7 @@ use crate::{
///
/// If the container is a tiling container, the siblings will be resized to
/// fill the freed up space. Will flatten empty parent split containers.
+#[allow(clippy::needless_pass_by_value)]
pub fn detach_container(child_to_remove: Container) -> anyhow::Result<()> {
// Flatten the parent split container if it'll be empty after removing
// the child.
diff --git a/packages/wm/src/commands/container/flatten_child_split_containers.rs b/packages/wm/src/commands/container/flatten_child_split_containers.rs
index 0ade487a..ff825b59 100644
--- a/packages/wm/src/commands/container/flatten_child_split_containers.rs
+++ b/packages/wm/src/commands/container/flatten_child_split_containers.rs
@@ -14,7 +14,7 @@ use crate::{
/// H[V[1]] -> V[1]
/// ```
pub fn flatten_child_split_containers(
- parent: Container,
+ parent: &Container,
) -> anyhow::Result<()> {
if let Ok(parent) = parent.as_direction_container() {
// Get children that are either tiling windows or split containers.
@@ -24,36 +24,33 @@ pub fn flatten_child_split_containers(
.filter(|child| child.is_tiling_window() || child.is_split())
.collect::<Vec<_>>();
- match tiling_children.len() {
- 1 => {
- // Handle case where the parent is a split container and has a
- // single split container child.
- if let Some(split_child) = tiling_children[0].as_split() {
- flatten_split_container(split_child.clone())?;
- parent.set_tiling_direction(parent.tiling_direction().inverse());
- }
+ if tiling_children.len() == 1 {
+ // Handle case where the parent is a split container and has a
+ // single split container child.
+ if let Some(split_child) = tiling_children[0].as_split() {
+ flatten_split_container(split_child.clone())?;
+ parent.set_tiling_direction(parent.tiling_direction().inverse());
}
- _ => {
- let split_children = tiling_children
- .into_iter()
- .filter_map(|child| child.as_split().cloned())
- .collect::<Vec<_>>();
+ } else {
+ let split_children = tiling_children
+ .into_iter()
+ .filter_map(|child| child.as_split().cloned())
+ .collect::<Vec<_>>();
- for split_child in split_children.iter().filter(|split_child| {
- split_child.tiling_direction() == parent.tiling_direction()
- }) {
- // Additionally flatten redundant top-level split containers in
- // the child.
- if split_child.child_count() == 1 {
- if let Some(split_grandchild) =
- split_child.children()[0].as_split()
- {
- flatten_split_container(split_grandchild.clone())?;
- }
+ for split_child in split_children.iter().filter(|split_child| {
+ split_child.tiling_direction() == parent.tiling_direction()
+ }) {
+ // Additionally flatten redundant top-level split containers in
+ // the child.
+ if split_child.child_count() == 1 {
+ if let Some(split_grandchild) =
+ split_child.children()[0].as_split()
+ {
+ flatten_split_container(split_grandchild.clone())?;
}
-
- flatten_split_container(split_child.clone())?;
}
+
+ flatten_split_container(split_child.clone())?;
}
}
}
diff --git a/packages/wm/src/commands/container/flatten_split_container.rs b/packages/wm/src/commands/container/flatten_split_container.rs
index 82c341a2..40254c6b 100644
--- a/packages/wm/src/commands/container/flatten_split_container.rs
+++ b/packages/wm/src/commands/container/flatten_split_container.rs
@@ -11,6 +11,7 @@ use crate::{
/// into the parent container.
///
/// The children will be resized to fit the size of the split container.
+#[allow(clippy::needless_pass_by_value)]
pub fn flatten_split_container(
split_container: SplitContainer,
) -> anyhow::Result<()> {
diff --git a/packages/wm/src/commands/container/focus_in_direction.rs b/packages/wm/src/commands/container/focus_in_direction.rs
index 006e0bf8..215a0143 100644
--- a/packages/wm/src/commands/container/focus_in_direction.rs
+++ b/packages/wm/src/commands/container/focus_in_direction.rs
@@ -9,7 +9,7 @@ use crate::{
};
pub fn focus_in_direction(
- origin_container: Container,
+ origin_container: &Container,
direction: &Direction,
state: &mut WmState,
) -> anyhow::Result<()> {
@@ -17,11 +17,10 @@ pub fn focus_in_direction(
Container::TilingWindow(_) => {
// If a suitable focus target isn't found in the current workspace,
// attempt to find a workspace in the given direction.
- tiling_focus_target(origin_container.clone(), direction)?
- .map_or_else(
- || workspace_focus_target(origin_container, direction, state),
- |container| Ok(Some(container)),
- )?
+ tiling_focus_target(origin_container, direction)?.map_or_else(
+ || workspace_focus_target(origin_container, direction, state),
+ |container| Ok(Some(container)),
+ )?
}
Container::NonTilingWindow(ref non_tiling_window) => {
match non_tiling_window.state() {
@@ -42,7 +41,7 @@ pub fn focus_in_direction(
// Set focus to the target container.
if let Some(focus_target) = focus_target {
- set_focused_descendant(focus_target.clone(), None);
+ set_focused_descendant(&focus_target, None);
state.pending_sync.focus_change = true;
state.pending_sync.cursor_jump = true;
}
@@ -51,11 +50,11 @@ pub fn focus_in_direction(
}
fn floating_focus_target(
- origin_container: Container,
+ origin_container: &Container,
direction: &Direction,
) -> Option<Container> {
let is_floating = |sibling: &Container| {
- sibling.as_non_tiling_window().map_or(false, |window| {
+ sibling.as_non_tiling_window().is_some_and(|window| {
matches!(window.state(), WindowState::Floating(_))
})
};
@@ -81,7 +80,7 @@ fn floating_focus_target(
/// Gets a focus target within the current workspace. Traverse upwards from
/// the origin container to find an adjacent container that can be focused.
fn tiling_focus_target(
- origin_container: Container,
+ origin_container: &Container,
direction: &Direction,
) -> anyhow::Result<Option<Container>> {
let tiling_direction = TilingDirection::from_direction(direction);
@@ -135,7 +134,7 @@ fn tiling_focus_target(
/// always return a tiling container. This makes it different from the
/// `focus_workspace` command with `FocusWorkspaceTarget::Direction`.
fn workspace_focus_target(
- origin_container: Container,
+ origin_container: &Container,
direction: &Direction,
state: &WmState,
) -> anyhow::Result<Option<Container>> {
diff --git a/packages/wm/src/commands/container/move_container_within_tree.rs b/packages/wm/src/commands/container/move_container_within_tree.rs
index 005c8f9c..4b039b51 100644
--- a/packages/wm/src/commands/container/move_container_within_tree.rs
+++ b/packages/wm/src/commands/container/move_container_within_tree.rs
@@ -21,8 +21,8 @@ use crate::{models::Container, traits::CommonGetters, wm_state::WmState};
/// example, in the layout V[1 H[2]] where container 1 is moved down, the
/// parent gets removed resulting in V[1 2].
pub fn move_container_within_tree(
- container_to_move: Container,
- target_parent: Container,
+ container_to_move: &Container,
+ target_parent: &Container,
target_index: usize,
state: &WmState,
) -> anyhow::Result<()> {
@@ -33,12 +33,12 @@ pub fn move_container_within_tree(
// Get lowest common ancestor (LCA) between `container_to_move` and
// `target_parent`. This could be the `target_parent` itself.
let lowest_common_ancestor =
- lowest_common_ancestor(&container_to_move, &target_parent)
+ lowest_common_ancestor(container_to_move, target_parent)
.context("No common ancestor between containers.")?;
// If the container is already a child of the target parent, then shift
// it to the target index.
- if container_to_move.parent().context("No parent.")? == target_parent {
+ if container_to_move.parent().context("No parent.")? == *target_parent {
target_parent
.borrow_children_mut()
.shift_to_index(target_index, container_to_move.clone());
@@ -54,10 +54,10 @@ pub fn move_container_within_tree(
// Handle case where target parent is the LCA. For example, when swapping
// sibling containers or moving a container to a direct ancestor.
- if target_parent == lowest_common_ancestor {
+ if *target_parent == lowest_common_ancestor {
return move_to_lowest_common_ancestor(
container_to_move,
- lowest_common_ancestor,
+ &lowest_common_ancestor,
target_index,
state,
);
@@ -83,7 +83,7 @@ pub fn move_container_within_tree(
// Get whether the container is the focused descendant in its original
// subtree from the LCA.
- let is_focused_descendant = container_to_move
+ let is_focused_descendant = *container_to_move
== container_to_move_ancestor
|| container_to_move
.has_focus(Some(container_to_move_ancestor.clone()));
@@ -106,8 +106,8 @@ pub fn move_container_within_tree(
// not the last focused within that subtree).
if is_subtree_focused {
set_focused_descendant(
- container_to_move.clone(),
- Some(target_parent_ancestor.clone()),
+ container_to_move,
+ Some(&target_parent_ancestor),
);
}
@@ -124,7 +124,7 @@ pub fn move_container_within_tree(
// For example, in the layout V[1 H[2]] where container 1 is moved down
// to become V[H[1 2]], this will then need to be flattened to V[1 2].
for ancestor in ancestors.iter().rev() {
- flatten_child_split_containers(ancestor.clone())?;
+ flatten_child_split_containers(ancestor)?;
}
if container_to_move.has_focus(None) {
@@ -137,8 +137,8 @@ pub fn move_container_within_tree(
}
fn move_to_lowest_common_ancestor(
- container_to_move: Container,
- lowest_common_ancestor: Container,
+ container_to_move: &Container,
+ lowest_common_ancestor: &Container,
target_index: usize,
state: &WmState,
) -> anyhow::Result<()> {
diff --git a/packages/wm/src/commands/container/replace_container.rs b/packages/wm/src/commands/container/replace_container.rs
index 6e6dc24e..27e62595 100644
--- a/packages/wm/src/commands/container/replace_container.rs
+++ b/packages/wm/src/commands/container/replace_container.rs
@@ -11,8 +11,8 @@ use crate::{
///
/// The replaced container will be detached from the tree.
pub fn replace_container(
- replacement_container: Container,
- target_parent: Container,
+ replacement_container: &Container,
+ target_parent: &Container,
target_index: usize,
) -> anyhow::Result<()> {
if !replacement_container.is_detached() {
@@ -25,7 +25,7 @@ pub fn replace_container(
.children()
.get(target_index)
.cloned()
- .with_context(|| format!("No container at index {}.", target_index))?;
+ .with_context(|| format!("No container at index {target_index}."))?;
let focus_index = container_to_replace.focus_index();
let tiling_size = container_to_replace
@@ -39,8 +39,8 @@ pub fn replace_container(
detach_container(container_to_replace)?;
attach_container(
- &replacement_container,
- &target_parent,
+ replacement_container,
+ target_parent,
Some(target_index),
)?;
diff --git a/packages/wm/src/commands/container/resize_tiling_container.rs b/packages/wm/src/commands/container/resize_tiling_container.rs
index 5b839797..dfcdc7c8 100644
--- a/packages/wm/src/commands/container/resize_tiling_container.rs
+++ b/packages/wm/src/commands/container/resize_tiling_container.rs
@@ -18,6 +18,7 @@ pub fn resize_tiling_container(
// Prevent the container from being smaller than the minimum size, and
// larger than the space available from sibling containers.
+ #[allow(clippy::cast_precision_loss)]
let clamped_target_size = target_size.clamp(
MIN_TILING_SIZE,
1. - (tiling_siblings.len() as f32 * MIN_TILING_SIZE),
diff --git a/packages/wm/src/commands/container/set_focused_descendant.rs b/packages/wm/src/commands/container/set_focused_descendant.rs
index df96e90d..4ef207d9 100644
--- a/packages/wm/src/commands/container/set_focused_descendant.rs
+++ b/packages/wm/src/commands/container/set_focused_descendant.rs
@@ -5,10 +5,10 @@ use crate::{models::Container, traits::CommonGetters};
/// Set a given container as the focused container up to and including the
/// end ancestor.
pub fn set_focused_descendant(
- focused_descendant: Container,
- end_ancestor: Option<Container>,
+ focused_descendant: &Container,
+ end_ancestor: Option<&Container>,
) {
- let mut target = focused_descendant;
+ let mut target = focused_descendant.clone();
// Traverse upwards, shifting the container's ancestors to the front in
// their focus order.
@@ -20,8 +20,7 @@ pub fn set_focused_descendant(
// Exit if we've reached the end ancestor.
if end_ancestor
.as_ref()
- .map(|end_ancestor| target.id() == end_ancestor.id())
- .unwrap_or(false)
+ .is_some_and(|end_ancestor| target.id() == end_ancestor.id())
{
break;
}
diff --git a/packages/wm/src/commands/container/toggle_tiling_direction.rs b/packages/wm/src/commands/container/toggle_tiling_direction.rs
index a0fbb7fa..cff1af1a 100644
--- a/packages/wm/src/commands/container/toggle_tiling_direction.rs
+++ b/packages/wm/src/commands/container/toggle_tiling_direction.rs
@@ -72,9 +72,9 @@ fn toggle_window_direction(
);
wrap_in_split_container(
- split_container.clone(),
- parent.into(),
- vec![tiling_window.clone().into()],
+ &split_container,
+ &parent.into(),
+ &[tiling_window.into()],
)?;
Ok(split_container.into())
@@ -84,14 +84,15 @@ pub fn set_tiling_direction(
container: Container,
state: &mut WmState,
config: &UserConfig,
- tiling_direction: TilingDirection,
+ tiling_direction: &TilingDirection,
) -> anyhow::Result<()> {
let direction_container = container
.direction_container()
.context("No direction container.")?;
- match direction_container.tiling_direction() == tiling_direction {
- true => Ok(()),
- false => toggle_tiling_direction(container, state, config),
+ if direction_container.tiling_direction() == *tiling_direction {
+ Ok(())
+ } else {
+ toggle_tiling_direction(container, state, config)
}
}
diff --git a/packages/wm/src/commands/container/wrap_in_split_container.rs b/packages/wm/src/commands/container/wrap_in_split_container.rs
index 33c0f1da..ff55ec2f 100644
--- a/packages/wm/src/commands/container/wrap_in_split_container.rs
+++ b/packages/wm/src/commands/container/wrap_in_split_container.rs
@@ -8,13 +8,13 @@ use crate::{
};
pub fn wrap_in_split_container(
- split_container: SplitContainer,
- target_parent: Container,
- target_children: Vec<TilingContainer>,
+ split_container: &SplitContainer,
+ target_parent: &Container,
+ target_children: &[TilingContainer],
) -> anyhow::Result<()> {
let starting_index = target_children
.iter()
- .map(|child| child.index())
+ .map(CommonGetters::index)
.min()
.context("Failed to get starting index.")?;
@@ -24,7 +24,7 @@ pub fn wrap_in_split_container(
let starting_focus_index = target_children
.iter()
- .map(|child| child.focus_index())
+ .map(CommonGetters::focus_index)
.min()
.context("Failed to get starting focus index.")?;
@@ -35,19 +35,19 @@ pub fn wrap_in_split_container(
// Get the total tiling size amongst all children.
let total_tiling_size = target_children
.iter()
- .map(|child| child.tiling_size())
+ .map(TilingSizeGetters::tiling_size)
.sum::<f32>();
let target_children_ids = target_children
.iter()
- .map(|child| child.id())
+ .map(CommonGetters::id)
.collect::<Vec<_>>();
let sorted_focus_ids = target_parent
.borrow_child_focus_order()
.iter()
.filter(|id| target_children_ids.contains(id))
- .cloned()
+ .copied()
.collect::<VecDeque<_>>();
// Set the split container's parent and tiling size.
@@ -55,7 +55,7 @@ pub fn wrap_in_split_container(
split_container.set_tiling_size(total_tiling_size);
// Move the children from their original parent to the split container.
- for target_child in target_children.iter() {
+ for target_child in target_children {
*target_child.borrow_parent_mut() =
Some(split_container.clone().into());
diff --git a/packages/wm/src/commands/general/cycle_focus.rs b/packages/wm/src/commands/general/cycle_focus.rs
index 5f10980a..6f85e5f4 100644
--- a/packages/wm/src/commands/general/cycle_focus.rs
+++ b/packages/wm/src/commands/general/cycle_focus.rs
@@ -58,7 +58,7 @@ pub fn cycle_focus(
});
if let Some(window) = window_of_type {
- set_focused_descendant(window.into(), None);
+ set_focused_descendant(&window.into(), None);
state.pending_sync.focus_change = true;
break;
}
diff --git a/packages/wm/src/commands/general/enable_binding_mode.rs b/packages/wm/src/commands/general/enable_binding_mode.rs
index 0d8d5b37..bfeba563 100644
--- a/packages/wm/src/commands/general/enable_binding_mode.rs
+++ b/packages/wm/src/commands/general/enable_binding_mode.rs
@@ -14,7 +14,7 @@ pub fn enable_binding_mode(
.iter()
.find(|config| name == config.name)
.with_context(|| {
- format!("No binding mode found with the name '{}'.", name)
+ format!("No binding mode found with the name '{name}'.")
})?;
state.binding_modes = vec![binding_mode.clone()];
diff --git a/packages/wm/src/commands/general/platform_sync.rs b/packages/wm/src/commands/general/platform_sync.rs
index 0da83fd6..a06e6175 100644
--- a/packages/wm/src/commands/general/platform_sync.rs
+++ b/packages/wm/src/commands/general/platform_sync.rs
@@ -48,26 +48,26 @@ pub fn platform_sync(
|| state.pending_sync.reset_window_effects
{
if let Ok(window) = focused_container.as_window_container() {
- apply_window_effects(window, true, config);
+ apply_window_effects(&window, true, config);
}
// Get windows that should have the unfocused border applied to them.
// For the sake of performance, we only update the border of the
// previously focused window. If the `reset_window_effects` flag is
// passed, the unfocused border is applied to all unfocused windows.
- let unfocused_windows =
- match state.pending_sync.reset_window_effects {
- true => state.windows(),
- false => recent_focused_container
- .and_then(|container| container.as_window_container().ok())
- .into_iter()
- .collect(),
- }
- .into_iter()
- .filter(|window| window.id() != focused_container.id());
+ let unfocused_windows = if state.pending_sync.reset_window_effects {
+ state.windows()
+ } else {
+ recent_focused_container
+ .and_then(|container| container.as_window_container().ok())
+ .into_iter()
+ .collect()
+ }
+ .into_iter()
+ .filter(|window| window.id() != focused_container.id());
for window in unfocused_windows {
- apply_window_effects(window, false, config);
+ apply_window_effects(&window, false, config);
}
state.pending_sync.reset_window_effects = false;
@@ -183,7 +183,7 @@ fn jump_cursor(
focused_container.monitor().context("No monitor.")?;
let cursor_monitor =
- state.monitor_at_position(&Platform::mouse_position()?);
+ state.monitor_at_point(&Platform::mouse_position()?);
// Jump to the target monitor if the cursor is not already on it.
cursor_monitor
@@ -204,40 +204,41 @@ fn jump_cursor(
}
fn apply_window_effects(
- window: WindowContainer,
+ window: &WindowContainer,
is_focused: bool,
config: &UserConfig,
) {
let window_effects = &config.value.window_effects;
- let effect_config = match is_focused {
- true => &window_effects.focused_window,
- false => &window_effects.other_windows,
+ let effect_config = if is_focused {
+ &window_effects.focused_window
+ } else {
+ &window_effects.other_windows
};
// Skip if both focused + non-focused window effects are disabled.
if window_effects.focused_window.border.enabled
|| window_effects.other_windows.border.enabled
{
- apply_border_effect(&window, effect_config);
+ apply_border_effect(window, effect_config);
};
if window_effects.focused_window.hide_title_bar.enabled
|| window_effects.other_windows.hide_title_bar.enabled
{
- apply_hide_title_bar_effect(&window, effect_config);
+ apply_hide_title_bar_effect(window, effect_config);
}
if window_effects.focused_window.corner_style.enabled
|| window_effects.other_windows.corner_style.enabled
{
- apply_corner_effect(&window, effect_config);
+ apply_corner_effect(window, effect_config);
}
if window_effects.focused_window.transparency.enabled
|| window_effects.other_windows.transparency.enabled
{
- apply_transparency_effect(&window, effect_config);
+ apply_transparency_effect(window, effect_config);
}
}
@@ -245,9 +246,10 @@ fn apply_border_effect(
window: &WindowContainer,
effect_config: &WindowEffectConfig,
) {
- let border_color = match effect_config.border.enabled {
- true => Some(&effect_config.border.color),
- false => None,
+ let border_color = if effect_config.border.enabled {
+ Some(&effect_config.border.color)
+ } else {
+ None
};
_ = window.native().set_border_color(border_color);
@@ -276,9 +278,10 @@ fn apply_corner_effect(
window: &WindowContainer,
effect_config: &WindowEffectConfig,
) {
- let corner_style = match effect_config.corner_style.enabled {
- true => &effect_config.corner_style.style,
- false => &CornerStyle::Default,
+ let corner_style = if effect_config.corner_style.enabled {
+ &effect_config.corner_style.style
+ } else {
+ &CornerStyle::Default
};
_ = window.native().set_corner_style(corner_style);
@@ -291,14 +294,14 @@ fn apply_transparency_effect(
_ = window
.native()
.set_opacity(if effect_config.transparency.enabled {
- effect_config.transparency.opacity.clone()
+ &effect_config.transparency.opacity
} else {
// This code is only reached if the transparency effect is only
// enabled in one of the two window effect configurations. In
// this case, reset the opacity to default.
- OpacityValue {
+ &OpacityValue {
amount: 255,
is_delta: false,
}
- })
+ });
}
diff --git a/packages/wm/src/commands/general/reload_config.rs b/packages/wm/src/commands/general/reload_config.rs
index 18435ad7..4e19b99b 100644
--- a/packages/wm/src/commands/general/reload_config.rs
+++ b/packages/wm/src/commands/general/reload_config.rs
@@ -25,7 +25,7 @@ pub fn reload_config(
// Re-run window rules on all active windows.
for window in state.windows() {
window.set_done_window_rules(Vec::new());
- run_window_rules(window, WindowRuleEvent::Manage, state, config)?;
+ run_window_rules(window, &WindowRuleEvent::Manage, state, config)?;
}
update_workspace_configs(state, config)?;
@@ -120,7 +120,7 @@ fn update_workspace_configs(
if *workspace_config != workspace.config() {
workspace.set_config(workspace_config.clone());
- sort_workspaces(monitor, config)?;
+ sort_workspaces(&monitor, config)?;
state.emit_event(WmEvent::WorkspaceUpdated {
updated_workspace: workspace.to_dto()?,
diff --git a/packages/wm/src/commands/general/shell_exec.rs b/packages/wm/src/commands/general/shell_exec.rs
index 1d22428e..8d6f35ca 100644
--- a/packages/wm/src/commands/general/shell_exec.rs
+++ b/packages/wm/src/commands/general/shell_exec.rs
@@ -1,27 +1,15 @@
-use tracing::{error, info};
-
+use tracing::info;
use wm_platform::Platform;
pub fn shell_exec(command: &str, hide_window: bool) -> anyhow::Result<()> {
- let res =
- Platform::parse_command(command).and_then(|(program, args)| {
- info!("Parsed command program: '{}', args: '{}'.", program, args);
-
- Platform::run_command(&program, &args, hide_window)
- });
-
- match res {
- Ok(_) => {
- info!("Command executed successfully: {}.", command);
- }
- Err(err) => {
- let err_message =
- format!("Failed to execute '{}'.\n\nError: {}", command, err);
-
- error!(err_message);
- Platform::show_error_dialog("Non-fatal error", &err_message);
- }
- }
+ let (program, args) = Platform::parse_command(command)?;
+ info!("Parsed command program: '{}', args: '{}'.", program, args);
+
+ Platform::run_command(&program, &args, hide_window).map_err(|err| {
+ anyhow::anyhow!(format!(
+ "Failed to execute '{command}'.\n\nError: {err}"
+ ))
+ })?;
Ok(())
}
diff --git a/packages/wm/src/commands/general/toggle_pause.rs b/packages/wm/src/commands/general/toggle_pause.rs
index 7c51b5c9..e9f18e6a 100644
--- a/packages/wm/src/commands/general/toggle_pause.rs
+++ b/packages/wm/src/commands/general/toggle_pause.rs
@@ -3,7 +3,7 @@ use wm_common::WmEvent;
use crate::wm_state::WmState;
/// Pauses or unpauses the WM.
-pub fn toggle_pause(state: &mut WmState) -> anyhow::Result<()> {
+pub fn toggle_pause(state: &mut WmState) {
let new_paused_state = !state.is_paused;
state.is_paused = new_paused_state;
@@ -19,6 +19,4 @@ pub fn toggle_pause(state: &mut WmState) -> anyhow::Result<()> {
state.emit_event(WmEvent::PauseChanged {
is_paused: new_paused_state,
});
-
- Ok(())
}
diff --git a/packages/wm/src/commands/monitor/focus_monitor.rs b/packages/wm/src/commands/monitor/focus_monitor.rs
index 4b223dc8..05e5e1ee 100644
--- a/packages/wm/src/commands/monitor/focus_monitor.rs
+++ b/packages/wm/src/commands/monitor/focus_monitor.rs
@@ -14,7 +14,7 @@ pub fn focus_monitor(
let monitors = state.monitors();
let target_monitor = monitors.get(monitor_index).with_context(|| {
- format!("Monitor at index {} was not found.", monitor_index)
+ format!("Monitor at index {monitor_index} was not found.")
})?;
let workspace_name = target_monitor
diff --git a/packages/wm/src/commands/monitor/remove_monitor.rs b/packages/wm/src/commands/monitor/remove_monitor.rs
index 22da540a..bf2b8201 100644
--- a/packages/wm/src/commands/monitor/remove_monitor.rs
+++ b/packages/wm/src/commands/monitor/remove_monitor.rs
@@ -13,6 +13,7 @@ use crate::{
wm_state::WmState,
};
+#[allow(clippy::needless_pass_by_value)]
pub fn remove_monitor(
monitor: Monitor,
state: &mut WmState,
@@ -42,13 +43,13 @@ pub fn remove_monitor(
for workspace in workspaces_to_move {
// Move workspace to target monitor.
move_container_within_tree(
- workspace.clone().into(),
- target_monitor.clone().into(),
+ &workspace.clone().into(),
+ &target_monitor.clone().into(),
target_monitor.child_count(),
state,
)?;
- sort_workspaces(target_monitor.clone(), config)?;
+ sort_workspaces(&target_monitor, config)?;
state.emit_event(WmEvent::WorkspaceUpdated {
updated_workspace: workspace.to_dto()?,
diff --git a/packages/wm/src/commands/monitor/sort_monitors.rs b/packages/wm/src/commands/monitor/sort_monitors.rs
index bcc1b364..78c876ba 100644
--- a/packages/wm/src/commands/monitor/sort_monitors.rs
+++ b/packages/wm/src/commands/monitor/sort_monitors.rs
@@ -5,7 +5,7 @@ use crate::{
/// Sorts the root container's monitors from left-to-right and
/// top-to-bottom.
-pub fn sort_monitors(root: RootContainer) -> anyhow::Result<()> {
+pub fn sort_monitors(root: &RootContainer) -> anyhow::Result<()> {
let monitors = root.monitors();
// Create a tuple of monitors and their rects.
diff --git a/packages/wm/src/commands/monitor/update_monitor.rs b/packages/wm/src/commands/monitor/update_monitor.rs
index 7a5dc69e..07aaf033 100644
--- a/packages/wm/src/commands/monitor/update_monitor.rs
+++ b/packages/wm/src/commands/monitor/update_monitor.rs
@@ -5,7 +5,7 @@ use wm_platform::NativeMonitor;
use crate::{models::Monitor, wm_state::WmState};
pub fn update_monitor(
- monitor: Monitor,
+ monitor: &Monitor,
native_monitor: NativeMonitor,
state: &mut WmState,
) -> anyhow::Result<()> {
diff --git a/packages/wm/src/commands/window/ignore_window.rs b/packages/wm/src/commands/window/ignore_window.rs
index 079ddd97..2648ba89 100644
--- a/packages/wm/src/commands/window/ignore_window.rs
+++ b/packages/wm/src/commands/window/ignore_window.rs
@@ -10,6 +10,7 @@ use crate::{
wm_state::WmState,
};
+#[allow(clippy::needless_pass_by_value)]
pub fn ignore_window(
window: WindowContainer,
state: &mut WmState,
@@ -24,7 +25,7 @@ pub fn ignore_window(
// For example, in the layout V[1 H[2]] where container 1 is detached to
// become V[H[2]], this will then need to be flattened to V[2].
for ancestor in ancestors.iter().rev() {
- flatten_child_split_containers(ancestor.clone())?;
+ flatten_child_split_containers(ancestor)?;
}
// Sibling containers need to be redrawn if the window was tiling.
diff --git a/packages/wm/src/commands/window/manage_window.rs b/packages/wm/src/commands/window/manage_window.rs
index 55a1ea78..d03331d2 100644
--- a/packages/wm/src/commands/window/manage_window.rs
+++ b/packages/wm/src/commands/window/manage_window.rs
@@ -31,12 +31,12 @@ pub fn manage_window(
// Set the newly added window as focus descendant. This means the window
// rules will be run as if the window is focused.
- set_focused_descendant(window.clone().into(), None);
+ set_focused_descendant(&window.clone().into(), None);
// Window might be detached if `ignore` command has been invoked.
let updated_window = run_window_rules(
window.clone(),
- WindowRuleEvent::Manage,
+ &WindowRuleEvent::Manage,
state,
config,
)?;
@@ -101,17 +101,22 @@ fn create_window(
// the original width/height of the window and optionally position it in
// the center of the workspace.
let is_same_workspace = nearest_workspace.id() == target_workspace.id();
- let floating_placement = match !is_same_workspace || prefers_centered {
- true => native_window
- .frame_position()?
- .translate_to_center(&target_workspace.to_rect()?),
- false => native_window.frame_position()?,
- }
- // Clamp the window size to 90% of the workspace size.
- .clamp_size(
- (target_workspace.to_rect()?.width() as f32 * 0.9) as i32,
- (target_workspace.to_rect()?.height() as f32 * 0.9) as i32,
- );
+ let floating_placement = {
+ let placement = if !is_same_workspace || prefers_centered {
+ native_window
+ .frame_position()?
+ .translate_to_center(&target_workspace.to_rect()?)
+ } else {
+ native_window.frame_position()?
+ };
+
+ // Clamp the window size to 90% of the workspace size.
+ #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
+ placement.clamp_size(
+ (target_workspace.to_rect()?.width() as f32 * 0.9) as i32,
+ (target_workspace.to_rect()?.height() as f32 * 0.9) as i32,
+ )
+ };
// Window has no border delta unless it's later changed via the
// `adjust_borders` command.
@@ -216,11 +221,12 @@ fn insertion_target(
let focused_container =
state.focused_container().context("No focused container.")?;
- match focused_container.is_workspace() {
- true => Ok((focused_container, 0)),
- false => Ok((
+ if focused_container.is_workspace() {
+ Ok((focused_container, 0))
+ } else {
+ Ok((
focused_container.parent().context("No insertion target.")?,
focused_container.index() + 1,
- )),
+ ))
}
}
diff --git a/packages/wm/src/commands/window/move_window_in_direction.rs b/packages/wm/src/commands/window/move_window_in_direction.rs
index 0216e687..039c6311 100644
--- a/packages/wm/src/commands/window/move_window_in_direction.rs
+++ b/packages/wm/src/commands/window/move_window_in_direction.rs
@@ -18,6 +18,9 @@ use crate::{
wm_state::WmState,
};
+/// The distance in pixels to snap the window to the monitor's edge.
+const SNAP_DISTANCE: i32 = 15;
+
pub fn move_window_in_direction(
window: WindowContainer,
direction: &Direction,
@@ -34,7 +37,7 @@ pub fn move_window_in_direction(
move_floating_window(non_tiling_window, direction, state)
}
WindowState::Fullscreen(_) => move_to_workspace_in_direction(
- non_tiling_window.into(),
+ &non_tiling_window.into(),
direction,
state,
),
@@ -70,7 +73,7 @@ fn move_tiling_window(
// Attempt to swap or move the window into a sibling container.
if has_matching_tiling_direction {
if let Some(sibling) =
- tiling_sibling_in_direction(window_to_move.clone(), direction)
+ tiling_sibling_in_direction(&window_to_move, direction)
{
return move_to_sibling_container(
window_to_move,
@@ -87,7 +90,7 @@ fn move_tiling_window(
&& parent.is_workspace()
{
return move_to_workspace_in_direction(
- window_to_move.into(),
+ &window_to_move.into(),
direction,
state,
);
@@ -114,8 +117,8 @@ fn move_tiling_window(
// Otherwise, move the container into the given ancestor. This could
// simply be the container's direct parent.
Some(target_ancestor) => insert_into_ancestor(
- window_to_move,
- target_ancestor,
+ &window_to_move,
+ &target_ancestor,
direction,
state,
),
@@ -125,7 +128,7 @@ fn move_tiling_window(
/// Gets the next sibling `TilingWindow` or `SplitContainer` in the given
/// direction.
fn tiling_sibling_in_direction(
- window: TilingWindow,
+ window: &TilingWindow,
direction: &Direction,
) -> Option<TilingContainer> {
match direction {
@@ -150,8 +153,8 @@ fn move_to_sibling_container(
TilingContainer::TilingWindow(sibling_window) => {
// Swap the window with sibling in given direction.
move_container_within_tree(
- window_to_move.clone().into(),
- parent,
+ &window_to_move.clone().into(),
+ &parent,
sibling_window.index(),
state,
)?;
@@ -185,8 +188,8 @@ fn move_to_sibling_container(
};
move_container_within_tree(
- window_to_move.into(),
- target_parent.clone().into(),
+ &window_to_move.into(),
+ &target_parent.clone().into(),
target_index,
state,
)?;
@@ -204,7 +207,7 @@ fn move_to_sibling_container(
}
fn move_to_workspace_in_direction(
- window_to_move: WindowContainer,
+ window_to_move: &WindowContainer,
direction: &Direction,
state: &mut WmState,
) -> anyhow::Result<()> {
@@ -241,8 +244,8 @@ fn move_to_workspace_in_direction(
};
move_container_within_tree(
- window_to_move.clone().into(),
- workspace.clone().into(),
+ &window_to_move.clone().into(),
+ &workspace.clone().into(),
target_index,
state,
)?;
@@ -284,9 +287,9 @@ fn invert_workspace_tiling_direction(
);
wrap_in_split_container(
- split_container,
- workspace.clone().into(),
- workspace_children,
+ &split_container,
+ &workspace.clone().into(),
+ &workspace_children,
)?;
}
@@ -301,8 +304,8 @@ fn invert_workspace_tiling_direction(
// Depending on the direction, place the window either before or after
// the split container.
move_container_within_tree(
- window_to_move.clone().into(),
- workspace.clone().into(),
+ &window_to_move.clone().into(),
+ &workspace.clone().into(),
target_index,
state,
)?;
@@ -310,7 +313,7 @@ fn invert_workspace_tiling_direction(
// Workspace might have redundant split containers after the tiling
// direction change. For example, V[H[1 2] 3] where container 3 is moved
// up results in H[3 H[1 2]], and needs to be flattened to H[3 1 2].
- flatten_child_split_containers(workspace.clone().into())?;
+ flatten_child_split_containers(&workspace.clone().into())?;
// Resize the window such that the split container and window are each
// 0.5.
@@ -325,8 +328,8 @@ fn invert_workspace_tiling_direction(
}
fn insert_into_ancestor(
- window_to_move: TilingWindow,
- target_ancestor: DirectionContainer,
+ window_to_move: &TilingWindow,
+ target_ancestor: &DirectionContainer,
direction: &Direction,
state: &mut WmState,
) -> anyhow::Result<()> {
@@ -338,7 +341,7 @@ fn insert_into_ancestor(
.find(|container| {
container
.parent()
- .map_or(false, |parent| parent == target_ancestor.clone().into())
+ .is_some_and(|parent| parent == target_ancestor.clone().into())
})
.context("Window ancestor not found.")?;
@@ -349,8 +352,8 @@ fn insert_into_ancestor(
// Move the window into the container above.
move_container_within_tree(
- window_to_move.clone().into(),
- target_ancestor.clone().into(),
+ &window_to_move.clone().into(),
+ &target_ancestor.clone().into(),
target_index,
state,
)?;
@@ -369,7 +372,7 @@ fn move_floating_window(
state: &mut WmState,
) -> anyhow::Result<()> {
let new_position =
- new_floating_position(window_to_move.clone(), direction, state)?;
+ new_floating_position(&window_to_move, direction, state)?;
if let Some((position_rect, target_monitor)) = new_position {
let monitor = window_to_move.monitor().context("No monitor.")?;
@@ -396,7 +399,7 @@ fn move_floating_window(
/// Returns a tuple of the new floating position and the target monitor.
fn new_floating_position(
- window_to_move: NonTilingWindow,
+ window_to_move: &NonTilingWindow,
direction: &Direction,
state: &mut WmState,
) -> anyhow::Result<Option<(Rect, Monitor)>> {
@@ -443,6 +446,7 @@ fn new_floating_position(
// Calculate the distance the window should move based on the ratio of
// the window's length to the monitor's length.
+ #[allow(clippy::cast_precision_loss)]
let move_distance = match window_length as f32 / monitor_length as f32 {
x if (0.0..0.2).contains(&x) => length_delta / 5,
x if (0.2..0.4).contains(&x) => length_delta / 4,
@@ -450,8 +454,6 @@ fn new_floating_position(
_ => length_delta / 2,
};
- const SNAP_DISTANCE: i32 = 15;
-
// Snap the window to the current monitor's edge if it's within 15px of
// it after the move.
let should_snap_to_edge = match direction {
@@ -486,13 +488,10 @@ fn new_floating_position(
Direction::Right => window_pos.left < monitor_rect.left,
};
- let position = match should_snap_to_inverse_edge {
- true => snap_to_monitor_edge(
- &window_pos,
- &monitor_rect,
- &direction.inverse(),
- ),
- false => window_pos.translate_in_direction(direction, move_distance),
+ let position = if should_snap_to_inverse_edge {
+ snap_to_monitor_edge(&window_pos, &monitor_rect, &direction.inverse())
+ } else {
+ window_pos.translate_in_direction(direction, move_distance)
};
Ok(Some((position, monitor)))
diff --git a/packages/wm/src/commands/window/move_window_to_workspace.rs b/packages/wm/src/commands/window/move_window_to_workspace.rs
index 37a002a1..8ab93425 100644
--- a/packages/wm/src/commands/window/move_window_to_workspace.rs
+++ b/packages/wm/src/commands/window/move_window_to_workspace.rs
@@ -76,9 +76,10 @@ pub fn move_window_to_workspace(
// Focus target is `None` if the window is not focused.
let focus_target = state.focus_target_after_removal(&window);
- let focus_reset_target = match target_workspace.is_displayed() {
- true => None,
- false => target_monitor.descendant_focus_order().next(),
+ let focus_reset_target = if target_workspace.is_displayed() {
+ None
+ } else {
+ target_monitor.descendant_focus_order().next()
};
let insertion_sibling = target_workspace
@@ -91,8 +92,8 @@ pub fn move_window_to_workspace(
(true, true) => {
if let Some(insertion_sibling) = insertion_sibling {
move_container_within_tree(
- window.clone().into(),
- insertion_sibling.clone().parent().context("No parent.")?,
+ &window.clone().into(),
+ &insertion_sibling.clone().parent().context("No parent.")?,
insertion_sibling.index() + 1,
state,
)?;
@@ -100,8 +101,8 @@ pub fn move_window_to_workspace(
}
_ => {
move_container_within_tree(
- window.clone().into(),
- target_workspace.clone().into(),
+ &window.clone().into(),
+ &target_workspace.clone().into(),
target_workspace.child_count(),
state,
)?;
@@ -114,13 +115,13 @@ pub fn move_window_to_workspace(
// monitor, we want to reset focus to the workspace that was displayed
// on that monitor.
if let Some(focus_reset_target) = focus_reset_target {
- set_focused_descendant(focus_reset_target, None);
+ set_focused_descendant(&focus_reset_target, None);
state.pending_sync.focus_change = true;
}
// Retain focus within the workspace from where the window was moved.
if let Some(focus_target) = focus_target {
- set_focused_descendant(focus_target, None);
+ set_focused_descendant(&focus_target, None);
state.pending_sync.focus_change = true;
}
diff --git a/packages/wm/src/commands/window/resize_window.rs b/packages/wm/src/commands/window/resize_window.rs
index af43281d..d576b079 100644
--- a/packages/wm/src/commands/window/resize_window.rs
+++ b/packages/wm/src/commands/window/resize_window.rs
@@ -8,7 +8,7 @@ use crate::{
};
pub fn resize_window(
- window: WindowContainer,
+ window: &WindowContainer,
width_delta: Option<LengthValue>,
height_delta: Option<LengthValue>,
state: &mut WmState,
@@ -27,6 +27,10 @@ pub fn resize_window(
.and_then(|parent_width| {
let (horizontal_gap, _) = tiling_window.inner_gaps().ok()?;
+ #[allow(
+ clippy::cast_possible_wrap,
+ clippy::cast_possible_truncation
+ )]
Some(
parent_width
- horizontal_gap
@@ -57,6 +61,10 @@ pub fn resize_window(
.and_then(|parent_height| {
let (_, vertical_gap) = tiling_window.inner_gaps().ok()?;
+ #[allow(
+ clippy::cast_possible_wrap,
+ clippy::cast_possible_truncation
+ )]
Some(
parent_height
- vertical_gap
diff --git a/packages/wm/src/commands/window/run_window_rules.rs b/packages/wm/src/commands/window/run_window_rules.rs
index 7fe665e0..53fea023 100644
--- a/packages/wm/src/commands/window/run_window_rules.rs
+++ b/packages/wm/src/commands/window/run_window_rules.rs
@@ -13,12 +13,12 @@ use crate::{
/// rules.
pub fn run_window_rules(
window: WindowContainer,
- event_type: WindowRuleEvent,
+ event_type: &WindowRuleEvent,
state: &mut WmState,
config: &mut UserConfig,
) -> anyhow::Result<Option<WindowContainer>> {
let pending_window_rules =
- config.pending_window_rules(&window, &event_type)?;
+ config.pending_window_rules(&window, event_type)?;
let mut subject_window = window;
@@ -35,12 +35,13 @@ pub fn run_window_rules(
// Update the subject container in case the container type changes.
// For example, when going from a tiling to a floating window.
- subject_window = match subject_window.is_detached() {
- false => subject_window,
- true => match state.window_from_native(&subject_window.native()) {
+ subject_window = if subject_window.is_detached() {
+ match state.window_from_native(&subject_window.native()) {
Some(window) => window,
None => return Ok(None),
- },
+ }
+ } else {
+ subject_window
}
}
diff --git a/packages/wm/src/commands/window/set_window_position.rs b/packages/wm/src/commands/window/set_window_position.rs
index fac403ba..ef8402fb 100644
--- a/packages/wm/src/commands/window/set_window_position.rs
+++ b/packages/wm/src/commands/window/set_window_position.rs
@@ -14,7 +14,7 @@ pub enum WindowPositionTarget {
pub fn set_window_position(
window: WindowContainer,
- target: WindowPositionTarget,
+ target: &WindowPositionTarget,
state: &mut WmState,
) -> anyhow::Result<()> {
if matches!(window.state(), WindowState::Floating(_)) {
diff --git a/packages/wm/src/commands/window/set_window_size.rs b/packages/wm/src/commands/window/set_window_size.rs
index d2983649..f8a20a04 100644
--- a/packages/wm/src/commands/window/set_window_size.rs
+++ b/packages/wm/src/commands/window/set_window_size.rs
@@ -22,12 +22,12 @@ pub fn set_window_size(
) -> anyhow::Result<()> {
match window {
WindowContainer::TilingWindow(window) => {
- set_tiling_window_size(window, target_width, target_height, state)?;
+ set_tiling_window_size(&window, target_width, target_height, state)?;
}
WindowContainer::NonTilingWindow(window) => {
if matches!(window.state(), WindowState::Floating(_)) {
set_floating_window_size(
- window,
+ &window,
target_width,
target_height,
state,
@@ -40,17 +40,17 @@ pub fn set_window_size(
}
fn set_tiling_window_size(
- window: TilingWindow,
+ window: &TilingWindow,
target_width: Option<LengthValue>,
target_height: Option<LengthValue>,
state: &mut WmState,
) -> anyhow::Result<()> {
if let Some(target_width) = target_width {
- set_tiling_window_length(window.clone(), target_width, true, state)?;
+ set_tiling_window_length(window, &target_width, true, state)?;
}
if let Some(target_height) = target_height {
- set_tiling_window_length(window.clone(), target_height, false, state)?;
+ set_tiling_window_length(window, &target_height, false, state)?;
}
Ok(())
@@ -58,8 +58,8 @@ fn set_tiling_window_size(
/// Updates either the width or height of a tiling window.
fn set_tiling_window_length(
- window: TilingWindow,
- target_length: LengthValue,
+ window: &TilingWindow,
+ target_length: &LengthValue,
is_width_resize: bool,
state: &mut WmState,
) -> anyhow::Result<()> {
@@ -72,15 +72,13 @@ fn set_tiling_window_length(
let (horizontal_gap, vertical_gap) =
container_to_resize.inner_gaps()?;
- let parent_length = match is_width_resize {
- true => {
- parent.to_rect()?.width()
- - horizontal_gap * window.tiling_siblings().count() as i32
- }
- false => {
- parent.to_rect()?.height()
- - vertical_gap * window.tiling_siblings().count() as i32
- }
+ #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
+ let parent_length = if is_width_resize {
+ parent.to_rect()?.width()
+ - horizontal_gap * window.tiling_siblings().count() as i32
+ } else {
+ parent.to_rect()?.height()
+ - vertical_gap * window.tiling_siblings().count() as i32
};
// Convert the target length to a tiling size.
@@ -101,7 +99,7 @@ fn set_tiling_window_length(
}
fn set_floating_window_size(
- window: NonTilingWindow,
+ window: &NonTilingWindow,
target_width: Option<LengthValue>,
target_height: Option<LengthValue>,
state: &mut WmState,
@@ -115,15 +113,13 @@ fn set_floating_window_size(
// be within minimum dimension values.
let length_with_clamp =
|target_length: Option<i32>, current_length, min_length| {
- target_length
- .map(|target_length| {
- if target_length >= current_length {
- target_length
- } else {
- target_length.max(min_length)
- }
- })
- .unwrap_or(current_length)
+ target_length.map_or(current_length, |target_length| {
+ if target_length >= current_length {
+ target_length
+ } else {
+ target_length.max(min_length)
+ }
+ })
};
let target_width_px = target_width
diff --git a/packages/wm/src/commands/window/unmanage_window.rs b/packages/wm/src/commands/window/unmanage_window.rs
index 84c178ad..aa39d1b0 100644
--- a/packages/wm/src/commands/window/unmanage_window.rs
+++ b/packages/wm/src/commands/window/unmanage_window.rs
@@ -11,6 +11,7 @@ use crate::{
wm_state::WmState,
};
+#[allow(clippy::needless_pass_by_value)]
pub fn unmanage_window(
window: WindowContainer,
state: &mut WmState,
@@ -27,7 +28,7 @@ pub fn unmanage_window(
// For example, in the layout V[1 H[2]] where container 1 is detached to
// become V[H[2]], this will then need to be flattened to V[2].
for ancestor in ancestors.iter().rev() {
- flatten_child_split_containers(ancestor.clone())?;
+ flatten_child_split_containers(ancestor)?;
}
state.emit_event(WmEvent::WindowUnmanaged {
@@ -37,7 +38,7 @@ pub fn unmanage_window(
// Reassign focus to suitable target.
if let Some(focus_target) = focus_target {
- set_focused_descendant(focus_target, None);
+ set_focused_descendant(&focus_target, None);
state.pending_sync.focus_change = true;
state.unmanaged_or_minimized_timestamp =
Some(std::time::Instant::now());
diff --git a/packages/wm/src/commands/window/update_window_state.rs b/packages/wm/src/commands/window/update_window_state.rs
index d10b7fb1..05b82c15 100644
--- a/packages/wm/src/commands/window/update_window_state.rs
+++ b/packages/wm/src/commands/window/update_window_state.rs
@@ -6,7 +6,7 @@ use crate::{
commands::container::{
move_container_within_tree, replace_container, resize_tiling_container,
},
- models::{InsertionTarget, WindowContainer},
+ models::{Container, InsertionTarget, WindowContainer},
traits::{CommonGetters, TilingSizeGetters, WindowGetters},
user_config::UserConfig,
wm_state::WmState,
@@ -30,14 +30,14 @@ pub fn update_window_state(
info!("Updating window state: {:?}.", target_state);
match target_state {
- WindowState::Tiling => set_tiling(window, state, config),
+ WindowState::Tiling => set_tiling(&window, state, config),
_ => set_non_tiling(window, target_state, state),
}
}
/// Updates the state of a window to be `WindowState::Tiling`.
fn set_tiling(
- window: WindowContainer,
+ window: &WindowContainer,
state: &mut WmState,
config: &UserConfig,
) -> anyhow::Result<WindowContainer> {
@@ -55,8 +55,7 @@ fn set_tiling(
insertion_target
.target_parent
.workspace()
- .map(|workspace| workspace.is_displayed())
- .unwrap_or(false)
+ .is_some_and(|workspace| workspace.is_displayed())
});
// Get the position in the tree to insert the new tiling window. This
@@ -74,7 +73,7 @@ fn set_tiling(
.or_else(|| {
let focused_window = workspace
.descendant_focus_order()
- .find(|descendant| descendant.is_tiling_window())?;
+ .find(Container::is_tiling_window)?;
Some((focused_window.parent()?, focused_window.index() + 1))
})
@@ -85,18 +84,19 @@ fn set_tiling(
// Replace the original window with the created tiling window.
replace_container(
- tiling_window.clone().into(),
- window.parent().context("No parent.")?,
+ &tiling_window.clone().into(),
+ &window.parent().context("No parent.")?,
window.index(),
)?;
move_container_within_tree(
- tiling_window.clone().into(),
- target_parent.clone(),
+ &tiling_window.clone().into(),
+ &target_parent,
target_index,
state,
)?;
+ #[allow(clippy::cast_precision_loss)]
if let Some(insertion_target) = &insertion_target {
let size_scale = (insertion_target.prev_sibling_count + 1) as f32
/ (tiling_window.tiling_siblings().count() + 1) as f32;
@@ -171,16 +171,16 @@ fn set_non_tiling(
// workspace.
if parent != workspace.clone().into() {
move_container_within_tree(
- window.clone().into(),
- workspace.clone().into(),
+ &window.clone().into(),
+ &workspace.clone().into(),
workspace.child_count(),
state,
)?;
}
replace_container(
- non_tiling_window.clone().into(),
- workspace.clone().into(),
+ &non_tiling_window.clone().into(),
+ &workspace.clone().into(),
window.index(),
)?;
diff --git a/packages/wm/src/commands/workspace/activate_workspace.rs b/packages/wm/src/commands/workspace/activate_workspace.rs
index c11d8821..96d93429 100644
--- a/packages/wm/src/commands/workspace/activate_workspace.rs
+++ b/packages/wm/src/commands/workspace/activate_workspace.rs
@@ -49,10 +49,11 @@ pub fn activate_workspace(
.context("Failed to get a target monitor for the workspace.")?;
let monitor_rect = target_monitor.to_rect()?;
- let tiling_direction = match monitor_rect.height() > monitor_rect.width()
- {
- true => TilingDirection::Vertical,
- false => TilingDirection::Horizontal,
+
+ let tiling_direction = if monitor_rect.height() > monitor_rect.width() {
+ TilingDirection::Vertical
+ } else {
+ TilingDirection::Horizontal
};
let workspace = Workspace::new(
@@ -68,7 +69,7 @@ pub fn activate_workspace(
None,
)?;
- sort_workspaces(target_monitor.clone(), config)?;
+ sort_workspaces(&target_monitor, config)?;
state.emit_event(WmEvent::WorkspaceActivated {
activated_workspace: workspace.to_dto()?,
@@ -91,8 +92,7 @@ fn workspace_config(
.find(|config| config.name == workspace_name)
.with_context(|| {
format!(
- "Workspace with name '{}' doesn't exist or is already active.",
- workspace_name
+ "Workspace with name '{workspace_name}' doesn't exist or is already active."
)
}),
None => target_monitor
diff --git a/packages/wm/src/commands/workspace/deactivate_workspace.rs b/packages/wm/src/commands/workspace/deactivate_workspace.rs
index afb6f419..4e2b5d8f 100644
--- a/packages/wm/src/commands/workspace/deactivate_workspace.rs
+++ b/packages/wm/src/commands/workspace/deactivate_workspace.rs
@@ -7,6 +7,7 @@ use crate::{
/// Deactivates a given workspace. This removes the container from its
/// parent monitor and emits a `WorkspaceDeactivated` event.
+#[allow(clippy::needless_pass_by_value)]
pub fn deactivate_workspace(
workspace: Workspace,
state: &WmState,
diff --git a/packages/wm/src/commands/workspace/focus_workspace.rs b/packages/wm/src/commands/workspace/focus_workspace.rs
index d410c550..ea63f718 100644
--- a/packages/wm/src/commands/workspace/focus_workspace.rs
+++ b/packages/wm/src/commands/workspace/focus_workspace.rs
@@ -62,7 +62,7 @@ pub fn focus_workspace(
.next()
.unwrap_or_else(|| target_workspace.clone().into());
- set_focused_descendant(container_to_focus.clone(), None);
+ set_focused_descendant(&container_to_focus, None);
state.pending_sync.focus_change = true;
// Display the workspace to switch focus to.
diff --git a/packages/wm/src/commands/workspace/move_workspace_in_direction.rs b/packages/wm/src/commands/workspace/move_workspace_in_direction.rs
index 5a85483c..49a7f2c6 100644
--- a/packages/wm/src/commands/workspace/move_workspace_in_direction.rs
+++ b/packages/wm/src/commands/workspace/move_workspace_in_direction.rs
@@ -11,14 +11,14 @@ use crate::{
};
pub fn move_workspace_in_direction(
- workspace: Workspace,
- direction: Direction,
+ workspace: &Workspace,
+ direction: &Direction,
state: &mut WmState,
config: &UserConfig,
) -> anyhow::Result<()> {
let origin_monitor = workspace.monitor().context("No monitor.")?;
let target_monitor =
- state.monitor_in_direction(&origin_monitor, &direction)?;
+ state.monitor_in_direction(&origin_monitor, direction)?;
if let Some(target_monitor) = target_monitor {
// Get currently displayed workspace on the target monitor.
@@ -27,8 +27,8 @@ pub fn move_workspace_in_direction(
.context("No displayed workspace.")?;
move_container_within_tree(
- workspace.clone().into(),
- target_monitor.clone().into(),
+ &workspace.clone().into(),
+ &target_monitor.clone().into(),
target_monitor.child_count(),
state,
)?;
@@ -82,7 +82,7 @@ pub fn move_workspace_in_direction(
deactivate_workspace(workspace, state)?;
}
- sort_workspaces(target_monitor, config)?;
+ sort_workspaces(&target_monitor, config)?;
state.emit_event(WmEvent::WorkspaceUpdated {
updated_workspace: workspace.to_dto()?,
diff --git a/packages/wm/src/commands/workspace/sort_workspaces.rs b/packages/wm/src/commands/workspace/sort_workspaces.rs
index a71e2183..13f4fabf 100644
--- a/packages/wm/src/commands/workspace/sort_workspaces.rs
+++ b/packages/wm/src/commands/workspace/sort_workspaces.rs
@@ -7,7 +7,7 @@ use crate::{
/// Sorts a monitor's workspaces by config order.
pub fn sort_workspaces(
- monitor: Monitor,
+ monitor: &Monitor,
config: &UserConfig,
) -> anyhow::Result<()> {
let mut workspaces = monitor.workspaces();
diff --git a/packages/wm/src/events/handle_display_settings_changed.rs b/packages/wm/src/events/handle_display_settings_changed.rs
index 9c1d639c..dc073c54 100644
--- a/packages/wm/src/events/handle_display_settings_changed.rs
+++ b/packages/wm/src/events/handle_display_settings_changed.rs
@@ -55,11 +55,12 @@ pub fn handle_display_settings_changed(
hardware_ids.iter().filter(|&id| *id == hardware_id).count()
== 1;
- match is_unique
+ if is_unique
&& hardware_id == *native_monitor.hardware_id().ok()??
{
- true => Some(monitor),
- false => None,
+ Some(monitor)
+ } else {
+ None
}
})
.cloned();
@@ -75,7 +76,7 @@ pub fn handle_display_settings_changed(
pending_monitors.remove(index);
}
- update_monitor(found_monitor, native_monitor, state)?;
+ update_monitor(&found_monitor, native_monitor, state)?;
}
None => {
new_native_monitors.push(native_monitor);
@@ -87,7 +88,7 @@ pub fn handle_display_settings_changed(
match pending_monitors.first() {
Some(_) => {
let monitor = pending_monitors.remove(0);
- update_monitor(monitor, native_monitor, state)
+ update_monitor(&monitor, native_monitor, state)
}
// Add monitor if it doesn't exist in state.
None => add_monitor(native_monitor, state, config),
@@ -108,7 +109,7 @@ pub fn handle_display_settings_changed(
}
// Sort monitors by position.
- sort_monitors(state.root_container.clone())?;
+ sort_monitors(&state.root_container)?;
for window in state.windows() {
// Display setting changes can spread windows out sporadically, so mark
diff --git a/packages/wm/src/events/handle_mouse_move.rs b/packages/wm/src/events/handle_mouse_move.rs
index 6bbb1f25..3ff12f67 100644
--- a/packages/wm/src/events/handle_mouse_move.rs
+++ b/packages/wm/src/events/handle_mouse_move.rs
@@ -7,7 +7,7 @@ use crate::{
};
pub fn handle_mouse_move(
- event: MouseMoveEvent,
+ event: &MouseMoveEvent,
state: &mut WmState,
config: &UserConfig,
) -> anyhow::Result<()> {
@@ -27,7 +27,7 @@ pub fn handle_mouse_move(
state.focused_container().context("No focused container.")?;
if focused_container.id() != window.id() {
- set_focused_descendant(window.as_container(), None);
+ set_focused_descendant(&window.as_container(), None);
state.pending_sync.focus_change = true;
}
}
diff --git a/packages/wm/src/events/handle_window_destroyed.rs b/packages/wm/src/events/handle_window_destroyed.rs
index f57e18c6..383ab91a 100644
--- a/packages/wm/src/events/handle_window_destroyed.rs
+++ b/packages/wm/src/events/handle_window_destroyed.rs
@@ -9,10 +9,10 @@ use crate::{
};
pub fn handle_window_destroyed(
- native_window: NativeWindow,
+ native_window: &NativeWindow,
state: &mut WmState,
) -> anyhow::Result<()> {
- let found_window = state.window_from_native(&native_window);
+ let found_window = state.window_from_native(native_window);
// Unmanage the window if it's currently managed.
if let Some(window) = found_window {
diff --git a/packages/wm/src/events/handle_window_focused.rs b/packages/wm/src/events/handle_window_focused.rs
index 98c79881..77a4ba79 100644
--- a/packages/wm/src/events/handle_window_focused.rs
+++ b/packages/wm/src/events/handle_window_focused.rs
@@ -15,11 +15,11 @@ use crate::{
};
pub fn handle_window_focused(
- native_window: NativeWindow,
+ native_window: &NativeWindow,
state: &mut WmState,
config: &mut UserConfig,
) -> anyhow::Result<()> {
- let found_window = state.window_from_native(&native_window);
+ let found_window = state.window_from_native(native_window);
if let Some(window) = found_window {
// Ignore the focus event if:
@@ -42,8 +42,7 @@ pub fn handle_window_focused(
// focus target and then to the WM's focus target.
if state
.unmanaged_or_minimized_timestamp
- .map(|time| time.elapsed().as_millis() < 100)
- .unwrap_or(false)
+ .is_some_and(|time| time.elapsed().as_millis() < 100)
{
info!("Overriding native focus.");
state.pending_sync.focus_change = true;
@@ -66,12 +65,12 @@ pub fn handle_window_focused(
}
// Update the WM's focus state.
- set_focused_descendant(window.clone().into(), None);
+ set_focused_descendant(&window.clone().into(), None);
// Run window rules for focus events.
run_window_rules(
window.clone(),
- WindowRuleEvent::Focus,
+ &WindowRuleEvent::Focus,
state,
config,
)?;
diff --git a/packages/wm/src/events/handle_window_hidden.rs b/packages/wm/src/events/handle_window_hidden.rs
index 13edd430..1dac56e4 100644
--- a/packages/wm/src/events/handle_window_hidden.rs
+++ b/packages/wm/src/events/handle_window_hidden.rs
@@ -8,10 +8,10 @@ use crate::{
};
pub fn handle_window_hidden(
- native_window: NativeWindow,
+ native_window: &NativeWindow,
state: &mut WmState,
) -> anyhow::Result<()> {
- let found_window = state.window_from_native(&native_window);
+ let found_window = state.window_from_native(native_window);
if let Some(window) = found_window {
// TODO: Log window details.
diff --git a/packages/wm/src/events/handle_window_location_changed.rs b/packages/wm/src/events/handle_window_location_changed.rs
index 072079b9..52674c0c 100644
--- a/packages/wm/src/events/handle_window_location_changed.rs
+++ b/packages/wm/src/events/handle_window_location_changed.rs
@@ -17,12 +17,13 @@ use crate::{
wm_state::WmState,
};
+#[allow(clippy::too_many_lines)]
pub fn handle_window_location_changed(
- native_window: NativeWindow,
+ native_window: &NativeWindow,
state: &mut WmState,
config: &UserConfig,
) -> anyhow::Result<()> {
- let found_window = state.window_from_native(&native_window);
+ let found_window = state.window_from_native(native_window);
// Update the window's state to be fullscreen or toggled from fullscreen.
if let Some(window) = found_window {
@@ -57,7 +58,7 @@ pub fn handle_window_location_changed(
// TODO: Include this as part of the `match` statement below.
if let Some(tiling_window) = window.as_tiling_window() {
update_drag_state(
- tiling_window.clone(),
+ tiling_window,
&frame_position,
&old_frame_position,
state,
@@ -77,8 +78,7 @@ pub fn handle_window_location_changed(
WindowState::Fullscreen(fullscreen_state) => {
// Restore the window if it's no longer fullscreen *or* for the
// edge case of fullscreen -> maximized -> restore from maximized.
- if !(is_fullscreen || is_maximized)
- || (is_fullscreen && !is_maximized && fullscreen_state.maximized)
+ if (fullscreen_state.maximized || !is_fullscreen) && !is_maximized
{
info!("Window restored from fullscreen.");
@@ -145,8 +145,8 @@ pub fn handle_window_location_changed(
}
move_container_within_tree(
- window.into(),
- updated_workspace.clone().into(),
+ &window.into(),
+ &updated_workspace.clone().into(),
updated_workspace.child_count(),
state,
)?;
@@ -165,7 +165,7 @@ pub fn handle_window_location_changed(
/// updates its operation state accordingly. If the window is being moved,
/// it's set to floating mode.
fn update_drag_state(
- window: TilingWindow,
+ window: &TilingWindow,
frame_position: &Rect,
old_frame_position: &Rect,
state: &mut WmState,
@@ -182,9 +182,10 @@ fn update_drag_state(
let is_move = frame_position.height() == old_frame_position.height()
&& frame_position.width() == old_frame_position.width();
- let operation = match is_move {
- true => ActiveDragOperation::Moving,
- false => ActiveDragOperation::Resizing,
+ let operation = if is_move {
+ ActiveDragOperation::Moving
+ } else {
+ ActiveDragOperation::Resizing
};
window.set_active_drag(Some(ActiveDrag {
diff --git a/packages/wm/src/events/handle_window_minimize_ended.rs b/packages/wm/src/events/handle_window_minimize_ended.rs
index 382c0133..84aef984 100644
--- a/packages/wm/src/events/handle_window_minimize_ended.rs
+++ b/packages/wm/src/events/handle_window_minimize_ended.rs
@@ -8,11 +8,11 @@ use crate::{
};
pub fn handle_window_minimize_ended(
- native_window: NativeWindow,
+ native_window: &NativeWindow,
state: &mut WmState,
config: &UserConfig,
) -> anyhow::Result<()> {
- let found_window = state.window_from_native(&native_window);
+ let found_window = state.window_from_native(native_window);
// Update the window's state to not be minimized.
if let Some(window) = found_window {
diff --git a/packages/wm/src/events/handle_window_minimized.rs b/packages/wm/src/events/handle_window_minimized.rs
index 9707df97..be1c16d3 100644
--- a/packages/wm/src/events/handle_window_minimized.rs
+++ b/packages/wm/src/events/handle_window_minimized.rs
@@ -12,11 +12,11 @@ use crate::{
};
pub fn handle_window_minimized(
- native_window: NativeWindow,
+ native_window: &NativeWindow,
state: &mut WmState,
config: &UserConfig,
) -> anyhow::Result<()> {
- let found_window = state.window_from_native(&native_window);
+ let found_window = state.window_from_native(native_window);
// Update the window's state to be minimized.
if let Some(window) = found_window {
@@ -36,7 +36,7 @@ pub fn handle_window_minimized(
// Focus should be reassigned after a window has been minimized.
if let Some(focus_target) = state.focus_target_after_removal(&window)
{
- set_focused_descendant(focus_target, None);
+ set_focused_descendant(&focus_target, None);
state.pending_sync.focus_change = true;
state.unmanaged_or_minimized_timestamp =
Some(std::time::Instant::now());
diff --git a/packages/wm/src/events/handle_window_moved_or_resized_end.rs b/packages/wm/src/events/handle_window_moved_or_resized_end.rs
index 77d46096..e477b8fa 100644
--- a/packages/wm/src/events/handle_window_moved_or_resized_end.rs
+++ b/packages/wm/src/events/handle_window_moved_or_resized_end.rs
@@ -28,11 +28,11 @@ use crate::{
/// This resizes the window if it's a tiling window and attach a dragged
/// floating window.
pub fn handle_window_moved_or_resized_end(
- native_window: NativeWindow,
+ native_window: &NativeWindow,
state: &mut WmState,
config: &UserConfig,
) -> anyhow::Result<()> {
- let found_window = state.window_from_native(&native_window);
+ let found_window = state.window_from_native(native_window);
if let Some(window) = found_window {
// TODO: Log window details.
@@ -51,7 +51,7 @@ pub fn handle_window_moved_or_resized_end(
{
// Window is a temporary floating window that should be
// reverted back to tiling.
- drop_as_tiling_window(window.clone(), state, config)?;
+ drop_as_tiling_window(window, state, config)?;
}
}
}
@@ -77,7 +77,7 @@ pub fn handle_window_moved_or_resized_end(
}
resize_window(
- window.clone().into(),
+ &window.clone().into(),
Some(LengthValue::from_px(width_delta)),
Some(LengthValue::from_px(height_delta)),
state,
@@ -96,7 +96,7 @@ pub fn handle_window_moved_or_resized_end(
/// Handles transition from temporary floating window to tiling window on
/// drag end.
fn drop_as_tiling_window(
- moved_window: NonTilingWindow,
+ moved_window: &NonTilingWindow,
state: &mut WmState,
config: &UserConfig,
) -> anyhow::Result<()> {
@@ -108,7 +108,7 @@ fn drop_as_tiling_window(
// Get the workspace, split containers, and other windows under the
// dragged window.
let containers_at_pos = state
- .containers_at_point(workspace.clone().into(), &mouse_pos)
+ .containers_at_point(&workspace.clone().into(), &mouse_pos)
.into_iter()
.filter(|container| container.id() != moved_window.id());
@@ -181,9 +181,9 @@ fn drop_as_tiling_window(
);
wrap_in_split_container(
- split_container.clone(),
- target_parent.clone().into(),
- vec![nearest_container],
+ &split_container,
+ &target_parent.clone().into(),
+ &[nearest_container],
)?;
let target_index = match drop_position {
@@ -192,8 +192,8 @@ fn drop_as_tiling_window(
};
move_container_within_tree(
- moved_window.clone().into(),
- split_container.into(),
+ &moved_window.clone().into(),
+ &split_container.into(),
target_index,
state,
)?;
@@ -204,8 +204,8 @@ fn drop_as_tiling_window(
};
move_container_within_tree(
- moved_window.clone().into(),
- target_parent.clone().into(),
+ &moved_window.clone().into(),
+ &target_parent.clone().into(),
target_index,
state,
)?;
@@ -236,16 +236,19 @@ fn drop_position(mouse_pos: &Point, rect: &Rect) -> DropPosition {
let delta_x = mouse_pos.x - rect.center_point().x;
let delta_y = mouse_pos.y - rect.center_point().y;
- match delta_x.abs() > delta_y.abs() {
+ if delta_x.abs() > delta_y.abs() {
// Window is in the left or right triangle.
- true => match delta_x > 0 {
- true => DropPosition::Right,
- false => DropPosition::Left,
- },
+ if delta_x > 0 {
+ DropPosition::Right
+ } else {
+ DropPosition::Left
+ }
+ } else {
// Window is in the top or bottom triangle.
- false => match delta_y > 0 {
- true => DropPosition::Bottom,
- false => DropPosition::Top,
- },
+ if delta_y > 0 {
+ DropPosition::Bottom
+ } else {
+ DropPosition::Top
+ }
}
}
diff --git a/packages/wm/src/events/handle_window_moved_or_resized_start.rs b/packages/wm/src/events/handle_window_moved_or_resized_start.rs
index 914ed839..d6cda14d 100644
--- a/packages/wm/src/events/handle_window_moved_or_resized_start.rs
+++ b/packages/wm/src/events/handle_window_moved_or_resized_start.rs
@@ -6,10 +6,10 @@ use crate::{traits::WindowGetters, wm_state::WmState};
/// Handles the event for when a window is started being moved or resized
/// by the user (e.g. via the window's drag handles).
pub fn handle_window_moved_or_resized_start(
- native_window: NativeWindow,
+ native_window: &NativeWindow,
state: &mut WmState,
-) -> anyhow::Result<()> {
- let found_window = state.window_from_native(&native_window);
+) {
+ let found_window = state.window_from_native(native_window);
if let Some(found_window) = found_window {
found_window.set_active_drag(Some(ActiveDrag {
@@ -17,6 +17,4 @@ pub fn handle_window_moved_or_resized_start(
is_from_tiling: found_window.is_tiling_window(),
}));
}
-
- Ok(())
}
diff --git a/packages/wm/src/events/handle_window_title_changed.rs b/packages/wm/src/events/handle_window_title_changed.rs
index 5ff3e875..57f79e8a 100644
--- a/packages/wm/src/events/handle_window_title_changed.rs
+++ b/packages/wm/src/events/handle_window_title_changed.rs
@@ -8,19 +8,25 @@ use crate::{
};
pub fn handle_window_title_changed(
- native_window: NativeWindow,
+ native_window: &NativeWindow,
state: &mut WmState,
config: &mut UserConfig,
) -> anyhow::Result<()> {
- let found_window = state.window_from_native(&native_window);
+ let found_window = state.window_from_native(native_window);
if let Some(window) = found_window {
// TODO: Log window details.
info!("Window title changed");
- // Run window rules for title change events.
try_warn!(window.native().refresh_title());
- run_window_rules(window, WindowRuleEvent::TitleChange, state, config)?;
+
+ // Run window rules for title change events.
+ run_window_rules(
+ window,
+ &WindowRuleEvent::TitleChange,
+ state,
+ config,
+ )?;
}
Ok(())
diff --git a/packages/wm/src/ipc_server.rs b/packages/wm/src/ipc_server.rs
index 14b12d20..99b17e05 100644
--- a/packages/wm/src/ipc_server.rs
+++ b/packages/wm/src/ipc_server.rs
@@ -44,7 +44,7 @@ impl IpcServer {
let (event_tx, _event_rx) = broadcast::channel(16);
let (unsubscribe_tx, _unsubscribe_rx) = broadcast::channel(16);
- let server_addr = format!("127.0.0.1:{}", DEFAULT_IPC_PORT);
+ let server_addr = format!("127.0.0.1:{DEFAULT_IPC_PORT}");
let server = TcpListener::bind(server_addr.clone()).await?;
info!("IPC server started on: '{}'.", server_addr);
@@ -64,10 +64,12 @@ impl IpcServer {
Ok(Self {
abort_handle: task.abort_handle(),
+ #[allow(clippy::used_underscore_binding)]
_event_rx,
event_tx,
message_rx,
unsubscribe_tx,
+ #[allow(clippy::used_underscore_binding)]
_unsubscribe_rx,
})
}
@@ -125,8 +127,8 @@ impl IpcServer {
pub fn process_message(
&self,
message: String,
- response_tx: mpsc::UnboundedSender<Message>,
- disconnection_tx: broadcast::Sender<()>,
+ response_tx: &mpsc::UnboundedSender<Message>,
+ disconnection_tx: &broadcast::Sender<()>,
wm: &mut WindowManager,
config: &mut UserConfig,
) -> anyhow::Result<()> {
@@ -140,7 +142,7 @@ impl IpcServer {
.and_then(|app_command| {
self.handle_app_command(
app_command,
- response_tx.clone(),
+ response_tx,
disconnection_tx,
wm,
config,
@@ -154,11 +156,12 @@ impl IpcServer {
Ok(())
}
+ #[allow(clippy::too_many_lines)]
fn handle_app_command(
&self,
app_command: AppCommand,
- response_tx: mpsc::UnboundedSender<Message>,
- disconnection_tx: broadcast::Sender<()>,
+ response_tx: &mpsc::UnboundedSender<Message>,
+ disconnection_tx: &broadcast::Sender<()>,
wm: &mut WindowManager,
config: &mut UserConfig,
) -> anyhow::Result<ClientResponseData> {
@@ -235,7 +238,7 @@ impl IpcServer {
command,
} => {
let subject_container_id = wm.process_commands(
- vec![command],
+ &vec![command],
subject_container_id,
config,
)?;
@@ -256,7 +259,7 @@ impl IpcServer {
task::spawn(async move {
loop {
tokio::select! {
- Ok(_) = disconnection_rx.recv() => {
+ Ok(()) = disconnection_rx.recv() => {
break;
}
Ok(id) = unsubscribe_rx.recv() => {
@@ -297,7 +300,7 @@ impl IpcServer {
ClientResponseData::EventUnsubscribe
}
- _ => bail!("Unsupported IPC command."),
+ AppCommand::Start { .. } => bail!("Unsupported IPC command."),
};
Ok(response_data)
@@ -307,7 +310,7 @@ impl IpcServer {
client_message: String,
response_data: anyhow::Result<ClientResponseData>,
) -> anyhow::Result<Message> {
- let error = response_data.as_ref().err().map(|err| err.to_string());
+ let error = response_data.as_ref().err().map(ToString::to_string);
let success = response_data.as_ref().is_ok();
let message = ServerMessage::ClientResponse(ClientResponseMessage {
diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rs
index 8b17e801..d9f08fa0 100644
--- a/packages/wm/src/main.rs
+++ b/packages/wm/src/main.rs
@@ -6,12 +6,12 @@
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
+#![warn(clippy::all, clippy::pedantic)]
#![feature(iterator_try_collect)]
-#![feature(once_cell_try)]
use std::{env, path::PathBuf};
-use anyhow::{Context, Error, Result};
+use anyhow::{Context, Error};
use tokio::{process::Command, signal};
use tracing::{debug, error, info, warn, Level};
use tracing_subscriber::{
@@ -41,7 +41,7 @@ mod wm_state;
/// Conditionally starts the WM or runs a CLI command based on the given
/// subcommand.
#[tokio::main]
-async fn main() -> Result<()> {
+async fn main() -> anyhow::Result<()> {
let args = std::env::args().collect::<Vec<_>>();
let app_command = AppCommand::parse_with_default(&args);
@@ -68,32 +68,8 @@ async fn main() -> Result<()> {
async fn start_wm(
config_path: Option<PathBuf>,
verbosity: Verbosity,
-) -> Result<()> {
- let error_log_dir = home::home_dir()
- .context("Unable to get home directory.")?
- .join(".glzr/glazewm/");
-
- let error_writer =
- tracing_appender::rolling::never(error_log_dir, "errors.log");
-
- let subscriber = tracing_subscriber::registry()
- .with(
- // Output to stdout with specified verbosity level.
- fmt::Layer::new()
- .with_writer(std::io::stdout.with_max_level(verbosity.level())),
- )
- .with(
- // Output to error log file.
- fmt::Layer::new()
- .with_writer(error_writer.with_max_level(Level::ERROR)),
- );
-
- tracing::subscriber::set_global_default(subscriber)?;
-
- info!(
- "Starting WM with log level {:?}.",
- verbosity.level().to_string()
- );
+) -> anyhow::Result<()> {
+ setup_logging(&verbosity)?;
// Ensure that only one instance of the WM is running.
let _single_instance = Platform::new_single_instance()?;
@@ -116,15 +92,15 @@ async fn start_wm(
// Run startup commands.
let startup_commands = config.value.general.startup_commands.clone();
- wm.process_commands(startup_commands, None, &mut config)?;
+ wm.process_commands(&startup_commands, None, &mut config)?;
loop {
let res = tokio::select! {
- Some(_) = tray.exit_rx.recv() => {
+ Some(()) = tray.exit_rx.recv() => {
info!("Exiting through system tray.");
break;
},
- Some(_) = wm.exit_rx.recv() => {
+ Some(()) = wm.exit_rx.recv() => {
info!("Exiting through WM command.");
break;
},
@@ -145,8 +121,8 @@ async fn start_wm(
ipc_server.process_message(
message,
- response_tx,
- disconnection_tx,
+ &response_tx,
+ &disconnection_tx,
&mut wm,
&mut config,
)
@@ -171,9 +147,9 @@ async fn start_wm(
ipc_server.process_event(wm_event)
},
- Some(_) = tray.config_reload_rx.recv() => {
+ Some(()) = tray.config_reload_rx.recv() => {
wm.process_commands(
- vec![InvokeCommand::WmReloadConfig],
+ &vec![InvokeCommand::WmReloadConfig],
None,
&mut config,
).map(|_| ())
@@ -188,7 +164,7 @@ async fn start_wm(
// Run shutdown commands.
let shutdown_commands = config.value.general.shutdown_commands.clone();
- wm.process_commands(shutdown_commands, None, &mut config)?;
+ wm.process_commands(&shutdown_commands, None, &mut config)?;
wm.state.emit_event(WmEvent::ApplicationExiting);
@@ -204,6 +180,39 @@ async fn start_wm(
Ok(())
}
+/// Initialize logging with the specified verbosity level.
+///
+/// Error logs are saved to `~/.glzr/glazewm/errors.log`.
+fn setup_logging(verbosity: &Verbosity) -> anyhow::Result<()> {
+ let error_log_dir = home::home_dir()
+ .context("Unable to get home directory.")?
+ .join(".glzr/glazewm/");
+
+ let error_writer =
+ tracing_appender::rolling::never(error_log_dir, "errors.log");
+
+ let subscriber = tracing_subscriber::registry()
+ .with(
+ // Output to stdout with specified verbosity level.
+ fmt::Layer::new()
+ .with_writer(std::io::stdout.with_max_level(verbosity.level())),
+ )
+ .with(
+ // Output to error log file.
+ fmt::Layer::new()
+ .with_writer(error_writer.with_max_level(Level::ERROR)),
+ );
+
+ tracing::subscriber::set_global_default(subscriber)?;
+
+ info!(
+ "Starting WM with log level {:?}.",
+ verbosity.level().to_string()
+ );
+
+ Ok(())
+}
+
/// Launches watcher binary. This is a separate process that is responsible
/// for restoring hidden windows in case the main WM process crashes.
///
diff --git a/packages/wm/src/models/container.rs b/packages/wm/src/models/container.rs
index 44c6de3a..a5b3e978 100644
--- a/packages/wm/src/models/container.rs
+++ b/packages/wm/src/models/container.rs
@@ -12,6 +12,7 @@ use wm_common::{
};
use wm_platform::NativeWindow;
+#[allow(clippy::wildcard_imports)]
use crate::{
models::{
Monitor, NonTilingWindow, RootContainer, SplitContainer, TilingWindow,
@@ -197,7 +198,9 @@ impl TryFrom<TilingContainer> for WindowContainer {
TilingContainer::TilingWindow(c) => {
Ok(WindowContainer::TilingWindow(c))
}
- _ => Err("Cannot convert type to a `WindowContainer`."),
+ TilingContainer::Split(_) => {
+ Err("Cannot convert type to a `WindowContainer`.")
+ }
}
}
}
@@ -253,7 +256,9 @@ impl TryFrom<TilingContainer> for DirectionContainer {
fn try_from(container: TilingContainer) -> Result<Self, Self::Error> {
match container {
TilingContainer::Split(c) => Ok(DirectionContainer::Split(c)),
- _ => Err("Cannot convert type to a `DirectionContainer`."),
+ TilingContainer::TilingWindow(_) => {
+ Err("Cannot convert type to a `DirectionContainer`.")
+ }
}
}
}
diff --git a/packages/wm/src/models/monitor.rs b/packages/wm/src/models/monitor.rs
index 8229c99b..3b42e5ed 100644
--- a/packages/wm/src/models/monitor.rs
+++ b/packages/wm/src/models/monitor.rs
@@ -86,7 +86,7 @@ impl Monitor {
let children = self
.children()
.iter()
- .map(|child| child.to_dto())
+ .map(CommonGetters::to_dto)
.try_collect()?;
Ok(ContainerDto::Monitor(MonitorDto {
diff --git a/packages/wm/src/models/non_tiling_window.rs b/packages/wm/src/models/non_tiling_window.rs
index 0380930e..c4c3cbcd 100644
--- a/packages/wm/src/models/non_tiling_window.rs
+++ b/packages/wm/src/models/non_tiling_window.rs
@@ -43,6 +43,7 @@ struct NonTilingWindowInner {
}
impl NonTilingWindow {
+ #[allow(clippy::too_many_arguments)]
pub fn new(
id: Option<Uuid>,
native: NativeWindow,
diff --git a/packages/wm/src/models/root_container.rs b/packages/wm/src/models/root_container.rs
index 0623af94..8ad60b2c 100644
--- a/packages/wm/src/models/root_container.rs
+++ b/packages/wm/src/models/root_container.rs
@@ -58,7 +58,7 @@ impl RootContainer {
let children = self
.children()
.iter()
- .map(|child| child.to_dto())
+ .map(CommonGetters::to_dto)
.try_collect()?;
Ok(ContainerDto::Root(RootContainerDto {
diff --git a/packages/wm/src/models/split_container.rs b/packages/wm/src/models/split_container.rs
index f5a2ebb5..7c524872 100644
--- a/packages/wm/src/models/split_container.rs
+++ b/packages/wm/src/models/split_container.rs
@@ -59,7 +59,7 @@ impl SplitContainer {
let children = self
.children()
.iter()
- .map(|child| child.to_dto())
+ .map(CommonGetters::to_dto)
.try_collect()?;
Ok(ContainerDto::Split(SplitContainerDto {
diff --git a/packages/wm/src/models/tiling_window.rs b/packages/wm/src/models/tiling_window.rs
index 94afcf11..021511d2 100644
--- a/packages/wm/src/models/tiling_window.rs
+++ b/packages/wm/src/models/tiling_window.rs
@@ -49,6 +49,7 @@ struct TilingWindowInner {
}
impl TilingWindow {
+ #[allow(clippy::too_many_arguments)]
pub fn new(
id: Option<Uuid>,
native: NativeWindow,
diff --git a/packages/wm/src/models/workspace.rs b/packages/wm/src/models/workspace.rs
index a7ff3132..0d27b5a0 100644
--- a/packages/wm/src/models/workspace.rs
+++ b/packages/wm/src/models/workspace.rs
@@ -68,8 +68,7 @@ impl Workspace {
self
.monitor()
.and_then(|monitor| monitor.displayed_workspace())
- .map(|workspace| workspace.id() == self.id())
- .unwrap_or(false)
+ .is_some_and(|workspace| workspace.id() == self.id())
}
pub fn set_gaps_config(&self, gaps_config: GapsConfig) {
@@ -83,7 +82,7 @@ impl Workspace {
let children = self
.children()
.iter()
- .map(|child| child.to_dto())
+ .map(CommonGetters::to_dto)
.try_collect()?;
Ok(ContainerDto::Workspace(WorkspaceDto {
diff --git a/packages/wm/src/models/workspace_target.rs b/packages/wm/src/models/workspace_target.rs
index 941b2b50..412667f0 100644
--- a/packages/wm/src/models/workspace_target.rs
+++ b/packages/wm/src/models/workspace_target.rs
@@ -7,5 +7,6 @@ pub enum WorkspaceTarget {
PreviousActive,
Next,
Previous,
+ #[allow(dead_code)]
Direction(Direction),
}
diff --git a/packages/wm/src/sys_tray.rs b/packages/wm/src/sys_tray.rs
index 1c083beb..32c8ba34 100644
--- a/packages/wm/src/sys_tray.rs
+++ b/packages/wm/src/sys_tray.rs
@@ -9,7 +9,7 @@ use tray_icon::{
};
use wm_platform::Platform;
-/// Ordinal to IDI_ICON definition in embedded resource file.
+/// Ordinal to `IDI_ICON` definition in embedded resource file.
const IDI_ICON: u16 = 32512;
pub struct SystemTray {
diff --git a/packages/wm/src/traits/common_getters.rs b/packages/wm/src/traits/common_getters.rs
index 9940db22..d9ba9c9c 100644
--- a/packages/wm/src/traits/common_getters.rs
+++ b/packages/wm/src/traits/common_getters.rs
@@ -215,7 +215,7 @@ pub trait CommonGetters {
fn ancestors(&self) -> Ancestors {
Ancestors {
- start: self.parent().map(Into::into),
+ start: self.parent(),
}
}
@@ -275,11 +275,7 @@ pub trait CommonGetters {
fn has_focus(&self, end_ancestor: Option<Container>) -> bool {
self
.self_and_ancestors()
- .take_while(|ancestor| {
- end_ancestor
- .as_ref()
- .map_or(true, |end_ancestor| end_ancestor != ancestor)
- })
+ .take_while(|ancestor| end_ancestor.as_ref() != Some(ancestor))
.chain(end_ancestor.clone())
.all(|ancestor| ancestor.focus_index() == 0)
}
@@ -295,7 +291,7 @@ impl Iterator for Ancestors {
fn next(&mut self) -> Option<Container> {
self.start.take().inspect(|container| {
- self.start = container.parent().map(Into::into);
+ self.start = container.parent();
})
}
}
diff --git a/packages/wm/src/traits/position_getters.rs b/packages/wm/src/traits/position_getters.rs
index 28e5b6bc..725667b9 100644
--- a/packages/wm/src/traits/position_getters.rs
+++ b/packages/wm/src/traits/position_getters.rs
@@ -29,6 +29,11 @@ macro_rules! impl_position_getters_as_resizable {
TilingDirection::Horizontal => horizontal_gap,
};
+ #[allow(
+ clippy::cast_precision_loss,
+ clippy::cast_possible_truncation,
+ clippy::cast_possible_wrap
+ )]
let (width, height) = match parent.tiling_direction() {
TilingDirection::Vertical => {
let available_height = parent_rect.height()
@@ -44,7 +49,7 @@ macro_rules! impl_position_getters_as_resizable {
- inner_gap * self.tiling_siblings().count() as i32;
let width =
- (self.tiling_size() * available_width as f32) as i32;
+ (available_width as f32 * self.tiling_size()).round() as i32;
(width, parent_rect.height())
}
diff --git a/packages/wm/src/traits/tiling_size_getters.rs b/packages/wm/src/traits/tiling_size_getters.rs
index 940fbe78..df4144e0 100644
--- a/packages/wm/src/traits/tiling_size_getters.rs
+++ b/packages/wm/src/traits/tiling_size_getters.rs
@@ -25,9 +25,10 @@ pub trait TilingSizeGetters: CommonGetters {
let monitor_rect = monitor.to_rect()?;
let gaps_config = self.gaps_config();
- let scale_factor = match gaps_config.scale_with_dpi {
- true => monitor.native().scale_factor()?,
- false => 1.,
+ let scale_factor = if gaps_config.scale_with_dpi {
+ monitor.native().scale_factor()?
+ } else {
+ 1.
};
Ok((
@@ -55,24 +56,24 @@ pub trait TilingSizeGetters: CommonGetters {
TilingDirection::Vertical => is_width_resize,
};
- let container_to_resize = match is_inverse_resize {
- true => match parent {
+ let container_to_resize = if is_inverse_resize {
+ match parent {
// Prevent workspaces from being resized.
DirectionContainer::Split(parent) => Some(parent.into()),
- _ => None,
- },
- false => {
- let grandparent = parent.parent().context("No grandparent.")?;
-
- match self.tiling_siblings().count() > 0 {
- // Window can only be resized if it has siblings.
- true => Some(self.as_tiling_container()?),
- // Resize grandparent in layouts like H[1 V[2 H[3]]], where
- // container 3 is resized horizontally.
- false => match grandparent {
- Container::Split(grandparent) => Some(grandparent.into()),
- _ => None,
- },
+ DirectionContainer::Workspace(_) => None,
+ }
+ } else {
+ let grandparent = parent.parent().context("No grandparent.")?;
+
+ if self.tiling_siblings().count() > 0 {
+ // Window can only be resized if it has siblings.
+ Some(self.as_tiling_container()?)
+ } else {
+ // Resize grandparent in layouts like H[1 V[2 H[3]]], where
+ // container 3 is resized horizontally.
+ match grandparent {
+ Container::Split(grandparent) => Some(grandparent.into()),
+ _ => None,
}
}
};
diff --git a/packages/wm/src/user_config.rs b/packages/wm/src/user_config.rs
index 46dca9bd..cbfefba1 100644
--- a/packages/wm/src/user_config.rs
+++ b/packages/wm/src/user_config.rs
@@ -64,7 +64,7 @@ impl UserConfig {
config_path: &PathBuf,
) -> anyhow::Result<(ParsedConfig, String)> {
if !config_path.exists() {
- Self::create_sample(config_path.clone())?;
+ Self::create_sample(config_path)?;
}
let config_str = fs::read_to_string(config_path)
@@ -78,7 +78,7 @@ impl UserConfig {
}
/// Initializes a new config file from the sample config resource.
- fn create_sample(config_path: PathBuf) -> Result<()> {
+ fn create_sample(config_path: &PathBuf) -> Result<()> {
let parent_dir =
config_path.parent().context("Invalid config path.")?;
@@ -86,7 +86,7 @@ impl UserConfig {
format!("Unable to create directory {}.", &config_path.display())
})?;
- fs::write(&config_path, SAMPLE_CONFIG).with_context(|| {
+ fs::write(config_path, SAMPLE_CONFIG).with_context(|| {
format!("Unable to write to {}.", config_path.display())
})?;
@@ -244,20 +244,17 @@ impl UserConfig {
let is_process_match = match_config
.window_process
.as_ref()
- .map(|match_type| match_type.is_match(&window_process))
- .unwrap_or(true);
+ .is_none_or(|match_type| match_type.is_match(&window_process));
let is_class_match = match_config
.window_class
.as_ref()
- .map(|match_type| match_type.is_match(&window_class))
- .unwrap_or(true);
+ .is_none_or(|match_type| match_type.is_match(&window_class));
let is_title_match = match_config
.window_title
.as_ref()
- .map(|match_type| match_type.is_match(&window_title))
- .unwrap_or(true);
+ .is_none_or(|match_type| match_type.is_match(&window_title));
is_process_match && is_class_match && is_title_match
})
@@ -296,8 +293,9 @@ impl UserConfig {
config
.bind_to_monitor
.as_ref()
- .map(|monitor_index| monitor.index() == *monitor_index as usize)
- .unwrap_or(false)
+ .is_some_and(|monitor_index| {
+ monitor.index() == *monitor_index as usize
+ })
})
}
@@ -314,7 +312,7 @@ impl UserConfig {
.iter()
.find(|config| config.bind_to_monitor.is_none())
.or(inactive_configs.first())
- .cloned()
+ .copied()
}
pub fn workspace_config_index(
diff --git a/packages/wm/src/wm.rs b/packages/wm/src/wm.rs
index 3230af9a..e3c740b8 100644
--- a/packages/wm/src/wm.rs
+++ b/packages/wm/src/wm.rs
@@ -72,43 +72,44 @@ impl WindowManager {
handle_display_settings_changed(state, config)
}
PlatformEvent::KeybindingTriggered(kb_config) => {
- self.process_commands(kb_config.commands, None, config)?;
+ self.process_commands(&kb_config.commands, None, config)?;
// Return early since we don't want to redraw twice.
return Ok(());
}
PlatformEvent::MouseMove(event) => {
- handle_mouse_move(event, state, config)
+ handle_mouse_move(&event, state, config)
}
PlatformEvent::WindowDestroyed(window) => {
- handle_window_destroyed(window, state)
+ handle_window_destroyed(&window, state)
}
PlatformEvent::WindowFocused(window) => {
- handle_window_focused(window, state, config)
+ handle_window_focused(&window, state, config)
}
PlatformEvent::WindowHidden(window) => {
- handle_window_hidden(window, state)
+ handle_window_hidden(&window, state)
}
PlatformEvent::WindowLocationChanged(window) => {
- handle_window_location_changed(window, state, config)
+ handle_window_location_changed(&window, state, config)
}
PlatformEvent::WindowMinimized(window) => {
- handle_window_minimized(window, state, config)
+ handle_window_minimized(&window, state, config)
}
PlatformEvent::WindowMinimizeEnded(window) => {
- handle_window_minimize_ended(window, state, config)
+ handle_window_minimize_ended(&window, state, config)
}
PlatformEvent::WindowMovedOrResizedEnd(window) => {
- handle_window_moved_or_resized_end(window, state, config)
+ handle_window_moved_or_resized_end(&window, state, config)
}
PlatformEvent::WindowMovedOrResizedStart(window) => {
- handle_window_moved_or_resized_start(window, state)
+ handle_window_moved_or_resized_start(&window, state);
+ Ok(())
}
PlatformEvent::WindowShown(window) => {
handle_window_shown(window, state, config)
}
PlatformEvent::WindowTitleChanged(window) => {
- handle_window_title_changed(window, state, config)
+ handle_window_title_changed(&window, state, config)
}
}?;
@@ -117,7 +118,7 @@ impl WindowManager {
pub fn process_commands(
&mut self,
- commands: Vec<InvokeCommand>,
+ commands: &Vec<InvokeCommand>,
subject_container_id: Option<Uuid>,
config: &mut UserConfig,
) -> anyhow::Result<Uuid> {
@@ -126,7 +127,7 @@ impl WindowManager {
// Get the container to run WM commands with.
let subject_container = match subject_container_id {
Some(id) => state.container_by_id(id).with_context(|| {
- format!("No container found with the given ID '{}'.", id)
+ format!("No container found with the given ID '{id}'.")
})?,
None => state
.focused_container()
@@ -134,7 +135,7 @@ impl WindowManager {
};
let new_subject_container_id = WindowManager::run_commands(
- &commands,
+ commands,
subject_container,
state,
config,
@@ -155,7 +156,7 @@ impl WindowManager {
for command in commands {
WindowManager::run_command(
- &command,
+ command,
current_subject_container.clone(),
state,
config,
@@ -164,20 +165,20 @@ impl WindowManager {
// Update the subject container in case the container type changes.
// For example, when going from a tiling to a floating window.
current_subject_container =
- match current_subject_container.is_detached() {
- false => current_subject_container,
- true => {
- match state.container_by_id(current_subject_container.id()) {
- Some(container) => container,
- None => break,
- }
+ if current_subject_container.is_detached() {
+ match state.container_by_id(current_subject_container.id()) {
+ Some(container) => container,
+ None => break,
}
+ } else {
+ current_subject_container
}
}
Ok(current_subject_container.id())
}
+ #[allow(clippy::too_many_lines)]
pub fn run_command(
command: &InvokeCommand,
subject_container: Container,
@@ -223,7 +224,7 @@ impl WindowManager {
}
InvokeCommand::Focus(args) => {
if let Some(direction) = &args.direction {
- focus_in_direction(subject_container, direction, state)?;
+ focus_in_direction(&subject_container, direction, state)?;
}
if let Some(name) = &args.workspace {
@@ -341,37 +342,32 @@ impl WindowManager {
let workspace =
subject_container.workspace().context("No workspace.")?;
- move_workspace_in_direction(
- workspace,
- direction.clone(),
- state,
- config,
- )
+ move_workspace_in_direction(&workspace, direction, state, config)
}
InvokeCommand::Position(args) => {
match subject_container.as_window_container() {
- Ok(window) => match args.centered {
- true => set_window_position(
- window,
- WindowPositionTarget::Centered,
- state,
- ),
- false => set_window_position(
- window,
- WindowPositionTarget::Coordinates(
- args.x_pos.clone(),
- args.y_pos.clone(),
- ),
- state,
- ),
- },
+ Ok(window) => {
+ if args.centered {
+ set_window_position(
+ window,
+ &WindowPositionTarget::Centered,
+ state,
+ )
+ } else {
+ set_window_position(
+ window,
+ &WindowPositionTarget::Coordinates(args.x_pos, args.y_pos),
+ state,
+ )
+ }
+ }
_ => Ok(()),
}
}
InvokeCommand::Resize(args) => {
match subject_container.as_window_container() {
Ok(window) => resize_window(
- window,
+ &window,
args.width.clone(),
args.height.clone(),
state,
@@ -418,16 +414,13 @@ impl WindowManager {
if centered {
set_window_position(
window,
- WindowPositionTarget::Centered,
+ &WindowPositionTarget::Centered,
state,
)?;
} else if x_pos.is_some() || y_pos.is_some() {
set_window_position(
window,
- WindowPositionTarget::Coordinates(
- x_pos.clone(),
- y_pos.clone(),
- ),
+ &WindowPositionTarget::Coordinates(*x_pos, *y_pos),
state,
)?;
}
@@ -505,7 +498,7 @@ impl WindowManager {
InvokeCommand::SetOpacity { opacity } => {
match subject_container.as_window_container() {
Ok(window) => {
- _ = window.native().set_opacity(opacity.clone());
+ _ = window.native().set_opacity(opacity);
Ok(())
}
_ => Ok(()),
@@ -551,7 +544,7 @@ impl WindowManager {
if !window.has_custom_floating_placement() && centered {
set_window_position(
window,
- WindowPositionTarget::Centered,
+ &WindowPositionTarget::Centered,
state,
)?;
}
@@ -625,7 +618,7 @@ impl WindowManager {
subject_container,
state,
config,
- tiling_direction.clone(),
+ tiling_direction,
)
}
InvokeCommand::WmCycleFocus {
@@ -639,10 +632,7 @@ impl WindowManager {
InvokeCommand::WmEnableBindingMode { name } => {
enable_binding_mode(name, state, config)
}
- InvokeCommand::WmExit => {
- state.emit_exit();
- Ok(())
- }
+ InvokeCommand::WmExit => state.emit_exit(),
InvokeCommand::WmRedraw => {
let root_container = state.root_container.clone();
state
@@ -653,7 +643,10 @@ impl WindowManager {
Ok(())
}
InvokeCommand::WmReloadConfig => reload_config(state, config),
- InvokeCommand::WmTogglePause => toggle_pause(state),
+ InvokeCommand::WmTogglePause => {
+ toggle_pause(state);
+ Ok(())
+ }
}
}
}
diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rs
index 8f309500..79dc2cc4 100644
--- a/packages/wm/src/wm_state.rs
+++ b/packages/wm/src/wm_state.rs
@@ -143,7 +143,7 @@ impl WmState {
.or(self.workspaces().pop().map(Into::into))
.context("Failed to get container to focus.")?;
- set_focused_descendant(container_to_focus, None);
+ set_focused_descendant(&container_to_focus, None);
self.pending_sync.focus_change = true;
self.pending_sync.reset_window_effects = true;
@@ -161,7 +161,7 @@ impl WmState {
self
.monitors()
.iter()
- .flat_map(|monitor| monitor.workspaces())
+ .flat_map(Monitor::workspaces)
.collect()
}
@@ -276,6 +276,7 @@ impl WmState {
///
/// Returns a tuple of the workspace name and the `Workspace` instance
/// if active.
+ #[allow(clippy::too_many_lines)]
pub fn workspace_by_target(
&self,
origin_workspace: &Workspace,
@@ -284,6 +285,7 @@ impl WmState {
) -> anyhow::Result<(Option<String>, Option<Workspace>)> {
let (name, workspace) = match target {
WorkspaceTarget::Name(name) => {
+ #[allow(clippy::match_bool)]
match origin_workspace.config().name == name {
false => (Some(name.clone()), self.workspace_by_name(&name)),
// Toggle the workspace if it's already focused.
@@ -413,7 +415,7 @@ impl WmState {
.pending_sync
.containers_to_redraw
.iter()
- .flat_map(|container| container.self_and_descendants())
+ .flat_map(CommonGetters::self_and_descendants)
.filter(|container| !container.is_detached())
.filter_map(|container| container.try_into().ok())
.filter(|window: &WindowContainer| unique_ids.insert(window.id()))
@@ -444,8 +446,9 @@ impl WmState {
}
/// Starts graceful shutdown via an MSPC channel.
- pub fn emit_exit(&self) {
- self.exit_tx.send(()).unwrap()
+ pub fn emit_exit(&self) -> anyhow::Result<()> {
+ self.exit_tx.send(())?;
+ Ok(())
}
pub fn container_by_id(&self, id: Uuid) -> Option<Container> {
@@ -503,9 +506,11 @@ impl WmState {
.or(Some(workspace.into()))
}
+ /// Returns all containers that contain the given point.
+ #[allow(clippy::unused_self)]
pub fn containers_at_point(
&self,
- origin_container: Container,
+ origin_container: &Container,
point: &Point,
) -> Vec<Container> {
origin_container
@@ -513,28 +518,24 @@ impl WmState {
.filter(|descendant| {
descendant
.to_rect()
- .map(|frame| frame.contains_point(point))
+ .map(|rect| rect.contains_point(point))
.unwrap_or(false)
})
.collect()
}
- /// Returns all window under the mouse position
- pub fn monitor_at_position(&self, position: &Point) -> Option<Monitor> {
+ /// Returns the monitor that contains the given point.
+ pub fn monitor_at_point(&self, point: &Point) -> Option<Monitor> {
self
- .root_container
- .descendants()
- .filter_map(|container| match container {
- Container::Monitor(monitor) => Some(monitor),
- _ => None,
- })
- .find(|c| {
- let frame = c.to_rect();
- frame
- .ok()
- .map(|frame| frame.contains_point(position))
+ .monitors()
+ .iter()
+ .find(|monitor| {
+ monitor
+ .to_rect()
+ .map(|rect| rect.contains_point(point))
.unwrap_or(false)
})
+ .cloned()
}
}