BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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