BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 20.1 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 std::time::Instant;
124
125 use calling::{CallState, CallUpdate, RosterEntry, call_channel};
126 use gpui_kit::Entity;
127
128 use crate::app_state::{AppState, Mode, Selection};
129 use crate::call::{ActiveCall, CallModel};
130 use crate::demo;
131 use crate::user_activity::UserInput;
132 use crate::views::recap_tab::RECAP_REGION;
133 use crate::views::shell::{AppShell, Startup, bind_keys, install_globals};
134 use crate::views::shortcuts::{OpenActivity, OpenCallsTab, OpenChannelsTab, OpenSaved};
135
136 const GUARDED: &[&str] = &[
137 "shell",
138 "shell/title-bar",
139 "shell/title-bar/search",
140 "shell/title-bar/own-status",
141 "shell/title-bar/own-status/avatar",
142 "shell/islands",
143 "shell/islands/rail",
144 "shell/islands/sidebar",
145 "shell/islands/main",
146 "shell/status-bar",
147 ];
148 const CALL_GUARDED: &[&str] = &[
149 "shell/islands/main/call-header",
150 "shell/islands/main/call-stage",
151 "shell/islands/main/call-controls",
152 ];
153 const SHARE_GUARDED: &[&str] = &[
154 "shell/islands/main/call-stage/share-content",
155 "shell/islands/main/call-stage/share-content/zoom-chip",
156 "shell/islands/main/call-stage/share-divider",
157 "shell/islands/main/call-stage/share-strip",
158 ];
159 const MENU: &str = "popup-menu";
160 const OWN_STATUS: &str = "shell/title-bar/own-status";
161 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
162 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
163 const SIZES: [(f32, f32); 2] = [(640., 480.), (1920., 1080.)];
164 const TOLERANCE: f32 = 0.5;
165 const KNOWN_VIOLATIONS: &[&str] = &[];
166
167 type Tag = (&'static str, Bounds<Pixels>);
168
169 enum Screen {
170 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
171 StatusMenu,
172 Call,
173 CallShare,
174 }
175
176 fn parent_of(path: &str) -> Option<&str> {
177 path.rsplit_once('/').map(|(parent, _)| parent)
178 }
179
180 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
181 let tolerance = px(TOLERANCE);
182 inner.left() >= outer.left() - tolerance
183 && inner.top() >= outer.top() - tolerance
184 && inner.right() <= outer.right() + tolerance
185 && inner.bottom() <= outer.bottom() + tolerance
186 }
187
188 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
189 let tolerance = px(TOLERANCE);
190 first.left() < second.right() - tolerance
191 && second.left() < first.right() - tolerance
192 && first.top() < second.bottom() - tolerance
193 && second.top() < first.bottom() - tolerance
194 }
195
196 fn describe(bounds: Bounds<Pixels>) -> String {
197 format!(
198 "[{:.1},{:.1} {:.1}x{:.1}]",
199 f32::from(bounds.origin.x),
200 f32::from(bounds.origin.y),
201 f32::from(bounds.size.width),
202 f32::from(bounds.size.height)
203 )
204 }
205
206 fn violations(
207 tags: &[Tag],
208 window: Bounds<Pixels>,
209 expected: &[&str],
210 ) -> Vec<(String, String)> {
211 let mut found = Vec::new();
212 let bounds_of = |path: &str| {
213 tags.iter()
214 .find(|(tag, _)| *tag == path)
215 .map(|(_, bounds)| *bounds)
216 };
217 for path in expected {
218 if bounds_of(path).is_none() {
219 found.push((
220 format!("{path}:missing"),
221 format!("{path} was not rendered"),
222 ));
223 }
224 }
225 for (path, bounds) in tags {
226 if !contains(window, *bounds) {
227 found.push((
228 format!("{path}:outside-window"),
229 format!(
230 "{path} {} leaves the window {}",
231 describe(*bounds),
232 describe(window)
233 ),
234 ));
235 }
236 if let Some(parent) =
237 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
238 {
239 if !contains(parent.1, *bounds) {
240 found.push((
241 format!("{path}:outside-parent"),
242 format!(
243 "{path} {} leaves {} {}",
244 describe(*bounds),
245 parent.0,
246 describe(parent.1)
247 ),
248 ));
249 }
250 }
251 for (other, other_bounds) in tags {
252 let siblings = path < other
253 && parent_of(path).is_some()
254 && parent_of(path) == parent_of(other);
255 if siblings && overlaps(*bounds, *other_bounds) {
256 found.push((
257 format!("{path}:overlaps:{other}"),
258 format!(
259 "{path} {} overlaps {other} {}",
260 describe(*bounds),
261 describe(*other_bounds)
262 ),
263 ));
264 }
265 }
266 }
267 found
268 }
269
270 const SETTLE_FRAMES: usize = 2;
271 const SETTLE_LIMIT: usize = 60;
272 const SETTLE_STEP: Duration = Duration::from_millis(50);
273
274 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
275 let mut frames = 0;
276 while frames < SETTLE_FRAMES
277 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
278 {
279 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
280 visual.executor().advance_clock(SETTLE_STEP);
281 std::thread::sleep(SETTLE_STEP);
282 visual.run_until_parked();
283 visual.update(|window, cx| window.render_frame(cx));
284 frames += 1;
285 }
286 GUARDED
287 .iter()
288 .chain(CALL_GUARDED)
289 .chain(SHARE_GUARDED)
290 .chain([&MENU, &RECAP_TAB, &RECAP_REGION])
291 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
292 .collect()
293 }
294
295 fn sharing_call() -> ActiveCall {
296 let mut call = gallery_call();
297 call.model.apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
298 call.share_stage.view.step_in((800., 450.));
299 call
300 }
301
302 fn gallery_call() -> ActiveCall {
303 let (handle, _control) = call_channel();
304 let mut model = CallModel::meeting("Standup", false);
305 model.apply(CallUpdate::State(CallState::Connected {
306 since: Instant::now(),
307 }));
308 model.apply(CallUpdate::Roster(
309 (0..11)
310 .map(|index| RosterEntry {
311 mri: format!("8:orgid:guard-{index}"),
312 display_name: format!("Guest {index}"),
313 muted: false,
314 in_lobby: false,
315 has_video: false,
316 sharing: false,
317 hand: None,
318 spotlight: None,
319 organizer: false,
320 })
321 .collect(),
322 ));
323 ActiveCall::new(1, model, handle.commands, None, handle.video)
324 }
325
326 fn mount(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
327 cx.update(gpui_kit::init);
328 cx.update(|cx| {
329 crate::theme::apply(cx);
330 bind_keys(cx);
331 let store = Store::open_in_memory().expect("in-memory store");
332 demo::seed(&store);
333 let mode = Mode {
334 demo: true,
335 read_only: false,
336 demo_sync: None,
337 };
338 let state = cx.new(|_| AppState::new(Arc::new(store), mode));
339 install_globals(&state, UserInput::new(), cx);
340 demo::start_session(&state, cx);
341 let shared_state = state.clone();
342 let startup = Startup {
343 switcher_query: None,
344 composer_text: None,
345 reply_to_last: false,
346 };
347 let window = gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
348 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
349 })
350 .expect("open test window")
351 .0;
352 (window, shared_state)
353 })
354 }
355
356 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
357 Bounds {
358 origin: point(px(left), px(top)),
359 size: size(px(width), px(height)),
360 }
361 }
362
363 #[test]
364 fn rules_flag_overlap_and_overflow() {
365 let window = rectangle(0., 0., 100., 100.);
366 let tags: Vec<Tag> = vec![
367 ("shell", rectangle(0., 0., 100., 100.)),
368 ("shell/islands", rectangle(0., 0., 100., 50.)),
369 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
370 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
371 ];
372 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
373 .into_iter()
374 .map(|(key, _)| key)
375 .collect();
376 assert_eq!(
377 keys,
378 [
379 "shell/status-bar:missing",
380 "shell/islands/rail:overlaps:shell/islands/sidebar",
381 "shell/islands/sidebar:outside-window",
382 "shell/islands/sidebar:outside-parent",
383 ]
384 );
385 }
386
387 #[gpui_kit::test]
388 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
389 let (handle, app) = mount(cx);
390 let mut visual = VisualTestContext::from_window(handle, cx);
391 let mut seen_known = HashSet::new();
392 let mut unexpected = Vec::new();
393 for (width, height) in SIZES {
394 visual.simulate_resize(size(px(width), px(height)));
395 let window = Bounds {
396 origin: point(px(0.), px(0.)),
397 size: size(px(width), px(height)),
398 };
399 let screens = [
400 Screen::Tab("chats", None),
401 Screen::Tab(
402 "activity",
403 Some(|visual| visual.dispatch_action(OpenActivity)),
404 ),
405 Screen::Tab(
406 "channels",
407 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
408 ),
409 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
410 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
411 Screen::StatusMenu,
412 Screen::Call,
413 Screen::CallShare,
414 ];
415 for screen in screens {
416 let (screen_name, status_menu) = match screen {
417 Screen::Tab(name, open) => {
418 if let Some(open) = open {
419 open(&mut visual);
420 }
421 (name, false)
422 }
423 Screen::Call => {
424 visual.update(|_, cx| {
425 app.update(cx, |state, cx| {
426 state.call = Some(gallery_call());
427 cx.notify();
428 })
429 });
430 ("call", false)
431 }
432 Screen::CallShare => {
433 visual.update(|_, cx| {
434 app.update(cx, |state, cx| {
435 state.call = Some(sharing_call());
436 cx.notify();
437 })
438 });
439 ("call-share", false)
440 }
441 Screen::StatusMenu => {
442 let tags = collect(&mut visual, None);
443 let button = tags
444 .iter()
445 .find(|(path, _)| *path == OWN_STATUS)
446 .map(|(_, bounds)| *bounds)
447 .expect("own status button rendered");
448 visual.simulate_click(button.center(), Default::default());
449 ("status-menu", true)
450 }
451 };
452 let tags = collect(&mut visual, status_menu.then_some(MENU));
453 let mut expected = GUARDED.to_vec();
454 if matches!(screen_name, "call" | "call-share") {
455 expected.extend(CALL_GUARDED);
456 }
457 if screen_name == "call-share" {
458 expected.extend(SHARE_GUARDED);
459 }
460 if status_menu {
461 expected.push(MENU);
462 }
463 let mut found = violations(&tags, window, &expected);
464 if status_menu {
465 let menu = tags
466 .iter()
467 .find(|(path, _)| *path == MENU)
468 .map(|(_, bounds)| *bounds);
469 let button = tags
470 .iter()
471 .find(|(path, _)| *path == OWN_STATUS)
472 .map(|(_, bounds)| *bounds);
473 if let (Some(menu), Some(button)) = (menu, button) {
474 if overlaps(menu, button) {
475 found.push((
476 format!("{MENU}:covers:{OWN_STATUS}"),
477 format!(
478 "{MENU} {} covers {OWN_STATUS} {}",
479 describe(menu),
480 describe(button)
481 ),
482 ));
483 }
484 }
485 visual.simulate_keystrokes("escape");
486 visual.run_until_parked();
487 }
488 if matches!(screen_name, "call" | "call-share") {
489 visual.update(|_, cx| {
490 app.update(cx, |state, cx| {
491 state.call = None;
492 cx.notify();
493 })
494 });
495 }
496 for (key, message) in found {
497 let full_key = format!("{screen_name}@{width}x{height}:{key}");
498 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
499 seen_known.insert(full_key);
500 } else {
501 unexpected.push(format!("{full_key}: {message}"));
502 }
503 }
504 }
505 }
506 let stale: Vec<String> = KNOWN_VIOLATIONS
507 .iter()
508 .filter(|key| !seen_known.contains(**key))
509 .map(|key| format!("stale known violation, remove it: {key}"))
510 .collect();
511 assert!(
512 unexpected.is_empty() && stale.is_empty(),
513 "{}",
514 unexpected
515 .into_iter()
516 .chain(stale)
517 .collect::<Vec<_>>()
518 .join("\n")
519 );
520 }
521 #[gpui_kit::test]
522 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
523 let (handle, state) = mount(cx);
524 let mut visual = VisualTestContext::from_window(handle, cx);
525 for (width, height) in SIZES {
526 visual.simulate_resize(size(px(width), px(height)));
527 let window = Bounds {
528 origin: point(px(0.), px(0.)),
529 size: size(px(width), px(height)),
530 };
531 visual.update(|_, cx| {
532 state.update(cx, |state, cx| {
533 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
534 })
535 });
536 collect(&mut visual, Some(RECAP_TAB));
537 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
538 visual.simulate_click(tab.center(), Default::default());
539 let tags = collect(&mut visual, Some(RECAP_REGION));
540 let mut expected = GUARDED.to_vec();
541 expected.extend([RECAP_TAB, RECAP_REGION]);
542 let found: Vec<String> = violations(&tags, window, &expected)
543 .into_iter()
544 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
545 .collect();
546 assert!(found.is_empty(), "{}", found.join("\n"));
547 }
548 }
549}