BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 43.7 KiB Download Raw
1use std::collections::HashSet;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use regex::Regex;
6
7const WIDGETS_FILE: &str = "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_roots() -> Vec<PathBuf> {
14 let crates_directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
15 let mut roots: Vec<PathBuf> = fs::read_dir(&crates_directory)
16 .expect("read crates directory")
17 .map(|entry| entry.expect("directory entry").path())
18 .filter(|path| {
19 path.file_name()
20 .is_some_and(|name| name.to_string_lossy().starts_with("app"))
21 })
22 .map(|path| path.join("src"))
23 .filter(|path| path.is_dir())
24 .collect();
25 roots.sort();
26 roots
27}
28
29fn source_files(directory: &Path, files: &mut Vec<PathBuf>) {
30 for entry in fs::read_dir(directory).expect("read source directory") {
31 let path = entry.expect("directory entry").path();
32 if path.is_dir() {
33 source_files(&path, files);
34 } else if path.extension().is_some_and(|extension| extension == "rs") {
35 files.push(path);
36 }
37 }
38}
39
40fn negative_offsets(
41 pattern: &Regex,
42 source: &str,
43 relative: &str,
44) -> Vec<(usize, Option<usize>, String)> {
45 pattern
46 .find_iter(source)
47 .map(|found| {
48 let line_number = source[..found.start()].matches('\n').count() + 1;
49 let from_match = &source[found.start()..];
50 let allowed = SCAN_ALLOWLIST.iter().position(|(allowed_file, snippet)| {
51 *allowed_file == relative && from_match.starts_with(snippet)
52 });
53 let line_end = from_match.find('\n').unwrap_or(from_match.len());
54 (
55 line_number,
56 allowed,
57 from_match[..line_end].trim().to_owned(),
58 )
59 })
60 .collect()
61}
62
63fn offset_pattern() -> Regex {
64 Regex::new(r"\.(top|right|bottom|left|inset)\(\s*(px\(\s*)?-").expect("pattern")
65}
66
67#[test]
68fn matcher_catches_wrapped_offsets() {
69 let source = "let a = 1;\nlet b = div()\n .top(\n px(-4.))\n .left(px(2.));\n";
70 let found = negative_offsets(&offset_pattern(), source, "views/other.rs");
71 assert_eq!(found, [(3, None, ".top(".to_owned())]);
72}
73
74#[test]
75fn matcher_matches_allowlist_from_match_start() {
76 let source = "x\n .bottom(px(-1.))\n";
77 let found = negative_offsets(&offset_pattern(), source, "views/conversation.rs");
78 assert_eq!(found, [(2, Some(1), ".bottom(px(-1.))".to_owned())]);
79}
80
81#[test]
82fn negative_offsets_go_through_corner_badge() {
83 let pattern = offset_pattern();
84 let mut matched_allowlist = HashSet::new();
85 let mut violations = Vec::new();
86 for root in source_roots() {
87 let mut files = Vec::new();
88 source_files(&root, &mut files);
89 for file in files {
90 let relative = file
91 .strip_prefix(&root)
92 .expect("inside src")
93 .to_string_lossy()
94 .replace('\\', "/");
95 if relative == WIDGETS_FILE || relative == "layout_guard.rs" {
96 continue;
97 }
98 let source = fs::read_to_string(&file).expect("read source file");
99 for (line_number, position, text) in negative_offsets(&pattern, &source, &relative) {
100 match position {
101 Some(position) => {
102 matched_allowlist.insert(position);
103 }
104 None => violations.push(format!(
105 "{relative}:{line_number}: negative absolute offset, use widgets::corner_badge: {text}"
106 )),
107 }
108 }
109 }
110 }
111 let stale: Vec<String> = SCAN_ALLOWLIST
112 .iter()
113 .enumerate()
114 .filter(|(position, _)| !matched_allowlist.contains(position))
115 .map(|(_, (file, snippet))| format!("stale allowlist entry, remove it: {file} {snippet}"))
116 .collect();
117 assert!(
118 violations.is_empty() && stale.is_empty(),
119 "{}",
120 violations
121 .into_iter()
122 .chain(stale)
123 .collect::<Vec<_>>()
124 .join("\n")
125 );
126}
127
128#[test]
129fn hover_styles_never_toggle_display() {
130 let toggle =
131 Regex::new(r"hover\([^|]*\|\w+\|\s*\w+\s*\.\s*(hidden|flex|block|grid)\(\)").unwrap();
132 let mut files = Vec::new();
133 for root in source_roots() {
134 source_files(&root, &mut files);
135 }
136 let offenders: Vec<String> = files
137 .iter()
138 .flat_map(|path| {
139 let source = fs::read_to_string(path).unwrap();
140 source
141 .lines()
142 .enumerate()
143 .filter(|(_, line)| toggle.is_match(line))
144 .map(|(index, _)| format!("{}:{}", path.display(), index + 1))
145 .collect::<Vec<_>>()
146 })
147 .collect();
148 assert!(
149 offenders.is_empty(),
150 "hover styles must toggle visible()/invisible(), not display (gpui panics \"must call prepaint before paint\"): {offenders:?}"
151 );
152}
153
154mod frames {
155 use std::collections::HashSet;
156 use std::sync::Arc;
157 use std::time::Duration;
158
159 use gpui_kit::test::TestWindowExt as _;
160 use gpui_kit::{
161 AppContext as _, Bounds, Pixels, TestAppContext, VisualTestContext, WindowOptions, point,
162 px, size,
163 };
164 use store::Store;
165
166 use std::time::Instant;
167
168 use calling::{CallState, CallUpdate, CaptionEntry, CaptionState, RosterEntry, call_channel};
169 use gpui_kit::Entity;
170
171 use crate::app_state::{AppHandle, AppState, Mode, Selection};
172 use crate::settings::metrics;
173 use crate::settings_section::SettingsSection;
174 use crate::call::{ActiveCall, CallModel, ConsultCall};
175 use crate::demo;
176 use crate::user_activity::UserInput;
177 use crate::views::call_transcript::TranscriptPanel;
178 use crate::views::call_view::CHAT_PANEL_TAG;
179 use crate::views::composer::{COMPOSER_BOX_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG};
180 use crate::views::message_row::BUBBLE_TAGS;
181 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
182 use crate::views::reaction_proposal_pill::REACTION_PILL;
183 use crate::views::recap_tab::RECAP_REGION;
184 use crate::views::shell::{AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call};
185 use crate::views::shortcuts::{OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved};
186
187 const GUARDED: &[&str] = &[
188 "shell",
189 "shell/title-bar",
190 "shell/title-bar/search",
191 "shell/title-bar/own-status",
192 "shell/title-bar/own-status/avatar",
193 "shell/islands",
194 "shell/islands/rail",
195 "shell/islands/sidebar",
196 "shell/islands/main",
197 ];
198 const CALL_GUARDED: &[&str] = &[
199 "shell/islands/main/call-header",
200 "shell/islands/main/call-stage",
201 "shell/islands/main/call-controls",
202 "shell/islands/main/call-controls/mic",
203 "shell/islands/main/call-controls/leave",
204 ];
205 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
206 const CALLS_TAGS: &[&str] = &[
207 "shell/islands/sidebar/calls-actions",
208 "shell/islands/sidebar/calls-actions/meet-now",
209 "shell/islands/sidebar/calls-actions/new-meeting",
210 ];
211 const PREJOIN_TAGS: &[&str] = &[
212 "shell/islands/main/prejoin",
213 "shell/islands/main/prejoin/preview",
214 "shell/islands/main/prejoin/controls",
215 "shell/islands/main/prejoin/devices",
216 "shell/islands/main/prejoin/audio",
217 "shell/islands/main/prejoin/actions",
218 ];
219 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";
220 const CONSULT_GUARDED: &[&str] = &[
221 "shell/islands/main/call-header/call-consult",
222 "shell/islands/main/call-header/call-consult/transfer",
223 "shell/islands/main/call-header/call-consult/resume",
224 ];
225 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
226 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
227 const SHARE_GUARDED: &[&str] = &[
228 "shell/islands/main/call-stage/share-content",
229 "shell/islands/main/call-stage/share-content/zoom-chip",
230 "shell/islands/main/call-stage/share-divider",
231 "shell/islands/main/call-stage/share-strip",
232 ];
233 const OVERLAY_PANELS: &[&str] = &[CALL_TRANSCRIPT, PEOPLE_PANEL];
234 const OVERLAY_CHROME: &[&str] = &[
235 "shell/islands/main/call-header",
236 "shell/islands/main/call-stage",
237 ];
238 const MENU: &str = "popup-menu";
239 const OWN_STATUS: &str = "shell/title-bar/own-status";
240 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
241 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
242 const PROPOSAL_CHAT: &str = "demo-chat-release";
243 const REACTION_CHAT: &str = "demo-chat-mara";
244 const AGENT_TAGS: [&str; 4] = [
245 PROPOSAL_CARD,
246 PROPOSAL_THUMBNAILS,
247 PROPOSAL_BUTTONS,
248 REACTION_PILL,
249 ];
250 const SETTINGS_TAGS: &[&str] = &[
251 "settings",
252 "settings/nav",
253 "settings/main",
254 "settings/main/header",
255 "settings/main/body",
256 ];
257 const SETTINGS_SECTIONS: [SettingsSection; 8] = [
258 SettingsSection::General,
259 SettingsSection::Notifications,
260 SettingsSection::Chats,
261 SettingsSection::Calls,
262 SettingsSection::Devices,
263 SettingsSection::Agents,
264 SettingsSection::Mcp,
265 SettingsSection::About,
266 ];
267 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
268 const TOLERANCE: f32 = 0.5;
269 const KNOWN_VIOLATIONS: &[&str] = &[];
270
271 type Tag = (&'static str, Bounds<Pixels>);
272
273 enum Screen {
274 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
275 StatusMenu,
276 Call,
277 Prejoin,
278 CallTranscript,
279 CallPeople,
280 CallShare,
281 CallConsult,
282 }
283
284 fn parent_of(path: &str) -> Option<&str> {
285 path.rsplit_once('/').map(|(parent, _)| parent)
286 }
287
288 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
289 let tolerance = px(TOLERANCE);
290 inner.left() >= outer.left() - tolerance
291 && inner.top() >= outer.top() - tolerance
292 && inner.right() <= outer.right() + tolerance
293 && inner.bottom() <= outer.bottom() + tolerance
294 }
295
296 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
297 let tolerance = px(TOLERANCE);
298 first.left() < second.right() - tolerance
299 && second.left() < first.right() - tolerance
300 && first.top() < second.bottom() - tolerance
301 && second.top() < first.bottom() - tolerance
302 }
303
304 fn describe(bounds: Bounds<Pixels>) -> String {
305 format!(
306 "[{:.1},{:.1} {:.1}x{:.1}]",
307 f32::from(bounds.origin.x),
308 f32::from(bounds.origin.y),
309 f32::from(bounds.size.width),
310 f32::from(bounds.size.height)
311 )
312 }
313
314 fn violations(
315 tags: &[Tag],
316 window: Bounds<Pixels>,
317 expected: &[&str],
318 ) -> Vec<(String, String)> {
319 let mut found = Vec::new();
320 let bounds_of = |path: &str| {
321 tags.iter()
322 .find(|(tag, _)| *tag == path)
323 .map(|(_, bounds)| *bounds)
324 };
325 for path in expected {
326 if bounds_of(path).is_none() {
327 found.push((
328 format!("{path}:missing"),
329 format!("{path} was not rendered"),
330 ));
331 }
332 }
333 for (path, bounds) in tags {
334 if !contains(window, *bounds) {
335 found.push((
336 format!("{path}:outside-window"),
337 format!(
338 "{path} {} leaves the window {}",
339 describe(*bounds),
340 describe(window)
341 ),
342 ));
343 }
344 if let Some(parent) =
345 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
346 {
347 if !contains(parent.1, *bounds) {
348 found.push((
349 format!("{path}:outside-parent"),
350 format!(
351 "{path} {} leaves {} {}",
352 describe(*bounds),
353 parent.0,
354 describe(parent.1)
355 ),
356 ));
357 }
358 }
359 for (other, other_bounds) in tags {
360 let overlays = |first: &str, second: &str| {
361 OVERLAY_PANELS.contains(&first) && OVERLAY_CHROME.contains(&second)
362 };
363 let siblings = path < other
364 && parent_of(path).is_some()
365 && parent_of(path) == parent_of(other)
366 && !overlays(path, other)
367 && !overlays(other, path);
368 if siblings && overlaps(*bounds, *other_bounds) {
369 found.push((
370 format!("{path}:overlaps:{other}"),
371 format!(
372 "{path} {} overlaps {other} {}",
373 describe(*bounds),
374 describe(*other_bounds)
375 ),
376 ));
377 }
378 }
379 }
380 found
381 }
382
383 const SETTLE_FRAMES: usize = 2;
384 const SETTLE_LIMIT: usize = 60;
385 const SETTLE_STEP: Duration = Duration::from_millis(50);
386
387 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
388 let mut frames = 0;
389 while frames < SETTLE_FRAMES
390 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
391 {
392 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
393 visual.executor().advance_clock(SETTLE_STEP);
394 std::thread::sleep(SETTLE_STEP);
395 visual.run_until_parked();
396 visual.update(|window, cx| window.render_frame(cx));
397 frames += 1;
398 }
399 GUARDED
400 .iter()
401 .chain(CALL_GUARDED)
402 .chain(CALLS_TAGS)
403 .chain(PREJOIN_TAGS)
404 .chain(SHARE_GUARDED)
405 .chain(CONSULT_GUARDED)
406 .chain([
407 &AGENTS_LIST,
408 &CALL_TRANSCRIPT,
409 &MENU,
410 &RECAP_TAB,
411 &RECAP_REGION,
412 &PEOPLE_PANEL,
413 ])
414 .chain(&AGENT_TAGS)
415 .chain(SETTINGS_TAGS)
416 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
417 .collect()
418 }
419
420 fn sharing_call() -> ActiveCall {
421 let mut call = gallery_call();
422 call.model.apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
423 call.share_stage.view.step_in((800., 450.));
424 call
425 }
426
427 fn gallery_call() -> ActiveCall {
428 let (handle, _control) = call_channel();
429 let mut model = CallModel::meeting("Standup", false);
430 model.apply(CallUpdate::State(CallState::Connected {
431 since: Instant::now(),
432 }));
433 model.apply(CallUpdate::Roster(
434 (0..11)
435 .map(|index| RosterEntry {
436 mri: format!("8:orgid:guard-{index}"),
437 display_name: format!("Guest {index}"),
438 muted: false,
439 in_lobby: false,
440 has_video: false,
441 sharing: false,
442 hand: None,
443 spotlight: None,
444 organizer: false,
445 ..Default::default()
446 })
447 .collect(),
448 ));
449 ActiveCall::new(1, model, handle.commands, None, handle.video)
450 }
451
452 fn consult_calls() -> (ActiveCall, ActiveCall) {
453 let connected = |id: u64, name: &str, mri: &str| {
454 let (handle, _control) = call_channel();
455 let mut model = CallModel::people(name, &[(mri.to_owned(), name.to_owned())]);
456 model.apply(CallUpdate::State(CallState::Connected {
457 since: Instant::now(),
458 }));
459 ActiveCall::new(id, model, handle.commands, None, handle.video)
460 };
461 let held = connected(1, "Christopher Montgomery-Lindqvist", "8:orgid:guard-held");
462 let mut consult = connected(2, "Jonas Ortega", "8:orgid:guard-consult");
463 consult.consult = Some(ConsultCall::new(
464 ("8:orgid:guard-consult".to_owned(), "Jonas Ortega".to_owned()),
465 held.model.peer_name.clone(),
466 ));
467 (consult, held)
468 }
469
470 fn mount(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
471 mount_with(cx, false)
472 }
473
474 fn mount_with(
475 cx: &mut TestAppContext,
476 agent_api: bool,
477 ) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
478 cx.update(gpui_kit::init);
479 cx.update(|cx| {
480 crate::theme::apply(cx);
481 bind_keys(cx);
482 let store = Store::open_in_memory().expect("in-memory store");
483 demo::seed(&store);
484 let store = Arc::new(store);
485 if agent_api {
486 crate::agent_api::init(store.clone(), true, cx);
487 }
488 let mode = Mode {
489 demo: true,
490 read_only: false,
491 demo_sync: None,
492 };
493 let state = cx.new(|_| AppState::new(store, mode));
494 install_globals(&state, UserInput::new(), cx);
495 crate::agents::install(state.clone(), cx);
496 demo::start_session(&state, cx);
497 let shared_state = state.clone();
498 let startup = Startup {
499 switcher_query: None,
500 composer_text: None,
501 reply_to_last: false,
502 };
503 let window = gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
504 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
505 })
506 .expect("open test window")
507 .0;
508 (window, shared_state)
509 })
510 }
511
512 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
513 Bounds {
514 origin: point(px(left), px(top)),
515 size: size(px(width), px(height)),
516 }
517 }
518
519 #[test]
520 fn rules_flag_overlap_and_overflow() {
521 let window = rectangle(0., 0., 100., 100.);
522 let tags: Vec<Tag> = vec![
523 ("shell", rectangle(0., 0., 100., 100.)),
524 ("shell/islands", rectangle(0., 0., 100., 50.)),
525 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
526 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
527 ];
528 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
529 .into_iter()
530 .map(|(key, _)| key)
531 .collect();
532 assert_eq!(
533 keys,
534 [
535 "shell/status-bar:missing",
536 "shell/islands/rail:overlaps:shell/islands/sidebar",
537 "shell/islands/sidebar:outside-window",
538 "shell/islands/sidebar:outside-parent",
539 ]
540 );
541 }
542
543 #[gpui_kit::test]
544 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
545 let (handle, app) = mount(cx);
546 let mut visual = VisualTestContext::from_window(handle, cx);
547 let mut seen_known = HashSet::new();
548 let mut unexpected = Vec::new();
549 for (width, height) in SIZES {
550 visual.simulate_resize(size(px(width), px(height)));
551 let window = Bounds {
552 origin: point(px(0.), px(0.)),
553 size: size(px(width), px(height)),
554 };
555 let screens = [
556 Screen::Tab("chats", None),
557 Screen::Tab(
558 "activity",
559 Some(|visual| visual.dispatch_action(OpenActivity)),
560 ),
561 Screen::Tab(
562 "channels",
563 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
564 ),
565 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
566 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
567 Screen::Tab("agents", Some(|visual| visual.dispatch_action(OpenAgents))),
568 Screen::Prejoin,
569 Screen::StatusMenu,
570 Screen::Call,
571 Screen::CallTranscript,
572 Screen::CallPeople,
573 Screen::CallShare,
574 Screen::CallConsult,
575 ];
576 for screen in screens {
577 let (screen_name, status_menu) = match screen {
578 Screen::Tab(name, open) => {
579 if let Some(open) = open {
580 open(&mut visual);
581 }
582 (name, false)
583 }
584 Screen::Call | Screen::CallPeople => {
585 let people_open = matches!(screen, Screen::CallPeople);
586 visual.update(|_, cx| {
587 app.update(cx, |state, cx| {
588 let mut call = gallery_call();
589 call.people_open = people_open;
590 state.call = Some(call);
591 cx.notify();
592 })
593 });
594 (if people_open { "call-people" } else { "call" }, false)
595 }
596 Screen::Prejoin => {
597 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
598 visual.update(|_, cx| {
599 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
600 });
601 ("prejoin", false)
602 }
603 Screen::CallTranscript => {
604 visual.update(|window, cx| {
605 app.update(cx, |state, cx| {
606 let mut call = gallery_call();
607 call.model.apply(CallUpdate::Captions(CaptionState::On));
608 for index in 0..40 {
609 call.model.note_caption(
610 CaptionEntry {
611 id: format!("guard-{index}"),
612 user_id: "8:orgid:guard-0".into(),
613 display_name: "Guest 0".into(),
614 text: "A long guarded sentence that has to wrap inside the panel".into(),
615 is_final: true,
616 },
617 Instant::now(),
618 );
619 }
620 call.transcript_open = true;
621 state.call = Some(call);
622 let app_entity = cx.entity();
623 state.transcript_panel = Some(cx.new(|cx| TranscriptPanel::new(app_entity, window, cx)).into());
624 cx.notify();
625 })
626 });
627 ("call-transcript", false)
628 }
629 Screen::CallShare => {
630 visual.update(|_, cx| {
631 app.update(cx, |state, cx| {
632 state.call = Some(sharing_call());
633 cx.notify();
634 })
635 });
636 ("call-share", false)
637 }
638 Screen::CallConsult => {
639 visual.update(|_, cx| {
640 app.update(cx, |state, cx| {
641 let (consult, held) = consult_calls();
642 state.call = Some(consult);
643 state.held_call = Some(held);
644 cx.notify();
645 })
646 });
647 ("call-consult", false)
648 }
649 Screen::StatusMenu => {
650 let tags = collect(&mut visual, None);
651 let button = tags
652 .iter()
653 .find(|(path, _)| *path == OWN_STATUS)
654 .map(|(_, bounds)| *bounds)
655 .expect("own status button rendered");
656 visual.simulate_click(button.center(), Default::default());
657 ("status-menu", true)
658 }
659 };
660 let is_call = matches!(
661 screen_name,
662 "call" | "call-people" | "call-transcript" | "call-share" | "call-consult"
663 );
664 let tags = collect(&mut visual, status_menu.then_some(MENU));
665 let mut expected = GUARDED.to_vec();
666 if is_call {
667 expected.extend(CALL_GUARDED);
668 let panel_open = matches!(screen_name, "call-people" | "call-transcript");
669 if sidebar_hidden_in_call(width, panel_open) {
670 expected.retain(|path| *path != "shell/islands/sidebar");
671 }
672 }
673 if screen_name == "call-transcript" {
674 expected.push(CALL_TRANSCRIPT);
675 }
676 if screen_name == "call-people" {
677 expected.push(PEOPLE_PANEL);
678 }
679 if screen_name == "call-share" {
680 expected.extend(SHARE_GUARDED);
681 }
682 if screen_name == "call-consult" {
683 expected.extend(CONSULT_GUARDED);
684 }
685 if status_menu {
686 expected.push(MENU);
687 }
688 match screen_name {
689 "calls" => expected.extend(CALLS_TAGS),
690 "agents" => expected.push(AGENTS_LIST),
691 "prejoin" => expected.extend(PREJOIN_TAGS),
692 _ => {}
693 }
694 let mut found = violations(&tags, window, &expected);
695 if status_menu {
696 let menu = tags
697 .iter()
698 .find(|(path, _)| *path == MENU)
699 .map(|(_, bounds)| *bounds);
700 let button = tags
701 .iter()
702 .find(|(path, _)| *path == OWN_STATUS)
703 .map(|(_, bounds)| *bounds);
704 if let (Some(menu), Some(button)) = (menu, button) {
705 if overlaps(menu, button) {
706 found.push((
707 format!("{MENU}:covers:{OWN_STATUS}"),
708 format!(
709 "{MENU} {} covers {OWN_STATUS} {}",
710 describe(menu),
711 describe(button)
712 ),
713 ));
714 }
715 }
716 visual.simulate_keystrokes("escape");
717 visual.run_until_parked();
718 }
719 if is_call {
720 visual.update(|_, cx| {
721 app.update(cx, |state, cx| {
722 state.call = None;
723 state.held_call = None;
724 cx.notify();
725 })
726 });
727 }
728 if screen_name == "prejoin" {
729 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
730 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
731 }
732 for (key, message) in found {
733 let full_key = format!("{screen_name}@{width}x{height}:{key}");
734 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
735 seen_known.insert(full_key);
736 } else {
737 unexpected.push(format!("{full_key}: {message}"));
738 }
739 }
740 }
741 }
742 let stale: Vec<String> = KNOWN_VIOLATIONS
743 .iter()
744 .filter(|key| !seen_known.contains(**key))
745 .map(|key| format!("stale known violation, remove it: {key}"))
746 .collect();
747 assert!(
748 unexpected.is_empty() && stale.is_empty(),
749 "{}",
750 unexpected
751 .into_iter()
752 .chain(stale)
753 .collect::<Vec<_>>()
754 .join("\n")
755 );
756 }
757 const TITLE_SEARCH: &str = "shell/title-bar/search";
758 const TITLE_NEIGHBOURS: &[&str] = &[
759 "shell/title-bar/leading",
760 "shell/title-bar/mode-pill",
761 "shell/title-bar/trailing",
762 "shell/title-bar/update",
763 OWN_STATUS,
764 ];
765 const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [
766 (1920., 1080., true),
767 (1280., 800., true),
768 (640., 480., false),
769 ];
770
771 #[gpui_kit::test]
772 fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {
773 let (handle, _) = mount(cx);
774 let mut visual = VisualTestContext::from_window(handle, cx);
775 let shell = visual.update(|window, cx| {
776 window
777 .root::<gpui_kit::base::Root>()
778 .flatten()
779 .and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())
780 .expect("app shell is the root view")
781 });
782 visual.update(|_, cx| {
783 shell.update(cx, |shell, cx| {
784 shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)
785 })
786 });
787 let mut found = Vec::new();
788 for (width, height, centered) in TITLE_SEARCH_SIZES {
789 visual.simulate_resize(size(px(width), px(height)));
790 collect(&mut visual, Some(TITLE_SEARCH));
791 let search = visual
792 .debug_bounds(TITLE_SEARCH)
793 .expect("title search rendered");
794 let search_center = f32::from(search.center().x);
795 eprintln!(
796 "title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",
797 describe(search),
798 width / 2.
799 );
800 if centered && (search_center - width / 2.).abs() > 1. {
801 found.push(format!(
802 "@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",
803 width / 2.
804 ));
805 }
806 if !contains(rectangle(0., 0., width, height), search) {
807 found.push(format!(
808 "@{width}x{height}: search {} leaves the window",
809 describe(search)
810 ));
811 }
812 for neighbour in TITLE_NEIGHBOURS {
813 match visual.debug_bounds(neighbour) {
814 None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),
815 Some(bounds) if overlaps(search, bounds) => found.push(format!(
816 "@{width}x{height}: search {} overlaps {neighbour} {}",
817 describe(search),
818 describe(bounds)
819 )),
820 Some(_) => {}
821 }
822 }
823 }
824 assert!(found.is_empty(), "{}", found.join("\n"));
825 }
826
827 #[gpui_kit::test]
828 fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
829 let (handle, app) = mount(cx);
830 let mut visual = VisualTestContext::from_window(handle, cx);
831 for (width, height) in SIZES {
832 visual.simulate_resize(size(px(width), px(height)));
833 visual.update(|_, cx| {
834 app.update(cx, |state, cx| {
835 let mut call = gallery_call();
836 call.conversation_id = Some(RECAP_MEETING_CHAT.to_owned());
837 call.chat_open = true;
838 state.call = Some(call);
839 cx.notify();
840 })
841 });
842 collect(&mut visual, Some(CHAT_PANEL_TAG));
843 let panel = visual
844 .debug_bounds(CHAT_PANEL_TAG)
845 .expect("chat panel rendered");
846 let bubbles: Vec<(usize, Bounds<Pixels>)> = BUBBLE_TAGS
847 .iter()
848 .enumerate()
849 .filter_map(|(index, tag)| visual.debug_bounds(tag).map(|bounds| (index, bounds)))
850 .collect();
851 assert!(!bubbles.is_empty(), "no bubbles rendered in the call chat");
852 let found: Vec<String> = bubbles
853 .into_iter()
854 .filter(|(_, bounds)| !contains(panel, *bounds))
855 .map(|(index, bounds)| {
856 format!(
857 "call-chat@{width}x{height}: bubble {index} {} leaves the chat panel {}",
858 describe(bounds),
859 describe(panel)
860 )
861 })
862 .collect();
863 visual.update(|_, cx| {
864 app.update(cx, |state, cx| {
865 state.call = None;
866 cx.notify();
867 })
868 });
869 assert!(found.is_empty(), "{}", found.join("\n"));
870 }
871 }
872
873 #[gpui_kit::test]
874 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
875 let (handle, state) = mount(cx);
876 let mut visual = VisualTestContext::from_window(handle, cx);
877 for (width, height) in SIZES {
878 visual.simulate_resize(size(px(width), px(height)));
879 let window = Bounds {
880 origin: point(px(0.), px(0.)),
881 size: size(px(width), px(height)),
882 };
883 visual.update(|_, cx| {
884 state.update(cx, |state, cx| {
885 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
886 })
887 });
888 collect(&mut visual, Some(RECAP_TAB));
889 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
890 visual.simulate_click(tab.center(), Default::default());
891 let tags = collect(&mut visual, Some(RECAP_REGION));
892 let mut expected = GUARDED.to_vec();
893 expected.extend([RECAP_TAB, RECAP_REGION]);
894 let found: Vec<String> = violations(&tags, window, &expected)
895 .into_iter()
896 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
897 .collect();
898 assert!(found.is_empty(), "{}", found.join("\n"));
899 }
900 }
901
902 #[gpui_kit::test]
903 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
904 let (handle, state) = mount_with(cx, true);
905 let mut visual = VisualTestContext::from_window(handle, cx);
906 for (width, height) in SIZES.into_iter().chain([(960., 640.)]) {
907 visual.simulate_resize(size(px(width), px(height)));
908 let window = Bounds {
909 origin: point(px(0.), px(0.)),
910 size: size(px(width), px(height)),
911 };
912 let inset = metrics(width, height).inset;
913 for section in SETTINGS_SECTIONS {
914 visual.update(|_, cx| {
915 state.update(cx, |state, cx| state.open_settings(section, cx))
916 });
917 let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
918 let found: Vec<String> = violations(&tags, window, SETTINGS_TAGS)
919 .into_iter()
920 .filter(|(key, _)| key.starts_with("settings"))
921 .map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
922 .collect();
923 assert!(found.is_empty(), "{}", found.join("\n"));
924 let dialog = visual.debug_bounds(SETTINGS_TAGS[0]).expect("settings dialog");
925 let edges = [
926 f32::from(dialog.left()),
927 f32::from(dialog.top()),
928 width - f32::from(dialog.right()),
929 height - f32::from(dialog.bottom()),
930 ];
931 assert!(
932 edges.iter().all(|edge| (edge - inset).abs() <= TOLERANCE),
933 "{section:?}@{width}x{height}: dialog edges {edges:?}, expected {inset}"
934 );
935 }
936 }
937 }
938
939 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
940 collect(visual, Some(COMPOSER_SEND_TAG));
941 let mut bounds_of = |path: &'static str| {
942 visual
943 .debug_bounds(path)
944 .unwrap_or_else(|| panic!("{path} rendered"))
945 };
946 let composer = bounds_of(COMPOSER_BOX_TAG);
947 let leading = bounds_of(COMPOSER_LEADING_TAG);
948 let send = bounds_of(COMPOSER_SEND_TAG);
949 [
950 f32::from(leading.left() - composer.left()),
951 f32::from(leading.top() - composer.top()),
952 f32::from(composer.bottom() - leading.bottom()),
953 f32::from(composer.right() - send.right()),
954 f32::from(send.top() - composer.top()),
955 f32::from(composer.bottom() - send.bottom()),
956 ]
957 }
958
959 #[gpui_kit::test]
960 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
961 let (handle, _) = mount(cx);
962 let mut visual = VisualTestContext::from_window(handle, cx);
963 visual.simulate_resize(size(px(1280.), px(800.)));
964 let single_line = composer_button_insets(&mut visual);
965 let left = single_line[0];
966 assert!(
967 single_line
968 .iter()
969 .all(|inset| (inset - left).abs() < TOLERANCE),
970 "single line: insets left, top, bottom of the first button and right, top, bottom of send {single_line:?}"
971 );
972 let leading = visual
973 .debug_bounds(COMPOSER_LEADING_TAG)
974 .expect("leading buttons");
975 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
976 visual.simulate_click(
977 point((leading.right() + send.left()) / 2., send.center().y),
978 Default::default(),
979 );
980 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
981 let three_lines = composer_button_insets(&mut visual);
982 assert!(
983 three_lines[1] > single_line[1] + 30.,
984 "three lines did not grow the composer: {three_lines:?}"
985 );
986 for inset in [
987 three_lines[0],
988 three_lines[2],
989 three_lines[3],
990 three_lines[5],
991 ] {
992 assert!(
993 (inset - left).abs() < TOLERANCE,
994 "three lines: insets left, top, bottom of the first button and right, top, bottom of send {three_lines:?}, expected {left}"
995 );
996 }
997 }
998
999 #[gpui_kit::test]
1000 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
1001 let (handle, state) = mount_with(cx, true);
1002 let mut visual = VisualTestContext::from_window(handle, cx);
1003 for (width, height) in SIZES {
1004 visual.simulate_resize(size(px(width), px(height)));
1005 let window = Bounds {
1006 origin: point(px(0.), px(0.)),
1007 size: size(px(width), px(height)),
1008 };
1009 for (chat, expected_tags) in [
1010 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
1011 (REACTION_CHAT, &AGENT_TAGS[3..]),
1012 ] {
1013 visual.update(|_, cx| {
1014 state.update(cx, |state, cx| {
1015 state.select(Selection::Chat(chat.to_owned()), cx)
1016 })
1017 });
1018 let tags = collect(&mut visual, Some(expected_tags[0]));
1019 let mut expected = GUARDED.to_vec();
1020 expected.extend(expected_tags);
1021 let found: Vec<String> = violations(&tags, window, &expected)
1022 .into_iter()
1023 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
1024 .collect();
1025 assert!(found.is_empty(), "{}", found.join("\n"));
1026 }
1027 }
1028 }
1029}
1030
1031#[test]
1032fn lines_are_solid() {
1033 let mut files = Vec::new();
1034 for root in source_roots() {
1035 source_files(&root, &mut files);
1036 }
1037 let violations: Vec<String> = files
1038 .iter()
1039 .filter(|file| !file.ends_with("layout_guard.rs"))
1040 .flat_map(|file| {
1041 let source = fs::read_to_string(file).expect("read source file");
1042 source
1043 .lines()
1044 .enumerate()
1045 .filter(|(_, line)| {
1046 line.contains(".border_dashed(") || line.contains(".border_dotted(")
1047 })
1048 .map(|(index, line)| {
1049 format!(
1050 "{}:{}: lines are always solid: {}",
1051 file.display(),
1052 index + 1,
1053 line.trim()
1054 )
1055 })
1056 .collect::<Vec<_>>()
1057 })
1058 .collect();
1059 assert!(violations.is_empty(), "{}", violations.join("\n"));
1060}
1061
1062fn indentation(line: &str) -> usize {
1063 line.len() - line.trim_start().len()
1064}
1065
1066fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
1067 let indent = indentation(lines[index]);
1068 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
1069 let start = lines[..index]
1070 .iter()
1071 .rposition(|line| !belongs(line))
1072 .map_or(0, |position| position + 1);
1073 let end = lines[index..]
1074 .iter()
1075 .position(|line| !belongs(line))
1076 .map_or(lines.len(), |position| index + position);
1077 lines[start..end]
1078 .iter()
1079 .filter(|line| indentation(line) == indent)
1080 .copied()
1081 .collect()
1082}
1083
1084fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
1085 let lines: Vec<&str> = source.lines().collect();
1086 (0..lines.len())
1087 .filter(|&index| row_height.is_match(lines[index]))
1088 .filter(|&index| {
1089 !chain_lines(&lines, index).iter().any(|line| {
1090 let line = line.trim();
1091 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
1092 })
1093 })
1094 .map(|index| index + 1)
1095 .collect()
1096}
1097
1098fn row_height_pattern() -> Regex {
1099 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
1100}
1101
1102#[test]
1103fn matcher_finds_rows_without_flex_none() {
1104 let source = "fn rows() {\n h_flex()\n .h(px(ROW_HEIGHT))\n .child(\n div()\n .flex_none(),\n );\n div()\n .id(1)\n .h(px(OWN_ROW_HEIGHT))\n .flex_none();\n}\n";
1105 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
1106}
1107
1108#[test]
1109fn fixed_height_rows_never_shrink() {
1110 let row_height = row_height_pattern();
1111 let mut files = Vec::new();
1112 for root in source_roots() {
1113 source_files(&root, &mut files);
1114 }
1115 let violations: Vec<String> = files
1116 .iter()
1117 .filter(|file| !file.ends_with("layout_guard.rs"))
1118 .flat_map(|file| {
1119 let source = fs::read_to_string(file).expect("read source file");
1120 shrinking_rows(&row_height, &source)
1121 .into_iter()
1122 .map(|line| format!("{}:{line}", file.display()))
1123 .collect::<Vec<_>>()
1124 })
1125 .collect();
1126 assert!(
1127 violations.is_empty(),
1128 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
1129 );
1130}