BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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