BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / layout_guard.rs

layout_guard.rs

layout_guard.rs 15.3 KiB Download Raw
1use std::collections::HashSet;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use regex::Regex;
6
7const WIDGETS_FILE: &str = "views/widgets.rs";
8const SCAN_ALLOWLIST: &[(&str, &str)] = &[
9 ("views/toolbar_placement.rs", ".top(px(-SLOT_HEIGHT))"),
10 ("views/conversation.rs", ".bottom(px(-1.))"),
11];
12
13fn source_files(directory: &Path, files: &mut Vec<PathBuf>) {
14 for entry in fs::read_dir(directory).expect("read source directory") {
15 let path = entry.expect("directory entry").path();
16 if path.is_dir() {
17 source_files(&path, files);
18 } else if path.extension().is_some_and(|extension| extension == "rs") {
19 files.push(path);
20 }
21 }
22}
23
24fn negative_offsets(
25 pattern: &Regex,
26 source: &str,
27 relative: &str,
28) -> Vec<(usize, Option<usize>, String)> {
29 pattern
30 .find_iter(source)
31 .map(|found| {
32 let line_number = source[..found.start()].matches('\n').count() + 1;
33 let from_match = &source[found.start()..];
34 let allowed = SCAN_ALLOWLIST.iter().position(|(allowed_file, snippet)| {
35 *allowed_file == relative && from_match.starts_with(snippet)
36 });
37 let line_end = from_match.find('\n').unwrap_or(from_match.len());
38 (
39 line_number,
40 allowed,
41 from_match[..line_end].trim().to_owned(),
42 )
43 })
44 .collect()
45}
46
47fn offset_pattern() -> Regex {
48 Regex::new(r"\.(top|right|bottom|left|inset)\(\s*(px\(\s*)?-").expect("pattern")
49}
50
51#[test]
52fn matcher_catches_wrapped_offsets() {
53 let source = "let a = 1;\nlet b = div()\n .top(\n px(-4.))\n .left(px(2.));\n";
54 let found = negative_offsets(&offset_pattern(), source, "views/other.rs");
55 assert_eq!(found, [(3, None, ".top(".to_owned())]);
56}
57
58#[test]
59fn matcher_matches_allowlist_from_match_start() {
60 let source = "x\n .bottom(px(-1.))\n";
61 let found = negative_offsets(&offset_pattern(), source, "views/conversation.rs");
62 assert_eq!(found, [(2, Some(1), ".bottom(px(-1.))".to_owned())]);
63}
64
65#[test]
66fn negative_offsets_go_through_corner_badge() {
67 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
68 let pattern = offset_pattern();
69 let mut files = Vec::new();
70 source_files(&root, &mut files);
71 let mut matched_allowlist = HashSet::new();
72 let mut violations = Vec::new();
73 for file in files {
74 let relative = file
75 .strip_prefix(&root)
76 .expect("inside src")
77 .to_string_lossy()
78 .replace('\\', "/");
79 if relative == WIDGETS_FILE || relative == "layout_guard.rs" {
80 continue;
81 }
82 let source = fs::read_to_string(&file).expect("read source file");
83 for (line_number, position, text) in negative_offsets(&pattern, &source, &relative) {
84 match position {
85 Some(position) => {
86 matched_allowlist.insert(position);
87 }
88 None => violations.push(format!(
89 "{relative}:{line_number}: negative absolute offset, use widgets::corner_badge: {text}"
90 )),
91 }
92 }
93 }
94 let stale: Vec<String> = SCAN_ALLOWLIST
95 .iter()
96 .enumerate()
97 .filter(|(position, _)| !matched_allowlist.contains(position))
98 .map(|(_, (file, snippet))| format!("stale allowlist entry, remove it: {file} {snippet}"))
99 .collect();
100 assert!(
101 violations.is_empty() && stale.is_empty(),
102 "{}",
103 violations
104 .into_iter()
105 .chain(stale)
106 .collect::<Vec<_>>()
107 .join("\n")
108 );
109}
110
111mod frames {
112 use std::collections::HashSet;
113 use std::sync::Arc;
114 use std::time::Duration;
115
116 use gpui_kit::test::TestWindowExt as _;
117 use gpui_kit::{
118 AppContext as _, Bounds, Pixels, TestAppContext, VisualTestContext, WindowOptions, point,
119 px, size,
120 };
121 use store::Store;
122
123 use crate::app_state::{AppState, Mode};
124 use crate::demo;
125 use crate::user_activity::UserInput;
126 use crate::views::shell::{AppShell, Startup, bind_keys, install_globals};
127 use crate::views::shortcuts::{OpenActivity, OpenCallsTab, OpenChannelsTab, OpenSaved};
128
129 const GUARDED: &[&str] = &[
130 "shell",
131 "shell/title-bar",
132 "shell/title-bar/search",
133 "shell/title-bar/own-status",
134 "shell/title-bar/own-status/avatar",
135 "shell/islands",
136 "shell/islands/rail",
137 "shell/islands/sidebar",
138 "shell/islands/main",
139 "shell/status-bar",
140 ];
141 const MENU: &str = "popup-menu";
142 const OWN_STATUS: &str = "shell/title-bar/own-status";
143 const SIZES: [(f32, f32); 2] = [(640., 480.), (1920., 1080.)];
144 const TOLERANCE: f32 = 0.5;
145 const KNOWN_VIOLATIONS: &[&str] = &[];
146
147 type Tag = (&'static str, Bounds<Pixels>);
148
149 enum Screen {
150 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
151 StatusMenu,
152 }
153
154 fn parent_of(path: &str) -> Option<&str> {
155 path.rsplit_once('/').map(|(parent, _)| parent)
156 }
157
158 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
159 let tolerance = px(TOLERANCE);
160 inner.left() >= outer.left() - tolerance
161 && inner.top() >= outer.top() - tolerance
162 && inner.right() <= outer.right() + tolerance
163 && inner.bottom() <= outer.bottom() + tolerance
164 }
165
166 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
167 let tolerance = px(TOLERANCE);
168 first.left() < second.right() - tolerance
169 && second.left() < first.right() - tolerance
170 && first.top() < second.bottom() - tolerance
171 && second.top() < first.bottom() - tolerance
172 }
173
174 fn describe(bounds: Bounds<Pixels>) -> String {
175 format!(
176 "[{:.1},{:.1} {:.1}x{:.1}]",
177 f32::from(bounds.origin.x),
178 f32::from(bounds.origin.y),
179 f32::from(bounds.size.width),
180 f32::from(bounds.size.height)
181 )
182 }
183
184 fn violations(
185 tags: &[Tag],
186 window: Bounds<Pixels>,
187 expected: &[&str],
188 ) -> Vec<(String, String)> {
189 let mut found = Vec::new();
190 let bounds_of = |path: &str| {
191 tags.iter()
192 .find(|(tag, _)| *tag == path)
193 .map(|(_, bounds)| *bounds)
194 };
195 for path in expected {
196 if bounds_of(path).is_none() {
197 found.push((
198 format!("{path}:missing"),
199 format!("{path} was not rendered"),
200 ));
201 }
202 }
203 for (path, bounds) in tags {
204 if !contains(window, *bounds) {
205 found.push((
206 format!("{path}:outside-window"),
207 format!(
208 "{path} {} leaves the window {}",
209 describe(*bounds),
210 describe(window)
211 ),
212 ));
213 }
214 if let Some(parent) =
215 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
216 {
217 if !contains(parent.1, *bounds) {
218 found.push((
219 format!("{path}:outside-parent"),
220 format!(
221 "{path} {} leaves {} {}",
222 describe(*bounds),
223 parent.0,
224 describe(parent.1)
225 ),
226 ));
227 }
228 }
229 for (other, other_bounds) in tags {
230 let siblings = path < other
231 && parent_of(path).is_some()
232 && parent_of(path) == parent_of(other);
233 if siblings && overlaps(*bounds, *other_bounds) {
234 found.push((
235 format!("{path}:overlaps:{other}"),
236 format!(
237 "{path} {} overlaps {other} {}",
238 describe(*bounds),
239 describe(*other_bounds)
240 ),
241 ));
242 }
243 }
244 }
245 found
246 }
247
248 const SETTLE_FRAMES: usize = 2;
249 const SETTLE_LIMIT: usize = 60;
250 const SETTLE_STEP: Duration = Duration::from_millis(50);
251
252 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
253 let mut frames = 0;
254 while frames < SETTLE_FRAMES
255 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
256 {
257 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
258 visual.executor().advance_clock(SETTLE_STEP);
259 std::thread::sleep(SETTLE_STEP);
260 visual.run_until_parked();
261 visual.update(|window, cx| window.render_frame(cx));
262 frames += 1;
263 }
264 GUARDED
265 .iter()
266 .chain([&MENU])
267 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
268 .collect()
269 }
270
271 fn mount(cx: &mut TestAppContext) -> gpui_kit::AnyWindowHandle {
272 cx.update(gpui_kit::init);
273 cx.update(|cx| {
274 crate::theme::apply(cx);
275 bind_keys(cx);
276 let store = Store::open_in_memory().expect("in-memory store");
277 demo::seed(&store);
278 let mode = Mode {
279 demo: true,
280 read_only: false,
281 demo_sync: None,
282 };
283 let state = cx.new(|_| AppState::new(Arc::new(store), mode));
284 install_globals(&state, UserInput::new(), cx);
285 demo::start_session(&state, cx);
286 let startup = Startup {
287 switcher_query: None,
288 composer_text: None,
289 reply_to_last: false,
290 };
291 gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
292 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
293 })
294 .expect("open test window")
295 .0
296 })
297 }
298
299 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
300 Bounds {
301 origin: point(px(left), px(top)),
302 size: size(px(width), px(height)),
303 }
304 }
305
306 #[test]
307 fn rules_flag_overlap_and_overflow() {
308 let window = rectangle(0., 0., 100., 100.);
309 let tags: Vec<Tag> = vec![
310 ("shell", rectangle(0., 0., 100., 100.)),
311 ("shell/islands", rectangle(0., 0., 100., 50.)),
312 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
313 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
314 ];
315 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
316 .into_iter()
317 .map(|(key, _)| key)
318 .collect();
319 assert_eq!(
320 keys,
321 [
322 "shell/status-bar:missing",
323 "shell/islands/rail:overlaps:shell/islands/sidebar",
324 "shell/islands/sidebar:outside-window",
325 "shell/islands/sidebar:outside-parent",
326 ]
327 );
328 }
329
330 #[gpui_kit::test]
331 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
332 let handle = mount(cx);
333 let mut visual = VisualTestContext::from_window(handle, cx);
334 let mut seen_known = HashSet::new();
335 let mut unexpected = Vec::new();
336 for (width, height) in SIZES {
337 visual.simulate_resize(size(px(width), px(height)));
338 let window = Bounds {
339 origin: point(px(0.), px(0.)),
340 size: size(px(width), px(height)),
341 };
342 let screens = [
343 Screen::Tab("chats", None),
344 Screen::Tab(
345 "activity",
346 Some(|visual| visual.dispatch_action(OpenActivity)),
347 ),
348 Screen::Tab(
349 "channels",
350 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
351 ),
352 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
353 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
354 Screen::StatusMenu,
355 ];
356 for screen in screens {
357 let (screen_name, status_menu) = match screen {
358 Screen::Tab(name, open) => {
359 if let Some(open) = open {
360 open(&mut visual);
361 }
362 (name, false)
363 }
364 Screen::StatusMenu => {
365 let tags = collect(&mut visual, None);
366 let button = tags
367 .iter()
368 .find(|(path, _)| *path == OWN_STATUS)
369 .map(|(_, bounds)| *bounds)
370 .expect("own status button rendered");
371 visual.simulate_click(button.center(), Default::default());
372 ("status-menu", true)
373 }
374 };
375 let tags = collect(&mut visual, status_menu.then_some(MENU));
376 let mut expected = GUARDED.to_vec();
377 if status_menu {
378 expected.push(MENU);
379 }
380 let mut found = violations(&tags, window, &expected);
381 if status_menu {
382 let menu = tags
383 .iter()
384 .find(|(path, _)| *path == MENU)
385 .map(|(_, bounds)| *bounds);
386 let button = tags
387 .iter()
388 .find(|(path, _)| *path == OWN_STATUS)
389 .map(|(_, bounds)| *bounds);
390 if let (Some(menu), Some(button)) = (menu, button) {
391 if overlaps(menu, button) {
392 found.push((
393 format!("{MENU}:covers:{OWN_STATUS}"),
394 format!(
395 "{MENU} {} covers {OWN_STATUS} {}",
396 describe(menu),
397 describe(button)
398 ),
399 ));
400 }
401 }
402 visual.simulate_keystrokes("escape");
403 visual.run_until_parked();
404 }
405 for (key, message) in found {
406 let full_key = format!("{screen_name}@{width}x{height}:{key}");
407 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
408 seen_known.insert(full_key);
409 } else {
410 unexpected.push(format!("{full_key}: {message}"));
411 }
412 }
413 }
414 }
415 let stale: Vec<String> = KNOWN_VIOLATIONS
416 .iter()
417 .filter(|key| !seen_known.contains(**key))
418 .map(|key| format!("stale known violation, remove it: {key}"))
419 .collect();
420 assert!(
421 unexpected.is_empty() && stale.is_empty(),
422 "{}",
423 unexpected
424 .into_iter()
425 .chain(stale)
426 .collect::<Vec<_>>()
427 .join("\n")
428 );
429 }
430}