forge
Explore
Log in

Don't you dare go Hollow

Implement wlr-output-management protocol

Browse files at this commit

43df7fad46033692abc6a2b223e6d98f8b7a5aedtetParent: d2087a2
fix: wlr_output_management use WeakOutput
niri-ipc/src/lib.rsmodified+2 -2
@@ -433,7 +433,7 @@ pub struct Output {
433 }433 }
434 434
435 /// Output mode.435 /// Output mode.
436-#[derive(Debug, Serialize, Deserialize, Clone, Copy)]436+#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
437 pub struct Mode {437 pub struct Mode {
438 /// Width in physical pixels.438 /// Width in physical pixels.
439 pub width: u16,439 pub width: u16,
@@ -446,7 +446,7 @@ pub struct Mode {
446 }446 }
447 447
448 /// Logical output in the compositor's coordinate space.448 /// Logical output in the compositor's coordinate space.
449-#[derive(Debug, Serialize, Deserialize, Clone, Copy)]449+#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
450 pub struct LogicalOutput {450 pub struct LogicalOutput {
451 /// Logical X position.451 /// Logical X position.
452 pub x: i32,452 pub x: i32,
src/handlers/mod.rsmodified+17 -1
@@ -68,9 +68,13 @@ use crate::protocols::foreign_toplevel::{
68 self, ForeignToplevelHandler, ForeignToplevelManagerState,68 self, ForeignToplevelHandler, ForeignToplevelManagerState,
69 };69 };
70 use crate::protocols::gamma_control::{GammaControlHandler, GammaControlManagerState};70 use crate::protocols::gamma_control::{GammaControlHandler, GammaControlManagerState};
71+use crate::protocols::output_management::{OutputManagementHandler, OutputManagementManagerState};
71 use crate::protocols::screencopy::{Screencopy, ScreencopyHandler};72 use crate::protocols::screencopy::{Screencopy, ScreencopyHandler};
72 use crate::utils::{output_size, send_scale_transform};73 use crate::utils::{output_size, send_scale_transform};
73-use crate::{delegate_foreign_toplevel, delegate_gamma_control, delegate_screencopy};74+use crate::{
75+ delegate_foreign_toplevel, delegate_gamma_control, delegate_output_management,
76+ delegate_screencopy,
77+};
74 78
75 impl SeatHandler for State {79 impl SeatHandler for State {
76 type KeyboardFocus = WlSurface;80 type KeyboardFocus = WlSurface;
@@ -545,3 +549,15 @@ delegate_xdg_activation!(State);
545 549
546 impl FractionalScaleHandler for State {}550 impl FractionalScaleHandler for State {}
547 delegate_fractional_scale!(State);551 delegate_fractional_scale!(State);
552+
553+impl OutputManagementHandler for State {
554+ fn output_management_state(&mut self) -> &mut OutputManagementManagerState {
555+ &mut self.niri.output_management_state
556+ }
557+
558+ fn apply_output_config(&mut self, config: Vec<niri_config::Output>) {
559+ self.niri.config.borrow_mut().outputs = config;
560+ self.reload_output_config();
561+ }
562+}
563+delegate_output_management!(State);
src/niri.rsmodified+15 -1
@@ -114,6 +114,7 @@ use crate::ipc::server::IpcServer;
114 use crate::layout::{Layout, LayoutElement as _, MonitorRenderElement};114 use crate::layout::{Layout, LayoutElement as _, MonitorRenderElement};
115 use crate::protocols::foreign_toplevel::{self, ForeignToplevelManagerState};115 use crate::protocols::foreign_toplevel::{self, ForeignToplevelManagerState};
116 use crate::protocols::gamma_control::GammaControlManagerState;116 use crate::protocols::gamma_control::GammaControlManagerState;
117+use crate::protocols::output_management::OutputManagementManagerState;
117 use crate::protocols::screencopy::{Screencopy, ScreencopyManagerState};118 use crate::protocols::screencopy::{Screencopy, ScreencopyManagerState};
118 use crate::pw_utils::{Cast, PipeWire};119 use crate::pw_utils::{Cast, PipeWire};
119 #[cfg(feature = "xdp-gnome-screencast")]120 #[cfg(feature = "xdp-gnome-screencast")]
@@ -202,6 +203,7 @@ pub struct Niri {
202 pub session_lock_state: SessionLockManagerState,203 pub session_lock_state: SessionLockManagerState,
203 pub foreign_toplevel_state: ForeignToplevelManagerState,204 pub foreign_toplevel_state: ForeignToplevelManagerState,
204 pub screencopy_state: ScreencopyManagerState,205 pub screencopy_state: ScreencopyManagerState,
206+ pub output_management_state: OutputManagementManagerState,
205 pub viewporter_state: ViewporterState,207 pub viewporter_state: ViewporterState,
206 pub xdg_foreign_state: XdgForeignState,208 pub xdg_foreign_state: XdgForeignState,
207 pub shm_state: ShmState,209 pub shm_state: ShmState,
@@ -1051,7 +1053,7 @@ impl State {
1051 self.niri.queue_redraw_all();1053 self.niri.queue_redraw_all();
1052 }1054 }
1053 1055
1054- fn reload_output_config(&mut self) {1056+ pub fn reload_output_config(&mut self) {
1055 let mut resized_outputs = vec![];1057 let mut resized_outputs = vec![];
1056 for output in self.niri.global_space.outputs() {1058 for output in self.niri.global_space.outputs() {
1057 let name = output.name();1059 let name = output.name();
@@ -1103,6 +1105,9 @@ impl State {
1103 if let Some(touch) = self.niri.seat.get_touch() {1105 if let Some(touch) = self.niri.seat.get_touch() {
1104 touch.cancel(self);1106 touch.cancel(self);
1105 }1107 }
1108+
1109+ let config = self.niri.config.borrow().outputs.clone();
1110+ self.niri.output_management_state.on_config_changed(config);
1106 }1111 }
1107 1112
1108 pub fn apply_transient_output_config(&mut self, name: &str, action: niri_ipc::OutputAction) {1113 pub fn apply_transient_output_config(&mut self, name: &str, action: niri_ipc::OutputAction) {
@@ -1178,6 +1183,9 @@ impl State {
1178 1183
1179 #[cfg(feature = "dbus")]1184 #[cfg(feature = "dbus")]
1180 self.niri.on_ipc_outputs_changed();1185 self.niri.on_ipc_outputs_changed();
1186+
1187+ let new_config = self.backend.ipc_outputs().lock().unwrap().clone();
1188+ self.niri.output_management_state.notify_changes(new_config);
1181 }1189 }
1182 1190
1183 #[cfg(feature = "xdp-gnome-screencast")]1191 #[cfg(feature = "xdp-gnome-screencast")]
@@ -1482,6 +1490,11 @@ impl Niri {
1482 ForeignToplevelManagerState::new::<State, _>(&display_handle, |client| {1490 ForeignToplevelManagerState::new::<State, _>(&display_handle, |client| {
1483 !client.get_data::<ClientState>().unwrap().restricted1491 !client.get_data::<ClientState>().unwrap().restricted
1484 });1492 });
1493+ let mut output_management_state =
1494+ OutputManagementManagerState::new::<State, _>(&display_handle, |client| {
1495+ !client.get_data::<ClientState>().unwrap().restricted
1496+ });
1497+ output_management_state.on_config_changed(config_.outputs.clone());
1485 let screencopy_state = ScreencopyManagerState::new::<State, _>(&display_handle, |client| {1498 let screencopy_state = ScreencopyManagerState::new::<State, _>(&display_handle, |client| {
1486 !client.get_data::<ClientState>().unwrap().restricted1499 !client.get_data::<ClientState>().unwrap().restricted
1487 });1500 });
@@ -1626,6 +1639,7 @@ impl Niri {
1626 layer_shell_state,1639 layer_shell_state,
1627 session_lock_state,1640 session_lock_state,
1628 foreign_toplevel_state,1641 foreign_toplevel_state,
1642+ output_management_state,
1629 screencopy_state,1643 screencopy_state,
1630 viewporter_state,1644 viewporter_state,
1631 xdg_foreign_state,1645 xdg_foreign_state,
src/protocols/mod.rsmodified+1 -0
@@ -1,3 +1,4 @@
1 pub mod foreign_toplevel;1 pub mod foreign_toplevel;
2 pub mod gamma_control;2 pub mod gamma_control;
3+pub mod output_management;
3 pub mod screencopy;4 pub mod screencopy;
src/protocols/output_management.rsadded+891 -0
@@ -0,0 +1,891 @@
1+use std::collections::hash_map::Entry;
2+use std::collections::HashMap;
3+use std::iter::zip;
4+use std::mem;
5+
6+use niri_config::FloatOrInt;
7+use niri_ipc::Transform;
8+use smithay::reexports::wayland_protocols_wlr::output_management::v1::server::{
9+ zwlr_output_configuration_head_v1, zwlr_output_configuration_v1, zwlr_output_head_v1,
10+ zwlr_output_manager_v1, zwlr_output_mode_v1,
11+};
12+use smithay::reexports::wayland_server::backend::ClientId;
13+use smithay::reexports::wayland_server::protocol::wl_output::Transform as WlTransform;
14+use smithay::reexports::wayland_server::{
15+ Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource, WEnum,
16+};
17+use zwlr_output_configuration_head_v1::ZwlrOutputConfigurationHeadV1;
18+use zwlr_output_configuration_v1::ZwlrOutputConfigurationV1;
19+use zwlr_output_head_v1::{AdaptiveSyncState, ZwlrOutputHeadV1};
20+use zwlr_output_manager_v1::ZwlrOutputManagerV1;
21+use zwlr_output_mode_v1::ZwlrOutputModeV1;
22+
23+use crate::backend::OutputId;
24+use crate::niri::State;
25+use crate::utils::ipc_transform_to_smithay;
26+
27+const VERSION: u32 = 4;
28+
29+#[derive(Debug)]
30+struct ClientData {
31+ heads: HashMap<OutputId, (ZwlrOutputHeadV1, Vec<ZwlrOutputModeV1>)>,
32+ confs: HashMap<ZwlrOutputConfigurationV1, OutputConfigurationState>,
33+ manager: ZwlrOutputManagerV1,
34+}
35+
36+pub struct OutputManagementManagerState {
37+ display: DisplayHandle,
38+ serial: u32,
39+ clients: HashMap<ClientId, ClientData>,
40+ current_state: HashMap<OutputId, niri_ipc::Output>,
41+ current_config: Vec<niri_config::Output>,
42+}
43+
44+pub struct OutputManagementManagerGlobalData {
45+ filter: Box<dyn for<'c> Fn(&'c Client) -> bool + Send + Sync>,
46+}
47+
48+pub trait OutputManagementHandler {
49+ fn output_management_state(&mut self) -> &mut OutputManagementManagerState;
50+ fn apply_output_config(&mut self, config: Vec<niri_config::Output>);
51+}
52+
53+#[derive(Debug)]
54+enum OutputConfigurationState {
55+ Ongoing(HashMap<OutputId, niri_config::Output>),
56+ Finished,
57+}
58+
59+pub enum OutputConfigurationHeadState {
60+ Cancelled,
61+ Ok(OutputId, ZwlrOutputConfigurationV1),
62+}
63+
64+impl OutputManagementManagerState {
65+ pub fn new<D, F>(display: &DisplayHandle, filter: F) -> Self
66+ where
67+ D: GlobalDispatch<ZwlrOutputManagerV1, OutputManagementManagerGlobalData>,
68+ D: Dispatch<ZwlrOutputManagerV1, ()>,
69+ D: Dispatch<ZwlrOutputHeadV1, OutputId>,
70+ D: Dispatch<ZwlrOutputConfigurationV1, u32>,
71+ D: Dispatch<ZwlrOutputConfigurationHeadV1, OutputConfigurationHeadState>,
72+ D: Dispatch<ZwlrOutputModeV1, ()>,
73+ D: OutputManagementHandler,
74+ D: 'static,
75+ F: for<'c> Fn(&'c Client) -> bool + Send + Sync + 'static,
76+ {
77+ let global_data = OutputManagementManagerGlobalData {
78+ filter: Box::new(filter),
79+ };
80+ display.create_global::<D, ZwlrOutputManagerV1, _>(VERSION, global_data);
81+
82+ Self {
83+ display: display.clone(),
84+ clients: HashMap::new(),
85+ serial: 0,
86+ current_state: HashMap::new(),
87+ current_config: Vec::new(),
88+ }
89+ }
90+
91+ pub fn on_config_changed(&mut self, new_config: Vec<niri_config::Output>) {
92+ self.current_config = new_config;
93+ }
94+
95+ pub fn notify_changes(&mut self, new_state: HashMap<OutputId, niri_ipc::Output>) {
96+ let mut changed = false; /* most likely to end up true */
97+ for (output, conf) in new_state.iter() {
98+ if let Some(old) = self.current_state.get(output) {
99+ if old.vrr_enabled != conf.vrr_enabled {
100+ changed = true;
101+ for client in self.clients.values() {
102+ if let Some((head, _)) = client.heads.get(output) {
103+ if head.version() >= zwlr_output_head_v1::EVT_ADAPTIVE_SYNC_SINCE {
104+ head.adaptive_sync(match conf.vrr_enabled {
105+ true => AdaptiveSyncState::Enabled,
106+ false => AdaptiveSyncState::Disabled,
107+ });
108+ }
109+ }
110+ }
111+ }
112+
113+ // TTY outputs can't change modes I think, however, winit and virtual outputs can.
114+ let modes_changed = old.modes != conf.modes;
115+ if modes_changed {
116+ changed = true;
117+ if old.modes.len() != conf.modes.len() {
118+ error!("output's old mode count doesn't match new modes");
119+ } else {
120+ for client in self.clients.values() {
121+ if let Some((_, modes)) = client.heads.get(output) {
122+ for (wl_mode, mode) in zip(modes, &conf.modes) {
123+ wl_mode.size(i32::from(mode.width), i32::from(mode.height));
124+ if let Ok(refresh_rate) = mode.refresh_rate.try_into() {
125+ wl_mode.refresh(refresh_rate);
126+ }
127+ }
128+ }
129+ }
130+ }
131+ }
132+
133+ match (old.current_mode, conf.current_mode) {
134+ (Some(old_index), Some(new_index)) => {
135+ if old.modes.len() == conf.modes.len()
136+ && (modes_changed || old_index != new_index)
137+ {
138+ changed = true;
139+ for client in self.clients.values() {
140+ if let Some((head, modes)) = client.heads.get(output) {
141+ if let Some(new_mode) = modes.get(new_index) {
142+ head.current_mode(new_mode);
143+ } else {
144+ error!(
145+ "output new mode doesnt exist for the client's output"
146+ );
147+ }
148+ }
149+ }
150+ }
151+ }
152+ (Some(_), None) => {
153+ changed = true;
154+ for client in self.clients.values() {
155+ if let Some((head, _)) = client.heads.get(output) {
156+ head.enabled(0);
157+ }
158+ }
159+ }
160+ (None, Some(new_index)) => {
161+ if old.modes.len() == conf.modes.len() {
162+ changed = true;
163+ for client in self.clients.values() {
164+ if let Some((head, modes)) = client.heads.get(output) {
165+ head.enabled(1);
166+ if let Some(mode) = modes.get(new_index) {
167+ head.current_mode(mode);
168+ } else {
169+ error!(
170+ "output new mode doesnt exist for the client's output"
171+ );
172+ }
173+ }
174+ }
175+ }
176+ }
177+ (None, None) => {}
178+ }
179+ match (old.logical, conf.logical) {
180+ (Some(old_logical), Some(new_logical)) => {
181+ if old_logical != new_logical {
182+ changed = true;
183+ for client in self.clients.values() {
184+ if let Some((head, _)) = client.heads.get(output) {
185+ if old_logical.x != new_logical.x
186+ || old_logical.y != new_logical.y
187+ {
188+ head.position(new_logical.x, new_logical.y);
189+ }
190+ if old_logical.scale != new_logical.scale {
191+ head.scale(new_logical.scale);
192+ }
193+ if old_logical.transform != new_logical.transform {
194+ head.transform(
195+ ipc_transform_to_smithay(new_logical.transform).into(),
196+ );
197+ }
198+ }
199+ }
200+ }
201+ }
202+ (None, Some(new_logical)) => {
203+ changed = true;
204+ for client in self.clients.values() {
205+ if let Some((head, _)) = client.heads.get(output) {
206+ // head enable in the mode diff check
207+ head.position(new_logical.x, new_logical.y);
208+ head.transform(
209+ ipc_transform_to_smithay(new_logical.transform).into(),
210+ );
211+ head.scale(new_logical.scale);
212+ }
213+ }
214+ }
215+ (Some(_), None) => {
216+ // heads disabled in the mode diff check
217+ }
218+ (None, None) => {}
219+ }
220+ } else {
221+ changed = true;
222+ notify_new_head(self, output, conf);
223+ }
224+ }
225+ for (old, _) in self.current_state.iter() {
226+ if !new_state.contains_key(old) {
227+ changed = true;
228+ notify_removed_head(&mut self.clients, old);
229+ }
230+ }
231+ if changed {
232+ self.current_state = new_state;
233+ self.serial += 1;
234+ for data in self.clients.values() {
235+ data.manager.done(self.serial);
236+ for conf in data.confs.keys() {
237+ conf.cancelled();
238+ }
239+ }
240+ }
241+ }
242+}
243+
244+impl<D> GlobalDispatch<ZwlrOutputManagerV1, OutputManagementManagerGlobalData, D>
245+ for OutputManagementManagerState
246+where
247+ D: GlobalDispatch<ZwlrOutputManagerV1, OutputManagementManagerGlobalData>,
248+ D: Dispatch<ZwlrOutputManagerV1, ()>,
249+ D: Dispatch<ZwlrOutputHeadV1, OutputId>,
250+ D: Dispatch<ZwlrOutputConfigurationV1, u32>,
251+ D: Dispatch<ZwlrOutputConfigurationHeadV1, OutputConfigurationHeadState>,
252+ D: Dispatch<ZwlrOutputModeV1, ()>,
253+ D: OutputManagementHandler,
254+ D: 'static,
255+{
256+ fn bind(
257+ state: &mut D,
258+ display: &DisplayHandle,
259+ client: &Client,
260+ manager: New<ZwlrOutputManagerV1>,
261+ _manager_state: &OutputManagementManagerGlobalData,
262+ data_init: &mut DataInit<'_, D>,
263+ ) {
264+ let manager = data_init.init(manager, ());
265+ let g_state = state.output_management_state();
266+ let mut client_data = ClientData {
267+ heads: HashMap::new(),
268+ confs: HashMap::new(),
269+ manager: manager.clone(),
270+ };
271+ for (output, conf) in &g_state.current_state {
272+ send_new_head::<D>(display, client, &mut client_data, *output, conf);
273+ }
274+ g_state.clients.insert(client.id(), client_data);
275+ manager.done(g_state.serial);
276+ }
277+
278+ fn can_view(client: Client, global_data: &OutputManagementManagerGlobalData) -> bool {
279+ (global_data.filter)(&client)
280+ }
281+}
282+
283+impl<D> Dispatch<ZwlrOutputManagerV1, (), D> for OutputManagementManagerState
284+where
285+ D: GlobalDispatch<ZwlrOutputManagerV1, OutputManagementManagerGlobalData>,
286+ D: Dispatch<ZwlrOutputManagerV1, ()>,
287+ D: Dispatch<ZwlrOutputHeadV1, OutputId>,
288+ D: Dispatch<ZwlrOutputConfigurationV1, u32>,
289+ D: Dispatch<ZwlrOutputConfigurationHeadV1, OutputConfigurationHeadState>,
290+ D: Dispatch<ZwlrOutputModeV1, ()>,
291+ D: OutputManagementHandler,
292+ D: 'static,
293+{
294+ fn request(
295+ state: &mut D,
296+ client: &Client,
297+ _manager: &ZwlrOutputManagerV1,
298+ request: zwlr_output_manager_v1::Request,
299+ _data: &(),
300+ _display: &DisplayHandle,
301+ data_init: &mut DataInit<'_, D>,
302+ ) {
303+ match request {
304+ zwlr_output_manager_v1::Request::CreateConfiguration { id, serial } => {
305+ let g_state = state.output_management_state();
306+ let conf = data_init.init(id, serial);
307+ if let Some(client_data) = g_state.clients.get_mut(&client.id()) {
308+ if serial != g_state.serial {
309+ conf.cancelled();
310+ }
311+ let state = OutputConfigurationState::Ongoing(HashMap::new());
312+ client_data.confs.insert(conf, state);
313+ } else {
314+ error!("CreateConfiguration: missing client data");
315+ }
316+ }
317+ zwlr_output_manager_v1::Request::Stop => {
318+ if let Some(c) = state.output_management_state().clients.remove(&client.id()) {
319+ c.manager.finished()
320+ }
321+ }
322+ _ => unreachable!(),
323+ }
324+ }
325+ fn destroyed(state: &mut D, client: ClientId, _resource: &ZwlrOutputManagerV1, _data: &()) {
326+ state.output_management_state().clients.remove(&client);
327+ }
328+}
329+
330+impl<D> Dispatch<ZwlrOutputConfigurationV1, u32, D> for OutputManagementManagerState
331+where
332+ D: GlobalDispatch<ZwlrOutputManagerV1, OutputManagementManagerGlobalData>,
333+ D: Dispatch<ZwlrOutputManagerV1, ()>,
334+ D: Dispatch<ZwlrOutputHeadV1, OutputId>,
335+ D: Dispatch<ZwlrOutputConfigurationV1, u32>,
336+ D: Dispatch<ZwlrOutputConfigurationHeadV1, OutputConfigurationHeadState>,
337+ D: Dispatch<ZwlrOutputModeV1, ()>,
338+ D: OutputManagementHandler,
339+ D: 'static,
340+{
341+ fn request(
342+ state: &mut D,
343+ client: &Client,
344+ conf: &ZwlrOutputConfigurationV1,
345+ request: zwlr_output_configuration_v1::Request,
346+ serial: &u32,
347+ _display: &DisplayHandle,
348+ data_init: &mut DataInit<'_, D>,
349+ ) {
350+ let g_state = state.output_management_state();
351+ let outdated = *serial != g_state.serial;
352+ if outdated {
353+ debug!("OutputConfiguration: request from an outdated configuration");
354+ }
355+
356+ let new_config = g_state
357+ .clients
358+ .get_mut(&client.id())
359+ .and_then(|data| data.confs.get_mut(conf));
360+ if new_config.is_none() {
361+ error!("OutputConfiguration: request from unknown configuration object");
362+ }
363+
364+ match request {
365+ zwlr_output_configuration_v1::Request::EnableHead { id, head } => {
366+ let Some(output) = head.data::<OutputId>() else {
367+ error!("EnableHead: Missing attached output");
368+ let _fail = data_init.init(id, OutputConfigurationHeadState::Cancelled);
369+ return;
370+ };
371+ if outdated {
372+ let _fail = data_init.init(id, OutputConfigurationHeadState::Cancelled);
373+ return;
374+ }
375+
376+ let Some(new_config) = new_config else {
377+ let _fail = data_init.init(id, OutputConfigurationHeadState::Cancelled);
378+ return;
379+ };
380+
381+ let OutputConfigurationState::Ongoing(new_config) = new_config else {
382+ let _fail = data_init.init(id, OutputConfigurationHeadState::Cancelled);
383+ conf.post_error(
384+ zwlr_output_configuration_v1::Error::AlreadyUsed,
385+ "configuration had already been used",
386+ );
387+ return;
388+ };
389+
390+ let Some(current_config) = g_state.current_state.get(output) else {
391+ error!("EnableHead: output missing from current config");
392+ let _fail = data_init.init(id, OutputConfigurationHeadState::Cancelled);
393+ return;
394+ };
395+
396+ match new_config.entry(*output) {
397+ Entry::Occupied(_) => {
398+ let _fail = data_init.init(id, OutputConfigurationHeadState::Cancelled);
399+ conf.post_error(
400+ zwlr_output_configuration_v1::Error::AlreadyConfiguredHead,
401+ "head has been already configured",
402+ );
403+ return;
404+ }
405+ Entry::Vacant(entry) => {
406+ let mut config = g_state
407+ .current_config
408+ .iter()
409+ .find(|o| o.name.eq_ignore_ascii_case(&current_config.name))
410+ .cloned()
411+ .unwrap_or_else(|| niri_config::Output {
412+ name: current_config.name.clone(),
413+ ..Default::default()
414+ });
415+ config.off = false;
416+ entry.insert(config);
417+ }
418+ };
419+
420+ data_init.init(id, OutputConfigurationHeadState::Ok(*output, conf.clone()));
421+ }
422+ zwlr_output_configuration_v1::Request::DisableHead { head } => {
423+ if outdated {
424+ return;
425+ }
426+ let Some(output) = head.data::<OutputId>() else {
427+ error!("DisableHead: missing attached output head name");
428+ return;
429+ };
430+
431+ let Some(new_config) = new_config else {
432+ return;
433+ };
434+
435+ let OutputConfigurationState::Ongoing(new_config) = new_config else {
436+ conf.post_error(
437+ zwlr_output_configuration_v1::Error::AlreadyUsed,
438+ "configuration had already been used",
439+ );
440+ return;
441+ };
442+
443+ let Some(current_config) = g_state.current_state.get(output) else {
444+ error!("EnableHead: output missing from current config");
445+ return;
446+ };
447+
448+ match new_config.entry(*output) {
449+ Entry::Occupied(_) => {
450+ conf.post_error(
451+ zwlr_output_configuration_v1::Error::AlreadyConfiguredHead,
452+ "head has been already configured",
453+ );
454+ }
455+ Entry::Vacant(entry) => {
456+ let mut config = g_state
457+ .current_config
458+ .iter()
459+ .find(|o| o.name.eq_ignore_ascii_case(&current_config.name))
460+ .cloned()
461+ .unwrap_or_else(|| niri_config::Output {
462+ name: current_config.name.clone(),
463+ ..Default::default()
464+ });
465+ config.off = true;
466+ entry.insert(config);
467+ }
468+ };
469+ }
470+ zwlr_output_configuration_v1::Request::Apply => {
471+ if outdated {
472+ conf.cancelled();
473+ return;
474+ }
475+
476+ let Some(new_config) = new_config else {
477+ return;
478+ };
479+
480+ let OutputConfigurationState::Ongoing(new_config) =
481+ mem::replace(new_config, OutputConfigurationState::Finished)
482+ else {
483+ conf.post_error(
484+ zwlr_output_configuration_v1::Error::AlreadyUsed,
485+ "configuration had already been used",
486+ );
487+ return;
488+ };
489+
490+ let any_enabled = new_config.values().any(|c| !c.off);
491+ if !any_enabled {
492+ conf.failed();
493+ return;
494+ }
495+
496+ state.apply_output_config(new_config.into_values().collect());
497+ // FIXME: verify that it had been applied successfully (which may be difficult).
498+ conf.succeeded();
499+ }
500+ zwlr_output_configuration_v1::Request::Test => {
501+ if outdated {
502+ conf.cancelled();
503+ return;
504+ }
505+
506+ let Some(new_config) = new_config else {
507+ return;
508+ };
509+
510+ let OutputConfigurationState::Ongoing(new_config) =
511+ mem::replace(new_config, OutputConfigurationState::Finished)
512+ else {
513+ conf.post_error(
514+ zwlr_output_configuration_v1::Error::AlreadyUsed,
515+ "configuration had already been used",
516+ );
517+ return;
518+ };
519+
520+ let any_enabled = new_config.values().any(|c| !c.off);
521+ if !any_enabled {
522+ conf.failed();
523+ return;
524+ }
525+
526+ // FIXME: actually test the configuration with TTY.
527+ conf.succeeded()
528+ }
529+ zwlr_output_configuration_v1::Request::Destroy => {
530+ g_state
531+ .clients
532+ .get_mut(&client.id())
533+ .map(|d| d.confs.remove(conf));
534+ }
535+ _ => unreachable!(),
536+ }
537+ }
538+}
539+
540+impl<D> Dispatch<ZwlrOutputConfigurationHeadV1, OutputConfigurationHeadState, D>
541+ for OutputManagementManagerState
542+where
543+ D: GlobalDispatch<ZwlrOutputManagerV1, OutputManagementManagerGlobalData>,
544+ D: Dispatch<ZwlrOutputManagerV1, ()>,
545+ D: Dispatch<ZwlrOutputHeadV1, OutputId>,
546+ D: Dispatch<ZwlrOutputConfigurationV1, u32>,
547+ D: Dispatch<ZwlrOutputConfigurationHeadV1, OutputConfigurationHeadState>,
548+ D: Dispatch<ZwlrOutputModeV1, ()>,
549+ D: OutputManagementHandler,
550+ D: 'static,
551+{
552+ fn request(
553+ state: &mut D,
554+ client: &Client,
555+ conf_head: &ZwlrOutputConfigurationHeadV1,
556+ request: zwlr_output_configuration_head_v1::Request,
557+ data: &OutputConfigurationHeadState,
558+ _display: &DisplayHandle,
559+ _data_init: &mut DataInit<'_, D>,
560+ ) {
561+ let g_state = state.output_management_state();
562+ let Some(client_data) = g_state.clients.get_mut(&client.id()) else {
563+ error!("ConfigurationHead: missing client data");
564+ return;
565+ };
566+ let OutputConfigurationHeadState::Ok(output_id, conf) = data else {
567+ warn!("ConfigurationHead: request sent to a cancelled head");
568+ return;
569+ };
570+ let Some(serial) = conf.data::<u32>() else {
571+ error!("ConfigurationHead: missing serial");
572+ return;
573+ };
574+ if *serial != g_state.serial {
575+ warn!("ConfigurationHead: request sent to an outdated");
576+ return;
577+ }
578+ let Some(new_config) = client_data.confs.get_mut(conf) else {
579+ error!("ConfigurationHead: unknown configuration");
580+ return;
581+ };
582+ let OutputConfigurationState::Ongoing(new_config) = new_config else {
583+ conf.post_error(
584+ zwlr_output_configuration_v1::Error::AlreadyUsed,
585+ "configuration had already been used",
586+ );
587+ return;
588+ };
589+ let Some(new_config) = new_config.get_mut(output_id) else {
590+ error!("ConfigurationHead: config missing from enabled heads");
591+ return;
592+ };
593+
594+ match request {
595+ zwlr_output_configuration_head_v1::Request::SetMode { mode } => {
596+ let index = match client_data
597+ .heads
598+ .get(output_id)
599+ .map(|(_, mods)| mods.iter().position(|m| m.id() == mode.id()))
600+ {
601+ Some(Some(index)) => index,
602+ _ => {
603+ warn!("SetMode: failed to find requested mode");
604+ conf_head.post_error(
605+ zwlr_output_configuration_head_v1::Error::InvalidMode,
606+ "failed to find requested mode",
607+ );
608+ return;
609+ }
610+ };
611+
612+ let Some(current_config) = g_state.current_state.get(output_id) else {
613+ warn!("SetMode: output missing from the current config");
614+ return;
615+ };
616+
617+ let Some(mode) = current_config.modes.get(index) else {
618+ error!("SetMode: requested mode is out of range");
619+ return;
620+ };
621+
622+ new_config.mode = Some(niri_ipc::ConfiguredMode {
623+ width: mode.width,
624+ height: mode.height,
625+ refresh: Some(mode.refresh_rate as f64 / 1000.),
626+ });
627+ }
628+ zwlr_output_configuration_head_v1::Request::SetCustomMode {
629+ width,
630+ height,
631+ refresh,
632+ } => {
633+ // FIXME: Support custom mode
634+ let (width, height, refresh): (u16, u16, u32) =
635+ match (width.try_into(), height.try_into(), refresh.try_into()) {
636+ (Ok(width), Ok(height), Ok(refresh)) => (width, height, refresh),
637+ _ => {
638+ warn!("SetCustomMode: invalid input data");
639+ return;
640+ }
641+ };
642+
643+ let Some(current_config) = g_state.current_state.get(output_id) else {
644+ warn!("SetMode: output missing from the current config");
645+ return;
646+ };
647+
648+ let Some(mode) = current_config.modes.iter().find(|m| {
649+ m.width == width
650+ && m.height == height
651+ && (refresh == 0 || m.refresh_rate == refresh)
652+ }) else {
653+ warn!("SetCustomMode: no matching mode");
654+ return;
655+ };
656+
657+ new_config.mode = Some(niri_ipc::ConfiguredMode {
658+ width: mode.width,
659+ height: mode.height,
660+ refresh: Some(mode.refresh_rate as f64 / 1000.),
661+ });
662+ }
663+ zwlr_output_configuration_head_v1::Request::SetPosition { x, y } => {
664+ new_config.position = Some(niri_config::Position { x, y });
665+ }
666+ zwlr_output_configuration_head_v1::Request::SetTransform { transform } => {
667+ let transform = match transform {
668+ WEnum::Value(WlTransform::Normal) => Transform::Normal,
669+ WEnum::Value(WlTransform::_90) => Transform::_90,
670+ WEnum::Value(WlTransform::_180) => Transform::_180,
671+ WEnum::Value(WlTransform::_270) => Transform::_270,
672+ WEnum::Value(WlTransform::Flipped) => Transform::Flipped,
673+ WEnum::Value(WlTransform::Flipped90) => Transform::Flipped90,
674+ WEnum::Value(WlTransform::Flipped180) => Transform::Flipped180,
675+ WEnum::Value(WlTransform::Flipped270) => Transform::Flipped270,
676+ _ => {
677+ warn!("SetTransform: unknown requested transform");
678+ conf_head.post_error(
679+ zwlr_output_configuration_head_v1::Error::InvalidTransform,
680+ "unknown transform value",
681+ );
682+ return;
683+ }
684+ };
685+ new_config.transform = transform;
686+ }
687+ zwlr_output_configuration_head_v1::Request::SetScale { scale } => {
688+ if scale <= 0. {
689+ conf_head.post_error(
690+ zwlr_output_configuration_head_v1::Error::InvalidScale,
691+ "scale is negative or zero",
692+ );
693+ return;
694+ }
695+ new_config.scale = Some(FloatOrInt(scale));
696+ }
697+ zwlr_output_configuration_head_v1::Request::SetAdaptiveSync { state } => {
698+ let enabled = match state {
699+ WEnum::Value(AdaptiveSyncState::Enabled) => true,
700+ WEnum::Value(AdaptiveSyncState::Disabled) => false,
701+ _ => {
702+ warn!("SetAdaptativeSync: unknown requested adaptative sync");
703+ conf_head.post_error(
704+ zwlr_output_configuration_head_v1::Error::InvalidAdaptiveSyncState,
705+ "unknown adaptive sync value",
706+ );
707+ return;
708+ }
709+ };
710+ new_config.variable_refresh_rate = enabled;
711+ }
712+ _ => unreachable!(),
713+ }
714+ }
715+}
716+
717+impl<D> Dispatch<ZwlrOutputHeadV1, OutputId, D> for OutputManagementManagerState
718+where
719+ D: GlobalDispatch<ZwlrOutputManagerV1, OutputManagementManagerGlobalData>,
720+ D: Dispatch<ZwlrOutputManagerV1, ()>,
721+ D: Dispatch<ZwlrOutputHeadV1, OutputId>,
722+ D: Dispatch<ZwlrOutputConfigurationV1, u32>,
723+ D: Dispatch<ZwlrOutputConfigurationHeadV1, OutputConfigurationHeadState>,
724+ D: Dispatch<ZwlrOutputModeV1, ()>,
725+ D: OutputManagementHandler,
726+ D: 'static,
727+{
728+ fn request(
729+ _state: &mut D,
730+ _client: &Client,
731+ _output_head: &ZwlrOutputHeadV1,
732+ request: zwlr_output_head_v1::Request,
733+ _data: &OutputId,
734+ _display: &DisplayHandle,
735+ _data_init: &mut DataInit<'_, D>,
736+ ) {
737+ match request {
738+ zwlr_output_head_v1::Request::Release => {}
739+ _ => unreachable!(),
740+ }
741+ }
742+ fn destroyed(state: &mut D, client: ClientId, _resource: &ZwlrOutputHeadV1, data: &OutputId) {
743+ if let Some(c) = state.output_management_state().clients.get_mut(&client) {
744+ c.heads.remove(data);
745+ }
746+ }
747+}
748+
749+impl<D> Dispatch<ZwlrOutputModeV1, (), D> for OutputManagementManagerState
750+where
751+ D: GlobalDispatch<ZwlrOutputManagerV1, OutputManagementManagerGlobalData>,
752+ D: Dispatch<ZwlrOutputManagerV1, ()>,
753+ D: Dispatch<ZwlrOutputHeadV1, OutputId>,
754+ D: Dispatch<ZwlrOutputConfigurationV1, u32>,
755+ D: Dispatch<ZwlrOutputConfigurationHeadV1, OutputConfigurationHeadState>,
756+ D: Dispatch<ZwlrOutputModeV1, ()>,
757+ D: OutputManagementHandler,
758+ D: 'static,
759+{
760+ fn request(
761+ _state: &mut D,
762+ _client: &Client,
763+ _mode: &ZwlrOutputModeV1,
764+ request: zwlr_output_mode_v1::Request,
765+ _data: &(),
766+ _display: &DisplayHandle,
767+ _data_init: &mut DataInit<'_, D>,
768+ ) {
769+ match request {
770+ zwlr_output_mode_v1::Request::Release => {}
771+ _ => unreachable!(),
772+ }
773+ }
774+}
775+
776+#[macro_export]
777+macro_rules! delegate_output_management{
778+ ($(@<$( $lt:tt $( : $clt:tt $(+ $dlt:tt )* )? ),+>)? $ty: ty) => {
779+ smithay::reexports::wayland_server::delegate_global_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
780+ smithay::reexports::wayland_protocols_wlr::output_management::v1::server::zwlr_output_manager_v1::ZwlrOutputManagerV1: $crate::protocols::output_management::OutputManagementManagerGlobalData
781+ ] => $crate::protocols::output_management::OutputManagementManagerState);
782+ smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
783+ smithay::reexports::wayland_protocols_wlr::output_management::v1::server::zwlr_output_manager_v1::ZwlrOutputManagerV1: ()
784+ ] => $crate::protocols::output_management::OutputManagementManagerState);
785+ smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
786+ smithay::reexports::wayland_protocols_wlr::output_management::v1::server::zwlr_output_configuration_v1::ZwlrOutputConfigurationV1: u32
787+ ] => $crate::protocols::output_management::OutputManagementManagerState);
788+ smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
789+ smithay::reexports::wayland_protocols_wlr::output_management::v1::server::zwlr_output_head_v1::ZwlrOutputHeadV1: $crate::backend::OutputId
790+ ] => $crate::protocols::output_management::OutputManagementManagerState);
791+ smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
792+ smithay::reexports::wayland_protocols_wlr::output_management::v1::server::zwlr_output_mode_v1::ZwlrOutputModeV1: ()
793+ ] => $crate::protocols::output_management::OutputManagementManagerState);
794+ smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
795+ smithay::reexports::wayland_protocols_wlr::output_management::v1::server::zwlr_output_configuration_head_v1::ZwlrOutputConfigurationHeadV1: $crate::protocols::output_management::OutputConfigurationHeadState
796+ ] => $crate::protocols::output_management::OutputManagementManagerState);
797+ };
798+}
799+
800+fn notify_removed_head(clients: &mut HashMap<ClientId, ClientData>, head: &OutputId) {
801+ for data in clients.values_mut() {
802+ if let Some((head, mods)) = data.heads.remove(head) {
803+ mods.iter().for_each(|m| m.finished());
804+ head.finished();
805+ }
806+ }
807+}
808+
809+fn notify_new_head(
810+ state: &mut OutputManagementManagerState,
811+ output: &OutputId,
812+ conf: &niri_ipc::Output,
813+) {
814+ let display = &state.display;
815+ let clients = &mut state.clients;
816+ for data in clients.values_mut() {
817+ if let Some(client) = data.manager.client() {
818+ send_new_head::<State>(display, &client, data, *output, conf);
819+ }
820+ }
821+}
822+
823+fn send_new_head<D>(
824+ display: &DisplayHandle,
825+ client: &Client,
826+ client_data: &mut ClientData,
827+ output: OutputId,
828+ conf: &niri_ipc::Output,
829+) where
830+ D: GlobalDispatch<ZwlrOutputManagerV1, OutputManagementManagerGlobalData>,
831+ D: Dispatch<ZwlrOutputManagerV1, ()>,
832+ D: Dispatch<ZwlrOutputConfigurationV1, u32>,
833+ D: Dispatch<ZwlrOutputConfigurationHeadV1, OutputConfigurationHeadState>,
834+ D: Dispatch<ZwlrOutputModeV1, ()>,
835+ D: OutputManagementHandler,
836+ D: 'static,
837+ D: Dispatch<ZwlrOutputHeadV1, OutputId>,
838+ D: Dispatch<ZwlrOutputModeV1, ()>,
839+ D: 'static,
840+{
841+ let new_head = client
842+ .create_resource::<ZwlrOutputHeadV1, _, D>(display, client_data.manager.version(), output)
843+ .unwrap();
844+ client_data.manager.head(&new_head);
845+ new_head.name(conf.name.clone());
846+ new_head.description(format!("{} - {} - {}", conf.make, conf.model, conf.name));
847+ if let Some((width, height)) = conf.physical_size {
848+ if let (Ok(a), Ok(b)) = (width.try_into(), height.try_into()) {
849+ new_head.physical_size(a, b);
850+ }
851+ }
852+ let mut new_modes = Vec::with_capacity(conf.modes.len());
853+ for (index, mode) in conf.modes.iter().enumerate() {
854+ let new_mode = client
855+ .create_resource::<ZwlrOutputModeV1, _, D>(display, new_head.version(), ())
856+ .unwrap();
857+ new_head.mode(&new_mode);
858+ new_mode.size(i32::from(mode.width), i32::from(mode.height));
859+ if mode.is_preferred {
860+ new_mode.preferred();
861+ }
862+ if let Ok(refresh_rate) = mode.refresh_rate.try_into() {
863+ new_mode.refresh(refresh_rate);
864+ }
865+ if Some(index) == conf.current_mode {
866+ new_head.current_mode(&new_mode);
867+ }
868+ new_modes.push(new_mode);
869+ }
870+ if let Some(logical) = conf.logical {
871+ new_head.position(logical.x, logical.y);
872+ new_head.transform(ipc_transform_to_smithay(logical.transform).into());
873+ new_head.scale(logical.scale);
874+ }
875+ new_head.enabled(conf.current_mode.is_some() as i32);
876+ if new_head.version() >= zwlr_output_head_v1::EVT_MAKE_SINCE {
877+ new_head.make(conf.make.clone());
878+ }
879+ if new_head.version() >= zwlr_output_head_v1::EVT_MODEL_SINCE {
880+ new_head.model(conf.model.clone());
881+ }
882+
883+ if new_head.version() >= zwlr_output_head_v1::EVT_ADAPTIVE_SYNC_SINCE {
884+ new_head.adaptive_sync(match conf.vrr_enabled {
885+ true => AdaptiveSyncState::Enabled,
886+ false => AdaptiveSyncState::Disabled,
887+ });
888+ }
889+ // new_head.serial_number(output.serial);
890+ client_data.heads.insert(output, (new_head, new_modes));
891+}