BlueGit

ict rusty-teams

Files

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

layout_guard.rs

layout_guard.rs 71.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 = "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, ScrollDelta, ScrollWheelEvent, TestAppContext,
162 VisualTestContext, WindowOptions, point, 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::call::{ActiveCall, CallModel, ConsultCall};
173 use crate::demo;
174 use crate::settings::{item_selector, label, label_selector, metrics};
175 use crate::settings_section::SettingsSection;
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::{
180 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
181 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
182 };
183 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON};
184 use crate::views::message_row::BUBBLE_TAGS;
185 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
186 use crate::views::reaction_proposal_pill::REACTION_PILL;
187 use crate::views::recap_tab::RECAP_REGION;
188 use crate::views::shell::{
189 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
190 };
191 use crate::views::shortcuts::{
192 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
193 };
194 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
195 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
196
197 const GUARDED: &[&str] = &[
198 "shell",
199 "shell/title-bar",
200 "shell/title-bar/search",
201 "shell/title-bar/own-status",
202 "shell/title-bar/own-status/avatar",
203 OWN_AVATAR_DISC,
204 "shell/islands",
205 "shell/islands/rail",
206 "shell/islands/sidebar",
207 "shell/islands/main",
208 ];
209 const CALL_GUARDED: &[&str] = &[
210 "shell/islands/main/call-header",
211 "shell/islands/main/call-stage",
212 "shell/islands/main/call-controls",
213 "shell/islands/main/call-controls/mic",
214 "shell/islands/main/call-controls/leave",
215 ];
216 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
217 const CALLS_TAGS: &[&str] = &[
218 "shell/islands/sidebar/calls-actions",
219 "shell/islands/sidebar/calls-actions/meet-now",
220 "shell/islands/sidebar/calls-actions/new-meeting",
221 ];
222 const PREJOIN_TAGS: &[&str] = &[
223 "shell/islands/main/prejoin",
224 "shell/islands/main/prejoin/preview",
225 "shell/islands/main/prejoin/controls",
226 "shell/islands/main/prejoin/devices",
227 "shell/islands/main/prejoin/audio",
228 "shell/islands/main/prejoin/actions",
229 ];
230 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";
231 const CONSULT_GUARDED: &[&str] = &[
232 "shell/islands/main/call-header/call-consult",
233 "shell/islands/main/call-header/call-consult/transfer",
234 "shell/islands/main/call-header/call-consult/resume",
235 ];
236 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
237 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
238 const SHARE_GUARDED: &[&str] = &[
239 "shell/islands/main/call-stage/share-content",
240 "shell/islands/main/call-stage/share-content/zoom-chip",
241 "shell/islands/main/call-stage/share-divider",
242 "shell/islands/main/call-stage/share-strip",
243 ];
244 const OVERLAY_PANELS: &[&str] = &[CALL_TRANSCRIPT, PEOPLE_PANEL];
245 const OVERLAY_CHROME: &[&str] = &[
246 "shell/islands/main/call-header",
247 "shell/islands/main/call-stage",
248 ];
249 const MENU: &str = "popup-menu";
250 const OWN_STATUS: &str = "shell/title-bar/own-status";
251 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
252 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
253 const PROPOSAL_CHAT: &str = "demo-chat-release";
254 const REACTION_CHAT: &str = "demo-chat-mara";
255 const AGENT_TAGS: [&str; 4] = [
256 PROPOSAL_CARD,
257 PROPOSAL_THUMBNAILS,
258 PROPOSAL_BUTTONS,
259 REACTION_PILL,
260 ];
261 const SETTINGS_TAGS: &[&str] = &[
262 "settings",
263 "settings/nav",
264 "settings/nav/divider",
265 "settings/nav/about",
266 "settings/main",
267 "settings/main/header",
268 "settings/main/header/close",
269 "settings/main/body",
270 ];
271 const SETTINGS_BODY: &str = "settings/main/body";
272 const SETTINGS_NAV: &str = "settings/nav";
273 const SETTINGS_NAV_ABOUT: &str = "settings/nav/about";
274 const NAV_LABEL_SIZE: f32 = 14.;
275 const NAV_LINE_HEIGHT: f32 = 20.;
276 const SETTINGS_CONTENT: &str = "settings/main/body/content";
277 const MEMBERS_TAGS: &[&str] = &["chat-members-popup", "chat-members-popup/divider"];
278 const MEMBERS_CHAT: &str = "demo-chat-release";
279 const SIDEBAR: &str = "shell/islands/sidebar";
280 const MAIN: &str = "shell/islands/main";
281 const EDGE_DIVIDERS: &[&str] = &[SIDEBAR_SCROLL_DIVIDER, HEADER_DIVIDER];
282 const DIVIDER_SEGMENT: &str = "divider";
283 const DIVIDER_THICKNESS: f32 = 1.;
284 const INSET_TOLERANCE: f32 = 1.;
285 const INSET_RULES: &[InsetRule] = &[
286 InsetRule {
287 panel: "settings/nav",
288 content: "settings/nav/about",
289 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
290 },
291 InsetRule {
292 panel: "settings/main",
293 content: "settings/main/header/close",
294 edges: &[Edge::Top, Edge::Right],
295 },
296 ];
297 const SCROLLED_INSET_RULE: InsetRule = InsetRule {
298 panel: SETTINGS_BODY,
299 content: SETTINGS_CONTENT,
300 edges: &[Edge::Left, Edge::Bottom],
301 };
302 const SCROLLED_INSET_ALLOWLIST: &[(SettingsSection, &str)] = &[(
303 SettingsSection::Agents,
304 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
305 )];
306 const SETTINGS_SECTIONS: [SettingsSection; 9] = [
307 SettingsSection::General,
308 SettingsSection::Notifications,
309 SettingsSection::Appearance,
310 SettingsSection::Chats,
311 SettingsSection::Calls,
312 SettingsSection::Devices,
313 SettingsSection::Agents,
314 SettingsSection::Mcp,
315 SettingsSection::About,
316 ];
317 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
318 const TOLERANCE: f32 = 0.5;
319 const KNOWN_VIOLATIONS: &[&str] = &[];
320
321 type Tag = (&'static str, Bounds<Pixels>);
322
323 #[derive(Clone, Copy, Debug)]
324 enum Edge {
325 Top,
326 Right,
327 Bottom,
328 Left,
329 }
330
331 struct InsetRule {
332 panel: &'static str,
333 content: &'static str,
334 edges: &'static [Edge],
335 }
336
337 fn inset(panel: Bounds<Pixels>, content: Bounds<Pixels>, edge: Edge) -> f32 {
338 f32::from(match edge {
339 Edge::Top => content.top() - panel.top(),
340 Edge::Right => panel.right() - content.right(),
341 Edge::Bottom => panel.bottom() - content.bottom(),
342 Edge::Left => content.left() - panel.left(),
343 })
344 }
345
346 fn inset_violation(
347 rule: &InsetRule,
348 panel: Bounds<Pixels>,
349 content: Bounds<Pixels>,
350 ) -> Option<(String, String)> {
351 let insets: Vec<(Edge, f32)> = rule
352 .edges
353 .iter()
354 .map(|edge| (*edge, inset(panel, content, *edge)))
355 .collect();
356 let values = insets.iter().map(|(_, value)| *value);
357 let spread = values.clone().fold(f32::MIN, f32::max) - values.fold(f32::MAX, f32::min);
358 (spread > INSET_TOLERANCE).then(|| {
359 (
360 format!("{}:uneven-inset", rule.panel),
361 format!(
362 "{} insets {} by {insets:?}, they must match",
363 rule.panel, rule.content
364 ),
365 )
366 })
367 }
368
369 fn inset_violations(tags: &[Tag], rules: &[InsetRule]) -> Vec<(String, String)> {
370 let bounds_of = |path: &str| {
371 tags.iter()
372 .find(|(tag, _)| *tag == path)
373 .map(|(_, bounds)| *bounds)
374 };
375 rules
376 .iter()
377 .filter_map(
378 |rule| match (bounds_of(rule.panel), bounds_of(rule.content)) {
379 (Some(panel), Some(content)) => inset_violation(rule, panel, content),
380 _ => None,
381 },
382 )
383 .collect()
384 }
385
386 fn divider_violations(tags: &[Tag]) -> Vec<(String, String)> {
387 let mut found = Vec::new();
388 for (path, bounds) in tags {
389 let Some((parent, segment)) = path.rsplit_once('/') else {
390 continue;
391 };
392 if !segment.starts_with(DIVIDER_SEGMENT) {
393 continue;
394 }
395 let Some((_, panel)) = tags.iter().find(|(tag, _)| *tag == parent) else {
396 found.push((
397 format!("{path}:no-panel"),
398 format!("{path} needs its panel {parent} tagged"),
399 ));
400 continue;
401 };
402 let thin = |length: Pixels| f32::from(length) <= DIVIDER_THICKNESS + TOLERANCE;
403 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
404 let spans = if thin(bounds.size.height) {
405 near(bounds.left(), panel.left()) && near(bounds.right(), panel.right())
406 } else if thin(bounds.size.width) {
407 near(bounds.top(), panel.top()) && near(bounds.bottom(), panel.bottom())
408 } else {
409 false
410 };
411 if !spans {
412 found.push((
413 format!("{path}:short-divider"),
414 format!(
415 "{path} {} must be a {DIVIDER_THICKNESS} px line from edge to edge of {parent} {}",
416 describe(*bounds),
417 describe(*panel)
418 ),
419 ));
420 }
421 }
422 found
423 }
424
425 enum Screen {
426 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
427 StatusMenu,
428 Call,
429 Prejoin,
430 CallTranscript,
431 CallPeople,
432 CallShare,
433 CallConsult,
434 }
435
436 fn parent_of(path: &str) -> Option<&str> {
437 path.rsplit_once('/').map(|(parent, _)| parent)
438 }
439
440 fn contains(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
441 let tolerance = px(TOLERANCE);
442 inner.left() >= outer.left() - tolerance
443 && inner.top() >= outer.top() - tolerance
444 && inner.right() <= outer.right() + tolerance
445 && inner.bottom() <= outer.bottom() + tolerance
446 }
447
448 fn overlaps(first: Bounds<Pixels>, second: Bounds<Pixels>) -> bool {
449 let tolerance = px(TOLERANCE);
450 first.left() < second.right() - tolerance
451 && second.left() < first.right() - tolerance
452 && first.top() < second.bottom() - tolerance
453 && second.top() < first.bottom() - tolerance
454 }
455
456 fn describe(bounds: Bounds<Pixels>) -> String {
457 format!(
458 "[{:.1},{:.1} {:.1}x{:.1}]",
459 f32::from(bounds.origin.x),
460 f32::from(bounds.origin.y),
461 f32::from(bounds.size.width),
462 f32::from(bounds.size.height)
463 )
464 }
465
466 fn violations(
467 tags: &[Tag],
468 window: Bounds<Pixels>,
469 expected: &[&str],
470 ) -> Vec<(String, String)> {
471 let mut found = Vec::new();
472 let bounds_of = |path: &str| {
473 tags.iter()
474 .find(|(tag, _)| *tag == path)
475 .map(|(_, bounds)| *bounds)
476 };
477 for path in expected {
478 if bounds_of(path).is_none() {
479 found.push((
480 format!("{path}:missing"),
481 format!("{path} was not rendered"),
482 ));
483 }
484 }
485 for (path, bounds) in tags {
486 if !contains(window, *bounds) {
487 found.push((
488 format!("{path}:outside-window"),
489 format!(
490 "{path} {} leaves the window {}",
491 describe(*bounds),
492 describe(window)
493 ),
494 ));
495 }
496 if let Some(parent) =
497 parent_of(path).and_then(|parent| bounds_of(parent).map(|bounds| (parent, bounds)))
498 {
499 if !contains(parent.1, *bounds) {
500 found.push((
501 format!("{path}:outside-parent"),
502 format!(
503 "{path} {} leaves {} {}",
504 describe(*bounds),
505 parent.0,
506 describe(parent.1)
507 ),
508 ));
509 }
510 }
511 for (other, other_bounds) in tags {
512 let overlays = |first: &str, second: &str| {
513 OVERLAY_PANELS.contains(&first) && OVERLAY_CHROME.contains(&second)
514 };
515 let siblings = path < other
516 && parent_of(path).is_some()
517 && parent_of(path) == parent_of(other)
518 && !overlays(path, other)
519 && !overlays(other, path);
520 if siblings && overlaps(*bounds, *other_bounds) {
521 found.push((
522 format!("{path}:overlaps:{other}"),
523 format!(
524 "{path} {} overlaps {other} {}",
525 describe(*bounds),
526 describe(*other_bounds)
527 ),
528 ));
529 }
530 }
531 }
532 found.extend(divider_violations(tags));
533 found
534 }
535
536 const SETTLE_FRAMES: usize = 2;
537 const SETTLE_LIMIT: usize = 60;
538 const SETTLE_STEP: Duration = Duration::from_millis(50);
539
540 fn collect(visual: &mut VisualTestContext, awaited: Option<&'static str>) -> Vec<Tag> {
541 let mut frames = 0;
542 while frames < SETTLE_FRAMES
543 || awaited.is_some_and(|path| visual.debug_bounds(path).is_none())
544 {
545 assert!(frames < SETTLE_LIMIT, "{awaited:?} never rendered");
546 visual.executor().advance_clock(SETTLE_STEP);
547 std::thread::sleep(SETTLE_STEP);
548 visual.run_until_parked();
549 visual.update(|window, cx| window.render_frame(cx));
550 frames += 1;
551 }
552 GUARDED
553 .iter()
554 .chain(CALL_GUARDED)
555 .chain(CALLS_TAGS)
556 .chain(PREJOIN_TAGS)
557 .chain(SHARE_GUARDED)
558 .chain(CONSULT_GUARDED)
559 .chain([
560 &AGENTS_LIST,
561 &CALL_TRANSCRIPT,
562 &MENU,
563 &RECAP_TAB,
564 &RECAP_REGION,
565 &PEOPLE_PANEL,
566 ])
567 .chain(&AGENT_TAGS)
568 .chain(SETTINGS_TAGS)
569 .chain(MEMBERS_TAGS)
570 .chain(EDGE_DIVIDERS)
571 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
572 .collect()
573 }
574
575 fn sharing_call() -> ActiveCall {
576 let mut call = gallery_call();
577 call.model
578 .apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
579 call.share_stage.view.step_in((800., 450.));
580 call
581 }
582
583 fn gallery_call() -> ActiveCall {
584 let (handle, _control) = call_channel();
585 let mut model = CallModel::meeting("Standup", false);
586 model.apply(CallUpdate::State(CallState::Connected {
587 since: Instant::now(),
588 }));
589 model.apply(CallUpdate::Roster(
590 (0..11)
591 .map(|index| RosterEntry {
592 mri: format!("8:orgid:guard-{index}"),
593 display_name: format!("Guest {index}"),
594 muted: false,
595 in_lobby: false,
596 has_video: false,
597 sharing: false,
598 hand: None,
599 spotlight: None,
600 organizer: false,
601 ..Default::default()
602 })
603 .collect(),
604 ));
605 ActiveCall::new(1, model, handle.commands, None, handle.video)
606 }
607
608 fn consult_calls() -> (ActiveCall, ActiveCall) {
609 let connected = |id: u64, name: &str, mri: &str| {
610 let (handle, _control) = call_channel();
611 let mut model = CallModel::people(name, &[(mri.to_owned(), name.to_owned())]);
612 model.apply(CallUpdate::State(CallState::Connected {
613 since: Instant::now(),
614 }));
615 ActiveCall::new(id, model, handle.commands, None, handle.video)
616 };
617 let held = connected(1, "Christopher Montgomery-Lindqvist", "8:orgid:guard-held");
618 let mut consult = connected(2, "Jonas Ortega", "8:orgid:guard-consult");
619 consult.consult = Some(ConsultCall::new(
620 (
621 "8:orgid:guard-consult".to_owned(),
622 "Jonas Ortega".to_owned(),
623 ),
624 held.model.peer_name.clone(),
625 ));
626 (consult, held)
627 }
628
629 fn mount(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
630 mount_with(cx, false)
631 }
632
633 fn mount_with(
634 cx: &mut TestAppContext,
635 agent_api: bool,
636 ) -> (gpui_kit::AnyWindowHandle, Entity<AppState>) {
637 cx.update(gpui_kit::init);
638 cx.update(|cx| {
639 crate::theme::apply(cx);
640 bind_keys(cx);
641 let store = Store::open_in_memory().expect("in-memory store");
642 demo::seed(&store);
643 let store = Arc::new(store);
644 if agent_api {
645 crate::agent_api::init(store.clone(), true, cx);
646 }
647 let mode = Mode {
648 demo: true,
649 read_only: false,
650 demo_sync: None,
651 };
652 let state = cx.new(|_| AppState::new(store, mode));
653 install_globals(&state, UserInput::new(), cx);
654 crate::agents::install(state.clone(), cx);
655 demo::start_session(&state, cx);
656 let shared_state = state.clone();
657 let startup = Startup {
658 switcher_query: None,
659 composer_text: None,
660 reply_to_last: false,
661 };
662 let window = gpui_kit::open_window(WindowOptions::default(), cx, move |window, cx| {
663 cx.new(|cx| AppShell::new(state, None, startup, window, cx))
664 })
665 .expect("open test window")
666 .0;
667 (window, shared_state)
668 })
669 }
670
671 fn rectangle(left: f32, top: f32, width: f32, height: f32) -> Bounds<Pixels> {
672 Bounds {
673 origin: point(px(left), px(top)),
674 size: size(px(width), px(height)),
675 }
676 }
677
678 #[test]
679 fn rules_flag_overlap_and_overflow() {
680 let window = rectangle(0., 0., 100., 100.);
681 let tags: Vec<Tag> = vec![
682 ("shell", rectangle(0., 0., 100., 100.)),
683 ("shell/islands", rectangle(0., 0., 100., 50.)),
684 ("shell/islands/rail", rectangle(0., 0., 60., 50.)),
685 ("shell/islands/sidebar", rectangle(50., 0., 60., 50.)),
686 ];
687 let keys: Vec<String> = violations(&tags, window, &["shell/status-bar"])
688 .into_iter()
689 .map(|(key, _)| key)
690 .collect();
691 let line_tags: Vec<Tag> = vec![
692 ("panel", rectangle(0., 0., 100., 100.)),
693 ("panel/divider", rectangle(0., 50., 100., 1.)),
694 ("panel/divider-inset", rectangle(12., 60., 76., 1.)),
695 ("panel/divider-side", rectangle(40., 0., 1., 100.)),
696 ("panel/about", rectangle(12., 76., 76., 12.)),
697 ("panel/footer", rectangle(12., 64., 76., 12.)),
698 ];
699 let line_keys: Vec<String> = divider_violations(&line_tags)
700 .into_iter()
701 .chain(inset_violations(
702 &line_tags,
703 &[
704 InsetRule {
705 panel: "panel",
706 content: "panel/about",
707 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
708 },
709 InsetRule {
710 panel: "panel",
711 content: "panel/footer",
712 edges: &[Edge::Left, Edge::Bottom],
713 },
714 ],
715 ))
716 .map(|(key, _)| key)
717 .collect();
718 assert_eq!(
719 line_keys,
720 ["panel/divider-inset:short-divider", "panel:uneven-inset"]
721 );
722 assert_eq!(
723 keys,
724 [
725 "shell/status-bar:missing",
726 "shell/islands/rail:overlaps:shell/islands/sidebar",
727 "shell/islands/sidebar:outside-window",
728 "shell/islands/sidebar:outside-parent",
729 ]
730 );
731 }
732
733 #[gpui_kit::test]
734 fn no_element_overlaps_or_leaves_its_container(cx: &mut TestAppContext) {
735 let (handle, app) = mount(cx);
736 let mut visual = VisualTestContext::from_window(handle, cx);
737 let mut seen_known = HashSet::new();
738 let mut unexpected = Vec::new();
739 for (width, height) in SIZES {
740 visual.simulate_resize(size(px(width), px(height)));
741 let window = Bounds {
742 origin: point(px(0.), px(0.)),
743 size: size(px(width), px(height)),
744 };
745 let screens = [
746 Screen::Tab("chats", None),
747 Screen::Tab(
748 "activity",
749 Some(|visual| visual.dispatch_action(OpenActivity)),
750 ),
751 Screen::Tab(
752 "channels",
753 Some(|visual| visual.dispatch_action(OpenChannelsTab)),
754 ),
755 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
756 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
757 Screen::Tab("agents", Some(|visual| visual.dispatch_action(OpenAgents))),
758 Screen::Prejoin,
759 Screen::StatusMenu,
760 Screen::Call,
761 Screen::CallTranscript,
762 Screen::CallPeople,
763 Screen::CallShare,
764 Screen::CallConsult,
765 ];
766 for screen in screens {
767 let (screen_name, status_menu) = match screen {
768 Screen::Tab(name, open) => {
769 if let Some(open) = open {
770 open(&mut visual);
771 }
772 (name, false)
773 }
774 Screen::Call | Screen::CallPeople => {
775 let people_open = matches!(screen, Screen::CallPeople);
776 visual.update(|_, cx| {
777 app.update(cx, |state, cx| {
778 let mut call = gallery_call();
779 call.people_open = people_open;
780 state.call = Some(call);
781 cx.notify();
782 })
783 });
784 (if people_open { "call-people" } else { "call" }, false)
785 }
786 Screen::Prejoin => {
787 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
788 visual.update(|_, cx| {
789 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
790 });
791 ("prejoin", false)
792 }
793 Screen::CallTranscript => {
794 visual.update(|window, cx| {
795 app.update(cx, |state, cx| {
796 let mut call = gallery_call();
797 call.model.apply(CallUpdate::Captions(CaptionState::On));
798 for index in 0..40 {
799 call.model.note_caption(
800 CaptionEntry {
801 id: format!("guard-{index}"),
802 user_id: "8:orgid:guard-0".into(),
803 display_name: "Guest 0".into(),
804 text: "A long guarded sentence that has to wrap inside the panel".into(),
805 is_final: true,
806 },
807 Instant::now(),
808 );
809 }
810 call.transcript_open = true;
811 state.call = Some(call);
812 let app_entity = cx.entity();
813 state.transcript_panel = Some(cx.new(|cx| TranscriptPanel::new(app_entity, window, cx)).into());
814 cx.notify();
815 })
816 });
817 ("call-transcript", false)
818 }
819 Screen::CallShare => {
820 visual.update(|_, cx| {
821 app.update(cx, |state, cx| {
822 state.call = Some(sharing_call());
823 cx.notify();
824 })
825 });
826 ("call-share", false)
827 }
828 Screen::CallConsult => {
829 visual.update(|_, cx| {
830 app.update(cx, |state, cx| {
831 let (consult, held) = consult_calls();
832 state.call = Some(consult);
833 state.held_call = Some(held);
834 cx.notify();
835 })
836 });
837 ("call-consult", false)
838 }
839 Screen::StatusMenu => {
840 let tags = collect(&mut visual, None);
841 let button = tags
842 .iter()
843 .find(|(path, _)| *path == OWN_STATUS)
844 .map(|(_, bounds)| *bounds)
845 .expect("own status button rendered");
846 visual.simulate_click(button.center(), Default::default());
847 ("status-menu", true)
848 }
849 };
850 let is_call = matches!(
851 screen_name,
852 "call" | "call-people" | "call-transcript" | "call-share" | "call-consult"
853 );
854 let tags = collect(&mut visual, status_menu.then_some(MENU));
855 let mut expected = GUARDED.to_vec();
856 if is_call {
857 expected.extend(CALL_GUARDED);
858 let panel_open = matches!(screen_name, "call-people" | "call-transcript");
859 if sidebar_hidden_in_call(width, panel_open) {
860 expected.retain(|path| *path != "shell/islands/sidebar");
861 }
862 }
863 if screen_name == "call-transcript" {
864 expected.push(CALL_TRANSCRIPT);
865 }
866 if screen_name == "call-people" {
867 expected.push(PEOPLE_PANEL);
868 }
869 if screen_name == "call-share" {
870 expected.extend(SHARE_GUARDED);
871 }
872 if screen_name == "call-consult" {
873 expected.extend(CONSULT_GUARDED);
874 }
875 if status_menu {
876 expected.push(MENU);
877 }
878 match screen_name {
879 "calls" => expected.extend(CALLS_TAGS),
880 "agents" => expected.push(AGENTS_LIST),
881 "prejoin" => expected.extend(PREJOIN_TAGS),
882 _ => {}
883 }
884 let mut found = violations(&tags, window, &expected);
885 if status_menu {
886 let menu = tags
887 .iter()
888 .find(|(path, _)| *path == MENU)
889 .map(|(_, bounds)| *bounds);
890 let button = tags
891 .iter()
892 .find(|(path, _)| *path == OWN_STATUS)
893 .map(|(_, bounds)| *bounds);
894 if let (Some(menu), Some(button)) = (menu, button) {
895 if overlaps(menu, button) {
896 found.push((
897 format!("{MENU}:covers:{OWN_STATUS}"),
898 format!(
899 "{MENU} {} covers {OWN_STATUS} {}",
900 describe(menu),
901 describe(button)
902 ),
903 ));
904 }
905 }
906 visual.simulate_keystrokes("escape");
907 visual.run_until_parked();
908 }
909 if is_call {
910 visual.update(|_, cx| {
911 app.update(cx, |state, cx| {
912 state.call = None;
913 state.held_call = None;
914 cx.notify();
915 })
916 });
917 }
918 if screen_name == "prejoin" {
919 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
920 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
921 }
922 for (key, message) in found {
923 let full_key = format!("{screen_name}@{width}x{height}:{key}");
924 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
925 seen_known.insert(full_key);
926 } else {
927 unexpected.push(format!("{full_key}: {message}"));
928 }
929 }
930 }
931 }
932 let stale: Vec<String> = KNOWN_VIOLATIONS
933 .iter()
934 .filter(|key| !seen_known.contains(**key))
935 .map(|key| format!("stale known violation, remove it: {key}"))
936 .collect();
937 assert!(
938 unexpected.is_empty() && stale.is_empty(),
939 "{}",
940 unexpected
941 .into_iter()
942 .chain(stale)
943 .collect::<Vec<_>>()
944 .join("\n")
945 );
946 }
947 #[gpui_kit::test]
948 fn own_avatar_matches_the_teams_me_control(cx: &mut TestAppContext) {
949 let (handle, _) = mount(cx);
950 let mut visual = VisualTestContext::from_window(handle, cx);
951 visual.simulate_resize(size(px(1280.), px(800.)));
952 collect(&mut visual, Some(OWN_AVATAR_DISC));
953 let disc = visual
954 .debug_bounds(OWN_AVATAR_DISC)
955 .expect("own avatar rendered");
956 let bar = visual
957 .debug_bounds("shell/title-bar")
958 .expect("title bar rendered");
959 assert_eq!(
960 f32::from(disc.size.width),
961 TITLE_AVATAR_SIZE,
962 "{}",
963 describe(disc)
964 );
965 assert_eq!(
966 f32::from(disc.size.height),
967 TITLE_AVATAR_SIZE,
968 "{}",
969 describe(disc)
970 );
971 let top = f32::from(disc.top() - bar.top());
972 let bottom = f32::from(bar.bottom() - disc.bottom());
973 assert!(
974 (top - bottom).abs() <= 1.,
975 "own avatar {} is not centered in the title bar {}",
976 describe(disc),
977 describe(bar)
978 );
979 }
980
981 const TITLE_SEARCH: &str = "shell/title-bar/search";
982 const TITLE_NEIGHBOURS: &[&str] = &[
983 "shell/title-bar/leading",
984 "shell/title-bar/mode-pill",
985 "shell/title-bar/trailing",
986 "shell/title-bar/update",
987 OWN_STATUS,
988 ];
989 const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [
990 (1920., 1080., true),
991 (1280., 800., true),
992 (640., 480., false),
993 ];
994
995 #[gpui_kit::test]
996 fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {
997 let (handle, _) = mount(cx);
998 let mut visual = VisualTestContext::from_window(handle, cx);
999 let shell = visual.update(|window, cx| {
1000 window
1001 .root::<gpui_kit::base::Root>()
1002 .flatten()
1003 .and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())
1004 .expect("app shell is the root view")
1005 });
1006 visual.update(|_, cx| {
1007 shell.update(cx, |shell, cx| {
1008 shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)
1009 })
1010 });
1011 let mut found = Vec::new();
1012 for (width, height, centered) in TITLE_SEARCH_SIZES {
1013 visual.simulate_resize(size(px(width), px(height)));
1014 collect(&mut visual, Some(TITLE_SEARCH));
1015 let search = visual
1016 .debug_bounds(TITLE_SEARCH)
1017 .expect("title search rendered");
1018 let search_center = f32::from(search.center().x);
1019 eprintln!(
1020 "title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",
1021 describe(search),
1022 width / 2.
1023 );
1024 if centered && (search_center - width / 2.).abs() > 1. {
1025 found.push(format!(
1026 "@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",
1027 width / 2.
1028 ));
1029 }
1030 if !contains(rectangle(0., 0., width, height), search) {
1031 found.push(format!(
1032 "@{width}x{height}: search {} leaves the window",
1033 describe(search)
1034 ));
1035 }
1036 for neighbour in TITLE_NEIGHBOURS {
1037 match visual.debug_bounds(neighbour) {
1038 None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),
1039 Some(bounds) if overlaps(search, bounds) => found.push(format!(
1040 "@{width}x{height}: search {} overlaps {neighbour} {}",
1041 describe(search),
1042 describe(bounds)
1043 )),
1044 Some(_) => {}
1045 }
1046 }
1047 }
1048 assert!(found.is_empty(), "{}", found.join("\n"));
1049 }
1050
1051 #[gpui_kit::test]
1052 fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
1053 let (handle, app) = mount(cx);
1054 let mut visual = VisualTestContext::from_window(handle, cx);
1055 for (width, height) in SIZES {
1056 visual.simulate_resize(size(px(width), px(height)));
1057 visual.update(|_, cx| {
1058 app.update(cx, |state, cx| {
1059 let mut call = gallery_call();
1060 call.conversation_id = Some(RECAP_MEETING_CHAT.to_owned());
1061 call.chat_open = true;
1062 state.call = Some(call);
1063 cx.notify();
1064 })
1065 });
1066 collect(&mut visual, Some(CHAT_PANEL_TAG));
1067 let panel = visual
1068 .debug_bounds(CHAT_PANEL_TAG)
1069 .expect("chat panel rendered");
1070 let bubbles: Vec<(usize, Bounds<Pixels>)> = BUBBLE_TAGS
1071 .iter()
1072 .enumerate()
1073 .filter_map(|(index, tag)| visual.debug_bounds(tag).map(|bounds| (index, bounds)))
1074 .collect();
1075 assert!(!bubbles.is_empty(), "no bubbles rendered in the call chat");
1076 let found: Vec<String> = bubbles
1077 .into_iter()
1078 .filter(|(_, bounds)| {
1079 !inside_horizontally(panel, *bounds) || !overlaps(panel, *bounds)
1080 })
1081 .map(|(index, bounds)| {
1082 format!(
1083 "call-chat@{width}x{height}: bubble {index} {} leaves the chat panel {}",
1084 describe(bounds),
1085 describe(panel)
1086 )
1087 })
1088 .collect();
1089 visual.update(|_, cx| {
1090 app.update(cx, |state, cx| {
1091 state.call = None;
1092 cx.notify();
1093 })
1094 });
1095 assert!(found.is_empty(), "{}", found.join("\n"));
1096 }
1097 }
1098
1099 fn inside_horizontally(outer: Bounds<Pixels>, inner: Bounds<Pixels>) -> bool {
1100 let tolerance = px(TOLERANCE);
1101 inner.left() >= outer.left() - tolerance && inner.right() <= outer.right() + tolerance
1102 }
1103
1104 fn scroll_sidebar(visual: &mut VisualTestContext, delta: f32) {
1105 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1106 visual.simulate_event(ScrollWheelEvent {
1107 position: sidebar.center(),
1108 delta: ScrollDelta::Pixels(point(px(0.), px(delta))),
1109 ..Default::default()
1110 });
1111 }
1112
1113 #[gpui_kit::test]
1114 fn chat_list_line_shows_only_while_scrolled(cx: &mut TestAppContext) {
1115 let (handle, _) = mount(cx);
1116 let mut visual = VisualTestContext::from_window(handle, cx);
1117 for (width, height) in SIZES {
1118 visual.simulate_resize(size(px(width), px(height)));
1119 let window = Bounds {
1120 origin: point(px(0.), px(0.)),
1121 size: size(px(width), px(height)),
1122 };
1123 collect(&mut visual, None);
1124 scroll_sidebar(&mut visual, 100_000.);
1125 let tags = collect(&mut visual, None);
1126 assert!(
1127 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1128 "chat list at its top must not show the line at {width}x{height}"
1129 );
1130 scroll_sidebar(&mut visual, -120.);
1131 let scrolled = collect(&mut visual, Some(SIDEBAR_SCROLL_DIVIDER));
1132 let sidebar = visual.debug_bounds(SIDEBAR).expect("sidebar rendered");
1133 let line = visual
1134 .debug_bounds(SIDEBAR_SCROLL_DIVIDER)
1135 .expect("scrolled chat list shows the line");
1136 assert!(
1137 line.top() > sidebar.top() + px(TOLERANCE),
1138 "the line sits under the Chats header, not on the island edge: {} in {}",
1139 describe(line),
1140 describe(sidebar)
1141 );
1142 let found: Vec<String> = violations(&scrolled, window, &[SIDEBAR_SCROLL_DIVIDER])
1143 .into_iter()
1144 .chain(violations(&tags, window, &[]))
1145 .map(|(key, message)| format!("chat-list@{width}x{height}:{key}: {message}"))
1146 .collect();
1147 assert!(found.is_empty(), "{}", found.join("\n"));
1148 scroll_sidebar(&mut visual, 100_000.);
1149 collect(&mut visual, None);
1150 assert!(
1151 visual.debug_bounds(SIDEBAR_SCROLL_DIVIDER).is_none(),
1152 "the line goes away once the chat list is back at its top"
1153 );
1154 }
1155 }
1156
1157 #[gpui_kit::test]
1158 fn header_tabs_sit_above_the_header_line(cx: &mut TestAppContext) {
1159 let (handle, state) = mount(cx);
1160 let mut visual = VisualTestContext::from_window(handle, cx);
1161 for (width, height) in SIZES {
1162 visual.simulate_resize(size(px(width), px(height)));
1163 let window = Bounds {
1164 origin: point(px(0.), px(0.)),
1165 size: size(px(width), px(height)),
1166 };
1167 visual.update(|_, cx| {
1168 state.update(cx, |state, cx| {
1169 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1170 })
1171 });
1172 let tags = collect(&mut visual, Some(RECAP_TAB));
1173 let main = visual.debug_bounds(MAIN).expect("main island rendered");
1174 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1175 let line = visual
1176 .debug_bounds(HEADER_DIVIDER)
1177 .expect("the header line is always shown");
1178 let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
1179 assert!(
1180 tab.top() >= main.top() && near(tab.bottom(), line.top()),
1181 "tab {} must sit in the top bar above the line {}",
1182 describe(tab),
1183 describe(line)
1184 );
1185 let found: Vec<String> = violations(&tags, window, &[HEADER_DIVIDER, RECAP_TAB])
1186 .into_iter()
1187 .map(|(key, message)| format!("header@{width}x{height}:{key}: {message}"))
1188 .collect();
1189 assert!(found.is_empty(), "{}", found.join("\n"));
1190 }
1191 }
1192
1193 #[gpui_kit::test]
1194 fn recap_tab_stays_inside_the_main_island(cx: &mut TestAppContext) {
1195 let (handle, state) = mount(cx);
1196 let mut visual = VisualTestContext::from_window(handle, cx);
1197 for (width, height) in SIZES {
1198 visual.simulate_resize(size(px(width), px(height)));
1199 let window = Bounds {
1200 origin: point(px(0.), px(0.)),
1201 size: size(px(width), px(height)),
1202 };
1203 visual.update(|_, cx| {
1204 state.update(cx, |state, cx| {
1205 state.select(Selection::Chat(RECAP_MEETING_CHAT.to_owned()), cx)
1206 })
1207 });
1208 collect(&mut visual, Some(RECAP_TAB));
1209 let tab = visual.debug_bounds(RECAP_TAB).expect("recap tab rendered");
1210 visual.simulate_click(tab.center(), Default::default());
1211 let tags = collect(&mut visual, Some(RECAP_REGION));
1212 let mut expected = GUARDED.to_vec();
1213 expected.extend([RECAP_TAB, RECAP_REGION]);
1214 let found: Vec<String> = violations(&tags, window, &expected)
1215 .into_iter()
1216 .map(|(key, message)| format!("recap@{width}x{height}:{key}: {message}"))
1217 .collect();
1218 assert!(found.is_empty(), "{}", found.join("\n"));
1219 }
1220 }
1221
1222 #[gpui_kit::test]
1223 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1224 check_settings_dialog(cx, &SETTINGS_SECTIONS);
1225 }
1226
1227 #[gpui_kit::test]
1228 fn settings_dialog_keeps_its_inset_in_the_teams_scheme(cx: &mut TestAppContext) {
1229 crate::theme::set_thread_scheme(Some("teams"));
1230 check_settings_dialog(cx, &[SettingsSection::Appearance, SettingsSection::General]);
1231 crate::theme::set_thread_scheme(None);
1232 }
1233
1234 fn check_settings_dialog(cx: &mut TestAppContext, sections: &[SettingsSection]) {
1235 let (handle, state) = mount_with(cx, true);
1236 let mut visual = VisualTestContext::from_window(handle, cx);
1237 for (width, height) in SIZES.into_iter().chain([(960., 640.)]) {
1238 visual.simulate_resize(size(px(width), px(height)));
1239 let window = Bounds {
1240 origin: point(px(0.), px(0.)),
1241 size: size(px(width), px(height)),
1242 };
1243 let inset = metrics(width, height).inset;
1244 let label_sizes = NAV_LABEL_SIZES.contains(&(width, height));
1245 for &section in sections {
1246 visual
1247 .update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
1248 let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
1249 let mut found: Vec<(String, String)> = violations(&tags, window, SETTINGS_TAGS)
1250 .into_iter()
1251 .filter(|(key, _)| key.starts_with("settings"))
1252 .chain(inset_violations(&tags, INSET_RULES))
1253 .collect();
1254 if label_sizes {
1255 found.extend(nav_label_violations(&mut visual));
1256 }
1257 let scrolled_exempt = SCROLLED_INSET_ALLOWLIST
1258 .iter()
1259 .any(|(exempt, _)| *exempt == section);
1260 if !scrolled_exempt {
1261 found.extend(scrolled_inset_violation(&mut visual));
1262 }
1263 let found: Vec<String> = found
1264 .into_iter()
1265 .map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
1266 .collect();
1267 assert!(found.is_empty(), "{}", found.join("\n"));
1268 let dialog = visual
1269 .debug_bounds(SETTINGS_TAGS[0])
1270 .expect("settings dialog");
1271 let edges = [
1272 f32::from(dialog.left()),
1273 f32::from(dialog.top()),
1274 width - f32::from(dialog.right()),
1275 height - f32::from(dialog.bottom()),
1276 ];
1277 assert!(
1278 edges.iter().all(|edge| (edge - inset).abs() <= TOLERANCE),
1279 "{section:?}@{width}x{height}: dialog edges {edges:?}, expected {inset}"
1280 );
1281 }
1282 }
1283 }
1284
1285 const NAV_LABEL_SIZES: [(f32, f32); 3] = [(960., 640.), (1280., 800.), (1920., 1080.)];
1286
1287 fn nav_label_violations(visual: &mut VisualTestContext) -> Vec<(String, String)> {
1288 let Some(nav) = visual.debug_bounds(SETTINGS_NAV) else {
1289 return vec![(SETTINGS_NAV.to_owned(), "not rendered".to_owned())];
1290 };
1291 let mut found = Vec::new();
1292 for section in SETTINGS_SECTIONS {
1293 let label_path: &'static str = Box::leak(label_selector(section).into_boxed_str());
1294 let item_path: &'static str = if section == SettingsSection::About {
1295 SETTINGS_NAV_ABOUT
1296 } else {
1297 Box::leak(item_selector(section).into_boxed_str())
1298 };
1299 let (Some(label_bounds), Some(item)) = (
1300 visual.debug_bounds(label_path),
1301 visual.debug_bounds(item_path),
1302 ) else {
1303 if section != SettingsSection::Agents {
1304 found.push((label_path.to_owned(), "not rendered".to_owned()));
1305 }
1306 continue;
1307 };
1308 let text = label(section);
1309 let text_width = visual.update(|window, _| {
1310 let run = window.text_style().to_run(text.len());
1311 f32::from(
1312 window
1313 .text_system()
1314 .shape_line(text.into(), px(NAV_LABEL_SIZE), &[run], None)
1315 .width,
1316 )
1317 });
1318 let label_width = f32::from(label_bounds.size.width);
1319 let label_height = f32::from(label_bounds.size.height);
1320 if text_width > label_width + TOLERANCE
1321 && label_height < 2. * NAV_LINE_HEIGHT - TOLERANCE
1322 {
1323 found.push((
1324 label_path.to_owned(),
1325 format!("{text:?} needs {text_width} px, has {label_width} px on one line: truncated"),
1326 ));
1327 }
1328 let outside = |inner: Bounds<Pixels>, outer: Bounds<Pixels>| {
1329 inner.left() < outer.left() - px(TOLERANCE)
1330 || inner.right() > outer.right() + px(TOLERANCE)
1331 || inner.top() < outer.top() - px(TOLERANCE)
1332 || inner.bottom() > outer.bottom() + px(TOLERANCE)
1333 };
1334 if outside(label_bounds, item) {
1335 found.push((
1336 label_path.to_owned(),
1337 format!("label {label_bounds:?} outside item {item:?}"),
1338 ));
1339 }
1340 if item.left() < nav.left() || item.right() > nav.right() {
1341 found.push((
1342 item_path.to_owned(),
1343 format!("item {item:?} outside nav {nav:?}"),
1344 ));
1345 }
1346 }
1347 found
1348 }
1349
1350 fn scrolled_inset_violation(visual: &mut VisualTestContext) -> Option<(String, String)> {
1351 let body = visual.debug_bounds(SETTINGS_BODY)?;
1352 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1353 if content.bottom() <= body.bottom() {
1354 return None;
1355 }
1356 visual.simulate_event(ScrollWheelEvent {
1357 position: body.center(),
1358 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1359 ..Default::default()
1360 });
1361 collect(visual, None);
1362 let body = visual.debug_bounds(SETTINGS_BODY)?;
1363 let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1364 inset_violation(&SCROLLED_INSET_RULE, body, content)
1365 }
1366
1367 #[gpui_kit::test]
1368 fn members_popup_lines_reach_the_edges(cx: &mut TestAppContext) {
1369 let (handle, state) = mount(cx);
1370 let mut visual = VisualTestContext::from_window(handle, cx);
1371 for (width, height) in SIZES {
1372 visual.simulate_resize(size(px(width), px(height)));
1373 let window = Bounds {
1374 origin: point(px(0.), px(0.)),
1375 size: size(px(width), px(height)),
1376 };
1377 visual.update(|_, cx| {
1378 state.update(cx, |state, cx| {
1379 state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1380 })
1381 });
1382 collect(&mut visual, Some(MEMBERS_BUTTON));
1383 let button = visual
1384 .debug_bounds(MEMBERS_BUTTON)
1385 .expect("members button rendered");
1386 visual.simulate_click(button.center(), Default::default());
1387 let tags = collect(&mut visual, Some(MEMBERS_TAGS[0]));
1388 let found: Vec<String> = violations(&tags, window, MEMBERS_TAGS)
1389 .into_iter()
1390 .filter(|(key, _)| key.starts_with("chat-members"))
1391 .map(|(key, message)| format!("members@{width}x{height}:{key}: {message}"))
1392 .collect();
1393 visual.simulate_keystrokes("escape");
1394 visual.run_until_parked();
1395 assert!(found.is_empty(), "{}", found.join("\n"));
1396 }
1397 }
1398
1399 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1400 collect(visual, Some(COMPOSER_SEND_TAG));
1401 let mut bounds_of = |path: &'static str| {
1402 visual
1403 .debug_bounds(path)
1404 .unwrap_or_else(|| panic!("{path} rendered"))
1405 };
1406 let composer = bounds_of(COMPOSER_BOX_TAG);
1407 let leading = bounds_of(COMPOSER_LEADING_TAG);
1408 let send = bounds_of(COMPOSER_SEND_TAG);
1409 [
1410 f32::from(leading.left() - composer.left()),
1411 f32::from(leading.top() - composer.top()),
1412 f32::from(composer.bottom() - leading.bottom()),
1413 f32::from(composer.right() - send.right()),
1414 f32::from(send.top() - composer.top()),
1415 f32::from(composer.bottom() - send.bottom()),
1416 ]
1417 }
1418
1419 #[gpui_kit::test]
1420 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
1421 let (handle, _) = mount(cx);
1422 let mut visual = VisualTestContext::from_window(handle, cx);
1423 visual.simulate_resize(size(px(1280.), px(800.)));
1424 let single_line = composer_button_insets(&mut visual);
1425 let left = single_line[0];
1426 assert!(
1427 single_line
1428 .iter()
1429 .all(|inset| (inset - left).abs() < TOLERANCE),
1430 "single line: insets left, top, bottom of the first button and right, top, bottom of send {single_line:?}"
1431 );
1432 let leading = visual
1433 .debug_bounds(COMPOSER_LEADING_TAG)
1434 .expect("leading buttons");
1435 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
1436 visual.simulate_click(
1437 point((leading.right() + send.left()) / 2., send.center().y),
1438 Default::default(),
1439 );
1440 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
1441 let three_lines = composer_button_insets(&mut visual);
1442 assert!(
1443 three_lines[1] > single_line[1] + 30.,
1444 "three lines did not grow the composer: {three_lines:?}"
1445 );
1446 for inset in [
1447 three_lines[0],
1448 three_lines[2],
1449 three_lines[3],
1450 three_lines[5],
1451 ] {
1452 assert!(
1453 (inset - left).abs() < TOLERANCE,
1454 "three lines: insets left, top, bottom of the first button and right, top, bottom of send {three_lines:?}, expected {left}"
1455 );
1456 }
1457 }
1458
1459 #[gpui_kit::test]
1460 fn the_format_bar_divider_runs_edge_to_edge_inside_the_composer(cx: &mut TestAppContext) {
1461 const FORMAT_TAGS: [&str; 6] = [
1462 COMPOSER_BOX_TAG,
1463 COMPOSER_FORMAT_BAR_TAG,
1464 COMPOSER_FORMAT_DIVIDER_TAG,
1465 COMPOSER_LEADING_TAG,
1466 COMPOSER_FORMAT_TAG,
1467 COMPOSER_SEND_TAG,
1468 ];
1469 let (handle, _) = mount(cx);
1470 let mut visual = VisualTestContext::from_window(handle, cx);
1471 for (width, height) in SIZES {
1472 visual.simulate_resize(size(px(width), px(height)));
1473 let window = Bounds {
1474 origin: point(px(0.), px(0.)),
1475 size: size(px(width), px(height)),
1476 };
1477 collect(&mut visual, Some(COMPOSER_FORMAT_TAG));
1478 let toggle = visual
1479 .debug_bounds(COMPOSER_FORMAT_TAG)
1480 .expect("format button");
1481 visual.simulate_click(toggle.center(), Default::default());
1482 collect(&mut visual, Some(COMPOSER_FORMAT_DIVIDER_TAG));
1483 let tags: Vec<Tag> = FORMAT_TAGS
1484 .iter()
1485 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
1486 .collect();
1487 let found: Vec<String> = violations(&tags, window, &FORMAT_TAGS)
1488 .into_iter()
1489 .map(|(key, message)| format!("format@{width}x{height}:{key}: {message}"))
1490 .collect();
1491 let bar = visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).expect("bar");
1492 let leading = visual.debug_bounds(COMPOSER_LEADING_TAG).expect("leading");
1493 let toggle = visual
1494 .debug_bounds(COMPOSER_FORMAT_TAG)
1495 .expect("format button");
1496 visual.simulate_click(toggle.center(), Default::default());
1497 collect(&mut visual, None);
1498 assert!(found.is_empty(), "{}", found.join("\n"));
1499 assert!(
1500 bar.bottom() <= leading.top(),
1501 "bar {bar:?} over the buttons {leading:?}"
1502 );
1503 assert!(visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).is_none());
1504 }
1505 }
1506
1507 #[gpui_kit::test]
1508 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
1509 let (handle, state) = mount_with(cx, true);
1510 let mut visual = VisualTestContext::from_window(handle, cx);
1511 for (width, height) in SIZES {
1512 visual.simulate_resize(size(px(width), px(height)));
1513 let window = Bounds {
1514 origin: point(px(0.), px(0.)),
1515 size: size(px(width), px(height)),
1516 };
1517 for (chat, expected_tags) in [
1518 (PROPOSAL_CHAT, &AGENT_TAGS[..3]),
1519 (REACTION_CHAT, &AGENT_TAGS[3..]),
1520 ] {
1521 visual.update(|_, cx| {
1522 state.update(cx, |state, cx| {
1523 state.select(Selection::Chat(chat.to_owned()), cx)
1524 })
1525 });
1526 let tags = collect(&mut visual, Some(expected_tags[0]));
1527 let mut expected = GUARDED.to_vec();
1528 expected.extend(expected_tags);
1529 let found: Vec<String> = violations(&tags, window, &expected)
1530 .into_iter()
1531 .map(|(key, message)| format!("{chat}@{width}x{height}:{key}: {message}"))
1532 .collect();
1533 assert!(found.is_empty(), "{}", found.join("\n"));
1534 }
1535 }
1536 }
1537}
1538
1539#[test]
1540fn lines_are_solid() {
1541 let mut files = Vec::new();
1542 for root in source_roots() {
1543 source_files(&root, &mut files);
1544 }
1545 let violations: Vec<String> = files
1546 .iter()
1547 .filter(|file| !file.ends_with("layout_guard.rs"))
1548 .flat_map(|file| {
1549 let source = fs::read_to_string(file).expect("read source file");
1550 source
1551 .lines()
1552 .enumerate()
1553 .filter(|(_, line)| {
1554 line.contains(".border_dashed(") || line.contains(".border_dotted(")
1555 })
1556 .map(|(index, line)| {
1557 format!(
1558 "{}:{}: lines are always solid: {}",
1559 file.display(),
1560 index + 1,
1561 line.trim()
1562 )
1563 })
1564 .collect::<Vec<_>>()
1565 })
1566 .collect();
1567 assert!(violations.is_empty(), "{}", violations.join("\n"));
1568}
1569
1570const STATE_RING_COLORS: &[&str] = &[
1571 "if focused",
1572 "if selected",
1573 "if speaking",
1574 "if current",
1575 "if open",
1576 "if state.failed",
1577];
1578const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
1579 (
1580 "notify/ring_view.rs",
1581 "theme::green()",
1582 "state signal (pulsing ring around the caller while it rings), not a resting outline",
1583 ),
1584 (
1585 "notify/meeting_view.rs",
1586 "theme::border_strong()",
1587 "outlined button, not a surface",
1588 ),
1589 (
1590 "settings/mcp.rs",
1591 "theme::border_strong()",
1592 "outlined button, not a surface",
1593 ),
1594 (
1595 "settings/rows.rs",
1596 "theme::border_strong()",
1597 "outlined button, not a surface",
1598 ),
1599 (
1600 "views/card_widgets.rs",
1601 "border)",
1602 "message content drawn as Teams renders it",
1603 ),
1604 (
1605 "views/card_widgets.rs",
1606 "theme::border_strong()",
1607 "message content drawn as Teams renders it",
1608 ),
1609 ("views/shared_tab.rs", "theme::accent()", "input field"),
1610 ("views/card_input.rs", "if error.is_some()", "input field"),
1611 ("views/format_toolbar.rs", "if refused", "input field"),
1612 (
1613 "views/card_code_block.rs",
1614 "theme::code_header_border()",
1615 "message content drawn as Teams renders it",
1616 ),
1617 ("views/call_transcript.rs", "theme::border()", "input field"),
1618 (
1619 "views/conversation.rs",
1620 "theme::accent()",
1621 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1622 ),
1623 (
1624 "views/attachment_tray.rs",
1625 "theme::accent()",
1626 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1627 ),
1628 (
1629 "views/card_carousel.rs",
1630 "theme::border_strong()",
1631 "message content drawn as Teams renders it",
1632 ),
1633 (
1634 "views/card_table.rs",
1635 "grid_color",
1636 "message content drawn as Teams renders it",
1637 ),
1638 (
1639 "views/activity_panel.rs",
1640 "theme::surface()",
1641 "cutout ring in the background color, invisible against its surface",
1642 ),
1643 (
1644 "views/avatar.rs",
1645 "theme::surface()",
1646 "cutout ring in the background color, invisible against its surface",
1647 ),
1648 (
1649 "views/avatar.rs",
1650 "theme::text_muted()",
1651 "offline presence glyph, Teams icon",
1652 ),
1653 (
1654 "views/message_row.rs",
1655 "theme::border_strong()",
1656 "deleted message placeholder, Teams look",
1657 ),
1658 (
1659 "views/message_row.rs",
1660 "theme::red()",
1661 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1662 ),
1663 (
1664 "views/message_row.rs",
1665 "if row.delivery",
1666 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1667 ),
1668 (
1669 "views/new_meeting_dialog.rs",
1670 "theme::border()",
1671 "input field",
1672 ),
1673 (
1674 "views/call_mini_window.rs",
1675 "theme::border_strong()",
1676 "self view over live video, needs an edge on any picture",
1677 ),
1678 ("views/transfer_picker.rs", "theme::border()", "input field"),
1679 (
1680 "views/call_notice.rs",
1681 "theme::border_strong()",
1682 "outlined button, not a surface",
1683 ),
1684 (
1685 "views/composer/schedule.rs",
1686 "theme::accent()",
1687 "input field",
1688 ),
1689 (
1690 "views/call_mini.rs",
1691 "border)",
1692 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1693 ),
1694 (
1695 "views/sidebar.rs",
1696 "theme::accent()",
1697 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1698 ),
1699 (
1700 "views/adaptive_card.rs",
1701 "theme::border()",
1702 "message content drawn as Teams renders it",
1703 ),
1704 (
1705 "views/adaptive_card.rs",
1706 "border)",
1707 "message content drawn as Teams renders it",
1708 ),
1709 (
1710 "views/share_bar.rs",
1711 "theme::red()",
1712 "state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1713 ),
1714 ("settings_controls.rs", "if invalid", "input field"),
1715];
1716
1717fn outlines(source: &str) -> Vec<(usize, String)> {
1718 let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");
1719 pattern
1720 .find_iter(source)
1721 .map(|found| {
1722 let line_number = source[..found.start()].matches('\n').count() + 1;
1723 let after = &source[found.end()..];
1724 let color = after
1725 .find(".border_color(")
1726 .filter(|position| *position < 120)
1727 .map(|position| {
1728 let start = &after[position + ".border_color(".len()..];
1729 start
1730 .lines()
1731 .map(str::trim)
1732 .find(|line| !line.is_empty())
1733 .unwrap_or_default()
1734 .to_owned()
1735 })
1736 .unwrap_or_default();
1737 (line_number, color)
1738 })
1739 .collect()
1740}
1741
1742#[test]
1743fn outline_matcher_reads_the_border_color() {
1744 let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";
1745 assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);
1746}
1747
1748#[test]
1749fn surfaces_are_soft() {
1750 let mut matched_allowlist = HashSet::new();
1751 let mut violations = Vec::new();
1752 for root in source_roots() {
1753 let mut files = Vec::new();
1754 source_files(&root, &mut files);
1755 for file in files {
1756 let relative = file
1757 .strip_prefix(&root)
1758 .expect("inside src")
1759 .to_string_lossy()
1760 .replace('\\', "/");
1761 if relative == "layout_guard.rs" {
1762 continue;
1763 }
1764 let source = fs::read_to_string(&file).expect("read source file");
1765 for (line_number, color) in outlines(&source) {
1766 if STATE_RING_COLORS
1767 .iter()
1768 .any(|prefix| color.starts_with(prefix))
1769 {
1770 continue;
1771 }
1772 match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {
1773 *allowed_file == relative && color.starts_with(prefix)
1774 }) {
1775 Some(position) => {
1776 matched_allowlist.insert(position);
1777 }
1778 None => violations.push(format!(
1779 "{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"
1780 )),
1781 }
1782 }
1783 }
1784 }
1785 let stale = OUTLINE_ALLOWLIST
1786 .iter()
1787 .enumerate()
1788 .filter(|(position, _)| !matched_allowlist.contains(position))
1789 .map(|(_, (file, prefix, _))| {
1790 format!("stale outline allowlist entry, remove it: {file} {prefix}")
1791 });
1792 let report: Vec<String> = violations.into_iter().chain(stale).collect();
1793 assert!(report.is_empty(), "{}", report.join("\n"));
1794}
1795
1796fn indentation(line: &str) -> usize {
1797 line.len() - line.trim_start().len()
1798}
1799
1800fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
1801 let indent = indentation(lines[index]);
1802 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
1803 let start = lines[..index]
1804 .iter()
1805 .rposition(|line| !belongs(line))
1806 .map_or(0, |position| position + 1);
1807 let end = lines[index..]
1808 .iter()
1809 .position(|line| !belongs(line))
1810 .map_or(lines.len(), |position| index + position);
1811 lines[start..end]
1812 .iter()
1813 .filter(|line| indentation(line) == indent)
1814 .copied()
1815 .collect()
1816}
1817
1818fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
1819 let lines: Vec<&str> = source.lines().collect();
1820 (0..lines.len())
1821 .filter(|&index| row_height.is_match(lines[index]))
1822 .filter(|&index| {
1823 !chain_lines(&lines, index).iter().any(|line| {
1824 let line = line.trim();
1825 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
1826 })
1827 })
1828 .map(|index| index + 1)
1829 .collect()
1830}
1831
1832fn row_height_pattern() -> Regex {
1833 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
1834}
1835
1836#[test]
1837fn matcher_finds_rows_without_flex_none() {
1838 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";
1839 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
1840}
1841
1842#[test]
1843fn fixed_height_rows_never_shrink() {
1844 let row_height = row_height_pattern();
1845 let mut files = Vec::new();
1846 for root in source_roots() {
1847 source_files(&root, &mut files);
1848 }
1849 let violations: Vec<String> = files
1850 .iter()
1851 .filter(|file| !file.ends_with("layout_guard.rs"))
1852 .flat_map(|file| {
1853 let source = fs::read_to_string(file).expect("read source file");
1854 shrinking_rows(&row_height, &source)
1855 .into_iter()
1856 .map(|line| format!("{}:{line}", file.display()))
1857 .collect::<Vec<_>>()
1858 })
1859 .collect();
1860 assert!(
1861 violations.is_empty(),
1862 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
1863 );
1864}