cosmic-comp/src/state.rs

450 lines
15 KiB
Rust
Raw Normal View History

// SPDX-License-Identifier: GPL-3.0-only
2021-12-21 18:57:09 +01:00
use crate::{
2022-01-20 19:51:46 +01:00
backend::{kms::KmsState, winit::WinitState, x11::X11State},
config::{Config, OutputConfig},
2022-02-05 00:40:17 +01:00
logger::LogState,
2022-03-24 20:32:31 +01:00
shell::{init_shell, Shell},
2021-12-21 18:57:09 +01:00
};
use smithay::{
reexports::{
2022-04-27 13:25:17 +02:00
calloop::{LoopHandle, LoopSignal},
2022-02-04 21:14:20 +01:00
wayland_server::{protocol::wl_surface::WlSurface, Display},
},
2021-12-21 18:57:09 +01:00
wayland::{
2022-02-01 13:59:39 +01:00
data_device::{default_action_chooser, init_data_device, DataDeviceEvent},
output::{
wlr_configuration::{
self, init_wlr_output_configuration, ConfigurationManager, ModeConfiguration,
},
xdg::init_xdg_output_manager,
2022-04-20 16:06:37 +02:00
Mode as OutputMode, Output, Scale,
},
2021-12-21 18:57:09 +01:00
seat::Seat,
shell::xdg::ToplevelSurface,
shm::init_shm_global,
},
};
2022-01-11 19:18:41 +01:00
use std::{
cell::RefCell,
2022-02-08 17:15:24 +01:00
ffi::OsString,
rc::Rc,
sync::{atomic::AtomicBool, Arc},
time::Instant,
};
2022-01-11 19:18:41 +01:00
#[cfg(feature = "debug")]
use std::{collections::VecDeque, time::Duration};
pub struct State {
2022-01-11 17:00:04 +01:00
pub backend: BackendData,
2022-03-16 19:47:39 +01:00
pub common: Common,
2022-01-11 17:00:04 +01:00
}
pub struct Common {
2022-03-28 23:45:30 +02:00
pub config: Config,
pub display: Rc<RefCell<Display>>,
2022-02-08 17:15:24 +01:00
pub socket: OsString,
pub event_loop_handle: LoopHandle<'static, State>,
2022-04-27 13:25:17 +02:00
pub event_loop_signal: LoopSignal,
2021-12-21 18:57:09 +01:00
pub output_conf: ConfigurationManager,
2022-03-24 20:32:31 +01:00
pub shell: Shell,
2021-12-21 18:57:09 +01:00
pub pending_toplevels: Vec<ToplevelSurface>,
pub dirty_flag: Arc<AtomicBool>,
2021-12-21 18:57:09 +01:00
pub seats: Vec<Seat>,
pub last_active_seat: Seat,
2021-12-15 23:23:49 +01:00
pub start_time: Instant,
pub should_stop: bool,
2022-01-11 17:22:23 +01:00
2022-02-05 00:40:17 +01:00
pub log: LogState,
#[cfg(feature = "debug")]
2022-01-11 17:22:23 +01:00
pub egui: Egui,
}
#[cfg(feature = "debug")]
pub struct Egui {
2022-02-05 00:40:17 +01:00
pub debug_state: smithay_egui::EguiState,
pub log_state: smithay_egui::EguiState,
2022-01-11 17:22:23 +01:00
pub modifiers: smithay::wayland::seat::ModifiersState,
pub active: bool,
pub alpha: f32,
2021-12-15 23:23:49 +01:00
}
2022-01-11 19:18:41 +01:00
#[cfg(feature = "debug")]
pub struct Fps {
2022-02-04 21:08:11 +01:00
pub state: smithay_egui::EguiState,
pub modifiers: smithay::wayland::seat::ModifiersState,
pub frames: VecDeque<(Instant, Duration)>,
pub start: Instant,
2022-01-11 19:18:41 +01:00
}
2021-12-15 23:23:49 +01:00
pub enum BackendData {
X11(X11State),
Winit(WinitState),
2022-01-20 19:51:46 +01:00
Kms(KmsState),
2021-12-15 23:23:49 +01:00
// TODO
// Wayland(WaylandState),
Unset,
}
impl BackendData {
2022-01-20 19:51:46 +01:00
pub fn kms(&mut self) -> &mut KmsState {
match self {
BackendData::Kms(ref mut kms_state) => kms_state,
_ => unreachable!("Called kms in non kms backend"),
}
}
2021-12-15 23:23:49 +01:00
pub fn x11(&mut self) -> &mut X11State {
match self {
BackendData::X11(ref mut x11_state) => x11_state,
_ => unreachable!("Called x11 in non x11 backend"),
}
}
pub fn winit(&mut self) -> &mut WinitState {
match self {
BackendData::Winit(ref mut winit_state) => winit_state,
_ => unreachable!("Called winit in non winit backend"),
}
}
pub fn apply_config_for_output(
&mut self,
output: &Output,
test_only: bool,
shell: &mut Shell,
) -> Result<(), anyhow::Error> {
let result = match self {
BackendData::Kms(ref mut state) => {
2022-04-14 22:16:37 +02:00
state.apply_config_for_output(output, shell, test_only)
}
BackendData::Winit(ref mut state) => state.apply_config_for_output(output, test_only),
BackendData::X11(ref mut state) => state.apply_config_for_output(output, test_only),
_ => unreachable!("No backend set when applying output config"),
};
if result.is_ok() {
// apply to Output
let final_config = output
.user_data()
.get::<RefCell<OutputConfig>>()
.unwrap()
.borrow();
let mode = Some(OutputMode {
size: final_config.mode_size(),
refresh: final_config.mode_refresh() as i32,
})
.filter(|m| match output.current_mode() {
None => true,
Some(c_m) => m.size != c_m.size || m.refresh != c_m.refresh,
});
let transform =
Some(final_config.transform.into()).filter(|x| *x != output.current_transform());
let scale =
2022-04-20 16:06:37 +02:00
Some(final_config.scale).filter(|x| *x != output.current_scale().fractional_scale());
let location =
Some(final_config.position.into()).filter(|x| *x != output.current_location());
2022-04-20 16:06:37 +02:00
output.change_current_state(mode, transform, scale.map(Scale::Fractional), location);
2022-03-30 13:47:06 +02:00
}
result
2022-03-30 13:47:06 +02:00
}
pub fn schedule_render(&mut self, output: &Output) {
match self {
2022-02-04 21:14:20 +01:00
BackendData::Winit(_) => {} // We cannot do this on the winit backend.
// Winit has a very strict render-loop and skipping frames breaks atleast the wayland winit-backend.
// Swapping with damage (which should be empty on these frames) is likely good enough anyway.
BackendData::X11(ref mut state) => state.schedule_render(output),
BackendData::Kms(ref mut state) => state.schedule_render(output),
_ => unreachable!("No backend was initialized"),
}
}
}
2022-02-01 13:59:39 +01:00
struct DnDIcon {
surface: RefCell<Option<WlSurface>>,
}
pub fn get_dnd_icon(seat: &Seat) -> Option<WlSurface> {
let userdata = seat.user_data();
2022-02-04 21:14:20 +01:00
userdata
.get::<DnDIcon>()
.and_then(|x| x.surface.borrow().clone())
2022-02-01 13:59:39 +01:00
}
impl State {
2022-03-16 20:01:34 +01:00
pub fn new(
mut display: Display,
socket: OsString,
handle: LoopHandle<'static, State>,
2022-04-27 13:25:17 +02:00
signal: LoopSignal,
2022-03-16 20:01:34 +01:00
log: LogState,
) -> State {
let config = Config::load();
2021-12-21 18:57:09 +01:00
init_shm_global(&mut display, vec![], None);
init_xdg_output_manager(&mut display, None);
let shell = init_shell(&config, &mut display);
2021-12-21 18:57:09 +01:00
let initial_seat = crate::input::add_seat(&mut display, "seat-0".into());
init_data_device(
&mut display,
2022-02-01 13:59:39 +01:00
|dnd_event| match dnd_event {
DataDeviceEvent::DnDStarted { icon, seat, .. } => {
let user_data = seat.user_data();
2022-02-04 21:14:20 +01:00
user_data.insert_if_missing(|| DnDIcon {
surface: RefCell::new(None),
});
2022-02-01 13:59:39 +01:00
*user_data.get::<DnDIcon>().unwrap().surface.borrow_mut() = icon;
2022-02-04 21:14:20 +01:00
}
2022-02-01 13:59:39 +01:00
DataDeviceEvent::DnDDropped { seat } => {
2022-02-04 21:14:20 +01:00
seat.user_data()
.get::<DnDIcon>()
.unwrap()
.surface
.borrow_mut()
.take();
}
_ => {}
2022-02-01 13:59:39 +01:00
},
2021-12-21 18:57:09 +01:00
default_action_chooser,
None,
);
let (output_conf, _) = init_wlr_output_configuration(
&mut display,
|_| true,
|conf, test_only, mut ddata| {
let state = ddata.get::<State>().unwrap();
if conf.iter().all(|(_, conf)| conf.is_none()) {
return false; // we don't allow the user to accidentally disable all their outputs
}
let mut backups = Vec::new();
for (output, conf) in &conf {
{
let mut current_config = output
.user_data()
.get::<RefCell<OutputConfig>>()
.unwrap()
.borrow_mut();
backups.push((output, current_config.clone()));
if let Some(conf) = conf {
match conf.mode {
Some(ModeConfiguration::Mode(mode)) => {
current_config.mode =
((mode.size.w, mode.size.h), Some(mode.refresh as u32));
}
Some(ModeConfiguration::Custom { size, refresh }) => {
current_config.mode =
((size.w, size.h), refresh.map(|x| x as u32));
}
_ => {}
}
if let Some(scale) = conf.scale {
current_config.scale = scale;
}
if let Some(transform) = conf.transform {
current_config.transform = transform;
}
if let Some(position) = conf.position {
current_config.position = position.into();
}
current_config.enabled = true;
} else {
current_config.enabled = false;
}
}
if let Err(err) = state.backend.apply_config_for_output(
output,
test_only,
&mut state.common.shell,
) {
slog_scope::warn!(
"Failed to apply config to {}: {}. Resetting",
output.name(),
err
);
for (output, backup) in backups {
{
let mut current_config = output
.user_data()
.get::<RefCell<OutputConfig>>()
.unwrap()
.borrow_mut();
*current_config = backup;
}
if !test_only {
if let Err(err) = state.backend.apply_config_for_output(
output,
false,
&mut state.common.shell,
) {
slog_scope::error!(
"Failed to reset output config for {}: {}",
output.name(),
err
);
}
}
}
return false;
}
2022-04-14 22:16:37 +02:00
}
for output in conf.iter().filter(|(_, c)| c.is_some()).map(|(o, _)| o) {
wlr_configuration::enable_head(output);
}
for output in conf.iter().filter(|(_, c)| c.is_none()).map(|(o, _)| o) {
wlr_configuration::disable_head(output);
}
2022-04-14 22:16:37 +02:00
state.common.config.write_outputs(state.common.output_conf.outputs());
state.common.event_loop_handle.insert_idle(move |state| {
state
.common
.output_conf
.update(&mut *state.common.display.borrow_mut());
});
true
},
None,
);
2021-12-21 18:57:09 +01:00
2022-02-05 00:40:17 +01:00
#[cfg(not(feature = "debug"))]
let dirty_flag = Arc::new(AtomicBool::new(false));
#[cfg(feature = "debug")]
let dirty_flag = log.dirty_flag.clone();
State {
2022-01-11 17:00:04 +01:00
common: Common {
config,
2022-01-11 17:00:04 +01:00
display: Rc::new(RefCell::new(display)),
2022-02-08 17:15:24 +01:00
socket,
event_loop_handle: handle,
2022-04-27 13:25:17 +02:00
event_loop_signal: signal,
2021-12-21 18:57:09 +01:00
output_conf,
2022-03-24 20:32:31 +01:00
shell,
2022-01-11 17:00:04 +01:00
pending_toplevels: Vec::new(),
2022-02-05 00:40:17 +01:00
dirty_flag,
2021-12-21 18:57:09 +01:00
2022-01-11 17:00:04 +01:00
seats: vec![initial_seat.clone()],
last_active_seat: initial_seat,
2021-12-15 23:23:49 +01:00
2022-01-11 17:00:04 +01:00
start_time: Instant::now(),
should_stop: false,
2022-01-11 17:22:23 +01:00
2022-02-05 00:40:17 +01:00
log,
2022-01-11 17:22:23 +01:00
#[cfg(feature = "debug")]
egui: Egui {
2022-02-05 00:40:17 +01:00
debug_state: smithay_egui::EguiState::new(smithay_egui::EguiMode::Continuous),
log_state: {
2022-03-16 20:01:34 +01:00
let mut state =
smithay_egui::EguiState::new(smithay_egui::EguiMode::Continuous);
2022-02-05 00:40:17 +01:00
state.set_zindex(0);
state
},
2022-01-11 17:22:23 +01:00
modifiers: Default::default(),
active: false,
alpha: 1.0,
},
2022-01-11 17:00:04 +01:00
},
2021-12-15 23:23:49 +01:00
backend: BackendData::Unset,
}
}
2022-03-16 19:47:39 +01:00
pub fn destroy(self) -> LogState {
self.common.log
}
}
2022-01-11 19:18:41 +01:00
#[cfg(feature = "debug")]
impl Fps {
const WINDOW_SIZE: usize = 100;
2022-02-04 21:08:11 +01:00
pub fn start(&mut self) {
self.start = Instant::now();
}
pub fn end(&mut self) {
let frame_time = Instant::now().duration_since(self.start);
2022-01-11 19:18:41 +01:00
2022-02-04 21:08:11 +01:00
self.frames.push_back((self.start, frame_time));
if self.frames.len() > Fps::WINDOW_SIZE {
2022-01-11 19:18:41 +01:00
self.frames.pop_front();
}
}
pub fn max_frametime(&self) -> &Duration {
2022-02-04 21:08:11 +01:00
self.frames
.iter()
.map(|(_, f)| f)
.max()
.unwrap_or(&Duration::ZERO)
2022-01-11 19:18:41 +01:00
}
pub fn min_frametime(&self) -> &Duration {
2022-02-04 21:08:11 +01:00
self.frames
.iter()
.map(|(_, f)| f)
.min()
.unwrap_or(&Duration::ZERO)
2022-01-11 19:18:41 +01:00
}
pub fn avg_frametime(&self) -> Duration {
if self.frames.is_empty() {
return Duration::ZERO;
}
2022-02-04 21:08:11 +01:00
self.frames
.iter()
.map(|(_, f)| f)
.cloned()
.sum::<Duration>()
/ (self.frames.len() as u32)
2022-01-11 19:18:41 +01:00
}
pub fn avg_fps(&self) -> f64 {
if self.frames.is_empty() {
return 0.0;
}
2022-02-04 21:08:11 +01:00
let secs = match (self.frames.front(), self.frames.back()) {
2022-03-16 20:01:34 +01:00
(Some((start, _)), Some((end, dur))) => end.duration_since(*start) + *dur,
2022-02-04 21:08:11 +01:00
_ => Duration::ZERO,
}
.as_secs_f64();
1.0 / (secs / self.frames.len() as f64)
2022-01-11 19:18:41 +01:00
}
}
#[cfg(feature = "debug")]
impl Default for Fps {
fn default() -> Fps {
Fps {
2022-02-04 21:08:11 +01:00
state: {
let mut state = smithay_egui::EguiState::new(smithay_egui::EguiMode::Continuous);
2022-02-04 21:08:11 +01:00
let mut visuals: egui::style::Visuals = Default::default();
visuals.window_shadow.extrusion = 0.0;
state.context().set_visuals(visuals);
state.set_zindex(110); // always render on top
2022-02-04 21:08:11 +01:00
state
},
modifiers: Default::default(),
frames: VecDeque::with_capacity(Fps::WINDOW_SIZE + 1),
2022-02-04 21:08:11 +01:00
start: Instant::now(),
}
}
}
#[cfg(feature = "debug")]
2022-01-18 19:42:56 +01:00
pub fn avg_fps<'a>(iter: impl Iterator<Item = &'a Duration>) -> f64 {
let sum_secs = iter.map(|d| d.as_secs_f64()).sum::<f64>();
1.0 / (sum_secs / Fps::WINDOW_SIZE as f64)
2022-01-18 19:42:56 +01:00
}