BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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