BlueGit

ict rusty-teams

Files

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

layout_guard.rs

e576db45 History
layout_guard.rs 38.8 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::message_row::BUBBLE_TAGS;
180 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
181 use crate::views::reaction_proposal_pill::REACTION_PILL;
182 use crate::views::recap_tab::RECAP_REGION;
183 use crate::views::shell::{AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call};
184 use crate::views::shortcuts::{OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved};
185
186 const GUARDED: &[&str] = &[
187 "shell",
188 "shell/title-bar",
189 "shell/title-bar/search",
190 "shell/title-bar/own-status",
191 "shell/title-bar/own-status/avatar",
192 "shell/islands",
193 "shell/islands/rail",
194 "shell/islands/sidebar",
195 "shell/islands/main",
196 ];
197 const CALL_GUARDED: &[&str] = &[
198 "shell/islands/main/call-header",
199 "shell/islands/main/call-stage",
200 "shell/islands/main/call-controls",
201 "shell/islands/main/call-controls/mic",
202 "shell/islands/main/call-controls/leave",
203 ];
204 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
205 const CALLS_TAGS: &[&str] = &[
206 "shell/islands/sidebar/calls-actions",
207 "shell/islands/sidebar/calls-actions/meet-now",
208 "shell/islands/sidebar/calls-actions/new-meeting",
209 ];
210 const PREJOIN_TAGS: &[&str] = &[
211 "shell/islands/main/prejoin",
212 "shell/islands/main/prejoin/preview",
213 "shell/islands/main/prejoin/controls",
214 "shell/islands/main/prejoin/devices",
215 "shell/islands/main/prejoin/audio",
216 "shell/islands/main/prejoin/actions",
217 ];
218 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";
219 const CONSULT_GUARDED: &[&str] = &[
220 "shell/islands/main/call-header/call-consult",
221 "shell/islands/main/call-header/call-consult/transfer",
222 "shell/islands/main/call-header/call-consult/resume",
223 ];
224 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
225 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
226 const SHARE_GUARDED: &[&str] = &[
227 "shell/islands/main/call-stage/share-content",
228 "shell/islands/main/call-stage/share-content/zoom-chip",
229 "shell/islands/main/call-stage/share-divider",
230 "shell/islands/main/call-stage/share-strip",
231 ];
232 const OVERLAY_PANELS: &[&str] = &[CALL_TRANSCRIPT, PEOPLE_PANEL];
233 const OVERLAY_CHROME: &[&str] = &[
234 "shell/islands/main/call-header",
235 "shell/islands/main/call-stage",
236 ];
237 const MENU: &str = "popup-menu";
238 const OWN_STATUS: &str = "shell/title-bar/own-status";
239 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
240 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
241 const PROPOSAL_CHAT: &str = "demo-chat-release";
242 const REACTION_CHAT: &str = "demo-chat-mara";
243 const AGENT_TAGS: [&str; 4] = [
244 PROPOSAL_CARD,
245 PROPOSAL_THUMBNAILS,
246 PROPOSAL_BUTTONS,
247 REACTION_PILL,
248 ];
249 const SETTINGS_TAGS: &[&str] = &[
250 "settings",
251 "settings/nav",
252 "settings/main",
253 "settings/main/header",
254 "settings/main/body",
255 ];
256 const SETTINGS_SECTIONS: [SettingsSection; 8] = [
257 SettingsSection::General,
258 SettingsSection::Notifications,
259 SettingsSection::Chats,
260 SettingsSection::Calls,
261 SettingsSection::Devices,
262 SettingsSection::Agents,
263 SettingsSection::Mcp,
264 SettingsSection::About,
265 ];
266 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
267 const TOLERANCE: f32 = 0.5;
268 const KNOWN_VIOLATIONS: &[&str] = &[];
269
270 type Tag = (&'static str, Bounds<Pixels>);
271
272 enum Screen {
273 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
274 StatusMenu,
275 Call,
276 Prejoin,
277 CallTranscript,
278 CallPeople,
279 CallShare,
280 CallConsult,
281 }
282
283 fn parent_of(path: &str) -> Option<&str> {
284 path.rsplit_once('/').map(|(parent, _)| parent)
285 }
286
287 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
288 let tolerance = px(TOLERANCE);
289 inner.left() >= outer.left() - tolerance
290 && inner.top() >= outer.top() - tolerance
291 && inner.right() <= outer.right() + tolerance
292 && inner.bottom() <= outer.bottom() + tolerance
293 }
294
295 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
296 let tolerance = px(TOLERANCE);
297 first.left() < second.right() - tolerance
298 && second.left() < first.right() - tolerance
299 && first.top() < second.bottom() - tolerance
300 && second.top() < first.bottom() - tolerance
301 }
302
303 fn describe(bounds: Bounds<Pixels>) -> String {
304 format!(
305 "[{:.1},{:.1} {:.1}x{:.1}]",
306 f32::from(bounds.origin.x),
307 f32::from(bounds.origin.y),
308 f32::from(bounds.size.width),
309 f32::from(bounds.size.height)
310 )
311 }
312
313 fn violations(
314 tags: &[Tag],
315 window: Bounds<Pixels>,
316 expected: &[&str],
317 ) -> Vec<(String, String)> {
318 let mut found = Vec::new();
319 let bounds_of = |path: &str| {
320 tags.iter()
321 .find(|(tag, _)| *tag == path)
322 .map(|(_, bounds)| *bounds)
323 };
324 for path in expected {
325 if bounds_of(path).is_none() {
326 found.push((
327 format!("{path}:missing"),
328 format!("{path} was not rendered"),
329 ));
330 }
331 }
332 for (path, bounds) in tags {
333 if !contains(window, *bounds) {
334 found.push((
335 format!("{path}:outside-window"),
336 format!(
337 "{path} {} leaves the window {}",
338 describe(*bounds),
339 describe(window)
340 ),
341 ));
342 }
343 if let Some(parent) =
344 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
345 {
346 if !contains(parent.1, *bounds) {
347 found.push((
348 format!("{path}:outside-parent"),
349 format!(
350 "{path} {} leaves {} {}",
351 describe(*bounds),
352 parent.0,
353 describe(parent.1)
354 ),
355 ));
356 }
357 }
358 for (other, other_bounds) in tags {
359 let overlays = |first: &str, second: &str| {
360 OVERLAY_PANELS.contains(&first) && OVERLAY_CHROME.contains(&second)
361 };
362 let siblings = path < other
363 && parent_of(path).is_some()
364 && parent_of(path) == parent_of(other)
365 && !overlays(path, other)
366 && !overlays(other, path);
367 if siblings && overlaps(*bounds, *other_bounds) {
368 found.push((
369 format!("{path}:overlaps:{other}"),
370 format!(
371 "{path} {} overlaps {other} {}",
372 describe(*bounds),
373 describe(*other_bounds)
374 ),
375 ));
376 }
377 }
378 }
379 found
380 }
381
382 const SETTLE_FRAMES: usize = 2;
383 const SETTLE_LIMIT: usize = 60;
384 const SETTLE_STEP: Duration = Duration::from_millis(50);
385
386 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
387 let mut frames = 0;
388 while frames < SETTLE_FRAMES
389 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
390 {
391 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
392 visual.executor().advance_clock(SETTLE_STEP);
393 std::thread::sleep(SETTLE_STEP);
394 visual.run_until_parked();
395 visual.update(|window, cx| window.render_frame(cx));
396 frames += 1;
397 }
398 GUARDED
399 .iter()
400 .chain(CALL_GUARDED)
401 .chain(CALLS_TAGS)
402 .chain(PREJOIN_TAGS)
403 .chain(SHARE_GUARDED)
404 .chain(CONSULT_GUARDED)
405 .chain([
406 &AGENTS_LIST,
407 &CALL_TRANSCRIPT,
408 &MENU,
409 &RECAP_TAB,
410 &RECAP_REGION,
411 &PEOPLE_PANEL,
412 ])
413 .chain(&AGENT_TAGS)
414 .chain(SETTINGS_TAGS)
415 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
416 .collect()
417 }
418
419 fn sharing_call() -> ActiveCall {
420 let mut call = gallery_call();
421 call.model.apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
422 call.share_stage.view.step_in((800., 450.));
423 call
424 }
425
426 fn gallery_call() -> ActiveCall {
427 let (handle, _control) = call_channel();
428 let mut model = CallModel::meeting("Standup", false);
429 model.apply(CallUpdate::State(CallState::Connected {
430 since: Instant::now(),
431 }));
432 model.apply(CallUpdate::Roster(
433 (0..11)
434 .map(|index| RosterEntry {
435 mri: format!("8:orgid:guard-{index}"),
436 display_name: format!("Guest {index}"),
437 muted: false,
438 in_lobby: false,
439 has_video: false,
440 sharing: false,
441 hand: None,
442 spotlight: None,
443 organizer: false,
444 ..Default::default()
445 })
446 .collect(),
447 ));
448 ActiveCall::new(1, model, handle.commands, None, handle.video)
449 }
450
451 fn consult_calls() -> (ActiveCall, ActiveCall) {
452 let connected = |id: u64, name: &str, mri: &str| {
453 let (handle, _control) = call_channel();
454 let mut model = CallModel::people(name, &[(mri.to_owned(), name.to_owned())]);
455 model.apply(CallUpdate::State(CallState::Connected {
456 since: Instant::now(),
457 }));
458 ActiveCall::new(id, model, handle.commands, None, handle.video)
459 };
460 let held = connected(1, "Christopher Montgomery-Lindqvist", "8:orgid:guard-held");
461 let mut consult = connected(2, "Jonas Ortega", "8:orgid:guard-consult");
462 consult.consult = Some(ConsultCall::new(
463 ("8:orgid:guard-consult".to_owned(), "Jonas Ortega".to_owned()),
464 held.model.peer_name.clone(),
465 ));
466 (consult, held)
467 }
468
469 fn mount(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
470 mount_with(cx, false)
471 }
472
473 fn mount_with(
474 cx: &mut TestAppContext,
475 agent_api: bool,
476 ) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
477 cx.update(gpui_kit::init);
478 cx.update(|cx| {
479 crate::theme::apply(cx);
480 bind_keys(cx);
481 let store = Store::open_in_memory().expect("in-memory store");
482 demo::seed(&store);
483 let store = Arc::new(store);
484 if agent_api {
485 crate::agent_api::init(store.clone(), true, cx);
486 }
487 let mode = Mode {
488 demo: true,
489 read_only: false,
490 demo_sync: None,
491 };
492 let state = cx.new(|_| AppState::new(store, mode));
493 install_globals(&state, UserInput::new(), cx);
494 crate::agents::install(state.clone(), cx);
495 demo::start_session(&state, cx);
496 let shared_state = state.clone();
497 let startup = Startup {
498 switcher_query: None,
499 composer_text: None,
500 reply_to_last: false,
501 };
502 let window = gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
503 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
504 })
505 .expect("open test window")
506 .0;
507 (window, shared_state)
508 })
509 }
510
511 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
512 Bounds {
513 origin: point(px(left), px(top)),
514 size: size(px(width), px(height)),
515 }
516 }
517
518 #[test]
519 fn rules_flag_overlap_and_overflow() {
520 let window = rectangle(0., 0., 100., 100.);
521 let tags: Vec<Tag> = vec![
522 ("shell", rectangle(0., 0., 100., 100.)),
523 ("shell/islands", rectangle(0., 0., 100., 50.)),
524 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
525 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
526 ];
527 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
528 .into_iter()
529 .map(|(key, _)| key)
530 .collect();
531 assert_eq!(
532 keys,
533 [
534 "shell/status-bar:missing",
535 "shell/islands/rail:overlaps:shell/islands/sidebar",
536 "shell/islands/sidebar:outside-window",
537 "shell/islands/sidebar:outside-parent",
538 ]
539 );
540 }
541
542 #[gpui_kit::test]
543 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
544 let (handle, app) = mount(cx);
545 let mut visual = VisualTestContext::from_window(handle, cx);
546 let mut seen_known = HashSet::new();
547 let mut unexpected = Vec::new();
548 for (width, height) in SIZES {
549 visual.simulate_resize(size(px(width), px(height)));
550 let window = Bounds {
551 origin: point(px(0.), px(0.)),
552 size: size(px(width), px(height)),
553 };
554 let screens = [
555 Screen::Tab("chats", None),
556 Screen::Tab(
557 "activity",
558 Some(|visual| visual.dispatch_action(OpenActivity)),
559 ),
560 Screen::Tab(
561 "channels",
562 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
563 ),
564 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
565 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
566 Screen::Tab("agents", Some(|visual| visual.dispatch_action(OpenAgents))),
567 Screen::Prejoin,
568 Screen::StatusMenu,
569 Screen::Call,
570 Screen::CallTranscript,
571 Screen::CallPeople,
572 Screen::CallShare,
573 Screen::CallConsult,
574 ];
575 for screen in screens {
576 let (screen_name, status_menu) = match screen {
577 Screen::Tab(name, open) => {
578 if let Some(open) = open {
579 open(&mut visual);
580 }
581 (name, false)
582 }
583 Screen::Call | Screen::CallPeople => {
584 let people_open = matches!(screen, Screen::CallPeople);
585 visual.update(|_, cx| {
586 app.update(cx, |state, cx| {
587 let mut call = gallery_call();
588 call.people_open = people_open;
589 state.call = Some(call);
590 cx.notify();
591 })
592 });
593 (if people_open { "call-people" } else { "call" }, false)
594 }
595 Screen::Prejoin => {
596 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
597 visual.update(|_, cx| {
598 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
599 });
600 ("prejoin", false)
601 }
602 Screen::CallTranscript => {
603 visual.update(|window, cx| {
604 app.update(cx, |state, cx| {
605 let mut call = gallery_call();
606 call.model.apply(CallUpdate::Captions(CaptionState::On));
607 for index in 0..40 {
608 call.model.note_caption(
609 CaptionEntry {
610 id: format!("guard-{index}"),
611 user_id: "8:orgid:guard-0".into(),
612 display_name: "Guest 0".into(),
613 text: "A long guarded sentence that has to wrap inside the panel".into(),
614 is_final: true,
615 },
616 Instant::now(),
617 );
618 }
619 call.transcript_open = true;
620 state.call = Some(call);
621 let app_entity = cx.entity();
622 state.transcript_panel = Some(cx.new(|cx| TranscriptPanel::new(app_entity, window, cx)).into());
623 cx.notify();
624 })
625 });
626 ("call-transcript", false)
627 }
628 Screen::CallShare => {
629 visual.update(|_, cx| {
630 app.update(cx, |state, cx| {
631 state.call = Some(sharing_call());
632 cx.notify();
633 })
634 });
635 ("call-share", false)
636 }
637 Screen::CallConsult => {
638 visual.update(|_, cx| {
639 app.update(cx, |state, cx| {
640 let (consult, held) = consult_calls();
641 state.call = Some(consult);
642 state.held_call = Some(held);
643 cx.notify();
644 })
645 });
646 ("call-consult", false)
647 }
648 Screen::StatusMenu => {
649 let tags = collect(&mut visual, None);
650 let button = tags
651 .iter()
652 .find(|(path, _)| *path == OWN_STATUS)
653 .map(|(_, bounds)| *bounds)
654 .expect("own status button rendered");
655 visual.simulate_click(button.center(), Default::default());
656 ("status-menu", true)
657 }
658 };
659 let is_call = matches!(
660 screen_name,
661 "call" | "call-people" | "call-transcript" | "call-share" | "call-consult"
662 );
663 let tags = collect(&mut visual, status_menu.then_some(MENU));
664 let mut expected = GUARDED.to_vec();
665 if is_call {
666 expected.extend(CALL_GUARDED);
667 let panel_open = matches!(screen_name, "call-people" | "call-transcript");
668 if sidebar_hidden_in_call(width, panel_open) {
669 expected.retain(|path| *path != "shell/islands/sidebar");
670 }
671 }
672 if screen_name == "call-transcript" {
673 expected.push(CALL_TRANSCRIPT);
674 }
675 if screen_name == "call-people" {
676 expected.push(PEOPLE_PANEL);
677 }
678 if screen_name == "call-share" {
679 expected.extend(SHARE_GUARDED);
680 }
681 if screen_name == "call-consult" {
682 expected.extend(CONSULT_GUARDED);
683 }
684 if status_menu {
685 expected.push(MENU);
686 }
687 match screen_name {
688 "calls" => expected.extend(CALLS_TAGS),
689 "agents" => expected.push(AGENTS_LIST),
690 "prejoin" => expected.extend(PREJOIN_TAGS),
691 _ => {}
692 }
693 let mut found = violations(&tags, window, &expected);
694 if status_menu {
695 let menu = tags
696 .iter()
697 .find(|(path, _)| *path == MENU)
698 .map(|(_, bounds)| *bounds);
699 let button = tags
700 .iter()
701 .find(|(path, _)| *path == OWN_STATUS)
702 .map(|(_, bounds)| *bounds);
703 if let (Some(menu), Some(button)) = (menu, button) {
704 if overlaps(menu, button) {
705 found.push((
706 format!("{MENU}:covers:{OWN_STATUS}"),
707 format!(
708 "{MENU} {} covers {OWN_STATUS} {}",
709 describe(menu),
710 describe(button)
711 ),
712 ));
713 }
714 }
715 visual.simulate_keystrokes("escape");
716 visual.run_until_parked();
717 }
718 if is_call {
719 visual.update(|_, cx| {
720 app.update(cx, |state, cx| {
721 state.call = None;
722 state.held_call = None;
723 cx.notify();
724 })
725 });
726 }
727 if screen_name == "prejoin" {
728 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
729 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
730 }
731 for (key, message) in found {
732 let full_key = format!("{screen_name}@{width}x{height}:{key}");
733 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
734 seen_known.insert(full_key);
735 } else {
736 unexpected.push(format!("{full_key}: {message}"));
737 }
738 }
739 }
740 }
741 let stale: Vec<String> = KNOWN_VIOLATIONS
742 .iter()
743 .filter(|key| !seen_known.contains(**key))
744 .map(|key| format!("stale known violation, remove it: {key}"))
745 .collect();
746 assert!(
747 unexpected.is_empty() && stale.is_empty(),
748 "{}",
749 unexpected
750 .into_iter()
751 .chain(stale)
752 .collect::<Vec<_>>()
753 .join("\n")
754 );
755 }
756 const TITLE_SEARCH: &str = "shell/title-bar/search";
757 const TITLE_NEIGHBOURS: &[&str] = &[
758 "shell/title-bar/leading",
759 "shell/title-bar/mode-pill",
760 "shell/title-bar/trailing",
761 "shell/title-bar/update",
762 OWN_STATUS,
763 ];
764 const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [
765 (1920., 1080., true),
766 (1280., 800., true),
767 (640., 480., false),
768 ];
769
770 #[gpui_kit::test]
771 fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {
772 let (handle, _) = mount(cx);
773 let mut visual = VisualTestContext::from_window(handle, cx);
774 let shell = visual.update(|window, cx| {
775 window
776 .root::<gpui_kit::base::Root>()
777 .flatten()
778 .and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())
779 .expect("app shell is the root view")
780 });
781 visual.update(|_, cx| {
782 shell.update(cx, |shell, cx| {
783 shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)
784 })
785 });
786 let mut found = Vec::new();
787 for (width, height, centered) in TITLE_SEARCH_SIZES {
788 visual.simulate_resize(size(px(width), px(height)));
789 collect(&mut visual, Some(TITLE_SEARCH));
790 let search = visual
791 .debug_bounds(TITLE_SEARCH)
792 .expect("title search rendered");
793 let search_center = f32::from(search.center().x);
794 eprintln!(
795 "title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",
796 describe(search),
797 width / 2.
798 );
799 if centered && (search_center - width / 2.).abs() > 1. {
800 found.push(format!(
801 "@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",
802 width / 2.
803 ));
804 }
805 if !contains(rectangle(0., 0., width, height), search) {
806 found.push(format!(
807 "@{width}x{height}: search {} leaves the window",
808 describe(search)
809 ));
810 }
811 for neighbour in TITLE_NEIGHBOURS {
812 match visual.debug_bounds(neighbour) {
813 None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),
814 Some(bounds) if overlaps(search, bounds) => found.push(format!(
815 "@{width}x{height}: search {} overlaps {neighbour} {}",
816 describe(search),
817 describe(bounds)
818 )),
819 Some(_) => {}
820 }
821 }
822 }
823 assert!(found.is_empty(), "{}", found.join("\n"));
824 }
825
826 #[gpui_kit::test]
827 fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
828 let (handle, app) = mount(cx);
829 let mut visual = VisualTestContext::from_window(handle, cx);
830 for (width, height) in SIZES {
831 visual.simulate_resize(size(px(width), px(height)));
832 visual.update(|_, cx| {
833 app.update(cx, |state, cx| {
834 let mut call = gallery_call();
835 call.conversation_id = Some(RECAP_MEETING_CHAT.to_owned());
836 call.chat_open = true;
837 state.call = Some(call);
838 cx.notify();
839 })
840 });
841 collect(&mut visual, Some(CHAT_PANEL_TAG));
842 let panel = visual
843 .debug_bounds(CHAT_PANEL_TAG)
844 .expect("chat panel rendered");
845 let bubbles: Vec<(usize, Bounds<Pixels>)> = BUBBLE_TAGS
846 .iter()
847 .enumerate()
848 .filter_map(|(index, tag)| visual.debug_bounds(tag).map(|bounds| (index, bounds)))
849 .collect();
850 assert!(!bubbles.is_empty(), "no bubbles rendered in the call chat");
851 let found: Vec<String> = bubbles
852 .into_iter()
853 .filter(|(_, bounds)| !contains(panel, *bounds))
854 .map(|(index, bounds)| {
855 format!(
856 "call-chat@{width}x{height}: bubble {index} {} leaves the chat panel {}",
857 describe(bounds),
858 describe(panel)
859 )
860 })
861 .collect();
862 visual.update(|_, cx| {
863 app.update(cx, |state, cx| {
864 state.call = None;
865 cx.notify();
866 })
867 });
868 assert!(found.is_empty(), "{}", found.join("\n"));
869 }
870 }
871
872 #[gpui_kit::test]
873 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
874 let (handle, state) = mount(cx);
875 let mut visual = VisualTestContext::from_window(handle, cx);
876 for (width, height) in SIZES {
877 visual.simulate_resize(size(px(width), px(height)));
878 let window = Bounds {
879 origin: point(px(0.), px(0.)),
880 size: size(px(width), px(height)),
881 };
882 visual.update(|_, cx| {
883 state.update(cx, |state, cx| {
884 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
885 })
886 });
887 collect(&mut visual, Some(RECAP_TAB));
888 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
889 visual.simulate_click(tab.center(), Default::default());
890 let tags = collect(&mut visual, Some(RECAP_REGION));
891 let mut expected = GUARDED.to_vec();
892 expected.extend([RECAP_TAB, RECAP_REGION]);
893 let found: Vec<String> = violations(&tags, window, &expected)
894 .into_iter()
895 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
896 .collect();
897 assert!(found.is_empty(), "{}", found.join("\n"));
898 }
899 }
900
901 #[gpui_kit::test]
902 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
903 let (handle, state) = mount_with(cx, true);
904 let mut visual = VisualTestContext::from_window(handle, cx);
905 for (width, height) in SIZES.into_iter().chain([(960., 640.)]) {
906 visual.simulate_resize(size(px(width), px(height)));
907 let window = Bounds {
908 origin: point(px(0.), px(0.)),
909 size: size(px(width), px(height)),
910 };
911 let inset = metrics(width, height).inset;
912 for section in SETTINGS_SECTIONS {
913 visual.update(|_, cx| {
914 state.update(cx, |state, cx| state.open_settings(section, cx))
915 });
916 let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
917 let found: Vec<String> = violations(&tags, window, SETTINGS_TAGS)
918 .into_iter()
919 .filter(|(key, _)| key.starts_with("settings"))
920 .map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
921 .collect();
922 assert!(found.is_empty(), "{}", found.join("\n"));
923 let dialog = visual.debug_bounds(SETTINGS_TAGS[0]).expect("settings dialog");
924 let edges = [
925 f32::from(dialog.left()),
926 f32::from(dialog.top()),
927 width - f32::from(dialog.right()),
928 height - f32::from(dialog.bottom()),
929 ];
930 assert!(
931 edges.iter().all(|edge| (edge - inset).abs() <= TOLERANCE),
932 "{section:?}@{width}x{height}: dialog edges {edges:?}, expected {inset}"
933 );
934 }
935 }
936 }
937
938 #[gpui_kit::test]
939 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
940 let (handle, state) = mount_with(cx, true);
941 let mut visual = VisualTestContext::from_window(handle, cx);
942 for (width, height) in SIZES {
943 visual.simulate_resize(size(px(width), px(height)));
944 let window = Bounds {
945 origin: point(px(0.), px(0.)),
946 size: size(px(width), px(height)),
947 };
948 for (chat, expected_tags) in [
949 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
950 (REACTION_CHAT, &AGENT_TAGS[3..]),
951 ] {
952 visual.update(|_, cx| {
953 state.update(cx, |state, cx| {
954 state.select(Selection::Chat(chat.to_owned()), cx)
955 })
956 });
957 let tags = collect(&mut visual, Some(expected_tags[0]));
958 let mut expected = GUARDED.to_vec();
959 expected.extend(expected_tags);
960 let found: Vec<String> = violations(&tags, window, &expected)
961 .into_iter()
962 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
963 .collect();
964 assert!(found.is_empty(), "{}", found.join("\n"));
965 }
966 }
967 }
968}
969
970#[test]
971fn lines_are_solid() {
972 let mut files = Vec::new();
973 for root in source_roots() {
974 source_files(&root, &mut files);
975 }
976 let violations: Vec<String> = files
977 .iter()
978 .filter(|file| !file.ends_with("layout_guard.rs"))
979 .flat_map(|file| {
980 let source = fs::read_to_string(file).expect("read source file");
981 source
982 .lines()
983 .enumerate()
984 .filter(|(_, line)| {
985 line.contains(".border_dashed(") || line.contains(".border_dotted(")
986 })
987 .map(|(index, line)| {
988 format!(
989 "{}:{}: lines are always solid: {}",
990 file.display(),
991 index + 1,
992 line.trim()
993 )
994 })
995 .collect::<Vec<_>>()
996 })
997 .collect();
998 assert!(violations.is_empty(), "{}", violations.join("\n"));
999}