BlueGit

ict rusty-teams

Files

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

layout_guard.rs

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