forge
Explore
Log in

Don't you dare go Hollow

Add the beginnings of window rules

Browse files at this commit

befdebfa03399eeed7869fb0788d553f7aa4dcdbIvan MolodetskikhParent: 7960a73
Cargo.lockmodified+1 -0
@@ -2130,6 +2130,7 @@ dependencies = [
21302130 "knuffel",
21312131 "miette",
21322132 "niri-ipc",
2133+ "regex",
21332134 "smithay",
21342135 "tracing",
21352136 "tracy-client",
niri-config/Cargo.tomlmodified+1 -0
@@ -12,6 +12,7 @@ bitflags.workspace = true
1212 knuffel = "3.2.0"
1313 miette = "5.10.0"
1414 niri-ipc = { version = "0.1.1", path = "../niri-ipc" }
15+regex = "1.10.3"
1516 smithay = { workspace = true, features = ["backend_libinput"] }
1617 tracing.workspace = true
1718 tracy-client.workspace = true
niri-config/src/lib.rsmodified+50 -0
@@ -7,6 +7,7 @@ use std::str::FromStr;
77 use bitflags::bitflags;
88 use miette::{miette, Context, IntoDiagnostic, NarratableReportHandler};
99 use niri_ipc::{LayoutSwitchTarget, SizeChange};
10+use regex::Regex;
1011 use smithay::input::keyboard::keysyms::KEY_NoSymbol;
1112 use smithay::input::keyboard::xkb::{keysym_from_name, KEYSYM_CASE_INSENSITIVE};
1213 use smithay::input::keyboard::{Keysym, XkbConfig};
@@ -38,6 +39,8 @@ pub struct Config {
3839 pub hotkey_overlay: HotkeyOverlay,
3940 #[knuffel(child, default)]
4041 pub animations: Animations,
42+ #[knuffel(children(name = "window-rule"))]
43+ pub window_rules: Vec<WindowRule>,
4144 #[knuffel(child, default)]
4245 pub binds: Binds,
4346 #[knuffel(child, default)]
@@ -524,6 +527,34 @@ pub enum AnimationCurve {
524527 EaseOutExpo,
525528 }
526529
530+#[derive(knuffel::Decode, Debug, Default, Clone, PartialEq)]
531+pub struct WindowRule {
532+ #[knuffel(children(name = "match"))]
533+ pub matches: Vec<Match>,
534+ #[knuffel(children(name = "exclude"))]
535+ pub excludes: Vec<Match>,
536+
537+ #[knuffel(child)]
538+ pub default_column_width: Option<DefaultColumnWidth>,
539+ #[knuffel(child, unwrap(argument))]
540+ pub open_on_output: Option<String>,
541+}
542+
543+#[derive(knuffel::Decode, Debug, Default, Clone)]
544+pub struct Match {
545+ #[knuffel(property, str)]
546+ pub app_id: Option<Regex>,
547+ #[knuffel(property, str)]
548+ pub title: Option<Regex>,
549+}
550+
551+impl PartialEq for Match {
552+ fn eq(&self, other: &Self) -> bool {
553+ self.app_id.as_ref().map(Regex::as_str) == other.app_id.as_ref().map(Regex::as_str)
554+ && self.title.as_ref().map(Regex::as_str) == other.title.as_ref().map(Regex::as_str)
555+ }
556+}
557+
527558 #[derive(knuffel::Decode, Debug, Default, PartialEq)]
528559 pub struct Binds(#[knuffel(children)] pub Vec<Bind>);
529560
@@ -965,6 +996,13 @@ mod tests {
965996 }
966997 }
967998
999+ window-rule {
1000+ match app-id=".*alacritty"
1001+ exclude title="~"
1002+
1003+ open-on-output "eDP-1"
1004+ }
1005+
9681006 binds {
9691007 Mod+T { spawn "alacritty"; }
9701008 Mod+Q { close-window; }
@@ -1098,6 +1136,18 @@ mod tests {
10981136 },
10991137 ..Default::default()
11001138 },
1139+ window_rules: vec![WindowRule {
1140+ matches: vec![Match {
1141+ app_id: Some(Regex::new(".*alacritty").unwrap()),
1142+ title: None,
1143+ }],
1144+ excludes: vec![Match {
1145+ app_id: None,
1146+ title: Some(Regex::new("~").unwrap()),
1147+ }],
1148+ open_on_output: Some("eDP-1".to_owned()),
1149+ ..Default::default()
1150+ }],
11011151 binds: Binds(vec![
11021152 Bind {
11031153 key: Key {
niri-visual-tests/src/cases/layout.rsmodified+3 -2
@@ -143,7 +143,8 @@ impl Layout {
143143 }
144144
145145 fn add_window(&mut self, window: TestWindow, width: Option<ColumnWidth>) {
146- self.layout.add_window(window.clone(), width, false);
146+ self.layout
147+ .add_window(window.clone(), width.map(Some), false);
147148 if window.communicate() {
148149 self.layout.update_window(&window);
149150 }
@@ -157,7 +158,7 @@ impl Layout {
157158 width: Option<ColumnWidth>,
158159 ) {
159160 self.layout
160- .add_window_right_of(right_of, window.clone(), width, false);
161+ .add_window_right_of(right_of, window.clone(), width.map(Some), false);
161162 if window.communicate() {
162163 self.layout.update_window(&window);
163164 }
resources/default-config.kdlmodified+43 -0
@@ -248,6 +248,49 @@ animations {
248248 }
249249 }
250250
251+// Window rules let you adjust behavior for individual windows.
252+// They are processed in order of appearance in this file.
253+// (This example rule is commented out with a "/-" in front.)
254+/-window-rule {
255+ // Match directives control which windows this rule will apply to.
256+ // You can match by app-id and by title.
257+ // The window must match all properties of the match directive.
258+ match app-id="org.myapp.MyApp" title="My Cool App"
259+
260+ // There can be multiple match directives. A window must match any one
261+ // of the rule's match directives.
262+ //
263+ // If there are no match directives, any window will match the rule.
264+ match title="Second App"
265+
266+ // You can also add exclude directives which have the same properties.
267+ // If a window matches any exclude directive, it won't match this rule.
268+ //
269+ // Both app-id and title are regular expressions.
270+ // Raw KDL strings are helpful here.
271+ exclude app-id=r#"\.unwanted\."#
272+
273+ // Here are the properties that you can set on a window rule.
274+ // You can override the default column width.
275+ default-column-width { proportion 0.75; }
276+
277+ // You can set the output that this window will initially open on.
278+ // If such an output does not exist, it will open on the currently
279+ // focused output as usual.
280+ open-on-output "eDP-1"
281+}
282+
283+// Here's a useful example. Work around WezTerm's initial configure bug
284+// by setting an empty default-column-width.
285+window-rule {
286+ // This regular expression is intentially made as specific as possile,
287+ // since this is the default config, and we want no false positives.
288+ // You can get away with just app-id="wezterm" if you want.
289+ // The regular expression can match anywhere in the string.
290+ match app-id=r#"^org\.wezfurlong\.wezterm$"#
291+ default-column-width {}
292+}
293+
251294 binds {
252295 // Keys consist of modifiers separated by + signs, followed by an XKB key name
253296 // in the end. To find an XKB name for a particular key, you may use a program
src/handlers/compositor.rsmodified+29 -3
@@ -16,6 +16,7 @@ use smithay::wayland::dmabuf::get_dmabuf;
1616 use smithay::wayland::shm::{ShmHandler, ShmState};
1717 use smithay::{delegate_compositor, delegate_shm};
1818
19+use super::xdg_shell::{initial_configure_sent, resolve_window_rules};
1920 use crate::niri::{ClientState, State};
2021 use crate::utils::clone2;
2122
@@ -113,13 +114,28 @@ impl CompositorHandler for State {
113114 .and_then(|parent| self.niri.layout.find_window_and_output(&parent))
114115 .map(|(win, _)| win.clone());
115116
117+ let (width, output) = {
118+ let config = self.niri.config.borrow();
119+ let rules = resolve_window_rules(&config.window_rules, window.toplevel());
120+ let output = rules
121+ .open_on_output
122+ .and_then(|name| self.niri.output_by_name.get(name))
123+ .cloned();
124+ (rules.default_width, output)
125+ };
126+
116127 let win = window.clone();
117128
118129 // Open dialogs immediately to the right of their parent window.
119130 let output = if let Some(p) = parent {
120- self.niri.layout.add_window_right_of(&p, win, None, false)
131+ self.niri.layout.add_window_right_of(&p, win, width, false)
132+ } else if let Some(output) = &output {
133+ self.niri
134+ .layout
135+ .add_window_on_output(output, win, width, false);
136+ Some(output)
121137 } else {
122- self.niri.layout.add_window(win, None, false)
138+ self.niri.layout.add_window(win, width, false)
123139 };
124140
125141 if let Some(output) = output.cloned() {
@@ -131,7 +147,17 @@ impl CompositorHandler for State {
131147
132148 // The toplevel remains unmapped.
133149 let window = entry.get().clone();
134- self.send_initial_configure_if_needed(&window);
150+
151+ // Send the initial configure in an idle, in case the client sent some more info
152+ // after the initial commit.
153+ if !initial_configure_sent(window.toplevel()) {
154+ self.niri.event_loop.insert_idle(move |state| {
155+ if !window.toplevel().alive() {
156+ return;
157+ }
158+ state.send_initial_configure_if_needed(&window);
159+ });
160+ }
135161 return;
136162 }
137163
src/handlers/xdg_shell.rsmodified+109 -7
@@ -1,3 +1,4 @@
1+use niri_config::{Match, WindowRule};
12 use smithay::desktop::{
23 find_popup_root_surface, get_popup_toplevel_coords, layer_map_for_output, LayerSurface,
34 PopupKeyboardGrab, PopupKind, PopupManager, PopupPointerGrab, PopupUngrabStrategy, Window,
@@ -19,13 +20,91 @@ use smithay::wayland::shell::wlr_layer::Layer;
1920 use smithay::wayland::shell::xdg::decoration::XdgDecorationHandler;
2021 use smithay::wayland::shell::xdg::{
2122 PopupSurface, PositionerState, ToplevelSurface, XdgPopupSurfaceData, XdgShellHandler,
22- XdgShellState, XdgToplevelSurfaceData,
23+ XdgShellState, XdgToplevelSurfaceData, XdgToplevelSurfaceRoleAttributes,
2324 };
2425 use smithay::{delegate_kde_decoration, delegate_xdg_decoration, delegate_xdg_shell};
2526
27+use crate::layout::workspace::ColumnWidth;
2628 use crate::niri::{PopupGrabState, State};
2729 use crate::utils::clone2;
2830
31+#[derive(Debug, Default)]
32+pub struct ResolvedWindowRule<'a> {
33+ /// Default width for this window.
34+ ///
35+ /// - `None`: unset.
36+ /// - `Some(None)`: set to empty.
37+ /// - `Some(Some(width))`: set to a particular width.
38+ pub default_width: Option<Option<ColumnWidth>>,
39+
40+ /// Output to open this window on.
41+ pub open_on_output: Option<&'a str>,
42+}
43+
44+fn window_matches(role: &XdgToplevelSurfaceRoleAttributes, m: &Match) -> bool {
45+ if let Some(app_id_re) = &m.app_id {
46+ let Some(app_id) = &role.app_id else {
47+ return false;
48+ };
49+ if !app_id_re.is_match(app_id) {
50+ return false;
51+ }
52+ }
53+
54+ if let Some(title_re) = &m.title {
55+ let Some(title) = &role.title else {
56+ return false;
57+ };
58+ if !title_re.is_match(title) {
59+ return false;
60+ }
61+ }
62+
63+ true
64+}
65+
66+pub fn resolve_window_rules<'a>(
67+ rules: &'a [WindowRule],
68+ toplevel: &ToplevelSurface,
69+) -> ResolvedWindowRule<'a> {
70+ let _span = tracy_client::span!("resolve_window_rules");
71+
72+ let mut resolved = ResolvedWindowRule::default();
73+
74+ with_states(toplevel.wl_surface(), |states| {
75+ let role = states
76+ .data_map
77+ .get::<XdgToplevelSurfaceData>()
78+ .unwrap()
79+ .lock()
80+ .unwrap();
81+
82+ for rule in rules {
83+ if !(rule.matches.is_empty() || rule.matches.iter().any(|m| window_matches(&role, m))) {
84+ continue;
85+ }
86+
87+ if rule.excludes.iter().any(|m| window_matches(&role, m)) {
88+ continue;
89+ }
90+
91+ if let Some(x) = rule
92+ .default_column_width
93+ .as_ref()
94+ .map(|d| d.0.first().copied().map(ColumnWidth::from))
95+ {
96+ resolved.default_width = Some(x);
97+ }
98+
99+ if let Some(x) = rule.open_on_output.as_deref() {
100+ resolved.open_on_output = Some(x);
101+ }
102+ }
103+ });
104+
105+ resolved
106+}
107+
29108 impl XdgShellHandler for State {
30109 fn xdg_shell_state(&mut self) -> &mut XdgShellState {
31110 &mut self.niri.xdg_shell_state
@@ -237,9 +316,20 @@ impl XdgShellHandler for State {
237316 let window = window.clone();
238317 self.niri.layout.set_fullscreen(&window, false);
239318 } else if let Some(window) = self.niri.unmapped_windows.get(surface.wl_surface()) {
240- if let Some(ws) = self.niri.layout.active_workspace() {
319+ let config = self.niri.config.borrow();
320+ let rules = resolve_window_rules(&config.window_rules, window.toplevel());
321+
322+ let output = rules
323+ .open_on_output
324+ .and_then(|name| self.niri.output_by_name.get(name));
325+ let mon = output.map(|o| self.niri.layout.monitor_for_output(o).unwrap());
326+ let ws = mon
327+ .map(|mon| mon.active_workspace_ref())
328+ .or_else(|| self.niri.layout.active_workspace());
329+
330+ if let Some(ws) = ws {
241331 window.toplevel().with_pending_state(|state| {
242- state.size = Some(ws.new_window_size());
332+ state.size = Some(ws.new_window_size(rules.default_width));
243333 state.states.unset(xdg_toplevel::State::Fullscreen);
244334 });
245335 }
@@ -333,7 +423,7 @@ impl KdeDecorationHandler for State {
333423
334424 delegate_kde_decoration!(State);
335425
336-fn initial_configure_sent(toplevel: &ToplevelSurface) -> bool {
426+pub fn initial_configure_sent(toplevel: &ToplevelSurface) -> bool {
337427 with_states(toplevel.wl_surface(), |states| {
338428 states
339429 .data_map
@@ -352,14 +442,26 @@ impl State {
352442 return;
353443 }
354444
445+ let _span = tracy_client::span!("State::send_initial_configure_if_needed");
446+
447+ let config = self.niri.config.borrow();
448+ let rules = resolve_window_rules(&config.window_rules, toplevel);
449+
450+ let output = rules
451+ .open_on_output
452+ .and_then(|name| self.niri.output_by_name.get(name));
453+ let mon = output.map(|o| self.niri.layout.monitor_for_output(o).unwrap());
454+ let ws = mon
455+ .map(|mon| mon.active_workspace_ref())
456+ .or_else(|| self.niri.layout.active_workspace());
457+
355458 // Tell the surface the preferred size and bounds for its likely output.
356- if let Some(ws) = self.niri.layout.active_workspace() {
357- ws.configure_new_window(window);
459+ if let Some(ws) = ws {
460+ ws.configure_new_window(window, rules.default_width);
358461 }
359462
360463 // If the user prefers no CSD, it's a reasonable assumption that they would prefer to get
361464 // rid of the various client-side rounded corners also by using the tiled state.
362- let config = self.niri.config.borrow();
363465 if config.prefer_no_csd {
364466 toplevel.with_pending_state(|state| {
365467 state.states.set(xdg_toplevel::State::TiledLeft);
src/layout/mod.rsmodified+63 -8
@@ -531,12 +531,15 @@ impl<W: LayoutElement> Layout<W> {
531531 pub fn add_window(
532532 &mut self,
533533 window: W,
534- width: Option<ColumnWidth>,
534+ width: Option<Option<ColumnWidth>>,
535535 is_full_width: bool,
536536 ) -> Option<&Output> {
537- let width = width
538- .or(self.options.default_width)
539- .unwrap_or_else(|| ColumnWidth::Fixed(window.size().w));
537+ let width = match width {
538+ Some(Some(width)) => Some(width),
539+ Some(None) => None,
540+ None => self.options.default_width,
541+ }
542+ .unwrap_or_else(|| ColumnWidth::Fixed(window.size().w));
540543
541544 match &mut self.monitor_set {
542545 MonitorSet::Normal {
@@ -584,12 +587,15 @@ impl<W: LayoutElement> Layout<W> {
584587 &mut self,
585588 right_of: &W,
586589 window: W,
587- width: Option<ColumnWidth>,
590+ width: Option<Option<ColumnWidth>>,
588591 is_full_width: bool,
589592 ) -> Option<&Output> {
590- let width = width
591- .or(self.options.default_width)
592- .unwrap_or_else(|| ColumnWidth::Fixed(window.size().w));
593+ let width = match width {
594+ Some(Some(width)) => Some(width),
595+ Some(None) => None,
596+ None => self.options.default_width,
597+ }
598+ .unwrap_or_else(|| ColumnWidth::Fixed(window.size().w));
593599
594600 match &mut self.monitor_set {
595601 MonitorSet::Normal { monitors, .. } => {
@@ -612,6 +618,55 @@ impl<W: LayoutElement> Layout<W> {
612618 }
613619 }
614620
621+ /// Adds a new window to the layout on a specific output.
622+ pub fn add_window_on_output(
623+ &mut self,
624+ output: &Output,
625+ window: W,
626+ width: Option<Option<ColumnWidth>>,
627+ is_full_width: bool,
628+ ) {
629+ let width = match width {
630+ Some(Some(width)) => Some(width),
631+ Some(None) => None,
632+ None => self.options.default_width,
633+ }
634+ .unwrap_or_else(|| ColumnWidth::Fixed(window.size().w));
635+
636+ let MonitorSet::Normal {
637+ monitors,
638+ active_monitor_idx,
639+ ..
640+ } = &mut self.monitor_set
641+ else {
642+ panic!()
643+ };
644+
645+ let (mon_idx, mon) = monitors
646+ .iter_mut()
647+ .enumerate()
648+ .find(|(_, mon)| mon.output == *output)
649+ .unwrap();
650+
651+ // Don't steal focus from an active fullscreen window.
652+ let mut activate = true;
653+ let ws = &mon.workspaces[mon.active_workspace_idx];
654+ if mon_idx == *active_monitor_idx
655+ && !ws.columns.is_empty()
656+ && ws.columns[ws.active_column_idx].is_fullscreen
657+ {
658+ activate = false;
659+ }
660+
661+ mon.add_window(
662+ mon.active_workspace_idx,
663+ window,
664+ activate,
665+ width,
666+ is_full_width,
667+ );
668+ }
669+
615670 pub fn remove_window(&mut self, window: &W) {
616671 match &mut self.monitor_set {
617672 MonitorSet::Normal { monitors, .. } => {
src/layout/monitor.rsmodified+4 -0
@@ -76,6 +76,10 @@ impl<W: LayoutElement> Monitor<W> {
7676 }
7777 }
7878
79+ pub fn active_workspace_ref(&self) -> &Workspace<W> {
80+ &self.workspaces[self.active_workspace_idx]
81+ }
82+
7983 pub fn active_workspace(&mut self) -> &mut Workspace<W> {
8084 &mut self.workspaces[self.active_workspace_idx]
8185 }
src/layout/workspace.rsmodified+17 -4
@@ -321,8 +321,17 @@ impl<W: LayoutElement> Workspace<W> {
321321 ))
322322 }
323323
324- pub fn new_window_size(&self) -> Size<i32, Logical> {
325- let width = if let Some(width) = self.options.default_width {
324+ pub fn new_window_size(
325+ &self,
326+ default_width: Option<Option<ColumnWidth>>,
327+ ) -> Size<i32, Logical> {
328+ let default_width = match default_width {
329+ Some(Some(width)) => Some(width),
330+ Some(None) => None,
331+ None => self.options.default_width,
332+ };
333+
334+ let width = if let Some(width) = default_width {
326335 let mut width = width.resolve(&self.options, self.working_area.size.w);
327336 if !self.options.border.off {
328337 width -= self.options.border.width as i32 * 2;
@@ -340,8 +349,12 @@ impl<W: LayoutElement> Workspace<W> {
340349 Size::from((width, max(height, 1)))
341350 }
342351
343- pub fn configure_new_window(&self, window: &Window) {
344- let size = self.new_window_size();
352+ pub fn configure_new_window(
353+ &self,
354+ window: &Window,
355+ default_width: Option<Option<ColumnWidth>>,
356+ ) {
357+ let size = self.new_window_size(default_width);
345358 let bounds = self.toplevel_bounds();
346359
347360 if let Some(output) = self.output.as_ref() {