use std::{
mem,
ops::Range,
rc::Rc,
sync::{Arc, LazyLock},
time::Duration,
};
use gpui_kit::base::TestSupportExt as _;
use gpui_kit::{
AnyElement, App, Bounds, ContentMask, Corners, CursorStyle, DispatchPhase, Div, Element,
ElementId, Entity, GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId,
InteractiveElement as _, IntoElement, LayoutId, LineLayout, MouseButton, MouseDownEvent,
MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point, RenderImage, Role,
ScrollEvent, SharedString, Stateful, StatefulInteractiveElement as _, Style, Styled as _,
TransformationMatrix, Window, div, fill, prelude::FluentBuilder as _, px, relative,
};
use crate::{
model::ColumnIx,
state::{A11yPlan, CellHover, ColumnZone, FOCUS_CELL_ID, LiveGridDelegate, LiveGridState},
text::{GlyphArena, TextItem, paint_text},
};
static FOCUS_CELL_NAME: LazyLock<Arc<ElementId>> =
LazyLock::new(|| Arc::new(ElementId::Name(FOCUS_CELL_ID.into())));
static WIDGET_HOST_NAME: LazyLock<Arc<ElementId>> =
LazyLock::new(|| Arc::new(ElementId::Name(HostLayer::Widget.id_name().into())));
static EDITOR_HOST_NAME: LazyLock<Arc<ElementId>> =
LazyLock::new(|| Arc::new(ElementId::Name(HostLayer::Editor.id_name().into())));
const ZONE_PAINT_ORDER: [ColumnZone; 3] = [
ColumnZone::Scrolling,
ColumnZone::FrozenLeft,
ColumnZone::FrozenRight,
];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum HostLayer {
Widget,
Editor,
}
impl HostLayer {
pub(crate) const fn id_name(self) -> &'static str {
match self {
Self::Widget => "live-grid-cell",
Self::Editor => "live-grid-editor",
}
}
}
pub(crate) struct CellHost {
pub(crate) layer: HostLayer,
pub(crate) column: ColumnIx,
pub(crate) zone: ColumnZone,
pub(crate) bounds: Bounds<Pixels>,
pub(crate) element: Stateful<Div>,
}
impl CellHost {
pub(crate) fn host_div(layer: HostLayer, column_id: &'static str) -> Stateful<Div> {
let name = match layer {
HostLayer::Widget => &WIDGET_HOST_NAME,
HostLayer::Editor => &EDITOR_HOST_NAME,
};
div().id(ElementId::NamedChild(
Arc::clone(name),
SharedString::new_static(column_id),
))
}
}
pub(crate) struct HostRow {
id_name: &'static str,
key_hash: u64,
line: Bounds<Pixels>,
clip: Bounds<Pixels>,
hosts: Range<usize>,
}
#[derive(Default)]
pub(crate) struct HostPlan {
rows: Vec<HostRow>,
hosts: Vec<CellHost>,
zones: [(Pixels, Pixels); 3],
}
impl HostPlan {
pub(crate) fn new(zones: [(Pixels, Pixels); 3]) -> Self {
Self {
zones,
..Self::default()
}
}
pub(crate) fn reserve(&mut self, hosts: usize) {
self.hosts.reserve(hosts);
}
pub(crate) fn len(&self) -> usize {
self.hosts.len()
}
pub(crate) fn is_empty(&self) -> bool {
self.hosts.is_empty()
}
pub(crate) fn push(&mut self, host: CellHost) {
self.hosts.push(host);
}
pub(crate) fn end_row(
&mut self,
first: usize,
id_name: &'static str,
key_hash: u64,
line: Bounds<Pixels>,
clip: Bounds<Pixels>,
) {
if self.hosts.len() > first {
self.rows.push(HostRow {
id_name,
key_hash,
line,
clip,
hosts: first..self.hosts.len(),
});
}
}
}
pub(crate) struct IconItem {
pub bounds: Bounds<Pixels>,
pub path: SharedString,
pub color: Hsla,
}
pub(crate) struct ImageItem {
pub bounds: Bounds<Pixels>,
pub image_bounds: Bounds<Pixels>,
pub corner_radius: Pixels,
pub data: Arc<RenderImage>,
}
pub(crate) struct Region {
mask: Bounds<Pixels>,
pub quads: Vec<(Bounds<Pixels>, Hsla)>,
pub fills: Vec<(Bounds<Pixels>, Hsla)>,
pub lines: Vec<(Bounds<Pixels>, Hsla)>,
pub pills: Vec<(Bounds<Pixels>, Hsla, Pixels)>,
pub texts: Vec<TextItem>,
pub icons: Vec<IconItem>,
pub images: Vec<ImageItem>,
pub outline: Vec<(Bounds<Pixels>, Hsla)>,
}
impl Region {
pub fn new(mask: Bounds<Pixels>) -> Self {
Self {
mask,
quads: Vec::new(),
fills: Vec::new(),
lines: Vec::new(),
pills: Vec::new(),
texts: Vec::new(),
icons: Vec::new(),
images: Vec::new(),
outline: Vec::new(),
}
}
pub fn mask(&self) -> Bounds<Pixels> {
self.mask
}
}
pub(crate) struct FramePlan {
pub regions: Vec<Region>,
pub overlay: Vec<(Bounds<Pixels>, Hsla)>,
pub ellipsis: Arc<LineLayout>,
pub line_height: Pixels,
pub glyphs: GlyphArena,
pub hover: Option<CellHover>,
pub a11y: Option<Rc<A11yPlan>>,
pub hosts: HostPlan,
pub drop_indicator: Vec<(Bounds<Pixels>, Hsla)>,
}
pub(crate) struct BodyPrepaint {
plan: FramePlan,
hitbox: Hitbox,
hover: Option<AnyElement>,
rows: Vec<(AnyElement, Option<Bounds<Pixels>>)>,
}
fn a11y_row<D: LiveGridDelegate>(
plan: &Rc<A11yPlan>,
row_ix: usize,
state: &Entity<LiveGridState<D>>,
zones: Vec<AnyElement>,
focus_taken: bool,
) -> (AnyElement, Bounds<Pixels>) {
let row = &plan.rows()[row_ix];
let bounds = row.bounds();
let (content, key_hash) = (row.content(), row.key_hash());
let focus = plan
.focus()
.filter(|focus| focus.row_ix() == row_ix && !focus_taken)
.map(|_| a11y_focus_cell(plan, bounds.origin));
let element = div()
.id(ElementId::NamedInteger(
SharedString::new_static(row.id_name()),
row.key_hash(),
))
.test_support()
.role(Role::Row)
.aria_row_index(row.row_index())
.when_some(row.selected(), |this, selected| {
this.aria_selected(selected)
})
.when_some(row.level(), |this, level| this.aria_level(level))
.when_some(row.expanded(), |this, expanded| {
this.aria_expanded(expanded)
})
.when_some(row.disclosure_action(), |this, action| {
let state = state.clone();
this.on_a11y_action(action, move |_, _, cx| {
state.update(cx, |state, cx| {
state.on_a11y_disclosure(content, key_hash, action, cx)
})
})
})
.a11y_synthetic_children({
let plan = plan.clone();
move |builder| {
let row = &plan.rows()[row_ix];
plan.write_row(row, builder.parent_node());
for cell in plan.cells(row) {
let id = builder.synthetic_node_id(cell.column());
builder.push_child(id, plan.cell_node(row, cell));
}
}
})
.w(bounds.size.width)
.h(bounds.size.height)
.children(focus)
.children(zones)
.into_any_element();
(element, bounds)
}
fn host_row_element(row: &HostRow, zones: Vec<AnyElement>, bounds: Bounds<Pixels>) -> AnyElement {
div()
.id(ElementId::NamedInteger(
SharedString::new_static(row.id_name),
row.key_hash,
))
.test_support()
.w(bounds.size.width)
.h(bounds.size.height)
.children(zones)
.into_any_element()
}
fn host_zones(
row: &HostRow,
hosts: &mut [Option<CellHost>],
zones: &[(Pixels, Pixels); 3],
origin: Point<Pixels>,
focus: Option<&Rc<A11yPlan>>,
) -> (Vec<AnyElement>, bool) {
let focus_column = focus
.and_then(|plan| plan.focus())
.map(|focus| focus.cell().column());
let mut focus_taken = false;
let mut containers = Vec::new();
for zone in ZONE_PAINT_ORDER {
let (zone_x, zone_width) = zones[zone.slot()];
let mut children = Vec::new();
for slot in &mut hosts[row.hosts.clone()] {
let Some(host) = slot.take_if(|host| host.zone == zone) else {
continue;
};
let takes_focus = host.layer == HostLayer::Widget && Some(host.column) == focus_column;
focus_taken |= takes_focus;
let bounds = host.bounds;
children.push(
host.element
.when_some(focus.filter(|_| takes_focus), |this, plan| {
let plan = plan.clone();
this.role(Role::GridCell)
.aria_active_descendant()
.a11y_synthetic_children(move |builder| {
if let Some(focus) = plan.focus() {
plan.write_focus(focus, builder.parent_node());
}
})
})
.absolute()
.left(bounds.origin.x - zone_x)
.top(bounds.origin.y - row.line.origin.y)
.w(bounds.size.width)
.h(bounds.size.height)
.test_support()
.into_any_element(),
);
}
if !children.is_empty() {
containers.push(
div()
.absolute()
.left(zone_x - origin.x)
.top(row.line.origin.y - origin.y)
.w(zone_width)
.h(row.line.size.height)
.overflow_hidden()
.children(children)
.into_any_element(),
);
}
}
(containers, focus_taken)
}
fn prepaint_rows<D: LiveGridDelegate>(
plan: &mut FramePlan,
state: &Entity<LiveGridState<D>>,
window: &mut Window,
cx: &mut App,
) -> Vec<(AnyElement, Option<Bounds<Pixels>>)> {
let HostPlan {
rows: host_rows,
hosts,
zones,
} = mem::take(&mut plan.hosts);
let mut hosts: Vec<Option<CellHost>> = hosts.into_iter().map(Some).collect();
let mut placed_hosts = vec![false; host_rows.len()];
let a11y_rows = plan.a11y.as_ref().map_or(0, |a11y| a11y.rows().len());
let mut rows = Vec::with_capacity(a11y_rows + host_rows.len());
let mut place = |element: AnyElement,
bounds: Bounds<Pixels>,
clip: Option<Bounds<Pixels>>,
window: &mut Window,
cx: &mut App| {
let mut element = element;
window.with_content_mask(clip.map(|bounds| ContentMask { bounds }), |window| {
element.layout_as_root(bounds.size.into(), window, cx);
element.prepaint_at(bounds.origin, window, cx);
});
rows.push((element, clip));
};
if let Some(a11y) = &plan.a11y {
for (row_ix, row) in a11y.rows().iter().enumerate() {
let hosted = host_rows.iter().position(|host_row| {
(host_row.id_name, host_row.key_hash) == (row.id_name(), row.key_hash())
});
let (zones, focus_taken, clip) = match hosted {
Some(ix) => {
placed_hosts[ix] = true;
let focus = a11y
.focus()
.filter(|focus| focus.row_ix() == row_ix)
.map(|_| a11y);
let host_row = &host_rows[ix];
let (containers, focus_taken) =
host_zones(host_row, &mut hosts, &zones, row.bounds().origin, focus);
(containers, focus_taken, Some(host_row.clip))
}
None => (Vec::new(), false, None),
};
let (element, bounds) = a11y_row(a11y, row_ix, state, zones, focus_taken);
place(element, bounds, clip, window, cx);
}
}
for (host_row, _) in host_rows
.iter()
.zip(&placed_hosts)
.filter(|(_, placed)| !**placed)
{
let visible = host_row.line.intersect(&host_row.clip);
let bounds = if visible.size.width > px(0.) && visible.size.height > px(0.) {
visible
} else {
host_row.line
};
let (containers, _) = host_zones(host_row, &mut hosts, &zones, bounds.origin, None);
place(
host_row_element(host_row, containers, bounds),
bounds,
Some(host_row.clip),
window,
cx,
);
}
rows
}
fn a11y_focus_cell(plan: &Rc<A11yPlan>, row_origin: Point<Pixels>) -> AnyElement {
let focus = plan.focus().expect("the row holds the focused cell");
let bounds = focus.cell().bounds();
div()
.id(ElementId::NamedChild(
FOCUS_CELL_NAME.clone(),
SharedString::new_static(focus.column_id()),
))
.test_support()
.role(Role::GridCell)
.aria_active_descendant()
.a11y_synthetic_children({
let plan = plan.clone();
move |builder| {
if let Some(focus) = plan.focus() {
plan.write_focus(focus, builder.parent_node());
}
}
})
.absolute()
.left(bounds.origin.x - row_origin.x)
.top(bounds.origin.y - row_origin.y)
.w(bounds.size.width)
.h(bounds.size.height)
.into_any_element()
}
pub(crate) struct GridBody<D: LiveGridDelegate> {
state: Entity<LiveGridState<D>>,
}
impl<D: LiveGridDelegate> GridBody<D> {
pub fn new(state: Entity<LiveGridState<D>>) -> Self {
Self { state }
}
}
impl<D: LiveGridDelegate> IntoElement for GridBody<D> {
type Element = Self;
fn into_element(self) -> Self::Element {
self
}
}
impl<D: LiveGridDelegate> Element for GridBody<D> {
type RequestLayoutState = ();
type PrepaintState = BodyPrepaint;
fn id(&self) -> Option<ElementId> {
None
}
fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, Self::RequestLayoutState) {
let mut style = Style::default();
style.flex_grow = 1.;
style.flex_shrink = 1.;
style.flex_basis = relative(0.).into();
style.size.width = relative(1.).into();
(window.request_layout(style, [], cx), ())
}
fn prepaint(
&mut self,
_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
bounds: Bounds<Pixels>,
_request_layout: &mut Self::RequestLayoutState,
window: &mut Window,
cx: &mut App,
) -> Self::PrepaintState {
let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
let mut plan = self
.state
.update(cx, |state, cx| state.plan_frame(bounds, window, cx));
let hover = plan.hover.take().map(|hover| {
let bounds = hover.bounds();
let mut element = hover.into_element();
element.layout_as_root(bounds.size.into(), window, cx);
element.prepaint_at(bounds.origin, window, cx);
element
});
let hosts_started = (!plan.hosts.is_empty()).then(web_time::Instant::now);
let rows = prepaint_rows(&mut plan, &self.state, window, cx);
if let Some(started) = hosts_started {
let elapsed: Duration = started.elapsed();
self.state
.update(cx, |state, _| state.set_last_hosts_prepaint(elapsed));
}
BodyPrepaint {
plan,
hitbox,
hover,
rows,
}
}
fn paint(
&mut self,
_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
_bounds: Bounds<Pixels>,
_request_layout: &mut Self::RequestLayoutState,
prepaint: &mut Self::PrepaintState,
window: &mut Window,
cx: &mut App,
) {
let plan = &prepaint.plan;
for region in &plan.regions {
if region.mask.size.width <= px(0.) || region.mask.size.height <= px(0.) {
continue;
}
window.with_content_mask(
Some(ContentMask {
bounds: region.mask,
}),
|window| {
window.paint_layer(region.mask, |window| {
for (bounds, color) in region
.quads
.iter()
.chain(®ion.fills)
.chain(®ion.lines)
{
window.paint_quad(fill(*bounds, *color));
}
for (bounds, color, radius) in ®ion.pills {
window.paint_quad(fill(*bounds, *color).corner_radii(*radius));
}
for item in ®ion.texts {
paint_text(
item,
&plan.glyphs,
item.ellipsis.as_deref().unwrap_or(&plan.ellipsis),
plan.line_height,
window,
);
}
for icon in ®ion.icons {
let _ = window.paint_svg(
icon.bounds,
icon.path.clone(),
None,
TransformationMatrix::unit(),
icon.color,
cx,
);
}
for image in ®ion.images {
let _ = window.paint_image(
image.bounds,
image.image_bounds,
Corners::all(image.corner_radius),
image.data.clone(),
0,
false,
);
}
});
},
);
}
for (bounds, color) in &plan.overlay {
window.paint_quad(fill(*bounds, *color));
}
if let Some(hover) = &mut prepaint.hover {
hover.paint(window, cx);
}
for (row, clip) in &mut prepaint.rows {
window.with_content_mask(clip.map(|bounds| ContentMask { bounds }), |window| {
row.paint(window, cx);
});
}
let mut outlines = 0;
for region in &plan.regions {
if region.outline.is_empty() {
continue;
}
window.with_content_mask(
Some(ContentMask {
bounds: region.mask,
}),
|window| {
for (bounds, color) in ®ion.outline {
window.paint_quad(fill(*bounds, *color));
}
},
);
outlines += region.outline.len();
}
for (bounds, color) in &plan.drop_indicator {
window.paint_quad(fill(*bounds, *color));
}
#[cfg(any(test, feature = "test-support"))]
{
let mut order = vec!["regions"];
order.extend((!plan.overlay.is_empty()).then_some("dividers"));
order.extend(prepaint.hover.is_some().then_some("tooltip"));
order.extend((!prepaint.rows.is_empty()).then_some("rows"));
order.extend((outlines > 0).then_some("outlines"));
order.extend((!plan.drop_indicator.is_empty()).then_some("drop"));
self.state
.update(cx, |state, _| state.set_last_paint_order(order));
}
#[cfg(not(any(test, feature = "test-support")))]
let _ = outlines;
if self.state.read(cx).is_link_hovered() {
window.set_cursor_style(CursorStyle::PointingHand, &prepaint.hitbox);
}
let hitbox = prepaint.hitbox.clone();
let state = self.state.clone();
window.on_mouse_event({
let hitbox = hitbox.clone();
let state = state.clone();
move |event: &ScrollEvent, phase, window, cx| {
if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
state.update(cx, |state, cx| state.on_scroll_wheel(event.delta, cx));
cx.stop_propagation();
}
}
});
window.on_mouse_event({
let hitbox = hitbox.clone();
let state = state.clone();
move |event: &MouseMoveEvent, phase, window, cx| {
if phase == DispatchPhase::Bubble {
let inside = hitbox.is_hovered(window);
state.update(cx, |state, cx| {
state.set_pointer_inside(inside, cx);
state.set_hover_position(inside.then_some(event.position), cx);
state.on_click_pointer_move(event.position);
if event.pressed_button == Some(MouseButton::Left) {
state.on_body_drag_move(event.position, cx);
}
});
}
}
});
window.on_mouse_event({
let state = state.clone();
move |event: &MouseDownEvent, phase, window, cx| {
if phase == DispatchPhase::Capture {
state.update(cx, |state, cx| {
state.on_window_mouse_down(event.position, window, cx);
state.cancel_click();
});
} else if hitbox.is_hovered(window) {
state.update(cx, |state, cx| state.on_body_mouse_down(event, window, cx));
}
}
});
window.on_mouse_event(move |event: &MouseUpEvent, phase, _, cx| {
if phase == DispatchPhase::Capture {
state.update(cx, |state, cx| {
if event.button == MouseButton::Left {
state.on_column_mouse_up(cx);
state.on_body_mouse_up(cx);
state.end_drop_hover(cx);
}
state.on_click_mouse_up(event, cx);
});
}
});
}
}