pinnacle/src/state.rs

401 lines
13 KiB
Rust
Raw Normal View History

2023-08-01 11:06:35 -05:00
// SPDX-License-Identifier: GPL-3.0-or-later
2023-06-25 17:18:50 -05:00
2023-08-14 20:43:35 -05:00
mod api_handlers;
use std::{cell::RefCell, os::fd::AsRawFd, sync::Arc, time::Duration};
2023-06-17 21:02:58 -05:00
use crate::{
2023-09-20 15:27:51 -05:00
backend::{udev::Udev, winit::Winit, BackendData},
2023-09-21 17:12:16 -05:00
config::{
api::{msg::Msg, ApiState},
Config,
2023-09-21 17:12:16 -05:00
},
cursor::Cursor,
2023-06-17 21:02:58 -05:00
focus::FocusState,
grab::resize_grab::ResizeSurfaceState,
2023-09-08 19:56:40 -05:00
window::WindowElement,
2023-06-17 21:02:58 -05:00
};
2023-09-21 17:12:16 -05:00
use calloop::futures::Scheduler;
2023-06-02 16:01:48 -05:00
use smithay::{
2023-09-20 16:54:39 -05:00
desktop::{PopupManager, Space},
2023-06-09 20:29:17 -05:00
input::{keyboard::XkbConfig, pointer::CursorImageStatus, Seat, SeatState},
2023-06-02 16:01:48 -05:00
reexports::{
2023-06-17 18:55:04 -05:00
calloop::{
self, channel::Event, generic::Generic, Interest, LoopHandle, LoopSignal, Mode,
PostAction,
},
2023-06-02 16:01:48 -05:00
wayland_server::{
backend::{ClientData, ClientId, DisconnectReason},
protocol::wl_surface::WlSurface,
Display, DisplayHandle,
2023-06-02 16:01:48 -05:00
},
},
2023-09-08 19:56:40 -05:00
utils::{Clock, Logical, Monotonic, Point, Size},
2023-06-02 16:01:48 -05:00
wayland::{
compositor::{self, CompositorClientState, CompositorState},
2023-06-02 16:01:48 -05:00
data_device::DataDeviceState,
2023-06-09 20:29:17 -05:00
dmabuf::DmabufFeedback,
fractional_scale::FractionalScaleManagerState,
2023-06-02 16:01:48 -05:00
output::OutputManagerState,
primary_selection::PrimarySelectionState,
2023-08-14 20:43:35 -05:00
shell::{wlr_layer::WlrLayerShellState, xdg::XdgShellState},
2023-06-02 16:01:48 -05:00
shm::ShmState,
2023-06-09 20:29:17 -05:00
socket::ListeningSocketSource,
viewporter::ViewporterState,
2023-06-02 16:01:48 -05:00
},
2023-09-09 23:43:29 -05:00
xwayland::{X11Surface, X11Wm, XWayland, XWaylandEvent},
2023-06-02 16:01:48 -05:00
};
2023-08-28 22:53:24 -05:00
use crate::input::InputState;
pub enum Backend {
/// The compositor is running in a Winit window
2023-08-28 22:53:24 -05:00
Winit(Winit),
/// The compositor is running in a tty
2023-08-28 22:53:24 -05:00
Udev(Udev),
}
impl Backend {
pub fn seat_name(&self) -> String {
match self {
Backend::Winit(winit) => winit.seat_name(),
Backend::Udev(udev) => udev.seat_name(),
}
}
pub fn early_import(&mut self, surface: &WlSurface) {
match self {
Backend::Winit(winit) => winit.early_import(surface),
Backend::Udev(udev) => udev.early_import(surface),
}
}
2023-09-10 05:02:29 -05:00
/// Returns `true` if the backend is [`Winit`].
///
/// [`Winit`]: Backend::Winit
#[must_use]
pub fn is_winit(&self) -> bool {
matches!(self, Self::Winit(..))
}
2023-08-28 22:53:24 -05:00
}
2023-06-02 16:01:48 -05:00
2023-06-21 18:58:49 -05:00
/// The main state of the application.
2023-08-28 22:53:24 -05:00
pub struct State {
2023-09-20 17:20:48 -05:00
/// Which backend is currently running
2023-08-28 22:53:24 -05:00
pub backend: Backend,
2023-09-20 17:20:48 -05:00
/// A loop signal used to stop the compositor
2023-06-02 16:01:48 -05:00
pub loop_signal: LoopSignal,
2023-09-20 17:20:48 -05:00
/// A handle to the event loop
2023-08-28 22:53:24 -05:00
pub loop_handle: LoopHandle<'static, CalloopData>,
pub display_handle: DisplayHandle,
2023-06-02 16:01:48 -05:00
pub clock: Clock<Monotonic>,
2023-07-24 18:59:05 -05:00
pub space: Space<WindowElement>,
2023-09-20 17:20:48 -05:00
/// The name of the Wayland socket
2023-06-09 20:29:17 -05:00
pub socket_name: String,
2023-08-28 22:53:24 -05:00
pub seat: Seat<State>,
2023-06-02 16:01:48 -05:00
pub compositor_state: CompositorState,
pub data_device_state: DataDeviceState,
pub seat_state: SeatState<Self>,
pub shm_state: ShmState,
pub output_manager_state: OutputManagerState,
pub xdg_shell_state: XdgShellState,
pub viewporter_state: ViewporterState,
pub fractional_scale_manager_state: FractionalScaleManagerState,
pub primary_selection_state: PrimarySelectionState,
2023-08-04 18:48:10 -05:00
pub layer_shell_state: WlrLayerShellState,
pub input_state: InputState,
2023-06-17 18:55:04 -05:00
pub api_state: ApiState,
2023-06-17 21:02:58 -05:00
pub focus_state: FocusState,
2023-06-02 16:01:48 -05:00
pub popup_manager: PopupManager,
pub cursor_status: CursorImageStatus,
pub pointer_location: Point<f64, Logical>,
2023-08-02 18:18:51 -05:00
pub dnd_icon: Option<WlSurface>,
2023-07-24 18:59:05 -05:00
pub windows: Vec<WindowElement>,
2023-09-20 17:40:36 -05:00
pub config: Config,
2023-07-11 11:59:38 -05:00
2023-09-20 17:40:36 -05:00
pub async_scheduler: Scheduler<()>,
pub xwayland: XWayland,
pub xwm: Option<X11Wm>,
pub xdisplay: Option<u32>,
2023-09-09 23:43:29 -05:00
pub override_redirect_windows: Vec<X11Surface>,
2023-07-02 18:15:44 -05:00
}
2023-08-28 22:53:24 -05:00
impl State {
/// Creates the central state and starts the config and xwayland
2023-07-02 18:15:44 -05:00
pub fn init(
2023-08-28 22:53:24 -05:00
backend: Backend,
2023-07-02 18:15:44 -05:00
display: &mut Display<Self>,
loop_signal: LoopSignal,
2023-08-28 22:53:24 -05:00
loop_handle: LoopHandle<'static, CalloopData>,
2023-08-16 11:28:35 -05:00
) -> anyhow::Result<Self> {
2023-07-02 18:15:44 -05:00
let socket = ListeningSocketSource::new_auto()?;
let socket_name = socket.socket_name().to_os_string();
std::env::set_var("WAYLAND_DISPLAY", socket_name.clone());
2023-08-06 19:41:48 -05:00
tracing::info!(
"Set WAYLAND_DISPLAY to {}",
socket_name.clone().to_string_lossy()
);
2023-07-02 18:15:44 -05:00
// Opening a new process will use up a few file descriptors, around 10 for Alacritty, for
// example. Because of this, opening up only around 100 processes would exhaust the file
// descriptor limit on my system (Arch btw) and cause a "Too many open files" crash.
//
// To fix this, I just set the limit to be higher. As Pinnacle is the whole graphical
// environment, I *think* this is ok.
2023-08-06 19:41:48 -05:00
tracing::info!("Trying to raise file descriptor limit...");
2023-07-02 18:15:44 -05:00
if let Err(err) = smithay::reexports::nix::sys::resource::setrlimit(
smithay::reexports::nix::sys::resource::Resource::RLIMIT_NOFILE,
65536,
65536 * 2,
) {
tracing::error!("Could not raise fd limit: errno {err}");
2023-08-06 19:41:48 -05:00
} else {
tracing::info!("Fd raise success!");
2023-07-02 18:15:44 -05:00
}
loop_handle.insert_source(socket, |stream, _metadata, data| {
data.display
.handle()
.insert_client(stream, Arc::new(ClientState::default()))
.expect("Could not insert client into loop handle");
})?;
loop_handle.insert_source(
Generic::new(
display.backend().poll_fd().as_raw_fd(),
Interest::READ,
Mode::Level,
),
|_readiness, _metadata, data| {
data.display.dispatch_clients(&mut data.state)?;
Ok(PostAction::Continue)
},
)?;
let (tx_channel, rx_channel) = calloop::channel::channel::<Msg>();
loop_handle.insert_idle(|data| {
if let Err(err) = data.state.start_config(crate::config::get_config_dir()) {
panic!("failed to start config: {err}");
2023-07-02 18:15:44 -05:00
}
2023-08-16 11:28:35 -05:00
});
2023-09-21 17:12:16 -05:00
let (executor, sched) = calloop::futures::executor::<()>()?;
2023-08-16 11:28:35 -05:00
if let Err(err) = loop_handle.insert_source(executor, |_, _, _| {}) {
anyhow::bail!("Failed to insert async executor into event loop: {err}");
}
2023-07-02 18:15:44 -05:00
let display_handle = display.handle();
let mut seat_state = SeatState::new();
2023-08-28 22:53:24 -05:00
let mut seat = seat_state.new_wl_seat(&display_handle, backend.seat_name());
2023-07-02 18:15:44 -05:00
seat.add_pointer();
2023-09-21 17:12:16 -05:00
// TODO: update from config
2023-09-20 16:43:50 -05:00
seat.add_keyboard(XkbConfig::default(), 500, 25)?;
2023-07-02 18:15:44 -05:00
loop_handle.insert_idle(|data| {
data.state
.loop_handle
.insert_source(rx_channel, |msg, _, data| match msg {
Event::Msg(msg) => data.state.handle_msg(msg),
Event::Closed => todo!(),
})
.expect("failed to insert rx_channel into loop");
});
let xwayland = {
let (xwayland, channel) = XWayland::new(&display_handle);
let clone = display_handle.clone();
2023-07-24 18:59:05 -05:00
tracing::debug!("inserting into loop");
let res = loop_handle.insert_source(channel, move |event, _, data| match event {
XWaylandEvent::Ready {
connection,
client,
client_fd: _,
display,
} => {
let mut wm = X11Wm::start_wm(
data.state.loop_handle.clone(),
clone.clone(),
connection,
client,
2023-07-24 18:59:05 -05:00
)
.expect("failed to attach x11wm");
2023-09-20 16:43:50 -05:00
2023-07-24 18:59:05 -05:00
let cursor = Cursor::load();
let image = cursor.get_image(1, Duration::ZERO);
wm.set_cursor(
&image.pixels_rgba,
Size::from((image.width as u16, image.height as u16)),
Point::from((image.xhot as u16, image.yhot as u16)),
)
.expect("failed to set xwayland default cursor");
2023-09-20 16:43:50 -05:00
2023-07-24 18:59:05 -05:00
tracing::debug!("setting xwm and xdisplay");
2023-09-20 16:43:50 -05:00
2023-07-24 18:59:05 -05:00
data.state.xwm = Some(wm);
data.state.xdisplay = Some(display);
}
XWaylandEvent::Exited => {
data.state.xwm.take();
}
});
if let Err(err) = res {
tracing::error!("Failed to insert XWayland source into loop: {err}");
}
xwayland
};
2023-09-20 16:43:50 -05:00
tracing::debug!("xwayland set up");
2023-07-02 18:15:44 -05:00
Ok(Self {
2023-08-28 22:53:24 -05:00
backend,
2023-07-02 18:15:44 -05:00
loop_signal,
loop_handle,
display_handle: display_handle.clone(),
2023-07-02 18:15:44 -05:00
clock: Clock::<Monotonic>::new()?,
compositor_state: CompositorState::new::<Self>(&display_handle),
data_device_state: DataDeviceState::new::<Self>(&display_handle),
seat_state,
pointer_location: (0.0, 0.0).into(),
shm_state: ShmState::new::<Self>(&display_handle, vec![]),
2023-07-24 18:59:05 -05:00
space: Space::<WindowElement>::default(),
2023-07-02 18:15:44 -05:00
cursor_status: CursorImageStatus::Default,
output_manager_state: OutputManagerState::new_with_xdg_output::<Self>(&display_handle),
xdg_shell_state: XdgShellState::new::<Self>(&display_handle),
viewporter_state: ViewporterState::new::<Self>(&display_handle),
fractional_scale_manager_state: FractionalScaleManagerState::new::<Self>(
&display_handle,
),
primary_selection_state: PrimarySelectionState::new::<Self>(&display_handle),
2023-08-04 18:48:10 -05:00
layer_shell_state: WlrLayerShellState::new::<Self>(&display_handle),
input_state: InputState::new(),
2023-09-20 16:43:50 -05:00
api_state: ApiState {
stream: None,
socket_token: None,
2023-09-20 16:43:50 -05:00
tx_channel,
},
2023-07-02 18:15:44 -05:00
focus_state: FocusState::new(),
2023-09-20 17:40:36 -05:00
config: Config::default(),
2023-07-02 18:15:44 -05:00
seat,
2023-08-02 18:18:51 -05:00
dnd_icon: None,
2023-07-02 18:15:44 -05:00
socket_name: socket_name.to_string_lossy().to_string(),
popup_manager: PopupManager::default(),
async_scheduler: sched,
windows: vec![],
xwayland,
xwm: None,
xdisplay: None,
2023-09-09 23:43:29 -05:00
override_redirect_windows: vec![],
2023-07-02 18:15:44 -05:00
})
}
2023-08-31 20:35:54 -05:00
/// Schedule `run` to run when `condition` returns true.
///
/// This will continually reschedule `run` in the event loop if `condition` returns false.
pub fn schedule<F1, F2>(&self, condition: F1, run: F2)
where
F1: Fn(&mut CalloopData) -> bool + 'static,
F2: FnOnce(&mut CalloopData) + 'static,
{
self.loop_handle.insert_idle(|data| {
Self::schedule_inner(data, condition, run);
});
}
2023-09-05 20:45:29 -05:00
/// Schedule something to be done when `condition` returns true.
2023-08-31 20:35:54 -05:00
fn schedule_inner<F1, F2>(data: &mut CalloopData, condition: F1, run: F2)
where
F1: Fn(&mut CalloopData) -> bool + 'static,
F2: FnOnce(&mut CalloopData) + 'static,
{
if !condition(data) {
data.state.loop_handle.insert_idle(|data| {
Self::schedule_inner(data, condition, run);
});
return;
}
run(data);
}
2023-06-05 21:08:37 -05:00
}
2023-08-16 10:34:50 -05:00
2023-08-28 22:53:24 -05:00
pub struct CalloopData {
pub display: Display<State>,
pub state: State,
2023-06-02 16:01:48 -05:00
}
#[derive(Default)]
pub struct ClientState {
pub compositor_state: CompositorClientState,
}
2023-09-05 20:45:29 -05:00
2023-06-02 16:01:48 -05:00
impl ClientData for ClientState {
fn initialized(&self, _client_id: ClientId) {}
fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {}
}
2023-06-09 20:29:17 -05:00
#[derive(Debug, Copy, Clone)]
pub struct SurfaceDmabufFeedback<'a> {
pub render_feedback: &'a DmabufFeedback,
pub scanout_feedback: &'a DmabufFeedback,
}
/// A trait meant to be used in types with a [`UserDataMap`][smithay::utils::user_data::UserDataMap]
/// to get user-defined state.
pub trait WithState {
/// The user-defined state
2023-09-05 20:45:29 -05:00
type State;
2023-09-20 15:13:03 -05:00
/// Access data map state.
///
/// RefCell Safety: This function will panic if called within itself.
fn with_state<F, T>(&self, func: F) -> T
where
2023-09-20 15:13:03 -05:00
F: FnOnce(&mut Self::State) -> T;
}
#[derive(Default, Debug)]
pub struct WlSurfaceState {
pub resize_state: ResizeSurfaceState,
}
impl WithState for WlSurface {
type State = WlSurfaceState;
2023-09-20 15:13:03 -05:00
fn with_state<F, T>(&self, func: F) -> T
where
2023-09-20 15:13:03 -05:00
F: FnOnce(&mut Self::State) -> T,
{
compositor::with_states(self, |states| {
let state = states
.data_map
2023-09-20 15:13:03 -05:00
.get_or_insert(RefCell::<Self::State>::default);
func(&mut state.borrow_mut())
})
}
}