From b6d19e6a12fb58aebe1d051b3c60c23d8e7cf889 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 17 Sep 2025 13:31:37 -0700 Subject: [PATCH] feat(wm): migrate workspace and layout code This commit migrates big chunks of code from komorebi for Windows which deal with state related to the Workspace struct, Layouts and the Arrangement trait. Layout remains an enum, but only the Layout::Default variant with DefaultLayout has been migrated because there are no plans to support EOL features in komorebi for Mac (custom layouts). The code for updating the layout in main.rs has been moved to Workspace.update, which is now called from main.rs instead. As part of this initial migration of code, this project has been restructured a little to match the layout of komorebi for Windows to minimize my own confusion. --- justfile | 6 +- komorebi/src/core/arrangement.rs | 1129 ++++++++++++++++++++++ komorebi/src/core/default_layout.rs | 200 ++++ komorebi/src/core/direction.rs | 347 +++++++ komorebi/src/core/layout.rs | 26 + komorebi/src/core/mod.rs | 15 + komorebi/src/core/operation_direction.rs | 58 ++ komorebi/src/core/rect.rs | 105 ++ komorebi/src/layout.rs | 82 -- komorebi/src/lib.rs | 4 +- komorebi/src/macos_api.rs | 2 +- komorebi/src/main.rs | 59 +- komorebi/src/rect.rs | 68 -- komorebi/src/window.rs | 2 +- komorebi/src/window_manager.rs | 23 +- komorebi/src/workspace.rs | 133 +++ 16 files changed, 2043 insertions(+), 216 deletions(-) create mode 100644 komorebi/src/core/arrangement.rs create mode 100644 komorebi/src/core/default_layout.rs create mode 100644 komorebi/src/core/direction.rs create mode 100644 komorebi/src/core/layout.rs create mode 100644 komorebi/src/core/mod.rs create mode 100644 komorebi/src/core/operation_direction.rs create mode 100644 komorebi/src/core/rect.rs delete mode 100644 komorebi/src/layout.rs delete mode 100644 komorebi/src/rect.rs create mode 100644 komorebi/src/workspace.rs diff --git a/justfile b/justfile index ad1d795e..6a068793 100644 --- a/justfile +++ b/justfile @@ -31,4 +31,8 @@ trace target $RUST_LOG="trace": depgen: cargo deny check - cargo deny list --format json | jq 'del(.unlicensed)' > dependencies.json \ No newline at end of file + cargo deny list --format json | jq 'del(.unlicensed)' > dependencies.json + +push: + git push origin master + git push komocorp master \ No newline at end of file diff --git a/komorebi/src/core/arrangement.rs b/komorebi/src/core/arrangement.rs new file mode 100644 index 00000000..c256ec1d --- /dev/null +++ b/komorebi/src/core/arrangement.rs @@ -0,0 +1,1129 @@ +use std::num::NonZeroUsize; + +use crate::core::default_layout::DefaultLayout; +use crate::core::default_layout::LayoutOptions; +use crate::core::rect::Rect; +use serde::Deserialize; +use serde::Serialize; + +pub trait Arrangement { + #[allow(clippy::too_many_arguments)] + fn calculate( + &self, + area: &Rect, + len: NonZeroUsize, + container_padding: Option, + layout_flip: Option, + resize_dimensions: &[Option], + focused_idx: usize, + layout_options: Option, + latest_layout: &[Rect], + ) -> Vec; +} + +impl Arrangement for DefaultLayout { + #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] + fn calculate( + &self, + area: &Rect, + len: NonZeroUsize, + container_padding: Option, + layout_flip: Option, + resize_dimensions: &[Option], + focused_idx: usize, + layout_options: Option, + latest_layout: &[Rect], + ) -> Vec { + let len = usize::from(len); + let mut dimensions = match self { + Self::Scrolling => { + let column_count = layout_options + .and_then(|o| o.scrolling.map(|s| s.columns)) + .unwrap_or(3); + + let column_width = area.right / column_count as i32; + let mut layouts = Vec::with_capacity(len); + + match len { + // treat < 3 windows the same as the columns layout + len if len < 3 => { + layouts = columns(area, len); + + let adjustment = calculate_columns_adjustment(resize_dimensions); + layouts.iter_mut().zip(adjustment.iter()).for_each( + |(layout, adjustment)| { + layout.top += adjustment.top; + layout.bottom += adjustment.bottom; + layout.left += adjustment.left; + layout.right += adjustment.right; + }, + ); + + if matches!( + layout_flip, + Some(Axis::Horizontal | Axis::HorizontalAndVertical) + ) && let 2.. = len + { + columns_reverse(&mut layouts); + } + } + // treat >= column_count as scrolling + len => { + let visible_columns = area.right / column_width; + let first_visible: isize = if focused_idx == 0 { + // if focused idx is 0, we are at the beginning of the scrolling strip + 0 + } else { + let previous_first_visible = if latest_layout.is_empty() { + 0 + } else { + // previous first_visible based on the left position of the first visible window + let left_edge = area.left; + latest_layout + .iter() + .position(|rect| rect.left >= left_edge) + .unwrap_or(0) as isize + }; + + let focused_idx = focused_idx as isize; + + if focused_idx < previous_first_visible { + // focused window is off the left edge, we need to scroll left + focused_idx + } else if focused_idx + >= previous_first_visible + visible_columns as isize + { + // focused window is off the right edge, we need to scroll right + // and make sure it's the last visible window + (focused_idx + 1 - visible_columns as isize).max(0) + } else { + // focused window is already visible, we don't need to scroll + previous_first_visible + } + .min( + (len as isize) + .saturating_sub(visible_columns as isize) + .max(0), + ) + }; + + for i in 0..len { + let position = (i as isize) - first_visible; + let left = area.left + (position as i32 * column_width); + + layouts.push(Rect { + left, + top: area.top, + right: column_width, + bottom: area.bottom, + }); + } + + let adjustment = calculate_scrolling_adjustment(resize_dimensions); + layouts.iter_mut().zip(adjustment.iter()).for_each( + |(layout, adjustment)| { + layout.top += adjustment.top; + layout.bottom += adjustment.bottom; + layout.left += adjustment.left; + layout.right += adjustment.right; + }, + ); + } + } + + layouts + } + Self::BSP => recursive_fibonacci( + 0, + len, + area, + layout_flip, + calculate_resize_adjustments(resize_dimensions), + ), + Self::Columns => { + let mut layouts = columns(area, len); + + let adjustment = calculate_columns_adjustment(resize_dimensions); + layouts + .iter_mut() + .zip(adjustment.iter()) + .for_each(|(layout, adjustment)| { + layout.top += adjustment.top; + layout.bottom += adjustment.bottom; + layout.left += adjustment.left; + layout.right += adjustment.right; + }); + + if matches!( + layout_flip, + Some(Axis::Horizontal | Axis::HorizontalAndVertical) + ) && let 2.. = len + { + columns_reverse(&mut layouts); + } + + layouts + } + Self::Rows => { + let mut layouts = rows(area, len); + + let adjustment = calculate_rows_adjustment(resize_dimensions); + layouts + .iter_mut() + .zip(adjustment.iter()) + .for_each(|(layout, adjustment)| { + layout.top += adjustment.top; + layout.bottom += adjustment.bottom; + layout.left += adjustment.left; + layout.right += adjustment.right; + }); + + if matches!( + layout_flip, + Some(Axis::Vertical | Axis::HorizontalAndVertical) + ) && let 2.. = len + { + rows_reverse(&mut layouts); + } + + layouts + } + Self::VerticalStack => { + let mut layouts: Vec = vec![]; + + let primary_right = match len { + 1 => area.right, + _ => area.right / 2, + }; + + let main_left = area.left; + let stack_left = area.left + primary_right; + + if len >= 1 { + layouts.push(Rect { + left: main_left, + top: area.top, + right: primary_right, + bottom: area.bottom, + }); + + if len > 1 { + layouts.append(&mut rows( + &Rect { + left: stack_left, + top: area.top, + right: area.right - primary_right, + bottom: area.bottom, + }, + len - 1, + )); + } + } + + let adjustment = calculate_vertical_stack_adjustment(resize_dimensions); + layouts + .iter_mut() + .zip(adjustment.iter()) + .for_each(|(layout, adjustment)| { + layout.top += adjustment.top; + layout.bottom += adjustment.bottom; + layout.left += adjustment.left; + layout.right += adjustment.right; + }); + + if matches!( + layout_flip, + Some(Axis::Horizontal | Axis::HorizontalAndVertical) + ) && let 2.. = len + { + let (primary, rest) = layouts.split_at_mut(1); + let primary = &mut primary[0]; + + for rect in rest.iter_mut() { + rect.left = primary.left; + } + primary.left = rest[0].left + rest[0].right; + } + + if matches!( + layout_flip, + Some(Axis::Vertical | Axis::HorizontalAndVertical) + ) && let 3.. = len + { + rows_reverse(&mut layouts[1..]); + } + + layouts + } + Self::RightMainVerticalStack => { + // Shamelessly borrowed from LeftWM: https://github.com/leftwm/leftwm/commit/f673851745295ae7584a102535566f559d96a941 + let mut layouts: Vec = vec![]; + + let primary_width = match len { + 1 => area.right, + _ => area.right / 2, + }; + + let primary_left = match len { + 1 => 0, + _ => area.right - primary_width, + }; + + if len >= 1 { + layouts.push(Rect { + left: area.left + primary_left, + top: area.top, + right: primary_width, + bottom: area.bottom, + }); + + if len > 1 { + layouts.append(&mut rows( + &Rect { + left: area.left, + top: area.top, + right: primary_left, + bottom: area.bottom, + }, + len - 1, + )); + } + } + + let adjustment = calculate_right_vertical_stack_adjustment(resize_dimensions); + layouts + .iter_mut() + .zip(adjustment.iter()) + .for_each(|(layout, adjustment)| { + layout.top += adjustment.top; + layout.bottom += adjustment.bottom; + layout.left += adjustment.left; + layout.right += adjustment.right; + }); + + if matches!( + layout_flip, + Some(Axis::Horizontal | Axis::HorizontalAndVertical) + ) && let 2.. = len + { + let (primary, rest) = layouts.split_at_mut(1); + let primary = &mut primary[0]; + + primary.left = rest[0].left; + for rect in rest.iter_mut() { + rect.left = primary.left + primary.right; + } + } + + if matches!( + layout_flip, + Some(Axis::Vertical | Axis::HorizontalAndVertical) + ) && let 3.. = len + { + rows_reverse(&mut layouts[1..]); + } + + layouts + } + Self::HorizontalStack => { + let mut layouts: Vec = vec![]; + + let bottom = match len { + 1 => area.bottom, + _ => area.bottom / 2, + }; + + let main_top = area.top; + let stack_top = area.top + bottom; + + if len >= 1 { + layouts.push(Rect { + left: area.left, + top: main_top, + right: area.right, + bottom, + }); + + if len > 1 { + layouts.append(&mut columns( + &Rect { + left: area.left, + top: stack_top, + right: area.right, + bottom: area.bottom - bottom, + }, + len - 1, + )); + } + } + + let adjustment = calculate_horizontal_stack_adjustment(resize_dimensions); + layouts + .iter_mut() + .zip(adjustment.iter()) + .for_each(|(layout, adjustment)| { + layout.top += adjustment.top; + layout.bottom += adjustment.bottom; + layout.left += adjustment.left; + layout.right += adjustment.right; + }); + + if matches!( + layout_flip, + Some(Axis::Vertical | Axis::HorizontalAndVertical) + ) && let 2.. = len + { + let (primary, rest) = layouts.split_at_mut(1); + let primary = &mut primary[0]; + + for rect in rest.iter_mut() { + rect.top = primary.top; + } + primary.top = rest[0].top + rest[0].bottom; + } + + if matches!( + layout_flip, + Some(Axis::Horizontal | Axis::HorizontalAndVertical) + ) && let 3.. = len + { + columns_reverse(&mut layouts[1..]); + } + + layouts + } + Self::UltrawideVerticalStack => { + let mut layouts: Vec = vec![]; + + let primary_right = match len { + 1 => area.right, + _ => area.right / 2, + }; + + let secondary_right = match len { + 1 => 0, + 2 => area.right - primary_right, + _ => (area.right - primary_right) / 2, + }; + + let (primary_left, secondary_left, stack_left) = match len { + 1 => (area.left, 0, 0), + 2 => { + let primary = area.left + secondary_right; + let secondary = area.left; + + (primary, secondary, 0) + } + _ => { + let primary = area.left + secondary_right; + let secondary = area.left; + let stack = area.left + primary_right + secondary_right; + + (primary, secondary, stack) + } + }; + + if len >= 1 { + layouts.push(Rect { + left: primary_left, + top: area.top, + right: primary_right, + bottom: area.bottom, + }); + + if len >= 2 { + layouts.push(Rect { + left: secondary_left, + top: area.top, + right: secondary_right, + bottom: area.bottom, + }); + + if len > 2 { + layouts.append(&mut rows( + &Rect { + left: stack_left, + top: area.top, + right: secondary_right, + bottom: area.bottom, + }, + len - 2, + )); + } + } + } + + let adjustment = calculate_ultrawide_adjustment(resize_dimensions); + layouts + .iter_mut() + .zip(adjustment.iter()) + .for_each(|(layout, adjustment)| { + layout.top += adjustment.top; + layout.bottom += adjustment.bottom; + layout.left += adjustment.left; + layout.right += adjustment.right; + }); + + if matches!( + layout_flip, + Some(Axis::Horizontal | Axis::HorizontalAndVertical) + ) { + match len { + 2 => { + let (primary, secondary) = layouts.split_at_mut(1); + let primary = &mut primary[0]; + let secondary = &mut secondary[0]; + + primary.left = secondary.left; + secondary.left = primary.left + primary.right; + } + 3.. => { + let (primary, rest) = layouts.split_at_mut(1); + let (secondary, tertiary) = rest.split_at_mut(1); + let primary = &mut primary[0]; + let secondary = &mut secondary[0]; + + for rect in tertiary.iter_mut() { + rect.left = secondary.left; + } + primary.left = tertiary[0].left + tertiary[0].right; + secondary.left = primary.left + primary.right; + } + _ => {} + } + } + + if matches!( + layout_flip, + Some(Axis::Vertical | Axis::HorizontalAndVertical) + ) && let 4.. = len + { + rows_reverse(&mut layouts[2..]); + } + + layouts + } + #[allow( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_possible_wrap + )] + Self::Grid => { + // Shamelessly lifted from LeftWM + // https://github.com/leftwm/leftwm/blob/18675067b8450e520ef75db2ebbb0d973aa1199e/leftwm-core/src/layouts/grid_horizontal.rs + let mut layouts: Vec = vec![]; + layouts.resize(len, Rect::default()); + + let len = len as i32; + + let num_cols = (len as f32).sqrt().ceil() as i32; + let mut iter = layouts.iter_mut().enumerate().peekable(); + + for col in 0..num_cols { + let iter_peek = iter.peek().map(|x| x.0).unwrap_or_default() as i32; + let remaining_windows = len - iter_peek; + let remaining_columns = num_cols - col; + let num_rows_in_this_col = remaining_windows / remaining_columns; + + let win_height = area.bottom / num_rows_in_this_col; + let win_width = area.right / num_cols; + + for row in 0..num_rows_in_this_col { + if let Some((_idx, win)) = iter.next() { + let mut left = area.left + win_width * col; + let mut top = area.top + win_height * row; + + match layout_flip { + Some(Axis::Horizontal) => { + left = area.right - win_width * (col + 1) + area.left; + } + Some(Axis::Vertical) => { + top = area.bottom - win_height * (row + 1) + area.top; + } + Some(Axis::HorizontalAndVertical) => { + left = area.right - win_width * (col + 1) + area.left; + top = area.bottom - win_height * (row + 1) + area.top; + } + None => {} // No flip + } + + win.bottom = win_height; + win.right = win_width; + win.left = left; + win.top = top; + } + } + } + + layouts + } + }; + + dimensions + .iter_mut() + .for_each(|l| l.add_padding(container_padding.unwrap_or_default())); + + dimensions + } +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)] +pub enum Axis { + Horizontal, + Vertical, + HorizontalAndVertical, +} + +#[must_use] +fn columns(area: &Rect, len: usize) -> Vec { + #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)] + let right = area.right / len as i32; + let mut left = 0; + + let mut layouts: Vec = vec![]; + for _ in 0..len { + layouts.push(Rect { + left: area.left + left, + top: area.top, + right, + bottom: area.bottom, + }); + + left += right; + } + + layouts +} + +#[must_use] +fn rows(area: &Rect, len: usize) -> Vec { + #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)] + let bottom = area.bottom / len as i32; + let mut top = 0; + + let mut layouts: Vec = vec![]; + for _ in 0..len { + layouts.push(Rect { + left: area.left, + top: area.top + top, + right: area.right, + bottom, + }); + + top += bottom; + } + + layouts +} + +fn columns_reverse(columns: &mut [Rect]) { + let len = columns.len(); + columns[len - 1].left = columns[0].left; + for i in (0..len - 1).rev() { + columns[i].left = columns[i + 1].left + columns[i + 1].right; + } +} + +fn rows_reverse(rows: &mut [Rect]) { + let len = rows.len(); + rows[len - 1].top = rows[0].top; + for i in (0..len - 1).rev() { + rows[i].top = rows[i + 1].top + rows[i + 1].bottom; + } +} + +fn calculate_resize_adjustments(resize_dimensions: &[Option]) -> Vec> { + let mut resize_adjustments = resize_dimensions.to_vec(); + + // This needs to be aware of layout flips + for (i, opt) in resize_dimensions.iter().enumerate() { + if let Some(resize_ref) = opt + && i > 0 + { + if resize_ref.left != 0 { + #[allow(clippy::if_not_else)] + let range = if i == 1 { + 0..1 + } else if i & 1 != 0 { + i - 1..i + } else { + i - 2..i + }; + + for n in range { + let should_adjust = n % 2 == 0; + if should_adjust { + if let Some(Some(adjacent_resize)) = resize_adjustments.get_mut(n) { + adjacent_resize.right += resize_ref.left; + } else { + resize_adjustments[n] = Option::from(Rect { + left: 0, + top: 0, + right: resize_ref.left, + bottom: 0, + }); + } + } + } + + if let Some(rr) = resize_adjustments[i].as_mut() { + rr.left = 0; + } + } + + if resize_ref.top != 0 { + let range = if i == 1 { + 0..1 + } else if i & 1 == 0 { + i - 1..i + } else { + i - 2..i + }; + + for n in range { + let should_adjust = n % 2 != 0; + if should_adjust { + if let Some(Some(adjacent_resize)) = resize_adjustments.get_mut(n) { + adjacent_resize.bottom += resize_ref.top; + } else { + resize_adjustments[n] = Option::from(Rect { + left: 0, + top: 0, + right: 0, + bottom: resize_ref.top, + }); + } + } + } + + if let Some(Some(resize)) = resize_adjustments.get_mut(i) { + resize.top = 0; + } + } + } + } + + let cleaned_resize_adjustments: Vec<_> = resize_adjustments + .iter() + .map(|adjustment| match adjustment { + None => None, + Some(rect) if rect.eq(&Rect::default()) => None, + Some(_) => *adjustment, + }) + .collect(); + + cleaned_resize_adjustments +} + +#[allow(clippy::only_used_in_recursion)] +fn recursive_fibonacci( + idx: usize, + count: usize, + area: &Rect, + layout_flip: Option, + resize_adjustments: Vec>, +) -> Vec { + let mut a = *area; + + let resized = if let Some(Some(r)) = resize_adjustments.get(idx) { + a.left += r.left; + a.top += r.top; + a.right += r.right; + a.bottom += r.bottom; + a + } else { + *area + }; + + let half_width = area.right / 2; + let half_height = area.bottom / 2; + let half_resized_width = resized.right / 2; + let half_resized_height = resized.bottom / 2; + + let (main_x, alt_x, alt_y, main_y); + + if let Some(flip) = layout_flip { + match flip { + Axis::Horizontal => { + main_x = resized.left + half_width + (half_width - half_resized_width); + alt_x = resized.left; + + alt_y = resized.top + half_resized_height; + main_y = resized.top; + } + Axis::Vertical => { + main_y = resized.top + half_height + (half_height - half_resized_height); + alt_y = resized.top; + + main_x = resized.left; + alt_x = resized.left + half_resized_width; + } + Axis::HorizontalAndVertical => { + main_x = resized.left + half_width + (half_width - half_resized_width); + alt_x = resized.left; + main_y = resized.top + half_height + (half_height - half_resized_height); + alt_y = resized.top; + } + } + } else { + main_x = resized.left; + alt_x = resized.left + half_resized_width; + main_y = resized.top; + alt_y = resized.top + half_resized_height; + } + + #[allow(clippy::if_not_else)] + if count == 0 { + vec![] + } else if count == 1 { + vec![Rect { + left: resized.left, + top: resized.top, + right: resized.right, + bottom: resized.bottom, + }] + } else if idx % 2 != 0 { + let mut res = vec![Rect { + left: resized.left, + top: main_y, + right: resized.right, + bottom: half_resized_height, + }]; + res.append(&mut recursive_fibonacci( + idx + 1, + count - 1, + &Rect { + left: area.left, + top: alt_y, + right: area.right, + bottom: area.bottom - half_resized_height, + }, + layout_flip, + resize_adjustments, + )); + res + } else { + let mut res = vec![Rect { + left: main_x, + top: resized.top, + right: half_resized_width, + bottom: resized.bottom, + }]; + res.append(&mut recursive_fibonacci( + idx + 1, + count - 1, + &Rect { + left: alt_x, + top: area.top, + right: area.right - half_resized_width, + bottom: area.bottom, + }, + layout_flip, + resize_adjustments, + )); + res + } +} + +fn calculate_columns_adjustment(resize_dimensions: &[Option]) -> Vec { + let len = resize_dimensions.len(); + let mut result = vec![Rect::default(); len]; + match len { + 0 | 1 => (), + _ => { + for (i, rect) in resize_dimensions.iter().enumerate() { + if let Some(rect) = rect { + if i != 0 { + resize_right(&mut result[i - 1], rect.left); + resize_left(&mut result[i], rect.left); + } + + if i != len - 1 { + resize_right(&mut result[i], rect.right); + resize_left(&mut result[i + 1], rect.right); + } + } + } + } + }; + + result +} + +fn calculate_rows_adjustment(resize_dimensions: &[Option]) -> Vec { + let len = resize_dimensions.len(); + let mut result = vec![Rect::default(); len]; + match len { + 0 | 1 => (), + _ => { + for (i, rect) in resize_dimensions.iter().enumerate() { + if let Some(rect) = rect { + if i != 0 { + resize_bottom(&mut result[i - 1], rect.top); + resize_top(&mut result[i], rect.top); + } + + if i != len - 1 { + resize_bottom(&mut result[i], rect.bottom); + resize_top(&mut result[i + 1], rect.bottom); + } + } + } + } + }; + + result +} + +fn calculate_vertical_stack_adjustment(resize_dimensions: &[Option]) -> Vec { + let len = resize_dimensions.len(); + let mut result = vec![Rect::default(); len]; + match len { + // One container can't be resized + 0 | 1 => (), + _ => { + let (master, stack) = result.split_at_mut(1); + let primary = &mut master[0]; + + if let Some(resize) = resize_dimensions[0] { + resize_right(primary, resize.right); + for s in &mut *stack { + resize_left(s, resize.right); + } + } + + // Handle stack on the right + for (i, rect) in resize_dimensions[1..].iter().enumerate() { + if let Some(rect) = rect { + resize_right(primary, rect.left); + stack + .iter_mut() + .for_each(|vertical_element| resize_left(vertical_element, rect.left)); + + // Containers in stack except first can be resized up displacing container + // above them + if i != 0 { + resize_bottom(&mut stack[i - 1], rect.top); + resize_top(&mut stack[i], rect.top); + } + + // Containers in stack except last can be resized down displacing container + // below them + if i != stack.len() - 1 { + resize_bottom(&mut stack[i], rect.bottom); + resize_top(&mut stack[i + 1], rect.bottom); + } + } + } + } + }; + + result +} + +fn calculate_right_vertical_stack_adjustment(resize_dimensions: &[Option]) -> Vec { + let len = resize_dimensions.len(); + let mut result = vec![Rect::default(); len]; + match len { + // One container can't be resized + 0 | 1 => (), + _ => { + let (master, stack) = result.split_at_mut(1); + let primary = &mut master[0]; + + if let Some(resize) = resize_dimensions[0] { + resize_left(primary, resize.left); + for s in &mut *stack { + resize_right(s, resize.left); + } + } + + // Handle stack on the left + for (i, rect) in resize_dimensions[1..].iter().enumerate() { + if let Some(rect) = rect { + resize_left(primary, rect.right); + stack + .iter_mut() + .for_each(|vertical_element| resize_right(vertical_element, rect.right)); + + // Containers in stack except first can be resized up displacing container + // above them + if i != 0 { + resize_bottom(&mut stack[i - 1], rect.top); + resize_top(&mut stack[i], rect.top); + } + + // Containers in stack except last can be resized down displacing container + // below them + if i != stack.len() - 1 { + resize_bottom(&mut stack[i], rect.bottom); + resize_top(&mut stack[i + 1], rect.bottom); + } + } + } + } + }; + + result +} + +fn calculate_horizontal_stack_adjustment(resize_dimensions: &[Option]) -> Vec { + let len = resize_dimensions.len(); + let mut result = vec![Rect::default(); len]; + match len { + 0 | 1 => (), + _ => { + let (primary, rest) = result.split_at_mut(1); + let primary = &mut primary[0]; + if let Some(resize_primary) = resize_dimensions[0] { + resize_bottom(primary, resize_primary.bottom); + + for horizontal_element in &mut *rest { + resize_top(horizontal_element, resize_primary.bottom); + } + } + + for (i, rect) in resize_dimensions[1..].iter().enumerate() { + if let Some(rect) = rect { + resize_bottom(primary, rect.top); + rest.iter_mut() + .for_each(|vertical_element| resize_top(vertical_element, rect.top)); + + if i != 0 { + resize_right(&mut rest[i - 1], rect.left); + resize_left(&mut rest[i], rect.left); + } + + if i != rest.len() - 1 { + resize_right(&mut rest[i], rect.right); + resize_left(&mut rest[i + 1], rect.right); + } + } + } + } + }; + + result +} + +fn calculate_ultrawide_adjustment(resize_dimensions: &[Option]) -> Vec { + let len = resize_dimensions.len(); + let mut result = vec![Rect::default(); len]; + match len { + // One container can't be resized + 0 | 1 => (), + 2 => { + let (primary, secondary) = result.split_at_mut(1); + let primary = &mut primary[0]; + let secondary = &mut secondary[0]; + // With two containers on screen container 0 is on the right + if let Some(resize_primary) = resize_dimensions[0] { + resize_left(primary, resize_primary.left); + resize_right(secondary, resize_primary.left); + } + + if let Some(resize_secondary) = resize_dimensions[1] { + resize_left(primary, resize_secondary.right); + resize_right(secondary, resize_secondary.right); + } + } + _ => { + let (primary, rest) = result.split_at_mut(1); + let (secondary, tertiary) = rest.split_at_mut(1); + let primary = &mut primary[0]; + let secondary = &mut secondary[0]; + // With three or more containers container 0 is in the center + if let Some(resize_primary) = resize_dimensions[0] { + resize_left(primary, resize_primary.left); + resize_right(primary, resize_primary.right); + + resize_right(secondary, resize_primary.left); + + for vertical_element in &mut *tertiary { + resize_left(vertical_element, resize_primary.right); + } + } + + // Container 1 is on the left + if let Some(resize_secondary) = resize_dimensions[1] { + resize_left(primary, resize_secondary.right); + resize_right(secondary, resize_secondary.right); + } + + // Handle stack on the right + for (i, rect) in resize_dimensions[2..].iter().enumerate() { + if let Some(rect) = rect { + resize_right(primary, rect.left); + tertiary + .iter_mut() + .for_each(|vertical_element| resize_left(vertical_element, rect.left)); + + // Containers in stack except first can be resized up displacing container + // above them + if i != 0 { + resize_bottom(&mut tertiary[i - 1], rect.top); + resize_top(&mut tertiary[i], rect.top); + } + + // Containers in stack except last can be resized down displacing container + // below them + if i != tertiary.len() - 1 { + resize_bottom(&mut tertiary[i], rect.bottom); + resize_top(&mut tertiary[i + 1], rect.bottom); + } + } + } + } + }; + + result +} + +fn calculate_scrolling_adjustment(resize_dimensions: &[Option]) -> Vec { + let len = resize_dimensions.len(); + let mut result = vec![Rect::default(); len]; + + if len <= 1 { + return result; + } + + for (i, rect) in resize_dimensions.iter().enumerate() { + if let Some(rect) = rect { + let is_leftmost = i == 0; + let is_rightmost = i == len - 1; + + resize_left(&mut result[i], rect.left); + resize_right(&mut result[i], rect.right); + resize_top(&mut result[i], rect.top); + resize_bottom(&mut result[i], rect.bottom); + + if !is_leftmost && rect.left != 0 { + resize_right(&mut result[i - 1], rect.left); + } + + if !is_rightmost && rect.right != 0 { + resize_left(&mut result[i + 1], rect.right); + } + } + } + + result +} + +fn resize_left(rect: &mut Rect, resize: i32) { + rect.left += resize / 2; + rect.right += -resize / 2; +} + +fn resize_right(rect: &mut Rect, resize: i32) { + rect.right += resize / 2; +} + +fn resize_top(rect: &mut Rect, resize: i32) { + rect.top += resize / 2; + rect.bottom += -resize / 2; +} + +fn resize_bottom(rect: &mut Rect, resize: i32) { + rect.bottom += resize / 2; +} diff --git a/komorebi/src/core/default_layout.rs b/komorebi/src/core/default_layout.rs new file mode 100644 index 00000000..43f208a4 --- /dev/null +++ b/komorebi/src/core/default_layout.rs @@ -0,0 +1,200 @@ +use crate::core::Sizing; +use crate::core::operation_direction::OperationDirection; +use crate::core::rect::Rect; +use serde::Deserialize; +use serde::Serialize; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq)] +pub enum DefaultLayout { + BSP, + Columns, + Rows, + VerticalStack, + HorizontalStack, + UltrawideVerticalStack, + Grid, + RightMainVerticalStack, + Scrolling, + // NOTE: If any new layout is added, please make sure to register the same in `DefaultLayout::cycle` +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq)] +pub struct LayoutOptions { + /// Options related to the Scrolling layout + pub scrolling: Option, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq)] +pub struct ScrollingLayoutOptions { + /// Desired number of visible columns (default: 3) + pub columns: usize, +} + +impl DefaultLayout { + pub fn leftmost_index(&self, len: usize) -> usize { + match self { + Self::UltrawideVerticalStack | Self::RightMainVerticalStack => match len { + n if n > 1 => 1, + _ => 0, + }, + Self::Scrolling => 0, + DefaultLayout::BSP + | DefaultLayout::Columns + | DefaultLayout::Rows + | DefaultLayout::VerticalStack + | DefaultLayout::HorizontalStack + | DefaultLayout::Grid => 0, + } + } + + pub fn rightmost_index(&self, len: usize) -> usize { + match self { + DefaultLayout::BSP + | DefaultLayout::Columns + | DefaultLayout::Rows + | DefaultLayout::VerticalStack + | DefaultLayout::HorizontalStack + | DefaultLayout::Grid => len.saturating_sub(1), + DefaultLayout::UltrawideVerticalStack => match len { + 2 => 0, + _ => len.saturating_sub(1), + }, + DefaultLayout::RightMainVerticalStack => 0, + DefaultLayout::Scrolling => len.saturating_sub(1), + } + } + + #[must_use] + #[allow(clippy::cast_precision_loss, clippy::only_used_in_recursion)] + pub fn resize( + &self, + unaltered: &Rect, + resize: &Option, + edge: OperationDirection, + sizing: Sizing, + delta: i32, + ) -> Option { + if !matches!( + self, + Self::BSP + | Self::Columns + | Self::Rows + | Self::VerticalStack + | Self::RightMainVerticalStack + | Self::HorizontalStack + | Self::UltrawideVerticalStack + | Self::Scrolling + ) { + return None; + }; + + let mut r = resize.unwrap_or_default(); + + let resize_delta = delta; + + match edge { + OperationDirection::Left => match sizing { + Sizing::Increase => { + // Some final checks to make sure the user can't infinitely resize to + // the point of pushing other windows out of bounds + + // Note: These checks cannot take into account the changes made to the + // edges of adjacent windows at operation time, so it is still possible + // to push windows out of bounds by maxing out an Increase Left on a + // Window with index 1, and then maxing out a Decrease Right on a Window + // with index 0. I don't think it's worth trying to defensively program + // against this; if people end up in this situation they are better off + // just hitting the retile command + let diff = ((r.left + -resize_delta) as f32).abs(); + if diff < unaltered.right as f32 { + r.left += -resize_delta; + } + } + Sizing::Decrease => { + let diff = ((r.left - -resize_delta) as f32).abs(); + if diff < unaltered.right as f32 { + r.left -= -resize_delta; + } + } + }, + OperationDirection::Up => match sizing { + Sizing::Increase => { + let diff = ((r.top + resize_delta) as f32).abs(); + if diff < unaltered.bottom as f32 { + r.top += -resize_delta; + } + } + Sizing::Decrease => { + let diff = ((r.top - resize_delta) as f32).abs(); + if diff < unaltered.bottom as f32 { + r.top -= -resize_delta; + } + } + }, + OperationDirection::Right => match sizing { + Sizing::Increase => { + let diff = ((r.right + resize_delta) as f32).abs(); + if diff < unaltered.right as f32 { + r.right += resize_delta; + } + } + Sizing::Decrease => { + let diff = ((r.right - resize_delta) as f32).abs(); + if diff < unaltered.right as f32 { + r.right -= resize_delta; + } + } + }, + OperationDirection::Down => match sizing { + Sizing::Increase => { + let diff = ((r.bottom + resize_delta) as f32).abs(); + if diff < unaltered.bottom as f32 { + r.bottom += resize_delta; + } + } + Sizing::Decrease => { + let diff = ((r.bottom - resize_delta) as f32).abs(); + if diff < unaltered.bottom as f32 { + r.bottom -= resize_delta; + } + } + }, + }; + + if r.eq(&Rect::default()) { + None + } else { + Option::from(r) + } + } + + #[must_use] + pub const fn cycle_next(self) -> Self { + match self { + Self::BSP => Self::Columns, + Self::Columns => Self::Rows, + Self::Rows => Self::VerticalStack, + Self::VerticalStack => Self::HorizontalStack, + Self::HorizontalStack => Self::UltrawideVerticalStack, + Self::UltrawideVerticalStack => Self::Grid, + Self::Grid => Self::RightMainVerticalStack, + Self::RightMainVerticalStack => Self::Scrolling, + Self::Scrolling => Self::BSP, + } + } + + #[must_use] + pub const fn cycle_previous(self) -> Self { + match self { + Self::Scrolling => Self::RightMainVerticalStack, + Self::RightMainVerticalStack => Self::Grid, + Self::Grid => Self::UltrawideVerticalStack, + Self::UltrawideVerticalStack => Self::HorizontalStack, + Self::HorizontalStack => Self::VerticalStack, + Self::VerticalStack => Self::Rows, + Self::Rows => Self::Columns, + Self::Columns => Self::BSP, + Self::BSP => Self::RightMainVerticalStack, + } + } +} diff --git a/komorebi/src/core/direction.rs b/komorebi/src/core/direction.rs new file mode 100644 index 00000000..2d8238f0 --- /dev/null +++ b/komorebi/src/core/direction.rs @@ -0,0 +1,347 @@ +use crate::core::default_layout::DefaultLayout; +use crate::core::operation_direction::OperationDirection; + +pub trait Direction { + fn index_in_direction( + &self, + op_direction: OperationDirection, + idx: usize, + count: usize, + ) -> Option; + + fn is_valid_direction( + &self, + op_direction: OperationDirection, + idx: usize, + count: usize, + ) -> bool; + fn up_index( + &self, + op_direction: Option, + idx: usize, + count: Option, + ) -> usize; + fn down_index( + &self, + op_direction: Option, + idx: usize, + count: Option, + ) -> usize; + fn left_index( + &self, + op_direction: Option, + idx: usize, + count: Option, + ) -> usize; + fn right_index( + &self, + op_direction: Option, + idx: usize, + count: Option, + ) -> usize; +} + +impl Direction for DefaultLayout { + fn index_in_direction( + &self, + op_direction: OperationDirection, + idx: usize, + count: usize, + ) -> Option { + match op_direction { + OperationDirection::Left => { + if self.is_valid_direction(op_direction, idx, count) { + Option::from(self.left_index(Some(op_direction), idx, Some(count))) + } else { + None + } + } + OperationDirection::Right => { + if self.is_valid_direction(op_direction, idx, count) { + Option::from(self.right_index(Some(op_direction), idx, Some(count))) + } else { + None + } + } + OperationDirection::Up => { + if self.is_valid_direction(op_direction, idx, count) { + Option::from(self.up_index(Some(op_direction), idx, Some(count))) + } else { + None + } + } + OperationDirection::Down => { + if self.is_valid_direction(op_direction, idx, count) { + Option::from(self.down_index(Some(op_direction), idx, Some(count))) + } else { + None + } + } + } + } + + fn is_valid_direction( + &self, + op_direction: OperationDirection, + idx: usize, + count: usize, + ) -> bool { + if count < 2 { + return false; + } + + match op_direction { + OperationDirection::Up => match self { + Self::BSP => idx != 0 && idx != 1, + Self::Columns => false, + Self::Rows | Self::HorizontalStack => idx != 0, + Self::VerticalStack | Self::RightMainVerticalStack => idx != 0 && idx != 1, + Self::UltrawideVerticalStack => idx > 2, + Self::Grid => !is_grid_edge(op_direction, idx, count), + Self::Scrolling => false, + }, + OperationDirection::Down => match self { + Self::BSP => idx != count - 1 && idx % 2 != 0, + Self::Columns => false, + Self::Rows => idx != count - 1, + Self::VerticalStack | Self::RightMainVerticalStack => idx != 0 && idx != count - 1, + Self::HorizontalStack => idx == 0, + Self::UltrawideVerticalStack => idx > 1 && idx != count - 1, + Self::Grid => !is_grid_edge(op_direction, idx, count), + Self::Scrolling => false, + }, + OperationDirection::Left => match self { + Self::BSP => idx != 0, + Self::Columns | Self::VerticalStack => idx != 0, + Self::RightMainVerticalStack => idx == 0, + Self::Rows => false, + Self::HorizontalStack => idx != 0 && idx != 1, + Self::UltrawideVerticalStack => idx != 1, + Self::Grid => !is_grid_edge(op_direction, idx, count), + Self::Scrolling => idx != 0, + }, + OperationDirection::Right => match self { + Self::BSP => idx % 2 == 0 && idx != count - 1, + Self::Columns => idx != count - 1, + Self::Rows => false, + Self::VerticalStack => idx == 0, + Self::RightMainVerticalStack => idx != 0, + Self::HorizontalStack => idx != 0 && idx != count - 1, + Self::UltrawideVerticalStack => match count { + 2 => idx != 0, + _ => idx < 2, + }, + Self::Grid => !is_grid_edge(op_direction, idx, count), + Self::Scrolling => idx != count - 1, + }, + } + } + + fn up_index( + &self, + op_direction: Option, + idx: usize, + count: Option, + ) -> usize { + match self { + Self::BSP => { + if idx % 2 == 0 { + idx - 1 + } else { + idx - 2 + } + } + Self::Columns => unreachable!(), + Self::Rows + | Self::VerticalStack + | Self::UltrawideVerticalStack + | Self::RightMainVerticalStack => idx - 1, + Self::HorizontalStack => 0, + Self::Grid => grid_neighbor(op_direction, idx, count), + Self::Scrolling => unreachable!(), + } + } + + fn down_index( + &self, + op_direction: Option, + idx: usize, + count: Option, + ) -> usize { + match self { + Self::BSP + | Self::Rows + | Self::VerticalStack + | Self::UltrawideVerticalStack + | Self::RightMainVerticalStack => idx + 1, + Self::Columns => unreachable!(), + Self::HorizontalStack => 1, + Self::Grid => grid_neighbor(op_direction, idx, count), + Self::Scrolling => unreachable!(), + } + } + + fn left_index( + &self, + op_direction: Option, + idx: usize, + count: Option, + ) -> usize { + match self { + Self::BSP => { + if idx % 2 == 0 { + idx - 2 + } else { + idx - 1 + } + } + Self::Columns | Self::HorizontalStack => idx - 1, + Self::Rows => unreachable!(), + Self::VerticalStack => 0, + Self::RightMainVerticalStack => 1, + Self::UltrawideVerticalStack => match idx { + 0 => 1, + 1 => unreachable!(), + _ => 0, + }, + Self::Grid => grid_neighbor(op_direction, idx, count), + Self::Scrolling => idx - 1, + } + } + + fn right_index( + &self, + op_direction: Option, + idx: usize, + count: Option, + ) -> usize { + match self { + Self::BSP | Self::Columns | Self::HorizontalStack => idx + 1, + Self::Rows => unreachable!(), + Self::VerticalStack => 1, + Self::RightMainVerticalStack => 0, + Self::UltrawideVerticalStack => match idx { + 1 => 0, + 0 => 2, + _ => unreachable!(), + }, + Self::Grid => grid_neighbor(op_direction, idx, count), + Self::Scrolling => idx + 1, + } + } +} + +struct GridItem { + state: GridItemState, + row: usize, + num_rows: usize, + touching_edges: GridTouchingEdges, +} + +enum GridItemState { + Valid, + Invalid, +} + +#[allow(clippy::struct_excessive_bools)] +struct GridTouchingEdges { + left: bool, + right: bool, + up: bool, + down: bool, +} + +#[allow( + clippy::cast_possible_truncation, + clippy::cast_precision_loss, + clippy::cast_sign_loss +)] +fn get_grid_item(idx: usize, count: usize) -> GridItem { + let num_cols = (count as f32).sqrt().ceil() as usize; + let mut iter = 0; + + for col in 0..num_cols { + let remaining_windows = count - iter; + let remaining_columns = num_cols - col; + let num_rows_in_this_col = remaining_windows / remaining_columns; + + for row in 0..num_rows_in_this_col { + if iter == idx { + return GridItem { + state: GridItemState::Valid, + row: row + 1, + num_rows: num_rows_in_this_col, + touching_edges: GridTouchingEdges { + left: col == 0, + right: col == num_cols - 1, + up: row == 0, + down: row == num_rows_in_this_col - 1, + }, + }; + } + + iter += 1; + } + } + + GridItem { + state: GridItemState::Invalid, + row: 0, + num_rows: 0, + touching_edges: GridTouchingEdges { + left: true, + right: true, + up: true, + down: true, + }, + } +} + +fn is_grid_edge(op_direction: OperationDirection, idx: usize, count: usize) -> bool { + let item = get_grid_item(idx, count); + + match item.state { + GridItemState::Invalid => false, + GridItemState::Valid => match op_direction { + OperationDirection::Left => item.touching_edges.left, + OperationDirection::Right => item.touching_edges.right, + OperationDirection::Up => item.touching_edges.up, + OperationDirection::Down => item.touching_edges.down, + }, + } +} + +fn grid_neighbor( + op_direction: Option, + idx: usize, + count: Option, +) -> usize { + let Some(op_direction) = op_direction else { + return 0; + }; + + let Some(count) = count else { + return 0; + }; + + let item = get_grid_item(idx, count); + + match op_direction { + OperationDirection::Left => { + let item_from_prev_col = get_grid_item(idx - item.row, count); + + if item.touching_edges.up && item.num_rows != item_from_prev_col.num_rows { + return idx - (item.num_rows - 1); + } + + if item.num_rows != item_from_prev_col.num_rows && !item.touching_edges.down { + return idx - (item.num_rows - 1); + } + + idx - item.num_rows + } + OperationDirection::Right => idx + item.num_rows, + OperationDirection::Up => idx - 1, + OperationDirection::Down => idx + 1, + } +} diff --git a/komorebi/src/core/layout.rs b/komorebi/src/core/layout.rs new file mode 100644 index 00000000..dd4131b6 --- /dev/null +++ b/komorebi/src/core/layout.rs @@ -0,0 +1,26 @@ +use crate::core::arrangement::Arrangement; +use crate::core::default_layout::DefaultLayout; +use crate::core::direction::Direction; +use serde::Deserialize; +use serde::Serialize; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub enum Layout { + Default(DefaultLayout), +} + +impl Layout { + #[must_use] + pub fn as_boxed_direction(&self) -> Box { + match self { + Layout::Default(layout) => Box::new(*layout), + } + } + + #[must_use] + pub fn as_boxed_arrangement(&self) -> Box { + match self { + Layout::Default(layout) => Box::new(*layout), + } + } +} diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs new file mode 100644 index 00000000..2daf9079 --- /dev/null +++ b/komorebi/src/core/mod.rs @@ -0,0 +1,15 @@ +use serde::Deserialize; +use serde::Serialize; + +pub mod arrangement; +pub mod default_layout; +pub mod direction; +pub mod layout; +pub mod operation_direction; +pub mod rect; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +pub enum Sizing { + Increase, + Decrease, +} diff --git a/komorebi/src/core/operation_direction.rs b/komorebi/src/core/operation_direction.rs new file mode 100644 index 00000000..0c66d6bf --- /dev/null +++ b/komorebi/src/core/operation_direction.rs @@ -0,0 +1,58 @@ +use std::num::NonZeroUsize; + +use crate::core::arrangement::Axis; +use crate::core::direction::Direction; +use serde::Deserialize; +use serde::Serialize; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +pub enum OperationDirection { + Left, + Right, + Up, + Down, +} + +impl OperationDirection { + #[must_use] + pub const fn opposite(self) -> Self { + match self { + Self::Left => Self::Right, + Self::Right => Self::Left, + Self::Up => Self::Down, + Self::Down => Self::Up, + } + } + + fn flip(self, layout_flip: Option) -> Self { + layout_flip.map_or(self, |flip| match self { + Self::Left => match flip { + Axis::Horizontal | Axis::HorizontalAndVertical => Self::Right, + Axis::Vertical => self, + }, + Self::Right => match flip { + Axis::Horizontal | Axis::HorizontalAndVertical => Self::Left, + Axis::Vertical => self, + }, + Self::Up => match flip { + Axis::Vertical | Axis::HorizontalAndVertical => Self::Down, + Axis::Horizontal => self, + }, + Self::Down => match flip { + Axis::Vertical | Axis::HorizontalAndVertical => Self::Up, + Axis::Horizontal => self, + }, + }) + } + + #[must_use] + pub fn destination( + self, + layout: &dyn Direction, + layout_flip: Option, + idx: usize, + len: NonZeroUsize, + ) -> Option { + layout.index_in_direction(self.flip(layout_flip), idx, len.get()) + } +} diff --git a/komorebi/src/core/rect.rs b/komorebi/src/core/rect.rs new file mode 100644 index 00000000..a125effd --- /dev/null +++ b/komorebi/src/core/rect.rs @@ -0,0 +1,105 @@ +use crate::core_graphics::CoreGraphicsApi; +use crate::window::WindowBounds; +use objc2_core_foundation::CGFloat; +use objc2_core_foundation::CGPoint; +use objc2_core_foundation::CGRect; +use objc2_core_foundation::CGSize; + +#[derive(Debug, Default, Copy, Clone, PartialEq)] +pub struct Rect { + pub left: i32, + pub top: i32, + pub right: i32, + pub bottom: i32, +} + +impl From for Rect { + fn from(value: CGSize) -> Self { + Self { + left: 0, + top: 0, + right: value.width as i32, + bottom: value.height as i32, + } + } +} + +impl From for Rect { + fn from(value: CGRect) -> Self { + Self { + left: value.origin.x as i32, + top: value.origin.y as i32, + right: value.size.width as i32, + bottom: value.size.height as i32, + } + } +} + +impl From<&Rect> for CGRect { + fn from(value: &Rect) -> Self { + Self { + origin: CGPoint { + x: value.left as CGFloat, + y: value.top as CGFloat, + }, + size: CGSize { + width: value.right as CGFloat, + height: value.bottom as CGFloat, + }, + } + } +} + +impl From for Rect { + fn from(value: WindowBounds) -> Self { + Self { + left: value.x as i32, + top: value.y as i32, + right: value.width as i32, + bottom: value.height as i32, + } + } +} + +impl Rect { + pub fn contains(&self, other: &Rect) -> bool { + CoreGraphicsApi::contains_rect(other.into(), self.into()) + } + + /// Decrease the size of self by the padding amount. + pub fn add_padding(&mut self, padding: T) + where + T: Into>, + { + if let Some(padding) = padding.into() { + self.left += padding; + self.top += padding; + self.right -= padding * 2; + self.bottom -= padding * 2; + } + } + + /// Increase the size of self by the margin amount. + pub fn add_margin(&mut self, margin: i32) { + self.left -= margin; + self.top -= margin; + self.right += margin * 2; + self.bottom += margin * 2; + } + + pub fn left_padding(&mut self, padding: i32) { + self.left += padding; + } + + pub fn right_padding(&mut self, padding: i32) { + self.right -= padding; + } + + #[must_use] + pub const fn contains_point(&self, point: (i32, i32)) -> bool { + point.0 >= self.left + && point.0 <= self.left + self.right + && point.1 >= self.top + && point.1 <= self.top + self.bottom + } +} diff --git a/komorebi/src/layout.rs b/komorebi/src/layout.rs deleted file mode 100644 index 3d30c6b7..00000000 --- a/komorebi/src/layout.rs +++ /dev/null @@ -1,82 +0,0 @@ -use crate::rect::Rect; - -pub fn recursive_fibonacci( - idx: usize, - count: usize, - area: &Rect, - resize_adjustments: Vec>, -) -> Vec { - let mut a = *area; - - let resized = if let Some(Some(r)) = resize_adjustments.get(idx) { - a.left += r.left; - a.top += r.top; - a.right += r.right; - a.bottom += r.bottom; - a - } else { - *area - }; - - // let half_width = area.right / 2.0; - // let half_height = area.bottom / 2.0; - let half_resized_width = resized.right / 2.0; - let half_resized_height = resized.bottom / 2.0; - - let (main_x, alt_x, alt_y, main_y); - - main_x = resized.left; - alt_x = resized.left + half_resized_width; - main_y = resized.top; - alt_y = resized.top + half_resized_height; - - #[allow(clippy::if_not_else)] - if count == 0 { - vec![] - } else if count == 1 { - vec![Rect { - left: resized.left, - top: resized.top, - right: resized.right, - bottom: resized.bottom, - }] - } else if idx % 2 != 0 { - let mut res = vec![Rect { - left: resized.left, - top: main_y, - right: resized.right, - bottom: half_resized_height, - }]; - res.append(&mut recursive_fibonacci( - idx + 1, - count - 1, - &Rect { - left: area.left, - top: alt_y, - right: area.right, - bottom: area.bottom - half_resized_height, - }, - resize_adjustments, - )); - res - } else { - let mut res = vec![Rect { - left: main_x, - top: resized.top, - right: half_resized_width, - bottom: resized.bottom, - }]; - res.append(&mut recursive_fibonacci( - idx + 1, - count - 1, - &Rect { - left: alt_x, - top: area.top, - right: area.right - half_resized_width, - bottom: area.bottom, - }, - resize_adjustments, - )); - res - } -} diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index aef1c7f4..aaf8e6ea 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -12,12 +12,12 @@ pub mod ring; pub mod accessibility; pub mod application; +pub mod core; pub mod core_graphics; -pub mod layout; pub mod macos_api; -pub mod rect; pub mod window; pub mod window_manager; +pub mod workspace; pub fn cf_array_as(array: &CFArray) -> impl Iterator> + use<'_, T> { let count = CFArray::count(array); diff --git a/komorebi/src/macos_api.rs b/komorebi/src/macos_api.rs index ae2e986f..5020e12d 100644 --- a/komorebi/src/macos_api.rs +++ b/komorebi/src/macos_api.rs @@ -1,8 +1,8 @@ use crate::LibraryError; use crate::application::Application; use crate::cf_array_as; +use crate::core::rect::Rect; use crate::core_graphics::CoreGraphicsApi; -use crate::rect::Rect; use crate::ring::Ring; use crate::window::WindowInfo; use crate::window_manager::Container; diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 2c0aa569..8c434763 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -2,8 +2,6 @@ use color_eyre::eyre; use color_eyre::eyre::eyre; -use komorebi::layout; -use komorebi::rect::Rect; use komorebi::window_manager::WindowManager; use objc2::rc::autoreleasepool; use objc2_application_services::AXIsProcessTrusted; @@ -99,57 +97,12 @@ fn main() -> eyre::Result<()> { let mut wm = WindowManager::new(&run_loop); wm.init()?; - let containers = wm - .monitors - .focused() - .expect("must have a monitor at this point") - .focused_workspace() - .expect("must have a workspace at this point") - .containers(); - - let layouts = - layout::recursive_fibonacci(0, containers.len(), &Rect::from(display_size), vec![]); - - containers - .iter() - .zip(layouts) - .for_each(|(container, layout)| { - let window = container - .focused_window() - .expect("must have a window at this point"); - if let Err(error) = window.set_position(&layout) { - tracing::error!( - "failed to position window: {} ({error})", - window - .title() - .unwrap_or_else(|| String::from("")) - ); - } - - // initial example to ensure that window focusing works - // if let Some(window_title) = window.title() - // && window_title.contains("Komorebi Community Server") - // { - // match window.focus() { - // Err(error) => { - // tracing::error!( - // "failed to focus window: {} ({error})", - // window - // .title() - // .unwrap_or_else(|| String::from("")) - // ); - // } - // Ok(()) => { - // tracing::info!( - // "focused window: {}", - // window - // .title() - // .unwrap_or_else(|| String::from("")) - // ); - // } - // } - // } - }); + wm.monitors + .focused_mut() + .unwrap() + .focused_workspace_mut() + .unwrap() + .update()?; let quit_ctrlc = Arc::new(AtomicBool::new(false)); let quit_thread = quit_ctrlc.clone(); diff --git a/komorebi/src/rect.rs b/komorebi/src/rect.rs deleted file mode 100644 index 6f1b029d..00000000 --- a/komorebi/src/rect.rs +++ /dev/null @@ -1,68 +0,0 @@ -use crate::core_graphics::CoreGraphicsApi; -use crate::window::WindowBounds; -use objc2_core_foundation::CGFloat; -use objc2_core_foundation::CGPoint; -use objc2_core_foundation::CGRect; -use objc2_core_foundation::CGSize; - -#[derive(Debug, Copy, Clone)] -pub struct Rect { - pub left: f32, - pub top: f32, - pub right: f32, - pub bottom: f32, -} - -impl From for Rect { - fn from(value: CGSize) -> Self { - Self { - left: 0.0, - top: 0.0, - right: value.width as f32, - bottom: value.height as f32, - } - } -} - -impl From for Rect { - fn from(value: CGRect) -> Self { - Self { - left: value.origin.x as f32, - top: value.origin.y as f32, - right: value.size.width as f32, - bottom: value.size.height as f32, - } - } -} - -impl From<&Rect> for CGRect { - fn from(value: &Rect) -> Self { - Self { - origin: CGPoint { - x: value.left as CGFloat, - y: value.top as CGFloat, - }, - size: CGSize { - width: value.right as CGFloat, - height: value.bottom as CGFloat, - }, - } - } -} - -impl From for Rect { - fn from(value: WindowBounds) -> Self { - Self { - left: value.x, - top: value.y, - right: value.width, - bottom: value.height, - } - } -} - -impl Rect { - pub fn contains(&self, other: &Rect) -> bool { - CoreGraphicsApi::contains_rect(other.into(), self.into()) - } -} diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index c4197f33..d28fbb43 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -12,7 +12,7 @@ use crate::accessibility::notification_constants::kAXWindowMovedNotification; use crate::accessibility::notification_constants::kAXWindowResizedNotification; use crate::application::Application; use crate::cf_dictionary_value; -use crate::rect::Rect; +use crate::core::rect::Rect; use objc2_app_kit::NSApplicationActivationOptions; use objc2_app_kit::NSRunningApplication; use objc2_application_services::AXObserver; diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 594b7391..558594a5 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1,9 +1,10 @@ use crate::LibraryError; use crate::application::Application; +use crate::core::rect::Rect; use crate::macos_api::MacosApi; -use crate::rect::Rect; use crate::ring::Ring; use crate::window::Window; +use crate::workspace::Workspace; use objc2_core_foundation::CFRetained; use objc2_core_foundation::CFRunLoop; use std::collections::HashMap; @@ -41,9 +42,21 @@ pub struct Monitor { } impl Monitor { + #[allow(clippy::field_reassign_with_default)] pub fn new(id: u32, size: Rect) -> Self { let mut workspaces = Ring::default(); - workspaces.elements_mut().push_back(Workspace::default()); + let mut workspace = Workspace::default(); + workspace.work_area = size; + workspace.container_padding = Some(20); + workspace.workspace_padding = Some(20); + workspace.work_area_offset = Some(Rect { + left: 0, + top: 0, + right: 0, + bottom: 40, + }); + + workspaces.elements_mut().push_back(workspace); Self { id, @@ -53,12 +66,6 @@ impl Monitor { } } -impl_ring_elements!(Workspace, Container); -#[derive(Debug, Default)] -pub struct Workspace { - pub containers: Ring, -} - impl_ring_elements!(Container, Window); #[derive(Debug)] pub struct Container { diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs new file mode 100644 index 00000000..51d6a663 --- /dev/null +++ b/komorebi/src/workspace.rs @@ -0,0 +1,133 @@ +use crate::core::arrangement::Axis; +use crate::core::default_layout::DefaultLayout; +use crate::core::default_layout::LayoutOptions; +use crate::core::layout::Layout; +use crate::core::rect::Rect; +use crate::ring::Ring; +use crate::window_manager::Container; +use color_eyre::eyre; +use color_eyre::eyre::eyre; +use std::num::NonZeroUsize; + +impl_ring_elements!(Workspace, Container); + +#[derive(Debug)] +pub struct Workspace { + pub containers: Ring, + pub workspace_padding: Option, + pub container_padding: Option, + pub resize_dimensions: Vec>, + pub layout: Layout, + pub work_area: Rect, + pub work_area_offset: Option, + pub latest_layout: Vec, + pub layout_flip: Option, + pub layout_options: Option, + pub globals: WorkspaceGlobals, + pub tile: bool, +} + +impl Default for Workspace { + fn default() -> Self { + Self { + containers: Default::default(), + workspace_padding: None, + container_padding: None, + resize_dimensions: vec![], + layout: Layout::Default(DefaultLayout::UltrawideVerticalStack), + work_area: Default::default(), + work_area_offset: None, + latest_layout: vec![], + layout_flip: None, + layout_options: None, + globals: Default::default(), + tile: true, + } + } +} + +#[derive(Debug, Default, Copy, Clone, PartialEq)] +/// Settings setup either by the parent monitor or by the `WindowManager` +pub struct WorkspaceGlobals { + pub container_padding: Option, + pub workspace_padding: Option, + pub border_width: i32, + pub border_offset: i32, + pub work_area: Rect, + pub work_area_offset: Option, + pub window_based_work_area_offset: Option, + pub window_based_work_area_offset_limit: isize, +} + +impl Workspace { + pub fn update(&mut self) -> eyre::Result<()> { + // make sure we are never holding on to empty containers + self.containers_mut().retain(|c| !c.windows().is_empty()); + + let container_padding = self + .container_padding + .or(self.globals.container_padding) + .unwrap_or_default(); + let workspace_padding = self + .workspace_padding + .or(self.globals.workspace_padding) + .unwrap_or_default(); + // let border_width = self.globals.border_width; + // let border_offset = self.globals.border_offset; + let work_area = self.globals.work_area; + let work_area_offset = self.work_area_offset.or(self.globals.work_area_offset); + // let window_based_work_area_offset = self.globals.window_based_work_area_offset; + // let window_based_work_area_offset_limit = + // self.globals.window_based_work_area_offset_limit; + + let mut adjusted_work_area = work_area_offset.map_or_else( + || self.work_area, + |offset| { + let mut with_offset = work_area; + with_offset.left += offset.left; + with_offset.top += offset.top; + with_offset.right -= offset.right; + with_offset.bottom -= offset.bottom; + + with_offset + }, + ); + + adjusted_work_area.add_padding(workspace_padding); + + #[allow(clippy::collapsible_if)] + if self.tile { + if !self.containers().is_empty() { + let mut layouts = self.layout.as_boxed_arrangement().calculate( + &adjusted_work_area, + NonZeroUsize::new(self.containers().len()).ok_or_else(|| { + eyre!( + "there must be at least one container to calculate a workspace layout" + ) + })?, + Some(container_padding), + self.layout_flip, + &self.resize_dimensions, + self.focused_container_idx(), + self.layout_options, + &self.latest_layout, + ); + + let containers = self.containers_mut(); + + for (i, container) in containers.iter_mut().enumerate() { + if let Some(layout) = layouts.get_mut(i) { + layout.add_padding(container_padding); + for window in container.windows() { + if let Err(error) = window.set_position(layout) { + tracing::warn!("failed to set window position: {error}"); + } + } + } + } + } + } + + Ok(()) + } +}