BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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