use std::sync::mpsc::Receiver;
use std::time::{Duration, Instant};
use bevy::MinimalPlugins;
use bevy::app::App as BevyApp;
use bevy::app::{PostUpdate, PreUpdate, Startup};
use bevy::ecs::hierarchy::ChildOf;
use bevy::ecs::lifecycle::RemovedComponents;
use bevy::ecs::message::Messages;
use bevy::ecs::query::{Added, Changed, With};
use bevy::ecs::resource::Resource;
use bevy::ecs::schedule::common_conditions::{not, resource_exists};
use bevy::ecs::system::{Commands, EntityCommands, Query, Res, SystemId};
use bevy::prelude::Event as BevyEvent;
use bevy::tasks::Task;
use bevy::time::Timer;
use bevy::time::common_conditions::on_timer;
use bevy::time::{Time, Virtual};
use bevy::{
app::Update,
ecs::{component::Component, entity::Entity, schedule::IntoScheduleConfigs},
};
use derive_more::{Deref, DerefMut};
use tracing::{Level, instrument};
use crate::commands::register_commands;
use crate::config::{CONFIGURATION_FILE, Config, WindowParams};
use crate::ecs::display::FloatingLayer;
use crate::ecs::layout::LayoutStrip;
use crate::ecs::state::PaneruState;
use crate::errors::Result;
use crate::events::{Event, EventSender};
use crate::manager::{
Application, Origin, ProcessApi, Size, Window, WindowManager, WindowManagerApi, WindowManagerOS,
};
use crate::menubar::MenuBarManager;
use crate::overlay::{FlashMessageManager, OverlayManager};
use crate::platform::{Modifiers, PlatformCallbacks, WinID, WorkspaceId};
pub mod display;
pub mod focus;
pub mod layout;
pub mod mouse;
pub mod params;
pub(crate) mod restore;
pub mod scroll;
pub mod state;
mod systems;
mod triggers;
pub mod workspace;
#[allow(clippy::too_many_lines)]
pub fn register_systems(app: &mut bevy::app::App) {
const LOW_POWER_MODE_CHECK_SEC: u64 = 60;
let not_swiping = |scrolling: Query<&Scrolling, With<ActiveWorkspaceMarker>>| {
scrolling
.iter()
.next()
.is_none_or(|marker| !marker.is_user_swiping)
};
let dimming_enabled = |config: Option<Res<Config>>| {
config
.is_some_and(|config| config.has_dim_inactive_color() || config.border_active_window())
};
let overlay_dirty = |strip_changed: Query<
(),
(With<ActiveWorkspaceMarker>, Changed<LayoutStrip>),
>,
focus_gained: Query<(), Added<FocusedMarker>>,
mut focus_lost: RemovedComponents<FocusedMarker>| {
!strip_changed.is_empty() || !focus_gained.is_empty() || focus_lost.read().next().is_some()
};
let workspace_menu_status =
|config: Option<Res<Config>>| config.is_some_and(|config| config.workspace_menu_status());
let native_tabs_enabled =
|config: Option<Res<Config>>| config.is_none_or(|config| config.native_tabs_enabled());
app.add_systems(
Startup,
(systems::gather_displays, systems::gather_initial_processes).chain(),
);
app.add_systems(
PreUpdate,
(systems::window_creation_event, systems::pump_events),
);
app.add_systems(
Update,
(
(
triggers::apply_window_defaults,
systems::detect_tabbed_windows.run_if(native_tabs_enabled),
triggers::apply_window_positions,
)
.chain(),
(
systems::add_existing_process,
systems::add_existing_application,
systems::finish_setup,
)
.chain()
.run_if(resource_exists::<Initializing>),
systems::add_launched_process,
systems::add_launched_application,
systems::fresh_marker_cleanup,
systems::timeout_ticker,
systems::retry_front_switch,
systems::update_low_power_state
.run_if(resource_exists::<LowPowerMode>)
.run_if(on_timer(Duration::from_secs(LOW_POWER_MODE_CHECK_SEC))),
(
systems::window_resized_update_frame,
systems::window_moved_update_frame,
)
.chain()
.run_if(not_swiping),
systems::cleanup_on_exit,
restore::tick_restore_grace,
state::periodic_state_save.run_if(on_timer(Duration::from_secs(300))),
state::cleanup_on_exit,
),
);
app.add_systems(
PostUpdate,
(
(
systems::animate_entities,
systems::commit_window_position.run_if(not(resource_exists::<Initializing>)),
systems::verify_window_position.run_if(not(resource_exists::<Initializing>)),
)
.chain(),
(
systems::animate_resize_entities,
systems::commit_window_size.run_if(not(resource_exists::<Initializing>)),
)
.chain(),
(
systems::update_overlays
.after(systems::animate_entities)
.after(systems::animate_resize_entities)
.run_if(dimming_enabled)
.run_if(overlay_dirty),
systems::update_flash_messages,
)
.chain(),
crate::menubar::update_virtual_workspace_status_item.run_if(workspace_menu_status),
),
);
}
pub fn register_triggers(app: &mut bevy::app::App) {
app.add_systems(
Update,
(
triggers::front_switched_trigger,
triggers::window_focused_trigger,
triggers::mission_control_trigger,
triggers::application_event_trigger,
triggers::dispatch_application_messages,
triggers::window_destroyed_trigger,
triggers::refresh_configuration_trigger,
triggers::theme_change_trigger,
triggers::window_resize_verifier,
),
);
app.add_observer(triggers::window_unmanaged_trigger)
.add_observer(triggers::window_managed_trigger)
.add_observer(triggers::window_minimized_trigger)
.add_observer(triggers::spawn_window_trigger)
.add_observer(triggers::send_message_trigger)
.add_observer(triggers::window_removal_trigger)
.add_observer(triggers::cleanup_timeout_trigger)
.add_observer(restore::restore_window_state);
}
#[derive(Component)]
pub struct FocusedMarker;
#[derive(Component)]
pub struct ActiveWorkspaceMarker;
#[derive(Component)]
pub struct SelectedVirtualMarker;
#[derive(Component)]
pub struct FlashMessage(pub String);
#[derive(Component)]
pub struct ActiveDisplayMarker;
#[derive(Component)]
pub struct FreshMarker;
#[derive(Component)]
pub struct ExistingMarker;
#[derive(Component, Debug, Deref, DerefMut)]
pub struct RepositionMarker(pub Origin);
#[derive(Component, Debug, Deref, DerefMut)]
pub struct ResizeMarker(pub Size);
#[derive(Component)]
pub struct ReshuffleAroundMarker;
#[derive(Component)]
pub struct EnsureVisibleMarker;
#[derive(Component, Debug)]
pub struct Scrolling {
pub velocity: f64,
pub position: f64,
pub is_user_swiping: bool,
pub last_event: Instant,
}
impl Default for Scrolling {
fn default() -> Self {
Self {
velocity: 0.0,
position: 0.0,
is_user_swiping: false,
last_event: Instant::now(),
}
}
}
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
pub struct LayoutPosition(pub Origin);
#[derive(Component, Clone, Debug, Deref, DerefMut)]
pub struct Position(pub Origin);
#[derive(Component, Clone, Debug, Deref, DerefMut)]
pub struct Bounds(pub Size);
#[derive(Component, Clone, Debug, Deref, DerefMut)]
pub struct WidthRatio(pub f64);
#[derive(Clone, Component, Debug)]
pub struct NativeFullscreenMarker {
pub layout_strip: Entity,
pub workspace_id: WorkspaceId,
pub index: usize,
}
#[derive(Component)]
pub struct FullWidthMarker {
pub width_ratio: f64,
}
#[derive(Component, Debug)]
pub enum Unmanaged {
Floating,
Minimized,
Hidden,
}
#[derive(Clone, Component, Copy, Debug)]
pub struct PreviousManagedStrip {
pub workspace_id: WorkspaceId,
pub virtual_index: u32,
pub index: usize,
}
#[derive(Component, Deref, DerefMut)]
pub struct BProcess(pub Box<dyn ProcessApi>);
#[derive(Component)]
pub struct Timeout {
pub timer: Timer,
pub system_id: Option<SystemId>,
}
impl Timeout {
pub fn new(duration: Duration, message: Option<String>, commands: &mut Commands) -> Self {
let timer = Timer::from_seconds(duration.as_secs_f32(), bevy::time::TimerMode::Once);
if let Some(message) = message {
let callback = move || {
tracing::debug!("{message}");
};
let system_id = Some(commands.register_system(callback));
Self { timer, system_id }
} else {
Self {
timer,
system_id: None,
}
}
}
pub fn callback(duration: Duration, system_id: SystemId, commands: &mut Commands) {
let timer = Timer::from_seconds(duration.as_secs_f32(), bevy::time::TimerMode::Once);
commands.spawn(Self {
timer,
system_id: Some(system_id),
});
}
}
#[derive(Component)]
pub struct StrayFocusEvent(pub WinID);
#[derive(Component)]
pub struct RetryFrontSwitch(pub Entity);
#[derive(Component)]
pub struct BruteforceWindows(Task<Vec<Window>>);
#[derive(Component, Debug)]
pub enum DockPosition {
Bottom(i32),
Left(i32),
Right(i32),
Hidden,
}
#[derive(Component)]
pub struct RefreshWindowSizes(pub Instant);
impl Default for RefreshWindowSizes {
fn default() -> Self {
Self(Instant::now())
}
}
impl RefreshWindowSizes {
pub fn ready(&self) -> bool {
const REFRESH_WINDOW_SIZE_DELAY_SEC: u64 = 5;
self.0.elapsed() > Duration::from_secs(REFRESH_WINDOW_SIZE_DELAY_SEC)
}
}
#[derive(Component)]
pub struct VerifyWindowPosition {
remaining: u8,
}
impl Default for VerifyWindowPosition {
fn default() -> Self {
Self { remaining: 3 }
}
}
impl VerifyWindowPosition {
pub fn tick(&mut self) -> bool {
self.remaining = self.remaining.saturating_sub(1);
self.remaining == 0
}
}
#[derive(Deref, DerefMut, Resource)]
pub struct LowPowerMode(pub bool);
#[derive(Resource)]
pub struct SystemTheme {
pub is_dark: bool,
}
#[derive(Resource)]
pub struct SkipReshuffle(pub bool);
#[derive(Component)]
pub struct MouseHeldMarker(pub Entity);
#[derive(PartialEq, Resource)]
pub struct MissionControlActive(pub bool);
#[derive(Resource)]
pub struct FocusFollowsMouse(pub Option<WinID>);
#[derive(PartialEq, Resource)]
pub struct Initializing;
#[derive(BevyEvent)]
pub struct SpawnWindowTrigger(pub Vec<Window>);
#[derive(BevyEvent)]
pub struct ReadDisplayProperties(pub Entity);
#[derive(BevyEvent)]
pub struct SendMessageTrigger(pub Event);
#[derive(BevyEvent)]
pub struct RestoreWindowState;
pub trait SpawnCommandsExt {
fn reposition_entity(&mut self, entity: Entity, origin: Origin);
fn resize_entity(&mut self, entity: Entity, size: Size);
fn reshuffle_around(&mut self, entity: Entity);
fn ensure_visible(&mut self, entity: Entity);
fn focus_entity(&mut self, entity: Entity, raise: bool);
fn flash_message(&mut self, message: String, duration: f32);
fn spawn_layout_strip(
&mut self,
layout_strip: LayoutStrip,
origin: Origin,
display_entity: Entity,
active: bool,
) -> EntityCommands<'_>;
}
impl SpawnCommandsExt for Commands<'_, '_> {
#[instrument(level = Level::TRACE, skip(self))]
fn reposition_entity(&mut self, entity: Entity, origin: Origin) {
if let Ok(mut entity_commands) = self.get_entity(entity) {
entity_commands.try_insert(RepositionMarker(origin));
}
}
#[instrument(level = Level::TRACE, skip(self))]
fn resize_entity(&mut self, entity: Entity, size: Size) {
if size.x <= 0 || size.y <= 0 {
return;
}
if let Ok(mut entity_commands) = self.get_entity(entity) {
entity_commands.try_insert(ResizeMarker(size));
}
}
#[instrument(level = Level::TRACE, skip(self))]
fn reshuffle_around(&mut self, entity: Entity) {
if let Ok(mut entity_commands) = self.get_entity(entity) {
entity_commands.try_insert(ReshuffleAroundMarker);
}
}
#[instrument(level = Level::TRACE, skip(self))]
fn ensure_visible(&mut self, entity: Entity) {
if let Ok(mut entity_commands) = self.get_entity(entity) {
entity_commands.try_insert(EnsureVisibleMarker);
}
}
#[instrument(level = Level::TRACE, skip(self))]
fn focus_entity(&mut self, entity: Entity, raise: bool) {
if let Ok(mut entity_commands) = self.get_entity(entity) {
entity_commands.try_insert(FocusedMarker);
self.trigger(focus::FocusWindow { entity, raise });
}
}
#[instrument(level = Level::TRACE, skip(self))]
fn flash_message(&mut self, message: String, duration: f32) {
let timeout = Timeout::new(Duration::from_secs_f32(duration), None, self);
self.spawn((timeout, FlashMessage(message)));
}
#[instrument(level = Level::TRACE, skip(self))]
fn spawn_layout_strip(
&mut self,
layout_strip: LayoutStrip,
origin: Origin,
display_entity: Entity,
active: bool,
) -> EntityCommands<'_> {
let mut spawned = self.spawn((
layout_strip,
Position(origin),
FloatingLayer::default(),
ChildOf(display_entity),
));
if active {
spawned.insert(ActiveWorkspaceMarker);
} else {
spawned.insert(SelectedVirtualMarker);
}
spawned
}
}
pub fn setup_bevy_app(sender: EventSender, receiver: Receiver<Event>) -> Result<BevyApp> {
let window_manager: Box<dyn WindowManagerApi> = Box::new(WindowManagerOS::new(sender.clone()));
let watcher = window_manager.setup_config_watcher(CONFIGURATION_FILE.as_path())?;
let mut app = BevyApp::new();
app.add_plugins(MinimalPlugins)
.init_resource::<Messages<Event>>()
.insert_resource(Time::<Virtual>::from_max_delta(Duration::from_secs(10)))
.insert_resource(WindowManager(window_manager))
.insert_resource(SkipReshuffle(false))
.insert_resource(SystemTheme {
is_dark: crate::util::is_dark_mode(),
})
.insert_resource(MissionControlActive(false))
.insert_resource(FocusFollowsMouse(None))
.insert_resource(Initializing)
.insert_non_send_resource(watcher)
.add_plugins(mouse::MouseEventsPlugin)
.add_plugins(scroll::ScrollEventsPlugin)
.add_plugins(workspace::WorkspaceEventsPlugin)
.add_plugins(layout::LayoutEventsPlugin)
.add_plugins(focus::FocusEventsPlugin)
.add_plugins(display::DisplayEventsPlugin)
.add_plugins((register_triggers, register_systems, register_commands));
let mut platform_callbacks = PlatformCallbacks::new(sender);
platform_callbacks.setup_handlers()?;
let mtm = platform_callbacks.main_thread_marker;
let overlay_manager = OverlayManager::new(mtm);
let flash_message_manager = FlashMessageManager::new(mtm);
let menu_bar_manager = MenuBarManager::new(mtm);
app.insert_non_send_resource(platform_callbacks)
.insert_non_send_resource(overlay_manager)
.insert_non_send_resource(flash_message_manager)
.insert_non_send_resource(menu_bar_manager)
.insert_non_send_resource(receiver);
if let Some(previous_state) =
PaneruState::load_from_file(&PaneruState::default_state_file_path())
{
app.insert_resource(previous_state);
}
app.insert_resource(LowPowerMode(false));
Ok(app)
}
struct WindowProperties {
params: Vec<WindowParams>,
}
impl WindowProperties {
pub fn new(app: &Application, window: &Window, config: &Config) -> Self {
let bundle_id = app.bundle_id().unwrap_or_default();
let title = window.title().unwrap_or_default();
let params = config.find_window_properties(&title, &bundle_id);
Self { params }
}
pub fn floating(&self) -> bool {
self.params
.iter()
.find_map(|props| props.floating)
.unwrap_or(false)
}
pub fn insertion(&self) -> Option<usize> {
self.params.iter().find_map(|props| props.index)
}
pub fn dont_focus(&self) -> bool {
self.params
.iter()
.find_map(|props| props.dont_focus)
.unwrap_or(false)
}
pub fn border_radius(&self) -> Option<f64> {
self.params.iter().find_map(|p| p.border_radius)
}
pub fn grid_ratios(&self) -> Option<(f64, f64, f64, f64)> {
self.params.iter().find_map(WindowParams::grid_ratios)
}
pub fn passthrough_keys(&self) -> Vec<(u8, Modifiers)> {
self.params
.iter()
.flat_map(|p| p.passthrough_keys().to_vec())
.collect::<Vec<_>>()
}
pub fn width_ratio(&self) -> Option<f64> {
self.params.iter().find_map(|props| props.width)
}
pub fn vertical_padding(&self) -> i32 {
self.params
.iter()
.find_map(|props| props.vertical_padding)
.unwrap_or(0)
}
pub fn horizontal_padding(&self) -> i32 {
self.params
.iter()
.find_map(|props| props.horizontal_padding)
.unwrap_or(0)
}
}