| 1 | use std::{ |
| 2 | cell::RefCell, |
| 3 | rc::Rc, |
| 4 | sync::{Arc, Mutex}, |
| 5 | }; |
| 6 | |
| 7 | use gpui::{ |
| 8 | AnyElement, App, AvailableSpace, Bounds, CursorStyle, Element, ElementId, GlobalElementId, |
| 9 | Hitbox, HitboxBehavior, InspectorElementId, IntoElement, LayoutId, MouseButton, MouseDownEvent, |
| 10 | ParentElement, Pixels, Refineable as _, Role, SharedString, Size, Styled, StyledText, |
| 11 | TextStyle, Window, div, px, size, |
| 12 | }; |
| 13 | |
| 14 | use super::{ |
| 15 | InlineElement, TextViewMultiClickKind, inline::point_in_text_selection, state::LineSpan, |
| 16 | }; |
| 17 | use crate::GlobalState; |
| 18 | |
| 19 | #[derive(Clone, Copy, Debug)] |
| 20 | pub(super) struct InlineMetrics { |
| 21 | pub size: Size<Pixels>, |
| 22 | pub baseline: Pixels, |
| 23 | } |
| 24 | |
| 25 | impl InlineMetrics { |
| 26 | fn is_valid(self) -> bool { |
| 27 | let width = f32::from(self.size.width); |
| 28 | let height = f32::from(self.size.height); |
| 29 | let baseline = f32::from(self.baseline); |
| 30 | width.is_finite() |
| 31 | && height.is_finite() |
| 32 | && baseline.is_finite() |
| 33 | && width > 0. |
| 34 | && height > 0. |
| 35 | && baseline >= 0. |
| 36 | && baseline <= height |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | /// Geometry can be cloned during wrapping; the frame's element is consumed once. |
| 41 | #[derive(Clone)] |
| 42 | pub(super) struct MeasuredInlineObject { |
| 43 | pub metrics: InlineMetrics, |
| 44 | content: Option<Rc<RefCell<Option<AnyElement>>>>, |
| 45 | text: SharedString, |
| 46 | font_size: Pixels, |
| 47 | text_style: TextStyle, |
| 48 | } |
| 49 | |
| 50 | impl MeasuredInlineObject { |
| 51 | /// Must run before entering a GPUI measured-layout callback: native element |
| 52 | /// layout itself uses the window's layout engine. |
| 53 | pub fn measure( |
| 54 | text: &str, |
| 55 | presentation: Option<InlineElement>, |
| 56 | style: &TextStyle, |
| 57 | window: &mut Window, |
| 58 | cx: &mut App, |
| 59 | ) -> Self { |
| 60 | let font_size = style.font_size.to_pixels(window.rem_size()); |
| 61 | let text: SharedString = text.replace(['\r', '\n'], " ").into(); |
| 62 | let line = window.text_system().shape_line( |
| 63 | text.clone(), |
| 64 | font_size, |
| 65 | &[style.to_run(text.len())], |
| 66 | None, |
| 67 | ); |
| 68 | let height = style |
| 69 | .line_height_in_pixels(window.rem_size()) |
| 70 | .max(line.ascent + line.descent); |
| 71 | let fallback = InlineMetrics { |
| 72 | size: size(line.width.max(px(1.)), height), |
| 73 | baseline: (height - line.ascent - line.descent) / 2. + line.ascent, |
| 74 | }; |
| 75 | let mut result = Self { |
| 76 | metrics: fallback, |
| 77 | content: None, |
| 78 | text, |
| 79 | font_size, |
| 80 | text_style: style.clone(), |
| 81 | }; |
| 82 | if let Some(presentation) = presentation { |
| 83 | // The wrapper carries inherited marks into both layout and painting. |
| 84 | let mut wrapper = div().child(presentation.element); |
| 85 | wrapper.style().text = style.subtract(&Default::default()); |
| 86 | let mut element = wrapper.into_any_element(); |
| 87 | let measured = element.layout_as_root( |
| 88 | size(AvailableSpace::MaxContent, AvailableSpace::MaxContent), |
| 89 | window, |
| 90 | cx, |
| 91 | ); |
| 92 | let metrics = InlineMetrics { |
| 93 | size: measured, |
| 94 | baseline: presentation.baseline.unwrap_or( |
| 95 | (measured.height - (fallback.size.height - fallback.baseline)) |
| 96 | .max(Pixels::ZERO), |
| 97 | ), |
| 98 | }; |
| 99 | if metrics.is_valid() { |
| 100 | result.metrics = metrics; |
| 101 | result.content = Some(Rc::new(RefCell::new(Some(element)))); |
| 102 | } |
| 103 | } |
| 104 | result |
| 105 | } |
| 106 | |
| 107 | pub fn fit_text(mut self, width: Option<Pixels>) -> Self { |
| 108 | // GPUI has no general subtree scale. Only our own plain-text fallback |
| 109 | // can be proportionally fitted; custom elements retain their real size. |
| 110 | if self.content.is_none() { |
| 111 | let scale = width.map_or(1., |width| { |
| 112 | (width.max(Pixels::ZERO) / self.metrics.size.width).min(1.) |
| 113 | }); |
| 114 | self.metrics.size = size( |
| 115 | self.metrics.size.width * scale, |
| 116 | self.metrics.size.height * scale, |
| 117 | ); |
| 118 | self.metrics.baseline *= scale; |
| 119 | self.font_size *= scale; |
| 120 | } |
| 121 | self |
| 122 | } |
| 123 | |
| 124 | fn element(&self) -> (AnyElement, bool) { |
| 125 | if let Some(content) = &self.content { |
| 126 | return ( |
| 127 | content |
| 128 | .borrow_mut() |
| 129 | .take() |
| 130 | .expect("inline element painted once per frame"), |
| 131 | true, |
| 132 | ); |
| 133 | } |
| 134 | let text = StyledText::new(self.text.clone()) |
| 135 | .with_runs(vec![self.text_style.to_run(self.text.len())]); |
| 136 | ( |
| 137 | div() |
| 138 | .w(self.metrics.size.width) |
| 139 | .h(self.metrics.size.height) |
| 140 | .text_size(self.font_size) |
| 141 | .line_height(self.metrics.size.height) |
| 142 | .whitespace_nowrap() |
| 143 | .overflow_hidden() |
| 144 | .child(text) |
| 145 | .into_any_element(), |
| 146 | false, |
| 147 | ) |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | /// Atomic selection wrapper that leaves child styling and interaction to GPUI. |
| 152 | pub(super) struct InlineObject { |
| 153 | id: ElementId, |
| 154 | text: SharedString, |
| 155 | accessibility_label: SharedString, |
| 156 | object: MeasuredInlineObject, |
| 157 | selected: Arc<Mutex<bool>>, |
| 158 | selection_bounds: Bounds<Pixels>, |
| 159 | line_bounds: Bounds<Pixels>, |
| 160 | content: AnyElement, |
| 161 | content_measured: bool, |
| 162 | link: Option<super::node::LinkMark>, |
| 163 | link_click_handler: Option<Arc<super::text_view::LinkClickHandlerFn>>, |
| 164 | } |
| 165 | |
| 166 | impl InlineObject { |
| 167 | pub fn link( |
| 168 | mut self, |
| 169 | link: Option<super::node::LinkMark>, |
| 170 | handler: Option<Arc<super::text_view::LinkClickHandlerFn>>, |
| 171 | ) -> Self { |
| 172 | self.link = link; |
| 173 | self.link_click_handler = handler; |
| 174 | self |
| 175 | } |
| 176 | |
| 177 | pub fn new( |
| 178 | id: impl Into<ElementId>, |
| 179 | text: SharedString, |
| 180 | accessibility_label: SharedString, |
| 181 | object: MeasuredInlineObject, |
| 182 | selected: Arc<Mutex<bool>>, |
| 183 | selection_bounds: Bounds<Pixels>, |
| 184 | line_bounds: Bounds<Pixels>, |
| 185 | ) -> Self { |
| 186 | let (content, content_measured) = object.element(); |
| 187 | Self { |
| 188 | id: id.into(), |
| 189 | text, |
| 190 | accessibility_label, |
| 191 | object, |
| 192 | selected, |
| 193 | selection_bounds, |
| 194 | line_bounds, |
| 195 | content, |
| 196 | content_measured, |
| 197 | link: None, |
| 198 | link_click_handler: None, |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | impl IntoElement for InlineObject { |
| 204 | type Element = Self; |
| 205 | fn into_element(self) -> Self { |
| 206 | self |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | impl Element for InlineObject { |
| 211 | type RequestLayoutState = (); |
| 212 | type PrepaintState = Hitbox; |
| 213 | fn id(&self) -> Option<ElementId> { |
| 214 | Some(self.id.clone()) |
| 215 | } |
| 216 | fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { |
| 217 | None |
| 218 | } |
| 219 | |
| 220 | fn a11y_role(&self) -> Option<Role> { |
| 221 | Some(Role::GenericContainer) |
| 222 | } |
| 223 | |
| 224 | fn write_a11y_info(&self, node: &mut gpui::accesskit::Node) { |
| 225 | node.set_role(Role::GenericContainer); |
| 226 | node.set_label(self.accessibility_label.as_ref()); |
| 227 | node.set_read_only(); |
| 228 | } |
| 229 | |
| 230 | fn request_layout( |
| 231 | &mut self, |
| 232 | _: Option<&GlobalElementId>, |
| 233 | _: Option<&InspectorElementId>, |
| 234 | window: &mut Window, |
| 235 | cx: &mut App, |
| 236 | ) -> (LayoutId, ()) { |
| 237 | let metrics = self.object.metrics; |
| 238 | ( |
| 239 | window.request_layout( |
| 240 | gpui::Style { |
| 241 | size: size(metrics.size.width.into(), metrics.size.height.into()), |
| 242 | ..Default::default() |
| 243 | }, |
| 244 | [], |
| 245 | cx, |
| 246 | ), |
| 247 | (), |
| 248 | ) |
| 249 | } |
| 250 | |
| 251 | fn prepaint( |
| 252 | &mut self, |
| 253 | _: Option<&GlobalElementId>, |
| 254 | _: Option<&InspectorElementId>, |
| 255 | bounds: Bounds<Pixels>, |
| 256 | _: &mut (), |
| 257 | window: &mut Window, |
| 258 | cx: &mut App, |
| 259 | ) -> Hitbox { |
| 260 | let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal); |
| 261 | if self.content_measured { |
| 262 | self.content.prepaint_at(bounds.origin, window, cx); |
| 263 | } else { |
| 264 | self.content.prepaint_as_root( |
| 265 | bounds.origin, |
| 266 | size( |
| 267 | AvailableSpace::Definite(bounds.size.width), |
| 268 | AvailableSpace::Definite(bounds.size.height), |
| 269 | ), |
| 270 | window, |
| 271 | cx, |
| 272 | ); |
| 273 | } |
| 274 | if let Some(view) = GlobalState::global(cx).text_view_state() { |
| 275 | let state = view.read(cx); |
| 276 | if state.max_lines.is_some() |
| 277 | && let Ok(mut spans) = state.line_spans.lock() |
| 278 | { |
| 279 | spans.push(LineSpan { |
| 280 | top: bounds.top(), |
| 281 | bottom: bounds.bottom(), |
| 282 | line_height: bounds.size.height, |
| 283 | }); |
| 284 | } |
| 285 | } |
| 286 | hitbox |
| 287 | } |
| 288 | |
| 289 | fn paint( |
| 290 | &mut self, |
| 291 | _: Option<&GlobalElementId>, |
| 292 | _: Option<&InspectorElementId>, |
| 293 | bounds: Bounds<Pixels>, |
| 294 | _: &mut (), |
| 295 | hitbox: &mut Hitbox, |
| 296 | window: &mut Window, |
| 297 | cx: &mut App, |
| 298 | ) { |
| 299 | let view = GlobalState::global(cx).text_view_state().cloned(); |
| 300 | let selectable = view |
| 301 | .as_ref() |
| 302 | .is_some_and(|view| view.read(cx).is_selectable()); |
| 303 | let selected = view.as_ref().is_some_and(|view| { |
| 304 | let state = view.read(cx); |
| 305 | if selectable && state.preserve_inline_selection && !state.is_all_selected() { |
| 306 | return self.selected.lock().is_ok_and(|selected| *selected); |
| 307 | } |
| 308 | selectable |
| 309 | && (state.is_all_selected() |
| 310 | || state.multi_click_selection().is_some_and(|s| { |
| 311 | s.line_bounds.map_or_else( |
| 312 | || bounds.contains(&s.pos), |
| 313 | |row| row.contains(&bounds.center()), |
| 314 | ) |
| 315 | }) |
| 316 | || state.selection_points(cx).is_some_and(|(start, end)| { |
| 317 | point_in_text_selection( |
| 318 | self.selection_bounds.origin, |
| 319 | self.selection_bounds.size.width, |
| 320 | start, |
| 321 | end, |
| 322 | self.selection_bounds.size.height, |
| 323 | ) |
| 324 | })) |
| 325 | }); |
| 326 | if let Ok(mut value) = self.selected.lock() { |
| 327 | *value = selected; |
| 328 | } |
| 329 | if selected { |
| 330 | let color = view.as_ref().unwrap().read(cx).text_view_style.selection(); |
| 331 | window.paint_quad(gpui::fill(bounds, color)); |
| 332 | } |
| 333 | if let Some(link) = self.link.clone() { |
| 334 | window.set_cursor_style(CursorStyle::PointingHand, hitbox); |
| 335 | let link_hitbox = hitbox.clone(); |
| 336 | let link_view = view.clone(); |
| 337 | let handler = self.link_click_handler.clone(); |
| 338 | window.on_mouse_event(move |event: &gpui::MouseUpEvent, phase, window, cx| { |
| 339 | if !phase.bubble() |
| 340 | || !link_hitbox.is_hovered(window) |
| 341 | || link_view |
| 342 | .as_ref() |
| 343 | .is_some_and(|view| view.read(cx).has_selection(cx)) |
| 344 | { |
| 345 | return; |
| 346 | } |
| 347 | crate::TextSelection::end(window, cx); |
| 348 | cx.stop_propagation(); |
| 349 | let click = gpui::ClickEvent::Mouse(gpui::MouseClickEvent { |
| 350 | down: MouseDownEvent { |
| 351 | button: event.button, |
| 352 | position: event.position, |
| 353 | modifiers: event.modifiers, |
| 354 | click_count: event.click_count, |
| 355 | first_mouse: false, |
| 356 | }, |
| 357 | up: event.clone(), |
| 358 | }); |
| 359 | super::text_view::handle_link_click(&handler, link.url.clone(), click, window, cx); |
| 360 | }); |
| 361 | } |
| 362 | if selectable { |
| 363 | if self.link.is_none() { |
| 364 | window.set_cursor_style(CursorStyle::IBeam, hitbox); |
| 365 | } |
| 366 | let visible = bounds.intersect(&window.content_mask().bounds); |
| 367 | if visible.size.width > Pixels::ZERO && visible.size.height > Pixels::ZERO { |
| 368 | view.as_ref().unwrap().update(cx, |state, _| { |
| 369 | state.selection_adapter.register_inline(vec![visible]); |
| 370 | }); |
| 371 | } |
| 372 | let hitbox = hitbox.clone(); |
| 373 | let selected_state = self.selected.clone(); |
| 374 | let text = self.text.to_string(); |
| 375 | let current_view = window.current_view(); |
| 376 | let line_bounds = self.line_bounds; |
| 377 | window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| { |
| 378 | if !phase.bubble() |
| 379 | || !hitbox.is_hovered(window) |
| 380 | || event.button != MouseButton::Left |
| 381 | || !(2..=3).contains(&event.click_count) |
| 382 | { |
| 383 | return; |
| 384 | } |
| 385 | GlobalState::suppress_text_selection(cx); |
| 386 | if let Ok(mut value) = selected_state.lock() { |
| 387 | *value = true; |
| 388 | } |
| 389 | if let Some(view) = &view { |
| 390 | view.update(cx, |state, cx| { |
| 391 | if event.click_count == 3 { |
| 392 | state.set_multi_click_line(line_bounds, cx); |
| 393 | } else { |
| 394 | state.set_multi_click_selection( |
| 395 | event.position, |
| 396 | TextViewMultiClickKind::Word, |
| 397 | text.clone(), |
| 398 | cx, |
| 399 | ); |
| 400 | } |
| 401 | }); |
| 402 | } |
| 403 | cx.notify(current_view); |
| 404 | }); |
| 405 | } |
| 406 | self.content.paint(window, cx); |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | #[cfg(test)] |
| 411 | mod tests { |
| 412 | use super::super::inline::test_draw::in_prepaint; |
| 413 | use super::*; |
| 414 | |
| 415 | #[test] |
| 416 | fn native_padding_and_fixed_size_are_measured_without_fake_scaling() { |
| 417 | let mut app = gpui::TestApp::new(); |
| 418 | in_prepaint(&mut app, |window, cx| { |
| 419 | let native = InlineElement::new( |
| 420 | div() |
| 421 | .px(px(4.)) |
| 422 | .py(px(2.)) |
| 423 | .child(div().w(px(40.)).h(px(10.))), |
| 424 | ) |
| 425 | .with_baseline(px(10.)); |
| 426 | let measured = MeasuredInlineObject::measure( |
| 427 | "badge", |
| 428 | Some(native), |
| 429 | &TextStyle::default(), |
| 430 | window, |
| 431 | cx, |
| 432 | ); |
| 433 | assert_eq!(measured.metrics.size, size(px(48.), px(14.))); |
| 434 | assert_eq!(measured.metrics.baseline, px(10.)); |
| 435 | let narrow = measured.fit_text(Some(px(20.))); |
| 436 | assert_eq!(narrow.metrics.size, size(px(48.), px(14.))); |
| 437 | }); |
| 438 | } |
| 439 | |
| 440 | #[test] |
| 441 | fn invalid_baseline_uses_text_fallback_and_zero_width_remains_finite() { |
| 442 | let mut app = gpui::TestApp::new(); |
| 443 | in_prepaint(&mut app, |window, cx| { |
| 444 | for baseline in [px(f32::NAN), px(-1.), px(30.)] { |
| 445 | let native = |
| 446 | InlineElement::new(div().w(px(20.)).h(px(20.))).with_baseline(baseline); |
| 447 | let measured = MeasuredInlineObject::measure( |
| 448 | "fallback", |
| 449 | Some(native), |
| 450 | &TextStyle::default(), |
| 451 | window, |
| 452 | cx, |
| 453 | ); |
| 454 | assert!(measured.content.is_none()); |
| 455 | assert!(measured.metrics.is_valid()); |
| 456 | let zero = measured.fit_text(Some(px(0.))); |
| 457 | assert_eq!(zero.metrics.size, size(px(0.), px(0.))); |
| 458 | assert_eq!(zero.metrics.baseline, px(0.)); |
| 459 | } |
| 460 | }); |
| 461 | } |
| 462 | |
| 463 | #[test] |
| 464 | fn atomic_wrapper_does_not_mislabel_native_controls_as_images() { |
| 465 | let mut app = gpui::TestApp::new(); |
| 466 | let mut window = app.open_window(|_, _| gpui::Empty); |
| 467 | window.update(|_, window, cx| { |
| 468 | let measured = |
| 469 | MeasuredInlineObject::measure("member", None, &TextStyle::default(), window, cx); |
| 470 | let object = InlineObject::new( |
| 471 | "member", |
| 472 | "member".into(), |
| 473 | "Member profile".into(), |
| 474 | measured, |
| 475 | Arc::default(), |
| 476 | Bounds::default(), |
| 477 | Bounds::default(), |
| 478 | ); |
| 479 | let mut accessible = gpui::accesskit::Node::new(Role::Unknown); |
| 480 | object.write_a11y_info(&mut accessible); |
| 481 | assert_eq!(accessible.role(), Role::GenericContainer); |
| 482 | assert_eq!(accessible.label(), Some("Member profile")); |
| 483 | }); |
| 484 | } |
| 485 | } |