forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBb0eb8adIvan Molodetskikh3 months ago2857 commits

config_error_notification.rs258 lines, 7.9 KiBHistoryRawDownload
1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::path::{Path, PathBuf};
4use std::rc::Rc;
5use std::time::Duration;
6
7use niri_config::Config;
8use ordered_float::NotNan;
9use pangocairo::cairo::{self, ImageSurface};
10use pangocairo::pango::FontDescription;
11use smithay::backend::renderer::element::Kind;
12use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
13use smithay::output::Output;
14use smithay::reexports::gbm::Format as Fourcc;
15use smithay::utils::{Point, Transform};
16
17use crate::animation::{Animation, Clock};
18use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;
19use crate::render_helpers::renderer::NiriRenderer;
20use crate::render_helpers::texture::{TextureBuffer, TextureRenderElement};
21use crate::utils::{output_size, to_physical_precise_round};
22
23const PADDING: i32 = 8;
24const FONT: &str = "sans 14px";
25const BORDER: i32 = 4;
26
27pub struct ConfigErrorNotification {
28 state: State,
29 buffers: RefCell<HashMap<NotNan<f64>, Option<TextureBuffer<GlesTexture>>>>,
30
31 // If set, this is a "Created config at {path}" notification. If unset, this is a config error
32 // notification.
33 created_path: Option<PathBuf>,
34
35 clock: Clock,
36 config: Rc<RefCell<Config>>,
37}
38
39enum State {
40 Hidden,
41 Showing(Animation),
42 Shown(Duration),
43 Hiding(Animation),
44}
45
46impl ConfigErrorNotification {
47 pub fn new(clock: Clock, config: Rc<RefCell<Config>>) -> Self {
48 Self {
49 state: State::Hidden,
50 buffers: RefCell::new(HashMap::new()),
51 created_path: None,
52 clock,
53 config,
54 }
55 }
56
57 fn animation(&self, from: f64, to: f64) -> Animation {
58 let c = self.config.borrow();
59 Animation::new(
60 self.clock.clone(),
61 from,
62 to,
63 0.,
64 c.animations.config_notification_open_close.0,
65 )
66 }
67
68 pub fn show_created(&mut self, created_path: &Path) {
69 if self.created_path.as_deref() != Some(created_path) {
70 self.created_path = Some(created_path.to_owned());
71 self.buffers.borrow_mut().clear();
72 }
73
74 self.state = State::Showing(self.animation(0., 1.));
75 }
76
77 pub fn show(&mut self) {
78 let c = self.config.borrow();
79 if c.config_notification.disable_failed {
80 return;
81 }
82
83 if self.created_path.is_some() {
84 self.created_path = None;
85 self.buffers.borrow_mut().clear();
86 }
87
88 // Show from scratch even if already showing to bring attention.
89 self.state = State::Showing(self.animation(0., 1.));
90 }
91
92 pub fn hide(&mut self) {
93 if matches!(self.state, State::Hidden) {
94 return;
95 }
96
97 self.state = State::Hiding(self.animation(1., 0.));
98 }
99
100 pub fn advance_animations(&mut self) {
101 match &mut self.state {
102 State::Hidden => (),
103 State::Showing(anim) => {
104 if anim.is_done() {
105 let duration = if self.created_path.is_some() {
106 // Make this quite a bit longer because it comes with a monitor modeset
107 // (can take a while) and an important hotkeys popup diverting the
108 // attention.
109 Duration::from_secs(8)
110 } else {
111 Duration::from_secs(4)
112 };
113 self.state = State::Shown(self.clock.now_unadjusted() + duration);
114 }
115 }
116 State::Shown(deadline) => {
117 if self.clock.now_unadjusted() >= *deadline {
118 self.hide();
119 }
120 }
121 State::Hiding(anim) => {
122 if anim.is_clamped_done() {
123 self.state = State::Hidden;
124 }
125 }
126 }
127 }
128
129 pub fn are_animations_ongoing(&self) -> bool {
130 !matches!(self.state, State::Hidden)
131 }
132
133 pub fn render<R: NiriRenderer>(
134 &self,
135 renderer: &mut R,
136 output: &Output,
137 ) -> Option<PrimaryGpuTextureRenderElement> {
138 if matches!(self.state, State::Hidden) {
139 return None;
140 }
141
142 let scale = output.current_scale().fractional_scale();
143 let output_size = output_size(output);
144 let path = self.created_path.as_deref();
145
146 let mut buffers = self.buffers.borrow_mut();
147 let buffer = buffers
148 .entry(NotNan::new(scale).unwrap())
149 .or_insert_with(move || render(renderer.as_gles_renderer(), scale, path).ok());
150 let buffer = buffer.clone()?;
151
152 let size = buffer.logical_size();
153 let y_range = size.h + f64::from(PADDING) * 2.;
154
155 let x = (output_size.w - size.w).max(0.) / 2.;
156 let y = match &self.state {
157 State::Hidden => unreachable!(),
158 State::Showing(anim) | State::Hiding(anim) => -size.h + anim.value() * y_range,
159 State::Shown(_) => f64::from(PADDING) * 2.,
160 };
161
162 let location = Point::from((x, y));
163 let location = location.to_physical_precise_round(scale).to_logical(scale);
164
165 let elem = TextureRenderElement::from_texture_buffer(
166 buffer,
167 location,
168 1.,
169 None,
170 None,
171 Kind::Unspecified,
172 );
173 Some(PrimaryGpuTextureRenderElement(elem))
174 }
175}
176
177fn render(
178 renderer: &mut GlesRenderer,
179 scale: f64,
180 created_path: Option<&Path>,
181) -> anyhow::Result<TextureBuffer<GlesTexture>> {
182 let _span = tracy_client::span!("config_error_notification::render");
183
184 let padding: i32 = to_physical_precise_round(scale, PADDING);
185
186 let mut text = error_text(true);
187 let mut border_color = (1., 0.3, 0.3);
188 if let Some(path) = created_path {
189 text = format!(
190 "Created a default config file at \
191 <span face='monospace' bgcolor='#000000'>{path:?}</span>",
192 );
193 border_color = (0.5, 1., 0.5);
194 };
195
196 let mut font = FontDescription::from_string(FONT);
197 font.set_absolute_size(to_physical_precise_round(scale, font.size()));
198
199 let surface = ImageSurface::create(cairo::Format::ARgb32, 0, 0)?;
200 let cr = cairo::Context::new(&surface)?;
201 let layout = pangocairo::functions::create_layout(&cr);
202 layout.context().set_round_glyph_positions(false);
203 layout.set_font_description(Some(&font));
204 layout.set_markup(&text);
205
206 let (mut width, mut height) = layout.pixel_size();
207 width += padding * 2;
208 height += padding * 2;
209
210 let surface = ImageSurface::create(cairo::Format::ARgb32, width, height)?;
211 let cr = cairo::Context::new(&surface)?;
212 cr.set_source_rgb(0.1, 0.1, 0.1);
213 cr.paint()?;
214
215 cr.move_to(padding.into(), padding.into());
216 let layout = pangocairo::functions::create_layout(&cr);
217 layout.context().set_round_glyph_positions(false);
218 layout.set_font_description(Some(&font));
219 layout.set_markup(&text);
220
221 cr.set_source_rgb(1., 1., 1.);
222 pangocairo::functions::show_layout(&cr, &layout);
223
224 cr.move_to(0., 0.);
225 cr.line_to(width.into(), 0.);
226 cr.line_to(width.into(), height.into());
227 cr.line_to(0., height.into());
228 cr.line_to(0., 0.);
229 cr.set_source_rgb(border_color.0, border_color.1, border_color.2);
230 // Keep the border width even to avoid blurry edges.
231 cr.set_line_width((f64::from(BORDER) / 2. * scale).round() * 2.);
232 cr.stroke()?;
233 drop(cr);
234
235 let data = surface.take_data().unwrap();
236 let buffer = TextureBuffer::from_memory(
237 renderer,
238 &data,
239 Fourcc::Argb8888,
240 (width, height),
241 false,
242 scale,
243 Transform::Normal,
244 Vec::new(),
245 )?;
246
247 Ok(buffer)
248}
249
250pub fn error_text(markup: bool) -> String {
251 let command = if markup {
252 "<span face='monospace' bgcolor='#000000'>niri validate</span>"
253 } else {
254 "niri validate"
255 };
256
257 format!("Failed to parse the config file. Please run {command} to see the errors.")
258}