From f2a079b16df2e8b14e5af3ad8404c6dc460cc783 Mon Sep 17 00:00:00 2001 From: egor Date: Fri, 4 Dec 2026 00:29:14 +0500 Subject: [PATCH 1/3] fix(agent): track autonomous provider turns in the composer Translate explicit ACP session activity into the existing session state machine. Preserve an autonomous continuation when a previous prompt completes, and keep the stop control and queued dispatch synchronized with provider activity. (cherry picked from commit fbe0e9ecad2dda5ddf39ee48935349594619bab7) --- crates/acp/src/client/lifecycle_tests.rs | 72 ++++++++++ crates/acp/src/mapping/session.rs | 18 ++- crates/acp/src/mapping/session_tests.rs | 27 ++++ crates/agent-chat/src/thread/client.rs | 26 ++-- .../agent-chat/src/thread/document/tests.rs | 1 + crates/agent-chat/src/thread/queue.rs | 126 ++++++------------ crates/agent-chat/src/thread/queue/prompt.rs | 81 +++++++++++ crates/agent-chat/src/thread/saved.rs | 8 ++ .../agent-chat/src/thread/session_driver.rs | 8 +- .../agent/src/panel/tests/authentication.rs | 102 ++++++++++++++ crates/agent/src/panel/tests/history.rs | 1 + crates/agent/src/panel/tests/labels.rs | 1 + crates/ai/src/model/session.rs | 8 ++ crates/ai/src/session.rs | 39 +++++- crates/ai/src/session/tests.rs | 57 ++++++++ crates/ai/src/tests.rs | 1 + crates/hub-io/src/chats/watch.rs | 1 + docs/architecture/adapter.md | 8 +- docs/architecture/service.md | 7 + 19 files changed, 491 insertions(+), 101 deletions(-) create mode 100644 crates/agent-chat/src/thread/queue/prompt.rs diff --git a/crates/acp/src/client/lifecycle_tests.rs b/crates/acp/src/client/lifecycle_tests.rs index 61ba1b45..875aefa9 100644 --- a/crates/acp/src/client/lifecycle_tests.rs +++ b/crates/acp/src/client/lifecycle_tests.rs @@ -6,6 +6,10 @@ async fn connection(mode: &str, directory: &std::path::Path) -> AgentConnection let script = r#" import json, sys mode = sys.argv[1] +def update(text): + return {'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'s1','update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':text}}}} +def activity(state): + return {'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'s1','update':{'sessionUpdate':'session_info_update','_meta':{'codex':{'threadStatus':{'type':state}}}}}} for line in sys.stdin: request = json.loads(line) if 'id' not in request: continue @@ -13,6 +17,14 @@ for line in sys.stdin: if method == 'initialize': result = {'protocolVersion':1,'agentCapabilities': {} if mode == 'unsupported' else {'sessionCapabilities':{'close':{}}}} elif method == 'session/new': result = {'sessionId':'s1'} + elif method == 'session/prompt' and mode == 'autonomous': + print(json.dumps(activity('active')), flush=True) + print(json.dumps(activity('idle')), flush=True) + print(json.dumps({'jsonrpc':'2.0','id':request['id'],'result':{'stopReason':'end_turn'}}),flush=True) + print(json.dumps(activity('active')), flush=True) + print(json.dumps(update('continuation')), flush=True) + print(json.dumps(activity('idle')), flush=True) + continue elif method == 'session/close': if mode == 'hang': continue if mode == 'error': @@ -43,6 +55,66 @@ for line in sys.stdin: .await .unwrap() } +#[test] +fn subprocess_activity_arrives_even_after_the_prompt_response() { + use nocterm_ai::model::session::{SessionActivity, StopReason}; + + let exercise = async { + let directory = tempfile::tempdir().unwrap(); + let connection = connection("autonomous", directory.path()).await; + let session = connection + .commands + .new_session(SessionOpen { + working_directory: directory.path().to_path_buf(), + endpoints: Vec::new(), + }) + .await + .unwrap(); + let result = connection + .commands + .prompt(PromptRequest { + session: session.session.clone(), + content: vec![nocterm_ai::model::content::Content::text("work")], + }) + .await + .unwrap(); + assert_eq!(result.stop_reason, StopReason::EndTurn); + for expected in [ + Some(SessionActivity::Active), + Some(SessionActivity::Idle), + Some(SessionActivity::Active), + None, + Some(SessionActivity::Idle), + ] { + let AgentEvent::Session(event) = connection.events.recv().await.unwrap() else { + panic!("expected an ACP session update"); + }; + assert_eq!(event.session, session.session); + match (expected, event.update) { + (Some(activity), SessionUpdate::SessionInfoUpdate(info)) => { + assert_eq!(info.activity, Some(activity)) + } + (None, SessionUpdate::AgentMessageChunk(content)) => assert_eq!( + content, + nocterm_ai::model::content::Content::text("continuation") + ), + _ => panic!("unexpected update"), + } + } + connection.commands.shutdown_gracefully().await.unwrap(); + }; + futures::executor::block_on(async { + assert!(matches!( + select( + Box::pin(exercise), + Box::pin(async_io::Timer::after(Duration::from_secs(5))) + ) + .await, + Either::Left(_) + )); + }); +} + #[cfg(unix)] #[test] fn acknowledged_close_waits_for_the_foreground_event_barrier() { diff --git a/crates/acp/src/mapping/session.rs b/crates/acp/src/mapping/session.rs index 6270e226..e885ab4f 100644 --- a/crates/acp/src/mapping/session.rs +++ b/crates/acp/src/mapping/session.rs @@ -10,7 +10,7 @@ use nocterm_ai::model::{ diagnostic::ModelError, ids::{ModeId, SessionId}, plan::{Plan, PlanEntry, PlanPriority, PlanStatus}, - session::{SessionInfo, SessionNotice, SessionUpdate}, + session::{SessionActivity, SessionInfo, SessionNotice, SessionUpdate}, usage::{ContextUsage, Cost}, }; @@ -55,6 +55,21 @@ fn title(value: MaybeUndefined) -> Change { _ => Change::Keep, } } +// codex-acp reports autonomous app-server turns through this session-info extension. +// Other provider metadata remains inert; unknown or malformed statuses do not change liveness. +fn session_activity(meta: Option<&wire::Meta>) -> Option { + match meta? + .get("codex")? + .get("threadStatus")? + .get("type")? + .as_str()? + { + "active" => Some(SessionActivity::Active), + "idle" => Some(SessionActivity::Idle), + _ => None, + } +} + fn update(value: wire::SessionUpdate) -> Result { Ok(match value { wire::SessionUpdate::UserMessageChunk(chunk) => { @@ -85,6 +100,7 @@ fn update(value: wire::SessionUpdate) -> Result { wire::SessionUpdate::SessionInfoUpdate(value) => { SessionUpdate::SessionInfoUpdate(SessionInfo { title: title(value.title), + activity: session_activity(value.meta.as_ref()), meta: extensions(value.meta), }) } diff --git a/crates/acp/src/mapping/session_tests.rs b/crates/acp/src/mapping/session_tests.rs index 8e6618d8..d5391758 100644 --- a/crates/acp/src/mapping/session_tests.rs +++ b/crates/acp/src/mapping/session_tests.rs @@ -234,3 +234,30 @@ fn agent_introductions_keep_images_and_sign_in_methods() { assert_eq!(setup.args, ["login"]); assert_eq!(methods[1].label, "Setup"); } + +#[test] +fn codex_thread_status_is_a_typed_activity_without_losing_the_title() { + for (status, expected) in [ + ( + json!({"type":"active","activeFlags":[]}), + Some(SessionActivity::Active), + ), + (json!({"type":"idle"}), Some(SessionActivity::Idle)), + (json!({"type":"notLoaded"}), None), + (json!({"type":"future"}), None), + (json!("active"), None), + (json!(null), None), + ] { + let notice = notice(update(json!({"update":{ + "sessionUpdate":"session_info_update", + "title":"Still my chat", + "_meta":{"codex":{"threadStatus":status}} + }}))) + .unwrap(); + let SessionUpdate::SessionInfoUpdate(info) = notice.update else { + panic!("session info expected"); + }; + assert_eq!(info.title, Change::Set("Still my chat".into())); + assert_eq!(info.activity, expected); + } +} diff --git a/crates/agent-chat/src/thread/client.rs b/crates/agent-chat/src/thread/client.rs index e191952f..8af1c3c3 100644 --- a/crates/agent-chat/src/thread/client.rs +++ b/crates/agent-chat/src/thread/client.rs @@ -323,6 +323,7 @@ impl AgentThread { self.state.set_pending_history(false, self.deps.timestamp()); self.persist(cx); } + self.resume_observed_turn(); self.dispatch_next(cx); cx.notify(); } @@ -341,13 +342,6 @@ impl AgentThread { } } - pub(super) fn clear_settled_disabled_document(&mut self, cx: &gpui::App) { - if !self.deps.enabled(cx) && self.state.release_disabled() { - self.config.disabled(); - self.composer.reset_after_disable(); - } - } - /// The chat's connection stopped. With AI turned off, the chat also /// forgets its transcript and what was attached. pub fn connection_stopped(&mut self, message: &str, cx: &mut Context) { @@ -362,14 +356,22 @@ impl AgentThread { self.config .keep_control(self.session.ticket(), notification); } + if self.session().as_ref() != Some(¬ification.session) { + return; + } if let SessionUpdate::Turn(activity) = ¬ification.update { - if self.session().as_ref() == Some(¬ification.session) { - self.external_turn(activity, cx); - } + self.external_turn(activity, cx); return; } - if self.session().as_ref() != Some(¬ification.session) - || !self.session.accepts_updates() + if let SessionUpdate::SessionInfoUpdate(info) = ¬ification.update + && let Some(activity) = info.activity + { + self.observe_session_activity(activity, cx); + if matches!(info.title, nocterm_ai::model::controls::Change::Keep) { + return; + } + } + if !self.session.accepts_updates() || matches!(notification.update, SessionUpdate::UserMessageChunk(_)) { return; diff --git a/crates/agent-chat/src/thread/document/tests.rs b/crates/agent-chat/src/thread/document/tests.rs index 97956b4d..1ad7ca5e 100644 --- a/crates/agent-chat/src/thread/document/tests.rs +++ b/crates/agent-chat/src/thread/document/tests.rs @@ -55,6 +55,7 @@ fn update(value: serde_json::Value) -> SessionUpdate { }), "session_info_update" => SessionUpdate::SessionInfoUpdate(SessionInfo { title: Change::Set(value["title"].as_str().unwrap().into()), + activity: None, meta: None, }), "usage_update" => SessionUpdate::UsageUpdate(ContextUsage::new( diff --git a/crates/agent-chat/src/thread/queue.rs b/crates/agent-chat/src/thread/queue.rs index 6069351a..2706eab8 100644 --- a/crates/agent-chat/src/thread/queue.rs +++ b/crates/agent-chat/src/thread/queue.rs @@ -8,8 +8,8 @@ use super::{ execution::WaitSubject, }; use gpui::{App, Context, EntityId, Task}; -use nocterm_ai::history::{SavedAttachment, SavedPrompt}; -use nocterm_ai::model::content::Content; +use nocterm_ai::history::SavedAttachment; +use nocterm_ai::model::{content::Content, session::SessionActivity}; use nocterm_ai::{BridgeCall, TerminalCall, ToolFailure}; use nocterm_workspace_ports::{ExpectedSession, TerminalEntry, TerminalStatus}; @@ -20,48 +20,8 @@ use super::{AgentThread, Attachment}; mod submit_error; pub(super) use submit_error::SubmitError; -#[derive(Clone)] -pub struct QueuedPrompt { - saved: Arc, - attachments: Vec, - encoded_len: usize, - memory_len: usize, -} - -impl QueuedPrompt { - #[cfg(any(test, feature = "test-support"))] - pub fn new(saved: SavedPrompt, attachments: Vec) -> Self { - Self::prepared(saved, attachments, None) - } - pub fn prepared( - saved: SavedPrompt, - attachments: Vec, - encoded_len: Option, - ) -> Self { - let encoded_len = encoded_len - .unwrap_or_else(|| nocterm_ai::history::prompt_size(&saved).unwrap_or(usize::MAX)); - let memory_len = nocterm_ai::history::prompt_memory(&saved).unwrap_or(usize::MAX); - Self { - memory_len, - saved: Arc::new(saved), - attachments, - encoded_len, - } - } - pub fn saved(&self) -> &Arc { - &self.saved - } - /// What the prompt was written about, captured when it was queued. - pub fn attachments(&self) -> &[Attachment] { - &self.attachments - } - pub fn encoded_len(&self) -> usize { - self.encoded_len - } - pub fn memory_len(&self) -> usize { - self.memory_len - } -} +mod prompt; +pub use prompt::QueuedPrompt; impl AgentThread { pub(super) fn start_execution_watch(&mut self, cx: &mut Context) { @@ -681,8 +641,8 @@ impl AgentThread { } self.state.validate_candidate( &metadata, - queue.iter().map(|prompt| prompt.encoded_len), - queue.iter().map(|prompt| prompt.memory_len), + queue.iter().map(QueuedPrompt::encoded_len), + queue.iter().map(QueuedPrompt::memory_len), )?; self.composer.commit_prompt_change(candidate); self.accept_document_inputs(cx, false); @@ -719,15 +679,46 @@ impl AgentThread { if !self.session.finish_external_turn() { return; } - self.finalize_tool_displays(); - self.notice.present("Ready".into()); - self.persist(cx); - self.dispatch_next(cx); + self.settle_external_turn(cx); } } cx.notify(); } + /// Provider status is an observation, not a new user prompt or a tool grant. + pub(super) fn observe_session_activity( + &mut self, + activity: SessionActivity, + cx: &mut Context, + ) { + if !self.session.observe_activity(activity) { + return; + } + if self.session.generating() { + self.notice.present("Working…".into()); + } else { + self.settle_external_turn(cx); + } + cx.notify(); + } + + pub(super) fn resume_observed_turn(&mut self) { + if self.session.resume_observed_turn() { + self.notice.present("Working…".into()); + } + } + + fn settle_external_turn(&mut self, cx: &mut Context) { + self.finalize_tool_displays(); + self.notice.present(if self.session.stopped() { + "Stopped".into() + } else { + "Ready".into() + }); + self.persist(cx); + self.dispatch_next(cx); + } + pub fn dispatch_next(&mut self, cx: &mut Context) { if !self.queue_dispatchable() || self.session.generating() @@ -751,8 +742,9 @@ impl AgentThread { return; }; // Context is fixed for this turn, including terminal tool access. - self.tools.capture_scope(prompt.attachments); - let saved = Arc::unwrap_or_clone(prompt.saved); + let (attachments, saved) = prompt.into_parts(); + self.tools.capture_scope(attachments); + let saved = Arc::unwrap_or_clone(saved); self.start_prompt(saved.text, saved.images, cx); } } @@ -767,33 +759,3 @@ pub(super) fn restore_attachments(values: &[SavedAttachment]) -> Vec }) .collect() } - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn rendering_snapshot_shares_immutable_image_payload() { - let prompt = QueuedPrompt::new( - SavedPrompt { - id: 1, - text: "image".into(), - images: vec![Content::Image(nocterm_ai::model::content::Image::new( - "a".repeat(2 * 1024 * 1024), - "image/png", - ))], - attachments: Vec::new(), - }, - Vec::new(), - ); - let copy = prompt.clone(); - assert!(Arc::ptr_eq(prompt.saved(), copy.saved())); - let Content::Image(original) = &prompt.saved().images[0] else { - panic!("image"); - }; - let Content::Image(cloned) = ©.saved().images[0] else { - panic!("image"); - }; - assert_eq!(original.data.as_ptr(), cloned.data.as_ptr()); - assert_eq!(cloned.data.len(), 2 * 1024 * 1024); - } -} diff --git a/crates/agent-chat/src/thread/queue/prompt.rs b/crates/agent-chat/src/thread/queue/prompt.rs new file mode 100644 index 00000000..e5213dbb --- /dev/null +++ b/crates/agent-chat/src/thread/queue/prompt.rs @@ -0,0 +1,81 @@ +//! Immutable queued prompt and its accounted snapshot; clones share the encoded payload. +use super::Attachment; +use nocterm_ai::history::SavedPrompt; +use std::sync::Arc; + +#[derive(Clone)] +pub struct QueuedPrompt { + saved: Arc, + attachments: Vec, + encoded_len: usize, + memory_len: usize, +} + +impl QueuedPrompt { + #[cfg(any(test, feature = "test-support"))] + pub fn new(saved: SavedPrompt, attachments: Vec) -> Self { + Self::prepared(saved, attachments, None) + } + pub fn prepared( + saved: SavedPrompt, + attachments: Vec, + encoded_len: Option, + ) -> Self { + let encoded_len = encoded_len + .unwrap_or_else(|| nocterm_ai::history::prompt_size(&saved).unwrap_or(usize::MAX)); + let memory_len = nocterm_ai::history::prompt_memory(&saved).unwrap_or(usize::MAX); + Self { + memory_len, + saved: Arc::new(saved), + attachments, + encoded_len, + } + } + pub(super) fn into_parts(self) -> (Vec, Arc) { + (self.attachments, self.saved) + } + pub fn saved(&self) -> &Arc { + &self.saved + } + /// What the prompt was written about, captured when it was queued. + pub fn attachments(&self) -> &[Attachment] { + &self.attachments + } + pub fn encoded_len(&self) -> usize { + self.encoded_len + } + pub fn memory_len(&self) -> usize { + self.memory_len + } +} + +#[cfg(test)] +mod tests { + use super::*; + use nocterm_ai::model::content::Content; + #[test] + fn rendering_snapshot_shares_immutable_image_payload() { + let prompt = QueuedPrompt::new( + SavedPrompt { + id: 1, + text: "image".into(), + images: vec![Content::Image(nocterm_ai::model::content::Image::new( + "a".repeat(2 * 1024 * 1024), + "image/png", + ))], + attachments: Vec::new(), + }, + Vec::new(), + ); + let copy = prompt.clone(); + assert!(Arc::ptr_eq(prompt.saved(), copy.saved())); + let Content::Image(original) = &prompt.saved().images[0] else { + panic!("image"); + }; + let Content::Image(cloned) = ©.saved().images[0] else { + panic!("image"); + }; + assert_eq!(original.data.as_ptr(), cloned.data.as_ptr()); + assert_eq!(cloned.data.len(), 2 * 1024 * 1024); + } +} diff --git a/crates/agent-chat/src/thread/saved.rs b/crates/agent-chat/src/thread/saved.rs index b57ce3b6..369b4cc0 100644 --- a/crates/agent-chat/src/thread/saved.rs +++ b/crates/agent-chat/src/thread/saved.rs @@ -126,10 +126,18 @@ impl AgentThread { cx.notify(); } + pub(super) fn clear_settled_disabled_document(&mut self, cx: &gpui::App) { + if !self.deps.enabled(cx) && self.state.release_disabled() { + self.config.disabled(); + self.composer.reset_after_disable(); + } + } + pub(super) fn configured(&mut self, cx: &mut Context) { self.session.opened(); self.sync_config(true, cx); self.remember_options(cx); + self.resume_observed_turn(); self.dispatch_next(cx); cx.notify(); } diff --git a/crates/agent-chat/src/thread/session_driver.rs b/crates/agent-chat/src/thread/session_driver.rs index dc7558b0..3fe3bf8a 100644 --- a/crates/agent-chat/src/thread/session_driver.rs +++ b/crates/agent-chat/src/thread/session_driver.rs @@ -1,7 +1,7 @@ //! Session and lease transitions retain their original connection and operation identity. use super::Restore; use crate::runtime::SessionLease; -use nocterm_ai::model::ids::SessionId; +use nocterm_ai::model::{ids::SessionId, session::SessionActivity}; use nocterm_ai::{ AgentCommands, AgentInfo, BridgeRegistration, session::{SessionPhase, SessionState, Ticket}, @@ -228,6 +228,12 @@ impl SessionDriver { pub(super) fn finish_external_turn(&mut self) -> bool { self.phase.finish_external_turn() } + pub(super) fn observe_activity(&mut self, activity: SessionActivity) -> bool { + self.phase.observe_activity(activity) + } + pub(super) fn resume_observed_turn(&mut self) -> bool { + self.phase.resume_observed_turn() + } pub(super) fn opened(&mut self) { self.phase.opened() } diff --git a/crates/agent/src/panel/tests/authentication.rs b/crates/agent/src/panel/tests/authentication.rs index 20a92291..6900dfb1 100644 --- a/crates/agent/src/panel/tests/authentication.rs +++ b/crates/agent/src/panel/tests/authentication.rs @@ -236,3 +236,105 @@ fn terminal_authentication_uses_host_callback_and_retries_after_cancel_or_failur .ends_with(&["--setup".into(), "$(literal_argument)".into()]) ); } + +fn report_activity( + f: &Fixture, + session: SessionId, + activity: nocterm_ai::model::session::SessionActivity, + cx: &mut TestAppContext, +) { + f.events + .try_send(AgentEvent::Session(SessionNotice::new( + session, + SessionUpdate::SessionInfoUpdate(nocterm_ai::model::session::SessionInfo { + activity: Some(activity), + ..Default::default() + }), + ))) + .unwrap(); + cx.run_until_parked(); +} + +#[gpui_kit::test] +fn autonomous_agent_activity_shows_stop_and_returns_to_idle(cx: &mut TestAppContext) { + use nocterm_ai::model::session::SessionActivity::{Active, Idle}; + let f = fixture(cx); + new_chat(&f, cx); + let session = cx.update(|cx| { + f.panel + .read(cx) + .current() + .unwrap() + .read(cx) + .session() + .clone() + .unwrap() + }); + report_activity(&f, SessionId::new("another-session"), Active, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("agent-thinking").is_none()); + }) + .unwrap(); + report_activity(&f, session.clone(), Active, cx); + report_activity(&f, session.clone(), Active, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("agent-thinking").is_some()); + window.click("agent-send", cx); + }) + .unwrap(); + assert_eq!(f.commands.cancels.load(Ordering::SeqCst), 1); + assert!(f.commands.prompts.lock().unwrap().is_empty()); + report_activity(&f, session, Idle, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + // Stopped remains a status notice, but the busy indicator and stop action are gone. + assert!(window.try_find("agent-thinking").is_none()); + let thread = f.panel.read(cx).current().unwrap(); + assert_eq!(thread.read(cx).status(), "Stopped"); + assert!(!thread.read(cx).session_generating()); + window.click("agent-send", cx); + }) + .unwrap(); + assert_eq!(f.commands.cancels.load(Ordering::SeqCst), 1); +} + +#[gpui_kit::test] +fn autonomous_continuation_keeps_the_composer_busy_and_queues_the_next_message( + cx: &mut TestAppContext, +) { + use nocterm_ai::model::session::{ + PromptOutcome, + SessionActivity::{Active, Idle}, + StopReason, + }; + let f = fixture(cx); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + let session = thread.read_with(cx, |thread, _| thread.session().clone().unwrap()); + thread.update(cx, |thread, cx| thread.send("first".into(), cx)); + cx.run_until_parked(); + report_activity(&f, session.clone(), Active, cx); + report_activity(&f, session.clone(), Idle, cx); + report_activity(&f, session.clone(), Active, cx); + f.commands + .pending + .lock() + .unwrap() + .take() + .unwrap() + .send(PromptOutcome::new(StopReason::EndTurn)) + .unwrap(); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("agent-thinking").is_some()); + }) + .unwrap(); + thread.update(cx, |thread, cx| thread.send("second".into(), cx)); + cx.run_until_parked(); + assert_eq!(f.commands.prompts.lock().unwrap().len(), 1); + report_activity(&f, session, Idle, cx); + assert_eq!(f.commands.prompts.lock().unwrap().len(), 2); +} diff --git a/crates/agent/src/panel/tests/history.rs b/crates/agent/src/panel/tests/history.rs index 055ec91a..18c76b3a 100644 --- a/crates/agent/src/panel/tests/history.rs +++ b/crates/agent/src/panel/tests/history.rs @@ -310,6 +310,7 @@ fn history_records_only_accepted_prompts_and_keeps_model_snapshot(cx: &mut TestA thread, SessionUpdate::SessionInfoUpdate(nocterm_ai::model::session::SessionInfo { title: nocterm_ai::model::controls::Change::Set("Updated title".into()), + activity: None, meta: None, }), cx, diff --git a/crates/agent/src/panel/tests/labels.rs b/crates/agent/src/panel/tests/labels.rs index 5bd968a8..9a21f7cb 100644 --- a/crates/agent/src/panel/tests/labels.rs +++ b/crates/agent/src/panel/tests/labels.rs @@ -77,6 +77,7 @@ fn chat_header_and_history_keep_multiline_titles_on_one_line(cx: &mut TestAppCon session, SessionUpdate::SessionInfoUpdate(nocterm_ai::model::session::SessionInfo { title: nocterm_ai::model::controls::Change::Set(agent_title.into()), + activity: None, meta: None, }), ))) diff --git a/crates/ai/src/model/session.rs b/crates/ai/src/model/session.rs index 735c7a21..ad2d893a 100644 --- a/crates/ai/src/model/session.rs +++ b/crates/ai/src/model/session.rs @@ -155,9 +155,17 @@ pub enum TurnActivity { Ended, } +/// A provider's explicit observation of whether the session is running work. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SessionActivity { + Active, + Idle, +} + #[derive(Clone, Debug, Default, PartialEq)] pub struct SessionInfo { pub title: Change, + pub activity: Option, pub meta: Option, } diff --git a/crates/ai/src/session.rs b/crates/ai/src/session.rs index 0bee37ab..9df9d9b4 100644 --- a/crates/ai/src/session.rs +++ b/crates/ai/src/session.rs @@ -5,7 +5,7 @@ //! session" or "failed but still accepting updates" cannot be built. The //! transitions only decide; the chat performs the side effects they ask for //! and drops async results whose [`Ticket`] is no longer current. -use crate::AgentError; +use crate::{AgentError, model::session::SessionActivity}; /// Where a chat's agent session is. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -69,6 +69,8 @@ pub struct SessionState { failures: u32, /// The running turn was started by the agent for another device. external: bool, + /// Latest explicit provider activity, including events racing a prompt response. + observed_active: bool, } impl SessionState { @@ -216,6 +218,31 @@ impl SessionState { self.phase = SessionPhase::Ready; true } + /// Observe session-wide activity without completing a client-owned prompt. + /// Returns whether the visible turn changed; duplicate observations do not redraw. + pub fn observe_activity(&mut self, activity: SessionActivity) -> bool { + if !matches!( + self.phase, + SessionPhase::Opening + | SessionPhase::Ready + | SessionPhase::Prompting + | SessionPhase::Cancelling + ) { + return false; + } + let was_active = self.observed_active; + self.observed_active = activity == SessionActivity::Active; + if self.observed_active { + self.resume_observed_turn() + } else { + was_active && self.finish_external_turn() + } + } + /// A provider may start another turn before the preceding prompt response arrives. + /// Reconcile after the client has settled its own turn and its tool bookkeeping. + pub fn resume_observed_turn(&mut self) -> bool { + self.observed_active && self.start_external_turn() + } /// The running turn is the agent's own, not one of this chat's prompts. pub fn external_turn(&self) -> bool { self.external && self.generating() @@ -234,19 +261,22 @@ impl SessionState { /// The turn of `ticket` finished. Returns whether it was the running /// one; a stale result changes nothing. pub fn finish_turn(&mut self, ticket: Ticket, completed: bool) -> bool { - if !self.turn_current(ticket) || !self.generating() { + if !self.turn_current(ticket) || !self.generating() || self.external { return false; } self.external = false; self.phase = SessionPhase::Ready; if completed { self.failures = 0; + } else { + self.observed_active = false; } true } /// The agent asks the user to sign in. pub fn require_sign_in(&mut self) { self.phase = SessionPhase::SignInRequired; + self.observed_active = false; } /// Returns whether signing in may start. pub fn begin_sign_in(&mut self) -> bool { @@ -271,6 +301,7 @@ impl SessionState { /// The session ended with an error. Results of its requests are dropped. pub fn fail(&mut self) { self.external = false; + self.observed_active = false; self.phase = SessionPhase::Failed; self.epoch += 1; self.stopped = false; @@ -280,6 +311,8 @@ impl SessionState { /// The chat let its connection go. A failed chat stays failed, so the /// user still sees why; otherwise it is detached until needed again. pub fn detach(&mut self) { + self.external = false; + self.observed_active = false; self.epoch += 1; self.closing = true; if self.phase != SessionPhase::Failed { @@ -288,6 +321,8 @@ impl SessionState { } /// The chat released everything it held, a failure included. pub fn release(&mut self) { + self.external = false; + self.observed_active = false; self.phase = SessionPhase::Detached; self.stopped = false; self.discarding = false; diff --git a/crates/ai/src/session/tests.rs b/crates/ai/src/session/tests.rs index 386e1f7c..b7adae18 100644 --- a/crates/ai/src/session/tests.rs +++ b/crates/ai/src/session/tests.rs @@ -173,3 +173,60 @@ fn a_turn_the_agent_runs_for_another_device_shows_and_ends_on_its_own() { ); assert!(state.finish_turn(ticket, true)); } + +#[test] +fn reported_activity_survives_an_earlier_prompt_response() { + let mut state = ready(); + let local = state.start_turn().unwrap(); + assert!(!state.observe_activity(SessionActivity::Active)); + assert!(!state.observe_activity(SessionActivity::Idle)); + assert!( + state.generating(), + "idle never completes the client's request" + ); + assert!(!state.observe_activity(SessionActivity::Active)); + assert!(state.finish_turn(local, true)); + assert!(state.resume_observed_turn()); + assert!(state.generating() && state.busy() && state.external_turn()); + assert!(!state.finish_turn(local, true)); + assert!(!state.observe_activity(SessionActivity::Active)); + assert!(state.start_turn().is_none()); + assert!(state.observe_activity(SessionActivity::Idle)); + assert!(!state.generating()); + assert!(!state.observe_activity(SessionActivity::Idle)); + assert!(state.start_turn().is_some()); +} + +#[test] +fn reported_activity_can_be_cancelled_and_cannot_survive_session_replacement() { + let mut state = ready(); + assert!(state.observe_activity(SessionActivity::Active)); + assert!(state.stop()); + assert!(!state.observe_activity(SessionActivity::Active)); + assert!(state.observe_activity(SessionActivity::Idle)); + assert!(!state.generating() && state.stopped()); + assert!(state.observe_activity(SessionActivity::Active)); + state.detach(); + assert!(!state.observe_activity(SessionActivity::Active)); + state.closed(); + assert!(state.queue()); + state.leased(); + state.opened(); + assert!(!state.resume_observed_turn()); + assert!(!state.generating()); +} + +#[test] +fn normal_prompt_completion_and_cancel_do_not_invent_a_continuation() { + let mut state = ready(); + let turn = state.start_turn().unwrap(); + state.observe_activity(SessionActivity::Active); + state.observe_activity(SessionActivity::Idle); + assert!(state.finish_turn(turn, true)); + assert!(!state.resume_observed_turn()); + let turn = state.start_turn().unwrap(); + state.observe_activity(SessionActivity::Active); + assert!(state.stop()); + assert!(state.finish_turn(turn, false)); + assert!(!state.resume_observed_turn()); +} diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rs index f91707f4..9016a61c 100644 --- a/crates/ai/src/tests.rs +++ b/crates/ai/src/tests.rs @@ -82,6 +82,7 @@ fn update(value: serde_json::Value) -> SessionUpdate { Some(serde_json::Value::Null) => Change::Clear, Some(title) => Change::Set(title.as_str().unwrap().into()), }, + activity: None, meta: None, }), "usage_update" => SessionUpdate::UsageUpdate(ContextUsage::new( diff --git a/crates/hub-io/src/chats/watch.rs b/crates/hub-io/src/chats/watch.rs index fdd1629b..a41424bb 100644 --- a/crates/hub-io/src/chats/watch.rs +++ b/crates/hub-io/src/chats/watch.rs @@ -129,6 +129,7 @@ impl Follow { outputs.push(Output::notice(SessionUpdate::SessionInfoUpdate( SessionInfo { title: Change::Set(chat.title.clone()), + activity: None, meta: None, }, ))); diff --git a/docs/architecture/adapter.md b/docs/architecture/adapter.md index 0cafccc9..7f46a8e3 100644 --- a/docs/architecture/adapter.md +++ b/docs/architecture/adapter.md @@ -309,9 +309,11 @@ authentication, EOF, registration revocation and bridge shutdown without recordi tokens or protocol contents. The ACP adapter maps the connected agent's context usage, token totals and usage -metadata into AI's neutral records. No adapter in Nocterm reads provider sign-in -tokens or session logs, or requests private provider account endpoints. The agent -owns its authentication, requests and state files +metadata into AI's neutral records. The Codex ACP session-info extension +`_meta.codex.threadStatus` is mapped to an optional typed active/idle observation; +other metadata and unknown status values do not decide activity. No adapter in +Nocterm reads provider sign-in tokens or session logs, or requests private +provider account endpoints. The agent owns its authentication, requests and state files ([ADR 0105](../adr/0105-provider-usage-through-acp-only.md)). ## Agent workspace and sandbox diff --git a/docs/architecture/service.md b/docs/architecture/service.md index 4e616793..9cb198fb 100644 --- a/docs/architecture/service.md +++ b/docs/architecture/service.md @@ -98,6 +98,13 @@ and the footer, without changing remembered docked widths. `ConnectionDirectory` methods take the workspace as a weak handle and are called outside workspace updates, because opening a connection updates the workspace. +A session's explicit activity observation can start or end an autonomous turn +without inserting a user prompt or granting a tool scope. A client-owned prompt +still settles on its own response; the latest observed activity is reconciled +before dispatching the next queued message. Repeated activity observations +without a phase change do not trigger a redraw. Session replacement clears the +observation. + Saved history starts as a catalogue of at most 200 metadata rows, with transcript files as the source of truth. Obsolete metadata sidecars are ignored. Opening or editing a row loads its document in the background. A shared loading permit From e18dd21e9fa9bfc1ebbbf79ecf64e1df0b52740b Mon Sep 17 00:00:00 2001 From: egor Date: Fri, 4 Dec 2026 00:41:21 +0500 Subject: [PATCH 2/3] build(vendor): synchronize vendored dependencies from master --- vendor/alacritty_terminal/NOCTERM.md | 45 +- vendor/alacritty_terminal/src/grid/mod.rs | 48 +- vendor/alacritty_terminal/src/grid/resize.rs | 58 +- vendor/alacritty_terminal/src/grid/row.rs | 67 +- vendor/alacritty_terminal/src/grid/storage.rs | 49 +- vendor/alacritty_terminal/src/term/cell.rs | 36 +- vendor/alacritty_terminal/src/term/mod.rs | 155 +- .../src/term/selection_text.rs | 246 + vendor/gpui-base/Cargo.lock | 165 +- vendor/gpui-base/Cargo.toml | 13 +- vendor/gpui-base/NOCTERM.md | 76 + vendor/gpui-base/src/button.rs | 67 +- vendor/gpui-base/src/calendar.rs | 222 +- vendor/gpui-base/src/calendar_grid_tests.rs | 113 + vendor/gpui-base/src/dock/active.rs | 18 +- vendor/gpui-base/src/dock/layout/edit.rs | 153 +- .../src/dock/layout/edit/split_sizes_tests.rs | 151 + vendor/gpui-base/src/dock/layout/mod.rs | 5 +- vendor/gpui-base/src/dock/layout/node.rs | 6 +- vendor/gpui-base/src/dock/layout/tree.rs | 45 +- vendor/gpui-base/src/dock/tab_group.rs | 1193 +-- .../src/dock/tab_group/constraints.rs | 2 +- .../gpui-base/src/dock/tab_group/rendering.rs | 280 + vendor/gpui-base/src/dock/tab_group/tests.rs | 615 ++ .../src/dock/tab_group/tests/rendering.rs | 259 + .../src/dock/tab_group/tests/selection.rs | 126 + vendor/gpui-base/src/frame_loop.rs | 114 + vendor/gpui-base/src/input/base/element.rs | 78 +- .../src/input/base/highlight_shape.rs | 89 + vendor/gpui-base/src/input/base/state.rs | 9 +- vendor/gpui-base/src/input/mod.rs | 3 + vendor/gpui-base/src/lib.rs | 4 + vendor/gpui-base/src/resizable/mod.rs | 55 +- .../src/resizable/tests/drag_work.rs | 98 + vendor/gpui-base/src/scrollbar.rs | 2453 +---- vendor/gpui-base/src/scrollbar/appearance.rs | 400 + vendor/gpui-base/src/scrollbar/element.rs | 661 ++ vendor/gpui-base/src/scrollbar/motion.rs | 711 ++ vendor/gpui-base/src/scrollbar/redraw.rs | 86 + vendor/gpui-base/src/scrollbar/tests.rs | 751 ++ vendor/gpui-base/src/text/document.rs | 40 +- vendor/gpui-base/src/text/inline.rs | 2001 +--- .../src/text/inline/fade_highlights_tests.rs | 36 + vendor/gpui-base/src/text/inline/geometry.rs | 204 + .../gpui-base/src/text/inline/highlights.rs | 214 + .../src/text/inline/line_bounds_tests.rs | 149 + vendor/gpui-base/src/text/inline/pointer.rs | 234 + .../src/text/inline/range_highlight_tests.rs | 160 + .../src/text/inline/retained_layout.rs | 107 + .../src/text/inline/retained_layout/tests.rs | 127 + vendor/gpui-base/src/text/inline/test_draw.rs | 44 + .../gpui-base/src/text/inline/test_fonts.rs | 181 + vendor/gpui-base/src/text/inline/tests.rs | 410 + vendor/gpui-base/src/text/inline_flow.rs | 1444 +-- .../gpui-base/src/text/inline_flow/layout.rs | 685 ++ .../src/text/inline_flow/layout/wrapping.rs | 189 + .../gpui-base/src/text/inline_flow/tests.rs | 493 + vendor/gpui-base/src/text/node.rs | 90 +- vendor/gpui-base/src/text_selection.rs | 259 +- vendor/gpui-base/src/time_field.rs | 48 +- vendor/gpui-base/tests/element_ext.rs | 7 + vendor/gpui-base/tests/flow_layout.rs | 91 + .../gpui-base/tests/inline_layout_sweeps.rs | 297 + vendor/gpui-base/tests/inline_pointer.rs | 119 + vendor/gpui-base/tests/paragraph_layout.rs | 161 + vendor/gpui-base/tests/selection_highlight.rs | 148 + vendor/gpui-component/Cargo.lock | 190 +- vendor/gpui-component/Cargo.toml | 14 +- vendor/gpui-component/NOCTERM.md | 67 + vendor/gpui-component/src/button/button.rs | 1325 +-- .../src/button/button/performance.rs | 83 + .../gpui-component/src/button/button/tests.rs | 689 ++ .../src/button/button/variant.rs | 628 ++ vendor/gpui-component/src/command/command.rs | 41 +- vendor/gpui-component/src/command/item.rs | 18 +- vendor/gpui-component/src/command/state.rs | 267 +- vendor/gpui-component/src/dock/panel.rs | 15 +- vendor/gpui-component/src/dock/tab_panel.rs | 213 +- .../src/dock/tab_panel/drag_preview.rs | 2 +- .../src/dock/tab_panel/tests/mod.rs | 10 +- .../src/dock/tab_panel/tests/rendering.rs | 29 + vendor/gpui-component/src/list/list.rs | 233 +- .../gpui-component/src/list/list/element.rs | 84 + .../src/list/list/measurement_tests.rs | 108 + .../src/list/list/search_tests.rs | 121 + vendor/gpui-component/src/shimmer.rs | 9 +- vendor/gpui-component/src/spinner.rs | 27 +- vendor/gpui-component/src/switch.rs | 137 +- vendor/gpui-component/src/tab/tab.rs | 459 +- vendor/gpui-component/src/tab/tab/variant.rs | 420 + vendor/gpui-component/src/tab/tab_bar.rs | 524 +- .../gpui-component/src/tab/tab_bar/tests.rs | 519 + vendor/gpui-component/src/time/calendar.rs | 9 +- vendor/gpui-component/src/time/date_picker.rs | 82 +- vendor/gpui-component/src/time/utils.rs | 200 - vendor/gpui-component/src/tooltip.rs | 4 +- vendor/gpui-pre-linux/Cargo.lock | 6835 ++++++++++++ vendor/gpui-pre-linux/Cargo.toml | 314 + vendor/gpui-pre-linux/Cargo.toml.orig | 107 + vendor/gpui-pre-linux/LICENSE-APACHE | 222 + vendor/gpui-pre-linux/NOCTERM_PATCH.md | 35 + vendor/gpui-pre-linux/src/gpui_linux.rs | 4 + vendor/gpui-pre-linux/src/linux.rs | 60 + vendor/gpui-pre-linux/src/linux/dispatcher.rs | 365 + vendor/gpui-pre-linux/src/linux/headless.rs | 4 + .../src/linux/headless/client.rs | 151 + .../src/linux/headless/window.rs | 236 + vendor/gpui-pre-linux/src/linux/keyboard.rs | 22 + vendor/gpui-pre-linux/src/linux/platform.rs | 410 + .../src/linux/platform/desktop.rs | 695 ++ .../src/linux/platform/desktop/tests.rs | 89 + .../src/linux/platform/keymap.rs | 324 + .../src/linux/platform/tests.rs | 117 + .../src/linux/system_notifications.rs | 154 + .../gpui-pre-linux/src/linux/text_system.rs | 1 + vendor/gpui-pre-linux/src/linux/wayland.rs | 42 + .../src/linux/wayland/client.rs | 628 ++ .../src/linux/wayland/client/connection.rs | 596 ++ .../src/linux/wayland/client/data_device.rs | 620 ++ .../src/linux/wayland/client/dmabuf.rs | 68 + .../src/linux/wayland/client/ime.rs | 245 + .../src/linux/wayland/client/keyboard.rs | 307 + .../src/linux/wayland/client/pointer.rs | 453 + .../src/linux/wayland/client/surfaces.rs | 379 + .../src/linux/wayland/clipboard.rs | 414 + .../src/linux/wayland/clipboard/reader.rs | 318 + .../src/linux/wayland/cursor.rs | 152 + .../src/linux/wayland/display.rs | 42 + .../src/linux/wayland/layer_shell.rs | 26 + .../gpui-pre-linux/src/linux/wayland/popup.rs | 38 + .../src/linux/wayland/serial.rs | 126 + .../src/linux/wayland/window.rs | 2332 ++++ vendor/gpui-pre-linux/src/linux/x11.rs | 12 + vendor/gpui-pre-linux/src/linux/x11/client.rs | 3156 ++++++ .../gpui-pre-linux/src/linux/x11/clipboard.rs | 696 ++ .../src/linux/x11/clipboard/error.rs | 102 + .../src/linux/x11/clipboard/protocol.rs | 197 + .../src/linux/x11/clipboard/reader.rs | 618 ++ .../gpui-pre-linux/src/linux/x11/display.rs | 51 + vendor/gpui-pre-linux/src/linux/x11/event.rs | 154 + vendor/gpui-pre-linux/src/linux/x11/window.rs | 2055 ++++ .../src/linux/x11/xim_handler.rs | 133 + .../src/linux/xdg_desktop_portal.rs | 191 + vendor/gpui-pre-scheduler/Cargo.toml | 97 + vendor/gpui-pre-scheduler/LICENSE-APACHE | 222 + vendor/gpui-pre-scheduler/src/clock.rs | 68 + vendor/gpui-pre-scheduler/src/executor.rs | 811 ++ vendor/gpui-pre-scheduler/src/scheduler.rs | 252 + .../gpui-pre-scheduler/src/test_scheduler.rs | 970 ++ vendor/gpui-pre-scheduler/src/tests.rs | 987 ++ vendor/gpui-pre-wgpu/Cargo.lock | 102 +- vendor/gpui-pre-wgpu/Cargo.toml | 6 + vendor/gpui-pre-wgpu/NOCTERM_PATCH.md | 72 +- vendor/gpui-pre-wgpu/benches/layout_line.rs | 17 +- .../src/cosmic_text_system/helpers.rs | 6 +- .../src/cosmic_text_system/tests.rs | 5 +- vendor/gpui-pre-wgpu/src/shaders.wgsl | 60 +- vendor/gpui-pre-wgpu/src/wgpu_atlas.rs | 53 +- vendor/gpui-pre-wgpu/src/wgpu_context.rs | 110 +- .../gpui-pre-wgpu/src/wgpu_context/native.rs | 216 + vendor/gpui-pre-wgpu/src/wgpu_renderer.rs | 126 +- .../gpui-pre-wgpu/src/wgpu_renderer/frame.rs | 296 +- .../src/wgpu_renderer/frame_uniforms.rs | 121 + .../src/wgpu_renderer/instances.rs | 28 +- .../src/wgpu_renderer/lifecycle.rs | 110 +- .../src/wgpu_renderer/path_region.rs | 82 + .../gpui-pre-wgpu/src/wgpu_renderer/paths.rs | 4 +- .../src/wgpu_renderer/pipelines.rs | 14 - .../src/wgpu_renderer/resources.rs | 146 +- .../src/wgpu_renderer/retained.rs | 106 +- .../src/wgpu_renderer/retained/tests.rs | 129 +- .../retained/tests/window_scene.rs | 190 + .../gpui-pre-wgpu/src/wgpu_renderer/tests.rs | 264 + .../src/wgpu_renderer/tests/atlas_sprites.rs | 274 + .../gpui-pre-wgpu/src/wgpu_renderer/timing.rs | 118 + vendor/gpui-pre-windows/Cargo.lock | 128 +- vendor/gpui-pre-windows/Cargo.toml | 6 + vendor/gpui-pre-zlog/Cargo.toml | 80 + vendor/gpui-pre-zlog/LICENSE-APACHE | 222 + vendor/gpui-pre-zlog/README.md | 15 + vendor/gpui-pre-zlog/src/env_config.rs | 122 + vendor/gpui-pre-zlog/src/filter.rs | 843 ++ vendor/gpui-pre-zlog/src/sink.rs | 337 + vendor/gpui-pre-zlog/src/zlog.rs | 409 + vendor/gpui-pre/Cargo.lock | 274 +- vendor/gpui-pre/Cargo.toml | 25 +- vendor/gpui-pre/NOCTERM_PATCH.md | 145 +- vendor/gpui-pre/src/app.rs | 48 +- vendor/gpui-pre/src/app/context.rs | 8 + vendor/gpui-pre/src/app/entity_map.rs | 23 +- vendor/gpui-pre/src/app/entity_map/read.rs | 43 + vendor/gpui-pre/src/element.rs | 75 +- vendor/gpui-pre/src/element/a11y.rs | 80 + vendor/gpui-pre/src/elements/animation.rs | 564 +- .../gpui-pre/src/elements/animation/tests.rs | 529 + vendor/gpui-pre/src/elements/img.rs | 241 +- vendor/gpui-pre/src/elements/img/animation.rs | 88 + vendor/gpui-pre/src/elements/img/tests.rs | 245 + vendor/gpui-pre/src/elements/text.rs | 243 +- .../gpui-pre/src/elements/text/measurement.rs | 164 + vendor/gpui-pre/src/gpui.rs | 14 + vendor/gpui-pre/src/platform.rs | 18 +- vendor/gpui-pre/src/platform/atlas.rs | 29 + vendor/gpui-pre/src/platform_scheduler.rs | 7 +- vendor/gpui-pre/src/scene.rs | 470 +- vendor/gpui-pre/src/scene/batches.rs | 305 + vendor/gpui-pre/src/scene/paint_replay.rs | 231 + vendor/gpui-pre/src/scene/tests.rs | 174 + vendor/gpui-pre/src/svg_renderer.rs | 11 +- vendor/gpui-pre/src/tab_stop.rs | 313 +- vendor/gpui-pre/src/taffy.rs | 77 +- vendor/gpui-pre/src/text_system.rs | 761 +- vendor/gpui-pre/src/text_system/font.rs | 272 + vendor/gpui-pre/src/text_system/line.rs | 10 + .../text_system/nocterm_background_tests.rs | 139 + .../gpui-pre/src/text_system/window_text.rs | 619 ++ vendor/gpui-pre/src/view.rs | 356 +- vendor/gpui-pre/src/view/cache.rs | 501 + vendor/gpui-pre/src/window.rs | 195 +- vendor/gpui-pre/src/window/a11y.rs | 283 +- vendor/gpui-pre/src/window/a11y/debug.rs | 170 +- vendor/gpui-pre/src/window/a11y/tree.rs | 353 + .../gpui-pre/src/window/element_state_key.rs | 81 + .../gpui-pre/src/window/input_presentation.rs | 143 +- .../src/window/paint_invalidation_tests.rs | 111 + vendor/gpui-pre/src/window/raster_tiles.rs | 173 + .../gpui-pre/tests/nocterm_element_state.rs | 204 + .../gpui-pre/tests/nocterm_list_estimates.rs | 222 +- vendor/gpui-pre/tests/nocterm_measurements.rs | 573 + vendor/gpui-pre/tests/nocterm_scene_replay.rs | 217 + .../tests/scene_replay/batch_order.rs | 137 + vendor/markdown/.cargo_vcs_info.json | 6 + vendor/markdown/Cargo.lock | 1897 ++++ vendor/markdown/Cargo.toml | 90 + vendor/markdown/Cargo.toml.orig | 47 + vendor/markdown/NOCTERM.md | 11 + vendor/markdown/README.md | 443 + vendor/markdown/license | 22 + vendor/markdown/src/configuration.rs | 1543 +++ vendor/markdown/src/construct/attention.rs | 440 + vendor/markdown/src/construct/autolink.rs | 358 + vendor/markdown/src/construct/blank_line.rs | 88 + vendor/markdown/src/construct/block_quote.rs | 135 + .../src/construct/character_escape.rs | 85 + .../src/construct/character_reference.rs | 204 + .../markdown/src/construct/code_indented.rs | 192 + vendor/markdown/src/construct/content.rs | 189 + vendor/markdown/src/construct/definition.rs | 404 + vendor/markdown/src/construct/document.rs | 628 ++ vendor/markdown/src/construct/flow.rs | 281 + vendor/markdown/src/construct/frontmatter.rs | 290 + .../src/construct/gfm_autolink_literal.rs | 849 ++ .../src/construct/gfm_footnote_definition.rs | 423 + .../src/construct/gfm_label_start_footnote.rs | 92 + vendor/markdown/src/construct/gfm_table.rs | 1038 ++ .../src/construct/gfm_task_list_item_check.rs | 157 + .../src/construct/hard_break_escape.rs | 85 + vendor/markdown/src/construct/heading_atx.rs | 280 + .../markdown/src/construct/heading_setext.rs | 281 + vendor/markdown/src/construct/html_flow.rs | 873 ++ vendor/markdown/src/construct/html_text.rs | 659 ++ vendor/markdown/src/construct/label_end.rs | 838 ++ .../src/construct/label_start_image.rs | 119 + .../src/construct/label_start_link.rs | 64 + vendor/markdown/src/construct/list_item.rs | 474 + vendor/markdown/src/construct/mdx_esm.rs | 238 + .../src/construct/mdx_expression_flow.rs | 179 + .../src/construct/mdx_expression_text.rs | 64 + vendor/markdown/src/construct/mdx_jsx_flow.rs | 168 + vendor/markdown/src/construct/mdx_jsx_text.rs | 76 + vendor/markdown/src/construct/mod.rs | 198 + vendor/markdown/src/construct/paragraph.rs | 115 + vendor/markdown/src/construct/partial_bom.rs | 67 + vendor/markdown/src/construct/partial_data.rs | 110 + .../src/construct/partial_destination.rs | 251 + .../markdown/src/construct/partial_label.rs | 220 + .../src/construct/partial_mdx_expression.rs | 263 + .../markdown/src/construct/partial_mdx_jsx.rs | 1144 ++ .../partial_non_lazy_continuation.rs | 49 + .../src/construct/partial_space_or_tab.rs | 153 + .../src/construct/partial_space_or_tab_eol.rs | 208 + .../markdown/src/construct/partial_title.rs | 196 + .../src/construct/partial_whitespace.rs | 213 + vendor/markdown/src/construct/raw_flow.rs | 663 ++ vendor/markdown/src/construct/raw_text.rs | 271 + vendor/markdown/src/construct/string.rs | 81 + vendor/markdown/src/construct/text.rs | 264 + .../markdown/src/construct/thematic_break.rs | 155 + vendor/markdown/src/event.rs | 3570 +++++++ vendor/markdown/src/lib.rs | 164 + vendor/markdown/src/mdast.rs | 2345 ++++ vendor/markdown/src/message.rs | 46 + vendor/markdown/src/parser.rs | 79 + vendor/markdown/src/resolve.rs | 81 + vendor/markdown/src/state.rs | 971 ++ vendor/markdown/src/subtokenize.rs | 275 + vendor/markdown/src/to_html.rs | 1751 +++ vendor/markdown/src/to_mdast.rs | 1830 ++++ vendor/markdown/src/tokenizer.rs | 824 ++ vendor/markdown/src/unist.rs | 103 + vendor/markdown/src/util/char.rs | 251 + .../markdown/src/util/character_reference.rs | 217 + vendor/markdown/src/util/constant.rs | 2756 +++++ vendor/markdown/src/util/edit_map.rs | 234 + vendor/markdown/src/util/edit_map/tests.rs | 66 + vendor/markdown/src/util/encode.rs | 55 + vendor/markdown/src/util/gfm_tagfilter.rs | 78 + vendor/markdown/src/util/identifier.rs | 17 + vendor/markdown/src/util/infer.rs | 192 + vendor/markdown/src/util/line_ending.rs | 130 + vendor/markdown/src/util/location.rs | 210 + vendor/markdown/src/util/mdx.rs | 130 + vendor/markdown/src/util/mdx_collect.rs | 53 + vendor/markdown/src/util/mod.rs | 19 + .../markdown/src/util/normalize_identifier.rs | 78 + vendor/markdown/src/util/sanitize_uri.rs | 148 + vendor/markdown/src/util/skip.rs | 80 + vendor/markdown/src/util/slice.rs | 125 + vendor/markdown/src/util/unicode.rs | 9388 +++++++++++++++++ vendor/patches/README.md | 8 +- .../0002-reflow-row-transfers.patch | 48 + .../0003-grow-scrollback-in-batches.patch | 56 + .../0004-skip-empty-line-metadata-scans.patch | 22 + .../0005-track-searchable-grid-changes.patch | 57 + ...6-version-terminal-palette-overrides.patch | 27 + .../0007-track-history-rotation.patch | 26 + .../0008-expose-row-occupancy-bound.patch | 28 + .../0009-bound-narrowing-reflow.patch | 53 + ...-probe-selected-text-without-copying.patch | 97 + .../0011-bound-selected-text-prefix.patch | 41 + .../0012-bound-clipboard-line-length.patch | 34 + .../0007-frame-driven-selection.patch | 119 + .../0008-append-inline-highlights.patch | 46 + .../0009-clip-inline-line-bounds.patch | 32 + .../0010-reserve-visible-line-bounds.patch | 14 + .../0011-amortize-inline-layout-sweeps.patch | 189 + ...ve-inline-layout-without-placeholder.patch | 52 + ...0013-prepaint-positioned-inline-text.patch | 307 + .../0014-use-measured-paragraph-spacing.patch | 109 + ...15-draw-rectangular-input-selections.patch | 131 + ...0016-refresh-input-on-alt-transition.patch | 67 + ...017-group-long-text-paragraph-layout.patch | 85 + ...0018-resolve-grouped-paragraph-width.patch | 40 + .../0019-limit-inline-pointer-listeners.patch | 938 ++ .../0020-omit-clipped-inline-hitboxes.patch | 541 + .../0021-window-inline-highlight-ranges.patch | 114 + .../0022-group-text-with-inline-code.patch | 49 + .../0023-pace-passive-scrollbar-fades.patch | 943 ++ ...-counting-after-second-visible-panel.patch | 21 + .../0025-retain-tab-panel-subscriptions.patch | 622 ++ .../0026-keep-tab-selection-local.patch | 268 + .../0027-resize-split-sizes-in-place.patch | 239 + .../0028-commit-split-sizes-locally.patch | 235 + ...ep-observers-on-tab-membership-edits.patch | 55 + ...-store-button-state-styles-on-demand.patch | 44 + .../patches/gpui-base/0031-migrate-jiff.patch | 187 + .../0002-reuse-command-row-measurements.patch | 46 + .../0003-skip-zero-tooltip-slides.patch | 23 + .../0004-refresh-dock-test-frames.patch | 21 + .../0005-pace-repeating-shimmer.patch | 26 + .../0006-pace-loading-spinner.patch | 25 + .../0007-install-fixed-command-models.patch | 27 + .../0008-limit-plain-picker-row-layout.patch | 79 + .../0009-skip-loading-for-ready-search.patch | 171 + ...er-offscreen-command-row-measurement.patch | 29 + ...-share-tab-bar-interaction-snapshots.patch | 36 + .../0012-avoid-redundant-tab-strip-work.patch | 319 + .../0013-prepare-tab-styles-on-demand.patch | 217 + ...-settle-switch-within-physical-pixel.patch | 59 + ...0015-prepare-button-styles-on-demand.patch | 517 + .../gpui-component/0016-migrate-jiff.patch | 157 + ...p-wayland-data-transfers-nonblocking.patch | 69 + .../0002-share-outgoing-plain-text.patch | 50 + ...ead-wayland-clipboard-asynchronously.patch | 1696 +++ ...004-wait-for-x11-clipboard-readiness.patch | 578 + .../gpui-pre-linux/0005-migrate-jiff.patch | 44 + .../0001-migrate-jiff.patch | 36 + .../gpui-pre-wgpu/0002-frame-timestamps.patch | 91 + .../0003-lazy-path-textures.patch | 25 + .../0004-skip-ascii-bidi-lookup.patch | 51 + ...05-prepare-only-used-frame-resources.patch | 155 + ...006-collect-atlas-pages-from-sprites.patch | 82 + .../0007-omit-unused-video-pipeline.patch | 66 + .../0008-defer-egl-until-required.patch | 135 + ...retry-presentation-after-device-loss.patch | 28 + ...led-device-recovery-without-blocking.patch | 106 + ...measure-retained-presentation-copies.patch | 75 + ...-reuse-finalized-window-presentation.patch | 95 + ...nux-instance-buffer-for-small-frames.patch | 48 + ...14-reuse-instance-bindings-on-repeat.patch | 68 + ...0015-reuse-ordered-batches-on-repeat.patch | 82 + ...016-bound-path-intermediate-textures.patch | 151 + .../0017-compact-large-polychrome-pages.patch | 92 + .../gpui-pre-wgpu/0018-migrate-jiff.patch | 41 + .../gpui-pre-windows/0002-migrate-jiff.patch | 45 + .../gpui-pre-zlog/0001-migrate-jiff.patch | 25 + .../gpui-pre/0006-frame-glyph-tiles.patch | 78 + ...t-key-presses-for-input-presentation.patch | 90 + .../0008-skip-empty-text-backgrounds.patch | 69 + .../0009-schedule-animated-image-frames.patch | 160 + ...0010-share-paced-animation-deadlines.patch | 265 + .../0011-size-line-decoration-storage.patch | 456 + .../0012-look-up-rendered-views.patch | 29 + .../0013-untracked-entity-reads.patch | 52 + ...in-content-cache-layout-dependencies.patch | 58 + ...alidation-associations-incrementally.patch | 100 + ...0016-borrow-keyed-element-state-path.patch | 117 + .../0017-release-measurement-captures.patch | 82 + .../0018-compact-window-paint-replay.patch | 366 + .../0019-select-next-scene-batches.patch | 74 + .../0020-measure-positioned-styled-text.patch | 113 + ...easure-styled-text-with-layout-style.patch | 28 + ...fer-scene-build-while-device-is-lost.patch | 69 + ...-reuse-input-tree-during-device-loss.patch | 92 + ...identify-finalized-window-draw-lists.patch | 62 + ...rtcut-actions-for-input-presentation.patch | 41 + .../0026-sort-frame-focus-order-once.patch | 140 + ...reuse-accessibility-diagnostic-nodes.patch | 108 + ...8-reuse-frame-accessibility-node-ids.patch | 152 + ...0029-keep-cached-controls-accessible.patch | 281 + .../0030-reuse-accessible-element-id.patch | 75 + ...031-expose-parsed-svg-intrinsic-size.patch | 16 + ...-consolidate-layout-coordinate-cache.patch | 125 + ...3-remove-redundant-test-handle-clone.patch | 10 + .../0034-acquire-text-wrapper-on-demand.patch | 74 + .../patches/gpui-pre/0035-migrate-jiff.patch | 136 + .../markdown/0001-batch-tokenizer-edits.patch | 133 + .../russh-util/0001-migrate-jiff.patch | 117 + vendor/patches/sources.json | 235 +- .../0001-vectorize-string-scans.patch | 49 + ...0002-bound-initial-token-reservation.patch | 26 + vendor/russh-util/Cargo.toml | 58 + vendor/russh-util/LICENSE-2.0.txt | 202 + vendor/russh-util/src/lib.rs | 2 + vendor/russh-util/src/runtime.rs | 63 + vendor/russh-util/src/time.rs | 29 + vendor/toml_parser/.cargo_vcs_info.json | 6 + vendor/toml_parser/Cargo.lock | 284 + vendor/toml_parser/Cargo.toml | 197 + vendor/toml_parser/Cargo.toml.orig | 46 + vendor/toml_parser/LICENSE-APACHE | 202 + vendor/toml_parser/LICENSE-MIT | 19 + vendor/toml_parser/NOCTERM.md | 19 + vendor/toml_parser/README.md | 21 + vendor/toml_parser/src/debug.rs | 140 + vendor/toml_parser/src/decoder/mod.rs | 117 + vendor/toml_parser/src/decoder/scalar.rs | 797 ++ vendor/toml_parser/src/decoder/string.rs | 1321 +++ vendor/toml_parser/src/decoder/ws.rs | 76 + vendor/toml_parser/src/error.rs | 102 + vendor/toml_parser/src/lexer/mod.rs | 637 ++ vendor/toml_parser/src/lexer/test.rs | 1700 +++ vendor/toml_parser/src/lexer/token.rs | 106 + vendor/toml_parser/src/lib.rs | 49 + vendor/toml_parser/src/macros.rs | 1 + vendor/toml_parser/src/parser/document.rs | 1631 +++ vendor/toml_parser/src/parser/event.rs | 543 + vendor/toml_parser/src/parser/mod.rs | 16 + vendor/toml_parser/src/source.rs | 394 + 459 files changed, 122141 insertions(+), 14216 deletions(-) create mode 100644 vendor/alacritty_terminal/src/term/selection_text.rs create mode 100644 vendor/gpui-base/src/calendar_grid_tests.rs create mode 100644 vendor/gpui-base/src/dock/layout/edit/split_sizes_tests.rs create mode 100644 vendor/gpui-base/src/dock/tab_group/rendering.rs create mode 100644 vendor/gpui-base/src/dock/tab_group/tests.rs create mode 100644 vendor/gpui-base/src/dock/tab_group/tests/rendering.rs create mode 100644 vendor/gpui-base/src/dock/tab_group/tests/selection.rs create mode 100644 vendor/gpui-base/src/frame_loop.rs create mode 100644 vendor/gpui-base/src/input/base/highlight_shape.rs create mode 100644 vendor/gpui-base/src/resizable/tests/drag_work.rs create mode 100644 vendor/gpui-base/src/scrollbar/appearance.rs create mode 100644 vendor/gpui-base/src/scrollbar/element.rs create mode 100644 vendor/gpui-base/src/scrollbar/motion.rs create mode 100644 vendor/gpui-base/src/scrollbar/redraw.rs create mode 100644 vendor/gpui-base/src/scrollbar/tests.rs create mode 100644 vendor/gpui-base/src/text/inline/fade_highlights_tests.rs create mode 100644 vendor/gpui-base/src/text/inline/geometry.rs create mode 100644 vendor/gpui-base/src/text/inline/highlights.rs create mode 100644 vendor/gpui-base/src/text/inline/line_bounds_tests.rs create mode 100644 vendor/gpui-base/src/text/inline/pointer.rs create mode 100644 vendor/gpui-base/src/text/inline/range_highlight_tests.rs create mode 100644 vendor/gpui-base/src/text/inline/retained_layout.rs create mode 100644 vendor/gpui-base/src/text/inline/retained_layout/tests.rs create mode 100644 vendor/gpui-base/src/text/inline/test_draw.rs create mode 100644 vendor/gpui-base/src/text/inline/test_fonts.rs create mode 100644 vendor/gpui-base/src/text/inline/tests.rs create mode 100644 vendor/gpui-base/src/text/inline_flow/layout.rs create mode 100644 vendor/gpui-base/src/text/inline_flow/layout/wrapping.rs create mode 100644 vendor/gpui-base/src/text/inline_flow/tests.rs create mode 100644 vendor/gpui-base/tests/flow_layout.rs create mode 100644 vendor/gpui-base/tests/inline_layout_sweeps.rs create mode 100644 vendor/gpui-base/tests/inline_pointer.rs create mode 100644 vendor/gpui-base/tests/paragraph_layout.rs create mode 100644 vendor/gpui-base/tests/selection_highlight.rs create mode 100644 vendor/gpui-component/src/button/button/performance.rs create mode 100644 vendor/gpui-component/src/button/button/tests.rs create mode 100644 vendor/gpui-component/src/button/button/variant.rs create mode 100644 vendor/gpui-component/src/list/list/element.rs create mode 100644 vendor/gpui-component/src/list/list/measurement_tests.rs create mode 100644 vendor/gpui-component/src/list/list/search_tests.rs create mode 100644 vendor/gpui-component/src/tab/tab/variant.rs create mode 100644 vendor/gpui-component/src/tab/tab_bar/tests.rs delete mode 100644 vendor/gpui-component/src/time/utils.rs create mode 100644 vendor/gpui-pre-linux/Cargo.lock create mode 100644 vendor/gpui-pre-linux/Cargo.toml create mode 100644 vendor/gpui-pre-linux/Cargo.toml.orig create mode 100644 vendor/gpui-pre-linux/LICENSE-APACHE create mode 100644 vendor/gpui-pre-linux/NOCTERM_PATCH.md create mode 100644 vendor/gpui-pre-linux/src/gpui_linux.rs create mode 100644 vendor/gpui-pre-linux/src/linux.rs create mode 100644 vendor/gpui-pre-linux/src/linux/dispatcher.rs create mode 100644 vendor/gpui-pre-linux/src/linux/headless.rs create mode 100644 vendor/gpui-pre-linux/src/linux/headless/client.rs create mode 100644 vendor/gpui-pre-linux/src/linux/headless/window.rs create mode 100644 vendor/gpui-pre-linux/src/linux/keyboard.rs create mode 100644 vendor/gpui-pre-linux/src/linux/platform.rs create mode 100644 vendor/gpui-pre-linux/src/linux/platform/desktop.rs create mode 100644 vendor/gpui-pre-linux/src/linux/platform/desktop/tests.rs create mode 100644 vendor/gpui-pre-linux/src/linux/platform/keymap.rs create mode 100644 vendor/gpui-pre-linux/src/linux/platform/tests.rs create mode 100644 vendor/gpui-pre-linux/src/linux/system_notifications.rs create mode 100644 vendor/gpui-pre-linux/src/linux/text_system.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/client.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/client/connection.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/client/data_device.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/client/dmabuf.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/client/ime.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/client/keyboard.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/client/pointer.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/client/surfaces.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/clipboard.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/clipboard/reader.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/cursor.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/display.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/layer_shell.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/popup.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/serial.rs create mode 100644 vendor/gpui-pre-linux/src/linux/wayland/window.rs create mode 100644 vendor/gpui-pre-linux/src/linux/x11.rs create mode 100644 vendor/gpui-pre-linux/src/linux/x11/client.rs create mode 100644 vendor/gpui-pre-linux/src/linux/x11/clipboard.rs create mode 100644 vendor/gpui-pre-linux/src/linux/x11/clipboard/error.rs create mode 100644 vendor/gpui-pre-linux/src/linux/x11/clipboard/protocol.rs create mode 100644 vendor/gpui-pre-linux/src/linux/x11/clipboard/reader.rs create mode 100644 vendor/gpui-pre-linux/src/linux/x11/display.rs create mode 100644 vendor/gpui-pre-linux/src/linux/x11/event.rs create mode 100644 vendor/gpui-pre-linux/src/linux/x11/window.rs create mode 100644 vendor/gpui-pre-linux/src/linux/x11/xim_handler.rs create mode 100644 vendor/gpui-pre-linux/src/linux/xdg_desktop_portal.rs create mode 100644 vendor/gpui-pre-scheduler/Cargo.toml create mode 100644 vendor/gpui-pre-scheduler/LICENSE-APACHE create mode 100644 vendor/gpui-pre-scheduler/src/clock.rs create mode 100644 vendor/gpui-pre-scheduler/src/executor.rs create mode 100644 vendor/gpui-pre-scheduler/src/scheduler.rs create mode 100644 vendor/gpui-pre-scheduler/src/test_scheduler.rs create mode 100644 vendor/gpui-pre-scheduler/src/tests.rs create mode 100644 vendor/gpui-pre-wgpu/src/wgpu_context/native.rs create mode 100644 vendor/gpui-pre-wgpu/src/wgpu_renderer/frame_uniforms.rs create mode 100644 vendor/gpui-pre-wgpu/src/wgpu_renderer/path_region.rs create mode 100644 vendor/gpui-pre-wgpu/src/wgpu_renderer/retained/tests/window_scene.rs create mode 100644 vendor/gpui-pre-wgpu/src/wgpu_renderer/tests/atlas_sprites.rs create mode 100644 vendor/gpui-pre-wgpu/src/wgpu_renderer/timing.rs create mode 100644 vendor/gpui-pre-zlog/Cargo.toml create mode 100644 vendor/gpui-pre-zlog/LICENSE-APACHE create mode 100644 vendor/gpui-pre-zlog/README.md create mode 100644 vendor/gpui-pre-zlog/src/env_config.rs create mode 100644 vendor/gpui-pre-zlog/src/filter.rs create mode 100644 vendor/gpui-pre-zlog/src/sink.rs create mode 100644 vendor/gpui-pre-zlog/src/zlog.rs create mode 100644 vendor/gpui-pre/src/app/entity_map/read.rs create mode 100644 vendor/gpui-pre/src/element/a11y.rs create mode 100644 vendor/gpui-pre/src/elements/animation/tests.rs create mode 100644 vendor/gpui-pre/src/elements/img/animation.rs create mode 100644 vendor/gpui-pre/src/elements/img/tests.rs create mode 100644 vendor/gpui-pre/src/elements/text/measurement.rs create mode 100644 vendor/gpui-pre/src/platform/atlas.rs create mode 100644 vendor/gpui-pre/src/scene/batches.rs create mode 100644 vendor/gpui-pre/src/scene/paint_replay.rs create mode 100644 vendor/gpui-pre/src/scene/tests.rs create mode 100644 vendor/gpui-pre/src/text_system/font.rs create mode 100644 vendor/gpui-pre/src/text_system/nocterm_background_tests.rs create mode 100644 vendor/gpui-pre/src/text_system/window_text.rs create mode 100644 vendor/gpui-pre/src/view/cache.rs create mode 100644 vendor/gpui-pre/src/window/a11y/tree.rs create mode 100644 vendor/gpui-pre/src/window/element_state_key.rs create mode 100644 vendor/gpui-pre/src/window/paint_invalidation_tests.rs create mode 100644 vendor/gpui-pre/src/window/raster_tiles.rs create mode 100644 vendor/gpui-pre/tests/nocterm_element_state.rs create mode 100644 vendor/gpui-pre/tests/nocterm_measurements.rs create mode 100644 vendor/gpui-pre/tests/nocterm_scene_replay.rs create mode 100644 vendor/gpui-pre/tests/scene_replay/batch_order.rs create mode 100644 vendor/markdown/.cargo_vcs_info.json create mode 100644 vendor/markdown/Cargo.lock create mode 100644 vendor/markdown/Cargo.toml create mode 100644 vendor/markdown/Cargo.toml.orig create mode 100644 vendor/markdown/NOCTERM.md create mode 100644 vendor/markdown/README.md create mode 100644 vendor/markdown/license create mode 100644 vendor/markdown/src/configuration.rs create mode 100644 vendor/markdown/src/construct/attention.rs create mode 100644 vendor/markdown/src/construct/autolink.rs create mode 100644 vendor/markdown/src/construct/blank_line.rs create mode 100644 vendor/markdown/src/construct/block_quote.rs create mode 100644 vendor/markdown/src/construct/character_escape.rs create mode 100644 vendor/markdown/src/construct/character_reference.rs create mode 100644 vendor/markdown/src/construct/code_indented.rs create mode 100644 vendor/markdown/src/construct/content.rs create mode 100644 vendor/markdown/src/construct/definition.rs create mode 100644 vendor/markdown/src/construct/document.rs create mode 100644 vendor/markdown/src/construct/flow.rs create mode 100644 vendor/markdown/src/construct/frontmatter.rs create mode 100644 vendor/markdown/src/construct/gfm_autolink_literal.rs create mode 100644 vendor/markdown/src/construct/gfm_footnote_definition.rs create mode 100644 vendor/markdown/src/construct/gfm_label_start_footnote.rs create mode 100644 vendor/markdown/src/construct/gfm_table.rs create mode 100644 vendor/markdown/src/construct/gfm_task_list_item_check.rs create mode 100644 vendor/markdown/src/construct/hard_break_escape.rs create mode 100644 vendor/markdown/src/construct/heading_atx.rs create mode 100644 vendor/markdown/src/construct/heading_setext.rs create mode 100644 vendor/markdown/src/construct/html_flow.rs create mode 100644 vendor/markdown/src/construct/html_text.rs create mode 100644 vendor/markdown/src/construct/label_end.rs create mode 100644 vendor/markdown/src/construct/label_start_image.rs create mode 100644 vendor/markdown/src/construct/label_start_link.rs create mode 100644 vendor/markdown/src/construct/list_item.rs create mode 100644 vendor/markdown/src/construct/mdx_esm.rs create mode 100644 vendor/markdown/src/construct/mdx_expression_flow.rs create mode 100644 vendor/markdown/src/construct/mdx_expression_text.rs create mode 100644 vendor/markdown/src/construct/mdx_jsx_flow.rs create mode 100644 vendor/markdown/src/construct/mdx_jsx_text.rs create mode 100644 vendor/markdown/src/construct/mod.rs create mode 100644 vendor/markdown/src/construct/paragraph.rs create mode 100644 vendor/markdown/src/construct/partial_bom.rs create mode 100644 vendor/markdown/src/construct/partial_data.rs create mode 100644 vendor/markdown/src/construct/partial_destination.rs create mode 100644 vendor/markdown/src/construct/partial_label.rs create mode 100644 vendor/markdown/src/construct/partial_mdx_expression.rs create mode 100644 vendor/markdown/src/construct/partial_mdx_jsx.rs create mode 100644 vendor/markdown/src/construct/partial_non_lazy_continuation.rs create mode 100644 vendor/markdown/src/construct/partial_space_or_tab.rs create mode 100644 vendor/markdown/src/construct/partial_space_or_tab_eol.rs create mode 100644 vendor/markdown/src/construct/partial_title.rs create mode 100644 vendor/markdown/src/construct/partial_whitespace.rs create mode 100644 vendor/markdown/src/construct/raw_flow.rs create mode 100644 vendor/markdown/src/construct/raw_text.rs create mode 100644 vendor/markdown/src/construct/string.rs create mode 100644 vendor/markdown/src/construct/text.rs create mode 100644 vendor/markdown/src/construct/thematic_break.rs create mode 100644 vendor/markdown/src/event.rs create mode 100644 vendor/markdown/src/lib.rs create mode 100644 vendor/markdown/src/mdast.rs create mode 100644 vendor/markdown/src/message.rs create mode 100644 vendor/markdown/src/parser.rs create mode 100644 vendor/markdown/src/resolve.rs create mode 100644 vendor/markdown/src/state.rs create mode 100644 vendor/markdown/src/subtokenize.rs create mode 100644 vendor/markdown/src/to_html.rs create mode 100644 vendor/markdown/src/to_mdast.rs create mode 100644 vendor/markdown/src/tokenizer.rs create mode 100644 vendor/markdown/src/unist.rs create mode 100644 vendor/markdown/src/util/char.rs create mode 100644 vendor/markdown/src/util/character_reference.rs create mode 100644 vendor/markdown/src/util/constant.rs create mode 100644 vendor/markdown/src/util/edit_map.rs create mode 100644 vendor/markdown/src/util/edit_map/tests.rs create mode 100644 vendor/markdown/src/util/encode.rs create mode 100644 vendor/markdown/src/util/gfm_tagfilter.rs create mode 100644 vendor/markdown/src/util/identifier.rs create mode 100644 vendor/markdown/src/util/infer.rs create mode 100644 vendor/markdown/src/util/line_ending.rs create mode 100644 vendor/markdown/src/util/location.rs create mode 100644 vendor/markdown/src/util/mdx.rs create mode 100644 vendor/markdown/src/util/mdx_collect.rs create mode 100644 vendor/markdown/src/util/mod.rs create mode 100644 vendor/markdown/src/util/normalize_identifier.rs create mode 100644 vendor/markdown/src/util/sanitize_uri.rs create mode 100644 vendor/markdown/src/util/skip.rs create mode 100644 vendor/markdown/src/util/slice.rs create mode 100644 vendor/markdown/src/util/unicode.rs create mode 100644 vendor/patches/alacritty_terminal/0002-reflow-row-transfers.patch create mode 100644 vendor/patches/alacritty_terminal/0003-grow-scrollback-in-batches.patch create mode 100644 vendor/patches/alacritty_terminal/0004-skip-empty-line-metadata-scans.patch create mode 100644 vendor/patches/alacritty_terminal/0005-track-searchable-grid-changes.patch create mode 100644 vendor/patches/alacritty_terminal/0006-version-terminal-palette-overrides.patch create mode 100644 vendor/patches/alacritty_terminal/0007-track-history-rotation.patch create mode 100644 vendor/patches/alacritty_terminal/0008-expose-row-occupancy-bound.patch create mode 100644 vendor/patches/alacritty_terminal/0009-bound-narrowing-reflow.patch create mode 100644 vendor/patches/alacritty_terminal/0010-probe-selected-text-without-copying.patch create mode 100644 vendor/patches/alacritty_terminal/0011-bound-selected-text-prefix.patch create mode 100644 vendor/patches/alacritty_terminal/0012-bound-clipboard-line-length.patch create mode 100644 vendor/patches/gpui-base/0007-frame-driven-selection.patch create mode 100644 vendor/patches/gpui-base/0008-append-inline-highlights.patch create mode 100644 vendor/patches/gpui-base/0009-clip-inline-line-bounds.patch create mode 100644 vendor/patches/gpui-base/0010-reserve-visible-line-bounds.patch create mode 100644 vendor/patches/gpui-base/0011-amortize-inline-layout-sweeps.patch create mode 100644 vendor/patches/gpui-base/0012-move-inline-layout-without-placeholder.patch create mode 100644 vendor/patches/gpui-base/0013-prepaint-positioned-inline-text.patch create mode 100644 vendor/patches/gpui-base/0014-use-measured-paragraph-spacing.patch create mode 100644 vendor/patches/gpui-base/0015-draw-rectangular-input-selections.patch create mode 100644 vendor/patches/gpui-base/0016-refresh-input-on-alt-transition.patch create mode 100644 vendor/patches/gpui-base/0017-group-long-text-paragraph-layout.patch create mode 100644 vendor/patches/gpui-base/0018-resolve-grouped-paragraph-width.patch create mode 100644 vendor/patches/gpui-base/0019-limit-inline-pointer-listeners.patch create mode 100644 vendor/patches/gpui-base/0020-omit-clipped-inline-hitboxes.patch create mode 100644 vendor/patches/gpui-base/0021-window-inline-highlight-ranges.patch create mode 100644 vendor/patches/gpui-base/0022-group-text-with-inline-code.patch create mode 100644 vendor/patches/gpui-base/0023-pace-passive-scrollbar-fades.patch create mode 100644 vendor/patches/gpui-base/0024-stop-counting-after-second-visible-panel.patch create mode 100644 vendor/patches/gpui-base/0025-retain-tab-panel-subscriptions.patch create mode 100644 vendor/patches/gpui-base/0026-keep-tab-selection-local.patch create mode 100644 vendor/patches/gpui-base/0027-resize-split-sizes-in-place.patch create mode 100644 vendor/patches/gpui-base/0028-commit-split-sizes-locally.patch create mode 100644 vendor/patches/gpui-base/0029-keep-observers-on-tab-membership-edits.patch create mode 100644 vendor/patches/gpui-base/0030-store-button-state-styles-on-demand.patch create mode 100644 vendor/patches/gpui-base/0031-migrate-jiff.patch create mode 100644 vendor/patches/gpui-component/0002-reuse-command-row-measurements.patch create mode 100644 vendor/patches/gpui-component/0003-skip-zero-tooltip-slides.patch create mode 100644 vendor/patches/gpui-component/0004-refresh-dock-test-frames.patch create mode 100644 vendor/patches/gpui-component/0005-pace-repeating-shimmer.patch create mode 100644 vendor/patches/gpui-component/0006-pace-loading-spinner.patch create mode 100644 vendor/patches/gpui-component/0007-install-fixed-command-models.patch create mode 100644 vendor/patches/gpui-component/0008-limit-plain-picker-row-layout.patch create mode 100644 vendor/patches/gpui-component/0009-skip-loading-for-ready-search.patch create mode 100644 vendor/patches/gpui-component/0010-defer-offscreen-command-row-measurement.patch create mode 100644 vendor/patches/gpui-component/0011-share-tab-bar-interaction-snapshots.patch create mode 100644 vendor/patches/gpui-component/0012-avoid-redundant-tab-strip-work.patch create mode 100644 vendor/patches/gpui-component/0013-prepare-tab-styles-on-demand.patch create mode 100644 vendor/patches/gpui-component/0014-settle-switch-within-physical-pixel.patch create mode 100644 vendor/patches/gpui-component/0015-prepare-button-styles-on-demand.patch create mode 100644 vendor/patches/gpui-component/0016-migrate-jiff.patch create mode 100644 vendor/patches/gpui-pre-linux/0001-keep-wayland-data-transfers-nonblocking.patch create mode 100644 vendor/patches/gpui-pre-linux/0002-share-outgoing-plain-text.patch create mode 100644 vendor/patches/gpui-pre-linux/0003-read-wayland-clipboard-asynchronously.patch create mode 100644 vendor/patches/gpui-pre-linux/0004-wait-for-x11-clipboard-readiness.patch create mode 100644 vendor/patches/gpui-pre-linux/0005-migrate-jiff.patch create mode 100644 vendor/patches/gpui-pre-scheduler/0001-migrate-jiff.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0002-frame-timestamps.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0003-lazy-path-textures.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0004-skip-ascii-bidi-lookup.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0005-prepare-only-used-frame-resources.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0006-collect-atlas-pages-from-sprites.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0007-omit-unused-video-pipeline.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0008-defer-egl-until-required.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0009-retry-presentation-after-device-loss.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0010-defer-failed-device-recovery-without-blocking.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0011-measure-retained-presentation-copies.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0012-reuse-finalized-window-presentation.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0013-size-linux-instance-buffer-for-small-frames.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0014-reuse-instance-bindings-on-repeat.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0015-reuse-ordered-batches-on-repeat.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0016-bound-path-intermediate-textures.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0017-compact-large-polychrome-pages.patch create mode 100644 vendor/patches/gpui-pre-wgpu/0018-migrate-jiff.patch create mode 100644 vendor/patches/gpui-pre-windows/0002-migrate-jiff.patch create mode 100644 vendor/patches/gpui-pre-zlog/0001-migrate-jiff.patch create mode 100644 vendor/patches/gpui-pre/0006-frame-glyph-tiles.patch create mode 100644 vendor/patches/gpui-pre/0007-count-key-presses-for-input-presentation.patch create mode 100644 vendor/patches/gpui-pre/0008-skip-empty-text-backgrounds.patch create mode 100644 vendor/patches/gpui-pre/0009-schedule-animated-image-frames.patch create mode 100644 vendor/patches/gpui-pre/0010-share-paced-animation-deadlines.patch create mode 100644 vendor/patches/gpui-pre/0011-size-line-decoration-storage.patch create mode 100644 vendor/patches/gpui-pre/0012-look-up-rendered-views.patch create mode 100644 vendor/patches/gpui-pre/0013-untracked-entity-reads.patch create mode 100644 vendor/patches/gpui-pre/0014-retain-content-cache-layout-dependencies.patch create mode 100644 vendor/patches/gpui-pre/0015-update-frame-invalidation-associations-incrementally.patch create mode 100644 vendor/patches/gpui-pre/0016-borrow-keyed-element-state-path.patch create mode 100644 vendor/patches/gpui-pre/0017-release-measurement-captures.patch create mode 100644 vendor/patches/gpui-pre/0018-compact-window-paint-replay.patch create mode 100644 vendor/patches/gpui-pre/0019-select-next-scene-batches.patch create mode 100644 vendor/patches/gpui-pre/0020-measure-positioned-styled-text.patch create mode 100644 vendor/patches/gpui-pre/0021-measure-styled-text-with-layout-style.patch create mode 100644 vendor/patches/gpui-pre/0022-defer-scene-build-while-device-is-lost.patch create mode 100644 vendor/patches/gpui-pre/0023-reuse-input-tree-during-device-loss.patch create mode 100644 vendor/patches/gpui-pre/0024-identify-finalized-window-draw-lists.patch create mode 100644 vendor/patches/gpui-pre/0025-count-shortcut-actions-for-input-presentation.patch create mode 100644 vendor/patches/gpui-pre/0026-sort-frame-focus-order-once.patch create mode 100644 vendor/patches/gpui-pre/0027-reuse-accessibility-diagnostic-nodes.patch create mode 100644 vendor/patches/gpui-pre/0028-reuse-frame-accessibility-node-ids.patch create mode 100644 vendor/patches/gpui-pre/0029-keep-cached-controls-accessible.patch create mode 100644 vendor/patches/gpui-pre/0030-reuse-accessible-element-id.patch create mode 100644 vendor/patches/gpui-pre/0031-expose-parsed-svg-intrinsic-size.patch create mode 100644 vendor/patches/gpui-pre/0032-consolidate-layout-coordinate-cache.patch create mode 100644 vendor/patches/gpui-pre/0033-remove-redundant-test-handle-clone.patch create mode 100644 vendor/patches/gpui-pre/0034-acquire-text-wrapper-on-demand.patch create mode 100644 vendor/patches/gpui-pre/0035-migrate-jiff.patch create mode 100644 vendor/patches/markdown/0001-batch-tokenizer-edits.patch create mode 100644 vendor/patches/russh-util/0001-migrate-jiff.patch create mode 100644 vendor/patches/toml_parser/0001-vectorize-string-scans.patch create mode 100644 vendor/patches/toml_parser/0002-bound-initial-token-reservation.patch create mode 100644 vendor/russh-util/Cargo.toml create mode 100644 vendor/russh-util/LICENSE-2.0.txt create mode 100644 vendor/russh-util/src/lib.rs create mode 100644 vendor/russh-util/src/runtime.rs create mode 100644 vendor/russh-util/src/time.rs create mode 100644 vendor/toml_parser/.cargo_vcs_info.json create mode 100644 vendor/toml_parser/Cargo.lock create mode 100644 vendor/toml_parser/Cargo.toml create mode 100644 vendor/toml_parser/Cargo.toml.orig create mode 100644 vendor/toml_parser/LICENSE-APACHE create mode 100644 vendor/toml_parser/LICENSE-MIT create mode 100644 vendor/toml_parser/NOCTERM.md create mode 100644 vendor/toml_parser/README.md create mode 100644 vendor/toml_parser/src/debug.rs create mode 100644 vendor/toml_parser/src/decoder/mod.rs create mode 100644 vendor/toml_parser/src/decoder/scalar.rs create mode 100644 vendor/toml_parser/src/decoder/string.rs create mode 100644 vendor/toml_parser/src/decoder/ws.rs create mode 100644 vendor/toml_parser/src/error.rs create mode 100644 vendor/toml_parser/src/lexer/mod.rs create mode 100644 vendor/toml_parser/src/lexer/test.rs create mode 100644 vendor/toml_parser/src/lexer/token.rs create mode 100644 vendor/toml_parser/src/lib.rs create mode 100644 vendor/toml_parser/src/macros.rs create mode 100644 vendor/toml_parser/src/parser/document.rs create mode 100644 vendor/toml_parser/src/parser/event.rs create mode 100644 vendor/toml_parser/src/parser/mod.rs create mode 100644 vendor/toml_parser/src/source.rs diff --git a/vendor/alacritty_terminal/NOCTERM.md b/vendor/alacritty_terminal/NOCTERM.md index 8a04b1fc..3d512a75 100644 --- a/vendor/alacritty_terminal/NOCTERM.md +++ b/vendor/alacritty_terminal/NOCTERM.md @@ -12,7 +12,9 @@ tests remain intact; Nocterm's additional coverage lives beside the modified engine methods and in `crates/vt/src/emulator.rs`. This is an internal Cargo patch, not a new published terminal library. -`src/term/cell.rs`, `src/term/mod.rs`, `src/term/keyboard.rs` and `src/tty/unix.rs` differ from the +`src/grid/mod.rs`, `src/grid/storage.rs`, `src/grid/resize.rs`, `src/grid/row.rs`, +`src/term/cell.rs`, `src/term/mod.rs`, +`src/term/keyboard.rs`, `src/term/selection_text.rs` and `src/tty/unix.rs` differ from the distribution's library sources. The Unix shell-user lookup uses equivalent `?` error propagation to satisfy current Clippy without changing environment-variable fallback behavior. Cargo uses the original normalized package dependencies. @@ -23,6 +25,13 @@ Nocterm's verification. ## Behavior and memory +Selection availability uses the same character traversal as clipboard +extraction. It stops as soon as the copied text would be nonempty and +allocates no text buffer. Regular copying appends directly into its result +without assembling intermediate strings for each row. +Consumers can request a prefix bounded by Unicode scalars using the same +character traversal and final newline rules. + Metadata is disabled by default. `Term::set_output_timestamp_ms` opts in and supplies the host's observation time. Nocterm calls it when feeding the parser. The resulting `LogicalLine` records a monotonic number and the first output time @@ -39,9 +48,24 @@ removing hyperlink/underline data. A bounded, one-entry cache shares the same `Arc` between ordinary characters of a logical line and attribute template; it does not retain an unbounded map of old lines. The scrollback limit still bounds retained cells and metadata. Marked output blanks count as occupied -for resize, so explicit blank lines are preserved. Without opt-in, upstream +for resize, so explicit blank lines are preserved. A row with zero occupied +cells has no lineage to look up. The existing row occupancy bookkeeping lets +the first write on such a row skip scanning the cells. Without opt-in, upstream cell emptiness and terminal behavior are unchanged. +Column reflow transfers cells directly between adjacent rows when widening. +When narrowing, the row drops empty trailing cells before allocating space for +the cells that wrap. A short suffix at the end of a logical line can reserve +room for its new row up front. As narrowing visits rows from oldest to newest, +the temporary buffer discards rows as soon as they exceed the scrollback limit. +Wide character spacers and the occupied range follow the same reflow rules. + +Scrollback starts with a batch of at most 16 initialized rows and increases +the batch as history fills, up to the existing 1,000-row growth ceiling. The +history-growth path also caps each batch at the remaining configured capacity. +Rows retain their existing ring order and remain immediately usable after a +rotation. Resize keeps using spare rows from the same ring. + Untrusted output cannot grow one cell's combining-character vector indefinitely: the engine retains at most 64 zero-width scalars per cell and ignores further marks until that cell is replaced or cleared. This limit applies before @@ -83,6 +107,23 @@ changing kitty support clear negotiated state. Input encoding remains in into rendered output. The GPUI adapter uses only available logical/shifted key metadata and never invents physical layout, keypad or modifier handedness. +## Searchable grid changes + +The grid records mutable cell access and operations that change their coordinates, +including buffer switches, scrollback eviction and reflow. The emulator consumes +this flag after parsing so cursor movement and protocol replies preserve active +search work. Review direct grid storage writes when updating the fork. +Top-origin upward scrolling also counts the rotation of retained history, +independently of viewport offset and history size. +`Row::occupied_end` exposes the existing dirty bound. For terminal cells the +untouched suffix has blank text and no line metadata, regardless of background. +Readers that preserve soft-wrap spacing still use the physical row width. +Clipboard extraction uses the dirty bound when finding the last text cell +on an unwrapped row, so increasing terminal width only adds work for cells +that were actually modified. +The term separately versions actual palette overrides so the host can invalidate +paint after color changes without comparing every slot. + ## Verification and updates ```sh diff --git a/vendor/alacritty_terminal/src/grid/mod.rs b/vendor/alacritty_terminal/src/grid/mod.rs index 4e394d9d..fe8dfa4a 100644 --- a/vendor/alacritty_terminal/src/grid/mod.rs +++ b/vendor/alacritty_terminal/src/grid/mod.rs @@ -1,3 +1,4 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. //! A specialized 2D grid implementation optimized for use in a terminal. use std::cmp::{max, min}; @@ -135,6 +136,14 @@ pub struct Grid { /// Maximum number of lines in history. max_scroll_limit: usize, + + /// Cells or their grid coordinates may have changed since the last observation. + #[cfg_attr(feature = "serde", serde(skip))] + content_changed: bool, + + /// Total upward rotation of the history in this buffer. + #[cfg_attr(feature = "serde", serde(skip))] + history_scroll: u64, } impl Grid { @@ -147,6 +156,8 @@ impl Grid { cursor: Cursor::default(), lines, columns, + content_changed: false, + history_scroll: 0, } } @@ -154,6 +165,7 @@ impl Grid { pub fn update_history(&mut self, history_size: usize) { let current_history_size = self.history_size(); if current_history_size > history_size { + self.mark_content_changed(); self.raw.shrink_lines(current_history_size - history_size); } self.display_offset = min(self.display_offset, history_size); @@ -173,9 +185,10 @@ impl Grid { } fn increase_scroll_limit(&mut self, count: usize) { - let count = min(count, self.max_scroll_limit - self.history_size()); + let remaining = self.max_scroll_limit - self.history_size(); + let count = min(count, remaining); if count != 0 { - self.raw.initialize(count, self.columns); + self.raw.initialize(count, self.columns, remaining); } } @@ -193,6 +206,7 @@ impl Grid { T: ResetDiscriminant, D: PartialEq, { + self.mark_content_changed(); // When rotating the entire region, just reset everything. if region.end - region.start <= positions { for i in (region.start.0..region.end.0).map(Line::from) { @@ -254,6 +268,7 @@ impl Grid { T: ResetDiscriminant, D: PartialEq, { + self.mark_content_changed(); // When rotating the entire region with fixed lines at the top, just reset everything. if region.end - region.start <= positions && region.start != 0 { for i in (region.start.0..region.end.0).map(Line::from) { @@ -270,6 +285,8 @@ impl Grid { // Only rotate the entire history if the active region starts at the top. if region.start == 0 { + self.history_scroll = self.history_scroll.wrapping_add(positions as u64); + // Create scrollback for the new lines. self.increase_scroll_limit(positions); @@ -338,6 +355,7 @@ impl Grid { T: ResetDiscriminant, D: PartialEq, { + self.mark_content_changed(); self.clear_history(); self.saved_cursor = Cursor::default(); @@ -353,6 +371,21 @@ impl Grid { } impl Grid { + #[inline] + pub(crate) fn mark_content_changed(&mut self) { + self.content_changed = true; + } + + pub(crate) fn take_content_changed(&mut self) -> bool { + std::mem::take(&mut self.content_changed) + } + + /// Upward translation of retained history since this buffer was created. + /// Callers must separately account for reflow and retain only in-bounds rows. + pub fn history_scroll(&self) -> u64 { + self.history_scroll + } + /// Reset a visible region within the grid. pub fn reset_region>(&mut self, bounds: R) where @@ -374,6 +407,7 @@ impl Grid { debug_assert!(start < self.screen_lines() as i32); debug_assert!(end <= self.screen_lines() as i32); + self.mark_content_changed(); for line in (start.0..end.0).map(Line::from) { self.raw[line].reset(&self.cursor.template); } @@ -382,7 +416,11 @@ impl Grid { #[inline] pub fn clear_history(&mut self) { // Explicitly purge all lines from history. - self.raw.shrink_lines(self.history_size()); + let history_size = self.history_size(); + if history_size != 0 { + self.mark_content_changed(); + } + self.raw.shrink_lines(history_size); // Reset display offset. self.display_offset = 0; @@ -398,7 +436,8 @@ impl Grid { self.truncate(); // Initialize everything with empty new lines. - self.raw.initialize(self.max_scroll_limit - self.history_size(), self.columns); + let remaining = self.max_scroll_limit - self.history_size(); + self.raw.initialize(remaining, self.columns, remaining); } /// This is used only for truncating before saving ref-tests. @@ -462,6 +501,7 @@ impl Index for Grid { impl IndexMut for Grid { #[inline] fn index_mut(&mut self, index: Line) -> &mut Row { + self.mark_content_changed(); &mut self.raw[index] } } diff --git a/vendor/alacritty_terminal/src/grid/resize.rs b/vendor/alacritty_terminal/src/grid/resize.rs index 37f93691..b48592c1 100644 --- a/vendor/alacritty_terminal/src/grid/resize.rs +++ b/vendor/alacritty_terminal/src/grid/resize.rs @@ -1,6 +1,8 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. //! Grid resize and reflow. use std::cmp::{Ordering, max, min}; +use std::collections::VecDeque; use std::mem; use crate::index::{Boundary, Column, Line}; @@ -16,6 +18,10 @@ impl Grid { T: ResetDiscriminant, D: PartialEq, { + if lines != self.lines || columns != self.columns { + self.mark_content_changed(); + } + // Use empty template cell for resetting cells due to resize. let template = mem::take(&mut self.cursor.template); @@ -147,22 +153,15 @@ impl Grid { let len = min(row.len(), num_wrapped); // Insert leading spacer when there's not enough room for reflowing wide char. - let mut cells = if row[Column(len - 1)].flags().contains(Flags::WIDE_CHAR) { + if row[Column(len - 1)].flags().contains(Flags::WIDE_CHAR) { num_wrapped -= 1; - - let mut cells = row.front_split_off(len - 1); - + last_row.append_prefix_from(&mut row, len - 1); let mut spacer = T::default(); spacer.flags_mut().insert(Flags::LEADING_WIDE_CHAR_SPACER); - cells.push(spacer); - - cells + last_row.push(spacer); } else { - row.front_split_off(len) - }; - - // Add removed cells to previous row and reflow content. - last_row.append(&mut cells); + last_row.append_prefix_from(&mut row, len); + } let cursor_buffer_line = self.lines - self.cursor.point.line.0 as usize - 1; @@ -251,7 +250,18 @@ impl Grid { self.cursor.point.column += 1; } - let mut new_raw = Vec::with_capacity(self.raw.len()); + // Reflow visits rows from oldest to newest. Retain only the rows + // that can survive in the grid under the scrollback limit. + let limit = self.max_scroll_limit + self.lines; + let mut new_raw = VecDeque::with_capacity(self.raw.len().min(limit)); + let push_row = |rows: &mut VecDeque<_>, row| { + if rows.len() == limit { + rows.pop_front(); + } else if rows.len() == rows.capacity() { + rows.reserve_exact(rows.capacity().min(limit - rows.len()).max(1)); + } + rows.push_back(row); + }; let mut buffered: Option> = None; let mut rows = self.raw.take_all(); @@ -270,7 +280,12 @@ impl Grid { loop { // Remove all cells which require reflowing. - let mut wrapped = match row.shrink(columns) { + let overflow = if reflow { + row.shrink_for_reflow(columns) + } else { + row.shrink(columns) + }; + let mut wrapped = match overflow { Some(wrapped) if reflow => wrapped, _ => { let cursor_buffer_line = self.lines - self.cursor.point.line.0 as usize - 1; @@ -280,7 +295,7 @@ impl Grid { Vec::new() } else { // Since it fits, just push the existing line without any reflow. - new_raw.push(row); + push_row(&mut new_raw, row); break; } }, @@ -302,7 +317,7 @@ impl Grid { if len > 0 && wrapped[len - 1].flags().contains(Flags::LEADING_WIDE_CHAR_SPACER) { if len == 1 { row[Column(columns - 1)].flags_mut().insert(Flags::WRAPLINE); - new_raw.push(row); + push_row(&mut new_raw, row); break; } else { // Remove the leading spacer from the end of the wrapped row. @@ -311,10 +326,10 @@ impl Grid { } } - new_raw.push(row); + push_row(&mut new_raw, row); // Set line as wrapped if cells got removed. - if let Some(cell) = new_raw.last_mut().and_then(|r| r.last_mut()) { + if let Some(cell) = new_raw.back_mut().and_then(|r| r.last_mut()) { cell.flags_mut().insert(Flags::WRAPLINE); } @@ -363,10 +378,9 @@ impl Grid { } } - // Reverse iterator and use it as the new grid storage. - let mut reversed: Vec> = new_raw.drain(..).rev().collect(); - reversed.truncate(self.max_scroll_limit + self.lines); - self.raw.replace_inner(reversed); + let mut rows = Vec::from(new_raw); + rows.reverse(); + self.raw.replace_inner(rows); // Clamp display offset in case some lines went off. self.display_offset = min(self.display_offset, self.history_size()); diff --git a/vendor/alacritty_terminal/src/grid/row.rs b/vendor/alacritty_terminal/src/grid/row.rs index 040f724d..1e8cab7d 100644 --- a/vendor/alacritty_terminal/src/grid/row.rs +++ b/vendor/alacritty_terminal/src/grid/row.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; use crate::grid::GridCell; use crate::index::Column; -use crate::term::cell::ResetDiscriminant; +use crate::term::cell::{Flags, ResetDiscriminant}; /// A row in the grid. #[derive(Default, Clone, Debug)] @@ -69,6 +69,20 @@ impl Row { /// /// This will return all non-empty cells that were removed. pub fn shrink(&mut self, columns: usize) -> Option> + where + T: GridCell, + { + self.shrink_to_columns(columns, false) + } + + pub(crate) fn shrink_for_reflow(&mut self, columns: usize) -> Option> + where + T: GridCell, + { + self.shrink_to_columns(columns, true) + } + + fn shrink_to_columns(&mut self, columns: usize, reflow: bool) -> Option> where T: GridCell, { @@ -76,14 +90,28 @@ impl Row { return None; } - // Split off cells for a new row. - let mut new_row = self.inner.split_off(columns); - let index = new_row.iter().rposition(|c| !c.is_empty()).map_or(0, |i| i + 1); - new_row.truncate(index); - + // Drop the empty tail in place before allocating space for wrapped cells. + let end = self.inner[columns..] + .iter() + .rposition(|cell| !cell.is_empty()) + .map_or(columns, |index| columns + index + 1); + self.inner.truncate(end); self.occ = min(self.occ, columns); - if new_row.is_empty() { None } else { Some(new_row) } + if end == columns { + return None; + } + + let overflow = end - columns; + // A short suffix ending a logical line usually becomes a new row. + // Give it space for its remaining blank cells before moving the suffix. + if reflow && overflow < columns && !self.inner[end - 1].flags().contains(Flags::WRAPLINE) { + let mut suffix = Vec::with_capacity(columns); + suffix.extend(self.inner.drain(columns..)); + Some(suffix) + } else { + Some(self.inner.split_off(columns)) + } } /// Reset all cells in the row to the `template` cell. @@ -122,6 +150,12 @@ impl Row { self.inner.len() } + /// Exclusive upper bound of the cells modified since initialization or reset. + #[inline] + pub fn occupied_end(&self) -> usize { + self.occ + } + #[inline] pub fn last(&self) -> Option<&T> { self.inner.last() @@ -138,7 +172,9 @@ impl Row { where T: GridCell, { - self.occ += vec.len(); + if !vec.is_empty() { + self.occ = self.inner.len() + vec.len(); + } self.inner.append(vec); } @@ -167,6 +203,21 @@ impl Row { std::mem::swap(&mut split, &mut self.inner); split } + + /// Move the prefix of a wrapped row directly into this row. + #[inline] + pub(super) fn append_prefix_from(&mut self, from: &mut Self, count: usize) { + debug_assert_eq!(self.occ, self.inner.len()); + self.inner.extend(from.inner.drain(..count)); + self.occ += count; + from.occ = from.occ.saturating_sub(count); + } + + #[inline] + pub(super) fn push(&mut self, cell: T) { + self.inner.push(cell); + self.occ = self.inner.len(); + } } impl<'a, T> IntoIterator for &'a Row { diff --git a/vendor/alacritty_terminal/src/grid/storage.rs b/vendor/alacritty_terminal/src/grid/storage.rs index 6d7984d4..3ba9098d 100644 --- a/vendor/alacritty_terminal/src/grid/storage.rs +++ b/vendor/alacritty_terminal/src/grid/storage.rs @@ -1,4 +1,4 @@ -use std::cmp::max; +use std::cmp::{max, min}; use std::mem; use std::mem::MaybeUninit; use std::ops::{Index, IndexMut}; @@ -9,6 +9,8 @@ use serde::{Deserialize, Serialize}; use super::Row; use crate::index::Line; +/// First batch of spare rows for a light terminal or viewport resize. +const INITIAL_ROW_BATCH: usize = 16; /// Maximum number of buffered lines outside of the grid for performance optimization. const MAX_CACHE_SIZE: usize = 1_000; @@ -47,8 +49,8 @@ pub struct Storage { /// /// Shrinking this length allows reducing the number of lines in the scrollback buffer without /// having to truncate the raw `inner` buffer. - /// As long as `len` is bigger than `inner`, it is also possible to grow the scrollback buffer - /// without any additional insertions. + /// While `len` is smaller than `inner.len()`, the scrollback buffer can grow + /// into existing rows without allocating more cells. len: usize, } @@ -85,7 +87,7 @@ impl Storage { let additional_lines = next - self.visible_lines; let columns = self[Line(0)].len(); - self.initialize(additional_lines, columns); + self.initialize(additional_lines, columns, usize::MAX); // Update visible lines. self.visible_lines = next; @@ -121,16 +123,24 @@ impl Storage { self.inner.truncate(self.len); } - /// Dynamically grow the storage buffer at runtime. + /// Grows the ring, limiting speculative rows to the caller's growth budget. #[inline] - pub fn initialize(&mut self, additional_rows: usize, columns: usize) + pub fn initialize(&mut self, additional_rows: usize, columns: usize, max_rows_to_add: usize) where T: Default, { if self.len + additional_rows > self.inner.len() { self.rezero(); - let realloc_size = self.inner.len() + max(additional_rows, MAX_CACHE_SIZE); + // Start small so a few output lines do not reserve thousands of cells. + // Once history reaches a full cache batch, keep the existing dense growth. + let history = self.len - self.visible_lines; + let batch = if history < MAX_CACHE_SIZE { + (history * 4).clamp(INITIAL_ROW_BATCH, MAX_CACHE_SIZE) - history + } else { + MAX_CACHE_SIZE + }; + let realloc_size = self.len + max(additional_rows, min(batch, max_rows_to_add)); self.inner.resize_with(realloc_size, || Row::new(columns)); } @@ -267,7 +277,7 @@ impl IndexMut for Storage { mod tests { use crate::grid::GridCell; use crate::grid::row::Row; - use crate::grid::storage::{MAX_CACHE_SIZE, Storage}; + use crate::grid::storage::{INITIAL_ROW_BATCH, Storage}; use crate::index::{Column, Line}; use crate::term::cell::Flags; @@ -345,7 +355,7 @@ mod tests { /// 2: - /// 3: \0 /// ... - /// MAX_CACHE_SIZE: \0 + /// INITIAL_ROW_BATCH: \0 #[test] fn grow_after_zero() { // Setup storage area. @@ -366,7 +376,7 @@ mod tests { visible_lines: 4, len: 4, }; - expected.inner.append(&mut vec![filled_row('\0'); MAX_CACHE_SIZE]); + expected.inner.append(&mut vec![filled_row('\0'); INITIAL_ROW_BATCH]); assert_eq!(storage.visible_lines, expected.visible_lines); assert_eq!(storage.inner, expected.inner); @@ -386,7 +396,7 @@ mod tests { /// 2: - /// 3: \0 /// ... - /// MAX_CACHE_SIZE: \0 + /// INITIAL_ROW_BATCH: \0 #[test] fn grow_before_zero() { // Setup storage area. @@ -407,7 +417,7 @@ mod tests { visible_lines: 4, len: 4, }; - expected.inner.append(&mut vec![filled_row('\0'); MAX_CACHE_SIZE]); + expected.inner.append(&mut vec![filled_row('\0'); INITIAL_ROW_BATCH]); assert_eq!(storage.visible_lines, expected.visible_lines); assert_eq!(storage.inner, expected.inner); @@ -686,7 +696,7 @@ mod tests { assert_eq!(storage.len, shrinking_expected.len); // Grow buffer. - storage.initialize(1, 1); + storage.initialize(1, 1, usize::MAX); // Make sure the previously freed elements are reused. let growing_expected = Storage { @@ -727,7 +737,7 @@ mod tests { // Initialize additional lines. let init_size = 3; - storage.initialize(init_size, 1); + storage.initialize(init_size, 1, usize::MAX); // Generate expected grid. let mut expected_inner = vec![ @@ -738,7 +748,7 @@ mod tests { filled_row('4'), filled_row('5'), ]; - let expected_init_size = std::cmp::max(init_size, MAX_CACHE_SIZE); + let expected_init_size = 18; expected_inner.append(&mut vec![filled_row('\0'); expected_init_size]); let expected_storage = Storage { inner: expected_inner, zero: 0, visible_lines: 0, len: 9 }; @@ -747,6 +757,15 @@ mod tests { assert_eq!(storage.inner, expected_storage.inner); } + #[test] + fn a_small_history_allocates_only_rows_the_grid_can_use() { + let mut storage = Storage::::with_capacity(48, 260); + storage.initialize(1, 260, 3); + assert_eq!(storage.len(), 49); + assert_eq!(storage.inner.len(), 51); + assert_eq!(storage[Line(-1)].len(), 260); + } + #[test] fn rotate_wrap_zero() { let mut storage: Storage = Storage { diff --git a/vendor/alacritty_terminal/src/term/cell.rs b/vendor/alacritty_terminal/src/term/cell.rs index 451778df..a20387cf 100644 --- a/vendor/alacritty_terminal/src/term/cell.rs +++ b/vendor/alacritty_terminal/src/term/cell.rs @@ -302,22 +302,22 @@ pub trait LineLength { impl LineLength for grid::Row { fn line_length(&self) -> Column { - let mut length = Column(0); - - if self[Column(self.len() - 1)].flags.contains(Flags::WRAPLINE) { + let has_text = |cell: &Cell| { + cell.c != ' ' + || cell.extra.as_ref().is_some_and(|extra| !extra.zerowidth.is_empty()) + }; + let last = &self[Column(self.len() - 1)]; + if last.flags.contains(Flags::WRAPLINE) || has_text(last) { return Column(self.len()); } - for (index, cell) in self[..].iter().rev().enumerate() { - if cell.c != ' ' - || cell.extra.as_ref().map(|extra| extra.zerowidth.is_empty()) == Some(false) - { - length = Column(self.len() - index); - break; - } - } - - length + // Only the occupied prefix may contain text added since reset. + Column( + self[..Column(self.occupied_end())] + .iter() + .rposition(has_text) + .map_or(0, |index| index + 1), + ) } } @@ -365,6 +365,16 @@ mod tests { assert_eq!(row.line_length(), Column(6)); } + #[test] + fn line_length_keeps_combining_marks_and_ignores_background_after_growth() { + let mut row = Row::::new(10); + row[Column(3)].push_zerowidth('\u{301}'); + row[Column(4)].bg = Color::Named(NamedColor::Red); + row.grow(500); + + assert_eq!(row.line_length(), Column(4)); + } + #[test] fn line_length_works_with_wrapline() { let mut row = Row::::new(10); diff --git a/vendor/alacritty_terminal/src/term/mod.rs b/vendor/alacritty_terminal/src/term/mod.rs index 2e94c5d8..dc4712e2 100644 --- a/vendor/alacritty_terminal/src/term/mod.rs +++ b/vendor/alacritty_terminal/src/term/mod.rs @@ -16,8 +16,8 @@ use unicode_width::UnicodeWidthChar; use crate::event::{Event, EventListener}; use crate::grid::{Dimensions, Grid, GridIterator, Scroll}; use crate::index::{self, Boundary, Column, Direction, Line, Point, Side}; -use crate::selection::{Selection, SelectionRange, SelectionType}; -use crate::term::cell::{Cell, CellExtra, Flags, LineLength, LogicalLine}; +use crate::selection::{Selection, SelectionRange}; +use crate::term::cell::{Cell, CellExtra, Flags, LogicalLine}; use crate::term::color::Colors; use crate::vi_mode::{ViModeCursor, ViMotion}; use crate::vte::ansi::{ @@ -31,6 +31,7 @@ pub mod color; mod keyboard; use keyboard::KeyboardProtocol; pub mod search; +mod selection_text; /// Minimum number of columns. /// @@ -309,6 +310,7 @@ pub struct Term { /// Modified terminal colors. colors: Colors, + palette_revision: u64, /// Current style of the cursor. cursor_style: Option, @@ -449,7 +451,11 @@ impl Term { } fn current_logical_line(&self) -> Option { - self.grid[self.grid.cursor.point.line][..].iter().find_map(|cell| cell.logical_line()) + let row = &self.grid[self.grid.cursor.point.line]; + if row.occ == 0 { + return None; + } + row[..].iter().find_map(|cell| cell.logical_line()) } fn ensure_logical_line(&mut self) -> Option { @@ -502,6 +508,7 @@ impl Term { vi_mode_cursor: Default::default(), cursor_style: Default::default(), colors: color::Colors::default(), + palette_revision: 0, title_stack: Default::default(), is_focused: Default::default(), selection: Default::default(), @@ -595,109 +602,22 @@ impl Term { /// Convert the active selection to a String. pub fn selection_to_string(&self) -> Option { - let selection_range = self.selection.as_ref().and_then(|s| s.to_range(self))?; - let SelectionRange { start, end, .. } = selection_range; - - let mut res = String::new(); - - match self.selection.as_ref() { - Some(Selection { ty: SelectionType::Block, .. }) => { - for line in (start.line.0..end.line.0).map(Line::from) { - res += self - .line_to_string(line, start.column..end.column, start.column.0 != 0) - .trim_end(); - res += "\n"; - } + selection_text::selection_to_string(self) + } - res += self.line_to_string(end.line, start.column..end.column, true).trim_end(); - }, - Some(Selection { ty: SelectionType::Lines, .. }) => { - res = self.bounds_to_string(start, end) + "\n"; - }, - _ => { - res = self.bounds_to_string(start, end); - }, - } + /// Whether copying the active selection would produce any text. + pub fn selection_has_text(&self) -> bool { + selection_text::selection_has_text(self) + } - Some(res) + /// Copy at most the first `max_chars` Unicode scalars of the selection. + pub fn selection_text_prefix(&self, max_chars: usize) -> Option { + selection_text::selection_text_prefix(self, max_chars) } /// Convert range between two points to a String. pub fn bounds_to_string(&self, start: Point, end: Point) -> String { - let mut res = String::new(); - - for line in (start.line.0..=end.line.0).map(Line::from) { - let start_col = if line == start.line { start.column } else { Column(0) }; - let end_col = if line == end.line { end.column } else { self.last_column() }; - - res += &self.line_to_string(line, start_col..end_col, line == end.line); - } - - res.strip_suffix('\n').map(str::to_owned).unwrap_or(res) - } - - /// Convert a single line in the grid to a String. - fn line_to_string( - &self, - line: Line, - mut cols: Range, - include_wrapped_wide: bool, - ) -> String { - let mut text = String::new(); - - let grid_line = &self.grid[line]; - let line_length = cmp::min(grid_line.line_length(), cols.end + 1); - - // Include wide char when trailing spacer is selected. - if grid_line[cols.start].flags.contains(Flags::WIDE_CHAR_SPACER) { - cols.start -= 1; - } - - let mut tab_mode = false; - for column in (cols.start.0..line_length.0).map(Column::from) { - let cell = &grid_line[column]; - - // Skip over cells until next tab-stop once a tab was found. - if tab_mode { - if self.tabs[column] || cell.c != ' ' { - tab_mode = false; - } else { - continue; - } - } - - if cell.c == '\t' { - tab_mode = true; - } - - if !cell.flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) { - // Push cells primary character. - text.push(cell.c); - - // Push zero-width characters. - for c in cell.zerowidth().into_iter().flatten() { - text.push(*c); - } - } - } - - if cols.end >= self.columns() - 1 - && (line_length.0 == 0 - || !self.grid[line][line_length - 1].flags.contains(Flags::WRAPLINE)) - { - text.push('\n'); - } - - // If wide char is not part of the selection, but leading spacer is, include it. - if line_length == self.columns() - && line_length.0 >= 2 - && grid_line[line_length - 1].flags.contains(Flags::LEADING_WIDE_CHAR_SPACER) - && include_wrapped_wide - { - text.push(self.grid[line - 1i32][Column(0)].c); - } - - text + selection_text::bounds_to_string(self, start, end) } /// Terminal content required for rendering. @@ -714,6 +634,12 @@ impl Term { &self.grid } + /// Whether active cells or their grid coordinates may have changed since the last call. + /// Cursor movement, mode changes, and scrolling the view alone leave it clear. + pub fn take_grid_changed(&mut self) -> bool { + self.grid.take_content_changed() + } + /// Mutable access to the raw grid data structure. pub fn grid_mut(&mut self) -> &mut Grid { &mut self.grid @@ -796,6 +722,7 @@ impl Term { self.sync_keyboard_mode(); mem::swap(&mut self.grid, &mut self.inactive_grid); + self.grid.mark_content_changed(); self.mode ^= TermMode::ALT_SCREEN; self.selection = None; self.mark_fully_damaged(); @@ -1020,6 +947,12 @@ impl Term { &self.colors } + /// Version of the program's palette overrides. + #[inline] + pub fn palette_revision(&self) -> u64 { + self.palette_revision + } + /// Insert a linebreak at the current cursor position. #[inline] fn wrapline(&mut self) @@ -1698,12 +1631,13 @@ impl Handler for Term { fn set_color(&mut self, index: usize, color: Rgb) { trace!("Setting color[{index}] = {color:?}"); - // Damage terminal if the color changed and it's not the cursor. - if index != NamedColor::Cursor as usize && self.colors[index] != Some(color) { - self.mark_fully_damaged(); + if self.colors[index] != Some(color) { + self.palette_revision = self.palette_revision.wrapping_add(1); + if index != NamedColor::Cursor as usize { + self.mark_fully_damaged(); + } + self.colors[index] = Some(color); } - - self.colors[index] = Some(color); } /// Respond to a color query escape sequence. @@ -1728,12 +1662,13 @@ impl Handler for Term { fn reset_color(&mut self, index: usize) { trace!("Resetting color[{index}]"); - // Damage terminal if the color changed and it's not the cursor. - if index != NamedColor::Cursor as usize && self.colors[index].is_some() { - self.mark_fully_damaged(); + if self.colors[index].is_some() { + self.palette_revision = self.palette_revision.wrapping_add(1); + if index != NamedColor::Cursor as usize { + self.mark_fully_damaged(); + } + self.colors[index] = None; } - - self.colors[index] = None; } /// Store data into clipboard. diff --git a/vendor/alacritty_terminal/src/term/selection_text.rs b/vendor/alacritty_terminal/src/term/selection_text.rs new file mode 100644 index 00000000..9df3c33a --- /dev/null +++ b/vendor/alacritty_terminal/src/term/selection_text.rs @@ -0,0 +1,246 @@ +// Modified by Nocterm contributors; licensed under Apache-2.0. +use std::cmp; +use std::ops::{ControlFlow, Range}; + +use crate::grid::Dimensions; +use crate::index::{Column, Line, Point}; +use crate::selection::{SelectionRange, SelectionType}; +use crate::term::{ + Term, + cell::{Flags, LineLength}, +}; + +pub(super) fn selection_to_string(term: &Term) -> Option { + let selection = term.selection.as_ref()?; + let SelectionRange { start, end, .. } = selection.to_range(term)?; + match selection.ty { + SelectionType::Block => { + let mut text = String::new(); + for line in (start.line.0..end.line.0).map(Line::from) { + text += line_to_string(term, line, start.column..end.column, start.column.0 != 0) + .trim_end(); + text.push('\n'); + } + text += line_to_string(term, end.line, start.column..end.column, true).trim_end(); + Some(text) + } + SelectionType::Lines => { + let mut text = bounds_to_string(term, start, end); + text.push('\n'); + Some(text) + } + _ => Some(bounds_to_string(term, start, end)), + } +} + +pub(super) fn selection_has_text(term: &Term) -> bool { + let Some(selection) = term.selection.as_ref() else { + return false; + }; + let Some(SelectionRange { start, end, .. }) = selection.to_range(term) else { + return false; + }; + match selection.ty { + SelectionType::Lines => true, + SelectionType::Block if start.line != end.line => true, + SelectionType::Block => visit_line(term, end.line, start.column..end.column, true, |ch| { + if ch.is_whitespace() { + ControlFlow::Continue(()) + } else { + ControlFlow::Break(()) + } + }) + .is_break(), + _ => { + // The serializer strips one trailing newline. One newline alone + // is empty, while a second character makes the result nonempty. + let mut one_newline = false; + for (line, columns, last) in selection_rows(term, start, end) { + if visit_line(term, line, columns, last, |ch| { + if ch != '\n' || one_newline { + return ControlFlow::Break(()); + } + one_newline = true; + ControlFlow::Continue(()) + }) + .is_break() + { + return true; + } + } + false + } + } +} + +pub(super) fn selection_text_prefix(term: &Term, max_chars: usize) -> Option { + let selection = term.selection.as_ref()?; + let SelectionRange { start, end, .. } = selection.to_range(term)?; + let mut prefix = String::new(); + let mut remaining = max_chars; + if selection.ty == SelectionType::Block { + for line in (start.line.0..=end.line.0).map(Line::from) { + if remaining == 0 { + break; + } + let final_row = line == end.line; + let text = line_to_string( + term, + line, + start.column..end.column, + final_row || start.column.0 != 0, + ); + for ch in text.trim_end().chars().chain((!final_row).then_some('\n')) { + if remaining == 0 { + return Some(prefix); + } + prefix.push(ch); + remaining -= 1; + } + } + return Some(prefix); + } + + for (line, columns, last) in selection_rows(term, start, end) { + if visit_line(term, line, columns, last, |ch| { + if remaining == 0 { + return ControlFlow::Break(()); + } + prefix.push(ch); + remaining -= 1; + ControlFlow::Continue(()) + }) + .is_break() + { + return Some(prefix); + } + } + if prefix.ends_with('\n') { + prefix.pop(); + remaining += 1; + } + if selection.ty == SelectionType::Lines && remaining > 0 { + prefix.push('\n'); + } + Some(prefix) +} + +pub(super) fn bounds_to_string(term: &Term, start: Point, end: Point) -> String { + let mut text = String::new(); + for (line, columns, last) in selection_rows(term, start, end) { + let _ = visit_line(term, line, columns, last, |ch| { + text.push(ch); + ControlFlow::Continue(()) + }); + } + if text.ends_with('\n') { + text.pop(); + } + text +} + +fn selection_rows( + term: &Term, + start: Point, + end: Point, +) -> impl Iterator, bool)> { + let last_column = term.last_column(); + (start.line.0..=end.line.0).map(move |line| { + let line = Line(line); + let first_column = if line == start.line { + start.column + } else { + Column(0) + }; + let last = line == end.line; + let end_column = if last { end.column } else { last_column }; + (line, first_column..end_column, last) + }) +} + +fn line_to_string( + term: &Term, + line: Line, + columns: Range, + include_wrapped_wide: bool, +) -> String { + let mut text = String::new(); + let _ = visit_line(term, line, columns, include_wrapped_wide, |ch| { + text.push(ch); + ControlFlow::Continue(()) + }); + text +} + +/// Visit the same characters in both the copy and availability paths. +fn visit_line( + term: &Term, + line: Line, + mut cols: Range, + include_wrapped_wide: bool, + mut visit: impl FnMut(char) -> ControlFlow<()>, +) -> ControlFlow<()> { + let grid_line = &term.grid[line]; + let line_length = cmp::min(grid_line.line_length(), cols.end + 1); + + // Include wide char when trailing spacer is selected. + if grid_line[cols.start] + .flags + .contains(Flags::WIDE_CHAR_SPACER) + { + cols.start -= 1; + } + + let mut tab_mode = false; + for column in (cols.start.0..line_length.0).map(Column::from) { + let cell = &grid_line[column]; + + // Skip over cells until next tab-stop once a tab was found. + if tab_mode { + if term.tabs[column] || cell.c != ' ' { + tab_mode = false; + } else { + continue; + } + } + + if cell.c == '\t' { + tab_mode = true; + } + + if !cell + .flags + .intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) + { + // Push cells primary character. + visit(cell.c)?; + + // Push zero-width characters. + for c in cell.zerowidth().into_iter().flatten() { + visit(*c)?; + } + } + } + + if cols.end >= term.columns() - 1 + && (line_length.0 == 0 + || !term.grid[line][line_length - 1] + .flags + .contains(Flags::WRAPLINE)) + { + visit('\n')?; + } + + // If wide char is not part of the selection, but leading spacer is, include it. + if line_length == term.columns() + && line_length.0 >= 2 + && grid_line[line_length - 1] + .flags + .contains(Flags::LEADING_WIDE_CHAR_SPACER) + && include_wrapped_wide + { + visit(term.grid[line - 1i32][Column(0)].c)?; + } + + ControlFlow::Continue(()) +} diff --git a/vendor/gpui-base/Cargo.lock b/vendor/gpui-base/Cargo.lock index 6a2e14e8..e2074d02 100644 --- a/vendor/gpui-base/Cargo.lock +++ b/vendor/gpui-base/Cargo.lock @@ -901,20 +901,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link 0.2.1", -] - [[package]] name = "ciborium" version = "0.2.2" @@ -1016,9 +1002,9 @@ dependencies = [ [[package]] name = "cocoa" -version = "0.26.0" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f79398230a6e2c08f5c9760610eb6924b52aa9e7950a619602baba59dcbbdbb2" +checksum = "ad36507aeb7e16159dfe68db81ccc27571c3ccd4b76fb2fb72fc59e7a4b1b64c" dependencies = [ "bitflags 2.13.1", "block", @@ -2280,7 +2266,6 @@ dependencies = [ "anyhow", "ashpd", "async-channel", - "chrono", "criterion 0.5.1", "data-url", "futures", @@ -2293,6 +2278,7 @@ dependencies = [ "indoc", "instant", "itertools 0.13.0", + "jiff", "lsp-types", "markdown", "markup5ever_rcdom", @@ -2318,8 +2304,6 @@ dependencies = [ [[package]] name = "gpui-pre" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e87a42bb37c7cb4e76dd1ac0ce88851e46e976e0373a47ab3e0757abffee54d" dependencies = [ "accesskit", "anyhow", @@ -2328,7 +2312,6 @@ dependencies = [ "backtrace", "bindgen", "bitflags 2.13.1", - "chrono", "core-video", "criterion 0.8.2", "ctor", @@ -2353,6 +2336,7 @@ dependencies = [ "image", "inventory", "itertools 0.14.0", + "jiff", "log", "lyon", "num_cpus", @@ -2399,7 +2383,7 @@ dependencies = [ "anyhow", "block2 0.6.2", "cbindgen", - "cocoa 0.26.0", + "cocoa 0.26.1", "core-foundation 0.10.1", "core-video", "derive_more", @@ -2484,8 +2468,6 @@ dependencies = [ [[package]] name = "gpui-pre-linux" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aac7022e347409454777701082201742710052813964a1e25160f7e22c965ad" dependencies = [ "accesskit", "accesskit_unix", @@ -2539,7 +2521,7 @@ dependencies = [ "anyhow", "async-task", "block2 0.6.2", - "cocoa 0.26.0", + "cocoa 0.26.1", "core-foundation 0.10.1", "core-foundation-sys", "core-graphics 0.24.0", @@ -2695,14 +2677,12 @@ dependencies = [ [[package]] name = "gpui-pre-scheduler" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8049963b716df01b67b58f86000597f222d5b31b15b35069b23a3b07f3c68352" dependencies = [ "async-task", "backtrace", - "chrono", "flume", "futures", + "jiff", "parking_lot", "rand 0.9.5", "wasm_thread", @@ -2787,8 +2767,6 @@ dependencies = [ [[package]] name = "gpui-pre-wgpu" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0b02657b56b09140ce542f5e4434fb96d9fdaba0fd0035ba7dba13c171ddb9b" dependencies = [ "anyhow", "bytemuck", @@ -2815,8 +2793,6 @@ dependencies = [ [[package]] name = "gpui-pre-windows" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f05592a6f9e3e6bb7a9f2a0d4779271cf747a948db1c07b02448de777ffff8f3" dependencies = [ "accesskit", "accesskit_windows", @@ -2844,12 +2820,10 @@ dependencies = [ [[package]] name = "gpui-pre-zlog" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7506302091e66d7fb5e04a5b3480e90cff0bbe3157458d7df91a41c59238c48" dependencies = [ "anyhow", - "chrono", "gpui-pre-collections", + "jiff", "log", ] @@ -3134,30 +3108,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core 0.62.2", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" version = "2.3.0" @@ -3451,6 +3401,60 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "js-sys", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "wasm-bindgen", + "windows-link 0.2.1", +] + +[[package]] +name = "jiff-core" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "jiff-tzdb" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" + +[[package]] +name = "jiff-tzdb-platform" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jni" version = "0.22.4" @@ -3521,13 +3525,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", - "once_cell", "wasm-bindgen", ] @@ -3627,9 +3630,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.23" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d8f1ea3f21fd3405dcaf6c9b5c1630af9afc422d9073ea39c5f6d6c772e08ed" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ "libc", ] @@ -5007,9 +5010,9 @@ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] name = "portable-atomic-util" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" dependencies = [ "portable-atomic", ] @@ -7315,12 +7318,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "serde", "wasm-bindgen-macro", @@ -7329,19 +7331,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.71" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -7349,22 +7352,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.4", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] @@ -7495,9 +7498,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -7515,9 +7518,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] diff --git a/vendor/gpui-base/Cargo.toml b/vendor/gpui-base/Cargo.toml index 8fbfd5ef..6532e31c 100644 --- a/vendor/gpui-base/Cargo.toml +++ b/vendor/gpui-base/Cargo.toml @@ -68,8 +68,9 @@ version = "1.1.3" [dependencies.anyhow] version = "1" -[dependencies.chrono] -version = "0.4.38" +[dependencies.jiff] +version = "1.1" +features = ["js"] [dependencies.data-url] version = "0.3" @@ -244,3 +245,11 @@ useless_conversion = "allow" [lints.clippy.style] level = "allow" priority = -1 + +[patch.crates-io] +gpui-pre = { path = "../gpui-pre" } +gpui-pre-linux = { path = "../gpui-pre-linux" } +gpui-pre-scheduler = { path = "../gpui-pre-scheduler" } +gpui-pre-wgpu = { path = "../gpui-pre-wgpu" } +gpui-pre-windows = { path = "../gpui-pre-windows" } +gpui-pre-zlog = { path = "../gpui-pre-zlog" } diff --git a/vendor/gpui-base/NOCTERM.md b/vendor/gpui-base/NOCTERM.md index 5cbde24c..f55e8472 100644 --- a/vendor/gpui-base/NOCTERM.md +++ b/vendor/gpui-base/NOCTERM.md @@ -1,5 +1,8 @@ # Nocterm's GPUI Base zoom patch +Multiline inputs refresh their pointer and rectangular-selection affordances +when Alt changes. Other modifier transitions leave the rendered input current. + The input engine exposes its existing synchronous document revision through a read-only getter. Programmatic value replacement advances it even when Change events are suppressed. The existing counter wraps at u64::MAX; consumers that @@ -32,6 +35,32 @@ explicit overrides, removed/replaced groups and callback behavior. Nocterm's workspace tests also retain the real native header double-click regression. Remove this patch when upstream offers equivalent safe request reconciliation. +Text selection line boxes test vertical clipping before looking up glyph positions +and allocate space only for the boxes returned to the viewport. Source selection, +copying and hit testing still use their existing text layouts. + +Fit-content paragraphs rendered as a single text element carry their trailing +space on the same layout node. The text bounds used for selection exclude the +paragraph gap. + +Large non-scrollable documents with text-only paragraphs, including inline +code spans, group their layout leaves into anonymous blocks of 32. This +bounds the temporary child arrays used by each Taffy block pass. The grouped root uses the content wrapper's +width when it is resolved. Paragraph indices, trailing spacing and paint +order still come from the original document. Short documents, virtualized +documents and documents with embedded inline elements use their original +layout path. + +Inline text leaves wholly clipped private hitboxes out of the frame's hit +test. Partially visible text keeps its hitbox, and only spans with links +register link-specific handlers. Clipped text remains part of the layout +and selection geometry. + +Inline flow wrapping and shaping use the sorted highlights intersecting +each line or fragment. Font-size segmentation is clipped in document byte +coordinates before constructing positioned text, keeping explicit line +breaks, style boundaries and source positions. + The published crate's `src/text/text_view.rs` unit test refers to the omitted repository root README. `tests/upstream/README.md` preserves that exact file from the same pinned commit; only the test include path changes. Existing assertions @@ -77,3 +106,50 @@ geometry, so ScrollableMask does not map wheel deltas through stale absolute content-height estimates. Horizontal routing and axis locks keep their existing behavior. Remove this patch when upstream provides equivalent relative wheel routing for variable-height lists. + +The text input paints single-row rectangular selections with GPUI's solid quad +primitive. Rectangles smaller than a device pixel keep their original path +coverage. Multi-row selection shapes retain the original outline, and token +gaps, masking, clipping and active-window styling use the same selection +ranges. Common text selection can therefore avoid creating the GPU renderer's +full-window path attachments. + +Scrollbars keep their visibility curves. Passive exits normally follow the +display callback. Two consecutive samples faster than 15 ms switch the +current exit to paced timer wakeups. At most one fade wake per scrollbar +is pending, with a shorter final interval when needed to reach the initial +deadline. Hover, wheel, track clicks and dragging keep their input path. +The scrollbar keeps interaction state and geometry together and separates +theme resolution, motion and GPUI painting. + +Dock last-panel guards stop checking visibility as soon as they encounter +a second visible panel. Hidden panels only affect how far the guard scans. + +When a tab group's membership changes, retained view entities keep their +observers. Each new view receives one observer, and departures detach as part +of reconciliation. The subscription table is sized to the current group. + +Tab-group reconciliation retains the panel observers when the ordered view +identities match. The group and its render snapshots share that immutable +list for as long as it describes their panels. Active-state delivery prunes +departed panel IDs after membership changes and move handoffs. + +Selecting a tab clamps the new index in its group while preserving the +existing edit result. Structural changes still normalize the tree. Panel +lookup stops at the last matching group in layout order, and existence +checks reuse that lookup without collecting panel IDs. + +Split resizing updates the existing size vector in place. The same +redistribution, size limits and notifications apply to pointer drags +and programmatic resizing. A zero-distance drag still synchronizes +the measured panel sizes. + +Committing split slot sizes updates the target split using the existing +child-count check. The canonical tree shape is preserved by size-only edits. + +Button semantic refinements are stored only when supplied, rather than +embedding two empty large style values in each transient button. The first +builder moves its refinement into the owned slot; repeated builders merge +into that slot. The same selected-then-disabled precedence still applies +and unconfigured states add no heap allocation. Remove this patch when +upstream avoids embedding unused button state refinements. diff --git a/vendor/gpui-base/src/button.rs b/vendor/gpui-base/src/button.rs index 84a870c4..59cefc57 100644 --- a/vendor/gpui-base/src/button.rs +++ b/vendor/gpui-base/src/button.rs @@ -1,3 +1,4 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. use std::rc::Rc; use gpui::{ @@ -142,8 +143,14 @@ impl Button { crate::state_style::resolve_style( &self.style, [ - self.selected.then_some(&self.semantic_styles.selected), - self.disabled.then_some(&self.semantic_styles.disabled), + self.semantic_styles + .selected + .as_deref() + .filter(|_| self.selected), + self.semantic_styles + .disabled + .as_deref() + .filter(|_| self.disabled), ] .into_iter() .flatten(), @@ -164,24 +171,33 @@ impl Selectable for Button { /// Semantic styles supported by [`Button`]. #[derive(Default)] pub struct ButtonStyles { - selected: StyleRefinement, - disabled: StyleRefinement, + // Most buttons supply no semantic override for the current state. Store + // only supplied refinements instead of copying two large empty values + // through every element builder. + selected: Option>, + disabled: Option>, } impl ButtonStyles { /// Refines the root style when the button is selected. pub fn selected(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self { - self.selected - .refine(&build(StateStyle::default()).into_refinement()); + Self::refine(&mut self.selected, build(StateStyle::default())); self } /// Refines the root style when the button is disabled. pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self { - self.disabled - .refine(&build(StateStyle::default()).into_refinement()); + Self::refine(&mut self.disabled, build(StateStyle::default())); self } + + fn refine(slot: &mut Option>, style: StateStyle) { + let refinement = style.into_refinement(); + match slot { + Some(existing) => existing.refine(&refinement), + None => *slot = Some(Box::new(refinement)), + } + } } impl Styled for Button { @@ -495,6 +511,41 @@ mod tests { ); } + #[gpui::test] + fn repeated_semantic_styles_preserve_earlier_painted_properties(cx: &mut TestAppContext) { + struct Host; + impl Render for Host { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + Button::new("semantic") + .size(px(40.)) + .selected(true) + .disabled(true) + .styles(|styles| styles.selected(|style| style.bg(gpui::rgb(0x123456)))) + .styles(|styles| { + styles.selected(|style| style.border_1().border_color(gpui::rgb(0x654321))) + }) + .styles(|styles| styles.disabled(|style| style.bg(gpui::rgb(0xabcdef)))) + } + } + + let (_, context) = cx.add_window_view(|_, _| Host); + context.update(|window, cx| { + window.draw(cx).clear(cx); + let quads = window.painted_quads(); + let background = quads + .iter() + .find(|quad| quad.background == gpui::rgb(0xabcdef).into()) + .expect("disabled background"); + assert!( + quads.iter().any(|quad| { + quad.bounds == background.bounds + && quad.border_color == gpui::rgb(0x654321).into() + }), + "earlier selected border must survive the later disabled background" + ); + }); + } + #[gpui::test] fn accessibility_role_label_and_disabled_action_surface(cx: &mut TestAppContext) { type Captured = Arc>>; diff --git a/vendor/gpui-base/src/calendar.rs b/vendor/gpui-base/src/calendar.rs index ea98c558..c9d5aa02 100644 --- a/vendor/gpui-base/src/calendar.rs +++ b/vendor/gpui-base/src/calendar.rs @@ -1,19 +1,23 @@ +// Modified by Nocterm: use Jiff civil dates and checked calendar arithmetic. use crate::TestSupportExt as _; use std::rc::Rc; use crate::{h_flex, styled::StyledExt as _, v_flex}; -use chrono::{Datelike, Local, NaiveDate, Weekday}; use gpui::{ AnyElement, App, Context, ElementId, Empty, Entity, EventEmitter, FocusHandle, InteractiveElement, IntoElement, ParentElement, Render, RenderOnce, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window, div, px, }; +use jiff::{ + Span, ZonedDateTime, + civil::{Date as CivilDate, Weekday}, +}; /// A controlled calendar value. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Date { - Single(Option), - Range(Option, Option), + Single(Option), + Range(Option, Option), } impl std::fmt::Display for Date { @@ -28,13 +32,13 @@ impl std::fmt::Display for Date { } } -impl From for Date { - fn from(value: NaiveDate) -> Self { +impl From for Date { + fn from(value: CivilDate) -> Self { Self::Single(Some(value)) } } -impl From<(NaiveDate, NaiveDate)> for Date { - fn from((start, end): (NaiveDate, NaiveDate)) -> Self { +impl From<(CivilDate, CivilDate)> for Date { + fn from((start, end): (CivilDate, CivilDate)) -> Self { Self::Range(Some(start), Some(end)) } } @@ -46,13 +50,13 @@ impl Date { pub fn is_complete(&self) -> bool { matches!(self, Self::Single(Some(_)) | Self::Range(Some(_), Some(_))) } - pub fn start(&self) -> Option { + pub fn start(&self) -> Option { match self { Self::Single(Some(v)) | Self::Range(Some(v), _) => Some(*v), _ => None, } } - pub fn end(&self) -> Option { + pub fn end(&self) -> Option { match self { Self::Range(_, Some(v)) => Some(*v), _ => None, @@ -60,14 +64,14 @@ impl Date { } pub fn format(&self, format: &str) -> Option { match self { - Self::Single(Some(v)) => Some(v.format(format).to_string().into()), + Self::Single(Some(v)) => Some(v.strftime(format).to_string().into()), Self::Range(Some(a), Some(b)) => { - Some(format!("{} - {}", a.format(format), b.format(format)).into()) + Some(format!("{} - {}", a.strftime(format), b.strftime(format)).into()) } _ => None, } } - pub fn is_active(&self, value: &NaiveDate) -> bool { + pub fn is_active(&self, value: &CivilDate) -> bool { match self { Self::Single(v) => *v == Some(*value), Self::Range(a, b) => *a == Some(*value) || *b == Some(*value), @@ -76,43 +80,43 @@ impl Date { pub fn is_single(&self) -> bool { matches!(self, Self::Single(_)) } - pub fn is_in_range(&self, value: &NaiveDate) -> bool { + pub fn is_in_range(&self, value: &CivilDate) -> bool { matches!(self, Self::Range(Some(a), Some(b)) if value >= a && value <= b) } } pub struct IntervalMatcher { - before: Option, - after: Option, + before: Option, + after: Option, } pub struct RangeMatcher { - from: Option, - to: Option, + from: Option, + to: Option, } pub enum Matcher { DayOfWeek(Vec), Interval(IntervalMatcher), Range(RangeMatcher), - Custom(Box bool + Send + Sync>), + Custom(Box bool + Send + Sync>), } impl From> for Matcher { fn from(v: Vec) -> Self { Self::DayOfWeek(v) } } -impl bool + Send + Sync + 'static> From for Matcher { +impl bool + Send + Sync + 'static> From for Matcher { fn from(v: F) -> Self { Self::Custom(Box::new(v)) } } impl Matcher { - pub fn interval(before: Option, after: Option) -> Self { + pub fn interval(before: Option, after: Option) -> Self { Self::Interval(IntervalMatcher { before, after }) } - pub fn range(from: Option, to: Option) -> Self { + pub fn range(from: Option, to: Option) -> Self { Self::Range(RangeMatcher { from, to }) } - pub fn custom bool + Send + Sync + 'static>(f: F) -> Self { + pub fn custom bool + Send + Sync + 'static>(f: F) -> Self { Self::Custom(Box::new(f)) } pub fn is_match(&self, date: &Date) -> bool { @@ -122,9 +126,11 @@ impl Matcher { _ => false, } } - pub fn matched(&self, date: &NaiveDate) -> bool { + pub fn matched(&self, date: &CivilDate) -> bool { match self { - Self::DayOfWeek(days) => days.contains(&date.weekday().num_days_from_sunday()), + Self::DayOfWeek(days) => { + days.contains(&(date.weekday().to_sunday_zero_offset() as u32)) + } Self::Interval(v) => { v.before.is_some_and(|x| date < &x) || v.after.is_some_and(|x| date > &x) } @@ -174,19 +180,19 @@ pub struct CalendarState { current_month: u8, years: Vec>, year_page: i32, - today: NaiveDate, + today: CivilDate, number_of_months: usize, disabled_matcher: Option>, } impl CalendarState { pub fn new(_: &mut Window, cx: &mut Context) -> Self { - let today = Local::now().date_naive(); + let today = ZonedDateTime::now().date(); Self { focus_handle: cx.focus_handle(), view: CalendarView::Day, date: Date::Single(None), - current_year: today.year(), + current_year: i32::from(today.year()), current_month: today.month() as u8, years: vec![], year_page: 0, @@ -194,7 +200,7 @@ impl CalendarState { number_of_months: 1, disabled_matcher: None, } - .year_range((today.year() - 50, today.year() + 50)) + .year_range((i32::from(today.year()) - 50, i32::from(today.year()) + 50)) } pub fn disabled_matcher(mut self, matcher: impl Into) -> Self { self.disabled_matcher = Some(Rc::new(matcher.into())); @@ -230,11 +236,11 @@ impl CalendarState { self.date = date; if let Some(v) = date.start() { self.current_month = v.month() as u8; - self.current_year = v.year(); + self.current_year = i32::from(v.year()); } true } - pub fn select_date(&mut self, value: NaiveDate) -> bool { + pub fn select_date(&mut self, value: CivilDate) -> bool { if self .disabled_matcher .as_ref() @@ -258,7 +264,7 @@ impl CalendarState { /// Activates a day item and emits [`CalendarEvent::Selected`] once the /// controlled value is complete. This is the single pointer/keyboard /// activation path used by the calendar root. - pub fn activate_date(&mut self, value: NaiveDate, cx: &mut Context) -> bool { + pub fn activate_date(&mut self, value: CivilDate, cx: &mut Context) -> bool { let complete = self.select_date(value); if complete { cx.emit(CalendarEvent::Selected(self.date())); @@ -285,7 +291,8 @@ impl CalendarState { cx.notify(); } fn apply_year_range(&mut self, range: (i32, i32)) { - self.years = (range.0..range.1) + self.years = (range.0.max(i32::from(CivilDate::MIN.year())) + ..range.1.min(i32::from(CivilDate::MAX.year()) + 1)) .collect::>() .chunks(20) .map(<[_]>::to_vec) @@ -303,18 +310,18 @@ impl CalendarState { n.rem_euclid(12) as u32 + 1, ) } - pub fn days(&self) -> Vec> { + pub fn days(&self) -> Vec> { self.month_days().into_iter().flatten().collect() } /// Calendar weeks grouped by visible month. This preserves six-week /// months and is the preferred rendering API. - pub fn month_days(&self) -> Vec>> { + pub fn month_days(&self) -> Vec>> { (0..self.number_of_months) .map(|n| { days_in_month( self.current_year, self.current_month as u32 + n as u32, - Weekday::Sun, + Weekday::Sunday, ) }) .collect() @@ -341,7 +348,16 @@ impl CalendarState { true } } + fn has_prev_month(&self) -> bool { + self.current_year > i32::from(CivilDate::MIN.year()) || self.current_month > 1 + } + fn has_next_month(&self) -> bool { + self.current_year < i32::from(CivilDate::MAX.year()) || self.current_month < 12 + } pub fn prev_month(&mut self) { + if !self.has_prev_month() { + return; + } if self.current_month == 1 { self.current_year -= 1; self.current_month = 12; @@ -350,6 +366,9 @@ impl CalendarState { } } pub fn next_month(&mut self) { + if !self.has_next_month() { + return; + } if self.current_month == 12 { self.current_year += 1; self.current_month = 1; @@ -369,7 +388,7 @@ impl CalendarState { pub fn current_month(&self) -> u8 { self.current_month } - pub fn today(&self) -> NaiveDate { + pub fn today(&self) -> CivilDate { self.today } pub fn years_on_page(&self) -> &[i32] { @@ -383,7 +402,10 @@ impl CalendarState { self.view = CalendarView::Day; } pub fn select_year(&mut self, year: i32) { - self.current_year = year; + self.current_year = year.clamp( + i32::from(CivilDate::MIN.year()), + i32::from(CivilDate::MAX.year()), + ); self.view = CalendarView::Day; } } @@ -574,7 +596,7 @@ impl Calendar { id: id.into(), state: state.clone(), number_of_months: 1, - first_day_of_week: Weekday::Sun, + first_day_of_week: Weekday::Sunday, style: StyleRefinement::default(), item: Rc::new(|item, _, _, _| item.into_any_element()), label: Rc::new(|kind, value| match kind { @@ -639,7 +661,9 @@ impl RenderOnce for Calendar { let view = self.state.read(cx).view(); let mut header = h_flex().items_center().justify_between().child({ let st = CalendarItemState::new(CalendarItemKind::Previous).disabled( - view.is_month() || (view.is_year() && !self.state.read(cx).has_prev_year_page()), + view.is_month() + || (view.is_year() && !self.state.read(cx).has_prev_year_page()) + || (view.is_day() && !self.state.read(cx).has_prev_month()), ); let mut item = CalendarItem::new("calendar-prev", st).with_label((self.label)(st.kind(), 0)); @@ -708,7 +732,9 @@ impl RenderOnce for Calendar { } header = header.child({ let st = CalendarItemState::new(CalendarItemKind::Next).disabled( - view.is_month() || (view.is_year() && !self.state.read(cx).has_next_year_page()), + view.is_month() + || (view.is_year() && !self.state.read(cx).has_next_year_page()) + || (view.is_day() && !self.state.read(cx).has_next_month()), ); let mut item = CalendarItem::new("calendar-next", st).with_label((self.label)(st.kind(), 0)); @@ -747,7 +773,7 @@ impl RenderOnce for Calendar { header_row = header_row.child(self.render_item( format!("weekday-{offset}-{weekday}"), st, - (weekday + self.first_day_of_week.num_days_from_sunday() as i32) % 7, + (weekday + self.first_day_of_week.to_sunday_zero_offset() as i32) % 7, window, cx, )); @@ -755,6 +781,9 @@ impl RenderOnce for Calendar { month = month.child(header_row); for (week_index, week) in weeks.iter().enumerate() { let mut week_row = h_flex(); + if week_index == 0 && week.len() < 7 { + week_row = week_row.justify_end(); + } for date in week { let date = *date; let st = { @@ -765,7 +794,7 @@ impl RenderOnce for Calendar { CalendarItemState::new(CalendarItemKind::Day) .active(s.date().is_active(&date)) .in_range(s.date().is_in_range(&date)) - .muted(date.month() != m || disabled) + .muted(u32::from(date.month() as u8) != m || disabled) .disabled(disabled) .today(date == s.today()) }; @@ -828,26 +857,36 @@ impl RenderOnce for Calendar { } } -fn days_in_month(year: i32, month: u32, first_day: Weekday) -> Vec> { - let total = year as i64 * 12 + month as i64 - 1; - let year = total.div_euclid(12) as i32; - let month = total.rem_euclid(12) as u32 + 1; - let first = NaiveDate::from_ymd_opt(year, month, 1).unwrap(); - let next = if month == 12 { - NaiveDate::from_ymd_opt(year + 1, 1, 1).unwrap() - } else { - NaiveDate::from_ymd_opt(year, month + 1, 1).unwrap() +fn days_in_month(year: i32, month: u32, first_day: Weekday) -> Vec> { + let total = i64::from(year) * 12 + i64::from(month) - 1; + let Ok(year) = i16::try_from(total.div_euclid(12)) else { + return Vec::new(); + }; + let month = total.rem_euclid(12) as i8 + 1; + let Ok(first) = CivilDate::new(year, month, 1) else { + return Vec::new(); }; - let offset = - (first.weekday().num_days_from_sunday() + 7 - first_day.num_days_from_sunday()) % 7; - let start = first - chrono::Duration::days(offset as i64); - let count = ((next - start).num_days() as usize).div_ceil(7) * 7; - (0..count) - .map(|n| start + chrono::Duration::days(n as i64)) - .collect::>() - .chunks(7) - .map(<[_]>::to_vec) - .collect() + let offset = i64::from( + (first.weekday().to_sunday_zero_offset() + 7 - first_day.to_sunday_zero_offset()) % 7, + ); + let count = ((i64::from(first.days_in_month()) + offset) as usize).div_ceil(7); + let start = first.checked_add(Span::new().days(-offset)); + let leading = if start.is_err() { offset as usize } else { 0 }; + let mut next = Some(start.unwrap_or(CivilDate::MIN)); + let mut weeks = Vec::with_capacity(count); + for index in 0..count { + let mut days = Vec::with_capacity(7); + let slots = if index == 0 { 7 - leading } else { 7 }; + for _ in 0..slots { + let Some(date) = next else { + break; + }; + days.push(date); + next = date.tomorrow().ok(); + } + weeks.push(days); + } + weeks } #[cfg(test)] @@ -886,9 +925,7 @@ mod tests { for mode in [CalendarView::Day, CalendarView::Month, CalendarView::Year] { cx.update(|window, cx| { view.read(cx).calendar.clone().update(cx, |state, cx| { - state.apply_date(Date::Single(Some( - NaiveDate::from_ymd_opt(2026, 9, 7).unwrap(), - ))); + state.apply_date(Date::Single(Some(CivilDate::new(2026, 9, 7).unwrap()))); state.set_view(mode); cx.notify(); }); @@ -943,8 +980,8 @@ mod tests { #[gpui::test] fn range_selection_restarts_and_completes(cx: &mut gpui::TestAppContext) { let s = state(cx, Date::Range(None, None)); - let a = NaiveDate::from_ymd_opt(2025, 2, 10).unwrap(); - let b = NaiveDate::from_ymd_opt(2025, 2, 12).unwrap(); + let a = CivilDate::new(2025, 2, 10).unwrap(); + let b = CivilDate::new(2025, 2, 12).unwrap(); s.update(cx, |s, _| { assert!(!s.select_date(a)); assert!(s.select_date(b)); @@ -961,24 +998,19 @@ mod tests { let s = state(cx, Date::Single(None)); s.update(cx, |s, _| { s.disabled_matcher = Some(Rc::new(Matcher::range( - Some(NaiveDate::from_ymd_opt(2025, 1, 1).unwrap()), - Some(NaiveDate::from_ymd_opt(2025, 1, 31).unwrap()), + Some(CivilDate::new(2025, 1, 1).unwrap()), + Some(CivilDate::new(2025, 1, 31).unwrap()), ))) }); s.update(cx, |s, _| { - assert!(!s.select_date(NaiveDate::from_ymd_opt(2025, 1, 2).unwrap())) + assert!(!s.select_date(CivilDate::new(2025, 1, 2).unwrap())) }); } #[gpui::test] fn month_navigation_crosses_year(cx: &mut gpui::TestAppContext) { - let s = state( - cx, - Date::Single(Some(NaiveDate::from_ymd_opt(2025, 1, 1).unwrap())), - ); + let s = state(cx, Date::Single(Some(CivilDate::new(2025, 1, 1).unwrap()))); s.update(cx, |s, _| { - s.apply_date(Date::Single(Some( - NaiveDate::from_ymd_opt(2025, 1, 1).unwrap(), - ))); + s.apply_date(Date::Single(Some(CivilDate::new(2025, 1, 1).unwrap()))); s.prev_month(); }); assert_eq!( @@ -992,16 +1024,32 @@ mod tests { ); } + #[gpui::test] + fn month_navigation_stays_within_supported_dates(cx: &mut gpui::TestAppContext) { + let s = state(cx, Date::Single(Some(CivilDate::MIN))); + s.update(cx, |s, _| { + s.apply_date(Date::Single(Some(CivilDate::MIN))); + s.prev_month(); + assert_eq!( + (s.current_year(), s.current_month()), + (i32::from(CivilDate::MIN.year()), 1) + ); + assert!(!s.has_prev_month()); + s.apply_date(Date::Single(Some(CivilDate::MAX))); + s.next_month(); + assert_eq!( + (s.current_year(), s.current_month()), + (i32::from(CivilDate::MAX.year()), 12) + ); + assert!(!s.has_next_month()); + }); + } + #[gpui::test] fn six_week_month_is_not_truncated(cx: &mut gpui::TestAppContext) { - let s = state( - cx, - Date::Single(Some(NaiveDate::from_ymd_opt(2025, 8, 1).unwrap())), - ); + let s = state(cx, Date::Single(Some(CivilDate::new(2025, 8, 1).unwrap()))); s.update(cx, |s, _| { - s.apply_date(Date::Single(Some( - NaiveDate::from_ymd_opt(2025, 8, 1).unwrap(), - ))); + s.apply_date(Date::Single(Some(CivilDate::new(2025, 8, 1).unwrap()))); assert_eq!(s.month_days().len(), 1); assert_eq!(s.month_days()[0].len(), 6); assert_eq!(s.days().len(), 6); @@ -1050,8 +1098,8 @@ mod tests { let (harness, _) = cx.add_window_view(EventHarness::new); let s = harness.read_with(cx, |h, _| h.calendar.clone()); s.update(cx, |s, _| s.date = Date::Range(None, None)); - let start = NaiveDate::from_ymd_opt(2025, 4, 4).unwrap(); - let end = NaiveDate::from_ymd_opt(2025, 4, 8).unwrap(); + let start = CivilDate::new(2025, 4, 4).unwrap(); + let end = CivilDate::new(2025, 4, 8).unwrap(); s.update(cx, |s, cx| { assert!(!s.activate_date(start, cx)); assert!(s.activate_date(end, cx)); @@ -1076,3 +1124,7 @@ mod tests { ); } } + +#[cfg(test)] +#[path = "calendar_grid_tests.rs"] +mod calendar_grid_tests; diff --git a/vendor/gpui-base/src/calendar_grid_tests.rs b/vendor/gpui-base/src/calendar_grid_tests.rs new file mode 100644 index 00000000..f0fa3741 --- /dev/null +++ b/vendor/gpui-base/src/calendar_grid_tests.rs @@ -0,0 +1,113 @@ +// Modified by Nocterm: exercise the active calendar grid instead of the unused component helper. +use jiff::civil::{Date as CivilDate, Weekday}; + +use super::days_in_month; + +#[test] +fn test_days_in_month() { + assert_eq!(CivilDate::new(2024, 2, 1).unwrap().days_in_month(), 29); + assert_eq!(CivilDate::new(2023, 2, 1).unwrap().days_in_month(), 28); + assert_eq!(CivilDate::new(2023, 1, 1).unwrap().days_in_month(), 31); + assert_eq!(CivilDate::new(2023, 4, 1).unwrap().days_in_month(), 30); +} + +#[test] +fn test_days() { + #[track_caller] + fn assert_case(date: CivilDate, first_day: Weekday, expected: Vec<&str>) { + let out = days_in_month(i32::from(date.year()), date.month() as u32, first_day) + .iter() + .map(|week| { + week.iter() + .map(|d| { + if d.year() == date.year() && d.month() == date.month() { + format!("{:2}", d.day()) + } else if d.year() == date.year() { + format!("{}-{}", d.month(), d.day()) + } else { + format!("{}-{}-{}", d.year(), d.month(), d.day()) + } + }) + .collect::>() + .join("|") + }) + .collect::>(); + + assert_eq!(out, expected); + } + + assert_case( + CivilDate::new(2024, 8, 1).unwrap(), + Weekday::Sunday, + vec![ + "7-28|7-29|7-30|7-31| 1| 2| 3", + " 4| 5| 6| 7| 8| 9|10", + "11|12|13|14|15|16|17", + "18|19|20|21|22|23|24", + "25|26|27|28|29|30|31", + ], + ); + assert_case( + CivilDate::new(2025, 1, 1).unwrap(), + Weekday::Sunday, + vec![ + "2024-12-29|2024-12-30|2024-12-31| 1| 2| 3| 4", + " 5| 6| 7| 8| 9|10|11", + "12|13|14|15|16|17|18", + "19|20|21|22|23|24|25", + "26|27|28|29|30|31|2-1", + ], + ); + + assert_case( + CivilDate::new(2024, 2, 1).unwrap(), + Weekday::Sunday, + vec![ + "1-28|1-29|1-30|1-31| 1| 2| 3", + " 4| 5| 6| 7| 8| 9|10", + "11|12|13|14|15|16|17", + "18|19|20|21|22|23|24", + "25|26|27|28|29|3-1|3-2", + ], + ); + assert_case( + CivilDate::new(2023, 2, 20).unwrap(), + Weekday::Sunday, + vec![ + "1-29|1-30|1-31| 1| 2| 3| 4", + " 5| 6| 7| 8| 9|10|11", + "12|13|14|15|16|17|18", + "19|20|21|22|23|24|25", + "26|27|28|3-1|3-2|3-3|3-4", + ], + ); + + // Monday-first week: Feb 2023 starts on a Wednesday, so the grid + // shifts to start on Monday (column 0 = Mon 30 Jan). + assert_case( + CivilDate::new(2023, 2, 1).unwrap(), + Weekday::Monday, + vec![ + "1-30|1-31| 1| 2| 3| 4| 5", + " 6| 7| 8| 9|10|11|12", + "13|14|15|16|17|18|19", + "20|21|22|23|24|25|26", + "27|28|3-1|3-2|3-3|3-4|3-5", + ], + ); +} + +#[test] +fn boundary_months_keep_all_representable_days_without_wrapping() { + for (date, month) in [(CivilDate::MIN, 1), (CivilDate::MAX, 12)] { + let grid = days_in_month(i32::from(date.year()), month, Weekday::Monday); + let days = grid.into_iter().flatten().collect::>(); + assert!(days.contains(&date)); + assert_eq!( + days.iter().filter(|d| d.month() as u32 == month).count(), + 31 + ); + assert!(days.windows(2).all(|w| w[0].tomorrow().ok() == Some(w[1]))); + } + assert!(days_in_month(10000, 1, Weekday::Monday).is_empty()); +} diff --git a/vendor/gpui-base/src/dock/active.rs b/vendor/gpui-base/src/dock/active.rs index 20cae4f0..18e0c148 100644 --- a/vendor/gpui-base/src/dock/active.rs +++ b/vendor/gpui-base/src/dock/active.rs @@ -1,4 +1,6 @@ -use std::collections::HashMap; +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use std::collections::{HashMap, HashSet}; use super::layout::PanelId; @@ -20,6 +22,7 @@ use super::layout::PanelId; pub(crate) struct ActiveTracker { notified: HashMap, sync_scheduled: bool, + prune_pending: bool, } impl ActiveTracker { @@ -48,7 +51,10 @@ impl ActiveTracker { displayed: Option, ) -> Vec<(PanelId, bool)> { // A panel that left the group is forgotten, not deactivated. - self.notified.retain(|panel, _| panels.contains(panel)); + if std::mem::take(&mut self.prune_pending) && !self.notified.is_empty() { + let members: HashSet<_> = panels.iter().copied().collect(); + self.notified.retain(|panel, _| members.contains(panel)); + } let mut deactivations = Vec::new(); let mut activation = None; @@ -81,11 +87,18 @@ impl ActiveTracker { deactivations } + /// Reconcile departures against the final membership when the scheduled + /// delivery runs. Display changes within that membership need no prune. + pub(crate) fn membership_changed(&mut self) { + self.prune_pending = true; + } + /// Record what a panel was last told, without emitting anything. Used /// when a panel moves between groups while displayed, so the move does /// not look like an edge to the destination group. pub(crate) fn seed(&mut self, panel: PanelId, active: bool) { self.notified.insert(panel, active); + self.membership_changed(); } /// What this tracker last told `panel`, if anything. A pure read: it does @@ -161,6 +174,7 @@ mod tests { let mut tracker = ActiveTracker::default(); tracker.reconcile(&[panel(1), panel(2)], Some(panel(1))); + tracker.membership_changed(); let changes = tracker.reconcile(&[panel(2)], Some(panel(2))); assert_eq!( diff --git a/vendor/gpui-base/src/dock/layout/edit.rs b/vendor/gpui-base/src/dock/layout/edit.rs index 2f6d4af9..a10ce104 100644 --- a/vendor/gpui-base/src/dock/layout/edit.rs +++ b/vendor/gpui-base/src/dock/layout/edit.rs @@ -1,3 +1,5 @@ +// Nocterm: keep selection and size edits local to their target node. + use std::collections::HashMap; use gpui::Pixels; @@ -79,45 +81,36 @@ impl PaneTree { } pub fn set_active(&mut self, node: NodeId, ix: usize) -> EditResult { - self.edit(|tree| { - let Some(path) = tree.path_of_node(node) else { - return false; - }; - let NodeKind::Tabs { active_ix, .. } = tree.node_at_mut(&path).kind_mut() else { - return false; - }; - if *active_ix == ix { - return false; - } - *active_ix = ix; - true - }) + let Some(path) = self.path_of_node(node) else { + return EditResult::default(); + }; + let NodeKind::Tabs { panels, active_ix } = self.node_at_mut(&path).kind_mut() else { + return EditResult::default(); + }; + // The layout is canonical already. Only this index can need clamping, + // and a request that differs before clamping still counts as an edit. + let changed = *active_ix != ix; + *active_ix = ix.min(panels.len().saturating_sub(1)); + EditResult { changed } } - /// Replace a split's slot sizes wholesale. - /// - /// A no-op, like every other operation given input it cannot resolve, if - /// `new_sizes.len()` does not match the split's child count: no rule in - /// `normalize` repairs a length mismatch, so applying it would otherwise - /// leave `children.len() != sizes.len()` and trip `normalize`'s - /// `debug_assert!`. + /// Replace a split's slot sizes. The vector must match its child count. + /// Changing size preferences preserves the already normalized tree shape. pub fn set_sizes(&mut self, node: NodeId, new_sizes: Vec>) -> EditResult { - self.edit(|tree| { - let Some(path) = tree.path_of_node(node) else { - return false; - }; - let NodeKind::Split { - children, sizes, .. - } = tree.node_at_mut(&path).kind_mut() - else { - return false; - }; - if new_sizes.len() != children.len() || *sizes == new_sizes { - return false; - } - *sizes = new_sizes; - true - }) + let Some(path) = self.path_of_node(node) else { + return EditResult::default(); + }; + let NodeKind::Split { + children, sizes, .. + } = self.node_at_mut(&path).kind_mut() + else { + return EditResult::default(); + }; + if new_sizes.len() != children.len() || *sizes == new_sizes { + return EditResult::default(); + } + *sizes = new_sizes; + EditResult { changed: true } } } @@ -181,7 +174,7 @@ impl PaneTree { /// Whether `panel` is anywhere in this tree. pub fn contains_panel(&self, panel: PanelId) -> bool { - self.panels().any(|candidate| candidate == panel) + self.find_panel_node(panel).is_some() } } @@ -344,6 +337,9 @@ fn split_parent_of(path: &super::tree::NodePath) -> Option<(super::tree::NodePat Some((parent.iter().copied().collect(), ix)) } +#[cfg(test)] +mod split_sizes_tests; + #[cfg(test)] mod tests { use super::super::*; @@ -572,6 +568,89 @@ mod tests { assert!(!result.changed()); } + #[test] + fn selecting_clamps_the_index_and_leaves_other_groups_alone() { + let (mut tree, tabs) = tree_with_one_group(); + tree.insert_panel( + panel(2), + InsertTarget::Tabs { + node: tabs, + ix: None, + activate: false, + }, + ); + tree.split(tabs, panel(3), Placement::Right, Some(px(90.))); + let other = tree.find_panel_node(panel(3)).unwrap(); + let before = tree.clone(); + + assert!(tree.set_active(tabs, usize::MAX).changed()); + assert!(tree.set_active(tabs, usize::MAX).changed()); + assert!(!tree.set_active(tabs, 1).changed()); + assert!(!tree.set_active(tree.root().id(), 1).changed()); + assert!(matches!( + tree.find_node(tabs).unwrap().kind(), + PaneRef::Tabs { active_ix: 1, .. } + )); + assert_eq!(tree.find_node(other), before.find_node(other)); + assert!(tree.set_active(tabs, 0).changed()); + assert_eq!(tree, before); + } + + #[test] + #[ignore = "manual CPU measurement of a wide pane tree"] + fn measure_selection_in_a_wide_pane_tree() { + use std::{hint::black_box, time::Instant}; + + let groups: usize = std::env::var("NOCTERM_PROFILE_PANE_COUNT") + .map(|value| value.parse().unwrap()) + .unwrap_or(128); + assert!(groups >= 1); + let (mut tree, first) = tree_with_one_group(); + for group in 0..groups { + let first_panel = panel(1 + group as u64 * 2); + if group > 0 { + assert!( + tree.split(first, first_panel, Placement::Right, None) + .changed() + ); + } + let node = tree.find_panel_node(first_panel).unwrap(); + assert!( + tree.insert_panel( + panel(first_panel.as_u64() + 1), + InsertTarget::Tabs { + node, + ix: None, + activate: false + }, + ) + .changed() + ); + } + + let mut samples = Vec::new(); + for _ in 0..101 { + let start = Instant::now(); + for selection in 0..512 { + let group = (selection / 2) % groups; + let second = 2 + group as u64 * 2; + let node = tree.find_panel_node(black_box(panel(second))).unwrap(); + black_box(tree.set_active(node, 1 - selection % 2).changed()); + } + samples.push(start.elapsed().as_nanos() as f64 / 512.0); + } + samples.sort_unstable_by(f64::total_cmp); + assert_eq!(tree.panels().count(), groups * 2); + assert!(matches!( + tree.find_node(first).unwrap().kind(), + PaneRef::Tabs { active_ix: 0, .. } + )); + eprintln!( + "groups={groups} selection_p50_ns={:.2} selection_p95_ns={:.2}", + samples[50], samples[95] + ); + } + #[test] fn set_sizes_replaces_a_matching_length_vector() { let (mut tree, tabs) = tree_with_one_group(); diff --git a/vendor/gpui-base/src/dock/layout/edit/split_sizes_tests.rs b/vendor/gpui-base/src/dock/layout/edit/split_sizes_tests.rs new file mode 100644 index 00000000..8a9daef3 --- /dev/null +++ b/vendor/gpui-base/src/dock/layout/edit/split_sizes_tests.rs @@ -0,0 +1,151 @@ +// Nocterm: characterize split commits and measure their dependence on tree size. + +use super::{NodeId, PaneTree, PanelId, Placement}; +use crate::dock::{ + DockArea, DockEvent, DockLayout, PaneRef, PanelInfo, RootKind, test_support::TestPanel, +}; + +use gpui::{Modifiers, MouseButton, Pixels, TestAppContext, point, px}; +use std::{cell::Cell, hint::black_box, rc::Rc, time::Instant}; + +fn nested_split(descendants: usize) -> PaneTree { + let mut tree = PaneTree::new(RootKind::Split); + let anchor = PanelId::from_u64(1); + tree.split(tree.root().id(), anchor, Placement::Right, None); + let first = tree.find_panel_node(anchor).unwrap(); + tree.split(first, PanelId::from_u64(2), Placement::Right, None); + for id in 0..descendants { + tree.split( + first, + PanelId::from_u64(id as u64 + 3), + Placement::Bottom, + None, + ); + } + let PaneRef::Split { children, .. } = tree.root().kind() else { + panic!("expected a root split"); + }; + assert_eq!(children.len(), 2); + tree +} + +fn slot_sizes(tree: &PaneTree, node: NodeId) -> &[Option] { + let PaneRef::Split { sizes, .. } = tree.find_node(node).unwrap().kind() else { + panic!("expected a split"); + }; + sizes +} + +#[test] +fn a_split_size_write_leaves_nested_layouts_alone() { + let mut tree = nested_split(8); + let root = tree.root().id(); + let tabs = tree.find_panel_node(PanelId::from_u64(1)).unwrap(); + let PaneRef::Split { children, .. } = tree.root().kind() else { + panic!("expected a root split"); + }; + let descendants = children.to_vec(); + let sizes = vec![Some(px(220.)), None]; + assert!(tree.set_sizes(root, sizes.clone()).changed()); + assert!(!tree.set_sizes(root, sizes.clone()).changed()); + assert!(!tree.set_sizes(tabs, vec![Some(px(180.))]).changed()); + let removed = PanelId::from_u64(9); + let removed_node = tree.find_panel_node(removed).unwrap(); + assert_eq!(slot_sizes(&tree, root), &sizes); + let PaneRef::Split { children, .. } = tree.root().kind() else { + panic!("expected a root split"); + }; + assert_eq!(children, &descendants); + assert!(tree.remove_panel(removed).changed()); + assert!(!tree.set_sizes(removed_node, sizes.clone()).changed()); + assert_eq!(slot_sizes(&tree, root), sizes); +} + +fn dumped_split(area: &DockArea, app: &gpui::App) -> Vec { + let PanelInfo::Stack { sizes, .. } = area.dump(app).center.info else { + panic!("expected a saved split"); + }; + sizes +} + +#[gpui::test] +fn dragging_a_split_commits_the_measured_sizes_on_release(cx: &mut TestAppContext) { + cx.update(|app| { + let _ = crate::Theme::global_mut(app); + }); + let (area, cx) = + cx.add_window_view(|window, cx| DockArea::new("split-commit", None, window, cx)); + cx.update(|window, app| { + area.update(app, |area, cx| { + area.set_center( + DockLayout::h_split() + .child( + DockLayout::tabs().panel(TestPanel::new("First", cx)), + Some(px(300.)), + ) + .child( + DockLayout::tabs().panel(TestPanel::new("Second", cx)), + Some(px(300.)), + ), + window, + cx, + ); + }); + }); + cx.run_until_parked(); + let initial = cx.read(|app| dumped_split(area.read(app), app)); + let changes = Rc::new(Cell::new(0)); + let _subscription = cx.update(|window, app| { + let changes = changes.clone(); + window.subscribe(&area, app, move |_, event: &DockEvent, _, _| { + if matches!(event, DockEvent::LayoutChanged) { + changes.set(changes.get() + 1); + } + }) + }); + let seam = initial[0]; + let y = px(72.); + let modifiers = Modifiers::default(); + cx.simulate_mouse_down(point(seam - px(2.), y), MouseButton::Left, modifiers); + cx.simulate_mouse_move(point(seam + px(10.), y), Some(MouseButton::Left), modifiers); + let target = seam + px(40.); + cx.simulate_mouse_move(point(target, y), Some(MouseButton::Left), modifiers); + assert_eq!(changes.get(), 0); + cx.simulate_mouse_up(point(target, y), MouseButton::Left, modifiers); + cx.run_until_parked(); + let saved = cx.read(|app| dumped_split(area.read(app), app)); + assert_eq!(changes.get(), 1); + assert_eq!(saved, [target, initial[1] - px(40.)]); +} + +#[test] +#[ignore = "manual CPU measurement of a split size commit"] +fn measure_split_size_commits() { + let descendants = std::env::var("NOCTERM_PROFILE_SPLIT_DESCENDANTS") + .map(|value| value.parse::().unwrap()) + .unwrap_or(128); + let change = std::env::var("NOCTERM_PROFILE_SPLIT_CHANGE").as_deref() != Ok("0"); + let mut tree = nested_split(descendants); + let root = tree.root().id(); + assert!( + tree.set_sizes(root, vec![Some(px(210.)), Some(px(300.))]) + .changed() + ); + let mut samples = Vec::new(); + for _ in 0..101 { + let started = Instant::now(); + for step in 0..256 { + let first = if change && step % 2 == 0 { 220. } else { 210. }; + let values = black_box(vec![Some(px(first)), Some(px(300.))]); + assert_eq!(tree.set_sizes(root, values).changed(), change); + } + samples.push(started.elapsed().as_nanos() as f64 / 256.); + } + samples.sort_unstable_by(f64::total_cmp); + assert_eq!(tree.panels().count(), descendants + 2); + assert_eq!(slot_sizes(&tree, root), &[Some(px(210.)), Some(px(300.))]); + eprintln!( + "descendants={descendants} change={change} commit_p50_ns={:.2} commit_p95_ns={:.2}", + samples[50], samples[95] + ); +} diff --git a/vendor/gpui-base/src/dock/layout/mod.rs b/vendor/gpui-base/src/dock/layout/mod.rs index d0cd3de7..a2bbc8e9 100644 --- a/vendor/gpui-base/src/dock/layout/mod.rs +++ b/vendor/gpui-base/src/dock/layout/mod.rs @@ -1,3 +1,5 @@ +// Nocterm: document the canonical layout invariant. + mod builder; mod edit; mod node; @@ -9,8 +11,7 @@ pub use edit::{EditResult, InsertTarget}; // `NodeKind` stays crate-private: `dock_area` reads through it to resolve slot // sizes before a dump, but nothing outside this crate may build a node without -// going through `PaneTree`, which is what guarantees normalization always -// runs. +// going through `PaneTree`, which maintains the normalized shape. pub(crate) use node::NodeKind; pub use node::{NodeId, PaneNode, PaneRef, PanelId}; pub use tree::{PaneTree, RootKind}; diff --git a/vendor/gpui-base/src/dock/layout/node.rs b/vendor/gpui-base/src/dock/layout/node.rs index d04d4352..6f071ecc 100644 --- a/vendor/gpui-base/src/dock/layout/node.rs +++ b/vendor/gpui-base/src/dock/layout/node.rs @@ -1,3 +1,5 @@ +// Nocterm: document the canonical layout invariant. + use gpui::{Axis, EntityId, Pixels}; /// Stable container identity. Survives structural edits and normalization so @@ -36,8 +38,8 @@ impl From for PanelId { } } -/// The shape of one container. Private: every mutation goes through -/// [`PaneTree`] so normalization always runs. +/// The shape of one container. Private: edits go through [`PaneTree`], +/// which maintains the normalized shape. /// /// [`PaneTree`]: super::PaneTree #[derive(Clone, PartialEq, Debug)] diff --git a/vendor/gpui-base/src/dock/layout/tree.rs b/vendor/gpui-base/src/dock/layout/tree.rs index ad743995..b912c8d1 100644 --- a/vendor/gpui-base/src/dock/layout/tree.rs +++ b/vendor/gpui-base/src/dock/layout/tree.rs @@ -1,3 +1,5 @@ +// Nocterm: short-circuit panel lookup in reverse layout order. + use std::sync::atomic::{AtomicU64, Ordering}; use smallvec::SmallVec; @@ -38,10 +40,10 @@ fn next_node_id() -> NodeId { /// no entity handle lives in here, so a tree can be built, edited, compared /// and serialized with no `App` in sight. /// -/// Every edit method normalizes before returning and reports what it did as -/// an [`EditResult`](super::EditResult), so there is no window in which a -/// caller can observe a tree with an empty container, a one-child split, or an -/// out-of-range active index. +/// Every edit preserves normalization and reports what it did as an +/// [`EditResult`](super::EditResult), so a caller cannot observe an empty +/// nested container, a nested one-child split, or an out-of-range active +/// index. #[derive(Clone, PartialEq, Debug)] pub struct PaneTree { root: PaneNode, @@ -99,19 +101,18 @@ impl PaneTree { self.path_of_node(id).map(|path| self.node_at(&path)) } - /// The tab node holding `panel`. + /// The last tab node in layout order holding `panel`. pub fn find_panel_node(&self, panel: PanelId) -> Option { - let mut found = None; - self.root.walk(&mut |node| { - let holds = match node.kind() { - PaneRef::Tabs { panels, .. } => panels.contains(&panel), - PaneRef::Split { .. } => false, - }; - if holds { - found = Some(node.id()); + fn find(node: &PaneNode, panel: PanelId) -> Option { + match node.kind_ref() { + NodeKind::Tabs { panels, .. } => panels.contains(&panel).then_some(node.id()), + NodeKind::Split { children, .. } => { + children.iter().rev().find_map(|child| find(child, panel)) + } } - }); - found + } + + find(&self.root, panel) } pub(crate) fn path_of_node(&self, id: NodeId) -> Option { @@ -300,4 +301,18 @@ mod tests { assert!(tree.find_node(tabs).is_some()); assert_eq!(tree.find_panel_node(panel_id(1)), Some(tabs)); } + + #[test] + fn panel_lookup_prefers_the_last_group_holding_that_panel() { + let mut tree = PaneTree::new(RootKind::Split); + let repeated = panel_id(1); + let first = tree.push_tabs_for_test(tree.root().id(), vec![repeated]); + let second = tree.push_tabs_for_test(tree.root().id(), vec![repeated]); + tree.normalize(); + + assert_eq!(tree.find_panel_node(repeated), Some(second)); + assert_eq!(tree.find_panel_node(panel_id(2)), None); + tree.remove_panel(repeated); + assert_eq!(tree.find_panel_node(repeated), Some(first)); + } } diff --git a/vendor/gpui-base/src/dock/tab_group.rs b/vendor/gpui-base/src/dock/tab_group.rs index 899349c1..444befeb 100644 --- a/vendor/gpui-base/src/dock/tab_group.rs +++ b/vendor/gpui-base/src/dock/tab_group.rs @@ -2,17 +2,23 @@ //! A tab group's behavior, with no appearance of its own. use crate::TestSupportExt as _; -use std::{rc::Rc, sync::Arc}; +use std::{ + collections::{HashMap, HashSet}, + rc::Rc, + sync::Arc, +}; use gpui::{ - AnyElement, AnyView, App, Bounds, Context, Div, DragMoveEvent, Empty, EventEmitter, - FocusHandle, Focusable, InteractiveElement as _, IntoElement, ParentElement as _, Pixels, - Render, Stateful, Styled as _, Subscription, WeakEntity, Window, div, - prelude::FluentBuilder as _, px, + App, Bounds, Context, DragMoveEvent, EntityId, EventEmitter, FocusHandle, Focusable, + InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Render, Styled as _, + Subscription, WeakEntity, Window, prelude::FluentBuilder as _, px, }; use crate::Placement; +pub(crate) use rendering::BareTabGroup; +pub use rendering::{TabGroupContext, TabGroupRenderer}; + use super::{ active::ActiveTracker, drag::{ @@ -153,7 +159,7 @@ pub struct TabGroup { /// Handed to the callbacks in [`TabGroupContext`], which are built from a /// plain `&App` and so cannot ask for it. this: WeakEntity, - panels: Vec>, + panels: Rc<[Arc]>, active_ix: usize, zoomed: bool, zoom_revision: u64, @@ -164,7 +170,7 @@ pub struct TabGroup { renderer: Rc, /// Nocterm: the area draws the group as a cached view, and the tab bar draws /// every panel's title, so any panel's change draws the group again. - _panel_changes: Vec, + panel_observations: HashMap, } impl TabGroup { @@ -175,7 +181,7 @@ impl TabGroup { Self { node, this: cx.weak_entity(), - panels: Vec::new(), + panels: Rc::default(), active_ix: 0, zoomed: false, zoom_revision: 0, @@ -185,7 +191,7 @@ impl TabGroup { active: ActiveTracker::default(), drop_indicator: None, renderer: Rc::new(BareTabGroup), - _panel_changes: Vec::new(), + panel_observations: HashMap::new(), } } @@ -281,53 +287,7 @@ impl TabGroup { /// A snapshot of everything a skin needs to draw this group. pub fn context(&self, cx: &App) -> TabGroupContext { - let group = self.this.clone(); - - TabGroupContext { - node: self.node, - panels: self.panels.clone(), - active_panel: self.active_panel(cx), - active_ix: self.active_ix, - zoomed: self.zoomed, - constraints: self.constraints, - active_panel_closable: self.is_closable(cx), - draggable: self.draggable(cx), - panel_close_allowed: self.closable_panels(cx), - droppable: self.droppable(), - // A stale indicator would otherwise outlive a drag that was - // cancelled while hovering this group. - drop_indicator: cx - .has_active_drag() - .then_some(self.drop_indicator) - .flatten(), - on_select_tab: { - let group = group.clone(); - Rc::new(move |ix, window, cx| { - _ = group.update(cx, |group, cx| group.select_tab(ix, window, cx)); - }) - }, - on_close: { - let group = group.clone(); - Rc::new(move |panel, _, cx| { - _ = group.update(cx, |group, cx| group.close_panel(panel, cx)); - }) - }, - on_toggle_zoom: { - let group = group.clone(); - Rc::new(move |window, cx| { - _ = group.update(cx, |group, cx| group.toggle_zoom(window, cx)); - }) - }, - on_drop_panel: { - let group = group.clone(); - Rc::new(move |drag, ix, activate, _, cx| { - _ = group.update(cx, |group, cx| group.on_drop(&drag, ix, activate, cx)); - }) - }, - on_drop_item: Rc::new(move |item, placement, _, cx| { - _ = group.update(cx, |group, cx| group.emit_drag_drop(&item, placement, cx)); - }), - } + TabGroupContext::from_group(self, cx) } } @@ -344,29 +304,55 @@ impl TabGroup { active_ix: usize, window: &mut Window, cx: &mut Context, + ) { + let same_panels = panels.len() == self.panels.len() + && panels + .iter() + .zip(self.panels.iter()) + .all(|(next, held)| Arc::ptr_eq(next, held)); + if !same_panels { + self.replace_panels(panels, window, cx); + } + self.active_ix = active_ix.min(self.panels.len().saturating_sub(1)); + self.schedule_active_sync(window, cx); + cx.notify(); + } + + fn replace_panels( + &mut self, + panels: Vec>, + window: &mut Window, + cx: &mut Context, ) { let group = cx.weak_entity(); - let existing: Vec = self.panels.iter().map(|panel| panel.panel_id(cx)).collect(); - for panel in panels.iter() { + let existing: HashSet = + self.panels.iter().map(|panel| panel.panel_id(cx)).collect(); + for panel in &panels { if !existing.contains(&panel.panel_id(cx)) { panel.on_added_to(group.clone(), window, cx); } } - self.panels = panels; - self._panel_changes = self - .panels - .iter() - .map(|panel| { - let group = group.clone(); - panel.view().observe(cx, move |cx| { - _ = group.update(cx, |_, cx| cx.notify()); + self.panels = panels.into(); + // A membership edit can leave most of the views in place. Move + // their observations into a map sized for the new membership; any + // remaining old subscriptions detach when this update returns. + let mut previous = std::mem::take(&mut self.panel_observations); + let mut observations = HashMap::with_capacity(self.panels.len()); + for panel in self.panels.iter() { + let view = panel.view(); + let id = view.entity_id(); + observations.entry(id).or_insert_with(|| { + previous.remove(&id).unwrap_or_else(|| { + let group = group.clone(); + view.observe(cx, move |cx| { + _ = group.update(cx, |_, cx| cx.notify()); + }) }) - }) - .collect(); - self.active_ix = active_ix.min(self.panels.len().saturating_sub(1)); - self.schedule_active_sync(window, cx); - cx.notify(); + }); + } + self.panel_observations = observations; + self.active.membership_changed(); } /// Replace everything the container knows about this group's place in the @@ -644,8 +630,8 @@ impl Render for TabGroup { let context = self.context(cx); let renderer = self.renderer.clone(); let focus_handle = self.focus_handle(cx); - let droppable = context.droppable; - let indicator = context.drop_indicator; + let droppable = context.is_droppable(); + let indicator = context.drop_indicator(); renderer .frame(&context, window, cx) @@ -699,7 +685,7 @@ impl Render for TabGroup { this.emit_drag_drop(item, placement, cx); })) }) - .map(|this| match context.active_panel.as_ref() { + .map(|this| match context.active_panel() { Some(panel) => this.child(renderer.render_active_panel( panel.view(), &context, @@ -715,1065 +701,10 @@ impl Render for TabGroup { } } -type SelectTabHandler = Rc; -type ClosePanelHandler = Rc; -type ToggleZoomHandler = Rc; -type DropPanelHandler = Rc, bool, &mut Window, &mut App)>; -type DropItemHandler = Rc, &mut Window, &mut App)>; - -/// What a skin needs to draw a tab group, and the callbacks it invokes rather -/// than reimplementing behavior. -#[derive(Clone)] -pub struct TabGroupContext { - node: NodeId, - panels: Vec>, - active_panel: Option>, - active_ix: usize, - zoomed: bool, - constraints: TabGroupConstraints, - draggable: bool, - panel_close_allowed: bool, - droppable: bool, - active_panel_closable: bool, - drop_indicator: Option, - on_select_tab: SelectTabHandler, - on_close: ClosePanelHandler, - on_toggle_zoom: ToggleZoomHandler, - on_drop_panel: DropPanelHandler, - on_drop_item: DropItemHandler, -} - -impl TabGroupContext { - /// The `Tabs` node this group mirrors, for a skin that needs to name the - /// group in a drag payload or a drop target. - pub fn node(&self) -> NodeId { - self.node - } - - /// Every panel in the group, in tab order — visible or not. A skin filters - /// with [`PanelView::visible`] when it draws. - pub fn panels(&self) -> &[Arc] { - &self.panels - } - - pub fn active_ix(&self) -> usize { - self.active_ix - } - - /// The panel on screen, which is the displayed tab unless that panel has - /// gone invisible. - pub fn active_panel(&self) -> Option<&Arc> { - self.active_panel.as_ref() - } - - pub fn drop_indicator(&self) -> Option { - self.drop_indicator - } - - pub fn is_zoomed(&self) -> bool { - self.zoomed - } - - pub fn is_collapsed(&self) -> bool { - self.constraints.is_collapsed() - } - - /// Whether the active panel can be closed. - pub fn is_closable(&self) -> bool { - self.active_panel_closable - } - - /// Whether `panel` can be closed from this group. Uses the same constraints - /// as [`TabGroup::close_panel`], including the panel's own `closable` flag. - pub fn is_panel_closable(&self, panel: PanelId, cx: &App) -> bool { - self.constraints.is_closable() - && self.panel_close_allowed - && self - .panels - .iter() - .any(|candidate| candidate.panel_id(cx) == panel && candidate.closable(cx)) - } - - pub fn is_locked(&self) -> bool { - self.constraints.is_locked() - } - - pub fn is_draggable(&self) -> bool { - self.draggable - } - - pub fn is_droppable(&self) -> bool { - self.droppable - } - - pub fn select_tab(&self, ix: usize, window: &mut Window, cx: &mut App) { - (self.on_select_tab)(ix, window, cx); - } - - pub fn close(&self, panel: PanelId, window: &mut Window, cx: &mut App) { - (self.on_close)(panel, window, cx); - } - - pub fn toggle_zoom(&self, window: &mut Window, cx: &mut App) { - (self.on_toggle_zoom)(window, cx); - } - - /// The drag payload for the tab at `ix`, for a skin wiring `on_drag` onto - /// its tabs. `None` when `ix` names no panel. - pub fn drag_panel(&self, ix: usize, cx: &App) -> Option { - self.panels - .get(ix) - .map(|panel| DragPanel::new(panel.panel_id(cx), self.node)) - } - - /// A panel dropped on the tab bar. `ix` names the slot it lands in, or - /// `None` to append; `activate` decides whether it becomes displayed. - pub fn drop_panel( - &self, - drag: DragPanel, - ix: Option, - activate: bool, - window: &mut Window, - cx: &mut App, - ) { - (self.on_drop_panel)(drag, ix, activate, window, cx); - } - - /// A host-owned drag dropped on the tab bar. `placement` is `None` to - /// merge into this group rather than split beside it. - pub fn drop_item( - &self, - item: AnyDrag, - placement: Option, - window: &mut Window, - cx: &mut App, - ) { - (self.on_drop_item)(item, placement, window, cx); - } -} - -/// Appearance for a tab group. Base draws none of it. -/// -/// The two frame hooks return the element itself rather than wrapping one, -/// because base attaches focus, keyboard grouping, and drop handling to the -/// very elements the skin styles: a wrapper would put the hit area and the -/// painted area on different elements. -#[allow(unused_variables)] -pub trait TabGroupRenderer: 'static { - /// The group's outer frame, which base tracks focus on. - /// - /// Identified rather than plain, so a skin can add a role, a tooltip, or - /// scroll tracking; `Stateful
` does everything base needs from it. - /// Appearance only. The group is laid out as a column that fills its slot - /// around whatever this returns, because a group that does not is a strip - /// of tabs with no content under it. - /// A renderer that needs the painted group bounds can attach `on_prepaint` - /// here and identify the group with [`TabGroupContext::node`]. - fn frame(&self, group: &TabGroupContext, window: &mut Window, cx: &mut App) -> Stateful
{ - div().id("tab-group") - } - - /// The region below the tab bar, which base installs drop handling on. - fn content_frame( - &self, - group: &TabGroupContext, - window: &mut Window, - cx: &mut App, - ) -> Stateful
{ - div().id("tab-group-content") - } - - fn render_tab_bar( - &self, - group: &TabGroupContext, - window: &mut Window, - cx: &mut App, - ) -> AnyElement; - - /// How the displayed panel's view is placed in the content region. The - /// skin receives the view rather than an element so it can decide how the - /// view is cached and stretched. - fn render_active_panel( - &self, - panel: AnyView, - group: &TabGroupContext, - window: &mut Window, - cx: &mut App, - ) -> AnyElement { - panel.into_any_element() - } - - fn render_drop_indicator( - &self, - indicator: DropIndicator, - window: &mut Window, - cx: &mut App, - ) -> Option { - None - } - - fn render_empty( - &self, - group: &TabGroupContext, - window: &mut Window, - cx: &mut App, - ) -> Option { - None - } -} - -/// The renderer a group starts with: the displayed panel and nothing else. -pub(crate) struct BareTabGroup; - -impl TabGroupRenderer for BareTabGroup { - fn render_tab_bar(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> AnyElement { - Empty.into_any_element() - } -} +mod rendering; #[cfg(test)] -mod tests { - use std::cell::RefCell; - - use gpui::{ - AppContext as _, Entity, Modifiers, MouseButton, StatefulInteractiveElement as _, - TestAppContext, VisualTestContext, point, px, size, - }; - - use super::*; - use crate::dock::test_support::{ - PanelSignal, build_group, drain, drain_active, log_of, panel_id, - }; - - /// The node `build_group` gives its group. - fn group_node() -> NodeId { - NodeId::from_u64(1) - } - - fn elsewhere() -> NodeId { - NodeId::from_u64(7) - } - - fn content_bounds() -> Bounds { - Bounds { - origin: point(px(0.), px(0.)), - size: size(px(400.), px(300.)), - } - } - - /// Collect the group's outgoing intents as readable strings, so an - /// assertion reads as the sentence the event means. - fn record_events( - group: &Entity, - cx: &mut VisualTestContext, - ) -> Rc>> { - let events: Rc>> = Rc::default(); - let sink = events.clone(); - cx.update(|_, cx| { - cx.subscribe(group, move |_, event: &TabGroupEvent, _| { - sink.borrow_mut().push(describe(event)); - }) - .detach(); - }); - events - } - - fn describe(event: &TabGroupEvent) -> String { - match event { - TabGroupEvent::Drop { - panel, - source, - target, - } => match target { - InsertTarget::Tabs { node, ix, activate } => format!( - "drop panel {} from {} into tabs {} at {:?} activate={}", - panel.as_u64(), - source.as_u64(), - node.as_u64(), - ix, - activate - ), - InsertTarget::Split { - node, placement, .. - } => format!( - "drop panel {} from {} split {} {}", - panel.as_u64(), - source.as_u64(), - node.as_u64(), - placement - ), - }, - TabGroupEvent::DragDrop { target, .. } => format!( - "item onto {} at {:?}", - target.node().as_u64(), - target.placement() - ), - TabGroupEvent::ClosePanel { panel } => format!("close {}", panel.as_u64()), - TabGroupEvent::ActiveChanged { ix } => format!("active {ix}"), - TabGroupEvent::ZoomIn { .. } => "zoom in".into(), - TabGroupEvent::ZoomOut { .. } => "zoom out".into(), - } - } - - #[gpui::test] - fn a_group_announces_its_first_panel_active(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a"], cx); - cx.run_until_parked(); - - assert_eq!(drain_active(&log), vec![("a", true)]); - let _ = (group, panels); - } - - #[gpui::test] - fn selecting_another_tab_deactivates_then_activates(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); - cx.run_until_parked(); - drain_active(&log); - - cx.update(|window, cx| { - group.update(cx, |group, cx| group.select_tab(1, window, cx)); - }); - cx.run_until_parked(); - - assert_eq!(drain_active(&log), vec![("a", false), ("b", true)]); - } - - #[gpui::test] - fn the_context_snapshots_the_group_state(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); - - let seen = cx.update(|_, cx| { - group.update(cx, |group, cx| { - let context = group.context(cx); - ( - context.panels().len(), - context.active_ix(), - context.is_zoomed(), - ) - }) - }); - - assert_eq!(seen, (2, 0, false)); - } - - /// A panel hidden while it holds the displayed slot is still the panel - /// told it is active; only what gets drawn falls back to a visible one. - #[gpui::test] - fn a_hidden_displayed_panel_is_still_the_active_one(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a", "b"], cx); - cx.update(|_, cx| { - panels[0].update(cx, |panel, cx| panel.set_visible(false, cx)); - }); - cx.run_until_parked(); - - assert_eq!(drain_active(&log), vec![("a", true)]); - assert_eq!( - cx.update(|_, cx| group.read(cx).active_panel(cx).unwrap().panel_name(cx)), - "b", - "rendering falls back to the first visible panel" - ); - } - - /// `on_removed` is a departing panel's deactivation signal, so the group - /// must not also announce `false` to it. - #[gpui::test] - fn a_panel_dropped_from_the_group_is_never_told_it_went_inactive(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a", "b"], cx); - cx.run_until_parked(); - drain(&log); - - cx.update(|window, cx| { - let remaining: Vec> = vec![Arc::new(panels[1].clone())]; - group.update(cx, |group, cx| { - group.sync_from_tree(remaining, 0, window, cx) - }); - }); - cx.run_until_parked(); - - assert_eq!(drain_active(&log), vec![("b", true)]); - } - - #[gpui::test] - fn selecting_a_tab_that_is_not_there_changes_nothing(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); - cx.run_until_parked(); - drain_active(&log); - let events = record_events(&group, cx); - - cx.update(|window, cx| { - group.update(cx, |group, cx| group.select_tab(5, window, cx)); - }); - cx.run_until_parked(); - - assert_eq!(cx.update(|_, cx| group.read(cx).active_ix()), 0); - assert!(events.borrow().is_empty()); - assert!(drain_active(&log).is_empty()); - } - - #[gpui::test] - fn a_locked_group_can_be_neither_dragged_nor_dropped_into(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(false), window, cx) - }) - }); - let unlocked = cx.update(|_, cx| { - let context = group.read(cx).context(cx); - (context.is_draggable(), context.is_droppable()) - }); - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints( - TabGroupConstraints::in_split(false).dock_locked(true), - window, - cx, - ) - }) - }); - let locked = cx.update(|_, cx| { - let context = group.read(cx).context(cx); - (context.is_draggable(), context.is_droppable()) - }); - - assert_eq!(unlocked, (true, true)); - assert_eq!(locked, (false, false)); - } - - /// Zoom retains the same native reorder and drop affordances. - #[gpui::test] - fn a_zoomed_group_keeps_tab_drag_and_drop(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(false), window, cx); - group.set_zoomed(true, window, cx); - }) - }); - - assert!(cx.update(|_, cx| group.read(cx).context(cx).is_droppable())); - assert!(cx.update(|_, cx| group.read(cx).context(cx).is_draggable())); - assert!(!cx.update(|_, cx| group.read(cx).context(cx).is_locked())); - } - - /// Dragging the last visible panel out of the only group would leave the - /// dock empty and undroppable, so it is refused. - #[gpui::test] - fn the_only_groups_last_visible_panel_cannot_be_dragged_out(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(true), window, cx) - }) - }); - let alone = cx.update(|_, cx| group.read(cx).context(cx).is_draggable()); - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(false), window, cx) - }) - }); - let beside_others = cx.update(|_, cx| group.read(cx).context(cx).is_draggable()); - - assert!(!alone); - assert!(beside_others); - } - - #[gpui::test] - fn a_panel_from_another_group_lands_as_one_move(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - let events = record_events(&group, cx); - - let drag = DragPanel::new(PanelId::from_u64(99), elsewhere()); - cx.update(|_, cx| { - group.update(cx, |group, cx| group.on_drop(&drag, None, true, cx)); - }); - cx.run_until_parked(); - - assert_eq!( - *events.borrow(), - vec!["drop panel 99 from 7 into tabs 1 at None activate=true"] - ); - } - - #[gpui::test] - fn dropping_a_panel_back_onto_its_own_group_is_ignored(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a", "b"], cx); - let events = record_events(&group, cx); - - let panel = panel_id(&panels[0], cx); - let drag = DragPanel::new(panel, group_node()); - cx.update(|_, cx| { - group.update(cx, |group, cx| group.on_drop(&drag, None, true, cx)); - }); - cx.run_until_parked(); - - assert!(events.borrow().is_empty()); - } - - #[gpui::test] - fn a_hovering_split_turns_a_drop_into_a_split(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - let events = record_events(&group, cx); - - let drag = DragPanel::new(PanelId::from_u64(99), elsewhere()); - cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.sync_drop_placeholder( - content_bounds(), - Some(Placement::Right), - drag.drag_session_id(), - DropPlaceholderBounds::for_placement(content_bounds(), None), - cx, - ); - group.on_drop(&drag, None, true, cx); - }); - }); - cx.run_until_parked(); - - assert_eq!(*events.borrow(), vec!["drop panel 99 from 7 split 1 Right"]); - } - - /// The tab bar reports the slot a drop landed on, and a slot always means - /// "into these tabs" however the content area had resolved the cursor. - #[gpui::test] - fn a_tab_slot_overrides_the_hovering_split(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - let events = record_events(&group, cx); - - let drag = DragPanel::new(PanelId::from_u64(99), elsewhere()); - cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.sync_drop_placeholder( - content_bounds(), - Some(Placement::Right), - drag.drag_session_id(), - DropPlaceholderBounds::for_placement(content_bounds(), None), - cx, - ); - group.on_drop(&drag, Some(0), true, cx); - }); - }); - cx.run_until_parked(); - - assert_eq!( - *events.borrow(), - vec!["drop panel 99 from 7 into tabs 1 at Some(0) activate=true"] - ); - } - - /// A lone panel splitting out of its own group would empty that group and - /// refill it, which is no move at all. - #[gpui::test] - fn a_lone_panel_cannot_split_out_of_its_own_group(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a"], cx); - let events = record_events(&group, cx); - - let drag = DragPanel::new(panel_id(&panels[0], cx), group_node()); - cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.sync_drop_placeholder( - content_bounds(), - Some(Placement::Right), - drag.drag_session_id(), - DropPlaceholderBounds::for_placement(content_bounds(), None), - cx, - ); - group.on_drop(&drag, None, true, cx); - }); - }); - cx.run_until_parked(); - - assert!(events.borrow().is_empty()); - } - - #[gpui::test] - fn the_placeholder_replays_only_when_the_target_moves(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - let bounds = content_bounds(); - let source = DropPlaceholderBounds::new(point(px(10.), px(10.)), size(px(96.), px(30.))); - - let sync = |placement: Option, cx: &mut VisualTestContext| { - cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.sync_drop_placeholder(bounds, placement, 42, source, cx); - group.drop_indicator.unwrap() - }) - }) - }; - - let first = sync(Some(Placement::Left), cx); - let again = sync(Some(Placement::Left), cx); - let moved = sync(Some(Placement::Right), cx); - - assert_eq!(first.epoch(), 0); - assert_eq!(first.from(), source, "the first run flies in from the drag"); - assert_eq!(again.epoch(), 0, "an unchanged target keeps animating"); - assert_eq!(again.from(), source); - assert_eq!(moved.epoch(), 1, "a moved target replays from where it was"); - assert_eq!(moved.from(), first.to()); - assert_eq!( - moved.to(), - DropPlaceholderBounds::for_placement(bounds, Some(Placement::Right)) - ); - } - - /// The indicator is hit state, not a latch: a drag cancelled while - /// hovering must not leave the placeholder painted. - #[gpui::test] - fn the_indicator_is_withheld_when_no_drag_is_in_flight(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - - let (stored, published) = cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.sync_drop_placeholder( - content_bounds(), - Some(Placement::Top), - 42, - DropPlaceholderBounds::for_placement(content_bounds(), None), - cx, - ); - ( - group.drop_indicator.is_some(), - group.context(cx).drop_indicator().is_some(), - ) - }) - }); - - assert!(stored); - assert!(!published); - } - - #[gpui::test] - fn a_host_drag_reports_the_group_and_the_edge_it_resolved(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - let events = record_events(&group, cx); - - cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.emit_drag_drop(&AnyDrag::new(7u32), Some(Placement::Bottom), cx) - }); - }); - cx.run_until_parked(); - - assert_eq!(*events.borrow(), vec!["item onto 1 at Some(Bottom)"]); - } - - #[gpui::test] - fn closing_asks_the_container_rather_than_editing_the_group(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a", "b"], cx); - let events = record_events(&group, cx); - let panel = panel_id(&panels[1], cx); - - cx.update(|_, cx| { - group.update(cx, |group, cx| { - group.close_panel(panel, cx); - // A panel that is not a member is not this group's to close. - group.close_panel(PanelId::from_u64(4242), cx); - }); - }); - cx.run_until_parked(); - - assert_eq!(*events.borrow(), vec![format!("close {}", panel.as_u64())]); - assert_eq!( - cx.update(|_, cx| group.read(cx).panels().len()), - 2, - "the group still holds both panels until the container edits the tree" - ); - } - - #[gpui::test] - fn zooming_toggles_and_tells_the_displayed_panel(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - let events = record_events(&group, cx); - - cx.update(|window, cx| group.update(cx, |group, cx| group.toggle_zoom(window, cx))); - cx.run_until_parked(); - cx.update(|window, cx| group.update(cx, |group, cx| group.toggle_zoom(window, cx))); - cx.run_until_parked(); - - assert_eq!(*events.borrow(), vec!["zoom in", "zoom out"]); - assert!(!cx.update(|_, cx| group.read(cx).is_zoomed())); - assert_eq!( - drain(&log) - .into_iter() - .filter(|(_, signal)| matches!(signal, PanelSignal::Zoomed(_))) - .collect::>(), - vec![ - ("a", PanelSignal::Zoomed(true)), - ("a", PanelSignal::Zoomed(false)) - ], - "the old TabPanel sent this to itself, where the default no-op swallowed it" - ); - } - - /// A real drag over a locked group must resolve nothing: base installs no - /// drop handling on one, so the placement is never computed and the layout - /// tree is never asked to move anything. - #[gpui::test] - fn a_drag_over_a_locked_group_resolves_nothing(cx: &mut TestAppContext) { - let (group, _calls, cx) = build_skinned_group(&["a", "b"], cx); - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints( - TabGroupConstraints::in_split(false).dock_locked(true), - window, - cx, - ) - }) - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - - drag_from_the_tab_into_the_content(cx); - - assert!( - cx.update(|_, cx| group.read(cx).drop_indicator.is_none()), - "a locked group installs no drag-move listener, so nothing resolved" - ); - } - - /// `Dock::new` marks a dock's last group unclosable so the dock cannot be - /// emptied out from under itself. - #[gpui::test] - fn a_group_the_container_sealed_shut_refuses_to_close(cx: &mut TestAppContext) { - let log = log_of(); - let (group, panels, cx) = build_group(&log, &["a", "b"], cx); - let events = record_events(&group, cx); - let panel = panel_id(&panels[0], cx); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints( - TabGroupConstraints::in_split(false).closable(false), - window, - cx, - ); - group.close_panel(panel, cx); - }) - }); - cx.run_until_parked(); - - assert!(!cx.update(|_, cx| group.read(cx).context(cx).is_closable())); - assert!(events.borrow().is_empty()); - } - - /// The last visible panel of the only group has nowhere to go, so it is - /// not closable either — closing it would empty the region out from under - /// itself. Placing a sibling beside the group makes the same panel - /// closable again, which is what pins the reason to `alone` rather than to - /// something else the sealed default also forbids. - #[gpui::test] - fn the_only_groups_last_panel_is_not_closable(cx: &mut TestAppContext) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a"], cx); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(true), window, cx) - }) - }); - let alone = cx.update(|_, cx| group.read(cx).context(cx).is_closable()); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(false), window, cx) - }) - }); - let beside_a_sibling = cx.update(|_, cx| group.read(cx).context(cx).is_closable()); - - assert!(!alone); - assert!(beside_a_sibling); - } - - /// Collapsing takes the displayed panel off screen, and the active-state - /// contract counts that as no panel being displayed. - #[gpui::test] - fn collapsing_deactivates_the_displayed_panel_and_expanding_restores_it( - cx: &mut TestAppContext, - ) { - let log = log_of(); - let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); - cx.run_until_parked(); - assert_eq!(drain_active(&log), vec![("a", true)]); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints( - TabGroupConstraints::in_split(false).collapsed(true), - window, - cx, - ) - }) - }); - cx.run_until_parked(); - assert_eq!(drain_active(&log), vec![("a", false)]); - - cx.update(|window, cx| { - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(false), window, cx) - }) - }); - cx.run_until_parked(); - assert_eq!(drain_active(&log), vec![("a", true)]); - } - - // ---- the renderer seam ---- - - /// Where `RecordingRenderer` puts its content frame. Deliberately not the - /// window's own origin or size, so a listener on the outer frame would - /// report different bounds. - fn skin_content() -> Bounds { - Bounds { - origin: point(px(100.), px(50.)), - size: size(px(400.), px(300.)), - } - } - - /// A skin that records which hooks base calls, and lays its two frames out - /// at known coordinates so a test can tell them apart by hit geometry. - struct RecordingRenderer { - calls: Rc>>, - } - - impl RecordingRenderer { - fn saw(&self, call: &'static str) { - self.calls.borrow_mut().push(call); - } - } - - impl TabGroupRenderer for RecordingRenderer { - fn frame(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> Stateful
{ - self.saw("frame"); - div().id("skin-frame").relative().size_full() - } - - fn content_frame(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> Stateful
{ - self.saw("content_frame"); - div() - .id("skin-content") - .absolute() - .left(skin_content().origin.x) - .top(skin_content().origin.y) - .w(skin_content().size.width) - .h(skin_content().size.height) - } - - fn render_tab_bar( - &self, - group: &TabGroupContext, - _: &mut Window, - cx: &mut App, - ) -> AnyElement { - self.saw("tab_bar"); - div() - .id("skin-tab") - .absolute() - .left(px(0.)) - .top(px(0.)) - .w(px(80.)) - .h(px(24.)) - .when_some(group.drag_panel(0, cx), |this, drag| { - this.on_drag(drag, |drag, offset, _, cx| { - drag.set_drag_offset(offset); - cx.new(|_| drag.clone()) - }) - }) - .into_any_element() - } - - fn render_active_panel( - &self, - panel: AnyView, - _: &TabGroupContext, - _: &mut Window, - _: &mut App, - ) -> AnyElement { - self.saw("active_panel"); - panel.into_any_element() - } - - fn render_empty( - &self, - _: &TabGroupContext, - _: &mut Window, - _: &mut App, - ) -> Option { - self.saw("empty"); - None - } - - fn render_drop_indicator( - &self, - _: DropIndicator, - _: &mut Window, - _: &mut App, - ) -> Option { - self.saw("drop_indicator"); - None - } - } - - fn build_skinned_group<'a>( - names: &[&'static str], - cx: &'a mut TestAppContext, - ) -> ( - Entity, - Rc>>, - &'a mut VisualTestContext, - ) { - let calls: Rc>> = Rc::default(); - let renderer = Rc::new(RecordingRenderer { - calls: calls.clone(), - }); - let (group, cx) = cx.add_window_view(|window, cx| { - TabGroup::new(NodeId::from_u64(1), window, cx).with_renderer(renderer) - }); - - let names = names.to_vec(); - let log = log_of(); - cx.update(|window, cx| { - let views: Vec> = names - .iter() - .map(|name| { - Arc::new(crate::dock::test_support::TestPanel::logging( - name, &log, cx, - )) as _ - }) - .collect(); - group.update(cx, |group, cx| { - group.set_constraints(TabGroupConstraints::in_split(false), window, cx); - group.sync_from_tree(views, 0, window, cx); - }); - }); - cx.run_until_parked(); - calls.borrow_mut().clear(); - - (group, calls, cx) - } - - /// Press on the skin's tab, start the drag, and move into the right-hand - /// third of `skin_content()`. - fn drag_from_the_tab_into_the_content(cx: &mut VisualTestContext) { - cx.simulate_mouse_down( - point(px(20.), px(10.)), - MouseButton::Left, - Modifiers::none(), - ); - cx.simulate_mouse_move( - point(px(30.), px(14.)), - MouseButton::Left, - Modifiers::none(), - ); - cx.simulate_mouse_move( - point(px(450.), px(200.)), - MouseButton::Left, - Modifiers::none(), - ); - } - - /// The composition contract every later renderer copies: which hooks base - /// calls, and in what order. - #[gpui::test] - fn the_renderer_composes_frame_then_tab_bar_then_content(cx: &mut TestAppContext) { - let (_group, calls, cx) = build_skinned_group(&["a"], cx); - - cx.update(|window, cx| window.draw(cx).clear(cx)); - - assert_eq!( - *calls.borrow(), - vec!["frame", "tab_bar", "content_frame", "active_panel"], - "the tab bar is a sibling of the content, not a child of it" - ); - } - - /// With nothing to display base asks for the empty element instead of the - /// active panel, and never for both. - #[gpui::test] - fn an_empty_group_asks_the_renderer_for_its_empty_state(cx: &mut TestAppContext) { - let (_group, calls, cx) = build_skinned_group(&[], cx); - - cx.update(|window, cx| window.draw(cx).clear(cx)); - - assert_eq!( - *calls.borrow(), - vec!["frame", "tab_bar", "content_frame", "empty"] - ); - } - - /// The drop listeners must sit on the content frame, not the outer frame: - /// a drag over the group resolves against the content frame's own bounds, - /// which the skin — not base — decides. - #[gpui::test] - fn the_content_frame_is_what_a_drag_is_measured_against(cx: &mut TestAppContext) { - let (group, calls, cx) = build_skinned_group(&["a", "b"], cx); - cx.update(|window, cx| window.draw(cx).clear(cx)); - - drag_from_the_tab_into_the_content(cx); - - let indicator = cx - .update(|_, cx| group.read(cx).drop_indicator) - .expect("the content frame's drag-move listener ran"); - - assert_eq!( - indicator.bounds(), - skin_content(), - "measured against the content frame, not the full-size outer frame" - ); - assert_eq!(indicator.placement(), Some(Placement::Right)); - - cx.update(|window, cx| window.draw(cx).clear(cx)); - assert!( - calls.borrow().contains(&"drop_indicator"), - "a published indicator is handed to the renderer to draw" - ); - } - - /// A drop landing on the content frame reports a move the container can - /// apply, and clears the hover state behind it. - #[gpui::test] - fn dropping_on_the_content_frame_reports_the_move(cx: &mut TestAppContext) { - let (group, _calls, cx) = build_skinned_group(&["a", "b"], cx); - let events = record_events(&group, cx); - cx.update(|window, cx| window.draw(cx).clear(cx)); - - drag_from_the_tab_into_the_content(cx); - cx.simulate_mouse_up( - point(px(450.), px(200.)), - MouseButton::Left, - Modifiers::none(), - ); - cx.run_until_parked(); - - assert_eq!(events.borrow().len(), 1, "got {:?}", events.borrow()); - assert!( - events.borrow()[0].ends_with("split 1 Right"), - "got {:?}", - events.borrow() - ); - assert!(cx.update(|_, cx| group.read(cx).drop_indicator.is_none())); - } -} +mod tests; mod zoom; diff --git a/vendor/gpui-base/src/dock/tab_group/constraints.rs b/vendor/gpui-base/src/dock/tab_group/constraints.rs index d73ec35b..90bd41c6 100644 --- a/vendor/gpui-base/src/dock/tab_group/constraints.rs +++ b/vendor/gpui-base/src/dock/tab_group/constraints.rs @@ -17,7 +17,7 @@ impl TabGroup { /// be rearranged around. Only visible panels count, so a hidden panel does /// not keep the last visible one draggable and leave the dock empty. pub(super) fn is_last_panel(&self, cx: &App) -> bool { - self.constraints.is_alone() && self.visible_panels(cx).count() <= 1 + self.constraints.is_alone() && self.visible_panels(cx).nth(1).is_none() } pub(super) fn draggable(&self, cx: &App) -> bool { diff --git a/vendor/gpui-base/src/dock/tab_group/rendering.rs b/vendor/gpui-base/src/dock/tab_group/rendering.rs new file mode 100644 index 00000000..112b2c27 --- /dev/null +++ b/vendor/gpui-base/src/dock/tab_group/rendering.rs @@ -0,0 +1,280 @@ +// Moved by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +//! Tab-group appearance contract and its render-time snapshot. +use std::{rc::Rc, sync::Arc}; + +use gpui::{ + AnyElement, AnyView, App, Div, Empty, InteractiveElement as _, IntoElement, Stateful, Window, + div, +}; + +use super::{ + AnyDrag, DragPanel, DropIndicator, NodeId, PanelId, PanelView, Placement, TabGroup, + TabGroupConstraints, +}; + +type SelectTabHandler = Rc; +type ClosePanelHandler = Rc; +type ToggleZoomHandler = Rc; +type DropPanelHandler = Rc, bool, &mut Window, &mut App)>; +type DropItemHandler = Rc, &mut Window, &mut App)>; + +/// What a skin needs to draw a tab group, and the callbacks it invokes rather +/// than reimplementing behavior. +#[derive(Clone)] +pub struct TabGroupContext { + node: NodeId, + panels: Rc<[Arc]>, + active_panel: Option>, + active_ix: usize, + zoomed: bool, + constraints: TabGroupConstraints, + draggable: bool, + panel_close_allowed: bool, + droppable: bool, + active_panel_closable: bool, + drop_indicator: Option, + on_select_tab: SelectTabHandler, + on_close: ClosePanelHandler, + on_toggle_zoom: ToggleZoomHandler, + on_drop_panel: DropPanelHandler, + on_drop_item: DropItemHandler, +} + +impl TabGroupContext { + pub(super) fn from_group(source: &TabGroup, cx: &App) -> Self { + let group = source.this.clone(); + + Self { + node: source.node, + panels: source.panels.clone(), + active_panel: source.active_panel(cx), + active_ix: source.active_ix, + zoomed: source.zoomed, + constraints: source.constraints, + active_panel_closable: source.is_closable(cx), + draggable: source.draggable(cx), + panel_close_allowed: source.closable_panels(cx), + droppable: source.droppable(), + // A stale indicator would otherwise outlive a drag that was + // cancelled while hovering this group. + drop_indicator: cx + .has_active_drag() + .then_some(source.drop_indicator) + .flatten(), + on_select_tab: { + let group = group.clone(); + Rc::new(move |ix, window, cx| { + _ = group.update(cx, |group, cx| group.select_tab(ix, window, cx)); + }) + }, + on_close: { + let group = group.clone(); + Rc::new(move |panel, _, cx| { + _ = group.update(cx, |group, cx| group.close_panel(panel, cx)); + }) + }, + on_toggle_zoom: { + let group = group.clone(); + Rc::new(move |window, cx| { + _ = group.update(cx, |group, cx| group.toggle_zoom(window, cx)); + }) + }, + on_drop_panel: { + let group = group.clone(); + Rc::new(move |drag, ix, activate, _, cx| { + _ = group.update(cx, |group, cx| group.on_drop(&drag, ix, activate, cx)); + }) + }, + on_drop_item: Rc::new(move |item, placement, _, cx| { + _ = group.update(cx, |group, cx| group.emit_drag_drop(&item, placement, cx)); + }), + } + } + + /// The `Tabs` node this group mirrors, for a skin that needs to name the + /// group in a drag payload or a drop target. + pub fn node(&self) -> NodeId { + self.node + } + + /// Every panel in the group, in tab order — visible or not. A skin filters + /// with [`PanelView::visible`] when it draws. + pub fn panels(&self) -> &[Arc] { + &self.panels + } + + pub fn active_ix(&self) -> usize { + self.active_ix + } + + /// The panel on screen, which is the displayed tab unless that panel has + /// gone invisible. + pub fn active_panel(&self) -> Option<&Arc> { + self.active_panel.as_ref() + } + + pub fn drop_indicator(&self) -> Option { + self.drop_indicator + } + + pub fn is_zoomed(&self) -> bool { + self.zoomed + } + + pub fn is_collapsed(&self) -> bool { + self.constraints.is_collapsed() + } + + /// Whether the active panel can be closed. + pub fn is_closable(&self) -> bool { + self.active_panel_closable + } + + /// Whether `panel` can be closed from this group. Uses the same constraints + /// as [`TabGroup::close_panel`], including the panel's own `closable` flag. + pub fn is_panel_closable(&self, panel: PanelId, cx: &App) -> bool { + self.constraints.is_closable() + && self.panel_close_allowed + && self + .panels + .iter() + .any(|candidate| candidate.panel_id(cx) == panel && candidate.closable(cx)) + } + + pub fn is_locked(&self) -> bool { + self.constraints.is_locked() + } + + pub fn is_draggable(&self) -> bool { + self.draggable + } + + pub fn is_droppable(&self) -> bool { + self.droppable + } + + pub fn select_tab(&self, ix: usize, window: &mut Window, cx: &mut App) { + (self.on_select_tab)(ix, window, cx); + } + + pub fn close(&self, panel: PanelId, window: &mut Window, cx: &mut App) { + (self.on_close)(panel, window, cx); + } + + pub fn toggle_zoom(&self, window: &mut Window, cx: &mut App) { + (self.on_toggle_zoom)(window, cx); + } + + /// The drag payload for the tab at `ix`, for a skin wiring `on_drag` onto + /// its tabs. `None` when `ix` names no panel. + pub fn drag_panel(&self, ix: usize, cx: &App) -> Option { + self.panels + .get(ix) + .map(|panel| DragPanel::new(panel.panel_id(cx), self.node)) + } + + /// A panel dropped on the tab bar. `ix` names the slot it lands in, or + /// `None` to append; `activate` decides whether it becomes displayed. + pub fn drop_panel( + &self, + drag: DragPanel, + ix: Option, + activate: bool, + window: &mut Window, + cx: &mut App, + ) { + (self.on_drop_panel)(drag, ix, activate, window, cx); + } + + /// A host-owned drag dropped on the tab bar. `placement` is `None` to + /// merge into this group rather than split beside it. + pub fn drop_item( + &self, + item: AnyDrag, + placement: Option, + window: &mut Window, + cx: &mut App, + ) { + (self.on_drop_item)(item, placement, window, cx); + } +} + +/// Appearance for a tab group. Base draws none of it. +/// +/// The two frame hooks return the element itself rather than wrapping one, +/// because base attaches focus, keyboard grouping, and drop handling to the +/// very elements the skin styles: a wrapper would put the hit area and the +/// painted area on different elements. +#[allow(unused_variables)] +pub trait TabGroupRenderer: 'static { + /// The group's outer frame, which base tracks focus on. + /// + /// Identified rather than plain, so a skin can add a role, a tooltip, or + /// scroll tracking; `Stateful
` does everything base needs from it. + /// Appearance only. The group is laid out as a column that fills its slot + /// around whatever this returns, because a group that does not is a strip + /// of tabs with no content under it. + /// A renderer that needs the painted group bounds can attach `on_prepaint` + /// here and identify the group with [`TabGroupContext::node`]. + fn frame(&self, group: &TabGroupContext, window: &mut Window, cx: &mut App) -> Stateful
{ + div().id("tab-group") + } + + /// The region below the tab bar, which base installs drop handling on. + fn content_frame( + &self, + group: &TabGroupContext, + window: &mut Window, + cx: &mut App, + ) -> Stateful
{ + div().id("tab-group-content") + } + + fn render_tab_bar( + &self, + group: &TabGroupContext, + window: &mut Window, + cx: &mut App, + ) -> AnyElement; + + /// How the displayed panel's view is placed in the content region. The + /// skin receives the view rather than an element so it can decide how the + /// view is cached and stretched. + fn render_active_panel( + &self, + panel: AnyView, + group: &TabGroupContext, + window: &mut Window, + cx: &mut App, + ) -> AnyElement { + panel.into_any_element() + } + + fn render_drop_indicator( + &self, + indicator: DropIndicator, + window: &mut Window, + cx: &mut App, + ) -> Option { + None + } + + fn render_empty( + &self, + group: &TabGroupContext, + window: &mut Window, + cx: &mut App, + ) -> Option { + None + } +} + +/// The renderer a group starts with: the displayed panel and nothing else. +pub(crate) struct BareTabGroup; + +impl TabGroupRenderer for BareTabGroup { + fn render_tab_bar(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> AnyElement { + Empty.into_any_element() + } +} diff --git a/vendor/gpui-base/src/dock/tab_group/tests.rs b/vendor/gpui-base/src/dock/tab_group/tests.rs new file mode 100644 index 00000000..c7951718 --- /dev/null +++ b/vendor/gpui-base/src/dock/tab_group/tests.rs @@ -0,0 +1,615 @@ +// Moved by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use std::cell::RefCell; + +use gpui::{Entity, TestAppContext, VisualTestContext, point, size}; + +use super::*; +use crate::dock::test_support::{PanelSignal, build_group, drain, drain_active, log_of, panel_id}; + +/// The node `build_group` gives its group. +fn group_node() -> NodeId { + NodeId::from_u64(1) +} + +fn elsewhere() -> NodeId { + NodeId::from_u64(7) +} + +fn content_bounds() -> Bounds { + Bounds { + origin: point(px(0.), px(0.)), + size: size(px(400.), px(300.)), + } +} + +/// Collect the group's outgoing intents as readable strings, so an +/// assertion reads as the sentence the event means. +fn record_events(group: &Entity, cx: &mut VisualTestContext) -> Rc>> { + let events: Rc>> = Rc::default(); + let sink = events.clone(); + cx.update(|_, cx| { + cx.subscribe(group, move |_, event: &TabGroupEvent, _| { + sink.borrow_mut().push(describe(event)); + }) + .detach(); + }); + events +} + +fn describe(event: &TabGroupEvent) -> String { + match event { + TabGroupEvent::Drop { + panel, + source, + target, + } => match target { + InsertTarget::Tabs { node, ix, activate } => format!( + "drop panel {} from {} into tabs {} at {:?} activate={}", + panel.as_u64(), + source.as_u64(), + node.as_u64(), + ix, + activate + ), + InsertTarget::Split { + node, placement, .. + } => format!( + "drop panel {} from {} split {} {}", + panel.as_u64(), + source.as_u64(), + node.as_u64(), + placement + ), + }, + TabGroupEvent::DragDrop { target, .. } => format!( + "item onto {} at {:?}", + target.node().as_u64(), + target.placement() + ), + TabGroupEvent::ClosePanel { panel } => format!("close {}", panel.as_u64()), + TabGroupEvent::ActiveChanged { ix } => format!("active {ix}"), + TabGroupEvent::ZoomIn { .. } => "zoom in".into(), + TabGroupEvent::ZoomOut { .. } => "zoom out".into(), + } +} + +#[gpui::test] +fn a_group_announces_its_first_panel_active(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a"], cx); + cx.run_until_parked(); + + assert_eq!(drain_active(&log), vec![("a", true)]); + let _ = (group, panels); +} + +#[gpui::test] +fn selecting_another_tab_deactivates_then_activates(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); + cx.run_until_parked(); + drain_active(&log); + + cx.update(|window, cx| { + group.update(cx, |group, cx| group.select_tab(1, window, cx)); + }); + cx.run_until_parked(); + + assert_eq!(drain_active(&log), vec![("a", false), ("b", true)]); +} + +#[gpui::test] +fn the_context_snapshots_the_group_state(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); + + let seen = cx.update(|_, cx| { + group.update(cx, |group, cx| { + let context = group.context(cx); + ( + context.panels().len(), + context.active_ix(), + context.is_zoomed(), + ) + }) + }); + + assert_eq!(seen, (2, 0, false)); +} + +/// A panel hidden while it holds the displayed slot is still the panel +/// told it is active; only what gets drawn falls back to a visible one. +#[gpui::test] +fn a_hidden_displayed_panel_is_still_the_active_one(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a", "b"], cx); + cx.update(|_, cx| { + panels[0].update(cx, |panel, cx| panel.set_visible(false, cx)); + }); + cx.run_until_parked(); + + assert_eq!(drain_active(&log), vec![("a", true)]); + assert_eq!( + cx.update(|_, cx| group.read(cx).active_panel(cx).unwrap().panel_name(cx)), + "b", + "rendering falls back to the first visible panel" + ); +} + +/// `on_removed` is a departing panel's deactivation signal, so the group +/// must not also announce `false` to it. +#[gpui::test] +fn a_panel_dropped_from_the_group_is_never_told_it_went_inactive(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a", "b"], cx); + cx.run_until_parked(); + drain(&log); + + cx.update(|window, cx| { + let remaining: Vec> = vec![Arc::new(panels[1].clone())]; + group.update(cx, |group, cx| { + group.sync_from_tree(remaining, 0, window, cx) + }); + }); + cx.run_until_parked(); + + assert_eq!(drain_active(&log), vec![("b", true)]); +} + +#[gpui::test] +fn selecting_a_tab_that_is_not_there_changes_nothing(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); + cx.run_until_parked(); + drain_active(&log); + let events = record_events(&group, cx); + + cx.update(|window, cx| { + group.update(cx, |group, cx| group.select_tab(5, window, cx)); + }); + cx.run_until_parked(); + + assert_eq!(cx.update(|_, cx| group.read(cx).active_ix()), 0); + assert!(events.borrow().is_empty()); + assert!(drain_active(&log).is_empty()); +} + +#[gpui::test] +fn a_locked_group_can_be_neither_dragged_nor_dropped_into(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(false), window, cx) + }) + }); + let unlocked = cx.update(|_, cx| { + let context = group.read(cx).context(cx); + (context.is_draggable(), context.is_droppable()) + }); + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints( + TabGroupConstraints::in_split(false).dock_locked(true), + window, + cx, + ) + }) + }); + let locked = cx.update(|_, cx| { + let context = group.read(cx).context(cx); + (context.is_draggable(), context.is_droppable()) + }); + + assert_eq!(unlocked, (true, true)); + assert_eq!(locked, (false, false)); +} + +/// Zoom retains the same native reorder and drop affordances. +#[gpui::test] +fn a_zoomed_group_keeps_tab_drag_and_drop(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(false), window, cx); + group.set_zoomed(true, window, cx); + }) + }); + + assert!(cx.update(|_, cx| group.read(cx).context(cx).is_droppable())); + assert!(cx.update(|_, cx| group.read(cx).context(cx).is_draggable())); + assert!(!cx.update(|_, cx| group.read(cx).context(cx).is_locked())); +} + +/// Dragging the last visible panel out of the only group would leave the +/// dock empty and undroppable, so it is refused. +#[gpui::test] +fn the_only_groups_last_visible_panel_cannot_be_dragged_out(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(true), window, cx) + }) + }); + let alone = cx.update(|_, cx| group.read(cx).context(cx).is_draggable()); + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(false), window, cx) + }) + }); + let beside_others = cx.update(|_, cx| group.read(cx).context(cx).is_draggable()); + + assert!(!alone); + assert!(beside_others); +} + +#[gpui::test] +fn a_panel_from_another_group_lands_as_one_move(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + let events = record_events(&group, cx); + + let drag = DragPanel::new(PanelId::from_u64(99), elsewhere()); + cx.update(|_, cx| { + group.update(cx, |group, cx| group.on_drop(&drag, None, true, cx)); + }); + cx.run_until_parked(); + + assert_eq!( + *events.borrow(), + vec!["drop panel 99 from 7 into tabs 1 at None activate=true"] + ); +} + +#[gpui::test] +fn dropping_a_panel_back_onto_its_own_group_is_ignored(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a", "b"], cx); + let events = record_events(&group, cx); + + let panel = panel_id(&panels[0], cx); + let drag = DragPanel::new(panel, group_node()); + cx.update(|_, cx| { + group.update(cx, |group, cx| group.on_drop(&drag, None, true, cx)); + }); + cx.run_until_parked(); + + assert!(events.borrow().is_empty()); +} + +#[gpui::test] +fn a_hovering_split_turns_a_drop_into_a_split(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + let events = record_events(&group, cx); + + let drag = DragPanel::new(PanelId::from_u64(99), elsewhere()); + cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.sync_drop_placeholder( + content_bounds(), + Some(Placement::Right), + drag.drag_session_id(), + DropPlaceholderBounds::for_placement(content_bounds(), None), + cx, + ); + group.on_drop(&drag, None, true, cx); + }); + }); + cx.run_until_parked(); + + assert_eq!(*events.borrow(), vec!["drop panel 99 from 7 split 1 Right"]); +} + +/// The tab bar reports the slot a drop landed on, and a slot always means +/// "into these tabs" however the content area had resolved the cursor. +#[gpui::test] +fn a_tab_slot_overrides_the_hovering_split(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + let events = record_events(&group, cx); + + let drag = DragPanel::new(PanelId::from_u64(99), elsewhere()); + cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.sync_drop_placeholder( + content_bounds(), + Some(Placement::Right), + drag.drag_session_id(), + DropPlaceholderBounds::for_placement(content_bounds(), None), + cx, + ); + group.on_drop(&drag, Some(0), true, cx); + }); + }); + cx.run_until_parked(); + + assert_eq!( + *events.borrow(), + vec!["drop panel 99 from 7 into tabs 1 at Some(0) activate=true"] + ); +} + +/// A lone panel splitting out of its own group would empty that group and +/// refill it, which is no move at all. +#[gpui::test] +fn a_lone_panel_cannot_split_out_of_its_own_group(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a"], cx); + let events = record_events(&group, cx); + + let drag = DragPanel::new(panel_id(&panels[0], cx), group_node()); + cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.sync_drop_placeholder( + content_bounds(), + Some(Placement::Right), + drag.drag_session_id(), + DropPlaceholderBounds::for_placement(content_bounds(), None), + cx, + ); + group.on_drop(&drag, None, true, cx); + }); + }); + cx.run_until_parked(); + + assert!(events.borrow().is_empty()); +} + +#[gpui::test] +fn the_placeholder_replays_only_when_the_target_moves(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + let bounds = content_bounds(); + let source = DropPlaceholderBounds::new(point(px(10.), px(10.)), size(px(96.), px(30.))); + + let sync = |placement: Option, cx: &mut VisualTestContext| { + cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.sync_drop_placeholder(bounds, placement, 42, source, cx); + group.drop_indicator.unwrap() + }) + }) + }; + + let first = sync(Some(Placement::Left), cx); + let again = sync(Some(Placement::Left), cx); + let moved = sync(Some(Placement::Right), cx); + + assert_eq!(first.epoch(), 0); + assert_eq!(first.from(), source, "the first run flies in from the drag"); + assert_eq!(again.epoch(), 0, "an unchanged target keeps animating"); + assert_eq!(again.from(), source); + assert_eq!(moved.epoch(), 1, "a moved target replays from where it was"); + assert_eq!(moved.from(), first.to()); + assert_eq!( + moved.to(), + DropPlaceholderBounds::for_placement(bounds, Some(Placement::Right)) + ); +} + +/// The indicator is hit state, not a latch: a drag cancelled while +/// hovering must not leave the placeholder painted. +#[gpui::test] +fn the_indicator_is_withheld_when_no_drag_is_in_flight(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + + let (stored, published) = cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.sync_drop_placeholder( + content_bounds(), + Some(Placement::Top), + 42, + DropPlaceholderBounds::for_placement(content_bounds(), None), + cx, + ); + ( + group.drop_indicator.is_some(), + group.context(cx).drop_indicator().is_some(), + ) + }) + }); + + assert!(stored); + assert!(!published); +} + +#[gpui::test] +fn a_host_drag_reports_the_group_and_the_edge_it_resolved(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + let events = record_events(&group, cx); + + cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.emit_drag_drop(&AnyDrag::new(7u32), Some(Placement::Bottom), cx) + }); + }); + cx.run_until_parked(); + + assert_eq!(*events.borrow(), vec!["item onto 1 at Some(Bottom)"]); +} + +#[gpui::test] +fn closing_asks_the_container_rather_than_editing_the_group(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a", "b"], cx); + let events = record_events(&group, cx); + let panel = panel_id(&panels[1], cx); + + cx.update(|_, cx| { + group.update(cx, |group, cx| { + group.close_panel(panel, cx); + // A panel that is not a member is not this group's to close. + group.close_panel(PanelId::from_u64(4242), cx); + }); + }); + cx.run_until_parked(); + + assert_eq!(*events.borrow(), vec![format!("close {}", panel.as_u64())]); + assert_eq!( + cx.update(|_, cx| group.read(cx).panels().len()), + 2, + "the group still holds both panels until the container edits the tree" + ); +} + +#[gpui::test] +fn zooming_toggles_and_tells_the_displayed_panel(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + let events = record_events(&group, cx); + + cx.update(|window, cx| group.update(cx, |group, cx| group.toggle_zoom(window, cx))); + cx.run_until_parked(); + cx.update(|window, cx| group.update(cx, |group, cx| group.toggle_zoom(window, cx))); + cx.run_until_parked(); + + assert_eq!(*events.borrow(), vec!["zoom in", "zoom out"]); + assert!(!cx.update(|_, cx| group.read(cx).is_zoomed())); + assert_eq!( + drain(&log) + .into_iter() + .filter(|(_, signal)| matches!(signal, PanelSignal::Zoomed(_))) + .collect::>(), + vec![ + ("a", PanelSignal::Zoomed(true)), + ("a", PanelSignal::Zoomed(false)) + ], + "the old TabPanel sent this to itself, where the default no-op swallowed it" + ); +} + +/// `Dock::new` marks a dock's last group unclosable so the dock cannot be +/// emptied out from under itself. +#[gpui::test] +fn a_group_the_container_sealed_shut_refuses_to_close(cx: &mut TestAppContext) { + let log = log_of(); + let (group, panels, cx) = build_group(&log, &["a", "b"], cx); + let events = record_events(&group, cx); + let panel = panel_id(&panels[0], cx); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints( + TabGroupConstraints::in_split(false).closable(false), + window, + cx, + ); + group.close_panel(panel, cx); + }) + }); + cx.run_until_parked(); + + assert!(!cx.update(|_, cx| group.read(cx).context(cx).is_closable())); + assert!(events.borrow().is_empty()); +} + +/// The last visible panel of the only group has nowhere to go, so it is +/// not closable either — closing it would empty the region out from under +/// itself. Placing a sibling beside the group makes the same panel +/// closable again, which is what pins the reason to `alone` rather than to +/// something else the sealed default also forbids. +#[gpui::test] +fn the_only_groups_last_panel_is_not_closable(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a"], cx); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(true), window, cx) + }) + }); + let alone = cx.update(|_, cx| group.read(cx).context(cx).is_closable()); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(false), window, cx) + }) + }); + let beside_a_sibling = cx.update(|_, cx| group.read(cx).context(cx).is_closable()); + + assert!(!alone); + assert!(beside_a_sibling); +} + +/// Collapsing takes the displayed panel off screen, and the active-state +/// contract counts that as no panel being displayed. +#[gpui::test] +fn collapsing_deactivates_the_displayed_panel_and_expanding_restores_it(cx: &mut TestAppContext) { + let log = log_of(); + let (group, _panels, cx) = build_group(&log, &["a", "b"], cx); + cx.run_until_parked(); + assert_eq!(drain_active(&log), vec![("a", true)]); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints( + TabGroupConstraints::in_split(false).collapsed(true), + window, + cx, + ) + }) + }); + cx.run_until_parked(); + assert_eq!(drain_active(&log), vec![("a", false)]); + + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(false), window, cx) + }) + }); + cx.run_until_parked(); + assert_eq!(drain_active(&log), vec![("a", true)]); +} + +mod rendering; +mod selection; + +#[gpui::test] +fn dock_membership_changes_keep_only_live_panel_observations(cx: &mut TestAppContext) { + use crate::dock::{DockArea, DockPlacement, test_support::TestPanel}; + use std::cell::Cell; + + let (area, cx) = + cx.add_window_view(|window, cx| DockArea::new("observed-dock", None, window, cx)); + let (survivor, removed, notifications, _observation) = cx.update(|window, cx| { + let survivor = TestPanel::new("survivor", cx); + let removed = TestPanel::new("removed", cx); + area.update(cx, |area, cx| { + for panel in [&survivor, &removed] { + area.add_panel(panel.clone(), DockPlacement::Center, None, window, cx); + } + }); + // The panel received the group handle through Panel::on_added_to. + let group = survivor + .read(cx) + .group + .as_ref() + .and_then(WeakEntity::upgrade) + .unwrap(); + let notifications = Rc::new(Cell::new(0)); + let observed = notifications.clone(); + let observation = cx.observe(&group, move |_, _| observed.set(observed.get() + 1)); + (survivor, removed, notifications, observation) + }); + + cx.update(|window, cx| { + area.update(cx, |area, cx| { + area.remove_panel(removed.clone(), window, cx) + }); + }); + cx.run_until_parked(); + notifications.set(0); + cx.update(|_, cx| removed.update(cx, |_, cx| cx.notify())); + assert_eq!(notifications.get(), 0); + cx.update(|_, cx| survivor.update(cx, |_, cx| cx.notify())); + assert_eq!(notifications.get(), 1); +} diff --git a/vendor/gpui-base/src/dock/tab_group/tests/rendering.rs b/vendor/gpui-base/src/dock/tab_group/tests/rendering.rs new file mode 100644 index 00000000..310151cd --- /dev/null +++ b/vendor/gpui-base/src/dock/tab_group/tests/rendering.rs @@ -0,0 +1,259 @@ +// Moved by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use super::super::*; +use super::record_events; +use crate::dock::test_support::log_of; +use gpui::{ + AnyElement, AnyView, AppContext as _, Div, Entity, Modifiers, MouseButton, Stateful, + StatefulInteractiveElement as _, TestAppContext, VisualTestContext, div, point, size, +}; +use std::cell::RefCell; + +/// Where `RecordingRenderer` puts its content frame. Deliberately not the +/// window's own origin or size, so a listener on the outer frame would +/// report different bounds. +fn skin_content() -> Bounds { + Bounds { + origin: point(px(100.), px(50.)), + size: size(px(400.), px(300.)), + } +} + +/// A skin that records which hooks base calls, and lays its two frames out +/// at known coordinates so a test can tell them apart by hit geometry. +struct RecordingRenderer { + calls: Rc>>, +} + +impl RecordingRenderer { + fn saw(&self, call: &'static str) { + self.calls.borrow_mut().push(call); + } +} + +impl TabGroupRenderer for RecordingRenderer { + fn frame(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> Stateful
{ + self.saw("frame"); + div().id("skin-frame").relative().size_full() + } + + fn content_frame(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> Stateful
{ + self.saw("content_frame"); + div() + .id("skin-content") + .absolute() + .left(skin_content().origin.x) + .top(skin_content().origin.y) + .w(skin_content().size.width) + .h(skin_content().size.height) + } + + fn render_tab_bar(&self, group: &TabGroupContext, _: &mut Window, cx: &mut App) -> AnyElement { + self.saw("tab_bar"); + div() + .id("skin-tab") + .absolute() + .left(px(0.)) + .top(px(0.)) + .w(px(80.)) + .h(px(24.)) + .when_some(group.drag_panel(0, cx), |this, drag| { + this.on_drag(drag, |drag, offset, _, cx| { + drag.set_drag_offset(offset); + cx.new(|_| drag.clone()) + }) + }) + .into_any_element() + } + + fn render_active_panel( + &self, + panel: AnyView, + _: &TabGroupContext, + _: &mut Window, + _: &mut App, + ) -> AnyElement { + self.saw("active_panel"); + panel.into_any_element() + } + + fn render_empty(&self, _: &TabGroupContext, _: &mut Window, _: &mut App) -> Option { + self.saw("empty"); + None + } + + fn render_drop_indicator( + &self, + _: DropIndicator, + _: &mut Window, + _: &mut App, + ) -> Option { + self.saw("drop_indicator"); + None + } +} + +fn build_skinned_group<'a>( + names: &[&'static str], + cx: &'a mut TestAppContext, +) -> ( + Entity, + Rc>>, + &'a mut VisualTestContext, +) { + let calls: Rc>> = Rc::default(); + let renderer = Rc::new(RecordingRenderer { + calls: calls.clone(), + }); + let (group, cx) = cx.add_window_view(|window, cx| { + TabGroup::new(NodeId::from_u64(1), window, cx).with_renderer(renderer) + }); + + let names = names.to_vec(); + let log = log_of(); + cx.update(|window, cx| { + let views: Vec> = names + .iter() + .map(|name| { + Arc::new(crate::dock::test_support::TestPanel::logging( + name, &log, cx, + )) as _ + }) + .collect(); + group.update(cx, |group, cx| { + group.set_constraints(TabGroupConstraints::in_split(false), window, cx); + group.sync_from_tree(views, 0, window, cx); + }); + }); + cx.run_until_parked(); + calls.borrow_mut().clear(); + + (group, calls, cx) +} + +/// Press on the skin's tab, start the drag, and move into the right-hand +/// third of `skin_content()`. +fn drag_from_the_tab_into_the_content(cx: &mut VisualTestContext) { + cx.simulate_mouse_down( + point(px(20.), px(10.)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_move( + point(px(30.), px(14.)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_move( + point(px(450.), px(200.)), + MouseButton::Left, + Modifiers::none(), + ); +} + +/// The composition contract every later renderer copies: which hooks base +/// calls, and in what order. +#[gpui::test] +fn the_renderer_composes_frame_then_tab_bar_then_content(cx: &mut TestAppContext) { + let (_group, calls, cx) = build_skinned_group(&["a"], cx); + + cx.update(|window, cx| window.draw(cx).clear(cx)); + + assert_eq!( + *calls.borrow(), + vec!["frame", "tab_bar", "content_frame", "active_panel"], + "the tab bar is a sibling of the content, not a child of it" + ); +} + +/// With nothing to display base asks for the empty element instead of the +/// active panel, and never for both. +#[gpui::test] +fn an_empty_group_asks_the_renderer_for_its_empty_state(cx: &mut TestAppContext) { + let (_group, calls, cx) = build_skinned_group(&[], cx); + + cx.update(|window, cx| window.draw(cx).clear(cx)); + + assert_eq!( + *calls.borrow(), + vec!["frame", "tab_bar", "content_frame", "empty"] + ); +} + +/// The drop listeners must sit on the content frame, not the outer frame: +/// a drag over the group resolves against the content frame's own bounds, +/// which the skin — not base — decides. +#[gpui::test] +fn the_content_frame_is_what_a_drag_is_measured_against(cx: &mut TestAppContext) { + let (group, calls, cx) = build_skinned_group(&["a", "b"], cx); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + drag_from_the_tab_into_the_content(cx); + + let indicator = cx + .update(|_, cx| group.read(cx).drop_indicator) + .expect("the content frame's drag-move listener ran"); + + assert_eq!( + indicator.bounds(), + skin_content(), + "measured against the content frame, not the full-size outer frame" + ); + assert_eq!(indicator.placement(), Some(Placement::Right)); + + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert!( + calls.borrow().contains(&"drop_indicator"), + "a published indicator is handed to the renderer to draw" + ); +} + +/// A drop landing on the content frame reports a move the container can +/// apply, and clears the hover state behind it. +#[gpui::test] +fn dropping_on_the_content_frame_reports_the_move(cx: &mut TestAppContext) { + let (group, _calls, cx) = build_skinned_group(&["a", "b"], cx); + let events = record_events(&group, cx); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + drag_from_the_tab_into_the_content(cx); + cx.simulate_mouse_up( + point(px(450.), px(200.)), + MouseButton::Left, + Modifiers::none(), + ); + cx.run_until_parked(); + + assert_eq!(events.borrow().len(), 1, "got {:?}", events.borrow()); + assert!( + events.borrow()[0].ends_with("split 1 Right"), + "got {:?}", + events.borrow() + ); + assert!(cx.update(|_, cx| group.read(cx).drop_indicator.is_none())); +} + +/// A real drag over a locked group must resolve nothing: base installs no +/// drop handling on one, so the placement is never computed and the layout +/// tree is never asked to move anything. +#[gpui::test] +fn a_drag_over_a_locked_group_resolves_nothing(cx: &mut TestAppContext) { + let (group, _calls, cx) = build_skinned_group(&["a", "b"], cx); + cx.update(|window, cx| { + group.update(cx, |group, cx| { + group.set_constraints( + TabGroupConstraints::in_split(false).dock_locked(true), + window, + cx, + ) + }) + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + drag_from_the_tab_into_the_content(cx); + + assert!( + cx.update(|_, cx| group.read(cx).drop_indicator.is_none()), + "a locked group installs no drag-move listener, so nothing resolved" + ); +} diff --git a/vendor/gpui-base/src/dock/tab_group/tests/selection.rs b/vendor/gpui-base/src/dock/tab_group/tests/selection.rs new file mode 100644 index 00000000..69726bb4 --- /dev/null +++ b/vendor/gpui-base/src/dock/tab_group/tests/selection.rs @@ -0,0 +1,126 @@ +// Added by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use std::{ + cell::Cell, + io::Write as _, + rc::Rc, + time::{Duration, Instant}, +}; + +use gpui::{TestAppContext, VisualTestContext}; + +use crate::dock::{ + DockArea, DockLayout, DockPlacement, PaneRef, PanelId, TabGroup, + test_support::{Log, TestPanel, drain, drain_active, log_of}, +}; + +fn open_dock<'a>( + names: impl IntoIterator, + log: &Log, + cx: &'a mut TestAppContext, +) -> ( + gpui::Entity, + Vec>, + &'a mut VisualTestContext, +) { + let (area, cx) = + cx.add_window_view(|window, cx| DockArea::new("tab-selection", None, window, cx)); + let panels = cx.update(|window, cx| { + let panels: Vec<_> = names + .into_iter() + .map(|name| TestPanel::logging(name, log, cx)) + .collect(); + let layout = panels + .iter() + .cloned() + .fold(DockLayout::tabs(), DockLayout::panel); + area.update(cx, |area, cx| area.set_center(layout, window, cx)); + panels + }); + cx.run_until_parked(); + (area, panels, cx) +} + +#[gpui::test] +fn a_panel_visibility_change_still_invalidates_its_group_after_selection(cx: &mut TestAppContext) { + let log = log_of(); + let (area, panels, cx) = open_dock(["first", "second"], &log, cx); + drain(&log); + let second = PanelId::from(panels[1].entity_id()); + let group = cx.read(|cx| { + panels[1] + .read(cx) + .group + .as_ref() + .and_then(|group| group.upgrade()) + .unwrap() + }); + cx.update(|window, cx| area.update(cx, |area, cx| area.select_panel(second, window, cx))); + cx.run_until_parked(); + assert_eq!(drain_active(&log), [("first", false), ("second", true)]); + + let invalidated = Rc::new(Cell::new(false)); + let _observation = cx.update(|_, cx| { + let invalidated = invalidated.clone(); + cx.observe(&group, move |_: gpui::Entity, _| { + invalidated.set(true) + }) + }); + cx.update(|_, cx| panels[1].update(cx, |panel, cx| panel.set_visible(false, cx))); + cx.run_until_parked(); + assert!(invalidated.get()); + assert_eq!( + cx.read(|cx| group.read(cx).active_panel(cx).unwrap().panel_name(cx)), + "first" + ); + assert!(drain_active(&log).is_empty()); +} + +#[gpui::test] +#[ignore = "release profile of native dock selection and deferred active-state delivery"] +fn measure_selecting_a_panel_in_a_large_dock(cx: &mut TestAppContext) { + let size = std::env::var("NOCTERM_PROFILE_TAB_COUNT") + .map_or(Ok(256usize), |value| value.parse()) + .unwrap(); + assert!(size > 1); + let log = log_of(); + let (area, panels, cx) = open_dock(std::iter::repeat_n("tab", size), &log, cx); + drain(&log); + let ids: Vec<_> = panels + .iter() + .map(|panel| PanelId::from(panel.entity_id())) + .collect(); + let mut selection = [Duration::ZERO; 301]; + let mut settled = [Duration::ZERO; 301]; + for (step, (selection, settled)) in selection.iter_mut().zip(&mut settled).enumerate() { + let ix = (step + 1) % size; + let started = Instant::now(); + cx.update(|window, cx| area.update(cx, |area, cx| area.select_panel(ids[ix], window, cx))); + *selection = started.elapsed(); + cx.run_until_parked(); + *settled = started.elapsed(); + assert_eq!(drain_active(&log), [("tab", false), ("tab", true)]); + } + cx.read(|cx| { + let layout = area.read(cx).layout(DockPlacement::Center).unwrap(); + let node = layout + .find_node(layout.find_panel_node(ids[0]).unwrap()) + .unwrap(); + let PaneRef::Tabs { panels, active_ix } = node.kind() else { + panic!("expected a tab group"); + }; + assert_eq!(panels, ids); + assert_eq!(active_ix, selection.len() % size); + }); + selection.sort_unstable(); + settled.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "tabs={size} selection_p50={:?} selection_p95={:?} settled_p50={:?} settled_p95={:?}", + selection[150], + selection[285], + settled[150], + settled[285], + ) + .unwrap(); +} diff --git a/vendor/gpui-base/src/frame_loop.rs b/vendor/gpui-base/src/frame_loop.rs new file mode 100644 index 00000000..4f7fcec8 --- /dev/null +++ b/vendor/gpui-base/src/frame_loop.rs @@ -0,0 +1,114 @@ +// Nocterm: drive continuous interactions from the window's frame clock. +use std::{ + cell::Cell, + rc::{Rc, Weak}, + time::Duration, +}; + +use gpui::{App, Context, WeakEntity, Window}; + +/// A cancellable next-frame loop owned by a view or gesture. +/// +/// The callback receives elapsed time and returns whether to request another +/// frame. It is responsible for invalidating only the content it changes. +#[derive(Default)] +pub struct FrameLoop(Option>>); + +impl FrameLoop { + pub fn is_active(&self) -> bool { + self.0.as_ref().is_some_and(|running| running.get()) + } + + pub fn stop(&mut self) { + self.0 = None; + } + + pub fn start( + &mut self, + window: &Window, + cx: &Context, + tick: impl Fn(&mut T, Duration, &mut Window, &mut Context) -> bool + 'static, + ) { + if self.is_active() { + return; + } + let running = Rc::new(Cell::new(true)); + let mut previous = cx.background_executor().now(); + let clock = move |cx: &App| { + let now = cx.background_executor().now(); + now.saturating_duration_since(std::mem::replace(&mut previous, now)) + }; + next( + window, + Rc::downgrade(&running), + cx.weak_entity(), + clock, + tick, + ); + self.0 = Some(running); + } +} + +fn next( + window: &Window, + active: Weak>, + entity: WeakEntity, + mut clock: impl FnMut(&App) -> Duration + 'static, + tick: impl Fn(&mut T, Duration, &mut Window, &mut Context) -> bool + 'static, +) { + window.on_next_frame(move |window, cx| { + if !active.upgrade().is_some_and(|running| running.get()) { + return; + } + let elapsed = clock(cx); + let again = entity.update(cx, |entity, cx| tick(entity, elapsed, window, cx)); + let Some(running) = active.upgrade() else { + return; + }; + if matches!(again, Ok(true)) && running.get() { + next(window, active, entity, clock, tick); + } else { + running.set(false); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use gpui::{AppContext as _, Empty, TestAppContext}; + + #[gpui::test] + fn frame_loop_tracks_elapsed_time_and_cancels_pending_callbacks(cx: &mut TestAppContext) { + let window = cx.add_window(|_, _| Empty); + let intervals = cx.update(|cx| cx.new(|_| Vec::new())); + let mut frames = FrameLoop::default(); + let start = |frames: &mut FrameLoop, cx: &mut TestAppContext| { + window + .update(cx, |_, window, cx| { + intervals.update(cx, |_, cx| { + frames.start(window, cx, |intervals, elapsed, _, _| { + intervals.push(elapsed); + true + }); + }); + }) + .unwrap(); + }; + let frame = |ms, cx: &mut TestAppContext| { + cx.executor().advance_clock(Duration::from_millis(ms)); + window + .update(cx, |_, window, cx| window.simulate_next_frame(cx)) + .unwrap(); + }; + start(&mut frames, cx); + frame(5, cx); + frame(11, cx); + frames.stop(); + start(&mut frames, cx); + frame(8, cx); + frames.stop(); + frame(20, cx); + cx.update(|cx| assert_eq!(intervals.read(cx), &[5, 11, 8].map(Duration::from_millis))); + } +} diff --git a/vendor/gpui-base/src/input/base/element.rs b/vendor/gpui-base/src/input/base/element.rs index 5c79ba96..1b6d535b 100644 --- a/vendor/gpui-base/src/input/base/element.rs +++ b/vendor/gpui-base/src/input/base/element.rs @@ -1,3 +1,4 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. use crate::input::{InputExtras as _, InputModeKind}; use gpui::Corners; use gpui::Half; @@ -22,6 +23,7 @@ use crate::{ use super::{ InputBaseState, RangeDecorationStyle, TextDecoration, + highlight_shape::{SelectionHighlight, frame_outline_points, outline_path}, layout::{LastLayout, WhitespaceIndicators}, mode::LayoutMode, }; @@ -716,15 +718,8 @@ impl TextElement { bounds: &Bounds, ) -> Option> { let corners = Self::layout_range_corners(&range, last_layout)?; - let points = frame_outline_points(&corners); let origin = bounds.origin + point(last_layout.line_number_width, px(0.)); - let mut builder = gpui::PathBuilder::fill(); - builder.move_to(origin + *points.first()?); - for point in points.iter().skip(1) { - builder.line_to(origin + *point); - } - builder.close(); - builder.build().ok() + outline_path(&corners, origin) } /// Project a buffer range through the visible (non-folded) shaped lines. @@ -921,14 +916,19 @@ impl TextElement { bounds: &mut Bounds, window: &mut Window, cx: &mut App, - ) -> Vec> { + ) -> Vec { let state = self.state.read(cx); if !state.focus_handle.is_focused(window) { return vec![]; } let active_id = state.active_selection().id; - let mut paths = Vec::new(); + let mut highlights = Vec::new(); + let origin = bounds.origin + point(last_layout.line_number_width, px(0.)); + let highlight = |range| { + let corners = Self::layout_range_corners(&range, last_layout)?; + SelectionHighlight::new(&corners, origin, window.scale_factor()) + }; for selection in state.selections.iter() { let is_active = selection.id == active_id; @@ -976,25 +976,17 @@ impl TextElement { .take_while(|s| s.range().start < range.end) { if start < span.range().start { - paths.extend(Self::layout_match_range( - start..span.range().start, - last_layout, - bounds, - )); + highlights.extend(highlight(start..span.range().start)); } start = span.range().end.max(start); } } if start < range.end { - paths.extend(Self::layout_match_range( - start..range.end, - last_layout, - bounds, - )); + highlights.extend(highlight(start..range.end)); } } - paths + highlights } /// Calculate the visible range of lines in the viewport. @@ -2194,7 +2186,7 @@ pub(super) struct PrepaintState { cursor_scroll_offset: Point, /// row index (zero based), no wrap, same line as the cursor. current_row: Option, - selection_paths: Vec>, + selection_highlights: Vec, hover_highlight_path: Option>, search_match_paths: Vec<(Path, bool)>, document_color_paths: Vec<(Path, Hsla)>, @@ -2272,40 +2264,6 @@ fn print_points_as_svg_path( } } -fn frame_outline_points(corners: &[Corners>]) -> Vec> { - let rects = corners - .iter() - .map(|corners| (corners.top_left, corners.bottom_right)) - .collect::>(); - let mut points = Vec::with_capacity(rects.len() * 4); - let first = rects[0]; - let last = rects[rects.len() - 1]; - points.push(first.0); - points.push(point(first.1.x, first.0.y)); - for pair in rects.windows(2) { - let current = pair[0]; - let next = pair[1]; - points.push(current.1); - points.push(point(next.1.x, current.1.y)); - points.push(point(next.1.x, next.1.y)); - } - if points.last() != Some(&last.1) { - points.push(last.1); - } - points.push(point(last.0.x, last.1.y)); - for pair in rects.windows(2).rev() { - let current = pair[1]; - let next = pair[0]; - points.push(point(current.0.x, current.0.y)); - points.push(point(next.0.x, current.0.y)); - points.push(point(next.0.x, next.0.y)); - } - if points.last() != points.first() { - points.push(points[0]); - } - points -} - fn pad_frame_corners( corners: &[Corners>], horizontal_padding: Pixels, @@ -2768,7 +2726,7 @@ impl Element for TextElement { .map(|info| info.bounds); let search_match_paths = self.layout_search_matches(&last_layout, &mut bounds, cx); - let selection_paths = self.layout_selections(&last_layout, &mut bounds, window, cx); + let selection_highlights = self.layout_selections(&last_layout, &mut bounds, window, cx); let hover_highlight_path = self.layout_hover_highlight(&last_layout, &mut bounds, cx); let document_color_paths = self.layout_document_colors(&document_colors, &last_layout, &bounds, cx); @@ -2862,7 +2820,7 @@ impl Element for TextElement { cursor_infos, cursor_scroll_offset, current_row, - selection_paths, + selection_highlights, search_match_paths, hover_highlight_path, hover_definition_hitbox, @@ -3020,8 +2978,8 @@ impl Element for TextElement { } } - for path in prepaint.selection_paths.drain(..) { - window.paint_path(path, editor_style.selection); + for highlight in prepaint.selection_highlights.drain(..) { + highlight.paint(editor_style.selection, window); } // Paint hover highlight diff --git a/vendor/gpui-base/src/input/base/highlight_shape.rs b/vendor/gpui-base/src/input/base/highlight_shape.rs new file mode 100644 index 00000000..a867bebf --- /dev/null +++ b/vendor/gpui-base/src/input/base/highlight_shape.rs @@ -0,0 +1,89 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use gpui::{Bounds, Corners, Hsla, Path, Pixels, Point, Window, fill, point}; + +/// The fill for a visible selection, in shaped text coordinates. +pub(super) enum SelectionHighlight { + Rect(Bounds), + Outline(Path), +} + +impl SelectionHighlight { + pub(super) fn new( + corners: &[Corners>], + origin: Point, + scale_factor: f32, + ) -> Option { + if let [one] = corners { + let left = one.top_left.x.min(one.top_right.x); + let right = one.top_left.x.max(one.top_right.x); + let rect = Bounds::from_corners( + origin + point(left, one.top_left.y), + origin + point(right, one.bottom_right.y), + ); + // GPUI snaps solid quads to device pixels. Keep partial coverage + // for a nonzero shape narrower than one device pixel. + if f32::from(rect.size.width) * scale_factor >= 1. + && f32::from(rect.size.height) * scale_factor >= 1. + { + return Some(Self::Rect(rect)); + } + } + outline_path(corners, origin).map(Self::Outline) + } + + pub(super) fn paint(self, color: Hsla, window: &mut Window) { + match self { + Self::Rect(bounds) => window.paint_quad(fill(bounds, color)), + Self::Outline(path) => window.paint_path(path, color), + } + } +} + +pub(super) fn outline_path( + corners: &[Corners>], + origin: Point, +) -> Option> { + let points = frame_outline_points(corners); + let mut builder = gpui::PathBuilder::fill(); + builder.move_to(origin + *points.first()?); + for point in points.iter().skip(1) { + builder.line_to(origin + *point); + } + builder.close(); + builder.build().ok() +} + +pub(super) fn frame_outline_points(corners: &[Corners>]) -> Vec> { + let rects = corners + .iter() + .map(|corners| (corners.top_left, corners.bottom_right)) + .collect::>(); + let mut points = Vec::with_capacity(rects.len() * 4); + let first = rects[0]; + let last = rects[rects.len() - 1]; + points.push(first.0); + points.push(point(first.1.x, first.0.y)); + for pair in rects.windows(2) { + let current = pair[0]; + let next = pair[1]; + points.push(current.1); + points.push(point(next.1.x, current.1.y)); + points.push(point(next.1.x, next.1.y)); + } + if points.last() != Some(&last.1) { + points.push(last.1); + } + points.push(point(last.0.x, last.1.y)); + for pair in rects.windows(2).rev() { + let current = pair[1]; + let next = pair[0]; + points.push(point(current.0.x, current.0.y)); + points.push(point(next.0.x, current.0.y)); + points.push(point(next.0.x, next.0.y)); + } + if points.last() != points.first() { + points.push(points[0]); + } + points +} diff --git a/vendor/gpui-base/src/input/base/state.rs b/vendor/gpui-base/src/input/base/state.rs index 4b8651ea..3e74172b 100644 --- a/vendor/gpui-base/src/input/base/state.rs +++ b/vendor/gpui-base/src/input/base/state.rs @@ -4533,7 +4533,14 @@ impl Render for InputBaseState { .on_mouse_move(window.listener_for(&entity, InputBaseState::on_mouse_move)) .on_scroll_wheel(window.listener_for(&entity, InputBaseState::on_scroll_wheel)) .when(self.is_multi_line() && !self.disabled, |this| { - this.on_modifiers_changed(cx.listener(|_, _, _, cx| cx.notify())) + let alt = window.modifiers().alt; + this.on_modifiers_changed(cx.listener( + move |_, event: &gpui::ModifiersChangedEvent, _, cx| { + if event.modifiers.alt != alt { + cx.notify(); + } + }, + )) }) .when(!self.disabled, |this| { if self.is_multi_line() && window.modifiers().alt { diff --git a/vendor/gpui-base/src/input/mod.rs b/vendor/gpui-base/src/input/mod.rs index bb2ae494..06da6480 100644 --- a/vendor/gpui-base/src/input/mod.rs +++ b/vendor/gpui-base/src/input/mod.rs @@ -1,3 +1,4 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. //! Text input: the shared editing engine and the three states built on it. //! //! Nothing here should be `pub` unless it is reachable from outside the crate. @@ -28,6 +29,8 @@ mod display_map; mod editor; #[path = "base/element.rs"] mod element; +#[path = "base/highlight_shape.rs"] +mod highlight_shape; #[path = "editor/highlighting.rs"] mod highlighting; #[path = "editor/indent.rs"] diff --git a/vendor/gpui-base/src/lib.rs b/vendor/gpui-base/src/lib.rs index 1978efc4..e878c4c7 100644 --- a/vendor/gpui-base/src/lib.rs +++ b/vendor/gpui-base/src/lib.rs @@ -4,6 +4,8 @@ //! colors, sizing, and motion belong to applications or the //! `gpui-component` façade. +// Nocterm: export a window-frame driver for continuous interactions. + mod accordion; pub mod actions; mod alert_dialog; @@ -25,6 +27,7 @@ pub mod dock; mod element_ext; mod event; mod focus_trap; +mod frame_loop; mod geometry; mod global_state; mod history; @@ -111,6 +114,7 @@ pub use event::{InteractiveElementExt, OngoingScrollExt}; pub use focus_trap::FocusTrapElement; #[doc(hidden)] pub use focus_trap::active_focus_trap; +pub use frame_loop::FrameLoop; pub use geometry::*; pub use global_state::{DeferredPopover, GlobalState}; pub use history::History; diff --git a/vendor/gpui-base/src/resizable/mod.rs b/vendor/gpui-base/src/resizable/mod.rs index b536c2d1..e9eb7986 100644 --- a/vendor/gpui-base/src/resizable/mod.rs +++ b/vendor/gpui-base/src/resizable/mod.rs @@ -1,8 +1,8 @@ +// Nocterm: redistribute split sizes in place during a resize. + use std::ops::Range; -use gpui::{ - Along, App, Axis, Bounds, Context, ElementId, EventEmitter, IsZero, Pixels, Window, px, -}; +use gpui::{Along, Axis, Bounds, Context, ElementId, EventEmitter, IsZero, Pixels, Window, px}; mod panel; mod resize_handle; @@ -263,7 +263,7 @@ impl ResizableState { panel.size_range.clone() } - fn sync_real_panel_sizes(&mut self, _: &App) { + fn sync_real_panel_sizes(&mut self) { for (i, panel) in self.panels.iter().enumerate() { self.sizes[i] = panel.bounds.size.along(self.axis); } @@ -282,68 +282,61 @@ impl ResizableState { _: &mut Window, cx: &mut Context, ) { - let old_sizes = self.sizes.clone(); - - let mut ix = ix; // Only resize the left panels. - if ix >= old_sizes.len() - 1 { + if ix >= self.sizes.len().saturating_sub(1) { return; } - let container_size = self.container_size(); - self.sync_real_panel_sizes(cx); - let move_changed = size - old_sizes[ix]; + let old_size = self.sizes[ix]; + let move_changed = size - old_size; if move_changed == px(0.) { + self.sync_real_panel_sizes(); return; } + let container_size = self.container_size(); let size_range = self.panel_size_range(ix); let new_size = size.clamp(size_range.start, size_range.end); - let is_expand = move_changed > px(0.); - let main_ix = ix; - let mut new_sizes = old_sizes.clone(); + let mut ix = ix; + self.sizes[ix] = new_size; - if is_expand { - let mut changed = new_size - old_sizes[ix]; - new_sizes[ix] = new_size; + if move_changed > px(0.) { + let mut changed = new_size - old_size; - while changed > px(0.) && ix < old_sizes.len() - 1 { + while changed > px(0.) && ix < self.sizes.len() - 1 { ix += 1; let size_range = self.panel_size_range(ix); - let available_size = (new_sizes[ix] - size_range.start).max(px(0.)); + let available_size = (self.sizes[ix] - size_range.start).max(px(0.)); let to_reduce = changed.min(available_size); - new_sizes[ix] -= to_reduce; + self.sizes[ix] -= to_reduce; changed -= to_reduce; } } else { let mut changed = new_size - size; - new_sizes[ix] = new_size; while changed > px(0.) && ix > 0 { ix -= 1; let size_range = self.panel_size_range(ix); - let available_size = (new_sizes[ix] - size_range.start).max(px(0.)); + let available_size = (self.sizes[ix] - size_range.start).max(px(0.)); let to_reduce = changed.min(available_size); changed -= to_reduce; - new_sizes[ix] -= to_reduce; + self.sizes[ix] -= to_reduce; } - new_sizes[main_ix + 1] += old_sizes[main_ix] - size - changed; + self.sizes[main_ix + 1] += old_size - size - changed; } // If total size exceeds container size, adjust the main panel - let total_size: Pixels = new_sizes.iter().map(|s| s.as_f32()).sum::().into(); + let total_size: Pixels = self.sizes.iter().map(|s| s.as_f32()).sum::().into(); if total_size > container_size { let overflow = total_size - container_size; - new_sizes[main_ix] = (new_sizes[main_ix] - overflow).max(size_range.start); + self.sizes[main_ix] = (self.sizes[main_ix] - overflow).max(size_range.start); } - for (i, _) in old_sizes.iter().enumerate() { - let size = new_sizes[i]; - self.panels[i].size = Some(size); + for (panel, &size) in self.panels.iter_mut().zip(&self.sizes) { + panel.size = Some(size); } - self.sizes = new_sizes; cx.notify(); } @@ -396,6 +389,8 @@ pub(crate) struct ResizablePanelState { #[cfg(test)] mod tests { + mod drag_work; + use std::{ cell::{Cell, RefCell}, rc::Rc, diff --git a/vendor/gpui-base/src/resizable/tests/drag_work.rs b/vendor/gpui-base/src/resizable/tests/drag_work.rs new file mode 100644 index 00000000..d1b145f2 --- /dev/null +++ b/vendor/gpui-base/src/resizable/tests/drag_work.rs @@ -0,0 +1,98 @@ +// Nocterm: characterize repeated divider input and measure split redistribution. + +use super::*; +use std::{hint::black_box, time::Instant}; + +#[gpui::test] +fn repeated_pointer_positions_and_reversal_preserve_rendered_split_sizes(cx: &mut TestAppContext) { + let (cx, state, resizes) = harness(cx); + let boundary = cx.debug_bounds("second-panel").unwrap().left(); + cx.simulate_mouse_down( + point(boundary - px(2.), px(50.)), + MouseButton::Left, + Modifiers::default(), + ); + cx.simulate_mouse_move( + point(boundary + px(10.), px(50.)), + Some(MouseButton::Left), + Modifiers::default(), + ); + for (position, expected) in [(220., 220.), (220., 220.), (130., 130.), (60., 100.)] { + cx.simulate_mouse_move( + point(px(position), px(50.)), + Some(MouseButton::Left), + Modifiers::default(), + ); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert_eq!( + cx.debug_bounds("first-panel").unwrap().size.width, + px(expected) + ); + } + cx.simulate_mouse_up( + point(px(60.), px(50.)), + MouseButton::Left, + Modifiers::default(), + ); + state.read_with(cx, |state, _| { + assert_eq!(state.sizes(), &[px(100.), px(300.)]) + }); + assert_eq!(resizes.get(), 1); +} + +struct WideSplit { + state: gpui::Entity, + panels: usize, +} + +impl Render for WideSplit { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().w(px(self.panels as f32 * 300.)).h(px(100.)).child( + h_resizable("wide-split") + .with_state(&self.state) + .children((0..self.panels).map(|_| resizable_panel().size(px(300.)))), + ) + } +} + +#[gpui::test] +#[ignore = "manual CPU measurement of a rendered split's resize operation"] +fn measure_programmatic_panel_resizing(cx: &mut TestAppContext) { + let count = std::env::var("NOCTERM_PROFILE_SPLIT_COUNT") + .map(|value| value.parse::().unwrap()) + .unwrap_or(16); + assert!(count >= 2); + let state = cx.update(|cx| cx.new(|_| ResizableState::default())); + let (_, cx) = cx.add_window_view({ + let state = state.clone(); + move |_, _| WideSplit { + state, + panels: count, + } + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let mut samples = Vec::new(); + for _ in 0..101 { + samples.push(cx.update(|window, cx| { + state.update(cx, |state, cx| { + let start = Instant::now(); + for step in 0..256 { + let width = if step % 2 == 0 { 260. } else { 320. }; + state.resize_panel(0, black_box(px(width)), window, cx); + } + start.elapsed().as_nanos() as f64 / 256. + }) + })); + } + samples.sort_unstable_by(f64::total_cmp); + state.read_with(cx, |state, _| { + assert_eq!(state.sizes().len(), count); + assert_eq!(state.sizes()[0], px(320.)); + assert_eq!(state.sizes()[1], px(280.)); + }); + eprintln!( + "panels={count} resize_p50_ns={:.2} resize_p95_ns={:.2}", + samples[50], samples[95] + ); +} diff --git a/vendor/gpui-base/src/scrollbar.rs b/vendor/gpui-base/src/scrollbar.rs index 89eee2d5..06a0dff7 100644 --- a/vendor/gpui-base/src/scrollbar.rs +++ b/vendor/gpui-base/src/scrollbar.rs @@ -1,48 +1,37 @@ // Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. -use std::{cell::Cell, ops::Deref, panic::Location, rc::Rc}; + +use std::{ + cell::{Cell, RefCell}, + ops::Deref, + panic::Location, + rc::Rc, +}; use instant::{Duration, Instant}; -use crate::{ - AxisExt, - animation::{ease_in_cubic, ease_out_cubic}, - theme::ActiveTheme as _, -}; +use crate::AxisExt; use gpui::{ - Anchor, App, Axis, Background, BorderStyle, Bounds, ContentMask, CursorStyle, Edges, Element, - ElementId, EntityId, GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId, - IntoElement, IsZero, LayoutId, ListState, MouseDownEvent, MouseMoveEvent, MouseUpEvent, - PaintQuad, Pixels, Point, Position, ScrollHandle, ScrollWheelEvent, Size, Style, - TouchDragEvent, TouchPhase, UniformListScrollHandle, Window, fill, point, - prelude::FluentBuilder, px, relative, size, + App, Axis, Bounds, ElementId, EntityId, IntoElement, ListState, Pixels, Point, ScrollHandle, + Size, UniformListScrollHandle, Window, point, px, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; +mod appearance; +mod element; +mod motion; +mod redraw; + +pub use appearance::{ScrollbarStyles, ScrollbarThumbStyle, ScrollbarTrackStyle}; +pub use motion::{ScrollbarEntrance, ScrollbarMotion}; +use motion::{VisibilityAnimation, WidthAnimation}; +use redraw::FadeRedraw; + +#[cfg(test)] +mod tests; + /// The width of the scrollbar (THUMB_ACTIVE_INSET * 2 + THUMB_ACTIVE_WIDTH) const WIDTH: Pixels = px(4. * 2. + 8.); -const MIN_THUMB_SIZE: Pixels = px(48.); - -const THUMB_WIDTH: Pixels = px(6.); -const THUMB_RADIUS: Pixels = Pixels::ZERO; -const THUMB_INSET: Pixels = px(4.); - -const THUMB_ACTIVE_WIDTH: Pixels = px(8.); -const THUMB_ACTIVE_RADIUS: Pixels = Pixels::ZERO; -const THUMB_ACTIVE_INSET: Pixels = px(4.); - -/// How long visibility is held after the last activity, when the styled layer -/// projects no [`ScrollbarMotion`] of its own. -/// -/// This is a visibility hold rather than motion: without it [`ScrollbarMode::Scrolling`] -/// could never reveal the scrollbar. -const DEFAULT_IDLE: Duration = Duration::from_secs(2); - -fn clamp_thumb_radius(radius: Pixels, bounds: Bounds) -> Pixels { - radius - .min(bounds.size.width / 2.) - .min(bounds.size.height / 2.) -} /// Scrollbar show mode. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash, Default, JsonSchema)] @@ -164,7 +153,13 @@ impl ScrollbarHandle for ListState { #[doc(hidden)] #[derive(Debug, Clone)] -struct ScrollbarState(Rc>); +struct ScrollbarState(Rc); + +#[derive(Debug)] +struct ScrollbarRuntime { + inner: Cell, + fade_redraw: RefCell, +} #[doc(hidden)] #[derive(Debug, Clone, Copy)] @@ -188,350 +183,71 @@ struct ScrollbarStateInner { impl Default for ScrollbarState { fn default() -> Self { let now = Instant::now(); - Self(Rc::new(Cell::new(ScrollbarStateInner { - hovered_axis: None, - hovered_on_thumb: None, - dragged_axis: None, - drag_pos: point(px(0.), px(0.)), - last_scroll_offset: point(px(0.), px(0.)), - last_scroll_time: None, - last_update: now, - drag_update_scheduled: false, - drag_update_generation: 0, - idle_timer_scheduled: false, - visibility: VisibilityAnimation::hidden(now), - vertical_width: WidthAnimation::new(now), - horizontal_width: WidthAnimation::new(now), - }))) - } -} - -#[derive(Debug, Clone, Copy)] -struct ScalarTransition { - from: T, - target: T, - started_at: Instant, - duration: Duration, -} - -impl ScalarTransition { - fn settled(value: T, now: Instant) -> Self { - Self { - from: value, - target: value, - started_at: now, - duration: Duration::ZERO, - } - } - - fn sample(&self, now: Instant, interpolate: impl FnOnce(T, T, f32) -> T) -> (T, bool) { - if self.from == self.target || self.duration.is_zero() { - return (self.target, false); - } - let linear = now.saturating_duration_since(self.started_at).as_secs_f32() - / self.duration.as_secs_f32(); - if linear >= 1.0 { - (self.target, false) - } else { - ( - interpolate(self.from, self.target, linear.clamp(0.0, 1.0)), - true, - ) - } - } - - fn start(&mut self, from: T, target: T, duration: Duration, now: Instant) { - self.from = from; - self.target = target; - self.started_at = now; - self.duration = duration; - } - - fn settle(&mut self, target: T, now: Instant) { - self.start(target, target, Duration::ZERO, now); - } -} - -#[derive(Debug, Clone, Copy)] -struct WidthAnimation { - transition: ScalarTransition, - initialized: bool, -} - -impl WidthAnimation { - fn new(now: Instant) -> Self { - Self { - transition: ScalarTransition::settled(Pixels::ZERO, now), - initialized: false, - } - } - - fn sample(&self, now: Instant) -> (Pixels, bool) { - self.transition.sample(now, |from, target, linear| { - from + (target - from) * ease_out_cubic(linear) - }) - } - - /// Move toward `target` over `duration`. A zero duration adopts the target - /// immediately, which is how reduced motion and a motionless theme arrive here. - fn set_target(&mut self, target: Pixels, duration: Duration, now: Instant) -> (Pixels, bool) { - if duration.is_zero() || !self.initialized { - self.transition.settle(target, now); - self.initialized = true; - } else if self.transition.target != target { - let from = self.sample(now).0; - self.transition.start(from, target, duration, now); - } - self.sample(now) - } -} - -/// How a scrollbar becomes visible. -/// -/// The styled layer chooses the choreography; Base only plays it. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum ScrollbarEntrance { - /// Fade in without moving. - #[default] - Fade, - /// Slide in from the nearest edge while fading. - SlideAndFade, -} - -/// Motion tokens used by [`Scrollbar`]. -/// -/// Base installs no motion of its own: every transition duration defaults to -/// zero, so visibility and thumb width snap. Product timing belongs to the -/// styled layer, which projects it through [`crate::ScrollbarTheme`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct ScrollbarMotion { - idle: Duration, - enter: Duration, - exit: Duration, - expand: Duration, - entrance: ScrollbarEntrance, - thumb_hover_entrance: ScrollbarEntrance, -} - -impl Default for ScrollbarMotion { - fn default() -> Self { - Self { - idle: DEFAULT_IDLE, - enter: Duration::ZERO, - exit: Duration::ZERO, - expand: Duration::ZERO, - entrance: ScrollbarEntrance::Fade, - thumb_hover_entrance: ScrollbarEntrance::Fade, - } + Self(Rc::new(ScrollbarRuntime { + inner: Cell::new(ScrollbarStateInner { + hovered_axis: None, + hovered_on_thumb: None, + dragged_axis: None, + drag_pos: point(px(0.), px(0.)), + last_scroll_offset: point(px(0.), px(0.)), + last_scroll_time: None, + last_update: now, + drag_update_scheduled: false, + drag_update_generation: 0, + idle_timer_scheduled: false, + visibility: VisibilityAnimation::hidden(now), + vertical_width: WidthAnimation::new(now), + horizontal_width: WidthAnimation::new(now), + }), + fade_redraw: RefCell::default(), + })) } } -impl ScrollbarMotion { - /// How long visibility is held after the last scroll, drag, or hover. - pub fn with_idle(mut self, idle: Duration) -> Self { - self.idle = idle; - self - } - - /// How long the scrollbar takes to become fully visible. - pub fn with_enter(mut self, enter: Duration) -> Self { - self.enter = enter; - self - } - - /// How long the scrollbar takes to fade away once the idle hold expires. - pub fn with_exit(mut self, exit: Duration) -> Self { - self.exit = exit; - self - } - - /// How long the thumb takes to reach a new width. - pub fn with_expand(mut self, expand: Duration) -> Self { - self.expand = expand; - self - } - - /// Which entrance choreography to play. - pub fn with_entrance(mut self, entrance: ScrollbarEntrance) -> Self { - self.entrance = entrance; - self - } - - /// Which entrance choreography to play when hover reveals the thumb. - pub fn with_thumb_hover_entrance(mut self, entrance: ScrollbarEntrance) -> Self { - self.thumb_hover_entrance = entrance; - self - } - - pub fn idle(&self) -> Duration { - self.idle - } - - pub fn enter(&self) -> Duration { - self.enter - } - - pub fn exit(&self) -> Duration { - self.exit - } - - pub fn expand(&self) -> Duration { - self.expand - } - - pub fn entrance(&self) -> ScrollbarEntrance { - self.entrance - } - - pub fn thumb_hover_entrance(&self) -> ScrollbarEntrance { - self.thumb_hover_entrance - } +impl Deref for ScrollbarState { + type Target = Cell; - fn entrance_for(&self, mode: ScrollbarMode, thumb_hovered: bool) -> ScrollbarEntrance { - if mode.is_hover() && thumb_hovered { - self.thumb_hover_entrance - } else { - self.entrance - } + fn deref(&self) -> &Self::Target { + &self.0.inner } } -#[derive(Debug, Clone, Copy)] -struct VisibilityAnimation { - opacity: ScalarTransition, - position: ScalarTransition, - entrance: ScrollbarEntrance, -} - -#[derive(Debug, Clone, Copy)] -struct VisibilitySample { - opacity: f32, - position: f32, - running: bool, -} - -impl VisibilityAnimation { - fn hidden(now: Instant) -> Self { - Self { - opacity: ScalarTransition::settled(0.0, now), - position: ScalarTransition::settled(0.0, now), - entrance: ScrollbarEntrance::Fade, - } - } - - fn sample(&self, now: Instant) -> VisibilitySample { - let entering = - self.opacity.target > self.opacity.from || self.position.target > self.position.from; - let (opacity, opacity_running) = self.opacity.sample(now, |from, target, linear| { - let factor = if entering { - linear - } else { - ease_in_cubic(linear) - }; - from + (target - from) * factor - }); - let (position, position_running) = self.position.sample(now, |from, target, linear| { - let factor = if entering { - ease_out_cubic(linear) - } else { - ease_in_cubic(linear) - }; - from + (target - from) * factor - }); - - VisibilitySample { - opacity, - position, - running: opacity_running || position_running, - } - } - - /// Reverse or start a transition toward `visible`. - /// - /// The leg runs for `enter` or `exit` scaled by the distance still to cover, - /// so an interrupted transition keeps its speed instead of restarting. - fn set_visible( - &mut self, +impl ScrollbarState { + fn request_visibility_redraw( + &self, + running: bool, visible: bool, - entrance: ScrollbarEntrance, - enter: Duration, - exit: Duration, + remaining: Duration, now: Instant, + window: &mut Window, + cx: &mut App, ) { - let target = if visible { 1.0 } else { 0.0 }; - let full_duration = if visible { enter } else { exit }; - if full_duration.is_zero() { - // A motionless policy — reduced motion, an always-visible scrollbar, - // or a theme that projects no motion — adopts the target outright, - // even if a transition was in flight when the policy changed. - self.opacity.settle(target, now); - self.position.settle(target, now); - self.entrance = entrance; - return; - } - if self.opacity.target == target - && self.position.target == target - && self.entrance == entrance - { - return; - } - - let sample = self.sample(now); - let from_position = if visible && entrance == ScrollbarEntrance::Fade { - 1.0 + let mut fade = self.0.fade_redraw.borrow_mut(); + if running && !visible { + if fade.schedule(now, remaining, window, cx) { + let state = Rc::downgrade(&self.0); + let view = window.current_view(); + window.on_next_frame(move |_, cx| { + let Some(state) = state.upgrade() else { + return; + }; + if state + .fade_redraw + .borrow_mut() + .frame_delivered(cx.background_executor().now()) + { + cx.notify(view); + } + }); + } } else { - sample.position - }; - let distance = (target - sample.opacity) - .abs() - .max((target - from_position).abs()); - let duration = full_duration.mul_f32(distance); - self.opacity.start(sample.opacity, target, duration, now); - self.position.start(from_position, target, duration, now); - self.entrance = entrance; - } -} - -fn visibility_translation(axis: Axis, track_width: Pixels, progress: f32) -> Point { - let offset = track_width * (1.0 - progress.clamp(0.0, 1.0)); - if axis.is_vertical() { - point(offset, px(0.)) - } else { - point(px(0.), offset) - } -} - -fn wants_visible( - mode: ScrollbarMode, - is_hovered: bool, - is_dragging: bool, - last_scroll_time: Option, - idle: Duration, - now: Instant, -) -> bool { - mode.is_always() - || is_dragging - || (mode.is_hover() && is_hovered) - || last_scroll_time.is_some_and(|last| now.saturating_duration_since(last) < idle) -} - -fn tracks_thumb_hover(mode: ScrollbarMode, is_visible: bool) -> bool { - mode.is_hover() || is_visible -} - -fn hover_keeps_visible(mode: ScrollbarMode, is_hovered: bool, is_currently_visible: bool) -> bool { - is_hovered && (mode.is_hover() || (mode == ScrollbarMode::Scrolling && is_currently_visible)) -} - -impl Deref for ScrollbarState { - type Target = Rc>; - - fn deref(&self) -> &Self::Target { - &self.0 + fade.cancel(); + if running { + window.request_animation_frame(); + } + } } -} -impl ScrollbarState { fn notify_drag( &self, now: Instant, @@ -604,13 +320,11 @@ impl ScrollbarStateInner { state } - fn with_hovered_on_thumb(&self, axis: Option) -> Self { + fn with_hovered_on_thumb(&self, axis: Option, now: Instant) -> Self { let mut state = *self; state.hovered_on_thumb = axis; - if self.is_scrollbar_visible() { - if axis.is_some() { - state.last_scroll_time = Some(Instant::now()); - } + if axis.is_some() && self.is_scrollbar_visible(now) { + state.last_scroll_time = Some(now); } state } @@ -638,8 +352,8 @@ impl ScrollbarStateInner { state } - fn is_scrollbar_visible(&self) -> bool { - self.dragged_axis.is_some() || self.visibility.sample(Instant::now()).opacity > 0.0 + fn is_scrollbar_visible(&self, now: Instant) -> bool { + self.dragged_axis.is_some() || self.visibility.sample(now).opacity > 0.0 } } @@ -654,129 +368,6 @@ pub enum ScrollbarAxis { Both, } -/// Paint-only styles for a scrollbar track. -#[derive(Clone, Default)] -pub struct ScrollbarTrackStyle { - background: Option, - border: Option, - width: Option, -} - -impl ScrollbarTrackStyle { - pub fn bg(mut self, background: Hsla) -> Self { - self.background = Some(background); - self - } - - pub fn border_color(mut self, border: Hsla) -> Self { - self.border = Some(border); - self - } - - pub fn width(mut self, width: impl Into) -> Self { - self.width = Some(width.into()); - self - } -} - -impl FluentBuilder for ScrollbarTrackStyle {} - -/// Paint-only styles for a scrollbar thumb. -#[derive(Clone, Default)] -pub struct ScrollbarThumbStyle { - background: Option, - width: Option, - inset: Option, - radius: Option, - min_length: Option, -} - -impl ScrollbarThumbStyle { - pub fn bg(mut self, background: impl Into) -> Self { - self.background = Some(background.into()); - self - } - - pub fn width(mut self, width: impl Into) -> Self { - self.width = Some(width.into()); - self - } - - pub fn inset(mut self, inset: impl Into) -> Self { - self.inset = Some(inset.into()); - self - } - - pub fn radius(mut self, radius: impl Into) -> Self { - self.radius = Some(radius.into()); - self - } - - pub fn min_length(mut self, min_length: impl Into) -> Self { - self.min_length = Some(min_length.into()); - self - } -} - -impl FluentBuilder for ScrollbarThumbStyle {} - -/// Typed paint styles supported by [`Scrollbar`]. -#[derive(Clone, Default)] -pub struct ScrollbarStyles { - track: ScrollbarTrackStyle, - track_hover: ScrollbarTrackStyle, - track_active: ScrollbarTrackStyle, - thumb: ScrollbarThumbStyle, - thumb_hover: ScrollbarThumbStyle, - thumb_active: ScrollbarThumbStyle, -} - -impl ScrollbarStyles { - pub fn track(mut self, build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle) -> Self { - self.track = build(self.track); - self - } - - pub fn track_hover( - mut self, - build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle, - ) -> Self { - self.track_hover = build(self.track_hover); - self - } - - pub fn track_active( - mut self, - build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle, - ) -> Self { - self.track_active = build(self.track_active); - self - } - - pub fn thumb(mut self, build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle) -> Self { - self.thumb = build(self.thumb); - self - } - - pub fn thumb_hover( - mut self, - build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle, - ) -> Self { - self.thumb_hover = build(self.thumb_hover); - self - } - - pub fn thumb_active( - mut self, - build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle, - ) -> Self { - self.thumb_active = build(self.thumb_active); - self - } -} - -impl FluentBuilder for ScrollbarStyles {} - impl From for ScrollbarAxis { fn from(axis: Axis) -> Self { match axis { @@ -960,214 +551,6 @@ impl Scrollbar { pub const fn width() -> Pixels { WIDTH } - - fn resolve_track( - &self, - cx: &App, - state: &ScrollbarTrackStyle, - global_state: &ScrollbarTrackStyle, - default_border: Hsla, - ) -> (Hsla, Hsla) { - let theme = cx.theme(); - let global = theme.scrollbar.styles(); - ( - state - .background - .or(self.styles.track.background) - .or(global_state.background) - .or(global.track.background) - .unwrap_or_else(gpui::transparent_black), - state - .border - .or(self.styles.track.border) - .or(global_state.border) - .or(global.track.border) - .unwrap_or(default_border), - ) - } - - fn resolve_thumb( - &self, - cx: &App, - state: &ScrollbarThumbStyle, - global_state: &ScrollbarThumbStyle, - defaults: ScrollbarThumbStyle, - ) -> (Background, Pixels, Pixels, Pixels, Pixels) { - let theme = cx.theme(); - let global = theme.scrollbar.styles(); - ( - state - .background - .or(self.styles.thumb.background) - .or(global_state.background) - .or(global.thumb.background) - .unwrap_or_else(|| defaults.background.unwrap()), - state - .width - .or(self.styles.thumb.width) - .or(global_state.width) - .or(global.thumb.width) - .unwrap_or_else(|| defaults.width.unwrap()), - state - .inset - .or(self.styles.thumb.inset) - .or(global_state.inset) - .or(global.thumb.inset) - .unwrap_or_else(|| defaults.inset.unwrap()), - state - .radius - .or(self.styles.thumb.radius) - .or(global_state.radius) - .or(global.thumb.radius) - .unwrap_or_else(|| defaults.radius.unwrap()), - state - .min_length - .or(self.styles.thumb.min_length) - .or(global_state.min_length) - .or(global.thumb.min_length) - .or(defaults.min_length) - .unwrap_or(MIN_THUMB_SIZE), - ) - } - - /// The thumb colour a scrollbar falls back to when nothing has overridden - /// it, taken from the active theme rather than fixed. - /// - /// It used to be literal black at these alphas. That reads as an ordinary - /// grey thumb on a light surface and as very nearly nothing at all on a - /// dark one, and no palette an application installed could change it: - /// `Theme` carries `scrollbar` beside `tokens` rather than derived from - /// them, so a theme swap moved every token except the ones the scrollbar - /// actually paints with. - /// - /// `foreground` is the token that already means "ink on this surface" and - /// already flips with the appearance, so on a light theme this stays within - /// a hair of the old constant and on a dark one it becomes visible. An - /// explicit `ScrollbarStyles` still wins: this is the bottom of the - /// cascade, not a new top of it. - fn thumb_default_background(cx: &App, alpha: f32) -> Background { - cx.theme().tokens.colors.foreground.alpha(alpha).into() - } - - fn thumb_defaults( - background: Background, - width: Pixels, - inset: Pixels, - radius: Pixels, - ) -> ScrollbarThumbStyle { - ScrollbarThumbStyle { - background: Some(background), - width: Some(width), - inset: Some(inset), - radius: Some(radius), - min_length: Some(MIN_THUMB_SIZE), - } - } - - fn style_for_active( - &self, - cx: &App, - ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { - let theme = cx.theme(); - let global = theme.scrollbar.styles(); - let (track, border) = self.resolve_track( - cx, - &self.styles.track_active, - &global.track_active, - gpui::transparent_black(), - ); - let (thumb, width, inset, radius, min_length) = self.resolve_thumb( - cx, - &self.styles.thumb_active, - &global.thumb_active, - Self::thumb_defaults( - Self::thumb_default_background(cx, 0.55), - THUMB_ACTIVE_WIDTH, - THUMB_ACTIVE_INSET, - THUMB_ACTIVE_RADIUS, - ), - ); - (thumb, track, border, width, inset, radius, min_length) - } - - fn style_for_hovered_thumb( - &self, - cx: &App, - ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { - let theme = cx.theme(); - let global = theme.scrollbar.styles(); - let (track, border) = self.resolve_track( - cx, - &self.styles.track_active, - &global.track_active, - gpui::transparent_black(), - ); - let (thumb, width, inset, radius, min_length) = self.resolve_thumb( - cx, - &self.styles.thumb_hover, - &global.thumb_hover, - Self::thumb_defaults( - Self::thumb_default_background(cx, 0.55), - THUMB_ACTIVE_WIDTH, - THUMB_ACTIVE_INSET, - THUMB_ACTIVE_RADIUS, - ), - ); - (thumb, track, border, width, inset, radius, min_length) - } - - fn style_for_hovered_bar( - &self, - cx: &App, - ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { - let theme = cx.theme(); - let global = theme.scrollbar.styles(); - let (track, border) = self.resolve_track( - cx, - &self.styles.track_hover, - &global.track_hover, - gpui::transparent_black(), - ); - let (thumb, width, inset, radius, min_length) = self.resolve_thumb( - cx, - &self.styles.thumb, - &global.thumb, - Self::thumb_defaults( - Self::thumb_default_background(cx, 0.35), - THUMB_WIDTH, - THUMB_INSET, - THUMB_RADIUS, - ), - ); - (thumb, track, border, width, inset, radius, min_length) - } - - fn style_for_normal( - &self, - cx: &App, - ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { - let theme = cx.theme(); - let global = theme.scrollbar.styles(); - - let (track, border) = self.resolve_track( - cx, - &self.styles.track, - &global.track, - gpui::transparent_black(), - ); - let (thumb, width, inset, radius, min_length) = self.resolve_thumb( - cx, - &self.styles.thumb, - &global.thumb, - Self::thumb_defaults( - Self::thumb_default_background(cx, 0.35), - THUMB_WIDTH, - THUMB_INSET, - THUMB_RADIUS, - ), - ); - (thumb, track, border, width, inset, radius, min_length) - } } impl IntoElement for Scrollbar { @@ -1178,33 +561,6 @@ impl IntoElement for Scrollbar { } } -#[doc(hidden)] -pub struct PrepaintState { - hitbox: Hitbox, - scrollbar_state: ScrollbarState, - states: Vec, -} - -#[doc(hidden)] -pub struct AxisPrepaintState { - axis: Axis, - bar_hitbox: Hitbox, - bounds: Bounds, - radius: Pixels, - bg: Hsla, - border: Hsla, - thumb_bounds: Bounds, - // Bounds of thumb to be rendered. - thumb_fill_bounds: Bounds, - thumb_bg: Background, - geometry: ThumbGeometry, - active_geometry: ThumbGeometry, - track_width: Pixels, - visibility_opacity: f32, - visibility_position: f32, - visibility_requested: bool, -} - /// The same longitudinal geometry drives painting, track clicks and dragging. /// `length` excludes the inset, while `travel` excludes the full logical thumb. #[derive(Clone, Copy)] @@ -1266,1638 +622,3 @@ impl ThumbGeometry { offset } } - -impl Element for Scrollbar { - type RequestLayoutState = (); - type PrepaintState = PrepaintState; - - fn id(&self) -> Option { - Some(self.id.clone()) - } - - fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { - None - } - - fn request_layout( - &mut self, - _: Option<&GlobalElementId>, - _: Option<&InspectorElementId>, - window: &mut Window, - cx: &mut App, - ) -> (LayoutId, Self::RequestLayoutState) { - let mut style = Style::default(); - style.position = Position::Absolute; - style.flex_grow = 1.0; - style.flex_shrink = 1.0; - style.size.width = relative(1.).into(); - style.size.height = relative(1.).into(); - - (window.request_layout(style, None, cx), ()) - } - - fn prepaint( - &mut self, - _: Option<&GlobalElementId>, - _: Option<&InspectorElementId>, - bounds: Bounds, - _: &mut Self::RequestLayoutState, - window: &mut Window, - cx: &mut App, - ) -> Self::PrepaintState { - let bounds = self.resolved_viewport_bounds(bounds); - let hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| { - window.insert_hitbox(bounds, HitboxBehavior::Normal) - }); - - let state = window - .use_state(cx, |_, _| ScrollbarState::default()) - .read(cx) - .clone(); - - let now = Instant::now(); - let base_theme = cx.theme(); - let mode = self.mode.unwrap_or(base_theme.scrollbar.mode()); - let motion = base_theme.scrollbar.motion(); - // Always-visible scrollbars skip visibility motion but still animate - // their activity width. Reduced motion snaps every channel. - let reduce_motion = cx.reduce_motion(); - let (enter, exit) = if !mode.is_always() && !reduce_motion { - (motion.enter(), motion.exit()) - } else { - (Duration::ZERO, Duration::ZERO) - }; - let expand = if reduce_motion { - Duration::ZERO - } else { - motion.expand() - }; - - let mut inner = state.get(); - let current_offset = self.scroll_handle.offset(); - if current_offset != inner.last_scroll_offset { - inner = inner.with_last_scroll(current_offset, Some(now)); - } - - let is_hovered = inner.hovered_axis.is_some() || inner.hovered_on_thumb.is_some(); - let is_dragging = inner.dragged_axis.is_some(); - let is_currently_visible = inner.visibility.sample(now).opacity > 0.0; - let visible = hover_keeps_visible(mode, is_hovered, is_currently_visible) - || wants_visible( - mode, - is_hovered, - is_dragging, - inner.last_scroll_time, - motion.idle(), - now, - ); - inner.visibility.set_visible( - visible, - motion.entrance_for(mode, inner.hovered_on_thumb.is_some()), - enter, - exit, - now, - ); - let visibility = inner.visibility.sample(now); - if visibility.running { - window.request_animation_frame(); - } - - if !is_hovered && !is_dragging { - if let Some(last_time) = inner.last_scroll_time { - let elapsed = now.saturating_duration_since(last_time); - if elapsed < motion.idle() && !inner.idle_timer_scheduled { - inner.idle_timer_scheduled = true; - let state = state.clone(); - let current_view = window.current_view(); - let next_delay = motion.idle() - elapsed; - window - .spawn(cx, async move |cx| { - cx.background_executor().timer(next_delay).await; - state.set(state.get().with_idle_timer_scheduled(false)); - cx.update(|_, cx| cx.notify(current_view)).ok(); - }) - .detach(); - } - } - } - state.set(inner); - - let mut states = vec![]; - let mut has_both = self.axis.is_both(); - let scroll_size = self - .scroll_size - .unwrap_or(self.scroll_handle.content_size()); - - for axis in self.axis.all().into_iter() { - let is_vertical = axis.is_vertical(); - let track_width = self - .styles - .track - .width - .or(cx.theme().scrollbar.styles().track.width) - .unwrap_or(WIDTH); - let (scroll_area_size, container_size, scroll_position) = if is_vertical { - ( - scroll_size.height, - hitbox.size.height, - self.scroll_handle.offset().y, - ) - } else { - ( - scroll_size.width, - hitbox.size.width, - self.scroll_handle.offset().x, - ) - }; - - // The horizontal scrollbar is set avoid overlapping with the vertical scrollbar, if the vertical scrollbar is visible. - let margin_end = if has_both && !is_vertical { - track_width - } else { - px(0.) - }; - - // Hide scrollbar, if the scroll area is smaller than the container. - if scroll_area_size <= container_size { - has_both = false; - continue; - } - - let bounds = Bounds { - origin: if is_vertical { - point( - hitbox.origin.x + hitbox.size.width - track_width, - hitbox.origin.y, - ) - } else { - point( - hitbox.origin.x, - hitbox.origin.y + hitbox.size.height - track_width, - ) - }, - size: gpui::Size { - width: if is_vertical { - track_width - } else { - hitbox.size.width - }, - height: if is_vertical { - hitbox.size.height - } else { - track_width - }, - }, - }; - - let is_always_to_show = mode.is_always(); - let is_hover_to_show = mode.is_hover(); - let is_hovered_on_bar = state.get().hovered_axis == Some(axis); - let is_hovered_on_thumb = state.get().hovered_on_thumb == Some(axis); - - let (thumb_bg, bar_bg, bar_border, mut thumb_width, inset, radius, min_length) = - if state.get().dragged_axis == Some(axis) { - self.style_for_active(cx) - } else if (is_hover_to_show || mode == ScrollbarMode::Scrolling) - && (is_hovered_on_bar || is_hovered_on_thumb) - { - if is_hovered_on_thumb { - self.style_for_hovered_thumb(cx) - } else { - self.style_for_hovered_bar(cx) - } - } else if is_always_to_show && (is_hovered_on_bar || is_hovered_on_thumb) { - if is_hovered_on_thumb { - self.style_for_hovered_thumb(cx) - } else { - self.style_for_hovered_bar(cx) - } - } else { - self.style_for_normal(cx) - }; - - let mut width_animation = if is_vertical { - state.get().vertical_width - } else { - state.get().horizontal_width - }; - let (animated_width, running) = width_animation.set_target(thumb_width, expand, now); - let mut updated = state.get(); - if is_vertical { - updated.vertical_width = width_animation; - } else { - updated.horizontal_width = width_animation; - } - state.set(updated); - thumb_width = animated_width; - if running { - window.request_animation_frame(); - } - - let origin = if is_vertical { - bounds.origin.y - } else { - bounds.origin.x - }; - let geometry = ThumbGeometry::new( - origin, - container_size, - scroll_area_size, - margin_end, - inset, - min_length, - ); - let (_, _, _, _, active_inset, _, active_min_length) = self.style_for_active(cx); - let active_geometry = ThumbGeometry::new( - origin, - container_size, - scroll_area_size, - margin_end, - active_inset, - active_min_length, - ); - let thumb_start = geometry.start(scroll_position) - origin; - - // The clickable area of the thumb - let thumb_length = geometry.length; - let thumb_bounds = if is_vertical { - Bounds::from_anchor_and_size( - Anchor::TopRight, - bounds.top_right() + point(-inset, thumb_start), - size(track_width, thumb_length), - ) - } else { - Bounds::from_anchor_and_size( - Anchor::BottomLeft, - bounds.bottom_left() + point(thumb_start, -inset), - size(thumb_length, track_width), - ) - }; - - // The actual render area of the thumb - let thumb_fill_bounds = if is_vertical { - Bounds::from_anchor_and_size( - Anchor::TopRight, - bounds.top_right() + point(-inset, thumb_start), - size(thumb_width, thumb_length), - ) - } else { - Bounds::from_anchor_and_size( - Anchor::BottomLeft, - bounds.bottom_left() + point(thumb_start, -inset), - size(thumb_length, thumb_width), - ) - }; - - let bar_hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| { - window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal) - }); - - states.push(AxisPrepaintState { - axis, - bar_hitbox, - bounds, - radius, - bg: bar_bg, - border: bar_border, - thumb_bounds, - thumb_fill_bounds, - thumb_bg, - geometry, - active_geometry, - track_width, - visibility_opacity: visibility.opacity, - visibility_position: visibility.position, - visibility_requested: visible, - }) - } - - PrepaintState { - hitbox, - states, - scrollbar_state: state, - } - } - - fn paint( - &mut self, - _: Option<&GlobalElementId>, - _: Option<&InspectorElementId>, - _: Bounds, - _: &mut Self::RequestLayoutState, - prepaint: &mut Self::PrepaintState, - window: &mut Window, - cx: &mut App, - ) { - let scrollbar_state = &prepaint.scrollbar_state; - let theme = cx.theme(); - let mode = self.mode.unwrap_or(theme.scrollbar.mode()); - let view_id = window.current_view(); - let hitbox_bounds = prepaint.hitbox.bounds; - let is_hover_to_show = mode.is_hover(); - - window.with_content_mask( - Some(ContentMask { - bounds: hitbox_bounds, - }), - |window| { - for state in prepaint.states.iter() { - let axis = state.axis; - let mut radius = state.radius; - if theme.tokens.radius.md.is_zero() { - radius = px(0.); - } - radius = clamp_thumb_radius(radius, state.thumb_fill_bounds); - let bounds = state.bounds; - let thumb_bounds = state.thumb_bounds; - let geometry = state.geometry; - let active_geometry = state.active_geometry; - let is_vertical = axis.is_vertical(); - let visibility_opacity = state.visibility_opacity; - let is_visible = state.visibility_requested || visibility_opacity > 0.0; - let translation = - visibility_translation(axis, state.track_width, state.visibility_position); - let painted_bounds = state.bounds + translation; - let painted_thumb_bounds = state.thumb_fill_bounds + translation; - let painted_track_bg = state.bg.opacity(visibility_opacity); - let painted_border = state.border.opacity(visibility_opacity); - let painted_thumb_bg = state.thumb_bg.clone().opacity(visibility_opacity); - - window.set_cursor_style(CursorStyle::default(), &state.bar_hitbox); - - window.paint_layer(hitbox_bounds, |cx| { - cx.paint_quad(fill(painted_bounds, painted_track_bg)); - - cx.paint_quad(PaintQuad { - bounds: painted_bounds, - corner_radii: (0.).into(), - background: gpui::transparent_black().into(), - border_widths: if is_vertical { - Edges { - top: px(0.), - right: px(0.), - bottom: px(0.), - left: px(0.), - } - } else { - Edges { - top: px(0.), - right: px(0.), - bottom: px(0.), - left: px(0.), - } - }, - border_color: painted_border, - border_style: BorderStyle::default(), - }); - - cx.paint_quad( - fill(painted_thumb_bounds, painted_thumb_bg).corner_radii(radius), - ); - }); - - window.on_mouse_event({ - let state = scrollbar_state.clone(); - let scroll_handle = self.scroll_handle.clone(); - - move |event: &ScrollWheelEvent, phase, _, cx| { - if phase.bubble() && hitbox_bounds.contains(&event.position) { - if scroll_handle.offset() != state.get().last_scroll_offset { - state.set(state.get().with_last_scroll( - scroll_handle.offset(), - Some(Instant::now()), - )); - cx.notify(view_id); - } - } - } - }); - - // A thumb follows the finger, unlike content panning. Claim - // this touch before the window turns it into wheel deltas. - window.on_mouse_event({ - let state = scrollbar_state.clone(); - let scroll_handle = self.scroll_handle.clone(); - let max_fps_duration = Duration::from_secs_f64(1. / self.max_fps as f64); - move |event: &TouchDragEvent, phase, window, cx| { - if !phase.bubble() { - return; - } - if event.phase == TouchPhase::Started { - if !is_visible - || window.default_prevented() - || !thumb_bounds.contains(&event.start_position) - { - return; - } - scroll_handle.start_drag(); - state.set(state.get().with_drag_pos( - axis, - event.start_position - thumb_bounds.origin, - )); - } else if state.get().dragged_axis != Some(axis) { - return; - } - if event.phase != TouchPhase::Cancelled { - scroll_handle.set_offset(active_geometry.drag_offset( - axis, - event.position, - state.get().drag_pos, - scroll_handle.offset(), - )); - } - if matches!(event.phase, TouchPhase::Ended | TouchPhase::Cancelled) { - scroll_handle.end_drag(); - state.set(state.get().with_unset_drag_pos(Instant::now())); - } - window.prevent_default(); - cx.stop_propagation(); - if event.phase == TouchPhase::Moved { - state.notify_drag( - Instant::now(), - max_fps_duration, - view_id, - window, - cx, - ); - } else { - cx.notify(view_id); - } - } - }); - - if is_visible { - window.on_mouse_event({ - let state = scrollbar_state.clone(); - let scroll_handle = self.scroll_handle.clone(); - - move |event: &MouseDownEvent, phase, _, cx| { - if phase.bubble() && bounds.contains(&event.position) { - cx.stop_propagation(); - - if thumb_bounds.contains(&event.position) { - // click on the thumb bar, set the drag position - let pos = event.position - thumb_bounds.origin; - - scroll_handle.start_drag(); - state.set(state.get().with_drag_pos(axis, pos)); - // Active styling can change the inset or minimum length. - // Keep the original grab point under the pointer on that frame. - scroll_handle.set_offset(active_geometry.drag_offset( - axis, - event.position, - pos, - scroll_handle.offset(), - )); - } else { - // click on the scrollbar, jump to the position - // Set the thumb bar center to the click position - let center = - point(geometry.length / 2., geometry.length / 2.); - scroll_handle.set_offset(geometry.drag_offset( - axis, - event.position, - center, - scroll_handle.offset(), - )); - } - - cx.notify(view_id); - } - } - }); - } - - window.on_mouse_event({ - let scroll_handle = self.scroll_handle.clone(); - let state = scrollbar_state.clone(); - let max_fps_duration = Duration::from_secs_f64(1. / self.max_fps as f64); - - move |event: &MouseMoveEvent, _, window, cx| { - let mut notify = false; - // When is hover to show mode or it was visible, - // we need to update the hovered state and increase the last_scroll_time. - let need_hover_to_update = is_hover_to_show || is_visible; - // Update hovered state for scrollbar - if bounds.contains(&event.position) && need_hover_to_update { - let hover_changed = state.get().hovered_axis != Some(axis); - state.set(state.get().with_hovered(Some(axis), Instant::now())); - notify |= hover_changed; - } else if state.get().hovered_axis == Some(axis) { - state.set(state.get().with_hovered(None, Instant::now())); - notify = true; - } - - // Update hovered state for scrollbar thumb - if tracks_thumb_hover(mode, is_visible) - && thumb_bounds.contains(&event.position) - { - if state.get().hovered_on_thumb != Some(axis) { - state.set(state.get().with_hovered_on_thumb(Some(axis))); - notify = true; - } - } else { - if state.get().hovered_on_thumb == Some(axis) { - state.set(state.get().with_hovered_on_thumb(None)); - notify = true; - } - } - - // Move thumb position on dragging - if state.get().dragged_axis == Some(axis) && event.dragging() { - // Stop the event propagation to avoid selecting text or other side effects. - cx.stop_propagation(); - - let offset = active_geometry.drag_offset( - axis, - event.position, - state.get().drag_pos, - scroll_handle.offset(), - ); - if scroll_handle.offset() != offset { - // Coalesce rendering, never discard the newest pointer position. - scroll_handle.set_offset(offset); - notify = true; - } - if notify { - state.notify_drag( - Instant::now(), - max_fps_duration, - view_id, - window, - cx, - ); - } - return; - } - - if notify { - cx.notify(view_id); - } - } - }); - - window.on_mouse_event({ - let state = scrollbar_state.clone(); - let scroll_handle = self.scroll_handle.clone(); - - move |event: &MouseUpEvent, phase, _, cx| { - if phase.bubble() && state.get().dragged_axis == Some(axis) { - scroll_handle.set_offset(active_geometry.drag_offset( - axis, - event.position, - state.get().drag_pos, - scroll_handle.offset(), - )); - scroll_handle.end_drag(); - state.set(state.get().with_unset_drag_pos(Instant::now())); - cx.notify(view_id); - } - } - }); - } - }, - ); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - use std::cell::{Cell, RefCell}; - - use gpui::{ - Context, Modifiers, MouseButton, ParentElement as _, Render, Styled as _, TestAppContext, - VisualTestContext, div, - }; - - #[test] - fn thumb_radius_is_limited_by_its_actual_bounds() { - let vertical_thumb = Bounds::new(Point::default(), size(px(8.), px(80.))); - let horizontal_thumb = Bounds::new(Point::default(), size(px(80.), px(6.))); - - assert_eq!(clamp_thumb_radius(px(6.), vertical_thumb), px(4.)); - assert_eq!(clamp_thumb_radius(px(6.), horizontal_thumb), px(3.)); - assert_eq!( - clamp_thumb_radius(Pixels::ZERO, vertical_thumb), - Pixels::ZERO - ); - } - - /// Timing standing in for what a styled layer projects. Base itself ships - /// none of these; see [`motionless_base_snaps_every_transition`]. - const ENTER: Duration = Duration::from_millis(300); - const EXIT: Duration = Duration::from_millis(500); - const EXPAND: Duration = Duration::from_millis(300); - - #[test] - fn visibility_animation_uses_direction_specific_curves_and_durations() { - let start = Instant::now(); - let mut animation = VisibilityAnimation::hidden(start); - - animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); - assert_eq!(animation.sample(start).opacity, 0.0); - let entering = animation.sample(start + ENTER / 2).position; - assert!(entering > 0.5, "ease-out must advance quickly"); - let entered = animation.sample(start + ENTER); - assert_eq!(entered.opacity, 1.0); - assert_eq!(entered.position, 1.0); - - animation.set_visible( - false, - ScrollbarEntrance::SlideAndFade, - ENTER, - EXIT, - start + ENTER, - ); - let exiting = animation.sample(start + ENTER + EXIT / 2).opacity; - assert!(exiting > 0.5, "ease-in must remain visible early in exit"); - assert_eq!(animation.sample(start + ENTER + EXIT).opacity, 0.0); - } - - #[test] - fn entrance_fades_linearly_while_position_eases_out() { - let start = Instant::now(); - let mut animation = VisibilityAnimation::hidden(start); - animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); - - let halfway = animation.sample(start + ENTER / 2); - assert!((halfway.opacity - 0.5).abs() < 0.001); - assert!(halfway.position > halfway.opacity); - } - - #[test] - fn fade_entrance_snaps_position_and_animates_opacity() { - let start = Instant::now(); - let mut animation = VisibilityAnimation::hidden(start); - animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, start); - - let initial = animation.sample(start); - assert_eq!(initial.opacity, 0.0); - assert_eq!(initial.position, 1.0); - let halfway = animation.sample(start + ENTER / 2); - assert!((halfway.opacity - 0.5).abs() < 0.001); - assert_eq!(halfway.position, 1.0); - } - - #[test] - fn active_visibility_adopts_a_changed_entrance_policy() { - let start = Instant::now(); - let halfway = start + ENTER / 2; - let mut animation = VisibilityAnimation::hidden(start); - animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); - let before = animation.sample(halfway); - - animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, halfway); - let after = animation.sample(halfway); - - assert_eq!( - after.opacity, before.opacity, - "policy changes must not flash" - ); - assert_eq!(after.position, 1.0, "fade entrance must stop stale sliding"); - } - - #[test] - fn base_ships_no_motion_of_its_own() { - let motion = ScrollbarMotion::default(); - assert_eq!(motion.enter(), Duration::ZERO); - assert_eq!(motion.exit(), Duration::ZERO); - assert_eq!(motion.expand(), Duration::ZERO); - assert_eq!(motion.entrance(), ScrollbarEntrance::Fade); - assert_eq!(motion.thumb_hover_entrance(), ScrollbarEntrance::Fade); - assert_eq!( - motion.idle(), - DEFAULT_IDLE, - "the visibility hold is behavior, not motion, and must stay usable" - ); - } - - #[test] - fn hover_mode_slides_only_when_the_thumb_is_hovered() { - let motion = ScrollbarMotion::default() - .with_entrance(ScrollbarEntrance::Fade) - .with_thumb_hover_entrance(ScrollbarEntrance::SlideAndFade); - - assert_eq!( - motion.entrance_for(ScrollbarMode::Hover, false), - ScrollbarEntrance::Fade - ); - assert_eq!( - motion.entrance_for(ScrollbarMode::Hover, true), - ScrollbarEntrance::SlideAndFade - ); - assert_eq!( - motion.entrance_for(ScrollbarMode::Scrolling, true), - ScrollbarEntrance::Fade - ); - } - - #[test] - fn hidden_scrolling_mode_does_not_track_thumb_hover() { - assert!(!tracks_thumb_hover(ScrollbarMode::Scrolling, false)); - assert!(tracks_thumb_hover(ScrollbarMode::Scrolling, true)); - assert!(tracks_thumb_hover(ScrollbarMode::Hover, false)); - } - - #[test] - fn visible_scrolling_mode_stays_visible_while_hovered() { - assert!(!hover_keeps_visible(ScrollbarMode::Scrolling, true, false)); - assert!(hover_keeps_visible(ScrollbarMode::Scrolling, true, true)); - assert!(hover_keeps_visible(ScrollbarMode::Hover, true, false)); - } - - #[test] - fn motionless_base_snaps_every_transition() { - let now = Instant::now(); - let motion = ScrollbarMotion::default(); - let mut visibility = VisibilityAnimation::hidden(now); - - visibility.set_visible(true, motion.entrance(), motion.enter(), motion.exit(), now); - let shown = visibility.sample(now); - assert_eq!(shown.opacity, 1.0); - assert_eq!(shown.position, 1.0); - assert!(!shown.running, "a motionless theme must request no frames"); - assert_eq!( - visibility_translation(Axis::Vertical, px(16.), shown.position), - Point::default() - ); - - visibility.set_visible(false, motion.entrance(), motion.enter(), motion.exit(), now); - let hidden = visibility.sample(now); - assert_eq!(hidden.opacity, 0.0); - assert_eq!(hidden.position, 0.0); - assert!(!hidden.running); - - let mut width = WidthAnimation::new(now); - assert_eq!( - width.set_target(px(8.), motion.expand(), now), - (px(8.), false) - ); - } - - #[test] - fn a_zero_duration_settles_a_transition_already_in_flight() { - let start = Instant::now(); - let mut animation = VisibilityAnimation::hidden(start); - animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); - - // Reduced motion turns on midway through the entrance. - let midway = start + ENTER / 2; - animation.set_visible( - true, - ScrollbarEntrance::SlideAndFade, - Duration::ZERO, - Duration::ZERO, - midway, - ); - let settled = animation.sample(midway); - assert_eq!(settled.opacity, 1.0); - assert_eq!(settled.position, 1.0); - assert!(!settled.running); - } - - #[test] - fn thumb_expansion_animates_in_both_directions() { - let start = Instant::now(); - let mut animation = WidthAnimation::new(start); - assert_eq!(animation.set_target(px(6.), EXPAND, start), (px(6.), false)); - - let (initial, running) = animation.set_target(px(8.), EXPAND, start); - assert_eq!(initial, px(6.)); - assert!(running); - let (expanded_halfway, _) = animation.sample(start + EXPAND / 2); - assert!(expanded_halfway > px(7.)); - - let reversal = start + EXPAND / 2; - let before = animation.sample(reversal).0; - let (after_reversal, running) = animation.set_target(px(6.), EXPAND, reversal); - assert_eq!(after_reversal, before); - assert!(running); - assert_eq!(animation.sample(reversal + EXPAND).0, px(6.)); - } - - #[test] - fn reduced_motion_snaps_thumb_expansion() { - let now = Instant::now(); - let mut animation = WidthAnimation::new(now); - assert_eq!( - animation.set_target(px(8.), Duration::ZERO, now), - (px(8.), false) - ); - } - - #[test] - fn visibility_translation_moves_toward_the_nearest_edge() { - assert_eq!( - visibility_translation(Axis::Vertical, px(16.), 0.0), - point(px(16.), px(0.)) - ); - assert_eq!( - visibility_translation(Axis::Horizontal, px(16.), 0.0), - point(px(0.), px(16.)) - ); - assert_eq!( - visibility_translation(Axis::Vertical, px(16.), 1.0), - Point::default() - ); - } - - #[test] - fn visibility_animation_reverses_from_current_progress() { - let start = Instant::now(); - let mut animation = VisibilityAnimation::hidden(start); - animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); - let reversal_time = start + Duration::from_millis(60); - let before = animation.sample(reversal_time); - - animation.set_visible( - false, - ScrollbarEntrance::SlideAndFade, - ENTER, - EXIT, - reversal_time, - ); - let reversed = animation.sample(reversal_time); - assert_eq!(reversed.opacity, before.opacity); - assert_eq!(reversed.position, before.position); - let after = animation.sample(reversal_time + Duration::from_millis(10)); - assert!(after.opacity < before.opacity); - assert!(after.position < before.position); - } - - #[test] - fn always_hover_drag_and_recent_scroll_request_visibility() { - let now = Instant::now(); - let idle = DEFAULT_IDLE; - assert!(wants_visible( - ScrollbarMode::Always, - false, - false, - None, - idle, - now - )); - assert!(wants_visible( - ScrollbarMode::Hover, - true, - false, - None, - idle, - now - )); - assert!(wants_visible( - ScrollbarMode::Scrolling, - false, - true, - None, - idle, - now - )); - assert!(wants_visible( - ScrollbarMode::Scrolling, - false, - false, - Some(now - idle + Duration::from_millis(1)), - idle, - now, - )); - assert!(!wants_visible( - ScrollbarMode::Scrolling, - false, - false, - Some(now - idle), - idle, - now, - )); - - let mut settled = VisibilityAnimation::hidden(now - ENTER); - settled.set_visible( - true, - ScrollbarEntrance::SlideAndFade, - ENTER, - EXIT, - now - ENTER, - ); - assert!(!settled.sample(now).running, "idle hold must not animate"); - } - - #[test] - fn leaving_hover_starts_a_fresh_idle_hold() { - let entered_at = Instant::now(); - let left_at = entered_at + Duration::from_secs(5); - let state = ScrollbarState::default().get(); - - let hovered = state.with_hovered(Some(Axis::Vertical), entered_at); - assert_eq!(hovered.last_scroll_time, Some(entered_at)); - let left = hovered.with_hovered(None, left_at); - assert_eq!(left.last_scroll_time, Some(left_at)); - assert!(wants_visible( - ScrollbarMode::Hover, - false, - false, - left.last_scroll_time, - DEFAULT_IDLE, - left_at + DEFAULT_IDLE - Duration::from_millis(1), - )); - } - - #[test] - fn idle_boundary_starts_the_exit_without_a_jump() { - let activity = Instant::now(); - let exit_start = activity + DEFAULT_IDLE; - let mut animation = VisibilityAnimation::hidden(activity - ENTER); - animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, activity - ENTER); - assert!(!wants_visible( - ScrollbarMode::Scrolling, - false, - false, - Some(activity), - DEFAULT_IDLE, - exit_start, - )); - - animation.set_visible(false, ScrollbarEntrance::Fade, ENTER, EXIT, exit_start); - let start = animation.sample(exit_start); - assert_eq!(start.opacity, 1.0); - assert_eq!(start.position, 1.0); - assert_eq!(animation.sample(exit_start + EXIT).opacity, 0.0); - } - - #[derive(Clone)] - struct TestHandle { - offset: Rc>>, - content_size: Size, - drag_starts: Rc>, - drag_ends: Rc>, - } - - impl TestHandle { - fn new(content_size: Size) -> Self { - Self { - offset: Rc::new(Cell::new(Point::default())), - content_size, - drag_starts: Rc::new(Cell::new(0)), - drag_ends: Rc::new(Cell::new(0)), - } - } - } - - impl ScrollbarHandle for TestHandle { - fn viewport_bounds(&self) -> Bounds { - Bounds::new(Point::default(), size(px(100.), px(100.))) - } - - fn offset(&self) -> Point { - self.offset.get() - } - - fn set_offset(&self, offset: Point) { - self.offset.set(offset); - } - - fn content_size(&self) -> Size { - self.content_size - } - - fn start_drag(&self) { - self.drag_starts.set(self.drag_starts.get() + 1); - } - - fn end_drag(&self) { - self.drag_ends.set(self.drag_ends.get() + 1); - } - } - - struct ScrollbarHarness { - handle: TestHandle, - axis: ScrollbarAxis, - mode: ScrollbarMode, - } - - impl Render for ScrollbarHarness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div() - .relative() - .size(px(100.)) - .child(Scrollbar::new(&self.handle).axis(self.axis).mode(self.mode)) - } - } - - fn harness( - cx: &mut TestAppContext, - axis: ScrollbarAxis, - mode: ScrollbarMode, - content_size: Size, - ) -> (&mut VisualTestContext, TestHandle) { - let handle = TestHandle::new(content_size); - let (_, cx) = cx.add_window_view({ - let handle = handle.clone(); - move |_, _| ScrollbarHarness { handle, axis, mode } - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - (cx, handle) - } - - #[test] - fn explicit_viewport_bounds_override_handle_bounds() { - let expected = Bounds::new(point(px(12.), px(24.)), size(px(240.), px(96.))); - let scrollbar = Scrollbar::vertical(&TestHandle::new(size(px(240.), px(480.)))) - .viewport_bounds(expected); - - assert_eq!( - scrollbar.resolved_viewport_bounds(Bounds::default()), - expected - ); - } - - #[test] - fn layout_viewport_uses_current_element_bounds() { - let expected = Bounds::new(point(px(20.), px(30.)), size(px(180.), px(12.))); - let scrollbar = - Scrollbar::horizontal(&TestHandle::new(size(px(600.), px(12.)))).viewport_from_layout(); - - assert_eq!(scrollbar.resolved_viewport_bounds(expected), expected); - } - - #[test] - fn typed_styles_are_fluent_and_include_geometry() { - let track = gpui::hsla(0.1, 0.2, 0.3, 1.0); - let border = gpui::hsla(0.2, 0.3, 0.4, 1.0); - let thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0); - let hover = gpui::hsla(0.4, 0.5, 0.6, 1.0); - let active = gpui::hsla(0.5, 0.6, 0.7, 1.0); - let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())).styles(|styles| { - styles - .track(|style| { - style - .width(px(14.)) - .bg(track) - .border_color(border) - .when(false, |style| style.width(px(99.))) - }) - .thumb(|style| { - style - .width(px(7.)) - .inset(px(3.)) - .radius(px(3.5)) - .min_length(px(40.)) - .bg(thumb) - }) - .thumb_hover(|style| style.width(px(9.)).bg(hover)) - .thumb_active(|style| style.radius(px(4.5)).bg(active)) - }); - - assert_eq!(scrollbar.styles.track.background, Some(track)); - assert_eq!(scrollbar.styles.track.border, Some(border)); - assert_eq!(scrollbar.styles.track.width, Some(px(14.))); - assert!(scrollbar.styles.thumb.background.is_some()); - assert_eq!(scrollbar.styles.thumb.width, Some(px(7.))); - assert_eq!(scrollbar.styles.thumb.inset, Some(px(3.))); - assert_eq!(scrollbar.styles.thumb.radius, Some(px(3.5))); - assert_eq!(scrollbar.styles.thumb.min_length, Some(px(40.))); - assert!(scrollbar.styles.thumb_hover.background.is_some()); - assert_eq!(scrollbar.styles.thumb_hover.width, Some(px(9.))); - assert!(scrollbar.styles.thumb_active.background.is_some()); - assert_eq!(scrollbar.styles.thumb_active.radius, Some(px(4.5))); - } - - #[gpui::test] - fn unstyled_thumb_follows_the_theme_rather_than_a_fixed_colour(cx: &mut TestAppContext) { - cx.update(|cx| { - let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())); - - let light = gpui::hsla(0., 0., 0.04, 1.0); - crate::Theme::global_mut(cx).tokens.colors.foreground = light; - let (on_light, ..) = scrollbar.style_for_normal(cx); - - let dark = gpui::hsla(0., 0., 0.98, 1.0); - crate::Theme::global_mut(cx).tokens.colors.foreground = dark; - let (on_dark, ..) = scrollbar.style_for_normal(cx); - - assert_eq!(on_light, Background::from(light.alpha(0.35))); - assert_eq!(on_dark, Background::from(dark.alpha(0.35))); - // The point of the change: a thumb that never moved with the - // palette was invisible on one of the two surfaces. - assert_ne!(on_light, on_dark); - }); - } - - #[gpui::test] - fn a_styled_thumb_still_beats_the_theme_derived_default(cx: &mut TestAppContext) { - cx.update(|cx| { - let chosen = gpui::hsla(0.6, 0.5, 0.5, 1.0); - crate::Theme::global_mut(cx).tokens.colors.foreground = gpui::hsla(0., 0., 0.98, 1.0); - - let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())) - .styles(|styles| styles.thumb(|style| style.bg(chosen))); - let (thumb, ..) = scrollbar.style_for_normal(cx); - - assert_eq!(thumb, Background::from(chosen)); - }); - } - - #[gpui::test] - fn instance_styles_override_theme_scrollbar_defaults(cx: &mut TestAppContext) { - cx.update(|cx| { - let theme_track = gpui::hsla(0.1, 0.2, 0.3, 1.0); - let theme_thumb = gpui::hsla(0.2, 0.3, 0.4, 1.0); - let instance_thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0); - - crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new() - .with_mode(ScrollbarMode::Always) - .with_motion(ScrollbarMotion::default()) - .with_styles( - ScrollbarStyles::default() - .track(|style| style.width(px(13.)).bg(theme_track)) - .thumb(|style| style.width(px(7.)).bg(theme_thumb)), - ); - - let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())) - .styles(|styles| styles.thumb(|style| style.bg(instance_thumb))); - let (thumb, track, _, width, _, _, _) = scrollbar.style_for_normal(cx); - - assert_eq!(thumb, Background::from(instance_thumb)); - assert_eq!(track, theme_track); - assert_eq!(width, px(7.)); - assert_eq!(cx.theme().scrollbar.styles().track.width, Some(px(13.))); - }); - } - - #[gpui::test] - fn auto_hide_modes_use_a_six_pixel_resting_thumb(cx: &mut TestAppContext) { - cx.update(|cx| { - let handle = TestHandle::new(Size::default()); - let scrolling = Scrollbar::new(&handle).mode(ScrollbarMode::Scrolling); - let always = Scrollbar::new(&handle).mode(ScrollbarMode::Always); - - assert_eq!(scrolling.style_for_normal(cx).3, px(6.)); - assert_eq!(always.style_for_normal(cx).3, px(6.)); - }); - } - - #[gpui::test] - fn every_mode_expands_only_for_thumb_hover(cx: &mut TestAppContext) { - cx.update(|cx| { - let handle = TestHandle::new(Size::default()); - for mode in [ - ScrollbarMode::Scrolling, - ScrollbarMode::Hover, - ScrollbarMode::Always, - ] { - let scrollbar = Scrollbar::new(&handle).mode(mode); - assert_eq!(scrollbar.style_for_normal(cx).3, px(6.)); - assert_eq!(scrollbar.style_for_hovered_bar(cx).3, px(6.)); - assert_eq!(scrollbar.style_for_hovered_thumb(cx).3, px(8.)); - } - }); - } - - #[gpui::test] - fn vertical_track_click_updates_vertical_offset(cx: &mut TestAppContext) { - let (cx, vertical) = harness( - cx, - ScrollbarAxis::Vertical, - ScrollbarMode::Always, - size(px(100.), px(500.)), - ); - cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); - assert!(vertical.offset().y < px(0.)); - assert_eq!(vertical.offset().x, px(0.)); - } - - #[gpui::test] - fn horizontal_track_click_updates_horizontal_offset(cx: &mut TestAppContext) { - let (cx, horizontal) = harness( - cx, - ScrollbarAxis::Horizontal, - ScrollbarMode::Always, - size(px(500.), px(100.)), - ); - cx.simulate_click(point(px(80.), px(95.)), Modifiers::default()); - assert!(horizontal.offset().x < px(0.)); - assert_eq!(horizontal.offset().y, px(0.)); - } - - #[gpui::test] - fn no_overflow_has_no_interactive_track(cx: &mut TestAppContext) { - let (cx, handle) = harness( - cx, - ScrollbarAxis::Both, - ScrollbarMode::Always, - size(px(100.), px(100.)), - ); - cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); - assert_eq!(handle.offset(), Point::default()); - } - - #[gpui::test] - fn hidden_hover_scrollbar_ignores_track_click(cx: &mut TestAppContext) { - let (cx, handle) = harness( - cx, - ScrollbarAxis::Vertical, - ScrollbarMode::Hover, - size(px(100.), px(500.)), - ); - cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); - assert_eq!(handle.offset(), Point::default()); - } - - #[gpui::test] - fn hidden_hover_scrollbar_ignores_thumb_drag(cx: &mut TestAppContext) { - let (cx, handle) = harness( - cx, - ScrollbarAxis::Vertical, - ScrollbarMode::Hover, - size(px(100.), px(500.)), - ); - cx.simulate_mouse_down( - point(px(95.), px(20.)), - MouseButton::Left, - Modifiers::default(), - ); - cx.simulate_mouse_move( - point(px(95.), px(70.)), - Some(MouseButton::Left), - Modifiers::default(), - ); - cx.simulate_mouse_up( - point(px(95.), px(70.)), - MouseButton::Left, - Modifiers::default(), - ); - - assert_eq!(handle.drag_starts.get(), 0); - assert_eq!(handle.drag_ends.get(), 0); - assert_eq!(handle.offset(), Point::default()); - } - - #[gpui::test] - fn hovering_reveals_scrollbar_for_track_interaction(cx: &mut TestAppContext) { - let (cx, handle) = harness( - cx, - ScrollbarAxis::Vertical, - ScrollbarMode::Hover, - size(px(100.), px(500.)), - ); - // Base ships no motion, so the reveal is immediate. - cx.simulate_mouse_move(point(px(95.), px(50.)), None, Modifiers::default()); - cx.run_until_parked(); - - cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); - assert!(handle.offset().y < px(0.)); - } - - #[gpui::test] - fn drag_notifications_are_throttled_and_deliver_the_latest_offset(cx: &mut TestAppContext) { - let handle = TestHandle::new(size(px(100.), px(1000.))); - let (view, cx) = cx.add_window_view({ - let handle = handle.clone(); - move |_, _| ScrollbarHarness { - handle, - axis: ScrollbarAxis::Vertical, - mode: ScrollbarMode::Always, - } - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - let observed = Rc::new(RefCell::new(Vec::new())); - let _subscription = cx.update(|_, cx| { - let observed = observed.clone(); - let handle = handle.clone(); - cx.observe(&view, move |_, _| { - observed.borrow_mut().push(handle.offset().y) - }) - }); - let state = ScrollbarState::default(); - let now = Instant::now(); - let interval = Duration::from_secs_f64(1. / 30.); - let mut inner = state.get().with_drag_pos(Axis::Vertical, Point::default()); - inner.last_update = now; - state.set(inner); - let update = |offset, elapsed, cx: &mut VisualTestContext| { - handle.set_offset(point(px(0.), px(offset))); - cx.update(|window, cx| { - state.notify_drag(now + elapsed, interval, view.entity_id(), window, cx) - }); - cx.run_until_parked(); - }; - update(-10., Duration::ZERO, cx); - cx.executor().advance_clock(Duration::from_millis(16)); - update(-20., Duration::from_millis(16), cx); - update(-30., Duration::from_millis(16), cx); - // Rendering at 120 Hz must not bypass the configured 30 Hz timer. - cx.update(|window, cx| { - window.simulate_next_frame(cx); - }); - cx.run_until_parked(); - assert!(observed.borrow().is_empty()); - cx.executor().advance_clock(Duration::from_millis(16)); - cx.run_until_parked(); - assert!(observed.borrow().is_empty()); - cx.executor().advance_clock(Duration::from_millis(2)); - cx.run_until_parked(); - assert_eq!( - *observed.borrow(), - vec![px(-30.)], - "one trailing notification must see the newest offset even when movement stops" - ); - - // A second burst gets its own interval, and release invalidates its timer. - let next = state.get().last_update; - handle.set_offset(point(px(0.), px(-40.))); - cx.update(|window, cx| state.notify_drag(next, interval, view.entity_id(), window, cx)); - cx.run_until_parked(); - state.set(state.get().with_unset_drag_pos(Instant::now())); - handle.set_offset(point(px(0.), px(-50.))); - cx.update(|_, cx| cx.notify(view.entity_id())); - assert_eq!(*observed.borrow(), vec![px(-30.), px(-50.)]); - cx.executor().advance_clock(interval); - cx.run_until_parked(); - assert_eq!( - *observed.borrow(), - vec![px(-30.), px(-50.)], - "release must not leave a stale trailing notification" - ); - } - - #[test] - fn full_track_thumb_does_not_reset_the_scroll_offset() { - let geometry = ThumbGeometry::new(px(20.), px(40.), px(500.), px(0.), px(4.), px(64.)); - let offset = point(px(0.), px(-100.)); - assert_eq!( - geometry.drag_offset( - Axis::Vertical, - point(px(0.), px(50.)), - point(px(0.), px(8.)), - offset - ), - offset - ); - } - - #[gpui::test] - fn repeated_touch_and_mouse_drags_keep_the_painted_grab_point(cx: &mut TestAppContext) { - struct Probe { - scrollbar: Scrollbar, - painted: Rc>>, - } - impl IntoElement for Probe { - type Element = Self; - fn into_element(self) -> Self { - self - } - } - impl Element for Probe { - type RequestLayoutState = (); - type PrepaintState = PrepaintState; - fn id(&self) -> Option { - Element::id(&self.scrollbar) - } - fn source_location(&self) -> Option<&'static Location<'static>> { - None - } - fn request_layout( - &mut self, - id: Option<&GlobalElementId>, - inspector: Option<&InspectorElementId>, - window: &mut Window, - cx: &mut App, - ) -> (LayoutId, ()) { - self.scrollbar.request_layout(id, inspector, window, cx) - } - fn prepaint( - &mut self, - id: Option<&GlobalElementId>, - inspector: Option<&InspectorElementId>, - bounds: Bounds, - layout: &mut (), - window: &mut Window, - cx: &mut App, - ) -> PrepaintState { - let state = self - .scrollbar - .prepaint(id, inspector, bounds, layout, window, cx); - self.painted.set(state.states[0].thumb_fill_bounds); - state - } - fn paint( - &mut self, - id: Option<&GlobalElementId>, - inspector: Option<&InspectorElementId>, - bounds: Bounds, - layout: &mut (), - state: &mut PrepaintState, - window: &mut Window, - cx: &mut App, - ) { - self.scrollbar - .paint(id, inspector, bounds, layout, state, window, cx); - } - } - struct Root { - handle: TestHandle, - painted: Rc>>, - axis: ScrollbarAxis, - viewport: Bounds, - } - impl Render for Root { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div().size(px(400.)).child(Probe { - scrollbar: Scrollbar::new(&self.handle) - .axis(self.axis) - .mode(ScrollbarMode::Always) - .viewport_bounds(self.viewport) - .styles(|style| { - style - .thumb(|style| style.inset(px(6.)).min_length(px(64.))) - .thumb_active(|style| style.inset(px(3.)).min_length(px(72.))) - }), - painted: self.painted.clone(), - }) - } - } - for touch in [true, false] { - for vertical in [true, false] { - for (origin, viewport_size, content_size) in [ - (Point::default(), 200., 1000.), - (point(px(30.), px(40.)), 240., 500.), - ] { - let handle = TestHandle::new(size(px(content_size), px(content_size))); - handle.set_offset(point(px(-100.), px(-100.))); - let painted = Rc::new(Cell::new(Bounds::default())); - let (_, cx) = cx.add_window_view({ - let handle = handle.clone(); - let painted = painted.clone(); - move |_, _| Root { - handle, - painted, - axis: if vertical { - ScrollbarAxis::Vertical - } else { - ScrollbarAxis::Both - }, - viewport: Bounds::new( - origin, - size(px(viewport_size), px(viewport_size)), - ), - } - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - let initial = painted.get(); - let start = initial.center(); - let grab = if vertical { - start.y - initial.origin.y - } else { - start.x - initial.origin.x - }; - let axis_delta = |value| { - if vertical { - point(px(0.), px(value)) - } else { - point(px(value), px(0.)) - } - }; - let axis_value = - |point: Point| if vertical { point.y } else { point.x }; - let started_position = if touch { start + axis_delta(5.) } else { start }; - if touch { - cx.simulate_event(TouchDragEvent { - phase: TouchPhase::Started, - start_position: start, - position: started_position, - }); - } else { - cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default()); - } - cx.update(|window, cx| window.draw(cx).clear(cx)); - assert!( - (axis_value(painted.get().origin) + grab - axis_value(started_position)) - .abs() - < px(0.1), - "starting must preserve the grab point and first displacement" - ); - let mut reference_offset = px(0.); - let mut offset_per_pixel = 0.; - for delta in [0., 24., -8., 32., -10., 8., 0.] { - let position = start + axis_delta(delta); - if touch { - cx.simulate_event(TouchDragEvent { - phase: TouchPhase::Moved, - start_position: start, - position, - }); - } else { - cx.simulate_mouse_move( - position, - Some(MouseButton::Left), - Modifiers::default(), - ); - } - cx.update(|window, cx| window.draw(cx).clear(cx)); - if delta == 0. { - reference_offset = axis_value(handle.offset()); - } - if delta == 24. { - offset_per_pixel = - (axis_value(handle.offset()) - reference_offset) / px(24.); - } - let actual = if vertical { - painted.get().origin.y + grab - } else { - painted.get().origin.x + grab - }; - let expected = if vertical { position.y } else { position.x }; - assert!( - (actual - expected).abs() < px(0.1), - "touch={touch} vertical={vertical} delta={delta}: painted grab {actual:?}, pointer {expected:?}" - ); - } - // Release contains a final displacement without an intervening move. - let expected_offset = reference_offset + px(12.) * offset_per_pixel; - if touch { - cx.simulate_event(TouchDragEvent { - phase: TouchPhase::Ended, - start_position: start, - position: start + axis_delta(12.), - }); - } else { - cx.simulate_mouse_up( - start + axis_delta(12.), - MouseButton::Left, - Modifiers::default(), - ); - } - assert!( - (axis_value(handle.offset()) - expected_offset).abs() < px(0.1), - "release must flush the last displacement" - ); - let released_offset = handle.offset(); - cx.update(|window, cx| window.draw(cx).clear(cx)); - assert_eq!( - handle.offset(), - released_offset, - "leaving active styling must not scroll" - ); - } - } - } - } - - #[gpui::test] - fn touch_thumb_drag_moves_down_and_cancel_releases_handle(cx: &mut TestAppContext) { - let (cx, handle) = harness( - cx, - ScrollbarAxis::Vertical, - ScrollbarMode::Always, - size(px(100.), px(500.)), - ); - let start_position = point(px(95.), px(20.)); - for (phase, position) in [ - (TouchPhase::Started, start_position), - (TouchPhase::Moved, point(px(95.), px(45.))), - (TouchPhase::Cancelled, point(px(95.), px(45.))), - ] { - cx.simulate_event(TouchDragEvent { - phase, - start_position, - position, - }); - } - assert!( - handle.offset().y < px(0.), - "thumb down must scroll toward later content" - ); - assert_eq!(handle.offset().x, px(0.)); - assert_eq!(handle.drag_starts.get(), 1); - assert_eq!(handle.drag_ends.get(), 1); - } - - #[gpui::test] - fn thumb_drag_notifies_handle_start_and_end(cx: &mut TestAppContext) { - let (cx, handle) = harness( - cx, - ScrollbarAxis::Vertical, - ScrollbarMode::Always, - size(px(100.), px(500.)), - ); - cx.simulate_mouse_down( - point(px(95.), px(20.)), - MouseButton::Left, - Modifiers::default(), - ); - cx.simulate_mouse_move( - point(px(95.), px(70.)), - Some(MouseButton::Left), - Modifiers::default(), - ); - cx.simulate_mouse_up( - point(px(95.), px(70.)), - MouseButton::Left, - Modifiers::default(), - ); - - assert_eq!(handle.drag_starts.get(), 1); - assert_eq!(handle.drag_ends.get(), 1); - } -} diff --git a/vendor/gpui-base/src/scrollbar/appearance.rs b/vendor/gpui-base/src/scrollbar/appearance.rs new file mode 100644 index 00000000..fff7f64b --- /dev/null +++ b/vendor/gpui-base/src/scrollbar/appearance.rs @@ -0,0 +1,400 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use crate::theme::ActiveTheme as _; +use gpui::{App, Background, Bounds, Hsla, Pixels, prelude::FluentBuilder, px}; + +const MIN_THUMB_SIZE: Pixels = px(48.); + +const THUMB_WIDTH: Pixels = px(6.); +const THUMB_RADIUS: Pixels = Pixels::ZERO; +const THUMB_INSET: Pixels = px(4.); + +const THUMB_ACTIVE_WIDTH: Pixels = px(8.); +const THUMB_ACTIVE_RADIUS: Pixels = Pixels::ZERO; +const THUMB_ACTIVE_INSET: Pixels = px(4.); + +pub(super) fn clamp_thumb_radius(radius: Pixels, bounds: Bounds) -> Pixels { + radius + .min(bounds.size.width / 2.) + .min(bounds.size.height / 2.) +} + +/// Paint-only styles for a scrollbar track. +#[derive(Clone, Default)] +pub struct ScrollbarTrackStyle { + background: Option, + border: Option, + width: Option, +} + +impl ScrollbarTrackStyle { + pub fn bg(mut self, background: Hsla) -> Self { + self.background = Some(background); + self + } + + pub fn border_color(mut self, border: Hsla) -> Self { + self.border = Some(border); + self + } + + pub fn width(mut self, width: impl Into) -> Self { + self.width = Some(width.into()); + self + } +} + +impl FluentBuilder for ScrollbarTrackStyle {} + +/// Paint-only styles for a scrollbar thumb. +#[derive(Clone, Default)] +pub struct ScrollbarThumbStyle { + background: Option, + width: Option, + inset: Option, + radius: Option, + min_length: Option, +} + +impl ScrollbarThumbStyle { + pub fn bg(mut self, background: impl Into) -> Self { + self.background = Some(background.into()); + self + } + + pub fn width(mut self, width: impl Into) -> Self { + self.width = Some(width.into()); + self + } + + pub fn inset(mut self, inset: impl Into) -> Self { + self.inset = Some(inset.into()); + self + } + + pub fn radius(mut self, radius: impl Into) -> Self { + self.radius = Some(radius.into()); + self + } + + pub fn min_length(mut self, min_length: impl Into) -> Self { + self.min_length = Some(min_length.into()); + self + } +} + +impl FluentBuilder for ScrollbarThumbStyle {} + +/// Typed paint styles supported by [`Scrollbar`](super::Scrollbar). +#[derive(Clone, Default)] +pub struct ScrollbarStyles { + track: ScrollbarTrackStyle, + track_hover: ScrollbarTrackStyle, + track_active: ScrollbarTrackStyle, + thumb: ScrollbarThumbStyle, + thumb_hover: ScrollbarThumbStyle, + thumb_active: ScrollbarThumbStyle, +} + +impl ScrollbarStyles { + pub fn track(mut self, build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle) -> Self { + self.track = build(self.track); + self + } + + pub fn track_hover( + mut self, + build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle, + ) -> Self { + self.track_hover = build(self.track_hover); + self + } + + pub fn track_active( + mut self, + build: impl FnOnce(ScrollbarTrackStyle) -> ScrollbarTrackStyle, + ) -> Self { + self.track_active = build(self.track_active); + self + } + + pub fn thumb(mut self, build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle) -> Self { + self.thumb = build(self.thumb); + self + } + + pub fn thumb_hover( + mut self, + build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle, + ) -> Self { + self.thumb_hover = build(self.thumb_hover); + self + } + + pub fn thumb_active( + mut self, + build: impl FnOnce(ScrollbarThumbStyle) -> ScrollbarThumbStyle, + ) -> Self { + self.thumb_active = build(self.thumb_active); + self + } +} + +impl FluentBuilder for ScrollbarStyles {} + +impl ScrollbarStyles { + pub(super) fn track_width(&self, cx: &App) -> Pixels { + self.track + .width + .or(cx.theme().scrollbar.styles().track.width) + .unwrap_or(super::WIDTH) + } + + fn resolve_track( + &self, + cx: &App, + state: &ScrollbarTrackStyle, + global_state: &ScrollbarTrackStyle, + default_border: Hsla, + ) -> (Hsla, Hsla) { + let theme = cx.theme(); + let global = theme.scrollbar.styles(); + ( + state + .background + .or(self.track.background) + .or(global_state.background) + .or(global.track.background) + .unwrap_or_else(gpui::transparent_black), + state + .border + .or(self.track.border) + .or(global_state.border) + .or(global.track.border) + .unwrap_or(default_border), + ) + } + + fn resolve_thumb( + &self, + cx: &App, + state: &ScrollbarThumbStyle, + global_state: &ScrollbarThumbStyle, + defaults: ScrollbarThumbStyle, + ) -> (Background, Pixels, Pixels, Pixels, Pixels) { + let theme = cx.theme(); + let global = theme.scrollbar.styles(); + ( + state + .background + .or(self.thumb.background) + .or(global_state.background) + .or(global.thumb.background) + .unwrap_or_else(|| defaults.background.unwrap()), + state + .width + .or(self.thumb.width) + .or(global_state.width) + .or(global.thumb.width) + .unwrap_or_else(|| defaults.width.unwrap()), + state + .inset + .or(self.thumb.inset) + .or(global_state.inset) + .or(global.thumb.inset) + .unwrap_or_else(|| defaults.inset.unwrap()), + state + .radius + .or(self.thumb.radius) + .or(global_state.radius) + .or(global.thumb.radius) + .unwrap_or_else(|| defaults.radius.unwrap()), + state + .min_length + .or(self.thumb.min_length) + .or(global_state.min_length) + .or(global.thumb.min_length) + .or(defaults.min_length) + .unwrap_or(MIN_THUMB_SIZE), + ) + } + + /// The thumb colour a scrollbar falls back to when nothing has overridden + /// it, taken from the active theme rather than fixed. + /// + /// It used to be literal black at these alphas. That reads as an ordinary + /// grey thumb on a light surface and as very nearly nothing at all on a + /// dark one, and no palette an application installed could change it: + /// `Theme` carries `scrollbar` beside `tokens` rather than derived from + /// them, so a theme swap moved every token except the ones the scrollbar + /// actually paints with. + /// + /// `foreground` is the token that already means "ink on this surface" and + /// already flips with the appearance, so on a light theme this stays within + /// a hair of the old constant and on a dark one it becomes visible. An + /// explicit `ScrollbarStyles` still wins: this is the bottom of the + /// cascade, not a new top of it. + fn thumb_default_background(cx: &App, alpha: f32) -> Background { + cx.theme().tokens.colors.foreground.alpha(alpha).into() + } + + fn thumb_defaults( + background: Background, + width: Pixels, + inset: Pixels, + radius: Pixels, + ) -> ScrollbarThumbStyle { + ScrollbarThumbStyle { + background: Some(background), + width: Some(width), + inset: Some(inset), + radius: Some(radius), + min_length: Some(MIN_THUMB_SIZE), + } + } + + pub(super) fn style_for_active( + &self, + cx: &App, + ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { + let theme = cx.theme(); + let global = theme.scrollbar.styles(); + let (track, border) = self.resolve_track( + cx, + &self.track_active, + &global.track_active, + gpui::transparent_black(), + ); + let (thumb, width, inset, radius, min_length) = self.resolve_thumb( + cx, + &self.thumb_active, + &global.thumb_active, + Self::thumb_defaults( + Self::thumb_default_background(cx, 0.55), + THUMB_ACTIVE_WIDTH, + THUMB_ACTIVE_INSET, + THUMB_ACTIVE_RADIUS, + ), + ); + (thumb, track, border, width, inset, radius, min_length) + } + + pub(super) fn style_for_hovered_thumb( + &self, + cx: &App, + ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { + let theme = cx.theme(); + let global = theme.scrollbar.styles(); + let (track, border) = self.resolve_track( + cx, + &self.track_active, + &global.track_active, + gpui::transparent_black(), + ); + let (thumb, width, inset, radius, min_length) = self.resolve_thumb( + cx, + &self.thumb_hover, + &global.thumb_hover, + Self::thumb_defaults( + Self::thumb_default_background(cx, 0.55), + THUMB_ACTIVE_WIDTH, + THUMB_ACTIVE_INSET, + THUMB_ACTIVE_RADIUS, + ), + ); + (thumb, track, border, width, inset, radius, min_length) + } + + pub(super) fn style_for_hovered_bar( + &self, + cx: &App, + ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { + let theme = cx.theme(); + let global = theme.scrollbar.styles(); + let (track, border) = self.resolve_track( + cx, + &self.track_hover, + &global.track_hover, + gpui::transparent_black(), + ); + let (thumb, width, inset, radius, min_length) = self.resolve_thumb( + cx, + &self.thumb, + &global.thumb, + Self::thumb_defaults( + Self::thumb_default_background(cx, 0.35), + THUMB_WIDTH, + THUMB_INSET, + THUMB_RADIUS, + ), + ); + (thumb, track, border, width, inset, radius, min_length) + } + + pub(super) fn style_for_normal( + &self, + cx: &App, + ) -> (Background, Hsla, Hsla, Pixels, Pixels, Pixels, Pixels) { + let theme = cx.theme(); + let global = theme.scrollbar.styles(); + + let (track, border) = + self.resolve_track(cx, &self.track, &global.track, gpui::transparent_black()); + let (thumb, width, inset, radius, min_length) = self.resolve_thumb( + cx, + &self.thumb, + &global.thumb, + Self::thumb_defaults( + Self::thumb_default_background(cx, 0.35), + THUMB_WIDTH, + THUMB_INSET, + THUMB_RADIUS, + ), + ); + (thumb, track, border, width, inset, radius, min_length) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn typed_styles_are_fluent_and_include_geometry() { + let track = gpui::hsla(0.1, 0.2, 0.3, 1.0); + let border = gpui::hsla(0.2, 0.3, 0.4, 1.0); + let thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0); + let hover = gpui::hsla(0.4, 0.5, 0.6, 1.0); + let active = gpui::hsla(0.5, 0.6, 0.7, 1.0); + let styles = ScrollbarStyles::default() + .track(|style| { + style + .width(px(14.)) + .bg(track) + .border_color(border) + .when(false, |style| style.width(px(99.))) + }) + .thumb(|style| { + style + .width(px(7.)) + .inset(px(3.)) + .radius(px(3.5)) + .min_length(px(40.)) + .bg(thumb) + }) + .thumb_hover(|style| style.width(px(9.)).bg(hover)) + .thumb_active(|style| style.radius(px(4.5)).bg(active)); + + assert_eq!(styles.track.background, Some(track)); + assert_eq!(styles.track.border, Some(border)); + assert_eq!(styles.track.width, Some(px(14.))); + assert!(styles.thumb.background.is_some()); + assert_eq!(styles.thumb.width, Some(px(7.))); + assert_eq!(styles.thumb.inset, Some(px(3.))); + assert_eq!(styles.thumb.radius, Some(px(3.5))); + assert_eq!(styles.thumb.min_length, Some(px(40.))); + assert!(styles.thumb_hover.background.is_some()); + assert_eq!(styles.thumb_hover.width, Some(px(9.))); + assert!(styles.thumb_active.background.is_some()); + assert_eq!(styles.thumb_active.radius, Some(px(4.5))); + } +} diff --git a/vendor/gpui-base/src/scrollbar/element.rs b/vendor/gpui-base/src/scrollbar/element.rs new file mode 100644 index 00000000..9c8ea162 --- /dev/null +++ b/vendor/gpui-base/src/scrollbar/element.rs @@ -0,0 +1,661 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use instant::{Duration, Instant}; + +use crate::{AxisExt, theme::ActiveTheme as _}; +use gpui::{ + Anchor, App, Axis, Background, BorderStyle, Bounds, ContentMask, CursorStyle, Edges, Element, + GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId, IsZero, LayoutId, + MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, Pixels, Position, ScrollWheelEvent, + Style, TouchDragEvent, TouchPhase, Window, fill, point, px, relative, size, +}; + +use super::motion::{ + hover_keeps_visible, tracks_thumb_hover, visibility_translation, wants_visible, +}; +use super::{ + Scrollbar, ScrollbarMode, ScrollbarState, ThumbGeometry, appearance::clamp_thumb_radius, +}; + +#[doc(hidden)] +pub struct PrepaintState { + hitbox: Hitbox, + scrollbar_state: ScrollbarState, + pub(super) states: Vec, +} + +#[doc(hidden)] +pub struct AxisPrepaintState { + axis: Axis, + bar_hitbox: Hitbox, + bounds: Bounds, + radius: Pixels, + bg: Hsla, + border: Hsla, + thumb_bounds: Bounds, + // Bounds of thumb to be rendered. + pub(super) thumb_fill_bounds: Bounds, + thumb_bg: Background, + geometry: ThumbGeometry, + active_geometry: ThumbGeometry, + track_width: Pixels, + visibility_opacity: f32, + visibility_position: f32, + visibility_requested: bool, +} + +impl Element for Scrollbar { + type RequestLayoutState = (); + type PrepaintState = PrepaintState; + + fn id(&self) -> Option { + Some(self.id.clone()) + } + + fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { + None + } + + fn request_layout( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + window: &mut Window, + cx: &mut App, + ) -> (LayoutId, Self::RequestLayoutState) { + let mut style = Style::default(); + style.position = Position::Absolute; + style.flex_grow = 1.0; + style.flex_shrink = 1.0; + style.size.width = relative(1.).into(); + style.size.height = relative(1.).into(); + + (window.request_layout(style, None, cx), ()) + } + + fn prepaint( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + bounds: Bounds, + _: &mut Self::RequestLayoutState, + window: &mut Window, + cx: &mut App, + ) -> Self::PrepaintState { + let bounds = self.resolved_viewport_bounds(bounds); + let hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| { + window.insert_hitbox(bounds, HitboxBehavior::Normal) + }); + + let state = window + .use_state(cx, |_, _| ScrollbarState::default()) + .read(cx) + .clone(); + + let now = cx.background_executor().now(); + let base_theme = cx.theme(); + let mode = self.mode.unwrap_or(base_theme.scrollbar.mode()); + let motion = base_theme.scrollbar.motion(); + // Always-visible scrollbars skip visibility motion but still animate + // their activity width. Reduced motion snaps every channel. + let reduce_motion = cx.reduce_motion(); + let (enter, exit) = if !mode.is_always() && !reduce_motion { + (motion.enter(), motion.exit()) + } else { + (Duration::ZERO, Duration::ZERO) + }; + let expand = if reduce_motion { + Duration::ZERO + } else { + motion.expand() + }; + + let mut inner = state.get(); + let current_offset = self.scroll_handle.offset(); + if current_offset != inner.last_scroll_offset { + inner = inner.with_last_scroll(current_offset, Some(now)); + } + + let is_hovered = inner.hovered_axis.is_some() || inner.hovered_on_thumb.is_some(); + let is_dragging = inner.dragged_axis.is_some(); + let is_currently_visible = inner.visibility.sample(now).opacity > 0.0; + let visible = hover_keeps_visible(mode, is_hovered, is_currently_visible) + || wants_visible( + mode, + is_hovered, + is_dragging, + inner.last_scroll_time, + motion.idle(), + now, + ); + inner.visibility.set_visible( + visible, + motion.entrance_for(mode, inner.hovered_on_thumb.is_some()), + enter, + exit, + now, + ); + let visibility = inner.visibility.sample(now); + state.request_visibility_redraw( + visibility.running, + visible, + inner.visibility.remaining(now), + now, + window, + cx, + ); + + if !is_hovered && !is_dragging { + if let Some(last_time) = inner.last_scroll_time { + let elapsed = now.saturating_duration_since(last_time); + if elapsed < motion.idle() && !inner.idle_timer_scheduled { + inner.idle_timer_scheduled = true; + let state = state.clone(); + let current_view = window.current_view(); + let next_delay = motion.idle() - elapsed; + window + .spawn(cx, async move |cx| { + cx.background_executor().timer(next_delay).await; + state.set(state.get().with_idle_timer_scheduled(false)); + cx.update(|_, cx| cx.notify(current_view)).ok(); + }) + .detach(); + } + } + } + state.set(inner); + + let mut states = vec![]; + let mut has_both = self.axis.is_both(); + let scroll_size = self + .scroll_size + .unwrap_or(self.scroll_handle.content_size()); + + for axis in self.axis.all().into_iter() { + let is_vertical = axis.is_vertical(); + let track_width = self.styles.track_width(cx); + let (scroll_area_size, container_size, scroll_position) = if is_vertical { + ( + scroll_size.height, + hitbox.size.height, + self.scroll_handle.offset().y, + ) + } else { + ( + scroll_size.width, + hitbox.size.width, + self.scroll_handle.offset().x, + ) + }; + + // The horizontal scrollbar is set avoid overlapping with the vertical scrollbar, if the vertical scrollbar is visible. + let margin_end = if has_both && !is_vertical { + track_width + } else { + px(0.) + }; + + // Hide scrollbar, if the scroll area is smaller than the container. + if scroll_area_size <= container_size { + has_both = false; + continue; + } + + let bounds = Bounds { + origin: if is_vertical { + point( + hitbox.origin.x + hitbox.size.width - track_width, + hitbox.origin.y, + ) + } else { + point( + hitbox.origin.x, + hitbox.origin.y + hitbox.size.height - track_width, + ) + }, + size: gpui::Size { + width: if is_vertical { + track_width + } else { + hitbox.size.width + }, + height: if is_vertical { + hitbox.size.height + } else { + track_width + }, + }, + }; + + let is_always_to_show = mode.is_always(); + let is_hover_to_show = mode.is_hover(); + let is_hovered_on_bar = state.get().hovered_axis == Some(axis); + let is_hovered_on_thumb = state.get().hovered_on_thumb == Some(axis); + + let (thumb_bg, bar_bg, bar_border, mut thumb_width, inset, radius, min_length) = + if state.get().dragged_axis == Some(axis) { + self.styles.style_for_active(cx) + } else if (is_hover_to_show || mode == ScrollbarMode::Scrolling) + && (is_hovered_on_bar || is_hovered_on_thumb) + { + if is_hovered_on_thumb { + self.styles.style_for_hovered_thumb(cx) + } else { + self.styles.style_for_hovered_bar(cx) + } + } else if is_always_to_show && (is_hovered_on_bar || is_hovered_on_thumb) { + if is_hovered_on_thumb { + self.styles.style_for_hovered_thumb(cx) + } else { + self.styles.style_for_hovered_bar(cx) + } + } else { + self.styles.style_for_normal(cx) + }; + + let mut width_animation = if is_vertical { + state.get().vertical_width + } else { + state.get().horizontal_width + }; + let (animated_width, running) = width_animation.set_target(thumb_width, expand, now); + let mut updated = state.get(); + if is_vertical { + updated.vertical_width = width_animation; + } else { + updated.horizontal_width = width_animation; + } + state.set(updated); + thumb_width = animated_width; + if running { + window.request_animation_frame(); + } + + let origin = if is_vertical { + bounds.origin.y + } else { + bounds.origin.x + }; + let geometry = ThumbGeometry::new( + origin, + container_size, + scroll_area_size, + margin_end, + inset, + min_length, + ); + let (_, _, _, _, active_inset, _, active_min_length) = self.styles.style_for_active(cx); + let active_geometry = ThumbGeometry::new( + origin, + container_size, + scroll_area_size, + margin_end, + active_inset, + active_min_length, + ); + let thumb_start = geometry.start(scroll_position) - origin; + + // The clickable area of the thumb + let thumb_length = geometry.length; + let thumb_bounds = if is_vertical { + Bounds::from_anchor_and_size( + Anchor::TopRight, + bounds.top_right() + point(-inset, thumb_start), + size(track_width, thumb_length), + ) + } else { + Bounds::from_anchor_and_size( + Anchor::BottomLeft, + bounds.bottom_left() + point(thumb_start, -inset), + size(thumb_length, track_width), + ) + }; + + // The actual render area of the thumb + let thumb_fill_bounds = if is_vertical { + Bounds::from_anchor_and_size( + Anchor::TopRight, + bounds.top_right() + point(-inset, thumb_start), + size(thumb_width, thumb_length), + ) + } else { + Bounds::from_anchor_and_size( + Anchor::BottomLeft, + bounds.bottom_left() + point(thumb_start, -inset), + size(thumb_length, thumb_width), + ) + }; + + let bar_hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| { + window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal) + }); + + states.push(AxisPrepaintState { + axis, + bar_hitbox, + bounds, + radius, + bg: bar_bg, + border: bar_border, + thumb_bounds, + thumb_fill_bounds, + thumb_bg, + geometry, + active_geometry, + track_width, + visibility_opacity: visibility.opacity, + visibility_position: visibility.position, + visibility_requested: visible, + }) + } + + PrepaintState { + hitbox, + states, + scrollbar_state: state, + } + } + + fn paint( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + _: Bounds, + _: &mut Self::RequestLayoutState, + prepaint: &mut Self::PrepaintState, + window: &mut Window, + cx: &mut App, + ) { + let scrollbar_state = &prepaint.scrollbar_state; + let theme = cx.theme(); + let mode = self.mode.unwrap_or(theme.scrollbar.mode()); + let view_id = window.current_view(); + let hitbox_bounds = prepaint.hitbox.bounds; + let is_hover_to_show = mode.is_hover(); + + window.with_content_mask( + Some(ContentMask { + bounds: hitbox_bounds, + }), + |window| { + for state in prepaint.states.iter() { + let axis = state.axis; + let mut radius = state.radius; + if theme.tokens.radius.md.is_zero() { + radius = px(0.); + } + radius = clamp_thumb_radius(radius, state.thumb_fill_bounds); + let bounds = state.bounds; + let thumb_bounds = state.thumb_bounds; + let geometry = state.geometry; + let active_geometry = state.active_geometry; + let is_vertical = axis.is_vertical(); + let visibility_opacity = state.visibility_opacity; + let is_visible = state.visibility_requested || visibility_opacity > 0.0; + let translation = + visibility_translation(axis, state.track_width, state.visibility_position); + let painted_bounds = state.bounds + translation; + let painted_thumb_bounds = state.thumb_fill_bounds + translation; + let painted_track_bg = state.bg.opacity(visibility_opacity); + let painted_border = state.border.opacity(visibility_opacity); + let painted_thumb_bg = state.thumb_bg.clone().opacity(visibility_opacity); + + window.set_cursor_style(CursorStyle::default(), &state.bar_hitbox); + + window.paint_layer(hitbox_bounds, |cx| { + cx.paint_quad(fill(painted_bounds, painted_track_bg)); + + cx.paint_quad(PaintQuad { + bounds: painted_bounds, + corner_radii: (0.).into(), + background: gpui::transparent_black().into(), + border_widths: if is_vertical { + Edges { + top: px(0.), + right: px(0.), + bottom: px(0.), + left: px(0.), + } + } else { + Edges { + top: px(0.), + right: px(0.), + bottom: px(0.), + left: px(0.), + } + }, + border_color: painted_border, + border_style: BorderStyle::default(), + }); + + cx.paint_quad( + fill(painted_thumb_bounds, painted_thumb_bg).corner_radii(radius), + ); + }); + + window.on_mouse_event({ + let state = scrollbar_state.clone(); + let scroll_handle = self.scroll_handle.clone(); + + move |event: &ScrollWheelEvent, phase, _, cx| { + if phase.bubble() && hitbox_bounds.contains(&event.position) { + if scroll_handle.offset() != state.get().last_scroll_offset { + state.set(state.get().with_last_scroll( + scroll_handle.offset(), + Some(cx.background_executor().now()), + )); + cx.notify(view_id); + } + } + } + }); + + // A thumb follows the finger, unlike content panning. Claim + // this touch before the window turns it into wheel deltas. + window.on_mouse_event({ + let state = scrollbar_state.clone(); + let scroll_handle = self.scroll_handle.clone(); + let max_fps_duration = Duration::from_secs_f64(1. / self.max_fps as f64); + move |event: &TouchDragEvent, phase, window, cx| { + if !phase.bubble() { + return; + } + if event.phase == TouchPhase::Started { + if !is_visible + || window.default_prevented() + || !thumb_bounds.contains(&event.start_position) + { + return; + } + scroll_handle.start_drag(); + state.set(state.get().with_drag_pos( + axis, + event.start_position - thumb_bounds.origin, + )); + } else if state.get().dragged_axis != Some(axis) { + return; + } + if event.phase != TouchPhase::Cancelled { + scroll_handle.set_offset(active_geometry.drag_offset( + axis, + event.position, + state.get().drag_pos, + scroll_handle.offset(), + )); + } + if matches!(event.phase, TouchPhase::Ended | TouchPhase::Cancelled) { + scroll_handle.end_drag(); + state.set( + state + .get() + .with_unset_drag_pos(cx.background_executor().now()), + ); + } + window.prevent_default(); + cx.stop_propagation(); + if event.phase == TouchPhase::Moved { + state.notify_drag( + Instant::now(), + max_fps_duration, + view_id, + window, + cx, + ); + } else { + cx.notify(view_id); + } + } + }); + + if is_visible { + window.on_mouse_event({ + let state = scrollbar_state.clone(); + let scroll_handle = self.scroll_handle.clone(); + + move |event: &MouseDownEvent, phase, _, cx| { + if phase.bubble() && bounds.contains(&event.position) { + cx.stop_propagation(); + + if thumb_bounds.contains(&event.position) { + // click on the thumb bar, set the drag position + let pos = event.position - thumb_bounds.origin; + + scroll_handle.start_drag(); + state.set(state.get().with_drag_pos(axis, pos)); + // Active styling can change the inset or minimum length. + // Keep the original grab point under the pointer on that frame. + scroll_handle.set_offset(active_geometry.drag_offset( + axis, + event.position, + pos, + scroll_handle.offset(), + )); + } else { + // click on the scrollbar, jump to the position + // Set the thumb bar center to the click position + let center = + point(geometry.length / 2., geometry.length / 2.); + scroll_handle.set_offset(geometry.drag_offset( + axis, + event.position, + center, + scroll_handle.offset(), + )); + } + + cx.notify(view_id); + } + } + }); + } + + window.on_mouse_event({ + let scroll_handle = self.scroll_handle.clone(); + let state = scrollbar_state.clone(); + let max_fps_duration = Duration::from_secs_f64(1. / self.max_fps as f64); + + move |event: &MouseMoveEvent, _, window, cx| { + let mut notify = false; + // When is hover to show mode or it was visible, + // we need to update the hovered state and increase the last_scroll_time. + let need_hover_to_update = is_hover_to_show || is_visible; + // Update hovered state for scrollbar + if bounds.contains(&event.position) && need_hover_to_update { + let hover_changed = state.get().hovered_axis != Some(axis); + state.set( + state + .get() + .with_hovered(Some(axis), cx.background_executor().now()), + ); + notify |= hover_changed; + } else if state.get().hovered_axis == Some(axis) { + state.set( + state + .get() + .with_hovered(None, cx.background_executor().now()), + ); + notify = true; + } + + // Update hovered state for scrollbar thumb + if tracks_thumb_hover(mode, is_visible) + && thumb_bounds.contains(&event.position) + { + if state.get().hovered_on_thumb != Some(axis) { + state.set(state.get().with_hovered_on_thumb( + Some(axis), + cx.background_executor().now(), + )); + notify = true; + } + } else { + if state.get().hovered_on_thumb == Some(axis) { + state.set(state.get().with_hovered_on_thumb( + None, + cx.background_executor().now(), + )); + notify = true; + } + } + + // Move thumb position on dragging + if state.get().dragged_axis == Some(axis) && event.dragging() { + // Stop the event propagation to avoid selecting text or other side effects. + cx.stop_propagation(); + + let offset = active_geometry.drag_offset( + axis, + event.position, + state.get().drag_pos, + scroll_handle.offset(), + ); + if scroll_handle.offset() != offset { + // Coalesce rendering, never discard the newest pointer position. + scroll_handle.set_offset(offset); + notify = true; + } + if notify { + state.notify_drag( + Instant::now(), + max_fps_duration, + view_id, + window, + cx, + ); + } + return; + } + + if notify { + cx.notify(view_id); + } + } + }); + + window.on_mouse_event({ + let state = scrollbar_state.clone(); + let scroll_handle = self.scroll_handle.clone(); + + move |event: &MouseUpEvent, phase, _, cx| { + if phase.bubble() && state.get().dragged_axis == Some(axis) { + scroll_handle.set_offset(active_geometry.drag_offset( + axis, + event.position, + state.get().drag_pos, + scroll_handle.offset(), + )); + scroll_handle.end_drag(); + state.set( + state + .get() + .with_unset_drag_pos(cx.background_executor().now()), + ); + cx.notify(view_id); + } + } + }); + } + }, + ); + } +} diff --git a/vendor/gpui-base/src/scrollbar/motion.rs b/vendor/gpui-base/src/scrollbar/motion.rs new file mode 100644 index 00000000..6a140307 --- /dev/null +++ b/vendor/gpui-base/src/scrollbar/motion.rs @@ -0,0 +1,711 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. + +use instant::{Duration, Instant}; + +use crate::{ + AxisExt, + animation::{ease_in_cubic, ease_out_cubic}, +}; +use gpui::{Axis, Pixels, Point, point, px}; + +use super::ScrollbarMode; + +/// How long visibility is held after the last activity, when the styled layer +/// projects no [`ScrollbarMotion`] of its own. +/// +/// This is a visibility hold rather than motion: without it [`ScrollbarMode::Scrolling`] +/// could never reveal the scrollbar. +const DEFAULT_IDLE: Duration = Duration::from_secs(2); + +#[derive(Debug, Clone, Copy)] +struct ScalarTransition { + from: T, + target: T, + started_at: Instant, + duration: Duration, +} + +impl ScalarTransition { + fn settled(value: T, now: Instant) -> Self { + Self { + from: value, + target: value, + started_at: now, + duration: Duration::ZERO, + } + } + + fn sample(&self, now: Instant, interpolate: impl FnOnce(T, T, f32) -> T) -> (T, bool) { + if self.from == self.target || self.duration.is_zero() { + return (self.target, false); + } + let linear = now.saturating_duration_since(self.started_at).as_secs_f32() + / self.duration.as_secs_f32(); + if linear >= 1.0 { + (self.target, false) + } else { + ( + interpolate(self.from, self.target, linear.clamp(0.0, 1.0)), + true, + ) + } + } + + fn remaining(&self, now: Instant) -> Duration { + if self.from == self.target { + return Duration::ZERO; + } + self.duration + .saturating_sub(now.saturating_duration_since(self.started_at)) + } + + fn start(&mut self, from: T, target: T, duration: Duration, now: Instant) { + self.from = from; + self.target = target; + self.started_at = now; + self.duration = duration; + } + + fn settle(&mut self, target: T, now: Instant) { + self.start(target, target, Duration::ZERO, now); + } +} + +#[derive(Debug, Clone, Copy)] +pub(super) struct WidthAnimation { + transition: ScalarTransition, + initialized: bool, +} + +impl WidthAnimation { + pub(super) fn new(now: Instant) -> Self { + Self { + transition: ScalarTransition::settled(Pixels::ZERO, now), + initialized: false, + } + } + + fn sample(&self, now: Instant) -> (Pixels, bool) { + self.transition.sample(now, |from, target, linear| { + from + (target - from) * ease_out_cubic(linear) + }) + } + + /// Move toward `target` over `duration`. A zero duration adopts the target + /// immediately, which is how reduced motion and a motionless theme arrive here. + pub(super) fn set_target( + &mut self, + target: Pixels, + duration: Duration, + now: Instant, + ) -> (Pixels, bool) { + if duration.is_zero() || !self.initialized { + self.transition.settle(target, now); + self.initialized = true; + } else if self.transition.target != target { + let from = self.sample(now).0; + self.transition.start(from, target, duration, now); + } + self.sample(now) + } +} + +/// How a scrollbar becomes visible. +/// +/// The styled layer chooses the choreography; Base only plays it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum ScrollbarEntrance { + /// Fade in without moving. + #[default] + Fade, + /// Slide in from the nearest edge while fading. + SlideAndFade, +} + +/// Motion tokens used by [`Scrollbar`](super::Scrollbar). +/// +/// Base installs no motion of its own: every transition duration defaults to +/// zero, so visibility and thumb width snap. Product timing belongs to the +/// styled layer, which projects it through [`crate::ScrollbarTheme`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ScrollbarMotion { + idle: Duration, + enter: Duration, + exit: Duration, + expand: Duration, + entrance: ScrollbarEntrance, + thumb_hover_entrance: ScrollbarEntrance, +} + +impl Default for ScrollbarMotion { + fn default() -> Self { + Self { + idle: DEFAULT_IDLE, + enter: Duration::ZERO, + exit: Duration::ZERO, + expand: Duration::ZERO, + entrance: ScrollbarEntrance::Fade, + thumb_hover_entrance: ScrollbarEntrance::Fade, + } + } +} + +impl ScrollbarMotion { + /// How long visibility is held after the last scroll, drag, or hover. + pub fn with_idle(mut self, idle: Duration) -> Self { + self.idle = idle; + self + } + + /// How long the scrollbar takes to become fully visible. + pub fn with_enter(mut self, enter: Duration) -> Self { + self.enter = enter; + self + } + + /// How long the scrollbar takes to fade away once the idle hold expires. + pub fn with_exit(mut self, exit: Duration) -> Self { + self.exit = exit; + self + } + + /// How long the thumb takes to reach a new width. + pub fn with_expand(mut self, expand: Duration) -> Self { + self.expand = expand; + self + } + + /// Which entrance choreography to play. + pub fn with_entrance(mut self, entrance: ScrollbarEntrance) -> Self { + self.entrance = entrance; + self + } + + /// Which entrance choreography to play when hover reveals the thumb. + pub fn with_thumb_hover_entrance(mut self, entrance: ScrollbarEntrance) -> Self { + self.thumb_hover_entrance = entrance; + self + } + + pub fn idle(&self) -> Duration { + self.idle + } + + pub fn enter(&self) -> Duration { + self.enter + } + + pub fn exit(&self) -> Duration { + self.exit + } + + pub fn expand(&self) -> Duration { + self.expand + } + + pub fn entrance(&self) -> ScrollbarEntrance { + self.entrance + } + + pub fn thumb_hover_entrance(&self) -> ScrollbarEntrance { + self.thumb_hover_entrance + } + + pub(super) fn entrance_for( + &self, + mode: ScrollbarMode, + thumb_hovered: bool, + ) -> ScrollbarEntrance { + if mode.is_hover() && thumb_hovered { + self.thumb_hover_entrance + } else { + self.entrance + } + } +} + +#[derive(Debug, Clone, Copy)] +pub(super) struct VisibilityAnimation { + opacity: ScalarTransition, + position: ScalarTransition, + entrance: ScrollbarEntrance, +} + +#[derive(Debug, Clone, Copy)] +pub(super) struct VisibilitySample { + pub(super) opacity: f32, + pub(super) position: f32, + pub(super) running: bool, +} + +impl VisibilityAnimation { + pub(super) fn hidden(now: Instant) -> Self { + Self { + opacity: ScalarTransition::settled(0.0, now), + position: ScalarTransition::settled(0.0, now), + entrance: ScrollbarEntrance::Fade, + } + } + + pub(super) fn sample(&self, now: Instant) -> VisibilitySample { + let entering = + self.opacity.target > self.opacity.from || self.position.target > self.position.from; + let (opacity, opacity_running) = self.opacity.sample(now, |from, target, linear| { + let factor = if entering { + linear + } else { + ease_in_cubic(linear) + }; + from + (target - from) * factor + }); + let (position, position_running) = self.position.sample(now, |from, target, linear| { + let factor = if entering { + ease_out_cubic(linear) + } else { + ease_in_cubic(linear) + }; + from + (target - from) * factor + }); + + VisibilitySample { + opacity, + position, + running: opacity_running || position_running, + } + } + + pub(super) fn remaining(&self, now: Instant) -> Duration { + self.opacity + .remaining(now) + .max(self.position.remaining(now)) + } + + /// Reverse or start a transition toward `visible`. + /// + /// The leg runs for `enter` or `exit` scaled by the distance still to cover, + /// so an interrupted transition keeps its speed instead of restarting. + pub(super) fn set_visible( + &mut self, + visible: bool, + entrance: ScrollbarEntrance, + enter: Duration, + exit: Duration, + now: Instant, + ) { + let target = if visible { 1.0 } else { 0.0 }; + let full_duration = if visible { enter } else { exit }; + if full_duration.is_zero() { + // A motionless policy — reduced motion, an always-visible scrollbar, + // or a theme that projects no motion — adopts the target outright, + // even if a transition was in flight when the policy changed. + self.opacity.settle(target, now); + self.position.settle(target, now); + self.entrance = entrance; + return; + } + if self.opacity.target == target + && self.position.target == target + && self.entrance == entrance + { + return; + } + + let sample = self.sample(now); + let from_position = if visible && entrance == ScrollbarEntrance::Fade { + 1.0 + } else { + sample.position + }; + let distance = (target - sample.opacity) + .abs() + .max((target - from_position).abs()); + let duration = full_duration.mul_f32(distance); + self.opacity.start(sample.opacity, target, duration, now); + self.position.start(from_position, target, duration, now); + self.entrance = entrance; + } +} + +pub(super) fn visibility_translation( + axis: Axis, + track_width: Pixels, + progress: f32, +) -> Point { + let offset = track_width * (1.0 - progress.clamp(0.0, 1.0)); + if axis.is_vertical() { + point(offset, px(0.)) + } else { + point(px(0.), offset) + } +} + +pub(super) fn wants_visible( + mode: ScrollbarMode, + is_hovered: bool, + is_dragging: bool, + last_scroll_time: Option, + idle: Duration, + now: Instant, +) -> bool { + mode.is_always() + || is_dragging + || (mode.is_hover() && is_hovered) + || last_scroll_time.is_some_and(|last| now.saturating_duration_since(last) < idle) +} + +pub(super) fn tracks_thumb_hover(mode: ScrollbarMode, is_visible: bool) -> bool { + mode.is_hover() || is_visible +} + +pub(super) fn hover_keeps_visible( + mode: ScrollbarMode, + is_hovered: bool, + is_currently_visible: bool, +) -> bool { + is_hovered && (mode.is_hover() || (mode == ScrollbarMode::Scrolling && is_currently_visible)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scrollbar::ScrollbarState; + /// Timing standing in for what a styled layer projects. Base itself ships + /// none of these; see [`motionless_base_snaps_every_transition`]. + const ENTER: Duration = Duration::from_millis(300); + const EXIT: Duration = Duration::from_millis(500); + const EXPAND: Duration = Duration::from_millis(300); + + #[test] + fn visibility_animation_uses_direction_specific_curves_and_durations() { + let start = Instant::now(); + let mut animation = VisibilityAnimation::hidden(start); + + animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); + assert_eq!(animation.sample(start).opacity, 0.0); + let entering = animation.sample(start + ENTER / 2).position; + assert!(entering > 0.5, "ease-out must advance quickly"); + let entered = animation.sample(start + ENTER); + assert_eq!(entered.opacity, 1.0); + assert_eq!(entered.position, 1.0); + + animation.set_visible( + false, + ScrollbarEntrance::SlideAndFade, + ENTER, + EXIT, + start + ENTER, + ); + let exiting = animation.sample(start + ENTER + EXIT / 2).opacity; + assert!(exiting > 0.5, "ease-in must remain visible early in exit"); + assert_eq!(animation.sample(start + ENTER + EXIT).opacity, 0.0); + } + + #[test] + fn entrance_fades_linearly_while_position_eases_out() { + let start = Instant::now(); + let mut animation = VisibilityAnimation::hidden(start); + animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); + + let halfway = animation.sample(start + ENTER / 2); + assert!((halfway.opacity - 0.5).abs() < 0.001); + assert!(halfway.position > halfway.opacity); + } + + #[test] + fn fade_entrance_snaps_position_and_animates_opacity() { + let start = Instant::now(); + let mut animation = VisibilityAnimation::hidden(start); + animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, start); + + let initial = animation.sample(start); + assert_eq!(initial.opacity, 0.0); + assert_eq!(initial.position, 1.0); + let halfway = animation.sample(start + ENTER / 2); + assert!((halfway.opacity - 0.5).abs() < 0.001); + assert_eq!(halfway.position, 1.0); + } + + #[test] + fn active_visibility_adopts_a_changed_entrance_policy() { + let start = Instant::now(); + let halfway = start + ENTER / 2; + let mut animation = VisibilityAnimation::hidden(start); + animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); + let before = animation.sample(halfway); + + animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, halfway); + let after = animation.sample(halfway); + + assert_eq!( + after.opacity, before.opacity, + "policy changes must not flash" + ); + assert_eq!(after.position, 1.0, "fade entrance must stop stale sliding"); + } + + #[test] + fn base_ships_no_motion_of_its_own() { + let motion = ScrollbarMotion::default(); + assert_eq!(motion.enter(), Duration::ZERO); + assert_eq!(motion.exit(), Duration::ZERO); + assert_eq!(motion.expand(), Duration::ZERO); + assert_eq!(motion.entrance(), ScrollbarEntrance::Fade); + assert_eq!(motion.thumb_hover_entrance(), ScrollbarEntrance::Fade); + assert_eq!( + motion.idle(), + DEFAULT_IDLE, + "the visibility hold is behavior, not motion, and must stay usable" + ); + } + + #[test] + fn hover_mode_slides_only_when_the_thumb_is_hovered() { + let motion = ScrollbarMotion::default() + .with_entrance(ScrollbarEntrance::Fade) + .with_thumb_hover_entrance(ScrollbarEntrance::SlideAndFade); + + assert_eq!( + motion.entrance_for(ScrollbarMode::Hover, false), + ScrollbarEntrance::Fade + ); + assert_eq!( + motion.entrance_for(ScrollbarMode::Hover, true), + ScrollbarEntrance::SlideAndFade + ); + assert_eq!( + motion.entrance_for(ScrollbarMode::Scrolling, true), + ScrollbarEntrance::Fade + ); + } + + #[test] + fn hidden_scrolling_mode_does_not_track_thumb_hover() { + assert!(!tracks_thumb_hover(ScrollbarMode::Scrolling, false)); + assert!(tracks_thumb_hover(ScrollbarMode::Scrolling, true)); + assert!(tracks_thumb_hover(ScrollbarMode::Hover, false)); + } + + #[test] + fn visible_scrolling_mode_stays_visible_while_hovered() { + assert!(!hover_keeps_visible(ScrollbarMode::Scrolling, true, false)); + assert!(hover_keeps_visible(ScrollbarMode::Scrolling, true, true)); + assert!(hover_keeps_visible(ScrollbarMode::Hover, true, false)); + } + + #[test] + fn motionless_base_snaps_every_transition() { + let now = Instant::now(); + let motion = ScrollbarMotion::default(); + let mut visibility = VisibilityAnimation::hidden(now); + + visibility.set_visible(true, motion.entrance(), motion.enter(), motion.exit(), now); + let shown = visibility.sample(now); + assert_eq!(shown.opacity, 1.0); + assert_eq!(shown.position, 1.0); + assert!(!shown.running, "a motionless theme must request no frames"); + assert_eq!( + visibility_translation(Axis::Vertical, px(16.), shown.position), + Point::default() + ); + + visibility.set_visible(false, motion.entrance(), motion.enter(), motion.exit(), now); + let hidden = visibility.sample(now); + assert_eq!(hidden.opacity, 0.0); + assert_eq!(hidden.position, 0.0); + assert!(!hidden.running); + + let mut width = WidthAnimation::new(now); + assert_eq!( + width.set_target(px(8.), motion.expand(), now), + (px(8.), false) + ); + } + + #[test] + fn a_zero_duration_settles_a_transition_already_in_flight() { + let start = Instant::now(); + let mut animation = VisibilityAnimation::hidden(start); + animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); + + // Reduced motion turns on midway through the entrance. + let midway = start + ENTER / 2; + animation.set_visible( + true, + ScrollbarEntrance::SlideAndFade, + Duration::ZERO, + Duration::ZERO, + midway, + ); + let settled = animation.sample(midway); + assert_eq!(settled.opacity, 1.0); + assert_eq!(settled.position, 1.0); + assert!(!settled.running); + } + + #[test] + fn thumb_expansion_animates_in_both_directions() { + let start = Instant::now(); + let mut animation = WidthAnimation::new(start); + assert_eq!(animation.set_target(px(6.), EXPAND, start), (px(6.), false)); + + let (initial, running) = animation.set_target(px(8.), EXPAND, start); + assert_eq!(initial, px(6.)); + assert!(running); + let (expanded_halfway, _) = animation.sample(start + EXPAND / 2); + assert!(expanded_halfway > px(7.)); + + let reversal = start + EXPAND / 2; + let before = animation.sample(reversal).0; + let (after_reversal, running) = animation.set_target(px(6.), EXPAND, reversal); + assert_eq!(after_reversal, before); + assert!(running); + assert_eq!(animation.sample(reversal + EXPAND).0, px(6.)); + } + + #[test] + fn reduced_motion_snaps_thumb_expansion() { + let now = Instant::now(); + let mut animation = WidthAnimation::new(now); + assert_eq!( + animation.set_target(px(8.), Duration::ZERO, now), + (px(8.), false) + ); + } + + #[test] + fn visibility_translation_moves_toward_the_nearest_edge() { + assert_eq!( + visibility_translation(Axis::Vertical, px(16.), 0.0), + point(px(16.), px(0.)) + ); + assert_eq!( + visibility_translation(Axis::Horizontal, px(16.), 0.0), + point(px(0.), px(16.)) + ); + assert_eq!( + visibility_translation(Axis::Vertical, px(16.), 1.0), + Point::default() + ); + } + + #[test] + fn visibility_animation_reverses_from_current_progress() { + let start = Instant::now(); + let mut animation = VisibilityAnimation::hidden(start); + animation.set_visible(true, ScrollbarEntrance::SlideAndFade, ENTER, EXIT, start); + let reversal_time = start + Duration::from_millis(60); + let before = animation.sample(reversal_time); + + animation.set_visible( + false, + ScrollbarEntrance::SlideAndFade, + ENTER, + EXIT, + reversal_time, + ); + let reversed = animation.sample(reversal_time); + assert_eq!(reversed.opacity, before.opacity); + assert_eq!(reversed.position, before.position); + let after = animation.sample(reversal_time + Duration::from_millis(10)); + assert!(after.opacity < before.opacity); + assert!(after.position < before.position); + } + + #[test] + fn always_hover_drag_and_recent_scroll_request_visibility() { + let now = Instant::now(); + let idle = DEFAULT_IDLE; + assert!(wants_visible( + ScrollbarMode::Always, + false, + false, + None, + idle, + now + )); + assert!(wants_visible( + ScrollbarMode::Hover, + true, + false, + None, + idle, + now + )); + assert!(wants_visible( + ScrollbarMode::Scrolling, + false, + true, + None, + idle, + now + )); + assert!(wants_visible( + ScrollbarMode::Scrolling, + false, + false, + Some(now - idle + Duration::from_millis(1)), + idle, + now, + )); + assert!(!wants_visible( + ScrollbarMode::Scrolling, + false, + false, + Some(now - idle), + idle, + now, + )); + + let mut settled = VisibilityAnimation::hidden(now - ENTER); + settled.set_visible( + true, + ScrollbarEntrance::SlideAndFade, + ENTER, + EXIT, + now - ENTER, + ); + assert!(!settled.sample(now).running, "idle hold must not animate"); + } + + #[test] + fn leaving_hover_starts_a_fresh_idle_hold() { + let entered_at = Instant::now(); + let left_at = entered_at + Duration::from_secs(5); + let state = ScrollbarState::default().get(); + + let hovered = state.with_hovered(Some(Axis::Vertical), entered_at); + assert_eq!(hovered.last_scroll_time, Some(entered_at)); + let left = hovered.with_hovered(None, left_at); + assert_eq!(left.last_scroll_time, Some(left_at)); + assert!(wants_visible( + ScrollbarMode::Hover, + false, + false, + left.last_scroll_time, + DEFAULT_IDLE, + left_at + DEFAULT_IDLE - Duration::from_millis(1), + )); + } + + #[test] + fn idle_boundary_starts_the_exit_without_a_jump() { + let activity = Instant::now(); + let exit_start = activity + DEFAULT_IDLE; + let mut animation = VisibilityAnimation::hidden(activity - ENTER); + animation.set_visible(true, ScrollbarEntrance::Fade, ENTER, EXIT, activity - ENTER); + assert!(!wants_visible( + ScrollbarMode::Scrolling, + false, + false, + Some(activity), + DEFAULT_IDLE, + exit_start, + )); + + animation.set_visible(false, ScrollbarEntrance::Fade, ENTER, EXIT, exit_start); + let start = animation.sample(exit_start); + assert_eq!(start.opacity, 1.0); + assert_eq!(start.position, 1.0); + assert_eq!(animation.sample(exit_start + EXIT).opacity, 0.0); + } +} diff --git a/vendor/gpui-base/src/scrollbar/redraw.rs b/vendor/gpui-base/src/scrollbar/redraw.rs new file mode 100644 index 00000000..25b96df9 --- /dev/null +++ b/vendor/gpui-base/src/scrollbar/redraw.rs @@ -0,0 +1,86 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. +//! Frame sampling and bounded wakeups for a single passive fade. + +use gpui::{App, Task, Window}; +use instant::{Duration, Instant}; + +const FADE_INTERVAL: Duration = Duration::from_nanos(16_666_667); +const FAST_FRAME_INTERVAL: Duration = Duration::from_millis(15); + +#[derive(Debug, Default)] +pub(super) struct FadeRedraw { + phase: Phase, + frame_pending: bool, +} + +#[derive(Debug, Default)] +enum Phase { + #[default] + Idle, + Sampling { + previous: Instant, + fast: u8, + }, + Paced { + deadline: Instant, + _task: Task<()>, + }, +} + +impl FadeRedraw { + /// Returns true when the caller must register the platform callback. + pub(super) fn schedule( + &mut self, + now: Instant, + remaining: Duration, + window: &mut Window, + cx: &mut App, + ) -> bool { + if matches!(self.phase, Phase::Idle) { + self.phase = Phase::Sampling { + previous: now, + fast: 0, + }; + } + match self.phase { + Phase::Sampling { fast, .. } if fast < 2 => { + return !std::mem::replace(&mut self.frame_pending, true); + } + Phase::Paced { deadline, .. } if now < deadline => return false, + _ => {} + } + + let wait = remaining.min(FADE_INTERVAL); + let timer = cx.background_executor().timer(wait); + let view = window.current_view(); + let task = window.spawn(cx, async move |cx| { + timer.await; + cx.update(|_, cx| cx.notify(view)).ok(); + }); + self.phase = Phase::Paced { + deadline: now + wait, + _task: task, + }; + false + } + + pub(super) fn frame_delivered(&mut self, now: Instant) -> bool { + self.frame_pending = false; + let Phase::Sampling { previous, fast } = &mut self.phase else { + return false; + }; + // Count actual platform callbacks. Extra layouts during a frame and a + // single short interval do not switch a 60 Hz window to timer wakes. + if now.saturating_duration_since(*previous) < FAST_FRAME_INTERVAL { + *fast += 1; + } else { + *fast = 0; + } + *previous = now; + true + } + + pub(super) fn cancel(&mut self) { + self.phase = Phase::Idle; + } +} diff --git a/vendor/gpui-base/src/scrollbar/tests.rs b/vendor/gpui-base/src/scrollbar/tests.rs new file mode 100644 index 00000000..3021b179 --- /dev/null +++ b/vendor/gpui-base/src/scrollbar/tests.rs @@ -0,0 +1,751 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. +use super::appearance::clamp_thumb_radius; +use super::element::PrepaintState; +use super::*; +use std::cell::RefCell; + +use gpui::{ + Background, Context, Element, GlobalElementId, InspectorElementId, LayoutId, Modifiers, + MouseButton, ParentElement as _, Render, Styled as _, TestAppContext, TouchDragEvent, + TouchPhase, VisualTestContext, div, size, +}; + +#[test] +fn thumb_radius_is_limited_by_its_actual_bounds() { + let vertical_thumb = Bounds::new(Point::default(), size(px(8.), px(80.))); + let horizontal_thumb = Bounds::new(Point::default(), size(px(80.), px(6.))); + + assert_eq!(clamp_thumb_radius(px(6.), vertical_thumb), px(4.)); + assert_eq!(clamp_thumb_radius(px(6.), horizontal_thumb), px(3.)); + assert_eq!( + clamp_thumb_radius(Pixels::ZERO, vertical_thumb), + Pixels::ZERO + ); +} + +#[derive(Clone)] +struct TestHandle { + offset: Rc>>, + content_size: Size, + drag_starts: Rc>, + drag_ends: Rc>, +} + +impl TestHandle { + fn new(content_size: Size) -> Self { + Self { + offset: Rc::new(Cell::new(Point::default())), + content_size, + drag_starts: Rc::new(Cell::new(0)), + drag_ends: Rc::new(Cell::new(0)), + } + } +} + +impl ScrollbarHandle for TestHandle { + fn viewport_bounds(&self) -> Bounds { + Bounds::new(Point::default(), size(px(100.), px(100.))) + } + + fn offset(&self) -> Point { + self.offset.get() + } + + fn set_offset(&self, offset: Point) { + self.offset.set(offset); + } + + fn content_size(&self) -> Size { + self.content_size + } + + fn start_drag(&self) { + self.drag_starts.set(self.drag_starts.get() + 1); + } + + fn end_drag(&self) { + self.drag_ends.set(self.drag_ends.get() + 1); + } +} + +struct ScrollbarHarness { + handle: TestHandle, + axis: ScrollbarAxis, + mode: ScrollbarMode, +} + +impl Render for ScrollbarHarness { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .relative() + .size(px(100.)) + .child(Scrollbar::new(&self.handle).axis(self.axis).mode(self.mode)) + } +} + +fn harness( + cx: &mut TestAppContext, + axis: ScrollbarAxis, + mode: ScrollbarMode, + content_size: Size, +) -> (&mut VisualTestContext, TestHandle) { + let handle = TestHandle::new(content_size); + let (_, cx) = cx.add_window_view({ + let handle = handle.clone(); + move |_, _| ScrollbarHarness { handle, axis, mode } + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + (cx, handle) +} + +#[test] +fn explicit_viewport_bounds_override_handle_bounds() { + let expected = Bounds::new(point(px(12.), px(24.)), size(px(240.), px(96.))); + let scrollbar = + Scrollbar::vertical(&TestHandle::new(size(px(240.), px(480.)))).viewport_bounds(expected); + + assert_eq!( + scrollbar.resolved_viewport_bounds(Bounds::default()), + expected + ); +} + +#[test] +fn layout_viewport_uses_current_element_bounds() { + let expected = Bounds::new(point(px(20.), px(30.)), size(px(180.), px(12.))); + let scrollbar = + Scrollbar::horizontal(&TestHandle::new(size(px(600.), px(12.)))).viewport_from_layout(); + + assert_eq!(scrollbar.resolved_viewport_bounds(expected), expected); +} + +#[gpui::test] +fn unstyled_thumb_follows_the_theme_rather_than_a_fixed_colour(cx: &mut TestAppContext) { + cx.update(|cx| { + let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())); + + let light = gpui::hsla(0., 0., 0.04, 1.0); + crate::Theme::global_mut(cx).tokens.colors.foreground = light; + let (on_light, ..) = scrollbar.styles.style_for_normal(cx); + + let dark = gpui::hsla(0., 0., 0.98, 1.0); + crate::Theme::global_mut(cx).tokens.colors.foreground = dark; + let (on_dark, ..) = scrollbar.styles.style_for_normal(cx); + + assert_eq!(on_light, Background::from(light.alpha(0.35))); + assert_eq!(on_dark, Background::from(dark.alpha(0.35))); + // The point of the change: a thumb that never moved with the + // palette was invisible on one of the two surfaces. + assert_ne!(on_light, on_dark); + }); +} + +#[gpui::test] +fn a_styled_thumb_still_beats_the_theme_derived_default(cx: &mut TestAppContext) { + cx.update(|cx| { + let chosen = gpui::hsla(0.6, 0.5, 0.5, 1.0); + crate::Theme::global_mut(cx).tokens.colors.foreground = gpui::hsla(0., 0., 0.98, 1.0); + + let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())) + .styles(|styles| styles.thumb(|style| style.bg(chosen))); + let (thumb, ..) = scrollbar.styles.style_for_normal(cx); + + assert_eq!(thumb, Background::from(chosen)); + }); +} + +#[gpui::test] +fn instance_styles_override_theme_scrollbar_defaults(cx: &mut TestAppContext) { + cx.update(|cx| { + let theme_track = gpui::hsla(0.1, 0.2, 0.3, 1.0); + let theme_thumb = gpui::hsla(0.2, 0.3, 0.4, 1.0); + let instance_thumb = gpui::hsla(0.3, 0.4, 0.5, 1.0); + + crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new() + .with_mode(ScrollbarMode::Always) + .with_motion(ScrollbarMotion::default()) + .with_styles( + ScrollbarStyles::default() + .track(|style| style.width(px(13.)).bg(theme_track)) + .thumb(|style| style.width(px(7.)).bg(theme_thumb)), + ); + + let scrollbar = Scrollbar::new(&TestHandle::new(Size::default())) + .styles(|styles| styles.thumb(|style| style.bg(instance_thumb))); + let (thumb, track, _, width, _, _, _) = scrollbar.styles.style_for_normal(cx); + + assert_eq!(thumb, Background::from(instance_thumb)); + assert_eq!(track, theme_track); + assert_eq!(width, px(7.)); + assert_eq!(scrollbar.styles.track_width(cx), px(13.)); + }); +} + +#[gpui::test] +fn auto_hide_modes_use_a_six_pixel_resting_thumb(cx: &mut TestAppContext) { + cx.update(|cx| { + let handle = TestHandle::new(Size::default()); + let scrolling = Scrollbar::new(&handle).mode(ScrollbarMode::Scrolling); + let always = Scrollbar::new(&handle).mode(ScrollbarMode::Always); + + assert_eq!(scrolling.styles.style_for_normal(cx).3, px(6.)); + assert_eq!(always.styles.style_for_normal(cx).3, px(6.)); + }); +} + +#[gpui::test] +fn every_mode_expands_only_for_thumb_hover(cx: &mut TestAppContext) { + cx.update(|cx| { + let handle = TestHandle::new(Size::default()); + for mode in [ + ScrollbarMode::Scrolling, + ScrollbarMode::Hover, + ScrollbarMode::Always, + ] { + let scrollbar = Scrollbar::new(&handle).mode(mode); + assert_eq!(scrollbar.styles.style_for_normal(cx).3, px(6.)); + assert_eq!(scrollbar.styles.style_for_hovered_bar(cx).3, px(6.)); + assert_eq!(scrollbar.styles.style_for_hovered_thumb(cx).3, px(8.)); + } + }); +} + +#[gpui::test] +fn vertical_track_click_updates_vertical_offset(cx: &mut TestAppContext) { + let (cx, vertical) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Always, + size(px(100.), px(500.)), + ); + cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); + assert!(vertical.offset().y < px(0.)); + assert_eq!(vertical.offset().x, px(0.)); +} + +#[gpui::test] +fn horizontal_track_click_updates_horizontal_offset(cx: &mut TestAppContext) { + let (cx, horizontal) = harness( + cx, + ScrollbarAxis::Horizontal, + ScrollbarMode::Always, + size(px(500.), px(100.)), + ); + cx.simulate_click(point(px(80.), px(95.)), Modifiers::default()); + assert!(horizontal.offset().x < px(0.)); + assert_eq!(horizontal.offset().y, px(0.)); +} + +#[gpui::test] +fn no_overflow_has_no_interactive_track(cx: &mut TestAppContext) { + let (cx, handle) = harness( + cx, + ScrollbarAxis::Both, + ScrollbarMode::Always, + size(px(100.), px(100.)), + ); + cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); + assert_eq!(handle.offset(), Point::default()); +} + +#[gpui::test] +fn hidden_hover_scrollbar_ignores_track_click(cx: &mut TestAppContext) { + let (cx, handle) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Hover, + size(px(100.), px(500.)), + ); + cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); + assert_eq!(handle.offset(), Point::default()); +} + +#[gpui::test] +fn hidden_hover_scrollbar_ignores_thumb_drag(cx: &mut TestAppContext) { + let (cx, handle) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Hover, + size(px(100.), px(500.)), + ); + cx.simulate_mouse_down( + point(px(95.), px(20.)), + MouseButton::Left, + Modifiers::default(), + ); + cx.simulate_mouse_move( + point(px(95.), px(70.)), + Some(MouseButton::Left), + Modifiers::default(), + ); + cx.simulate_mouse_up( + point(px(95.), px(70.)), + MouseButton::Left, + Modifiers::default(), + ); + + assert_eq!(handle.drag_starts.get(), 0); + assert_eq!(handle.drag_ends.get(), 0); + assert_eq!(handle.offset(), Point::default()); +} + +#[gpui::test] +fn hovering_reveals_scrollbar_for_track_interaction(cx: &mut TestAppContext) { + let (cx, handle) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Hover, + size(px(100.), px(500.)), + ); + // Base ships no motion, so the reveal is immediate. + cx.simulate_mouse_move(point(px(95.), px(50.)), None, Modifiers::default()); + cx.run_until_parked(); + + cx.simulate_click(point(px(95.), px(80.)), Modifiers::default()); + assert!(handle.offset().y < px(0.)); +} + +#[gpui::test] +fn drag_notifications_are_throttled_and_deliver_the_latest_offset(cx: &mut TestAppContext) { + let handle = TestHandle::new(size(px(100.), px(1000.))); + let (view, cx) = cx.add_window_view({ + let handle = handle.clone(); + move |_, _| ScrollbarHarness { + handle, + axis: ScrollbarAxis::Vertical, + mode: ScrollbarMode::Always, + } + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let observed = Rc::new(RefCell::new(Vec::new())); + let _subscription = cx.update(|_, cx| { + let observed = observed.clone(); + let handle = handle.clone(); + cx.observe(&view, move |_, _| { + observed.borrow_mut().push(handle.offset().y) + }) + }); + let state = ScrollbarState::default(); + let now = Instant::now(); + let interval = Duration::from_secs_f64(1. / 30.); + let mut inner = state.get().with_drag_pos(Axis::Vertical, Point::default()); + inner.last_update = now; + state.set(inner); + let update = |offset, elapsed, cx: &mut VisualTestContext| { + handle.set_offset(point(px(0.), px(offset))); + cx.update(|window, cx| { + state.notify_drag(now + elapsed, interval, view.entity_id(), window, cx) + }); + cx.run_until_parked(); + }; + update(-10., Duration::ZERO, cx); + cx.executor().advance_clock(Duration::from_millis(16)); + update(-20., Duration::from_millis(16), cx); + update(-30., Duration::from_millis(16), cx); + // Rendering at 120 Hz must not bypass the configured 30 Hz timer. + cx.update(|window, cx| { + window.simulate_next_frame(cx); + }); + cx.run_until_parked(); + assert!(observed.borrow().is_empty()); + cx.executor().advance_clock(Duration::from_millis(16)); + cx.run_until_parked(); + assert!(observed.borrow().is_empty()); + cx.executor().advance_clock(Duration::from_millis(2)); + cx.run_until_parked(); + assert_eq!( + *observed.borrow(), + vec![px(-30.)], + "one trailing notification must see the newest offset even when movement stops" + ); + + // A second burst gets its own interval, and release invalidates its timer. + let next = state.get().last_update; + handle.set_offset(point(px(0.), px(-40.))); + cx.update(|window, cx| state.notify_drag(next, interval, view.entity_id(), window, cx)); + cx.run_until_parked(); + state.set(state.get().with_unset_drag_pos(Instant::now())); + handle.set_offset(point(px(0.), px(-50.))); + cx.update(|_, cx| cx.notify(view.entity_id())); + assert_eq!(*observed.borrow(), vec![px(-30.), px(-50.)]); + cx.executor().advance_clock(interval); + cx.run_until_parked(); + assert_eq!( + *observed.borrow(), + vec![px(-30.), px(-50.)], + "release must not leave a stale trailing notification" + ); +} + +#[test] +fn full_track_thumb_does_not_reset_the_scroll_offset() { + let geometry = ThumbGeometry::new(px(20.), px(40.), px(500.), px(0.), px(4.), px(64.)); + let offset = point(px(0.), px(-100.)); + assert_eq!( + geometry.drag_offset( + Axis::Vertical, + point(px(0.), px(50.)), + point(px(0.), px(8.)), + offset + ), + offset + ); +} + +#[gpui::test] +fn repeated_touch_and_mouse_drags_keep_the_painted_grab_point(cx: &mut TestAppContext) { + struct Probe { + scrollbar: Scrollbar, + painted: Rc>>, + } + impl IntoElement for Probe { + type Element = Self; + fn into_element(self) -> Self { + self + } + } + impl Element for Probe { + type RequestLayoutState = (); + type PrepaintState = PrepaintState; + fn id(&self) -> Option { + Element::id(&self.scrollbar) + } + fn source_location(&self) -> Option<&'static Location<'static>> { + None + } + fn request_layout( + &mut self, + id: Option<&GlobalElementId>, + inspector: Option<&InspectorElementId>, + window: &mut Window, + cx: &mut App, + ) -> (LayoutId, ()) { + self.scrollbar.request_layout(id, inspector, window, cx) + } + fn prepaint( + &mut self, + id: Option<&GlobalElementId>, + inspector: Option<&InspectorElementId>, + bounds: Bounds, + layout: &mut (), + window: &mut Window, + cx: &mut App, + ) -> PrepaintState { + let state = self + .scrollbar + .prepaint(id, inspector, bounds, layout, window, cx); + self.painted.set(state.states[0].thumb_fill_bounds); + state + } + fn paint( + &mut self, + id: Option<&GlobalElementId>, + inspector: Option<&InspectorElementId>, + bounds: Bounds, + layout: &mut (), + state: &mut PrepaintState, + window: &mut Window, + cx: &mut App, + ) { + self.scrollbar + .paint(id, inspector, bounds, layout, state, window, cx); + } + } + struct Root { + handle: TestHandle, + painted: Rc>>, + axis: ScrollbarAxis, + viewport: Bounds, + } + impl Render for Root { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().size(px(400.)).child(Probe { + scrollbar: Scrollbar::new(&self.handle) + .axis(self.axis) + .mode(ScrollbarMode::Always) + .viewport_bounds(self.viewport) + .styles(|style| { + style + .thumb(|style| style.inset(px(6.)).min_length(px(64.))) + .thumb_active(|style| style.inset(px(3.)).min_length(px(72.))) + }), + painted: self.painted.clone(), + }) + } + } + for touch in [true, false] { + for vertical in [true, false] { + for (origin, viewport_size, content_size) in [ + (Point::default(), 200., 1000.), + (point(px(30.), px(40.)), 240., 500.), + ] { + let handle = TestHandle::new(size(px(content_size), px(content_size))); + handle.set_offset(point(px(-100.), px(-100.))); + let painted = Rc::new(Cell::new(Bounds::default())); + let (_, cx) = cx.add_window_view({ + let handle = handle.clone(); + let painted = painted.clone(); + move |_, _| Root { + handle, + painted, + axis: if vertical { + ScrollbarAxis::Vertical + } else { + ScrollbarAxis::Both + }, + viewport: Bounds::new(origin, size(px(viewport_size), px(viewport_size))), + } + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let initial = painted.get(); + let start = initial.center(); + let grab = if vertical { + start.y - initial.origin.y + } else { + start.x - initial.origin.x + }; + let axis_delta = |value| { + if vertical { + point(px(0.), px(value)) + } else { + point(px(value), px(0.)) + } + }; + let axis_value = |point: Point| if vertical { point.y } else { point.x }; + let started_position = if touch { start + axis_delta(5.) } else { start }; + if touch { + cx.simulate_event(TouchDragEvent { + phase: TouchPhase::Started, + start_position: start, + position: started_position, + }); + } else { + cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default()); + } + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert!( + (axis_value(painted.get().origin) + grab - axis_value(started_position)).abs() + < px(0.1), + "starting must preserve the grab point and first displacement" + ); + let mut reference_offset = px(0.); + let mut offset_per_pixel = 0.; + for delta in [0., 24., -8., 32., -10., 8., 0.] { + let position = start + axis_delta(delta); + if touch { + cx.simulate_event(TouchDragEvent { + phase: TouchPhase::Moved, + start_position: start, + position, + }); + } else { + cx.simulate_mouse_move( + position, + Some(MouseButton::Left), + Modifiers::default(), + ); + } + cx.update(|window, cx| window.draw(cx).clear(cx)); + if delta == 0. { + reference_offset = axis_value(handle.offset()); + } + if delta == 24. { + offset_per_pixel = + (axis_value(handle.offset()) - reference_offset) / px(24.); + } + let actual = if vertical { + painted.get().origin.y + grab + } else { + painted.get().origin.x + grab + }; + let expected = if vertical { position.y } else { position.x }; + assert!( + (actual - expected).abs() < px(0.1), + "touch={touch} vertical={vertical} delta={delta}: painted grab {actual:?}, pointer {expected:?}" + ); + } + // Release contains a final displacement without an intervening move. + let expected_offset = reference_offset + px(12.) * offset_per_pixel; + if touch { + cx.simulate_event(TouchDragEvent { + phase: TouchPhase::Ended, + start_position: start, + position: start + axis_delta(12.), + }); + } else { + cx.simulate_mouse_up( + start + axis_delta(12.), + MouseButton::Left, + Modifiers::default(), + ); + } + assert!( + (axis_value(handle.offset()) - expected_offset).abs() < px(0.1), + "release must flush the last displacement" + ); + let released_offset = handle.offset(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert_eq!( + handle.offset(), + released_offset, + "leaving active styling must not scroll" + ); + } + } + } +} + +#[gpui::test] +fn touch_thumb_drag_moves_down_and_cancel_releases_handle(cx: &mut TestAppContext) { + let (cx, handle) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Always, + size(px(100.), px(500.)), + ); + let start_position = point(px(95.), px(20.)); + for (phase, position) in [ + (TouchPhase::Started, start_position), + (TouchPhase::Moved, point(px(95.), px(45.))), + (TouchPhase::Cancelled, point(px(95.), px(45.))), + ] { + cx.simulate_event(TouchDragEvent { + phase, + start_position, + position, + }); + } + assert!( + handle.offset().y < px(0.), + "thumb down must scroll toward later content" + ); + assert_eq!(handle.offset().x, px(0.)); + assert_eq!(handle.drag_starts.get(), 1); + assert_eq!(handle.drag_ends.get(), 1); +} + +#[gpui::test] +fn thumb_drag_notifies_handle_start_and_end(cx: &mut TestAppContext) { + let (cx, handle) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Always, + size(px(100.), px(500.)), + ); + cx.simulate_mouse_down( + point(px(95.), px(20.)), + MouseButton::Left, + Modifiers::default(), + ); + cx.simulate_mouse_move( + point(px(95.), px(70.)), + Some(MouseButton::Left), + Modifiers::default(), + ); + cx.simulate_mouse_up( + point(px(95.), px(70.)), + MouseButton::Left, + Modifiers::default(), + ); + + assert_eq!(handle.drag_starts.get(), 1); + assert_eq!(handle.drag_ends.get(), 1); +} + +#[gpui::test] +fn idle_fade_coalesces_redraws_and_reaches_the_hidden_state(cx: &mut TestAppContext) { + let tint = gpui::hsla(0.82, 0.9, 0.5, 1.); + let idle = Duration::from_millis(80); + cx.update(|cx| { + crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new() + .with_motion( + ScrollbarMotion::default() + .with_idle(idle) + .with_exit(Duration::from_millis(51)), + ) + .with_styles(ScrollbarStyles::default().thumb(|thumb| thumb.bg(tint))); + }); + let handle = TestHandle::new(size(px(100.), px(500.))); + let (view, cx) = cx.add_window_view(|_, _| ScrollbarHarness { + handle: handle.clone(), + axis: ScrollbarAxis::Vertical, + mode: ScrollbarMode::Scrolling, + }); + let notifications = Rc::new(Cell::new(0)); + let _observation = cx.update(|_, cx| { + let notifications = notifications.clone(); + cx.observe(&view, move |_, _| { + notifications.set(notifications.get() + 1) + }) + }); + let executor = cx.executor(); + let advance = |duration| { + executor.advance_clock(duration); + while executor.tick() {} + }; + let draw_thumb = |window: &mut Window, cx: &mut App| { + window.draw(cx).clear(cx); + window + .painted_quads() + .into_iter() + .filter_map(|quad| quad.background.as_solid()) + .find(|color| color.h == tint.h) + .map_or(0., |color| color.a) + }; + handle.set_offset(point(px(0.), px(-20.))); + assert_eq!(cx.update(draw_thumb), 1.); + advance(idle); + assert_eq!(cx.update(draw_thumb), 1.); + for _ in 0..2 { + advance(Duration::from_millis(6)); + assert_eq!(cx.update(|window, cx| window.simulate_next_frame(cx)), 1); + assert!((0. ..1.).contains(&cx.update(draw_thumb))); + } + assert_eq!(cx.update(|window, cx| window.simulate_next_frame(cx)), 0); + + notifications.set(0); + advance(Duration::from_millis(16)); + assert_eq!(notifications.get(), 0); + let alpha = cx.update(draw_thumb); + assert!((0. ..1.).contains(&alpha)); + advance(Duration::from_millis(1)); + assert_eq!(notifications.get(), 1); + assert!(cx.update(draw_thumb) < alpha); + + advance(Duration::from_millis(17)); + assert_eq!(notifications.get(), 2); + cx.update(draw_thumb); + advance(Duration::from_millis(5)); + assert_eq!(notifications.get(), 3); + assert_eq!(cx.update(draw_thumb), 0.); + advance(Duration::from_millis(20)); + assert_eq!(notifications.get(), 3); +} + +#[gpui::test] +fn an_idle_fade_uses_platform_frames_at_the_ordinary_display_rate(cx: &mut TestAppContext) { + let idle = Duration::from_millis(70); + cx.update(|cx| { + crate::Theme::global_mut(cx).scrollbar = crate::ScrollbarTheme::new().with_motion( + ScrollbarMotion::default() + .with_idle(idle) + .with_exit(Duration::from_millis(100)), + ); + }); + let (cx, handle) = harness( + cx, + ScrollbarAxis::Vertical, + ScrollbarMode::Scrolling, + size(px(100.), px(500.)), + ); + handle.set_offset(point(px(0.), px(-20.))); + let draw = |window: &mut Window, cx: &mut App| window.draw(cx).clear(cx); + cx.update(draw); + cx.executor().advance_clock(idle); + cx.update(draw); + for _ in 0..4 { + cx.executor().advance_clock(Duration::from_millis(16)); + assert_eq!(cx.update(|window, cx| window.simulate_next_frame(cx)), 1); + cx.update(draw); + } +} diff --git a/vendor/gpui-base/src/text/document.rs b/vendor/gpui-base/src/text/document.rs index 915c65ac..0720c7b6 100644 --- a/vendor/gpui-base/src/text/document.rs +++ b/vendor/gpui-base/src/text/document.rs @@ -12,6 +12,10 @@ use crate::text::{ node::{BlockNode, NodeContext, SourceRangeSelection}, }; +// Nocterm: bound the number of text leaves in each Taffy block layout pass. +const PARAGRAPHS_PER_GROUP: usize = 32; +const MIN_GROUPED_PARAGRAPHS: usize = 256; + /// The parsed document AST. #[derive(Debug, Clone, PartialEq, Default)] pub(crate) struct ParsedDocument { @@ -195,7 +199,7 @@ impl ParsedDocument { ) -> impl IntoElement { let Some(list_state) = list_state else { let blocks_len = self.blocks.len(); - return div().children(self.blocks.iter().enumerate().map(move |(ix, node)| { + let mut render_block = |ix, node: &BlockNode| { let is_last = ix + 1 == blocks_len; node.render_block( NodeRenderOptions { @@ -207,7 +211,26 @@ impl ParsedDocument { window, cx, ) - })); + }; + if self.can_group_paragraphs(node_cx) { + // The TextView content wrapper supplies the paragraph width. + return div().w_full().children( + self.blocks + .chunks(PARAGRAPHS_PER_GROUP) + .enumerate() + .map(|(group, blocks)| { + div().children(blocks.iter().enumerate().map(|(index, node)| { + render_block(group * PARAGRAPHS_PER_GROUP + index, node) + })) + }), + ); + } + return div().children( + self.blocks + .iter() + .enumerate() + .map(|(ix, node)| render_block(ix, node)), + ); }; let options = NodeRenderOptions { @@ -243,4 +266,17 @@ impl ParsedDocument { .size_full(), ) } + + fn can_group_paragraphs(&self, node_cx: &NodeContext) -> bool { + let gap = node_cx.style.paragraph_gap().0; + self.blocks.len() >= MIN_GROUPED_PARAGRAPHS + && gap.is_finite() + && gap >= 0. + && self.blocks.iter().all(|node| { + matches!(node, BlockNode::Paragraph(paragraph) if paragraph.children.iter().all(|child| { + child.custom.is_none() + && child.image.is_none() + })) + }) + } } diff --git a/vendor/gpui-base/src/text/inline.rs b/vendor/gpui-base/src/text/inline.rs index 8767ff00..a73d6219 100644 --- a/vendor/gpui-base/src/text/inline.rs +++ b/vendor/gpui-base/src/text/inline.rs @@ -1,209 +1,43 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + use gpui::Corners; use std::{ - cell::RefCell, - collections::HashMap, - mem, ops::Range, rc::Rc, - sync::{Arc, Mutex, Weak}, + sync::{Arc, Mutex}, }; use gpui::{ - App, BorderStyle, Bounds, ClickEvent, CursorStyle, Edges, Element, ElementId, GlobalElementId, - Half, HighlightStyle, Hitbox, HitboxBehavior, Hsla, InspectorElementId, IntoElement, LayoutId, - MouseButton, MouseClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, - SharedString, StyledText, TextAlign, TextLayout, TextRun, TextStyle, Window, point, px, quad, - size, + App, BorderStyle, Bounds, Edges, Element, ElementId, GlobalElementId, Half, Hitbox, + HitboxBehavior, Hsla, InspectorElementId, IntoElement, LayoutId, Pixels, Rems, SharedString, + Style, StyledText, TextLayout, TextStyle, Window, point, px, quad, size, +}; + +mod geometry; +mod highlights; +mod pointer; +mod retained_layout; + +pub(super) use geometry::point_in_text_selection; +use geometry::{glyph_boxes, range_boxes, selection_for_multi_click}; +pub(super) use highlights::{ + InlineHighlight, append_node_highlights, fade_highlights, highlights_in_range, text_runs, + text_size_ranges, text_size_ranges_in, }; +use pointer::InlinePointer; +use retained_layout::{RetainedLayout, has_retained_layout, retain_layout, take_retained_layout}; use crate::{ - GlobalState, TextSelection, - input::Selection, - text::TextViewMultiClickKind, - text::node::LinkMark, - text::range_highlight::RevealAt, - text::selection::word_range_at, - text::state::LineSpan, - text::text_view::{LinkClickHandlerFn, handle_link_click}, + GlobalState, input::Selection, text::TextViewMultiClickKind, text::node::LinkMark, + text::range_highlight::RevealAt, text::state::LineSpan, text::text_view::LinkClickHandlerFn, text_selection::text_rows_extent, }; -/// The style applied to one range of inline text. -/// -/// A [`HighlightStyle`] carries no font family, so the family an inline code -/// span is set in rides beside it; `None` keeps the family of the enclosing -/// text style. -#[derive(Clone, Debug, Default, PartialEq)] -pub(super) struct InlineHighlight { - pub(super) style: HighlightStyle, - pub(super) font_family: Option, - pub(super) font_size_scale: Option, -} - -impl InlineHighlight { - /// Layers `other` over `self`, the way [`HighlightStyle::highlight`] does. - fn highlight(mut self, other: &InlineHighlight) -> Self { - self.style = self.style.highlight(other.style); - if other.font_family.is_some() { - self.font_family = other.font_family.clone(); - } - if other.font_size_scale.is_some() { - self.font_size_scale = other.font_size_scale; - } - self - } -} - -impl From for InlineHighlight { - fn from(style: HighlightStyle) -> Self { - Self { - style, - font_family: None, - font_size_scale: None, - } - } -} - -/// Merges two highlight lists over one text into non-overlapping ranges, -/// cutting at every endpoint of every input range. Same sweep as -/// [`gpui::combine_highlights`], for [`InlineHighlight`] payloads. -pub(super) fn combine_highlights( - a: impl IntoIterator, InlineHighlight)>, - b: impl IntoIterator, InlineHighlight)>, -) -> Vec<(Range, InlineHighlight)> { - let mut endpoints = Vec::new(); - let mut highlights = Vec::new(); - for (range, highlight) in a.into_iter().chain(b) { - if !range.is_empty() { - let id = highlights.len(); - endpoints.push((range.start, id, true)); - endpoints.push((range.end, id, false)); - highlights.push(highlight); - } - } - endpoints.sort_unstable_by_key(|(position, _, _)| *position); - - let mut combined = Vec::new(); - let mut active: Vec = Vec::new(); - let mut ix = 0; - for (position, id, is_start) in endpoints { - if position > ix && !active.is_empty() { - let style = active.iter().fold(InlineHighlight::default(), |acc, id| { - acc.highlight(&highlights[*id]) - }); - combined.push((ix..position, style)); - } - ix = position; - if is_start { - active.push(id); - } else { - active.retain(|active_id| *active_id != id); - } - } - combined -} - -/// Layers a streamed fade-in over `highlights`: text inside each fade range -/// loses that share of its color, and a highlight background fades with it so -/// an inline code chip does not appear before its text. -pub(super) fn fade_highlights( - highlights: Vec<(Range, InlineHighlight)>, - fades: &[(Range, f32)], -) -> Vec<(Range, InlineHighlight)> { - if fades.is_empty() { - return highlights; - } - let fade_highlights = fades.iter().map(|(range, fade_out)| { - ( - range.clone(), - InlineHighlight::from(HighlightStyle { - fade_out: Some(*fade_out), - ..Default::default() - }), - ) - }); - let mut combined = combine_highlights(highlights, fade_highlights); - for (_, highlight) in &mut combined { - if let Some(fade_out) = highlight.style.fade_out - && let Some(background) = highlight.style.background_color.as_mut() - { - background.fade_out(fade_out); - } - } - combined -} - -/// Builds the [`TextRun`]s for `text_len` bytes of inline text: each -/// highlight refines `default_style` over its range, and a highlight that -/// names a font family shapes its run in that family. -pub(super) fn text_runs( - text_len: usize, - default_style: &TextStyle, - highlights: &[(Range, InlineHighlight)], -) -> Vec { - let mut runs = Vec::with_capacity(highlights.len() * 2 + 1); - let mut ix = 0; - for (range, highlight) in highlights { - if ix < range.start { - runs.push(default_style.clone().to_run(range.start - ix)); - } - let mut run = default_style - .clone() - .highlight(highlight.style) - .to_run(range.len()); - if let Some(family) = &highlight.font_family { - run.font.family = family.clone(); - } - runs.push(run); - ix = range.end; - } - if ix < text_len { - runs.push(default_style.to_run(text_len - ix)); - } - runs -} - -/// Splits text into contiguous ranges sharing one font size. GPUI runs can -/// vary the font but not its size, so each range needs its own shaped line. -pub(super) fn text_size_ranges( - text_len: usize, - highlights: &[(Range, InlineHighlight)], -) -> Vec<(Range, f32)> { - let mut ranges: Vec<(Range, f32)> = Vec::new(); - let mut push = |range: Range, scale: f32| { - if range.is_empty() { - return; - } - if let Some((last, last_scale)) = ranges.last_mut() - && *last_scale == scale - && last.end == range.start - { - last.end = range.end; - } else { - ranges.push((range, scale)); - } - }; - let mut cursor = 0; - for (range, highlight) in highlights { - push(cursor..range.start, 1.); - push(range.clone(), highlight.font_size_scale.unwrap_or(1.)); - cursor = range.end; - } - push(cursor..text_len, 1.); - ranges -} - -/// A inline element used to render a inline text and support selectable. -/// -/// All text in TextView (including the CodeBlock) used this for text rendering. +/// Selectable inline text drawn by TextView and its code blocks. pub(super) struct Inline { text: SharedString, links: Rc, LinkMark)>>, highlights: Vec<(Range, InlineHighlight)>, - styled_text: StyledText, - /// The resolved style from a parent deferred layout, when there is one. - text_style: Option, - paint_origin: Option>, selection_bounds: Option>, selection_source: Option<(Arc>, Range)>, /// Range highlight backgrounds, painted behind the text. @@ -211,12 +45,10 @@ pub(super) struct Inline { /// The start of a pending reveal, when it is in this text. reveal: Option, link_click_handler: Option>, - /// What this frame's layout was shaped with, to hand the shaped text to - /// the next frame (see [`RetainedLayout`]). - retained_key: Option<(Vec, TextStyle)>, - /// The shaped text is in the table, not in `styled_text`, until paint - /// takes it back. - handed_over: bool, + bottom_padding: Rems, + /// Nocterm: only hold a layout while this element owns the shaped text. + /// Prepaint returns it to the retained table; paint briefly takes it back. + layout: Option, state: Arc>, } @@ -229,74 +61,6 @@ pub(crate) struct InlineState { pub(super) selection: Option, } -/// One frame's [`StyledText`], kept for the next frame's [`Inline`] of the -/// same [`InlineState`]. -/// -/// A [`TextLayout`] remembers the size and the shaped lines of its last -/// measurement and answers a repeated measure at the same wrap width from -/// them, but a fresh `StyledText` every frame throws that away, so every -/// frame of a scroll paid for a line wrapper, a shaping-cache lookup that -/// hashes the whole paragraph, and the allocations around them for every -/// visible paragraph. Handing the same `StyledText` to the next frame makes -/// those measurements hits. A layout is only reused when the text, the runs -/// (colors, fades, fonts) and the text style (font size, line height) it was -/// shaped with are unchanged; a different wrap width misses inside -/// `TextLayout` and reshapes as before. -/// -/// `StyledText` is main-thread only (an `Rc` inside), while `InlineState` -/// travels through the background parse, so the layouts live in a -/// thread-local table keyed by the state's address, with a `Weak` to tell a -/// live state from a reused address. -struct RetainedLayout { - state: Weak>, - styled_text: StyledText, - text: SharedString, - runs: Vec, - text_style: TextStyle, -} - -thread_local! { - static RETAINED_LAYOUTS: RefCell> = RefCell::new(HashMap::new()); -} - -/// Dead entries (states that were dropped without a final paint, e.g. a -/// replaced document) are swept once the table grows past this many. -const RETAINED_SWEEP_AT: usize = 4096; - -fn state_key(state: &Arc>) -> usize { - Arc::as_ptr(state) as usize -} - -/// Takes the layout retained for `state`, if the previous frame left one. -fn take_retained_layout(state: &Arc>) -> Option { - RETAINED_LAYOUTS.with(|layouts| { - let retained = layouts.borrow_mut().remove(&state_key(state))?; - // The address may belong to a new state by now. - retained - .state - .upgrade() - .is_some_and(|live| Arc::ptr_eq(&live, state)) - .then_some(retained) - }) -} - -/// Whether the table already holds a layout for `state`: every entry left -/// by the previous frame is taken at layout time, so one that is present -/// afterwards was put there this frame, by another element of the same state. -fn has_retained_layout(state: &Arc>) -> bool { - RETAINED_LAYOUTS.with(|layouts| layouts.borrow().contains_key(&state_key(state))) -} - -fn retain_layout(state: &Arc>, retained: RetainedLayout) { - RETAINED_LAYOUTS.with(|layouts| { - let mut layouts = layouts.borrow_mut(); - if layouts.len() >= RETAINED_SWEEP_AT { - layouts.retain(|_, retained| retained.state.strong_count() > 0); - } - layouts.insert(state_key(state), retained); - }); -} - impl InlineState { /// Save actually rendered text for selected text to use. pub(crate) fn set_text(&mut self, text: SharedString) { @@ -315,38 +79,12 @@ impl Inline { /// table holds one layout per state, and an element must never be left /// to paint without its shaped text. fn retain_styled_text(&mut self) { - if self.handed_over || self.retained_key.is_none() || has_retained_layout(&self.state) { + if has_retained_layout(&self.state) { return; } - let Some((runs, text_style)) = self.retained_key.take() else { - return; - }; - retain_layout( - &self.state, - RetainedLayout { - state: Arc::downgrade(&self.state), - styled_text: mem::replace(&mut self.styled_text, StyledText::new("")), - text: self.text.clone(), - runs, - text_style, - }, - ); - self.handed_over = true; - } - - /// Takes the shaped text back from the table for painting. `false` when - /// it is gone, in which case there is nothing to paint with. - fn reclaim_styled_text(&mut self) -> bool { - if !self.handed_over { - return true; + if let Some(layout) = self.layout.take() { + retain_layout(&self.state, layout); } - let Some(retained) = take_retained_layout(&self.state) else { - return false; - }; - self.styled_text = retained.styled_text; - self.retained_key = Some((retained.runs, retained.text_style)); - self.handed_over = false; - true } pub(super) fn new( @@ -363,33 +101,18 @@ impl Inline { Self { links: Rc::new(links), highlights, - text: text.clone(), - styled_text: StyledText::new(text), - text_style: None, - paint_origin: None, + text, selection_bounds: None, selection_source: None, range_backgrounds: Vec::new(), reveal: None, link_click_handler, - retained_key: None, - handed_over: false, + bottom_padding: Rems::ZERO, + layout: None, state, } } - /// Use the resolved style captured by a deferred parent layout. - pub(super) fn text_style(mut self, text_style: TextStyle) -> Self { - self.text_style = Some(text_style); - self - } - - /// Preserve the shared inline-flow baseline through GPUI's element-bound snapping. - pub(super) fn paint_origin(mut self, origin: Point) -> Self { - self.paint_origin = Some(origin); - self - } - pub(super) fn selection_bounds(mut self, bounds: Bounds) -> Self { self.selection_bounds = Some(bounds); self @@ -411,6 +134,51 @@ impl Inline { self } + pub(super) fn bottom_padding(mut self, padding: Rems) -> Self { + self.bottom_padding = padding; + self + } + + fn prepare_layout(&mut self, text_style: TextStyle) { + let runs = text_runs(self.text.len(), &text_style, &self.highlights); + + // Reuse the previous frame's shaped text when it was shaped from the + // same text, runs and style; `StyledText` consumes its runs on every + // layout, so they are handed over again either way. + let retained = take_retained_layout(&self.state).filter(|retained| { + retained.text == self.text && retained.runs == runs && retained.text_style == text_style + }); + let styled_text = match retained { + Some(retained) => retained.styled_text.with_runs(runs.clone()), + None => StyledText::new(self.text.clone()).with_runs(runs.clone()), + }; + self.layout = Some(RetainedLayout { + styled_text, + text: self.text.clone(), + runs, + text_style, + }); + } + + pub(super) fn prepaint_positioned( + &mut self, + available: Bounds, + style: TextStyle, + window: &mut Window, + cx: &mut App, + ) -> (Bounds, InlinePrepaint) { + self.prepare_layout(style); + let size = self + .layout + .as_mut() + .expect("prepared layout") + .styled_text + .measure_as_block(available.size, window, cx); + let bounds = Bounds::new(available.origin, size); + let prepared = self.prepaint(None, None, bounds, &mut px(0.), window, cx); + (bounds, prepared) + } + /// Scroll the line `reveal` starts on into view during prepaint. pub(super) fn reveal(mut self, reveal: Option) -> Self { self.reveal = reveal; @@ -420,11 +188,10 @@ impl Inline { /// Ask the enclosing list to scroll the line of the pending reveal into /// view, and report where it is and whether it is inside the visible /// area. - fn request_reveal(&self, window: &mut Window) { - let Some(reveal) = &self.reveal else { + fn request_reveal(reveal: Option<&RevealAt>, text_layout: &TextLayout, window: &mut Window) { + let Some(reveal) = reveal else { return; }; - let text_layout = self.styled_text.layout(); let bounds = text_layout.bounds(); let line_height = text_layout.line_height(); let glyphs = glyph_boxes( @@ -466,35 +233,6 @@ impl Inline { ); } - /// Get link at given mouse position. - fn link_for_position( - layout: &TextLayout, - links: &Vec<(Range, LinkMark)>, - position: Point, - ) -> Option { - let offset = layout.index_for_position(position).ok()?; - for (range, link) in links.iter() { - if range.contains(&offset) { - return Some(link.clone()); - } - } - - None - } - - /// Get the range of the link at given mouse position. - fn link_range_for_position( - layout: &TextLayout, - links: &[(Range, LinkMark)], - position: Point, - ) -> Option> { - let offset = layout.index_for_position(position).ok()?; - links - .iter() - .find(|(range, _)| range.contains(&offset)) - .map(|(range, _)| range.clone()) - } - /// Paint selected bounds for debug. #[allow(unused)] fn paint_selected_bounds(&self, bounds: Bounds, window: &mut Window, cx: &mut App) { @@ -692,7 +430,7 @@ impl Inline { .iter() .map(|line| line.wrap_boundaries.len() + 1) .sum(); - let mut line_bounds = Vec::with_capacity(row_count); + let mut line_bounds = Vec::new(); let mut row_ix = 0; let mut y = origin.y; for line in &lines { @@ -704,18 +442,28 @@ impl Inline { .map(|boundary| layout.runs[boundary.run_ix].glyphs[boundary.glyph_ix].index) .chain([line.len()]); for row_end in row_ends { - let mut width = layout.x_for_index(row_end) - layout.x_for_index(row_start); + let start = std::mem::replace(&mut row_start, row_end); + let row_y = y; + y += line_height; row_ix += 1; + if row_y >= mask_bounds.bottom() || y <= mask_bounds.top() { + continue; + } + let mut width = layout.x_for_index(row_end) - layout.x_for_index(start); if row_ix < row_count { width += line_height.half(); } - let bounds = Bounds::new(point(origin.x, y), size(width, line_height)) + let bounds = Bounds::new(point(origin.x, row_y), size(width, line_height)) .intersect(&mask_bounds); if bounds.size.width > px(0.) && bounds.size.height > px(0.) { + if line_bounds.is_empty() { + // A partially visible row can intersect either edge. + let visible = ((mask_bounds.size.height / line_height).ceil() as usize) + .saturating_add(1); + line_bounds.reserve_exact(row_count.min(visible)); + } line_bounds.push(bounds); } - y += line_height; - row_start = row_end; } } line_bounds @@ -849,9 +597,14 @@ impl IntoElement for Inline { } } +pub(super) enum InlinePrepaint { + Visible(Hitbox), + Clipped(Bounds), +} + impl Element for Inline { - type RequestLayoutState = (); - type PrepaintState = Hitbox; + type RequestLayoutState = Pixels; + type PrepaintState = InlinePrepaint; fn id(&self) -> Option { None @@ -863,46 +616,41 @@ impl Element for Inline { fn request_layout( &mut self, - global_element_id: Option<&GlobalElementId>, - inspector_id: Option<&InspectorElementId>, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, window: &mut Window, - cx: &mut App, + _: &mut App, ) -> (LayoutId, Self::RequestLayoutState) { - let text_style = self - .text_style - .clone() - .unwrap_or_else(|| window.text_style()); - let runs = text_runs(self.text.len(), &text_style, &self.highlights); - - // Reuse the previous frame's shaped text when it was shaped from the - // same text, runs and style; `StyledText` consumes its runs on every - // layout, so they are handed over again either way. - let retained = take_retained_layout(&self.state).filter(|retained| { - retained.text == self.text && retained.runs == runs && retained.text_style == text_style - }); - self.styled_text = match retained { - Some(retained) => retained.styled_text.with_runs(runs.clone()), - None => StyledText::new(self.text.clone()).with_runs(runs.clone()), - }; - self.retained_key = Some((runs, text_style)); - let (layout_id, _) = - self.styled_text - .request_layout(global_element_id, inspector_id, window, cx); - - (layout_id, ()) + self.prepare_layout(window.text_style()); + let mut style = Style::default(); + style.padding.bottom = self.bottom_padding.into(); + let padding = window.pixel_snap(self.bottom_padding.to_pixels(window.rem_size())); + let layout = self + .layout + .as_mut() + .expect("prepared layout") + .styled_text + .request_layout_with_style(style, window); + (layout, padding) } fn prepaint( &mut self, id: Option<&GlobalElementId>, inspector_id: Option<&InspectorElementId>, - bounds: Bounds, - _: &mut Self::RequestLayoutState, + mut bounds: Bounds, + padding: &mut Self::RequestLayoutState, window: &mut Window, cx: &mut App, ) -> Self::PrepaintState { - let bounds = Bounds::new(self.paint_origin.unwrap_or(bounds.origin), bounds.size); - self.styled_text + // The gap belongs to layout, outside the text clip and hitbox. + bounds.size.height = (bounds.size.height - *padding).max(Pixels::ZERO); + let layout = self + .layout + .as_mut() + .expect("request_layout precedes prepaint"); + layout + .styled_text .prepaint(id, inspector_id, bounds, &mut (), window, cx); // Report this element's laid-out extent so an ancestor TextView with @@ -922,37 +670,45 @@ impl Element for Inline { } } - self.request_reveal(window); + Self::request_reveal(self.reveal.as_ref(), layout.styled_text.layout(), window); - let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal); self.retain_styled_text(); - hitbox + // This private hitbox cannot participate in GPUI's frame hit test when masked. + if bounds.intersect(&window.content_mask().bounds).is_empty() { + InlinePrepaint::Clipped(bounds) + } else { + InlinePrepaint::Visible(window.insert_hitbox(bounds, HitboxBehavior::Normal)) + } } fn paint( &mut self, global_id: Option<&GlobalElementId>, _: Option<&InspectorElementId>, - bounds: Bounds, + _: Bounds, _: &mut Self::RequestLayoutState, prepaint: &mut Self::PrepaintState, window: &mut Window, cx: &mut App, ) { - let bounds = Bounds::new(self.paint_origin.unwrap_or(bounds.origin), bounds.size); - let current_view = window.current_view(); - let hitbox = prepaint; - if !self.reclaim_styled_text() { - // Cannot happen (only this element takes what it handed over, - // and a live state is never swept); skip the frame rather than - // paint an unmeasured placeholder. - return; + let bounds = match prepaint { + InlinePrepaint::Visible(hitbox) => hitbox.bounds, + InlinePrepaint::Clipped(bounds) => *bounds, + }; + if self.layout.is_none() { + self.layout = take_retained_layout(&self.state); } - let text_layout = self.styled_text.layout().clone(); + let Some(layout) = &self.layout else { + return; + }; + let text_layout = layout.styled_text.layout().clone(); if !self.range_backgrounds.is_empty() { self.paint_range_highlights(&text_layout, window); } - self.styled_text + self.layout + .as_mut() + .expect("retained layout was just restored") + .styled_text .paint(global_id, None, bounds, &mut (), &mut (), window, cx); // layout selections @@ -976,17 +732,6 @@ impl Element for Inline { }); } - if is_selection || is_selectable { - window.set_cursor_style(CursorStyle::IBeam, &hitbox); - } - - // link cursor pointer - let hovered_link = - Self::link_range_for_position(&text_layout, &self.links, window.mouse_position()); - if hovered_link.is_some() { - window.set_cursor_style(CursorStyle::PointingHand, &hitbox); - } - if let Some(selection) = &state.selection { let color = GlobalState::global(cx) .text_view_state() @@ -1002,165 +747,37 @@ impl Element for Inline { } } - if is_selectable { - if let Some(text_view_state) = GlobalState::global(cx).text_view_state().cloned() { - let text_bounds = Self::text_line_bounds( - &text_layout, - text_layout.line_height(), - window.content_mask().bounds, - ); - text_view_state.update(cx, |state, _| { - state.selection_adapter.register_inline(text_bounds); - state - .selection_adapter - .register_text_run(crate::TextSelectionRun::new( - self.text.clone(), - text_layout.clone(), - hitbox.bounds, - )); - }); - } - - window.on_mouse_event({ - let hitbox = hitbox.clone(); - let text_layout = text_layout.clone(); - let inline_state = self.state.clone(); - let text = self.text.clone(); - let text_view_state = GlobalState::global(cx).text_view_state().cloned(); - let line_bounds = self.selection_bounds; - move |event: &MouseDownEvent, phase, window, cx| { - if !phase.bubble() - || !hitbox.is_hovered(window) - || event.button != MouseButton::Left - { - return; - } - - if event.click_count == 3 - && let Some(line_bounds) = line_bounds - { - GlobalState::suppress_text_selection(cx); - if let Some(view) = &text_view_state { - view.update(cx, |state, cx| { - state.set_multi_click_line(line_bounds, cx) - }); - } - cx.notify(current_view); - return; - } - - // A finger selects read-only text with a long press only; - // a double tap selects nothing here, neither the mouse's - // plain word nor the window layer's touch selection. The - // handles and the menu on a double tap belong to `Input`. - if event.click_count == 2 && GlobalState::is_touch_press(cx) { - GlobalState::suppress_text_selection(cx); - return; - } - - let kind = match event.click_count { - 2 => TextViewMultiClickKind::Word, - 3 => TextViewMultiClickKind::Paragraph, - _ => return, - }; - - let Some(range) = selection_for_multi_click( - &text, - &text_layout, - hitbox.bounds, - event.position, - kind, - ) else { - return; - }; - - let selected_text = text[range.clone()].to_string(); - - // This renderer owns multi-click selection. Prevent the - // window selection layer from handling the same press. - GlobalState::suppress_text_selection(cx); - - if let Ok(mut inline_state) = inline_state.lock() { - inline_state.selection = Some(range.into()); - } - if let Some(text_view_state) = &text_view_state { - text_view_state.update(cx, |state, cx| { - state.set_multi_click_selection( - event.position, - kind, - selected_text, - cx, - ); - }); - } - cx.notify(current_view); - } - }); - } - - // Mouse move: repaint only when the pointer enters, leaves or moves - // between links, so the link cursor follows it. Hovering plain text - // changes nothing painted. - if !self.links.is_empty() { - window.on_mouse_event({ - let hitbox = hitbox.clone(); - let text_layout = text_layout.clone(); - let links = self.links.clone(); - let mut hovered_link = hovered_link; - move |event: &MouseMoveEvent, phase, window, cx| { - if !phase.bubble() || !hitbox.is_hovered(window) { - return; - } - - let updated = - Self::link_range_for_position(&text_layout, &links, event.position); - if hovered_link != updated { - hovered_link = updated; - cx.notify(current_view); - } - } + if is_selectable + && let Some(text_view_state) = GlobalState::global(cx).text_view_state().cloned() + { + let text_bounds = Self::text_line_bounds( + &text_layout, + text_layout.line_height(), + window.content_mask().bounds, + ); + text_view_state.update(cx, |state, _| { + state.selection_adapter.register_inline(text_bounds); + state + .selection_adapter + .register_text_run(crate::TextSelectionRun::new( + self.text.clone(), + text_layout.clone(), + bounds, + )); }); } - if !is_selection { - // click to open link - window.on_mouse_event({ - let links = self.links.clone(); - let text_layout = text_layout.clone(); - let hitbox = hitbox.clone(); - let text_view_state = GlobalState::global(cx).text_view_state().cloned(); - let link_click_handler = self.link_click_handler.clone(); - - move |event: &MouseUpEvent, phase, window, cx| { - if !phase.bubble() || !hitbox.is_hovered(window) { - return; - } - if text_view_state - .as_ref() - .is_some_and(|state| state.read(cx).has_selection(cx)) - { - return; - } - - if let Some(link) = - Self::link_for_position(&text_layout, &links, event.position) - { - TextSelection::end(window, cx); - cx.stop_propagation(); - let click = ClickEvent::Mouse(MouseClickEvent { - down: MouseDownEvent { - button: event.button, - position: event.position, - modifiers: event.modifiers, - click_count: event.click_count, - first_mouse: false, - }, - up: event.clone(), - }); - handle_link_click(&link_click_handler, link.url, click, window, cx); - } - } - }); + if let InlinePrepaint::Visible(hitbox) = prepaint { + InlinePointer { + hitbox, + text_layout: &text_layout, + inline_state: &self.state, + text: &self.text, + links: &self.links, + link_click_handler: &self.link_click_handler, + line_bounds: self.selection_bounds, + } + .register(is_selectable, is_selection, window, cx); } drop(state); @@ -1168,1269 +785,15 @@ impl Element for Inline { } } -/// Where one glyph of laid-out text paints: its row, and its horizontal -/// extent past the text's origin, alignment applied. `text` is the byte range -/// of the text it draws. -#[derive(Clone, Debug, PartialEq)] -struct GlyphBox { - text: Range, - row: usize, - left: Pixels, - right: Pixels, -} - -/// The glyphs of `text_layout`, sorted by the text they draw, each placed -/// the way GPUI paints it: every row aligned in `align_width` by `align`, -/// and a glyph reaching to the next one on its row, or to the row's end. -/// -/// Glyphs are read in the order they paint, so right-to-left text, whose -/// glyphs paint in the reverse order of its text, is placed as it shows. -fn glyph_boxes(text_layout: &TextLayout, align: TextAlign, align_width: Pixels) -> Vec { - let mut boxes = Vec::new(); - let mut row = 0; - let mut line_start = 0; - for line in text_layout.line_layouts() { - let layout = &line.unwrapped_layout; - let glyphs = layout - .runs - .iter() - .flat_map(|run| run.glyphs.iter()) - .collect::>(); - // Each row starts at a wrap boundary glyph, and ends where the next - // row starts, or at the end of the line. - let run_offsets = layout - .runs - .iter() - .scan(0, |offset, run| { - let start = *offset; - *offset += run.glyphs.len(); - Some(start) - }) - .collect::>(); - let row_starts = line - .wrap_boundaries - .iter() - .map(|boundary| run_offsets[boundary.run_ix] + boundary.glyph_ix) - .collect::>(); - let line_boxes = boxes.len(); - let mut from = 0; - for (row_in_line, to) in row_starts.iter().copied().chain([glyphs.len()]).enumerate() { - let start_x = if row_in_line == 0 { - Pixels::ZERO - } else { - glyphs[from].position.x - }; - let end_x = glyphs - .get(to) - .map_or(layout.width, |glyph| glyph.position.x); - let shift = aligned_row_left(align, align_width, end_x - start_x) - start_x; - for ix in from..to { - let glyph = glyphs[ix]; - let right = if ix + 1 < to { - glyphs[ix + 1].position.x - } else { - end_x - }; - boxes.push(GlyphBox { - text: line_start + glyph.index..line_start + glyph.index, - row: row + row_in_line, - left: shift + glyph.position.x, - right: shift + right, - }); - } - from = to; - } - - // A glyph draws its text up to where the next glyph's text starts. - let line_boxes = &mut boxes[line_boxes..]; - line_boxes.sort_by_key(|glyph| glyph.text.start); - let line_end = line_start + line.len(); - for ix in 0..line_boxes.len() { - let start = line_boxes[ix].text.start; - line_boxes[ix].text.end = line_boxes[ix + 1..] - .iter() - .map(|glyph| glyph.text.start) - .find(|next| *next > start) - .unwrap_or(line_end); - } - - row += line.wrap_boundaries.len() + 1; - line_start = line_end + 1; - } - boxes -} - -fn aligned_row_left(align: TextAlign, align_width: Pixels, width: Pixels) -> Pixels { - match align { - TextAlign::Left => Pixels::ZERO, - TextAlign::Center => (align_width - width) / 2., - TextAlign::Right => align_width - width, - } -} - -/// The boxes behind the text of `range`, as a row and the horizontal extent -/// on it, from `glyphs` sorted by the text they draw: every glyph drawing -/// some of that text, joined where they touch on a row. -fn range_boxes(glyphs: &[GlyphBox], range: Range) -> Vec<(usize, Pixels, Pixels)> { - let first = glyphs.partition_point(|glyph| glyph.text.end <= range.start); - let mut hits = glyphs[first..] - .iter() - .take_while(|glyph| glyph.text.start < range.end) - .map(|glyph| (glyph.row, glyph.left, glyph.right)) - .collect::>(); - hits.sort_by(|a, b| { - (a.0, a.1) - .partial_cmp(&(b.0, b.1)) - .unwrap_or(std::cmp::Ordering::Equal) - }); - - let mut boxes: Vec<(usize, Pixels, Pixels)> = Vec::with_capacity(hits.len()); - for (row, left, right) in hits { - match boxes.last_mut() { - Some(last) if last.0 == row && left <= last.2 => last.2 = last.2.max(right), - _ => boxes.push((row, left, right)), - } - } - boxes -} - -fn selection_for_multi_click( - text: &str, - text_layout: &TextLayout, - bounds: Bounds, - pos: Point, - kind: TextViewMultiClickKind, -) -> Option> { - if !bounds.contains(&pos) { - return None; - } - - let offset = text_layout.index_for_position(pos).ok()?; - - match kind { - TextViewMultiClickKind::Word => word_range_at(text, offset), - // Known limitation: a paragraph maps to a single Inline run here. When a - // paragraph embeds an inline image it is split into multiple Inline runs, - // so triple-click only selects the run on the clicked side of the image. - TextViewMultiClickKind::Paragraph | TextViewMultiClickKind::Line => { - (!text.is_empty()).then_some(0..text.len()) - } - } -} - -/// Check if a `pos` is within a `bounds`, considering multi-line selections. -pub(super) fn point_in_text_selection( - pos: Point, - char_width: Pixels, - selection_start: Point, - selection_end: Point, - line_height: Pixels, -) -> bool { - let point_in_line = |point: Point| point.y >= pos.y && point.y < pos.y + line_height; - let top = selection_start.y.min(selection_end.y); - let bottom = selection_start.y.max(selection_end.y); - let x = pos.x + char_width.half(); - - // Out of the vertical bounds - if pos.y + line_height <= top || pos.y > bottom { - return false; - } - - // Treat the selection as single-line when both drag points fall within the - // same rendered line, even if their y coordinates differ inside that line. - if point_in_line(selection_start) && point_in_line(selection_end) { - let left = selection_start.x.min(selection_end.x); - let right = selection_start.x.max(selection_end.x); - return x >= left && x <= right; - } - - let (top_point, bottom_point) = if selection_start.y < selection_end.y { - (selection_start, selection_end) - } else { - (selection_end, selection_start) - }; - let is_top_line = point_in_line(top_point); - let is_bottom_line = point_in_line(bottom_point); - - if is_top_line { - return x >= top_point.x; - } else if is_bottom_line { - return x <= bottom_point.x; - } else { - return true; - } -} - #[cfg(test)] -mod fade_highlights_tests { - use super::*; - - #[test] - fn fades_text_and_background_only_inside_the_range() { - let code = InlineHighlight::from(HighlightStyle { - background_color: Some(gpui::red()), - ..Default::default() - }); - let combined = fade_highlights(vec![(0..4, code)], &[(2..6, 0.5)]); - - let ranges: Vec<_> = combined.iter().map(|(range, _)| range.clone()).collect(); - assert_eq!(ranges, vec![0..2, 2..4, 4..6]); - - let (_, untouched) = &combined[0]; - assert_eq!(untouched.style.fade_out, None); - assert_eq!(untouched.style.background_color.unwrap().a, 1.0); - - let (_, faded_code) = &combined[1]; - assert_eq!(faded_code.style.fade_out, Some(0.5)); - assert_eq!(faded_code.style.background_color.unwrap().a, 0.5); - - let (_, faded_text) = &combined[2]; - assert_eq!(faded_text.style.fade_out, Some(0.5)); - assert!(faded_text.style.background_color.is_none()); - } - - #[test] - fn no_fades_leave_highlights_untouched() { - let bold = InlineHighlight::from(HighlightStyle { - font_weight: Some(gpui::FontWeight::BOLD), - ..Default::default() - }); - let highlights = vec![(1..3, bold)]; - assert_eq!(fade_highlights(highlights.clone(), &[]), highlights); - } -} - -#[cfg(test)] -mod line_bounds_tests { - use super::*; - use super::{ - test_draw::in_prepaint, - test_fonts::{BODY, WideMonoTextSystem}, - }; - use gpui::{AvailableSpace, TestApp, size}; - - /// The character walk this replaced, kept as the oracle: one box per - /// character from `position_for_index`, unioned per row. - fn by_character( - text: &str, - text_layout: &TextLayout, - line_height: Pixels, - mask_bounds: Bounds, - ) -> Vec> { - let mut line_bounds = Vec::new(); - let mut current_line_y = None; - let mut current_bounds: Option> = None; - let mut offset = 0; - for c in text.chars() { - let next_offset = offset + c.len_utf8(); - let Some(pos) = text_layout.position_for_index(offset) else { - offset = next_offset; - continue; - }; - let mut char_width = line_height.half(); - if let Some(next_pos) = text_layout.position_for_index(next_offset) - && next_pos.y == pos.y - { - char_width = next_pos.x - pos.x; - } - let bounds = Bounds::from_corners(pos, point(pos.x + char_width, pos.y + line_height)) - .intersect(&mask_bounds); - if bounds.size.width > px(0.) && bounds.size.height > px(0.) { - if current_line_y == Some(pos.y) { - if let Some(current) = current_bounds.as_mut() { - *current = current.union(&bounds); - } - } else { - if let Some(current) = current_bounds.take() { - line_bounds.push(current); - } - current_line_y = Some(pos.y); - current_bounds = Some(bounds); - } - } - offset = next_offset; - } - if let Some(current) = current_bounds { - line_bounds.push(current); - } - line_bounds - } - - #[test] - fn row_walk_matches_the_character_walk() { - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - in_prepaint(&mut app, |window, cx| { - let style = TextStyle { - font_family: BODY.into(), - font_size: px(16.).into(), - ..Default::default() - }; - let origin = point(px(7.), px(11.)); - let mask = Bounds::new(point(px(0.), px(0.)), size(px(1000.), px(1000.))); - let clipped = Bounds::new(point(px(20.), px(30.)), size(px(50.), px(60.))); - for text in [ - "", - "one row", - "a long paragraph that wraps onto several rows of eight pixel glyphs", - "first line\nsecond line that also wraps around\n\nfourth", - "中文与 English 混排的一段文字也会换行", - "trailing newline\n", - ] { - for wrap_width in [40., 100., 1000.] { - let runs = text_runs(text.len(), &style, &[]); - let styled = - StyledText::new(SharedString::from(text.to_string())).with_runs(runs); - let layout = styled.layout().clone(); - let mut element = styled.into_any_element(); - element.layout_as_root( - size( - AvailableSpace::Definite(px(wrap_width)), - AvailableSpace::MinContent, - ), - window, - cx, - ); - element.prepaint_at(origin, window, cx); - let line_height = layout.line_height(); - for mask in [mask, clipped] { - let expected = by_character(text, &layout, line_height, mask); - let actual = Inline::text_line_bounds(&layout, line_height, mask); - let context = format!("{text:?} at {wrap_width}px in {mask:?}"); - // The character walk placed a wrapped row's first - // character at the end of the row before it: that row's - // box started one glyph in, and a row holding only that - // one glyph had no box at all. The row walk covers every - // row from its start, so it may see more rows, never - // fewer, and agrees on every row the walk could see. - assert!( - actual.len() >= expected.len(), - "rows of {context}: {} < {}", - actual.len(), - expected.len() - ); - for (row, expected) in expected.iter().enumerate() { - let actual = actual - .iter() - .find(|actual| actual.top() == expected.top()) - .unwrap_or_else(|| panic!("row {row} of {context} is missing")); - assert_eq!( - actual.bottom(), - expected.bottom(), - "row {row} of {context}" - ); - assert_eq!(actual.right(), expected.right(), "row {row} of {context}"); - assert!( - actual.left() <= expected.left(), - "row {row} of {context} starts at {:?}, after {:?}", - actual.left(), - expected.left() - ); - } - for actual in &actual { - assert_eq!( - actual.left(), - origin.x.max(mask.left()), - "left of {context}" - ); - } - } - } - } - }); - } -} - +mod fade_highlights_tests; #[cfg(test)] -mod range_highlight_tests { - use super::*; - use super::{ - test_draw::in_prepaint, - test_fonts::{BODY, WideMonoTextSystem}, - }; - use gpui::{AvailableSpace, TestApp, size}; - - /// Lays `text` out at `wrap_width` and returns the highlight boxes of - /// `range` with rows aligned by `align`: the left and right edges past - /// the text's origin, and the row. - fn boxes( - text: &'static str, - wrap_width: f32, - align: TextAlign, - range: Range, - ) -> Vec<(Pixels, Pixels, usize)> { - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - in_prepaint(&mut app, move |window, cx| { - let style = TextStyle { - font_family: BODY.into(), - font_size: px(16.).into(), - ..Default::default() - }; - let styled = StyledText::new(SharedString::from(text)).with_runs(text_runs( - text.len(), - &style, - &[], - )); - let layout = styled.layout().clone(); - let mut element = styled.into_any_element(); - element.layout_as_root( - size( - AvailableSpace::Definite(px(wrap_width)), - AvailableSpace::MinContent, - ), - window, - cx, - ); - let origin = point(px(7.), px(11.)); - element.prepaint_at(origin, window, cx); - let glyphs = glyph_boxes(&layout, align, layout.bounds().size.width); - range_boxes(&glyphs, range) - .into_iter() - .map(|(row, left, right)| (left, right, row)) - .collect() - }) - } - - /// The selection fast paths decide a whole inline from this extent, so it - /// must start exactly at the first row the per-character walk tests and - /// reach at least the bottom of the last one. It may reach further: a - /// trailing empty line, or a last row whose only character the walk - /// places at the end of the row before it, holds no row the walk tests. - #[test] - fn text_rows_extent_matches_the_character_walk() { - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - in_prepaint(&mut app, |window, cx| { - let style = TextStyle { - font_family: BODY.into(), - font_size: px(16.).into(), - ..Default::default() - }; - let origin = point(px(7.), px(11.3)); - for text in [ - "one row", - "a long paragraph that wraps onto several rows of eight pixel glyphs", - "first line\nsecond line that also wraps around\n\nfourth", - "中文与 English 混排的一段文字也会换行", - "trailing newline\n", - ] { - for wrap_width in [40., 100., 1000.] { - let runs = text_runs(text.len(), &style, &[]); - let styled = - StyledText::new(SharedString::from(text.to_string())).with_runs(runs); - let layout = styled.layout().clone(); - let mut element = styled.into_any_element(); - element.layout_as_root( - size( - AvailableSpace::Definite(px(wrap_width)), - AvailableSpace::MinContent, - ), - window, - cx, - ); - element.prepaint_at(origin, window, cx); - // Taller than the layout's rows, as a window line height - // may be. - let line_height = layout.line_height() + px(3.); - let rows_y = text - .char_indices() - .filter_map(|(offset, _)| layout.position_for_index(offset)) - .map(|position| position.y); - let top = rows_y.clone().fold(Pixels::MAX, Pixels::min); - let bottom = rows_y.fold(Pixels::MIN, Pixels::max) + line_height; - - let (rows_top, rows_bottom) = text_rows_extent(&layout, line_height); - let context = format!("{text:?} at {wrap_width}px"); - assert_eq!(rows_top, top, "top of {context}"); - assert!(rows_bottom >= bottom, "bottom of {context}"); - } - } - }); - } - - #[test] - fn a_highlight_starting_a_wrapped_row_paints_only_that_row() { - // Three rows of "aaaa ", "bbbb ", "cccc". - let text = "aaaa bbbb cccc"; - let rows = boxes(text, 45., TextAlign::Left, 0..text.len()); - assert_eq!(rows.len(), 3, "{rows:?}"); - - let bbbb = text.find("bbbb").unwrap(); - let highlight = boxes(text, 45., TextAlign::Left, bbbb..bbbb + 4); - assert_eq!(highlight.len(), 1, "{highlight:?}"); - assert_eq!(highlight[0].0, px(0.)); - assert_eq!(highlight[0].2, 1); - - // Across the wrap, each row only as far as its text. - let across = boxes(text, 45., TextAlign::Left, 2..7); - assert_eq!(across.len(), 2, "{across:?}"); - assert_eq!(across[0].1, rows[0].1); - assert_eq!((across[1].0, across[1].2), (px(0.), 1)); - } - - #[test] - fn highlights_after_a_hard_line_break_start_on_its_row() { - // Rows "aa", "bbb cc": the break is one byte of the text, not a glyph. - let text = "aa\nbbb cc"; - let bbb = text.find("bbb").unwrap(); - let aa = boxes(text, 1000., TextAlign::Left, 0..2); - let highlight = boxes(text, 1000., TextAlign::Left, bbb..bbb + 3); - assert_eq!(highlight.len(), 1, "{highlight:?}"); - assert_eq!(highlight[0].0, px(0.)); - assert_eq!(highlight[0].2, 1); - // Three glyphs as wide as the two of "aa" and a half. - assert_eq!(highlight[0].1, (aa[0].1 - aa[0].0) * 1.5); - } - - #[test] - fn highlights_follow_centered_and_right_aligned_rows() { - // Rows "aaaa ", "bbbb ", "cc": the last is narrower than the text, so - // alignment moves it. - let text = "aaaa bbbb cc"; - let cc = text.find("cc").unwrap()..text.len(); - let widest = boxes(text, 45., TextAlign::Left, 0..5)[0].1; - let left = boxes(text, 45., TextAlign::Left, cc.clone())[0]; - let center = boxes(text, 45., TextAlign::Center, cc.clone())[0]; - let right = boxes(text, 45., TextAlign::Right, cc)[0]; - let width = left.1 - left.0; - assert!(width > px(0.) && width < widest, "{left:?} in {widest:?}"); - // GPUI aligns each row in the width of the laid-out text, the wrap - // width here. - let align_width = px(45.); - assert_eq!(left.0, px(0.)); - assert_eq!( - center, - ( - (align_width - width) / 2., - (align_width + width) / 2., - left.2 - ) - ); - assert_eq!(right, (align_width - width, align_width, left.2)); - } -} - -/// A platform text system for tests where the `Mono` family shapes twice as -/// wide as every other family, so a measurement that ignores the family of a -/// run comes out visibly short. +mod line_bounds_tests; #[cfg(test)] -pub(super) mod test_draw { - use gpui::{App, Context, IntoElement, Render, Styled as _, TestApp, Window, canvas, px}; - use std::{cell::RefCell, rc::Rc}; - - struct Probe { - body: Option>, - } - - impl Render for Probe { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - let body = self.body.take(); - canvas( - move |_, window, cx| { - if let Some(body) = body { - body(window, cx); - } - }, - |_, _, _, _| {}, - ) - .w(px(1000.)) - .h(px(1000.)) - } - } - - /// Runs `f` inside a real prepaint pass and returns its value. - /// - /// Measuring an inline object lays its GPUI element out through the - /// window, which GPUI only permits while a frame is being drawn, so a test - /// that builds a real element cannot call the measurement helpers straight - /// from `TestAppWindow::update`. - pub(crate) fn in_prepaint( - app: &mut TestApp, - f: impl FnOnce(&mut Window, &mut App) -> R + 'static, - ) -> R { - let slot: Rc>> = Rc::new(RefCell::new(None)); - let out = slot.clone(); - let mut window = app.open_window(|_, _| Probe { - body: Some(Box::new(move |window, cx| { - *out.borrow_mut() = Some(f(window, cx)); - })), - }); - window.draw(); - let value = slot.borrow_mut().take(); - value.expect("prepaint probe did not run") - } -} - +mod range_highlight_tests; #[cfg(test)] -pub(super) mod test_fonts { - use gpui::{ - Bounds, DevicePixels, Font, FontId, FontMetrics, FontRun, FontWeight, GlyphId, LineLayout, - Pixels, PlatformTextSystem, RenderGlyphParams, ShapedGlyph, ShapedRun, Size, - TextRenderingMode, point, px, size, - }; - use std::{borrow::Cow, cell::RefCell}; - - pub(crate) const BODY: &str = "Body"; - pub(crate) const MONO: &str = "Mono"; - const BODY_ID: FontId = FontId(1); - const MONO_ID: FontId = FontId(2); - const BOLD_BODY_ID: FontId = FontId(3); - const BOLD_MONO_ID: FontId = FontId(4); - const UNITS_PER_EM: f32 = 1000.; - - pub(crate) struct WideMonoTextSystem; - - impl WideMonoTextSystem { - /// Advance of one glyph in `font_id`, in em units. - fn advance_units(font_id: FontId) -> f32 { - match font_id { - MONO_ID => 1000., - BOLD_MONO_ID => 1250., - BODY_ID => 500., - BOLD_BODY_ID => 750., - _ => 500., - } - } - - /// Width of `text` shaped entirely in `family` at `font_size`. - pub(crate) fn width_of(text: &str, family: &str, font_size: Pixels) -> Pixels { - let font_id = if family == MONO { MONO_ID } else { BODY_ID }; - font_size * (Self::advance_units(font_id) / UNITS_PER_EM) * text.chars().count() as f32 - } - } - - thread_local! { - static SHAPED_LINE_RECORDER: RefCell>> = const { RefCell::new(None) }; - } - - struct ShapeRecorderGuard; - - impl Drop for ShapeRecorderGuard { - fn drop(&mut self) { - SHAPED_LINE_RECORDER.with(|recorder| recorder.borrow_mut().take()); - } - } - - /// Runs `f` while recording text submitted to [`PlatformTextSystem::layout_line`]. - pub(crate) fn record_shaped_lines(f: impl FnOnce() -> R) -> (R, Vec) { - SHAPED_LINE_RECORDER.with(|recorder| *recorder.borrow_mut() = Some(Vec::new())); - let _guard = ShapeRecorderGuard; - let result = f(); - let shaped_lines = - SHAPED_LINE_RECORDER.with(|recorder| recorder.borrow_mut().take().unwrap_or_default()); - (result, shaped_lines) - } - - impl PlatformTextSystem for WideMonoTextSystem { - fn add_fonts(&self, _fonts: Vec>) -> anyhow::Result<()> { - Ok(()) - } - - fn all_font_names(&self) -> Vec { - vec![BODY.into(), MONO.into()] - } - - fn font_id(&self, descriptor: &Font) -> anyhow::Result { - Ok( - match ( - descriptor.family.as_ref() == MONO, - descriptor.weight == FontWeight::BOLD, - ) { - (true, true) => BOLD_MONO_ID, - (true, false) => MONO_ID, - (false, true) => BOLD_BODY_ID, - (false, false) => BODY_ID, - }, - ) - } - - fn font_metrics(&self, _font_id: FontId) -> FontMetrics { - FontMetrics { - units_per_em: UNITS_PER_EM as u32, - ascent: 800., - descent: -200., - line_gap: 0., - underline_position: -100., - underline_thickness: 50., - cap_height: 700., - x_height: 500., - bounding_box: Bounds { - origin: point(0., -200.), - size: size(1000., 1000.), - }, - } - } - - fn typographic_bounds( - &self, - font_id: FontId, - _glyph_id: GlyphId, - ) -> anyhow::Result> { - Ok(Bounds { - origin: point(0., 0.), - size: size(Self::advance_units(font_id), 700.), - }) - } - - fn advance(&self, font_id: FontId, _glyph_id: GlyphId) -> anyhow::Result> { - Ok(size(Self::advance_units(font_id), 0.)) - } - - fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option { - Some(GlyphId(ch as u32)) - } - - fn glyph_raster_bounds( - &self, - _params: &RenderGlyphParams, - ) -> anyhow::Result> { - Ok(Bounds::default()) - } - - fn rasterize_glyph( - &self, - _params: &RenderGlyphParams, - raster_bounds: Bounds, - ) -> anyhow::Result<(Size, Vec)> { - Ok((raster_bounds.size, Vec::new())) - } - - fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout { - SHAPED_LINE_RECORDER.with(|recorder| { - if let Some(lines) = recorder.borrow_mut().as_mut() { - lines.push(text.to_string()); - } - }); - - let mut position = px(0.); - let mut shaped_runs = Vec::new(); - let mut run_start = 0; - for run in runs { - let run_text = &text[run_start..run_start + run.len]; - let advance = font_size * (Self::advance_units(run.font_id) / UNITS_PER_EM); - let mut glyphs = Vec::new(); - for (ix, ch) in run_text.char_indices() { - glyphs.push(ShapedGlyph { - id: GlyphId(ch as u32), - position: point(position, px(0.)), - index: run_start + ix, - is_emoji: false, - }); - position += advance; - } - shaped_runs.push(ShapedRun { - font_id: run.font_id, - glyphs, - }); - run_start += run.len; - } - let metrics = self.font_metrics(BODY_ID); - LineLayout { - font_size, - width: position, - ascent: font_size * (metrics.ascent / UNITS_PER_EM), - // Native backends normalize the signed font metric for shaped lines. - descent: font_size * (-metrics.descent / UNITS_PER_EM), - runs: shaped_runs, - len: text.len(), - } - } - - fn recommended_rendering_mode( - &self, - _font_id: FontId, - _font_size: Pixels, - ) -> TextRenderingMode { - TextRenderingMode::Grayscale - } - } -} - +pub(super) mod test_draw; #[cfg(test)] -mod tests { - use super::{ - GlyphBox, InlineHighlight, aligned_row_left, combine_highlights, point_in_text_selection, - range_boxes, text_runs, - }; - use gpui::{FontWeight, HighlightStyle, SharedString, TextAlign, TextStyle, point, px}; - use std::ops::Range; - - fn mono(style: HighlightStyle) -> InlineHighlight { - InlineHighlight { - style, - font_family: Some(SharedString::from("Mono")), - font_size_scale: None, - } - } - - #[test] - fn text_runs_shape_a_code_highlight_in_its_font_family() { - let style = TextStyle { - font_family: SharedString::from("Body"), - ..Default::default() - }; - let highlights = vec![(4..8, mono(HighlightStyle::default()))]; - - let runs = text_runs(12, &style, &highlights); - - let families = runs - .iter() - .map(|run| (run.len, run.font.family.as_ref())) - .collect::>(); - assert_eq!(families, vec![(4, "Body"), (4, "Mono"), (4, "Body")]); - } - - #[test] - fn rows_align_the_way_gpui_paints_them() { - let width = px(100.); - assert_eq!(aligned_row_left(TextAlign::Left, width, px(40.)), px(0.)); - assert_eq!(aligned_row_left(TextAlign::Center, width, px(40.)), px(30.)); - assert_eq!(aligned_row_left(TextAlign::Right, width, px(40.)), px(60.)); - } - - fn glyph(text: Range, row: usize, left: f32, right: f32) -> GlyphBox { - GlyphBox { - text, - row, - left: px(left), - right: px(right), - } - } - - #[test] - fn range_boxes_join_the_glyphs_of_a_range_on_each_row() { - // "ab cd" wrapped after the space, glyphs 8px wide. - let glyphs = [ - glyph(0..1, 0, 0., 8.), - glyph(1..2, 0, 8., 16.), - glyph(2..3, 0, 16., 24.), - glyph(3..4, 1, 0., 8.), - glyph(4..5, 1, 8., 16.), - ]; - let boxes = |range| range_boxes(&glyphs, range); - assert_eq!(boxes(1..2), [(0, px(8.), px(16.))]); - assert_eq!(boxes(0..5), [(0, px(0.), px(24.)), (1, px(0.), px(16.))]); - // Starting at the wrap paints the next row only. - assert_eq!(boxes(3..5), [(1, px(0.), px(16.))]); - assert!(boxes(2..2).is_empty()); - } - - #[test] - fn range_boxes_follow_right_to_left_glyphs() { - // Three two-byte letters painted right to left: the first letter's - // glyph is the rightmost. - let glyphs = [ - glyph(0..2, 0, 16., 24.), - glyph(2..4, 0, 8., 16.), - glyph(4..6, 0, 0., 8.), - ]; - assert_eq!(range_boxes(&glyphs, 0..2), [(0, px(16.), px(24.))]); - assert_eq!(range_boxes(&glyphs, 2..6), [(0, px(0.), px(16.))]); - } - - #[test] - fn range_boxes_cover_a_glyph_drawing_part_of_the_range() { - // A ligature drawing "fi" in one glyph. - let glyphs = [glyph(0..2, 0, 0., 10.), glyph(2..3, 0, 10., 15.)]; - assert_eq!(range_boxes(&glyphs, 1..2), [(0, px(0.), px(10.))]); - } - - #[test] - fn combine_highlights_cuts_a_bold_span_at_the_code_boundary() { - // `**bold `code`**`: the bold mark spans the code mark, so the - // combined list carries the weight on both sides and the family on - // the code side only. - let bold = InlineHighlight::from(HighlightStyle { - font_weight: Some(FontWeight::BOLD), - ..Default::default() - }); - let combined = combine_highlights( - vec![(0..10, bold)], - vec![(6..10, mono(HighlightStyle::default()))], - ); - - assert_eq!(combined.len(), 2); - assert_eq!(combined[0].0, 0..6); - assert_eq!(combined[0].1.style.font_weight, Some(FontWeight::BOLD)); - assert_eq!(combined[0].1.font_family, None); - assert_eq!(combined[1].0, 6..10); - assert_eq!(combined[1].1.style.font_weight, Some(FontWeight::BOLD)); - assert_eq!(combined[1].1.font_family.as_deref(), Some("Mono")); - } - - #[test] - fn test_point_in_text_selection() { - let line_height = px(20.); - let char_width = px(10.); - let start = point(px(50.), px(50.)); - let end = point(px(150.), px(150.)); - - // First line but haft line height, true - // | p --------| - // | selection | - // |-----------| - assert!(point_in_text_selection( - point(px(50.), px(40.)), - char_width, - start, - end, - line_height - )); - - // First line in selection, true - // | p --------| - // | selection | - // |-----------| - assert!(point_in_text_selection( - point(px(50.), px(50.)), - char_width, - start, - end, - line_height - )); - // First line, but left out of selection, false - // p |-----------| - // | selection | - // |-----------| - assert!(!point_in_text_selection( - point(px(40.), px(50.)), - char_width, - start, - end, - line_height - )); - // First line but right out of selection, true - // |-----------| p - // | selection | - // |-----------| - assert!(point_in_text_selection( - point(px(160.), px(50.)), - char_width, - start, - end, - line_height - )); - - // Middle line in selection, true - // |-----------| - // | p | - // |-----------| - assert!(point_in_text_selection( - point(px(100.), px(70.)), - char_width, - start, - end, - line_height - )); - // Middle line, but left out of selection, true - // |-----------| - // p | selection | - // |-----------| - assert!(point_in_text_selection( - point(px(40.), px(70.)), - char_width, - start, - end, - line_height - )); - // Middle line, but right out of selection, true - // |-----------| - // | selection | p - // |-----------| - assert!(point_in_text_selection( - point(px(160.), px(70.)), - char_width, - start, - end, - line_height - )); - - // Last line in selection, true - // |-----------| - // | selection | - // |------- p -| - assert!(point_in_text_selection( - point(px(100.), px(140.)), - char_width, - start, - end, - line_height - )); - // Last line, but left out of selection, true - // - // |-----------| - // | selection | - // p |-----------| - assert!(point_in_text_selection( - point(px(40.), px(140.)), - char_width, - start, - end, - line_height - )); - // Last line, but right out of selection, false - // |-----------| - // | selection | - // |-----------| p - assert!(!point_in_text_selection( - point(px(160.), px(140.)), - char_width, - start, - end, - line_height - )); - - // Out of vertical bounds (top), false - // p - // |-----------| - // | selection | - // |-----------| - assert!(!point_in_text_selection( - point(px(100.), px(20.)), - char_width, - start, - end, - line_height - )); - // Out of vertical bounds (bottom), false - // |-----------| - // | selection | - // |-----------| - // p - assert!(!point_in_text_selection( - point(px(100.), px(160.)), - char_width, - start, - end, - line_height - )); - } - - #[test] - fn test_point_in_text_selection_reversed_drag_direction() { - let line_height = px(20.); - let char_width = px(10.); - - // Mouse down on lower line then drag upward to x=150. - // Top line should follow current mouse x, bottom line should keep anchor x. - let start = point(px(80.), px(150.)); - let end = point(px(150.), px(50.)); - - // On top line, selection starts from top cursor x (150), so x=140 should be excluded. - assert!(!point_in_text_selection( - point(px(140.), px(50.)), - char_width, - start, - end, - line_height - )); - assert!(point_in_text_selection( - point(px(150.), px(50.)), - char_width, - start, - end, - line_height - )); - - // On bottom line, selection ends at anchor x (80), so x=90 should be excluded. - assert!(point_in_text_selection( - point(px(75.), px(140.)), - char_width, - start, - end, - line_height - )); - assert!(!point_in_text_selection( - point(px(80.), px(140.)), - char_width, - start, - end, - line_height - )); - } - - #[test] - fn test_point_in_text_selection_same_visual_line_with_different_y() { - let line_height = px(20.); - let char_width = px(10.); - let start = point(px(100.), px(55.)); - let end = point(px(60.), px(58.)); - - assert!(!point_in_text_selection( - point(px(40.), px(50.)), - char_width, - start, - end, - line_height - )); - assert!(point_in_text_selection( - point(px(70.), px(50.)), - char_width, - start, - end, - line_height - )); - assert!(!point_in_text_selection( - point(px(110.), px(50.)), - char_width, - start, - end, - line_height - )); - } - - #[test] - fn test_point_in_text_selection_same_visual_line_with_reversed_y() { - let line_height = px(20.); - let char_width = px(10.); - let start = point(px(60.), px(58.)); - let end = point(px(100.), px(55.)); - - assert!(!point_in_text_selection( - point(px(40.), px(50.)), - char_width, - start, - end, - line_height - )); - assert!(point_in_text_selection( - point(px(70.), px(50.)), - char_width, - start, - end, - line_height - )); - assert!(!point_in_text_selection( - point(px(110.), px(50.)), - char_width, - start, - end, - line_height - )); - } -} - +pub(super) mod test_fonts; #[cfg(test)] -mod retained_layout_tests { - use gpui::{ - AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, - TestAppContext, Window, div, px, - }; - - use super::RETAINED_LAYOUTS; - use crate::text::{TextView, TextViewState}; - - /// The same document shown twice in one window, as a preview beside the - /// text: both `Inline`s share every `InlineState`. - struct Twice { - state: Entity, - } - - impl Render for Twice { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div() - .w(px(300.)) - .child(TextView::new(&self.state)) - .child(TextView::new(&self.state)) - } - } - - /// Without the hand-over rule the second copy's prepaint replaced the - /// first copy's entry, and the first copy painted with the second's - /// layout — at the second's bounds. - #[gpui::test] - fn the_same_paragraph_rendered_twice_in_a_frame_keeps_one_layout_and_paints_both( - cx: &mut TestAppContext, - ) { - cx.update(crate::init); - let (_, cx) = cx.add_window_view(|_, cx| Twice { - state: cx - .new(|cx| TextViewState::markdown("First paragraph.\n\nSecond **paragraph**.", cx)), - }); - cx.run_until_parked(); - - // Frame 1 fills the table, frame 2 reuses it; neither may lose the - // shaped text of either copy (painting an unmeasured placeholder - // panics inside GPUI). - for _ in 0..3 { - cx.update(|window, cx| window.draw(cx).clear(cx)); - } - - let retained = RETAINED_LAYOUTS.with(|layouts| layouts.borrow().len()); - assert_eq!(retained, 2, "one layout per paragraph state"); - } - - struct Once { - state: Entity, - } - - impl Render for Once { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div().w(px(300.)).child(TextView::new(&self.state)) - } - } - - /// A paragraph with a code span is laid out by `InlineFlow`, as one - /// `Inline` per wrapped fragment. The fragments' states have to outlive - /// the frame, or every frame shapes the fragments again and leaves the - /// table an entry nobody will take. - #[gpui::test] - fn inline_flow_fragments_keep_their_layouts_across_frames(cx: &mut TestAppContext) { - cx.update(crate::init); - let (_, cx) = cx.add_window_view(|_, cx| Once { - state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), - }); - cx.run_until_parked(); - - for _ in 0..3 { - cx.update(|window, cx| window.draw(cx).clear(cx)); - } - - // "Call ", "foo" and " now.": three fragments on one line. - let (retained, alive) = RETAINED_LAYOUTS.with(|layouts| { - let layouts = layouts.borrow(); - ( - layouts.len(), - layouts - .values() - .filter(|retained| retained.state.strong_count() > 0) - .count(), - ) - }); - assert_eq!(retained, 3, "one layout per fragment"); - assert_eq!( - alive, 3, - "every retained layout belongs to a live fragment state" - ); - } - - #[gpui::test] - fn shortening_an_inline_flow_releases_obsolete_fragment_layouts(cx: &mut TestAppContext) { - cx.update(crate::init); - let source = "word `code` ".repeat(100); - let (view, cx) = cx.add_window_view(|_, cx| Once { - state: cx.new(|cx| TextViewState::markdown(&source, cx)), - }); - cx.run_until_parked(); - for _ in 0..2 { - cx.update(|window, cx| window.draw(cx).clear(cx)); - } - - view.update(cx, |view, cx| { - view.state.update(cx, |state, cx| { - state.set_text("word `code` now", cx); - }); - }); - cx.run_until_parked(); - for _ in 0..2 { - cx.update(|window, cx| window.draw(cx).clear(cx)); - } - - let alive = RETAINED_LAYOUTS.with(|layouts| { - layouts - .borrow() - .values() - .filter(|retained| retained.state.strong_count() > 0) - .count() - }); - assert_eq!(alive, 3, "one live layout per remaining fragment"); - } -} +mod tests; diff --git a/vendor/gpui-base/src/text/inline/fade_highlights_tests.rs b/vendor/gpui-base/src/text/inline/fade_highlights_tests.rs new file mode 100644 index 00000000..c22e76eb --- /dev/null +++ b/vendor/gpui-base/src/text/inline/fade_highlights_tests.rs @@ -0,0 +1,36 @@ +use super::{InlineHighlight, fade_highlights}; +use gpui::HighlightStyle; + +#[test] +fn fades_text_and_background_only_inside_the_range() { + let code = InlineHighlight::from(HighlightStyle { + background_color: Some(gpui::red()), + ..Default::default() + }); + let combined = fade_highlights(vec![(0..4, code)], &[(2..6, 0.5)]); + + let ranges: Vec<_> = combined.iter().map(|(range, _)| range.clone()).collect(); + assert_eq!(ranges, vec![0..2, 2..4, 4..6]); + + let (_, untouched) = &combined[0]; + assert_eq!(untouched.style.fade_out, None); + assert_eq!(untouched.style.background_color.unwrap().a, 1.0); + + let (_, faded_code) = &combined[1]; + assert_eq!(faded_code.style.fade_out, Some(0.5)); + assert_eq!(faded_code.style.background_color.unwrap().a, 0.5); + + let (_, faded_text) = &combined[2]; + assert_eq!(faded_text.style.fade_out, Some(0.5)); + assert!(faded_text.style.background_color.is_none()); +} + +#[test] +fn no_fades_leave_highlights_untouched() { + let bold = InlineHighlight::from(HighlightStyle { + font_weight: Some(gpui::FontWeight::BOLD), + ..Default::default() + }); + let highlights = vec![(1..3, bold)]; + assert_eq!(fade_highlights(highlights.clone(), &[]), highlights); +} diff --git a/vendor/gpui-base/src/text/inline/geometry.rs b/vendor/gpui-base/src/text/inline/geometry.rs new file mode 100644 index 00000000..b30434cc --- /dev/null +++ b/vendor/gpui-base/src/text/inline/geometry.rs @@ -0,0 +1,204 @@ +use gpui::{Bounds, Half, Pixels, Point, TextAlign, TextLayout}; +use std::ops::Range; + +use crate::text::{TextViewMultiClickKind, selection::word_range_at}; + +/// Where one glyph of laid-out text paints: its row, and its horizontal +/// extent past the text's origin, alignment applied. `text` is the byte range +/// of the text it draws. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct GlyphBox { + pub(super) text: Range, + pub(super) row: usize, + pub(super) left: Pixels, + pub(super) right: Pixels, +} + +/// The glyphs of `text_layout`, sorted by the text they draw, each placed +/// the way GPUI paints it: every row aligned in `align_width` by `align`, +/// and a glyph reaching to the next one on its row, or to the row's end. +/// +/// Glyphs are read in the order they paint, so right-to-left text, whose +/// glyphs paint in the reverse order of its text, is placed as it shows. +pub(super) fn glyph_boxes( + text_layout: &TextLayout, + align: TextAlign, + align_width: Pixels, +) -> Vec { + let mut boxes = Vec::new(); + let mut row = 0; + let mut line_start = 0; + for line in text_layout.line_layouts() { + let layout = &line.unwrapped_layout; + let glyphs = layout + .runs + .iter() + .flat_map(|run| run.glyphs.iter()) + .collect::>(); + // Each row starts at a wrap boundary glyph, and ends where the next + // row starts, or at the end of the line. + let run_offsets = layout + .runs + .iter() + .scan(0, |offset, run| { + let start = *offset; + *offset += run.glyphs.len(); + Some(start) + }) + .collect::>(); + let row_starts = line + .wrap_boundaries + .iter() + .map(|boundary| run_offsets[boundary.run_ix] + boundary.glyph_ix) + .collect::>(); + let line_boxes = boxes.len(); + let mut from = 0; + for (row_in_line, to) in row_starts.iter().copied().chain([glyphs.len()]).enumerate() { + let start_x = if row_in_line == 0 { + Pixels::ZERO + } else { + glyphs[from].position.x + }; + let end_x = glyphs + .get(to) + .map_or(layout.width, |glyph| glyph.position.x); + let shift = aligned_row_left(align, align_width, end_x - start_x) - start_x; + for ix in from..to { + let glyph = glyphs[ix]; + let right = if ix + 1 < to { + glyphs[ix + 1].position.x + } else { + end_x + }; + boxes.push(GlyphBox { + text: line_start + glyph.index..line_start + glyph.index, + row: row + row_in_line, + left: shift + glyph.position.x, + right: shift + right, + }); + } + from = to; + } + + // A glyph draws its text up to where the next glyph's text starts. + let line_boxes = &mut boxes[line_boxes..]; + line_boxes.sort_by_key(|glyph| glyph.text.start); + let line_end = line_start + line.len(); + for ix in 0..line_boxes.len() { + let start = line_boxes[ix].text.start; + line_boxes[ix].text.end = line_boxes[ix + 1..] + .iter() + .map(|glyph| glyph.text.start) + .find(|next| *next > start) + .unwrap_or(line_end); + } + + row += line.wrap_boundaries.len() + 1; + line_start = line_end + 1; + } + boxes +} + +pub(super) fn aligned_row_left(align: TextAlign, align_width: Pixels, width: Pixels) -> Pixels { + match align { + TextAlign::Left => Pixels::ZERO, + TextAlign::Center => (align_width - width) / 2., + TextAlign::Right => align_width - width, + } +} + +/// The boxes behind the text of `range`, as a row and the horizontal extent +/// on it, from `glyphs` sorted by the text they draw: every glyph drawing +/// some of that text, joined where they touch on a row. +pub(super) fn range_boxes( + glyphs: &[GlyphBox], + range: Range, +) -> Vec<(usize, Pixels, Pixels)> { + let first = glyphs.partition_point(|glyph| glyph.text.end <= range.start); + let mut hits = glyphs[first..] + .iter() + .take_while(|glyph| glyph.text.start < range.end) + .map(|glyph| (glyph.row, glyph.left, glyph.right)) + .collect::>(); + hits.sort_by(|a, b| { + (a.0, a.1) + .partial_cmp(&(b.0, b.1)) + .unwrap_or(std::cmp::Ordering::Equal) + }); + + let mut boxes: Vec<(usize, Pixels, Pixels)> = Vec::with_capacity(hits.len()); + for (row, left, right) in hits { + match boxes.last_mut() { + Some(last) if last.0 == row && left <= last.2 => last.2 = last.2.max(right), + _ => boxes.push((row, left, right)), + } + } + boxes +} + +/// Check if a `pos` is within a `bounds`, considering multi-line selections. +pub(in crate::text) fn point_in_text_selection( + pos: Point, + char_width: Pixels, + selection_start: Point, + selection_end: Point, + line_height: Pixels, +) -> bool { + let point_in_line = |point: Point| point.y >= pos.y && point.y < pos.y + line_height; + let top = selection_start.y.min(selection_end.y); + let bottom = selection_start.y.max(selection_end.y); + let x = pos.x + char_width.half(); + + // Out of the vertical bounds + if pos.y + line_height <= top || pos.y > bottom { + return false; + } + + // Treat the selection as single-line when both drag points fall within the + // same rendered line, even if their y coordinates differ inside that line. + if point_in_line(selection_start) && point_in_line(selection_end) { + let left = selection_start.x.min(selection_end.x); + let right = selection_start.x.max(selection_end.x); + return x >= left && x <= right; + } + + let (top_point, bottom_point) = if selection_start.y < selection_end.y { + (selection_start, selection_end) + } else { + (selection_end, selection_start) + }; + let is_top_line = point_in_line(top_point); + let is_bottom_line = point_in_line(bottom_point); + + if is_top_line { + return x >= top_point.x; + } else if is_bottom_line { + return x <= bottom_point.x; + } else { + return true; + } +} + +pub(super) fn selection_for_multi_click( + text: &str, + text_layout: &TextLayout, + bounds: Bounds, + pos: Point, + kind: TextViewMultiClickKind, +) -> Option> { + if !bounds.contains(&pos) { + return None; + } + + let offset = text_layout.index_for_position(pos).ok()?; + + match kind { + TextViewMultiClickKind::Word => word_range_at(text, offset), + // Known limitation: a paragraph maps to a single Inline run here. When a + // paragraph embeds an inline image it is split into multiple Inline runs, + // so triple-click only selects the run on the clicked side of the image. + TextViewMultiClickKind::Paragraph | TextViewMultiClickKind::Line => { + (!text.is_empty()).then_some(0..text.len()) + } + } +} diff --git a/vendor/gpui-base/src/text/inline/highlights.rs b/vendor/gpui-base/src/text/inline/highlights.rs new file mode 100644 index 00000000..d51d69d3 --- /dev/null +++ b/vendor/gpui-base/src/text/inline/highlights.rs @@ -0,0 +1,214 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use gpui::{HighlightStyle, SharedString, TextRun, TextStyle}; +use smallvec::SmallVec; +use std::{mem, ops::Range}; + +/// The style applied to one range of inline text. +/// +/// A [`HighlightStyle`] carries no font family, so the family an inline code +/// span is set in rides beside it; `None` keeps the family of the enclosing +/// text style. +#[derive(Clone, Debug, Default, PartialEq)] +pub(in crate::text) struct InlineHighlight { + pub(in crate::text) style: HighlightStyle, + pub(in crate::text) font_family: Option, + pub(in crate::text) font_size_scale: Option, +} + +impl InlineHighlight { + /// Layers `other` over `self`, the way [`HighlightStyle::highlight`] does. + fn highlight(mut self, other: &InlineHighlight) -> Self { + self.style = self.style.highlight(other.style); + if other.font_family.is_some() { + self.font_family = other.font_family.clone(); + } + if other.font_size_scale.is_some() { + self.font_size_scale = other.font_size_scale; + } + self + } +} + +impl From for InlineHighlight { + fn from(style: HighlightStyle) -> Self { + Self { + style, + font_family: None, + font_size_scale: None, + } + } +} + +/// Merges two highlight lists over one text into non-overlapping ranges, +/// cutting at every endpoint of every input range. Same sweep as +/// [`gpui::combine_highlights`], for [`InlineHighlight`] payloads. +pub(super) fn combine_highlights( + a: impl IntoIterator, InlineHighlight)>, + b: impl IntoIterator, InlineHighlight)>, +) -> Vec<(Range, InlineHighlight)> { + let mut endpoints = Vec::new(); + let mut highlights = Vec::new(); + for (range, highlight) in a.into_iter().chain(b) { + if !range.is_empty() { + let id = highlights.len(); + endpoints.push((range.start, id, true)); + endpoints.push((range.end, id, false)); + highlights.push(highlight); + } + } + endpoints.sort_unstable_by_key(|(position, _, _)| *position); + + let mut combined = Vec::new(); + let mut active: Vec = Vec::new(); + let mut ix = 0; + for (position, id, is_start) in endpoints { + if position > ix && !active.is_empty() { + let style = active.iter().fold(InlineHighlight::default(), |acc, id| { + acc.highlight(&highlights[*id]) + }); + combined.push((ix..position, style)); + } + ix = position; + if is_start { + active.push(id); + } else { + active.retain(|active_id| *active_id != id); + } + } + combined +} + +// Nocterm: adjacent inline children usually contribute zero or one mark. +// Sweep only when marks overlap, so long paragraphs do not rebuild every +// earlier highlight while visiting each unstyled or singly styled child. +pub(in crate::text) fn append_node_highlights( + highlights: &mut Vec<(Range, InlineHighlight)>, + mut node: SmallVec<[(Range, InlineHighlight); 2]>, +) { + node.retain(|(span, _)| span.start < span.end); + let Some((first, _)) = node.first() else { + return; + }; + if highlights + .last() + .is_none_or(|(last, _)| last.end <= first.start) + && node.windows(2).all(|pair| pair[0].0.end <= pair[1].0.start) + { + highlights.extend(node); + } else { + *highlights = combine_highlights(mem::take(highlights), node); + } +} + +/// Layers a streamed fade-in over `highlights`: text inside each fade range +/// loses that share of its color, and a highlight background fades with it so +/// an inline code chip does not appear before its text. +pub(in crate::text) fn fade_highlights( + highlights: Vec<(Range, InlineHighlight)>, + fades: &[(Range, f32)], +) -> Vec<(Range, InlineHighlight)> { + if fades.is_empty() { + return highlights; + } + let fade_highlights = fades.iter().map(|(range, fade_out)| { + ( + range.clone(), + InlineHighlight::from(HighlightStyle { + fade_out: Some(*fade_out), + ..Default::default() + }), + ) + }); + let mut combined = combine_highlights(highlights, fade_highlights); + for (_, highlight) in &mut combined { + if let Some(fade_out) = highlight.style.fade_out + && let Some(background) = highlight.style.background_color.as_mut() + { + background.fade_out(fade_out); + } + } + combined +} + +/// Builds the [`TextRun`]s for `text_len` bytes of inline text: each +/// highlight refines `default_style` over its range, and a highlight that +/// names a font family shapes its run in that family. +pub(in crate::text) fn text_runs( + text_len: usize, + default_style: &TextStyle, + highlights: &[(Range, InlineHighlight)], +) -> Vec { + let mut runs = Vec::with_capacity(highlights.len() * 2 + 1); + let mut ix = 0; + for (range, highlight) in highlights { + if ix < range.start { + runs.push(default_style.clone().to_run(range.start - ix)); + } + let mut run = default_style + .clone() + .highlight(highlight.style) + .to_run(range.len()); + if let Some(family) = &highlight.font_family { + run.font.family = family.clone(); + } + runs.push(run); + ix = range.end; + } + if ix < text_len { + runs.push(default_style.to_run(text_len - ix)); + } + runs +} + +/// Splits text into contiguous ranges sharing one font size. GPUI runs can +/// vary the font but not its size, so each range needs its own shaped line. +pub(in crate::text) fn text_size_ranges( + text_len: usize, + highlights: &[(Range, InlineHighlight)], +) -> Vec<(Range, f32)> { + text_size_ranges_in(0..text_len, highlights) +} + +/// Selects highlights intersecting `span`. The input ranges are sorted and +/// disjoint, as produced by the inline highlight composition. +pub(in crate::text) fn highlights_in_range<'a>( + highlights: &'a [(Range, InlineHighlight)], + span: &Range, +) -> &'a [(Range, InlineHighlight)] { + let first = highlights.partition_point(|(range, _)| range.end <= span.start); + let remaining = &highlights[first..]; + let last = remaining.partition_point(|(range, _)| range.start < span.end); + &remaining[..last] +} + +/// Font-size segments clipped to an absolute byte range of the original text. +pub(in crate::text) fn text_size_ranges_in( + span: Range, + highlights: &[(Range, InlineHighlight)], +) -> Vec<(Range, f32)> { + let mut ranges: Vec<(Range, f32)> = Vec::new(); + let mut push = |range: Range, scale: f32| { + if range.is_empty() { + return; + } + if let Some((last, last_scale)) = ranges.last_mut() + && *last_scale == scale + && last.end == range.start + { + last.end = range.end; + } else { + ranges.push((range, scale)); + } + }; + let mut cursor = span.start; + for (range, highlight) in highlights_in_range(highlights, &span) { + let start = span.start.max(range.start); + let end = span.end.min(range.end); + push(cursor..start, 1.); + push(start..end, highlight.font_size_scale.unwrap_or(1.)); + cursor = end; + } + push(cursor..span.end, 1.); + ranges +} diff --git a/vendor/gpui-base/src/text/inline/line_bounds_tests.rs b/vendor/gpui-base/src/text/inline/line_bounds_tests.rs new file mode 100644 index 00000000..a147fb8f --- /dev/null +++ b/vendor/gpui-base/src/text/inline/line_bounds_tests.rs @@ -0,0 +1,149 @@ +use super::*; +use super::{ + test_draw::in_prepaint, + test_fonts::{BODY, WideMonoTextSystem}, +}; +use gpui::{AvailableSpace, TestApp, size}; + +/// The character walk this replaced, kept as the oracle: one box per +/// character from `position_for_index`, unioned per row. +fn by_character( + text: &str, + text_layout: &TextLayout, + line_height: Pixels, + mask_bounds: Bounds, +) -> Vec> { + let mut line_bounds = Vec::new(); + let mut current_line_y = None; + let mut current_bounds: Option> = None; + let mut offset = 0; + for c in text.chars() { + let next_offset = offset + c.len_utf8(); + let Some(pos) = text_layout.position_for_index(offset) else { + offset = next_offset; + continue; + }; + let mut char_width = line_height.half(); + if let Some(next_pos) = text_layout.position_for_index(next_offset) + && next_pos.y == pos.y + { + char_width = next_pos.x - pos.x; + } + let bounds = Bounds::from_corners(pos, point(pos.x + char_width, pos.y + line_height)) + .intersect(&mask_bounds); + if bounds.size.width > px(0.) && bounds.size.height > px(0.) { + if current_line_y == Some(pos.y) { + if let Some(current) = current_bounds.as_mut() { + *current = current.union(&bounds); + } + } else { + if let Some(current) = current_bounds.take() { + line_bounds.push(current); + } + current_line_y = Some(pos.y); + current_bounds = Some(bounds); + } + } + offset = next_offset; + } + if let Some(current) = current_bounds { + line_bounds.push(current); + } + line_bounds +} + +#[test] +fn row_walk_matches_the_character_walk() { + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + in_prepaint(&mut app, |window, cx| { + let style = TextStyle { + font_family: BODY.into(), + font_size: px(16.).into(), + ..Default::default() + }; + let origin = point(px(7.), px(11.)); + let mask = Bounds::new(point(px(0.), px(0.)), size(px(1000.), px(1000.))); + let clipped = Bounds::new(point(px(20.), px(30.)), size(px(50.), px(60.))); + for text in [ + "", + "one row", + "a long paragraph that wraps onto several rows of eight pixel glyphs", + "first line\nsecond line that also wraps around\n\nfourth", + "中文与 English 混排的一段文字也会换行", + "trailing newline\n", + ] { + for wrap_width in [40., 100., 1000.] { + let runs = text_runs(text.len(), &style, &[]); + let styled = StyledText::new(SharedString::from(text.to_string())).with_runs(runs); + let layout = styled.layout().clone(); + let mut element = styled.into_any_element(); + element.layout_as_root( + size( + AvailableSpace::Definite(px(wrap_width)), + AvailableSpace::MinContent, + ), + window, + cx, + ); + element.prepaint_at(origin, window, cx); + let line_height = layout.line_height(); + let full = Inline::text_line_bounds(&layout, line_height, mask); + for mask in [ + mask, + clipped, + Bounds::new( + point(origin.x, origin.y + line_height), + size(px(100.), line_height), + ), + Bounds::new( + point(origin.x, layout.bounds().bottom()), + size(px(100.), line_height), + ), + ] { + let expected = by_character(text, &layout, line_height, mask); + let actual = Inline::text_line_bounds(&layout, line_height, mask); + let clipped_full: Vec<_> = full + .iter() + .map(|bounds| bounds.intersect(&mask)) + .filter(|bounds| bounds.size.width > px(0.) && bounds.size.height > px(0.)) + .collect(); + assert_eq!(actual, clipped_full); + let context = format!("{text:?} at {wrap_width}px in {mask:?}"); + // The character walk placed a wrapped row's first + // character at the end of the row before it: that row's + // box started one glyph in, and a row holding only that + // one glyph had no box at all. The row walk covers every + // row from its start, so it may see more rows, never + // fewer, and agrees on every row the walk could see. + assert!( + actual.len() >= expected.len(), + "rows of {context}: {} < {}", + actual.len(), + expected.len() + ); + for (row, expected) in expected.iter().enumerate() { + let actual = actual + .iter() + .find(|actual| actual.top() == expected.top()) + .unwrap_or_else(|| panic!("row {row} of {context} is missing")); + assert_eq!(actual.bottom(), expected.bottom(), "row {row} of {context}"); + assert_eq!(actual.right(), expected.right(), "row {row} of {context}"); + assert!( + actual.left() <= expected.left(), + "row {row} of {context} starts at {:?}, after {:?}", + actual.left(), + expected.left() + ); + } + for actual in &actual { + assert_eq!( + actual.left(), + origin.x.max(mask.left()), + "left of {context}" + ); + } + } + } + } + }); +} diff --git a/vendor/gpui-base/src/text/inline/pointer.rs b/vendor/gpui-base/src/text/inline/pointer.rs new file mode 100644 index 00000000..f36b3568 --- /dev/null +++ b/vendor/gpui-base/src/text/inline/pointer.rs @@ -0,0 +1,234 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use std::{ + ops::Range, + rc::Rc, + sync::{Arc, Mutex}, +}; + +use gpui::{ + App, Bounds, ClickEvent, CursorStyle, Hitbox, MouseButton, MouseClickEvent, MouseDownEvent, + MouseMoveEvent, MouseUpEvent, Pixels, Point, SharedString, TextLayout, Window, +}; + +use crate::{ + GlobalState, TextSelection, + text::TextViewMultiClickKind, + text::node::LinkMark, + text::text_view::{LinkClickHandlerFn, handle_link_click}, +}; + +use super::{InlineState, geometry::selection_for_multi_click}; + +/// The geometry and callbacks used to install one inline's pointer handlers. +pub(super) struct InlinePointer<'a> { + pub(super) hitbox: &'a Hitbox, + pub(super) text_layout: &'a TextLayout, + pub(super) inline_state: &'a Arc>, + pub(super) text: &'a SharedString, + pub(super) links: &'a Rc, LinkMark)>>, + pub(super) link_click_handler: &'a Option>, + pub(super) line_bounds: Option>, +} + +impl InlinePointer<'_> { + pub(super) fn register( + self, + is_selectable: bool, + is_selection: bool, + window: &mut Window, + cx: &mut App, + ) { + let Self { + hitbox, + text_layout, + inline_state, + text, + links, + link_click_handler, + line_bounds, + } = self; + let has_links = !links.is_empty(); + let current_view = window.current_view(); + let text_view_state = GlobalState::global(cx).text_view_state().cloned(); + if is_selection || is_selectable { + window.set_cursor_style(CursorStyle::IBeam, hitbox); + } + + // link cursor pointer + let hovered_link = has_links + .then(|| link_range_for_position(text_layout, links, window.mouse_position())) + .flatten(); + if hovered_link.is_some() { + window.set_cursor_style(CursorStyle::PointingHand, hitbox); + } + + if is_selectable { + window.on_mouse_event({ + let hitbox = hitbox.clone(); + let text_layout = text_layout.clone(); + let inline_state = inline_state.clone(); + let text = text.clone(); + let text_view_state = text_view_state.clone(); + move |event: &MouseDownEvent, phase, window, cx| { + if !phase.bubble() + || !hitbox.is_hovered(window) + || event.button != MouseButton::Left + { + return; + } + + if event.click_count == 3 + && let Some(line_bounds) = line_bounds + { + GlobalState::suppress_text_selection(cx); + if let Some(view) = &text_view_state { + view.update(cx, |state, cx| { + state.set_multi_click_line(line_bounds, cx) + }); + } + cx.notify(current_view); + return; + } + + // A finger selects read-only text with a long press only; + // a double tap selects nothing here, neither the mouse's + // plain word nor the window layer's touch selection. The + // handles and the menu on a double tap belong to `Input`. + if event.click_count == 2 && GlobalState::is_touch_press(cx) { + GlobalState::suppress_text_selection(cx); + return; + } + + let kind = match event.click_count { + 2 => TextViewMultiClickKind::Word, + 3 => TextViewMultiClickKind::Paragraph, + _ => return, + }; + + let Some(range) = selection_for_multi_click( + &text, + &text_layout, + hitbox.bounds, + event.position, + kind, + ) else { + return; + }; + + let selected_text = text[range.clone()].to_string(); + + // This renderer owns multi-click selection. Prevent the + // window selection layer from handling the same press. + GlobalState::suppress_text_selection(cx); + + if let Ok(mut inline_state) = inline_state.lock() { + inline_state.selection = Some(range.into()); + } + if let Some(text_view_state) = &text_view_state { + text_view_state.update(cx, |state, cx| { + state.set_multi_click_selection( + event.position, + kind, + selected_text, + cx, + ); + }); + } + cx.notify(current_view); + } + }); + } + + // Mouse move: repaint only when the pointer enters, leaves or moves + // between links, so the link cursor follows it. Hovering plain text + // changes nothing painted. + if has_links { + window.on_mouse_event({ + let hitbox = hitbox.clone(); + let text_layout = text_layout.clone(); + let links = links.clone(); + let mut hovered_link = hovered_link; + move |event: &MouseMoveEvent, phase, window, cx| { + if !phase.bubble() || !hitbox.is_hovered(window) { + return; + } + + let updated = link_range_for_position(&text_layout, &links, event.position); + if hovered_link != updated { + hovered_link = updated; + cx.notify(current_view); + } + } + }); + } + + if has_links && !is_selection { + // click to open link + window.on_mouse_event({ + let links = links.clone(); + let text_layout = text_layout.clone(); + let hitbox = hitbox.clone(); + let text_view_state = text_view_state.clone(); + let link_click_handler = link_click_handler.clone(); + + move |event: &MouseUpEvent, phase, window, cx| { + if !phase.bubble() || !hitbox.is_hovered(window) { + return; + } + if text_view_state + .as_ref() + .is_some_and(|state| state.read(cx).has_selection(cx)) + { + return; + } + + if let Some(link) = link_for_position(&text_layout, &links, event.position) { + TextSelection::end(window, cx); + cx.stop_propagation(); + let click = ClickEvent::Mouse(MouseClickEvent { + down: MouseDownEvent { + button: event.button, + position: event.position, + modifiers: event.modifiers, + click_count: event.click_count, + first_mouse: false, + }, + up: event.clone(), + }); + handle_link_click(&link_click_handler, link.url, click, window, cx); + } + } + }); + } + } +} + +/// Get link at given mouse position. +fn link_for_position( + layout: &TextLayout, + links: &[(Range, LinkMark)], + position: Point, +) -> Option { + let offset = layout.index_for_position(position).ok()?; + for (range, link) in links.iter() { + if range.contains(&offset) { + return Some(link.clone()); + } + } + + None +} + +/// Get the range of the link at given mouse position. +fn link_range_for_position( + layout: &TextLayout, + links: &[(Range, LinkMark)], + position: Point, +) -> Option> { + let offset = layout.index_for_position(position).ok()?; + links + .iter() + .find(|(range, _)| range.contains(&offset)) + .map(|(range, _)| range.clone()) +} diff --git a/vendor/gpui-base/src/text/inline/range_highlight_tests.rs b/vendor/gpui-base/src/text/inline/range_highlight_tests.rs new file mode 100644 index 00000000..dd7b3546 --- /dev/null +++ b/vendor/gpui-base/src/text/inline/range_highlight_tests.rs @@ -0,0 +1,160 @@ +use super::*; +use super::{ + test_draw::in_prepaint, + test_fonts::{BODY, WideMonoTextSystem}, +}; +use gpui::{AvailableSpace, TestApp, TextAlign, size}; + +/// Lays `text` out at `wrap_width` and returns the highlight boxes of +/// `range` with rows aligned by `align`: the left and right edges past +/// the text's origin, and the row. +fn boxes( + text: &'static str, + wrap_width: f32, + align: TextAlign, + range: Range, +) -> Vec<(Pixels, Pixels, usize)> { + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + in_prepaint(&mut app, move |window, cx| { + let style = TextStyle { + font_family: BODY.into(), + font_size: px(16.).into(), + ..Default::default() + }; + let styled = + StyledText::new(SharedString::from(text)).with_runs(text_runs(text.len(), &style, &[])); + let layout = styled.layout().clone(); + let mut element = styled.into_any_element(); + element.layout_as_root( + size( + AvailableSpace::Definite(px(wrap_width)), + AvailableSpace::MinContent, + ), + window, + cx, + ); + let origin = point(px(7.), px(11.)); + element.prepaint_at(origin, window, cx); + let glyphs = glyph_boxes(&layout, align, layout.bounds().size.width); + range_boxes(&glyphs, range) + .into_iter() + .map(|(row, left, right)| (left, right, row)) + .collect() + }) +} + +/// The selection fast paths decide a whole inline from this extent, so it +/// must start exactly at the first row the per-character walk tests and +/// reach at least the bottom of the last one. It may reach further: a +/// trailing empty line, or a last row whose only character the walk +/// places at the end of the row before it, holds no row the walk tests. +#[test] +fn text_rows_extent_matches_the_character_walk() { + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + in_prepaint(&mut app, |window, cx| { + let style = TextStyle { + font_family: BODY.into(), + font_size: px(16.).into(), + ..Default::default() + }; + let origin = point(px(7.), px(11.3)); + for text in [ + "one row", + "a long paragraph that wraps onto several rows of eight pixel glyphs", + "first line\nsecond line that also wraps around\n\nfourth", + "中文与 English 混排的一段文字也会换行", + "trailing newline\n", + ] { + for wrap_width in [40., 100., 1000.] { + let runs = text_runs(text.len(), &style, &[]); + let styled = StyledText::new(SharedString::from(text.to_string())).with_runs(runs); + let layout = styled.layout().clone(); + let mut element = styled.into_any_element(); + element.layout_as_root( + size( + AvailableSpace::Definite(px(wrap_width)), + AvailableSpace::MinContent, + ), + window, + cx, + ); + element.prepaint_at(origin, window, cx); + // Taller than the layout's rows, as a window line height + // may be. + let line_height = layout.line_height() + px(3.); + let rows_y = text + .char_indices() + .filter_map(|(offset, _)| layout.position_for_index(offset)) + .map(|position| position.y); + let top = rows_y.clone().fold(Pixels::MAX, Pixels::min); + let bottom = rows_y.fold(Pixels::MIN, Pixels::max) + line_height; + + let (rows_top, rows_bottom) = text_rows_extent(&layout, line_height); + let context = format!("{text:?} at {wrap_width}px"); + assert_eq!(rows_top, top, "top of {context}"); + assert!(rows_bottom >= bottom, "bottom of {context}"); + } + } + }); +} + +#[test] +fn a_highlight_starting_a_wrapped_row_paints_only_that_row() { + // Three rows of "aaaa ", "bbbb ", "cccc". + let text = "aaaa bbbb cccc"; + let rows = boxes(text, 45., TextAlign::Left, 0..text.len()); + assert_eq!(rows.len(), 3, "{rows:?}"); + + let bbbb = text.find("bbbb").unwrap(); + let highlight = boxes(text, 45., TextAlign::Left, bbbb..bbbb + 4); + assert_eq!(highlight.len(), 1, "{highlight:?}"); + assert_eq!(highlight[0].0, px(0.)); + assert_eq!(highlight[0].2, 1); + + // Across the wrap, each row only as far as its text. + let across = boxes(text, 45., TextAlign::Left, 2..7); + assert_eq!(across.len(), 2, "{across:?}"); + assert_eq!(across[0].1, rows[0].1); + assert_eq!((across[1].0, across[1].2), (px(0.), 1)); +} + +#[test] +fn highlights_after_a_hard_line_break_start_on_its_row() { + // Rows "aa", "bbb cc": the break is one byte of the text, not a glyph. + let text = "aa\nbbb cc"; + let bbb = text.find("bbb").unwrap(); + let aa = boxes(text, 1000., TextAlign::Left, 0..2); + let highlight = boxes(text, 1000., TextAlign::Left, bbb..bbb + 3); + assert_eq!(highlight.len(), 1, "{highlight:?}"); + assert_eq!(highlight[0].0, px(0.)); + assert_eq!(highlight[0].2, 1); + // Three glyphs as wide as the two of "aa" and a half. + assert_eq!(highlight[0].1, (aa[0].1 - aa[0].0) * 1.5); +} + +#[test] +fn highlights_follow_centered_and_right_aligned_rows() { + // Rows "aaaa ", "bbbb ", "cc": the last is narrower than the text, so + // alignment moves it. + let text = "aaaa bbbb cc"; + let cc = text.find("cc").unwrap()..text.len(); + let widest = boxes(text, 45., TextAlign::Left, 0..5)[0].1; + let left = boxes(text, 45., TextAlign::Left, cc.clone())[0]; + let center = boxes(text, 45., TextAlign::Center, cc.clone())[0]; + let right = boxes(text, 45., TextAlign::Right, cc)[0]; + let width = left.1 - left.0; + assert!(width > px(0.) && width < widest, "{left:?} in {widest:?}"); + // GPUI aligns each row in the width of the laid-out text, the wrap + // width here. + let align_width = px(45.); + assert_eq!(left.0, px(0.)); + assert_eq!( + center, + ( + (align_width - width) / 2., + (align_width + width) / 2., + left.2 + ) + ); + assert_eq!(right, (align_width - width, align_width, left.2)); +} diff --git a/vendor/gpui-base/src/text/inline/retained_layout.rs b/vendor/gpui-base/src/text/inline/retained_layout.rs new file mode 100644 index 00000000..baa65e3b --- /dev/null +++ b/vendor/gpui-base/src/text/inline/retained_layout.rs @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::InlineState; +use gpui::{SharedString, StyledText, TextRun, TextStyle}; +use std::{ + cell::RefCell, + collections::HashMap, + sync::{Arc, Mutex, Weak}, +}; + +/// One frame's [`StyledText`], kept for the next frame's [`super::Inline`] of the +/// same [`InlineState`]. +/// +/// A [`gpui::TextLayout`] remembers the size and the shaped lines of its last +/// measurement and answers a repeated measure at the same wrap width from +/// them, but a fresh `StyledText` every frame throws that away, so every +/// frame of a scroll paid for a line wrapper, a shaping-cache lookup that +/// hashes the whole paragraph, and the allocations around them for every +/// visible paragraph. Handing the same `StyledText` to the next frame makes +/// those measurements hits. A layout is only reused when the text, the runs +/// (colors, fades, fonts) and the text style (font size, line height) it was +/// shaped with are unchanged; a different wrap width misses inside +/// `TextLayout` and reshapes as before. +/// +/// `StyledText` is main-thread only (an `Rc` inside), while `InlineState` +/// travels through the background parse, so the layouts live in a +/// thread-local table keyed by the state's address, with a `Weak` to tell a +/// live state from a reused address. +pub(super) struct RetainedLayout { + pub(super) styled_text: StyledText, + pub(super) text: SharedString, + pub(super) runs: Vec, + pub(super) text_style: TextStyle, +} + +type InlineOwner = Mutex; + +struct Entry { + state: Weak, + layout: RetainedLayout, +} + +#[derive(Default)] +struct RetainedLayouts { + entries: HashMap, + inserts_until_sweep: usize, +} + +thread_local! { + static RETAINED_LAYOUTS: RefCell = RefCell::new(RetainedLayouts::default()); +} + +const RETAINED_SWEEP_AT: usize = 4096; + +impl RetainedLayouts { + fn insert(&mut self, state: &Arc, layout: RetainedLayout) { + if self.inserts_until_sweep == 0 + && (self.entries.len() >= RETAINED_SWEEP_AT + || self.entries.capacity() > RETAINED_SWEEP_AT * 4) + { + self.entries + .retain(|_, entry| entry.state.strong_count() > 0); + let live_budget = self.entries.len().max(RETAINED_SWEEP_AT); + if self.entries.capacity() > live_budget.saturating_mul(4) { + self.entries.shrink_to(live_budget); + } + // A sweep visits the table's buckets even if most are empty. + self.inserts_until_sweep = self.entries.capacity().max(RETAINED_SWEEP_AT); + } + self.inserts_until_sweep = self.inserts_until_sweep.saturating_sub(1); + self.entries.insert( + state_key(state), + Entry { + state: Arc::downgrade(state), + layout, + }, + ); + } +} + +fn state_key(state: &Arc) -> usize { + Arc::as_ptr(state) as usize +} + +/// Takes the layout retained for this exact state. +pub(super) fn take_retained_layout(state: &Arc) -> Option { + RETAINED_LAYOUTS.with(|layouts| { + let entry = layouts.borrow_mut().entries.remove(&state_key(state))?; + entry + .state + .upgrade() + .is_some_and(|live| Arc::ptr_eq(&live, state)) + .then_some(entry.layout) + }) +} + +/// An element of the same state may have handed over its layout this frame. +pub(super) fn has_retained_layout(state: &Arc) -> bool { + RETAINED_LAYOUTS.with(|layouts| layouts.borrow().entries.contains_key(&state_key(state))) +} + +pub(super) fn retain_layout(state: &Arc, layout: RetainedLayout) { + RETAINED_LAYOUTS.with(|layouts| layouts.borrow_mut().insert(state, layout)); +} + +#[cfg(test)] +mod tests; diff --git a/vendor/gpui-base/src/text/inline/retained_layout/tests.rs b/vendor/gpui-base/src/text/inline/retained_layout/tests.rs new file mode 100644 index 00000000..4322a1bd --- /dev/null +++ b/vendor/gpui-base/src/text/inline/retained_layout/tests.rs @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: Apache-2.0 + +use gpui::{ + AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, + TestAppContext, Window, div, px, +}; + +use super::RETAINED_LAYOUTS; +use crate::text::{TextView, TextViewState}; + +/// The same document shown twice in one window, as a preview beside the +/// text: both `Inline`s share every `InlineState`. +struct Twice { + state: Entity, +} + +impl Render for Twice { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .w(px(300.)) + .child(TextView::new(&self.state)) + .child(TextView::new(&self.state)) + } +} + +/// Without the hand-over rule the second copy's prepaint replaced the +/// first copy's entry, and the first copy painted with the second's +/// layout — at the second's bounds. +#[gpui::test] +fn the_same_paragraph_rendered_twice_in_a_frame_keeps_one_layout_and_paints_both( + cx: &mut TestAppContext, +) { + cx.update(crate::init); + let (_, cx) = cx.add_window_view(|_, cx| Twice { + state: cx + .new(|cx| TextViewState::markdown("First paragraph.\n\nSecond **paragraph**.", cx)), + }); + cx.run_until_parked(); + + // Frame 1 fills the table, frame 2 reuses it; neither may lose the + // shaped text of either copy (painting an unmeasured placeholder + // panics inside GPUI). + for _ in 0..3 { + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + let retained = RETAINED_LAYOUTS.with(|layouts| layouts.borrow().entries.len()); + assert_eq!(retained, 2, "one layout per paragraph state"); +} + +struct Once { + state: Entity, +} + +impl Render for Once { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().w(px(300.)).child(TextView::new(&self.state)) + } +} + +/// A paragraph with a code span is laid out by `InlineFlow`, as one +/// `Inline` per wrapped fragment. The fragments' states have to outlive +/// the frame, or every frame shapes the fragments again and leaves the +/// table an entry nobody will take. +#[gpui::test] +fn inline_flow_fragments_keep_their_layouts_across_frames(cx: &mut TestAppContext) { + cx.update(crate::init); + let (_, cx) = cx.add_window_view(|_, cx| Once { + state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), + }); + cx.run_until_parked(); + + for _ in 0..3 { + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + // "Call ", "foo" and " now.": three fragments on one line. + let (retained, alive) = RETAINED_LAYOUTS.with(|layouts| { + let layouts = layouts.borrow(); + ( + layouts.entries.len(), + layouts + .entries + .values() + .filter(|retained| retained.state.strong_count() > 0) + .count(), + ) + }); + assert_eq!(retained, 3, "one layout per fragment"); + assert_eq!( + alive, 3, + "every retained layout belongs to a live fragment state" + ); +} + +#[gpui::test] +fn shortening_an_inline_flow_releases_obsolete_fragment_layouts(cx: &mut TestAppContext) { + cx.update(crate::init); + let source = "word `code` ".repeat(100); + let (view, cx) = cx.add_window_view(|_, cx| Once { + state: cx.new(|cx| TextViewState::markdown(&source, cx)), + }); + cx.run_until_parked(); + for _ in 0..2 { + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + view.update(cx, |view, cx| { + view.state.update(cx, |state, cx| { + state.set_text("word `code` now", cx); + }); + }); + cx.run_until_parked(); + for _ in 0..2 { + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + let alive = RETAINED_LAYOUTS.with(|layouts| { + layouts + .borrow() + .entries + .values() + .filter(|retained| retained.state.strong_count() > 0) + .count() + }); + assert_eq!(alive, 3, "one live layout per remaining fragment"); +} diff --git a/vendor/gpui-base/src/text/inline/test_draw.rs b/vendor/gpui-base/src/text/inline/test_draw.rs new file mode 100644 index 00000000..b2438c55 --- /dev/null +++ b/vendor/gpui-base/src/text/inline/test_draw.rs @@ -0,0 +1,44 @@ +use gpui::{App, Context, IntoElement, Render, Styled as _, TestApp, Window, canvas, px}; +use std::{cell::RefCell, rc::Rc}; + +struct Probe { + body: Option>, +} + +impl Render for Probe { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let body = self.body.take(); + canvas( + move |_, window, cx| { + if let Some(body) = body { + body(window, cx); + } + }, + |_, _, _, _| {}, + ) + .w(px(1000.)) + .h(px(1000.)) + } +} + +/// Runs `f` inside a real prepaint pass and returns its value. +/// +/// Measuring an inline object lays its GPUI element out through the +/// window, which GPUI only permits while a frame is being drawn, so a test +/// that builds a real element cannot call the measurement helpers straight +/// from `TestAppWindow::update`. +pub(crate) fn in_prepaint( + app: &mut TestApp, + f: impl FnOnce(&mut Window, &mut App) -> R + 'static, +) -> R { + let slot: Rc>> = Rc::new(RefCell::new(None)); + let out = slot.clone(); + let mut window = app.open_window(|_, _| Probe { + body: Some(Box::new(move |window, cx| { + *out.borrow_mut() = Some(f(window, cx)); + })), + }); + window.draw(); + let value = slot.borrow_mut().take(); + value.expect("prepaint probe did not run") +} diff --git a/vendor/gpui-base/src/text/inline/test_fonts.rs b/vendor/gpui-base/src/text/inline/test_fonts.rs new file mode 100644 index 00000000..639e08fe --- /dev/null +++ b/vendor/gpui-base/src/text/inline/test_fonts.rs @@ -0,0 +1,181 @@ +use gpui::{ + Bounds, DevicePixels, Font, FontId, FontMetrics, FontRun, FontWeight, GlyphId, LineLayout, + Pixels, PlatformTextSystem, RenderGlyphParams, ShapedGlyph, ShapedRun, Size, TextRenderingMode, + point, px, size, +}; +use std::{borrow::Cow, cell::RefCell}; + +pub(crate) const BODY: &str = "Body"; +pub(crate) const MONO: &str = "Mono"; +const BODY_ID: FontId = FontId(1); +const MONO_ID: FontId = FontId(2); +const BOLD_BODY_ID: FontId = FontId(3); +const BOLD_MONO_ID: FontId = FontId(4); +const UNITS_PER_EM: f32 = 1000.; + +pub(crate) struct WideMonoTextSystem; + +impl WideMonoTextSystem { + /// Advance of one glyph in `font_id`, in em units. + fn advance_units(font_id: FontId) -> f32 { + match font_id { + MONO_ID => 1000., + BOLD_MONO_ID => 1250., + BODY_ID => 500., + BOLD_BODY_ID => 750., + _ => 500., + } + } + + /// Width of `text` shaped entirely in `family` at `font_size`. + pub(crate) fn width_of(text: &str, family: &str, font_size: Pixels) -> Pixels { + let font_id = if family == MONO { MONO_ID } else { BODY_ID }; + font_size * (Self::advance_units(font_id) / UNITS_PER_EM) * text.chars().count() as f32 + } +} + +thread_local! { + static SHAPED_LINE_RECORDER: RefCell>> = const { RefCell::new(None) }; +} + +struct ShapeRecorderGuard; + +impl Drop for ShapeRecorderGuard { + fn drop(&mut self) { + SHAPED_LINE_RECORDER.with(|recorder| recorder.borrow_mut().take()); + } +} + +/// Runs `f` while recording text submitted to [`PlatformTextSystem::layout_line`]. +pub(crate) fn record_shaped_lines(f: impl FnOnce() -> R) -> (R, Vec) { + SHAPED_LINE_RECORDER.with(|recorder| *recorder.borrow_mut() = Some(Vec::new())); + let _guard = ShapeRecorderGuard; + let result = f(); + let shaped_lines = + SHAPED_LINE_RECORDER.with(|recorder| recorder.borrow_mut().take().unwrap_or_default()); + (result, shaped_lines) +} + +impl PlatformTextSystem for WideMonoTextSystem { + fn add_fonts(&self, _fonts: Vec>) -> anyhow::Result<()> { + Ok(()) + } + + fn all_font_names(&self) -> Vec { + vec![BODY.into(), MONO.into()] + } + + fn font_id(&self, descriptor: &Font) -> anyhow::Result { + Ok( + match ( + descriptor.family.as_ref() == MONO, + descriptor.weight == FontWeight::BOLD, + ) { + (true, true) => BOLD_MONO_ID, + (true, false) => MONO_ID, + (false, true) => BOLD_BODY_ID, + (false, false) => BODY_ID, + }, + ) + } + + fn font_metrics(&self, _font_id: FontId) -> FontMetrics { + FontMetrics { + units_per_em: UNITS_PER_EM as u32, + ascent: 800., + descent: -200., + line_gap: 0., + underline_position: -100., + underline_thickness: 50., + cap_height: 700., + x_height: 500., + bounding_box: Bounds { + origin: point(0., -200.), + size: size(1000., 1000.), + }, + } + } + + fn typographic_bounds( + &self, + font_id: FontId, + _glyph_id: GlyphId, + ) -> anyhow::Result> { + Ok(Bounds { + origin: point(0., 0.), + size: size(Self::advance_units(font_id), 700.), + }) + } + + fn advance(&self, font_id: FontId, _glyph_id: GlyphId) -> anyhow::Result> { + Ok(size(Self::advance_units(font_id), 0.)) + } + + fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option { + Some(GlyphId(ch as u32)) + } + + fn glyph_raster_bounds( + &self, + _params: &RenderGlyphParams, + ) -> anyhow::Result> { + Ok(Bounds::default()) + } + + fn rasterize_glyph( + &self, + _params: &RenderGlyphParams, + raster_bounds: Bounds, + ) -> anyhow::Result<(Size, Vec)> { + Ok((raster_bounds.size, Vec::new())) + } + + fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout { + SHAPED_LINE_RECORDER.with(|recorder| { + if let Some(lines) = recorder.borrow_mut().as_mut() { + lines.push(text.to_string()); + } + }); + + let mut position = px(0.); + let mut shaped_runs = Vec::new(); + let mut run_start = 0; + for run in runs { + let run_text = &text[run_start..run_start + run.len]; + let advance = font_size * (Self::advance_units(run.font_id) / UNITS_PER_EM); + let mut glyphs = Vec::new(); + for (ix, ch) in run_text.char_indices() { + glyphs.push(ShapedGlyph { + id: GlyphId(ch as u32), + position: point(position, px(0.)), + index: run_start + ix, + is_emoji: false, + }); + position += advance; + } + shaped_runs.push(ShapedRun { + font_id: run.font_id, + glyphs, + }); + run_start += run.len; + } + let metrics = self.font_metrics(BODY_ID); + LineLayout { + font_size, + width: position, + ascent: font_size * (metrics.ascent / UNITS_PER_EM), + // Native backends normalize the signed font metric for shaped lines. + descent: font_size * (-metrics.descent / UNITS_PER_EM), + runs: shaped_runs, + len: text.len(), + } + } + + fn recommended_rendering_mode( + &self, + _font_id: FontId, + _font_size: Pixels, + ) -> TextRenderingMode { + TextRenderingMode::Grayscale + } +} diff --git a/vendor/gpui-base/src/text/inline/tests.rs b/vendor/gpui-base/src/text/inline/tests.rs new file mode 100644 index 00000000..f8159075 --- /dev/null +++ b/vendor/gpui-base/src/text/inline/tests.rs @@ -0,0 +1,410 @@ +use super::{ + InlineHighlight, + geometry::{GlyphBox, aligned_row_left}, + highlights::combine_highlights, + point_in_text_selection, range_boxes, text_runs, +}; +use gpui::{FontWeight, HighlightStyle, SharedString, TextAlign, TextStyle, point, px}; +use std::ops::Range; + +fn mono(style: HighlightStyle) -> InlineHighlight { + InlineHighlight { + style, + font_family: Some(SharedString::from("Mono")), + font_size_scale: None, + } +} + +#[test] +fn text_runs_shape_a_code_highlight_in_its_font_family() { + let style = TextStyle { + font_family: SharedString::from("Body"), + ..Default::default() + }; + let highlights = vec![(4..8, mono(HighlightStyle::default()))]; + + let runs = text_runs(12, &style, &highlights); + + let families = runs + .iter() + .map(|run| (run.len, run.font.family.as_ref())) + .collect::>(); + assert_eq!(families, vec![(4, "Body"), (4, "Mono"), (4, "Body")]); +} + +#[test] +fn rows_align_the_way_gpui_paints_them() { + let width = px(100.); + assert_eq!(aligned_row_left(TextAlign::Left, width, px(40.)), px(0.)); + assert_eq!(aligned_row_left(TextAlign::Center, width, px(40.)), px(30.)); + assert_eq!(aligned_row_left(TextAlign::Right, width, px(40.)), px(60.)); +} + +fn glyph(text: Range, row: usize, left: f32, right: f32) -> GlyphBox { + GlyphBox { + text, + row, + left: px(left), + right: px(right), + } +} + +#[test] +fn range_boxes_join_the_glyphs_of_a_range_on_each_row() { + // "ab cd" wrapped after the space, glyphs 8px wide. + let glyphs = [ + glyph(0..1, 0, 0., 8.), + glyph(1..2, 0, 8., 16.), + glyph(2..3, 0, 16., 24.), + glyph(3..4, 1, 0., 8.), + glyph(4..5, 1, 8., 16.), + ]; + let boxes = |range| range_boxes(&glyphs, range); + assert_eq!(boxes(1..2), [(0, px(8.), px(16.))]); + assert_eq!(boxes(0..5), [(0, px(0.), px(24.)), (1, px(0.), px(16.))]); + // Starting at the wrap paints the next row only. + assert_eq!(boxes(3..5), [(1, px(0.), px(16.))]); + assert!(boxes(2..2).is_empty()); +} + +#[test] +fn range_boxes_follow_right_to_left_glyphs() { + // Three two-byte letters painted right to left: the first letter's + // glyph is the rightmost. + let glyphs = [ + glyph(0..2, 0, 16., 24.), + glyph(2..4, 0, 8., 16.), + glyph(4..6, 0, 0., 8.), + ]; + assert_eq!(range_boxes(&glyphs, 0..2), [(0, px(16.), px(24.))]); + assert_eq!(range_boxes(&glyphs, 2..6), [(0, px(0.), px(16.))]); +} + +#[test] +fn range_boxes_cover_a_glyph_drawing_part_of_the_range() { + // A ligature drawing "fi" in one glyph. + let glyphs = [glyph(0..2, 0, 0., 10.), glyph(2..3, 0, 10., 15.)]; + assert_eq!(range_boxes(&glyphs, 1..2), [(0, px(0.), px(10.))]); +} + +#[test] +fn combine_highlights_cuts_a_bold_span_at_the_code_boundary() { + // `**bold `code`**`: the bold mark spans the code mark, so the + // combined list carries the weight on both sides and the family on + // the code side only. + let bold = InlineHighlight::from(HighlightStyle { + font_weight: Some(FontWeight::BOLD), + ..Default::default() + }); + let combined = combine_highlights( + vec![(0..10, bold)], + vec![(6..10, mono(HighlightStyle::default()))], + ); + + assert_eq!(combined.len(), 2); + assert_eq!(combined[0].0, 0..6); + assert_eq!(combined[0].1.style.font_weight, Some(FontWeight::BOLD)); + assert_eq!(combined[0].1.font_family, None); + assert_eq!(combined[1].0, 6..10); + assert_eq!(combined[1].1.style.font_weight, Some(FontWeight::BOLD)); + assert_eq!(combined[1].1.font_family.as_deref(), Some("Mono")); +} + +#[test] +fn appending_child_marks_matches_the_sweep_for_gaps_and_nested_styles() { + let bold = InlineHighlight::from(HighlightStyle { + font_weight: Some(FontWeight::BOLD), + ..Default::default() + }); + let code = mono(HighlightStyle::default()); + let cases = [ + vec![(0..6, bold.clone())], + vec![], + vec![(8..8, code.clone()), (8..14, bold.clone())], + vec![(18..22, code.clone()), (16..22, bold.clone())], + vec![(22..23, code)], + ]; + let mut old = Vec::new(); + let mut current = Vec::new(); + for child in cases { + old = combine_highlights(old, child.clone()); + super::append_node_highlights(&mut current, child.into_iter().collect()); + assert_eq!(current, old); + } +} + +#[test] +#[ignore = "manual release benchmark for long formatted paragraphs"] +fn many_child_marks_benchmark() { + let style = mono(HighlightStyle::default()); + let mut old = Vec::new(); + let previous = std::time::Instant::now(); + for index in 0..512 { + let first = index * 4; + old = combine_highlights(old, [(first..first + 2, style.clone())]); + } + let previous = previous.elapsed(); + let mut current = Vec::new(); + let optimized = std::time::Instant::now(); + for index in 0..512 { + let first = index * 4; + super::append_node_highlights( + &mut current, + [(first..first + 2, style.clone())].into_iter().collect(), + ); + } + let optimized = optimized.elapsed(); + assert_eq!(current, old); + eprintln!("512 children: sweep {previous:?}, append {optimized:?}"); +} + +#[test] +fn test_point_in_text_selection() { + let line_height = px(20.); + let char_width = px(10.); + let start = point(px(50.), px(50.)); + let end = point(px(150.), px(150.)); + + // First line but haft line height, true + // | p --------| + // | selection | + // |-----------| + assert!(point_in_text_selection( + point(px(50.), px(40.)), + char_width, + start, + end, + line_height + )); + + // First line in selection, true + // | p --------| + // | selection | + // |-----------| + assert!(point_in_text_selection( + point(px(50.), px(50.)), + char_width, + start, + end, + line_height + )); + // First line, but left out of selection, false + // p |-----------| + // | selection | + // |-----------| + assert!(!point_in_text_selection( + point(px(40.), px(50.)), + char_width, + start, + end, + line_height + )); + // First line but right out of selection, true + // |-----------| p + // | selection | + // |-----------| + assert!(point_in_text_selection( + point(px(160.), px(50.)), + char_width, + start, + end, + line_height + )); + + // Middle line in selection, true + // |-----------| + // | p | + // |-----------| + assert!(point_in_text_selection( + point(px(100.), px(70.)), + char_width, + start, + end, + line_height + )); + // Middle line, but left out of selection, true + // |-----------| + // p | selection | + // |-----------| + assert!(point_in_text_selection( + point(px(40.), px(70.)), + char_width, + start, + end, + line_height + )); + // Middle line, but right out of selection, true + // |-----------| + // | selection | p + // |-----------| + assert!(point_in_text_selection( + point(px(160.), px(70.)), + char_width, + start, + end, + line_height + )); + + // Last line in selection, true + // |-----------| + // | selection | + // |------- p -| + assert!(point_in_text_selection( + point(px(100.), px(140.)), + char_width, + start, + end, + line_height + )); + // Last line, but left out of selection, true + // + // |-----------| + // | selection | + // p |-----------| + assert!(point_in_text_selection( + point(px(40.), px(140.)), + char_width, + start, + end, + line_height + )); + // Last line, but right out of selection, false + // |-----------| + // | selection | + // |-----------| p + assert!(!point_in_text_selection( + point(px(160.), px(140.)), + char_width, + start, + end, + line_height + )); + + // Out of vertical bounds (top), false + // p + // |-----------| + // | selection | + // |-----------| + assert!(!point_in_text_selection( + point(px(100.), px(20.)), + char_width, + start, + end, + line_height + )); + // Out of vertical bounds (bottom), false + // |-----------| + // | selection | + // |-----------| + // p + assert!(!point_in_text_selection( + point(px(100.), px(160.)), + char_width, + start, + end, + line_height + )); +} + +#[test] +fn test_point_in_text_selection_reversed_drag_direction() { + let line_height = px(20.); + let char_width = px(10.); + + // Mouse down on lower line then drag upward to x=150. + // Top line should follow current mouse x, bottom line should keep anchor x. + let start = point(px(80.), px(150.)); + let end = point(px(150.), px(50.)); + + // On top line, selection starts from top cursor x (150), so x=140 should be excluded. + assert!(!point_in_text_selection( + point(px(140.), px(50.)), + char_width, + start, + end, + line_height + )); + assert!(point_in_text_selection( + point(px(150.), px(50.)), + char_width, + start, + end, + line_height + )); + + // On bottom line, selection ends at anchor x (80), so x=90 should be excluded. + assert!(point_in_text_selection( + point(px(75.), px(140.)), + char_width, + start, + end, + line_height + )); + assert!(!point_in_text_selection( + point(px(80.), px(140.)), + char_width, + start, + end, + line_height + )); +} + +#[test] +fn test_point_in_text_selection_same_visual_line_with_different_y() { + let line_height = px(20.); + let char_width = px(10.); + let start = point(px(100.), px(55.)); + let end = point(px(60.), px(58.)); + + assert!(!point_in_text_selection( + point(px(40.), px(50.)), + char_width, + start, + end, + line_height + )); + assert!(point_in_text_selection( + point(px(70.), px(50.)), + char_width, + start, + end, + line_height + )); + assert!(!point_in_text_selection( + point(px(110.), px(50.)), + char_width, + start, + end, + line_height + )); +} + +#[test] +fn test_point_in_text_selection_same_visual_line_with_reversed_y() { + let line_height = px(20.); + let char_width = px(10.); + let start = point(px(60.), px(58.)); + let end = point(px(100.), px(55.)); + + assert!(!point_in_text_selection( + point(px(40.), px(50.)), + char_width, + start, + end, + line_height + )); + assert!(point_in_text_selection( + point(px(70.), px(50.)), + char_width, + start, + end, + line_height + )); + assert!(!point_in_text_selection( + point(px(110.), px(50.)), + char_width, + start, + end, + line_height + )); +} diff --git a/vendor/gpui-base/src/text/inline_flow.rs b/vendor/gpui-base/src/text/inline_flow.rs index 00de6d88..121b9605 100644 --- a/vendor/gpui-base/src/text/inline_flow.rs +++ b/vendor/gpui-base/src/text/inline_flow.rs @@ -1,29 +1,36 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + use std::{ cell::RefCell, ops::Range, rc::Rc, sync::{Arc, Mutex}, }; -use unicode_segmentation::UnicodeSegmentation as _; use gpui::{ - AbsoluteLength, AnyElement, App, AvailableSpace, Bounds, DefiniteLength, Element, ElementId, - GlobalElementId, Hsla, ImageSource, InspectorElementId, InteractiveElement as _, IntoElement, - LayoutId, LineFragment as WrapLineFragment, ObjectFit, Pixels, Refineable as _, ShapedLine, - SharedString, Size, StatefulInteractiveElement as _, Styled, StyledImage as _, TextRun, - TextStyle, WhiteSpace, Window, img, point, prelude::FluentBuilder as _, px, relative, size, + AnyElement, App, AvailableSpace, Bounds, DefiniteLength, Element, ElementId, GlobalElementId, + Hsla, ImageSource, InspectorElementId, InteractiveElement as _, IntoElement, LayoutId, + ObjectFit, Pixels, Refineable as _, SharedString, Size, StatefulInteractiveElement as _, + Styled, StyledImage as _, TextStyle, WhiteSpace, Window, img, point, + prelude::FluentBuilder as _, px, relative, size, }; use crate::text::text_view::{LinkClickHandlerFn, handle_link_click}; use super::{ - inline::{Inline, InlineHighlight, InlineState, text_runs, text_size_ranges}, - inline_object::{InlineObject, MeasuredInlineObject}, + inline::{Inline, InlineHighlight, InlinePrepaint, InlineState}, + inline_object::InlineObject, node::LinkMark, range_highlight::RevealAt, }; -const IMAGE_LEN: usize = 1; +mod layout; + +pub(super) use layout::intrinsic_width; +use layout::{ + InlineFlowLayout, MeasureItem, PositionedFragment, layout_measured_flow, measure_image_size, + prepare_objects, +}; pub(super) const INLINE_CODE_PADDING: f32 = 2.; pub(super) struct InlineFlow { @@ -167,80 +174,6 @@ struct InlineFlowTypography { line_height: Pixels, } -#[derive(Default)] -struct InlineFlowLayout { - fragments: Vec, - size: Size, - wrap_width: Option, -} - -enum PositionedFragment { - Object { - item_ix: usize, - origin: gpui::Point, - object: Box, - selection_bounds: Bounds, - }, - Text { - item_ix: usize, - origin: gpui::Point, - size: Size, - source_range: Range, - font_size: Pixels, - text: SharedString, - links: Vec<(Range, LinkMark)>, - highlights: Vec<(Range, InlineHighlight)>, - selection_bounds: Bounds, - /// The rounded box behind a code span, relative to the flow. - code_background: Option<(Bounds, Hsla)>, - }, - Image { - item_ix: usize, - origin: gpui::Point, - size: Size, - }, -} - -enum MeasureItem { - Object { - text: SharedString, - id: usize, - renderer: Arc, - style: gpui::HighlightStyle, - }, - Text { - text: SharedString, - links: Vec<(Range, LinkMark)>, - highlights: Vec<(Range, InlineHighlight)>, - }, - Image { - source: ImageSource, - width: Option, - height: Option, - }, -} - -struct LineFragmentLayout { - item_ix: usize, - kind: LineFragmentKind, - size: Size, - source_range: Range, - baseline: Pixels, -} - -enum LineFragmentKind { - Object(Box), - Text { - font_size: Pixels, - text: SharedString, - links: Vec<(Range, LinkMark)>, - highlights: Vec<(Range, InlineHighlight)>, - /// The code span's box, relative to the fragment. - code_background: Option<(Bounds, Hsla)>, - }, - Image, -} - impl InlineFlow { pub(super) fn new( id: impl Into, @@ -307,9 +240,23 @@ impl IntoElement for InlineFlow { } } +// Nocterm: positioned text needs no layout-tree node or drawable wrapper. +pub(super) struct InlineFlowPrepaint { + order: Vec, + text: Vec<(Inline, Bounds, InlinePrepaint)>, +} + +enum PrepaintedFragment { + Text { + index: usize, + background: Option<(Bounds, Hsla)>, + }, + Element(AnyElement), +} + impl Element for InlineFlow { type RequestLayoutState = InlineFlowLayoutState; - type PrepaintState = Vec<(AnyElement, Option<(Bounds, gpui::Hsla)>)>; + type PrepaintState = InlineFlowPrepaint; fn id(&self) -> Option { Some(self.id.clone()) @@ -428,12 +375,23 @@ impl Element for InlineFlow { cx: &mut App, ) -> Self::PrepaintState { let frame_state = request_layout.frame_state.clone(); + let mut prepaint = InlineFlowPrepaint { + order: Vec::new(), + text: Vec::new(), + }; let Some(layout) = request_layout.current.borrow().clone() else { - return Vec::new(); + return prepaint; }; let typography = request_layout.typography.clone(); let text_style = &typography.text_style; - let mut elements = Vec::with_capacity(layout.fragments.len()); + prepaint.order.reserve(layout.fragments.len()); + prepaint.text.reserve( + layout + .fragments + .iter() + .filter(|fragment| matches!(fragment, PositionedFragment::Text { .. })) + .count(), + ); // A reveal goes to the fragment it starts in. A line break lays out // no fragment, so a reveal starting on one, or on an empty line, goes @@ -510,7 +468,7 @@ impl Element for InlineFlow { window, cx, ); - elements.push((element, None)); + prepaint.order.push(PrepaintedFragment::Element(element)); } PositionedFragment::Text { item_ix, @@ -578,35 +536,26 @@ impl Element for InlineFlow { .filter(|_| reveal_fragment == Some(fragment_ix)) .map(|reveal| reveal.clamp(source_range.start, source_range.end)), ) - .text_style(fragment_style.clone()) .selection_bounds(Bounds::new( point(bounds.left(), bounds.top() + selection_bounds.top()), size(bounds.size.width, selection_bounds.size.height), - )) - .paint_origin(bounds.origin + origin + point(padding, Pixels::ZERO)) - .into_any_element(); - // The `Inline` is its own layout root, with no box around - // it: its text measures with the window's text style, so - // the fragment's style is pushed for the layout. - window.with_rem_size(Some(typography.rem_size), |window| { - window.with_text_style( - Some(fragment_style.subtract(&Default::default())), - |window| { - element.prepaint_as_root( - bounds.origin + origin + point(padding, Pixels::ZERO), - size( - AvailableSpace::Definite( - fragment_size.width - padding * 2., - ), - AvailableSpace::Definite(fragment_size.height), - ), - window, - cx, - ); - }, - ); + )); + let refinement = fragment_style.subtract(&Default::default()); + let available = Bounds::new( + bounds.origin + origin + point(padding, Pixels::ZERO), + size(fragment_size.width - padding * 2., fragment_size.height), + ); + let (bounds, prepared) = + window.with_rem_size(Some(typography.rem_size), |window| { + window.with_text_style(Some(refinement), |window| { + element.prepaint_positioned(available, fragment_style, window, cx) + }) + }); + prepaint.order.push(PrepaintedFragment::Text { + index: prepaint.text.len(), + background, }); - elements.push((element, background)); + prepaint.text.push((element, bounds, prepared)); } PositionedFragment::Image { item_ix, @@ -624,7 +573,7 @@ impl Element for InlineFlow { }; let (origin, fragment_size) = (*origin, *fragment_size); let mut element = Self::image_element( - elements.len(), + prepaint.order.len(), source, link, title.as_str(), @@ -640,7 +589,7 @@ impl Element for InlineFlow { window, cx, ); - elements.push((element, None)); + prepaint.order.push(PrepaintedFragment::Element(element)); } } } @@ -650,7 +599,7 @@ impl Element for InlineFlow { .fragment_states .truncate(text_fragment_count); - elements + prepaint } fn paint( @@ -675,774 +624,21 @@ impl Element for InlineFlow { } } let radius = crate::Theme::global(cx).tokens.radius.sm; - for (element, background) in prepaint { - if let Some((bounds, color)) = background { - window.paint_quad(gpui::fill(*bounds, *color).corner_radii(radius)); - } - element.paint(window, cx); - } - } -} - -impl From<&InlineFlowItem> for MeasureItem { - fn from(item: &InlineFlowItem) -> Self { - match item { - InlineFlowItem::Object { - text, - id, - renderer, - style, - .. - } => Self::Object { - text: text.clone(), - id: *id, - renderer: renderer.clone(), - style: *style, - }, - InlineFlowItem::Text { - state: _, - text, - links, - highlights, - .. - } => MeasureItem::Text { - text: text.clone(), - links: links.clone(), - highlights: highlights.clone(), - }, - InlineFlowItem::Image { - source, - width, - height, - .. - } => MeasureItem::Image { - source: source.clone(), - width: *width, - height: *height, - }, - } - } -} - -impl MeasureItem { - fn len(&self) -> usize { - match self { - MeasureItem::Text { text, .. } => text.len(), - MeasureItem::Image { .. } | MeasureItem::Object { .. } => IMAGE_LEN, - } - } - - /// Whether `other` lays out the same as this item. An object is - /// rendered anew every frame, so a flow with one is never reused. - fn same_layout_input(&self, other: &Self) -> bool { - match (self, other) { - ( - MeasureItem::Text { - text, - links, - highlights, - }, - MeasureItem::Text { - text: other_text, - links: other_links, - highlights: other_highlights, - }, - ) => text == other_text && links == other_links && highlights == other_highlights, - ( - MeasureItem::Image { width, height, .. }, - MeasureItem::Image { - width: other_width, - height: other_height, - .. - }, - ) => width == other_width && height == other_height, - _ => false, - } - } -} - -/// Intrinsic width for table sizing, using the same objects and wrapping inputs as painting. -pub(super) fn intrinsic_width( - items: &[InlineFlowItem], - window: &mut Window, - cx: &mut App, -) -> Pixels { - let items = items.iter().map(MeasureItem::from).collect::>(); - let line_height = window.line_height(); - let rem_size = window.rem_size(); - let images = items - .iter() - .enumerate() - .map(|(ix, item)| match item { - MeasureItem::Image { - source, - width, - height, - } => Some(measure_image_size( - ix, - source, - *width, - *height, - line_height, - rem_size, - window, - cx, - )), - _ => None, - }) - .collect::>(); - layout_flow(&items, &images, &window.text_style(), None, window, cx) - .size - .width -} - -fn prepare_objects( - items: &[MeasureItem], - text_style: &TextStyle, - window: &mut Window, - cx: &mut App, -) -> Vec> { - items - .iter() - .map(|item| match item { - MeasureItem::Object { - text, - id, - renderer, - style, - } => { - let style = text_style.clone().highlight(*style); - let context = super::InlineRenderContext::new( - style.clone(), - style.font_size.to_pixels(window.rem_size()), - style.line_height_in_pixels(window.rem_size()), - window.rem_size(), - ); - // Must be the id `InlineObject` paints under: GPUI asserts a - // stateful child (a plugin's HoverCard) sees the same id path - // in request_layout as in prepaint, and the element is laid - // out here but painted inside `InlineObject`. - Some(window.with_id(("inline-object", *id), |window| { - let element = window - .with_text_style(Some(style.subtract(&Default::default())), |window| { - renderer(&context, window, cx) - }); - MeasuredInlineObject::measure(text, element, &style, window, cx) - })) - } - _ => None, - }) - .collect() -} - -fn layout_flow( - items: &[MeasureItem], - image_sizes: &[Option>], - text_style: &TextStyle, - wrap_width: Option, - window: &mut Window, - cx: &mut App, -) -> InlineFlowLayout { - let objects = prepare_objects(items, text_style, window, cx); - layout_measured_flow( - items, - image_sizes, - &objects, - text_style, - wrap_width, - window, - cx, - ) -} - -#[cfg(test)] -thread_local! { - /// How many flows were laid out (wrapped and shaped) on this thread. - pub(super) static FLOW_LAYOUTS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -fn layout_measured_flow( - items: &[MeasureItem], - image_sizes: &[Option>], - prepared_objects: &[Option], - text_style: &TextStyle, - wrap_width: Option, - window: &mut Window, - _cx: &mut App, -) -> InlineFlowLayout { - #[cfg(test)] - FLOW_LAYOUTS.with(|layouts| layouts.set(layouts.get() + 1)); - let rem_size = window.rem_size(); - let line_height = plain_line_height(text_style, rem_size, window); - let total_len = items.iter().map(MeasureItem::len).sum::(); - if total_len == 0 { - return InlineFlowLayout::default(); - } - - let objects = prepared_objects - .iter() - .map(|object| object.clone().map(|object| object.fit_text(wrap_width))) - .collect::>(); - let line_ranges = line_ranges(items, image_sizes, &objects, text_style, wrap_width, window); - let font_size = text_style.font_size.to_pixels(rem_size); - let mut fragments = Vec::new(); - let mut max_width = Pixels::ZERO; - let mut y = Pixels::ZERO; - - for line_range in line_ranges { - let mut line_fragments = Vec::new(); - let mut line_width = Pixels::ZERO; - // `LineLayout` is the metric source used by the text paint path. Its - // descent is normalized positive by native backends, whereas - // `FontMetrics::descent` remains signed. Start with the same shaped - // body metrics used below for every text fragment rather than mixing - // those two conventions through `TextSystem::baseline_offset`. - let body_runs = text_runs(1, text_style, &[]); - let body_line = shape_line(" ".into(), font_size, &body_runs, window); - let body_baseline = centered_baseline(&body_line, line_height); - // Like a plain text line, the body line box is the line height even - // when the font's glyphs are taller; runs may overflow it as far as - // body glyphs do. - let body_overflow_above = (body_line.ascent - body_baseline).max(Pixels::ZERO); - let body_overflow_below = - (body_line.descent - (line_height - body_baseline)).max(Pixels::ZERO); - let mut line_ascent = body_baseline; - let mut line_descent = line_height - body_baseline; - let mut item_start = 0; - - for (item_ix, item) in items.iter().enumerate() { - let item_end = item_start + item.len(); - if item_end <= line_range.start { - item_start = item_end; - continue; - } - if item_start >= line_range.end { - break; - } - - match item { - MeasureItem::Text { - text, - links, - highlights, - } => { - let local_start = line_range.start.max(item_start) - item_start; - let local_end = line_range.end.min(item_end) - item_start; - for (segment, scale) in text_size_ranges(text.len(), highlights) { - let start = local_start.max(segment.start); - let end = local_end.min(segment.end); - if start >= end { - continue; - } - let subtext = SharedString::from(text[start..end].to_string()); - let mut highlights = - slice_ranges(highlights, start, end, |range, style| { - (range, style.clone()) - }); - let links = - slice_ranges(links, start, end, |range, link| (range, link.clone())); - let runs = text_runs(subtext.len(), text_style, &highlights); - let segment_font_size = font_size * scale; - let shaped_line = - shape_line(subtext.clone(), segment_font_size, &runs, window); - let is_code = highlights.iter().any(|(_, h)| h.font_size_scale.is_some()); - let padding = if is_code { - px(INLINE_CODE_PADDING * 2.) - } else { - Pixels::ZERO - }; - let width = shaped_line.width() + padding; - // Measure the run by its glyph box. The body strut already - // carries the line's leading, so a run only has to fit its - // glyphs: leading of its own would make a smaller or - // differently proportioned run, such as inline code, push - // its line taller than a plain one. Positioning grows the - // box back to the line. The compact code background is - // painted independently. - let glyph_size = size(width, shaped_line.ascent + shaped_line.descent); - let baseline = shaped_line.ascent; - let code_background = is_code - .then(|| { - code_background( - &shaped_line, - &runs, - segment_font_size, - &mut highlights, - glyph_size, - baseline, - window, - ) - }) - .flatten(); - line_ascent = line_ascent.max(baseline - body_overflow_above); - line_descent = - line_descent.max(glyph_size.height - baseline - body_overflow_below); - line_width += width; - line_fragments.push(LineFragmentLayout { - item_ix, - kind: LineFragmentKind::Text { - font_size: segment_font_size, - text: subtext, - links, - highlights, - code_background, - }, - size: glyph_size, - source_range: start..end, - baseline: baseline, - }); - } - } - MeasureItem::Object { .. } => { - let object = objects[item_ix].as_ref().unwrap().clone(); - let metrics = object.metrics; - line_ascent = line_ascent.max(metrics.baseline); - line_descent = line_descent.max(metrics.size.height - metrics.baseline); - line_width += metrics.size.width; - line_fragments.push(LineFragmentLayout { - item_ix, - kind: LineFragmentKind::Object(Box::new(object)), - size: metrics.size, - source_range: 0..IMAGE_LEN, - baseline: metrics.baseline, - }); - } - MeasureItem::Image { .. } => { - if line_range.start <= item_start && item_end <= line_range.end { - let size = image_sizes[item_ix] - .expect("image size should be measured before layout"); - line_width += size.width; - let baseline = (size.height / 2. + body_baseline - line_height / 2.) - .max(Pixels::ZERO) - .min(size.height); - line_ascent = line_ascent.max(baseline); - line_descent = line_descent.max(size.height - baseline); - line_fragments.push(LineFragmentLayout { - item_ix, - kind: LineFragmentKind::Image, - size, - source_range: 0..IMAGE_LEN, - baseline: baseline, - }); - } - } - } - - item_start = item_end; - } - - let mut x = Pixels::ZERO; - for mut fragment in line_fragments { - // Give a text run's glyph box equal leading on both sides, as - // much as the line allows: its glyphs are painted centered in the - // box, so this keeps them on the line's baseline, and a body run - // gets exactly the line box. The leading is negative where the - // glyphs overflow the line, as a plain text line's do. - let leading = match fragment.kind { - LineFragmentKind::Text { .. } => (line_ascent - fragment.baseline) - .min(line_descent - (fragment.size.height - fragment.baseline)) - .max(-fragment.size.height / 2.), - _ => Pixels::ZERO, - }; - fragment.size.height += leading * 2.; - fragment.baseline += leading; - let origin = point(x, y + line_ascent - fragment.baseline); - let selection_bounds = Bounds::new( - point(x, y), - size(fragment.size.width, line_ascent + line_descent), - ); - let positioned = match fragment.kind { - LineFragmentKind::Object(object) => PositionedFragment::Object { - item_ix: fragment.item_ix, - origin, - object, - selection_bounds, - }, - LineFragmentKind::Text { - font_size, - text, - links, - highlights, - code_background, - } => PositionedFragment::Text { - item_ix: fragment.item_ix, - origin, - size: fragment.size, - source_range: fragment.source_range, - selection_bounds, - font_size, - text, - links, - highlights, - code_background: code_background.map(|(background, color)| { - ( - Bounds::new( - origin + point(Pixels::ZERO, leading) + background.origin, - background.size, - ), - color, - ) - }), - }, - LineFragmentKind::Image => PositionedFragment::Image { - item_ix: fragment.item_ix, - origin, - size: fragment.size, - }, - }; - x += fragment.size.width; - fragments.push(positioned); - } - - max_width = max_width.max(line_width); - y += line_ascent + line_descent; - } - - InlineFlowLayout { - fragments, - size: size(max_width, y), - wrap_width, - } -} - -/// The rounded box behind a code span, relative to the fragment: centered on -/// the capital-height body of the text, with the descender room shared -/// between both sides instead of added only below. Takes the background -/// color out of `highlights`, so the text does not paint it a second time -/// at the full line height. -fn code_background( - shaped_line: &ShapedLine, - runs: &[TextRun], - font_size: Pixels, - highlights: &mut [(Range, InlineHighlight)], - fragment_size: Size, - baseline: Pixels, - window: &Window, -) -> Option<(Bounds, Hsla)> { - let cap_height = runs - .iter() - .map(|run| { - let font = window.text_system().resolve_font(&run.font); - window.text_system().cap_height(font, font_size) - }) - .fold(Pixels::ZERO, Pixels::max); - let vertical_padding = font_size * 0.125 + shaped_line.descent / 2.; - let color = highlights - .iter() - .find_map(|(_, h)| h.style.background_color); - for (_, highlight) in highlights.iter_mut() { - highlight.style.background_color = None; - } - color.map(|color| { - ( - Bounds::new( - point(Pixels::ZERO, baseline - cap_height - vertical_padding), - size(fragment_size.width, cap_height + vertical_padding * 2.), - ), - color, - ) - }) -} - -fn line_ranges( - items: &[MeasureItem], - image_sizes: &[Option>], - objects: &[Option], - text_style: &TextStyle, - wrap_width: Option, - window: &mut Window, -) -> Vec> { - let total_len = items.iter().map(MeasureItem::len).sum::(); - let mut hard_lines = Vec::new(); - let mut line_start = 0; - let mut item_start = 0; - - for item in items { - if let MeasureItem::Text { text, .. } = item { - for (newline, _) in text.match_indices('\n') { - let newline = item_start + newline; - hard_lines.push(line_start..newline); - line_start = newline + 1; - } - } - item_start += item.len(); - } - hard_lines.push(line_start..total_len); - - let Some(wrap_width) = wrap_width else { - return hard_lines; - }; - let rem_size = window.rem_size(); - let font_size = text_style.font_size.to_pixels(rem_size); - let mut wrapper = window - .text_system() - .line_wrapper(text_style.font(), font_size); - let mut ranges = Vec::new(); - - for hard_line in hard_lines { - let mut item_start = 0; - let mut wrap_fragments = Vec::new(); - for (ix, item) in items.iter().enumerate() { - let item_end = item_start + item.len(); - if item_end > hard_line.start && item_start < hard_line.end { - match item { - MeasureItem::Text { - text, highlights, .. - } => { - let start = hard_line.start.max(item_start) - item_start; - let end = hard_line.end.min(item_end) - item_start; - if start < end { - push_text_wrap_fragments( - &mut wrap_fragments, - text, - highlights, - start..end, - text_style, - wrap_width, - window, - ); - } - } - MeasureItem::Object { .. } => { - wrap_fragments.push(WrapLineFragment::element( - objects[ix].as_ref().unwrap().metrics.size.width, - IMAGE_LEN, - )); - } - MeasureItem::Image { .. } => { - if hard_line.start <= item_start && item_end <= hard_line.end { - wrap_fragments.push(WrapLineFragment::element( - image_sizes[ix] - .expect("image size should be measured before wrapping") - .width, - IMAGE_LEN, - )); - } - } - } - } - item_start = item_end; - } - - let boundaries = wrapper - .wrap_line(&wrap_fragments, wrap_width) - .map(|boundary| hard_line.start + boundary.ix.min(hard_line.len())) - .collect::>(); - let mut start = hard_line.start; - - for end in boundaries { - if start < end { - ranges.push(start..end); - } - start = end; - } - - if start < hard_line.end || hard_line.is_empty() { - ranges.push(start..hard_line.end); - } - } - - ranges -} - -/// Appends the wrap fragments for `range` of `text`. The line wrapper -/// measures text fragments in the body font, so a span whose highlight sets -/// another family is shaped with the same run the renderer uses and enters -/// the wrapper as measured elements. Oversized spans retain word boundaries; -/// oversized words can break at grapheme boundaries without splitting Unicode. -fn push_text_wrap_fragments<'a>( - fragments: &mut Vec>, - text: &'a str, - highlights: &[(Range, InlineHighlight)], - range: Range, - text_style: &TextStyle, - wrap_width: Pixels, - window: &mut Window, -) { - let font_size = text_style.font_size.to_pixels(window.rem_size()); - let mut cursor = range.start; - for (highlight_range, highlight) in highlights { - if highlight.font_family.is_none() { - continue; - } - let start = highlight_range.start.max(cursor); - let end = highlight_range.end.min(range.end); - if start >= end { - continue; - } - if cursor < start { - fragments.push(WrapLineFragment::text(&text[cursor..start])); - } - let span = &text[start..end]; - let measure = |text: &str| { - let runs = text_runs( - text.len(), - text_style, - &[(0..text.len(), highlight.clone())], - ); - window - .text_system() - .layout_line( - text, - font_size * highlight.font_size_scale.unwrap_or(1.), - &runs, - None, - ) - .width - }; - let padding = if highlight.font_size_scale.is_some() { - px(INLINE_CODE_PADDING * 2.) - } else { - Pixels::ZERO - }; - let width = measure(span) + padding; - if width <= wrap_width { - fragments.push(WrapLineFragment::element(width, span.len())); - } else { - for word in span.split_word_bounds() { - let width = measure(word) + padding; - if width <= wrap_width { - fragments.push(WrapLineFragment::element(width, word.len())); - } else { - for grapheme in word.graphemes(true) { - fragments.push(WrapLineFragment::element( - measure(grapheme) + padding, - grapheme.len(), - )); + for fragment in &mut prepaint.order { + match fragment { + PrepaintedFragment::Text { index, background } => { + if let Some((bounds, color)) = background { + window.paint_quad(gpui::fill(*bounds, *color).corner_radii(radius)); } + let (inline, bounds, prepared) = &mut prepaint.text[*index]; + inline.paint(None, None, *bounds, &mut px(0.), prepared, window, cx); } + PrepaintedFragment::Element(element) => element.paint(window, cx), } } - cursor = end; - } - if cursor < range.end { - fragments.push(WrapLineFragment::text(&text[cursor..range.end])); } } -#[allow(clippy::too_many_arguments)] -fn measure_image_size( - ix: usize, - source: &ImageSource, - width: Option, - height: Option, - line_height: Pixels, - rem_size: Pixels, - window: &mut Window, - cx: &mut App, -) -> Size { - let intrinsic_size = if width.is_some() && height.is_some() { - None - } else { - intrinsic_image_size(ix, source, width, height, window, cx) - }; - image_size(width, height, intrinsic_size, line_height, rem_size) -} - -fn intrinsic_image_size( - ix: usize, - source: &ImageSource, - width: Option, - height: Option, - window: &mut Window, - cx: &mut App, -) -> Option> { - let mut element = img(source.clone()) - .id(ix) - .object_fit(ObjectFit::Contain) - .max_w(relative(1.)) - .when_some(width, |this, width| this.w(width)) - .when_some(height, |this, height| this.h(height)) - .into_any_element(); - let measured_size = element.layout_as_root(AvailableSpace::min_size(), window, cx); - - if measured_size.width <= Pixels::ZERO || measured_size.height <= Pixels::ZERO { - None - } else { - Some(measured_size) - } -} - -fn image_size( - width: Option, - height: Option, - intrinsic_size: Option>, - line_height: Pixels, - rem_size: Pixels, -) -> Size { - let base_size = AbsoluteLength::Pixels(line_height); - match (width, height) { - (Some(width), Some(height)) => size( - width.to_pixels(base_size, rem_size), - height.to_pixels(base_size, rem_size), - ), - (Some(width), None) => { - let width = width.to_pixels(base_size, rem_size); - let height = intrinsic_size - .and_then(|intrinsic_size| { - (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO) - .then(|| width * (intrinsic_size.height / intrinsic_size.width)) - }) - .unwrap_or(line_height); - size(width, height) - } - (None, Some(height)) => { - let height = height.to_pixels(base_size, rem_size); - let width = intrinsic_size - .and_then(|intrinsic_size| { - (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO) - .then(|| height * (intrinsic_size.width / intrinsic_size.height)) - }) - .unwrap_or(height); - size(width, height) - } - (None, None) => inline_image_size_for_line(intrinsic_size, line_height), - } -} - -fn inline_image_size_for_line( - intrinsic_size: Option>, - line_height: Pixels, -) -> Size { - let height = line_height * 0.75; - let aspect_ratio = intrinsic_size - .and_then(|intrinsic_size| { - (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO) - .then(|| intrinsic_size.width / intrinsic_size.height) - }) - .unwrap_or(1.); - - size((height * aspect_ratio).max(px(1.)), height.max(px(1.))) -} - -fn shape_line( - text: SharedString, - font_size: Pixels, - runs: &[TextRun], - window: &mut Window, -) -> ShapedLine { - window.text_system().shape_line(text, font_size, runs, None) -} - -/// The line height GPUI's text layout gives a plain line in `text_style`. -/// Unlike `Window::line_height`, it is not first rounded to a whole logical -/// pixel, which would make a flow line taller than a plain one. -fn plain_line_height(text_style: &TextStyle, rem_size: Pixels, window: &Window) -> Pixels { - window.pixel_snap( - text_style - .line_height - .to_pixels(text_style.font_size, rem_size), - ) -} - -/// Returns where GPUI text painting puts the baseline of `shaped_line` in a -/// box `line_height` tall: centered, even when the glyphs overflow the box. -/// `ShapedLine::descent` is positive; do not substitute the signed -/// `FontMetrics::descent` exposed by `TextSystem::baseline_offset` here. -fn centered_baseline(shaped_line: &ShapedLine, line_height: Pixels) -> Pixels { - (line_height - shaped_line.ascent - shaped_line.descent) / 2. + shaped_line.ascent -} - pub(super) fn slice_ranges( ranges: &[(Range, T)], start: usize, @@ -1461,498 +657,4 @@ pub(super) fn slice_ranges( } #[cfg(test)] -mod tests { - use super::*; - use gpui::SharedUri; - - mod frames { - use super::super::FLOW_LAYOUTS; - use crate::text::{TextView, TextViewState}; - use gpui::{ - AppContext as _, Context, Entity, IntoElement, ParentElement as _, Pixels, Render, - Styled as _, TestAppContext, VisualTestContext, Window, div, px, - }; - - struct Answer { - state: Entity, - width: Pixels, - } - - impl Render for Answer { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div().w(self.width).child(TextView::new(&self.state)) - } - } - - fn draw(cx: &mut VisualTestContext) { - cx.update(|window, cx| window.draw(cx).clear(cx)); - } - - fn layouts() -> usize { - FLOW_LAYOUTS.with(|layouts| layouts.get()) - } - - /// Scrolling redraws every visible paragraph each frame; a flow whose - /// text, style and width are unchanged has nothing to wrap or shape. - #[gpui::test] - fn an_unchanged_flow_is_not_laid_out_again(cx: &mut TestAppContext) { - cx.update(crate::init); - let (_, cx) = cx.add_window_view(|_, cx| Answer { - state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), - width: px(300.), - }); - cx.run_until_parked(); - draw(cx); - let after_first_frame = layouts(); - assert!(after_first_frame >= 1, "the first frame lays the flow out"); - - for _ in 0..3 { - draw(cx); - } - - assert_eq!(layouts(), after_first_frame, "a frame that changes nothing"); - } - - #[gpui::test] - fn a_flow_is_laid_out_again_at_another_width(cx: &mut TestAppContext) { - cx.update(crate::init); - let (answer, cx) = cx.add_window_view(|_, cx| Answer { - state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), - width: px(300.), - }); - cx.run_until_parked(); - draw(cx); - let before = layouts(); - - answer.update(cx, |answer, _| answer.width = px(120.)); - draw(cx); - - assert!(layouts() > before, "a narrower flow wraps differently"); - } - - #[gpui::test] - fn a_flow_is_laid_out_again_when_its_text_changes(cx: &mut TestAppContext) { - cx.update(crate::init); - let (answer, cx) = cx.add_window_view(|_, cx| Answer { - state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), - width: px(300.), - }); - cx.run_until_parked(); - draw(cx); - let before = layouts(); - - answer.update(cx, |answer, cx| { - answer.state.update(cx, |state, cx| { - state.set_text("Call `foo` and `bar` now.", cx); - }) - }); - cx.run_until_parked(); - draw(cx); - - assert!(layouts() > before, "a new text has a new layout"); - } - } - - #[test] - fn atomic_objects_wrap_and_share_a_baseline_at_multiple_font_sizes() { - use super::super::inline::test_draw::in_prepaint; - use super::super::inline::test_fonts::{BODY, WideMonoTextSystem}; - use gpui::TestApp; - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - in_prepaint(&mut app, |window, cx| { - for scale in [1., 1.5, 2.] { - let style = TextStyle { - font_family: BODY.into(), - font_size: px(16. * scale).into(), - ..Default::default() - }; - let items = vec![ - MeasureItem::Text { - text: "中文 ".into(), - links: vec![], - highlights: vec![], - }, - MeasureItem::Object { - text: "x²".into(), - id: 0, - renderer: Arc::new(|_, _, _| None), - style: Default::default(), - }, - MeasureItem::Object { - text: "y²".into(), - id: 1, - renderer: Arc::new(|_, _, _| None), - style: Default::default(), - }, - MeasureItem::Text { - text: " English".into(), - links: vec![], - highlights: vec![], - }, - ]; - for width in [1., 30., 80., 500.] { - let layout = layout_flow( - &items, - &[None, None, None, None], - &style, - Some(px(width)), - window, - cx, - ); - let objects: Vec<_> = layout - .fragments - .iter() - .filter_map(|fragment| match fragment { - PositionedFragment::Object { origin, object, .. } => { - Some((origin, object)) - } - _ => None, - }) - .collect(); - assert_eq!(objects.len(), 2); - for (origin, object) in &objects { - assert!(object.metrics.size.width <= px(width)); - assert!(origin.y >= px(0.)); - assert!(origin.y + object.metrics.size.height <= layout.size.height); - } - if width == 500. { - assert_eq!( - objects[0].0.y + objects[0].1.metrics.baseline, - objects[1].0.y + objects[1].1.metrics.baseline - ); - } - } - } - }); - } - - #[test] - fn inline_image_without_explicit_size_scales_intrinsic_ratio_to_line_height() { - let line_height = px(20.); - let intrinsic_size = size(px(160.), px(40.)); - - let measured = inline_image_size_for_line(Some(intrinsic_size), line_height); - - assert_eq!(measured, size(px(60.), px(15.))); - } - - #[test] - fn inline_image_without_intrinsic_size_uses_compact_square_fallback() { - let measured = inline_image_size_for_line(None, px(20.)); - - assert_eq!(measured, size(px(15.), px(15.))); - } - - /// Line breaking must see the width of an inline code span in its own - /// family. With a body-font-only wrapper the span below is measured at - /// half its shaped width, the line is kept whole, and the flow reports a - /// width past `wrap_width`. - #[test] - fn inline_code_near_the_wrap_width_does_not_overflow_the_flow() { - use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; - use gpui::{AbsoluteLength, Empty, HighlightStyle, TestApp}; - - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - let mut window = app.open_window(|_, _| Empty); - - let font_size = px(10.); - let text_style = TextStyle { - font_family: SharedString::from(BODY), - font_size: AbsoluteLength::Pixels(font_size), - ..Default::default() - }; - let lead = SharedString::from("See "); - let tail_text = " with code_span_here end"; - let code = tail_text.find("code_span_here").unwrap(); - let code_range = code..code + "code_span_here".len(); - let code_highlight = InlineHighlight { - style: HighlightStyle::default(), - font_family: Some(SharedString::from(MONO)), - font_size_scale: None, - }; - let items = vec![ - MeasureItem::Text { - text: lead.clone(), - links: vec![], - highlights: vec![], - }, - MeasureItem::Image { - source: SharedUri::from("https://example.com/badge.png").into(), - width: None, - height: None, - }, - MeasureItem::Text { - text: SharedString::from(tail_text), - links: vec![], - highlights: vec![(code_range.clone(), code_highlight)], - }, - ]; - let image_size = size(px(10.), px(10.)); - let image_sizes = vec![None, Some(image_size), None]; - // Body text, the image and the mono span fill the wrap width exactly; - // the trailing "end" only fits if the span is under-measured. - let wrap_width = WideMonoTextSystem::width_of("See with ", BODY, font_size) - + image_size.width - + WideMonoTextSystem::width_of("code_span_here", MONO, font_size); - - let layout = window.update(|_, window, cx| { - layout_flow( - &items, - &image_sizes, - &text_style, - Some(wrap_width), - window, - cx, - ) - }); - - assert!( - layout.size.width <= wrap_width, - "flow width {:?} exceeds wrap width {:?}", - layout.size.width, - wrap_width - ); - let mono_fragment_width = layout - .fragments - .iter() - .find_map(|fragment| match fragment { - PositionedFragment::Text { text, size, .. } if text.contains("code_span_here") => { - Some(size.width) - } - _ => None, - }) - .expect("the code span is laid out as a text fragment"); - assert!( - mono_fragment_width >= WideMonoTextSystem::width_of("code_span_here", MONO, font_size), - "the code span fragment is shaped in the mono family" - ); - // The image sits vertically centred in its line, so line membership is - // read off the text fragments only. - let text_lines = layout - .fragments - .iter() - .filter_map(|fragment| match fragment { - PositionedFragment::Text { text, origin, .. } => Some((text.trim(), origin.y)), - PositionedFragment::Image { .. } | PositionedFragment::Object { .. } => None, - }) - .collect::>(); - let first_y = text_lines[0].1; - assert!( - text_lines - .iter() - .any(|(text, y)| text.contains("code_span_here") && *y == first_y), - "the span stays on the first line: {text_lines:?}" - ); - assert!( - text_lines - .iter() - .any(|(text, y)| *text == "end" && *y > first_y), - "the trailing word wraps to a second line: {text_lines:?}" - ); - } - #[test] - fn long_inline_code_wraps_in_mixed_flow() { - use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; - use gpui::{Empty, TestApp}; - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - let mut window = app.open_window(|_, _| Empty); - let style = TextStyle { - font_family: BODY.into(), - font_size: AbsoluteLength::Pixels(px(10.)), - ..Default::default() - }; - for text in [ - "one two three four five six", - "very_long_unbroken_identifier", - "你好世界你好世界你好世界", - "e\u{301}e\u{301}e\u{301}e\u{301}e\u{301}e\u{301}", - ] { - let items = vec![ - MeasureItem::Image { - source: SharedUri::from("https://example.com/icon.png").into(), - width: None, - height: None, - }, - MeasureItem::Text { - text: text.into(), - links: vec![], - highlights: vec![( - 0..text.len(), - InlineHighlight { - font_family: Some(MONO.into()), - ..Default::default() - }, - )], - }, - ]; - let image_sizes = vec![Some(size(px(10.), px(10.))), None]; - let layout = window.update(|_, window, cx| { - layout_flow(&items, &image_sizes, &style, Some(px(100.)), window, cx) - }); - assert!(layout.size.width <= px(100.), "{text:?}: {:?}", layout.size); - let reconstructed: String = layout - .fragments - .iter() - .filter_map(|fragment| match fragment { - PositionedFragment::Text { text, .. } => Some(text.as_ref()), - _ => None, - }) - .collect(); - assert_eq!(reconstructed, text); - } - } - - #[test] - fn inline_code_line_is_as_tall_as_a_plain_line_when_glyphs_overflow_it() { - use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; - use gpui::{Empty, TestApp}; - - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - let mut window = app.open_window(|_, _| Empty); - let style = TextStyle { - font_family: BODY.into(), - font_size: AbsoluteLength::Pixels(px(40.)), - line_height: px(30.).into(), - ..Default::default() - }; - let items = vec![MeasureItem::Text { - text: "a code z".into(), - links: vec![], - highlights: vec![( - 2..6, - InlineHighlight { - font_family: Some(MONO.into()), - font_size_scale: Some(0.875), - ..Default::default() - }, - )], - }]; - // The 40px glyphs are taller than the 30px line. A plain text line - // keeps the line height and lets them overflow, so a line with - // inline code must not grow to fit them. - window.update(|_, window, cx| { - let layout = layout_flow(&items, &[None], &style, None, window, cx); - assert_eq!(layout.size.height, window.pixel_snap(px(30.))); - }); - } - - #[test] - fn inline_code_size_is_relative_and_uses_the_native_body_baseline() { - use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; - use gpui::{Empty, TestApp}; - - let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); - let mut window = app.open_window(|_, _| Empty); - // These are the 16px body size and the example-markdown preview's - // 1.25x/1.5x inherited text-size zooms. - for body_size in [16., 20., 24.] { - let style = TextStyle { - font_family: BODY.into(), - font_size: AbsoluteLength::Pixels(px(body_size)), - ..Default::default() - }; - let items = vec![MeasureItem::Text { - text: "a code z".into(), - links: vec![], - highlights: vec![( - 2..6, - InlineHighlight { - font_family: Some(MONO.into()), - font_size_scale: Some(0.875), - ..Default::default() - }, - )], - }]; - window.update(|_, window, cx| { - let layout = layout_flow(&items, &[None], &style, None, window, cx); - let text_fragments = layout - .fragments - .iter() - .filter_map(|fragment| match fragment { - PositionedFragment::Text { - text, - font_size, - origin, - size, - .. - } => Some((text.as_ref(), *font_size, origin.y, *size)), - _ => None, - }) - .collect::>(); - assert_eq!(text_fragments.len(), 3); - assert_eq!(text_fragments[0].1, px(body_size)); - assert_eq!(text_fragments[1].0, "code"); - assert_eq!(text_fragments[1].1, px(body_size * 0.875)); - // The code run's box stays inside the line, so whatever it - // paints over its box cannot reach a neighboring line. - assert!(text_fragments[1].2 >= Pixels::ZERO); - assert!(text_fragments[1].2 + text_fragments[1].3.height <= layout.size.height); - assert_eq!( - text_fragments[1].3.width, - WideMonoTextSystem::width_of("code", MONO, px(body_size * 0.875)) - + px(INLINE_CODE_PADDING * 2.) - ); - - // GPUI paints shaped lines with positive `LineLayout::descent`. - // Derive the ordinary body glyph baseline directly from that - // native-compatible shaped line, rather than `baseline_offset`, - // whose FontMetrics descent is intentionally signed. - let body_runs = text_runs(1, &style, &[]); - let body_line = shape_line("a".into(), px(body_size), &body_runs, window); - let body_line_height = plain_line_height(&style, window.rem_size(), window); - let plain_body_baseline = (body_line_height - body_line.ascent - body_line.descent) - / 2. - + body_line.ascent; - // The smaller code run fits inside the body line, so the - // line must be exactly as tall as a plain one. - assert_eq!( - layout.size.height, body_line_height, - "{body_size}px line height" - ); - let mut painted_glyph_baseline = - |fragment: &(&str, Pixels, Pixels, Size)| { - let runs = if fragment.0 == "code" { - text_runs( - fragment.0.len(), - &style, - &[( - 0..fragment.0.len(), - InlineHighlight { - font_family: Some(MONO.into()), - font_size_scale: Some(0.875), - ..Default::default() - }, - )], - ) - } else { - text_runs(fragment.0.len(), &style, &[]) - }; - let shaped = shape_line(fragment.0.into(), fragment.1, &runs, window); - fragment.2 - + (fragment.3.height - shaped.ascent - shaped.descent) / 2. - + shaped.ascent - }; - - // `origin` is passed unchanged to Inline::paint_origin, so this - // checks the first body glyph's painted row position, not only - // the enclosing paragraph height. It must agree with a normal - // body line and with the adjacent inline-code glyph baseline. - assert_eq!( - text_fragments[0].2, - Pixels::ZERO, - "{body_size}px body origin" - ); - assert_eq!( - painted_glyph_baseline(&text_fragments[0]), - plain_body_baseline, - "{body_size}px body glyph baseline" - ); - assert_eq!( - painted_glyph_baseline(&text_fragments[1]), - plain_body_baseline, - "{body_size}px code glyph baseline" - ); - }); - } - } -} +mod tests; diff --git a/vendor/gpui-base/src/text/inline_flow/layout.rs b/vendor/gpui-base/src/text/inline_flow/layout.rs new file mode 100644 index 00000000..9803da79 --- /dev/null +++ b/vendor/gpui-base/src/text/inline_flow/layout.rs @@ -0,0 +1,685 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use std::{ops::Range, sync::Arc}; + +use gpui::{ + AbsoluteLength, App, AvailableSpace, Bounds, DefiniteLength, Hsla, ImageSource, + InteractiveElement as _, IntoElement as _, ObjectFit, Pixels, Refineable as _, ShapedLine, + SharedString, Size, Styled as _, StyledImage as _, TextRun, TextStyle, Window, img, point, + prelude::FluentBuilder as _, px, relative, size, +}; + +use crate::text::{ + InlineRenderContext, + inline::{InlineHighlight, highlights_in_range, text_runs, text_size_ranges_in}, + inline_object::MeasuredInlineObject, + node::LinkMark, +}; + +use super::{INLINE_CODE_PADDING, InlineFlowItem, InlineRenderer, slice_ranges}; + +mod wrapping; +use wrapping::line_ranges; + +const IMAGE_LEN: usize = 1; + +#[derive(Default)] +pub(super) struct InlineFlowLayout { + pub(super) fragments: Vec, + pub(super) size: Size, + pub(super) wrap_width: Option, +} + +pub(super) enum PositionedFragment { + Object { + item_ix: usize, + origin: gpui::Point, + object: Box, + selection_bounds: Bounds, + }, + Text { + item_ix: usize, + origin: gpui::Point, + size: Size, + source_range: Range, + font_size: Pixels, + text: SharedString, + links: Vec<(Range, LinkMark)>, + highlights: Vec<(Range, InlineHighlight)>, + selection_bounds: Bounds, + /// The rounded box behind a code span, relative to the flow. + code_background: Option<(Bounds, Hsla)>, + }, + Image { + item_ix: usize, + origin: gpui::Point, + size: Size, + }, +} + +pub(super) enum MeasureItem { + Object { + text: SharedString, + id: usize, + renderer: Arc, + style: gpui::HighlightStyle, + }, + Text { + text: SharedString, + links: Vec<(Range, LinkMark)>, + highlights: Vec<(Range, InlineHighlight)>, + }, + Image { + source: ImageSource, + width: Option, + height: Option, + }, +} + +struct LineFragmentLayout { + item_ix: usize, + kind: LineFragmentKind, + size: Size, + source_range: Range, + baseline: Pixels, +} + +enum LineFragmentKind { + Object(Box), + Text { + font_size: Pixels, + text: SharedString, + links: Vec<(Range, LinkMark)>, + highlights: Vec<(Range, InlineHighlight)>, + /// The code span's box, relative to the fragment. + code_background: Option<(Bounds, Hsla)>, + }, + Image, +} + +impl From<&InlineFlowItem> for MeasureItem { + fn from(item: &InlineFlowItem) -> Self { + match item { + InlineFlowItem::Object { + text, + id, + renderer, + style, + .. + } => Self::Object { + text: text.clone(), + id: *id, + renderer: renderer.clone(), + style: *style, + }, + InlineFlowItem::Text { + state: _, + text, + links, + highlights, + .. + } => MeasureItem::Text { + text: text.clone(), + links: links.clone(), + highlights: highlights.clone(), + }, + InlineFlowItem::Image { + source, + width, + height, + .. + } => MeasureItem::Image { + source: source.clone(), + width: *width, + height: *height, + }, + } + } +} + +impl MeasureItem { + fn len(&self) -> usize { + match self { + MeasureItem::Text { text, .. } => text.len(), + MeasureItem::Image { .. } | MeasureItem::Object { .. } => IMAGE_LEN, + } + } + + /// Whether `other` lays out the same as this item. An object is + /// rendered anew every frame, so a flow with one is never reused. + pub(super) fn same_layout_input(&self, other: &Self) -> bool { + match (self, other) { + ( + MeasureItem::Text { + text, + links, + highlights, + }, + MeasureItem::Text { + text: other_text, + links: other_links, + highlights: other_highlights, + }, + ) => text == other_text && links == other_links && highlights == other_highlights, + ( + MeasureItem::Image { width, height, .. }, + MeasureItem::Image { + width: other_width, + height: other_height, + .. + }, + ) => width == other_width && height == other_height, + _ => false, + } + } +} + +/// Intrinsic width for table sizing, using the same objects and wrapping inputs as painting. +pub(in crate::text) fn intrinsic_width( + items: &[InlineFlowItem], + window: &mut Window, + cx: &mut App, +) -> Pixels { + let items = items.iter().map(MeasureItem::from).collect::>(); + let line_height = window.line_height(); + let rem_size = window.rem_size(); + let images = items + .iter() + .enumerate() + .map(|(ix, item)| match item { + MeasureItem::Image { + source, + width, + height, + } => Some(measure_image_size( + ix, + source, + *width, + *height, + line_height, + rem_size, + window, + cx, + )), + _ => None, + }) + .collect::>(); + layout_flow(&items, &images, &window.text_style(), None, window, cx) + .size + .width +} + +pub(super) fn prepare_objects( + items: &[MeasureItem], + text_style: &TextStyle, + window: &mut Window, + cx: &mut App, +) -> Vec> { + items + .iter() + .map(|item| match item { + MeasureItem::Object { + text, + id, + renderer, + style, + } => { + let style = text_style.clone().highlight(*style); + let context = InlineRenderContext::new( + style.clone(), + style.font_size.to_pixels(window.rem_size()), + style.line_height_in_pixels(window.rem_size()), + window.rem_size(), + ); + // Must be the id `InlineObject` paints under: GPUI asserts a + // stateful child (a plugin's HoverCard) sees the same id path + // in request_layout as in prepaint, and the element is laid + // out here but painted inside `InlineObject`. + Some(window.with_id(("inline-object", *id), |window| { + let element = window + .with_text_style(Some(style.subtract(&Default::default())), |window| { + renderer(&context, window, cx) + }); + MeasuredInlineObject::measure(text, element, &style, window, cx) + })) + } + _ => None, + }) + .collect() +} + +pub(super) fn layout_flow( + items: &[MeasureItem], + image_sizes: &[Option>], + text_style: &TextStyle, + wrap_width: Option, + window: &mut Window, + cx: &mut App, +) -> InlineFlowLayout { + let objects = prepare_objects(items, text_style, window, cx); + layout_measured_flow( + items, + image_sizes, + &objects, + text_style, + wrap_width, + window, + cx, + ) +} + +#[cfg(test)] +thread_local! { + /// How many flows were laid out (wrapped and shaped) on this thread. + pub(super) static FLOW_LAYOUTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +pub(super) fn layout_measured_flow( + items: &[MeasureItem], + image_sizes: &[Option>], + prepared_objects: &[Option], + text_style: &TextStyle, + wrap_width: Option, + window: &mut Window, + _cx: &mut App, +) -> InlineFlowLayout { + #[cfg(test)] + FLOW_LAYOUTS.with(|layouts| layouts.set(layouts.get() + 1)); + let rem_size = window.rem_size(); + let line_height = plain_line_height(text_style, rem_size, window); + let total_len = items.iter().map(MeasureItem::len).sum::(); + if total_len == 0 { + return InlineFlowLayout::default(); + } + + let objects = prepared_objects + .iter() + .map(|object| object.clone().map(|object| object.fit_text(wrap_width))) + .collect::>(); + let line_ranges = line_ranges(items, image_sizes, &objects, text_style, wrap_width, window); + let font_size = text_style.font_size.to_pixels(rem_size); + let mut fragments = Vec::new(); + let mut max_width = Pixels::ZERO; + let mut y = Pixels::ZERO; + + for line_range in line_ranges { + let mut line_fragments = Vec::new(); + let mut line_width = Pixels::ZERO; + // `LineLayout` is the metric source used by the text paint path. Its + // descent is normalized positive by native backends, whereas + // `FontMetrics::descent` remains signed. Start with the same shaped + // body metrics used below for every text fragment rather than mixing + // those two conventions through `TextSystem::baseline_offset`. + let body_runs = text_runs(1, text_style, &[]); + let body_line = shape_line(" ".into(), font_size, &body_runs, window); + let body_baseline = centered_baseline(&body_line, line_height); + // Like a plain text line, the body line box is the line height even + // when the font's glyphs are taller; runs may overflow it as far as + // body glyphs do. + let body_overflow_above = (body_line.ascent - body_baseline).max(Pixels::ZERO); + let body_overflow_below = + (body_line.descent - (line_height - body_baseline)).max(Pixels::ZERO); + let mut line_ascent = body_baseline; + let mut line_descent = line_height - body_baseline; + let mut item_start = 0; + + for (item_ix, item) in items.iter().enumerate() { + let item_end = item_start + item.len(); + if item_end <= line_range.start { + item_start = item_end; + continue; + } + if item_start >= line_range.end { + break; + } + + match item { + MeasureItem::Text { + text, + links, + highlights, + } => { + let local_start = line_range.start.max(item_start) - item_start; + let local_end = line_range.end.min(item_end) - item_start; + for (segment, scale) in text_size_ranges_in(local_start..local_end, highlights) + { + let start = segment.start; + let end = segment.end; + let subtext = SharedString::from(text[start..end].to_string()); + let mut highlights = slice_ranges( + highlights_in_range(highlights, &(start..end)), + start, + end, + |range, style| (range, style.clone()), + ); + let links = + slice_ranges(links, start, end, |range, link| (range, link.clone())); + let runs = text_runs(subtext.len(), text_style, &highlights); + let segment_font_size = font_size * scale; + let shaped_line = + shape_line(subtext.clone(), segment_font_size, &runs, window); + let is_code = highlights.iter().any(|(_, h)| h.font_size_scale.is_some()); + let padding = if is_code { + px(INLINE_CODE_PADDING * 2.) + } else { + Pixels::ZERO + }; + let width = shaped_line.width() + padding; + // Measure the run by its glyph box. The body strut already + // carries the line's leading, so a run only has to fit its + // glyphs: leading of its own would make a smaller or + // differently proportioned run, such as inline code, push + // its line taller than a plain one. Positioning grows the + // box back to the line. The compact code background is + // painted independently. + let glyph_size = size(width, shaped_line.ascent + shaped_line.descent); + let baseline = shaped_line.ascent; + let code_background = is_code + .then(|| { + code_background( + &shaped_line, + &runs, + segment_font_size, + &mut highlights, + glyph_size, + baseline, + window, + ) + }) + .flatten(); + line_ascent = line_ascent.max(baseline - body_overflow_above); + line_descent = + line_descent.max(glyph_size.height - baseline - body_overflow_below); + line_width += width; + line_fragments.push(LineFragmentLayout { + item_ix, + kind: LineFragmentKind::Text { + font_size: segment_font_size, + text: subtext, + links, + highlights, + code_background, + }, + size: glyph_size, + source_range: start..end, + baseline: baseline, + }); + } + } + MeasureItem::Object { .. } => { + let object = objects[item_ix].as_ref().unwrap().clone(); + let metrics = object.metrics; + line_ascent = line_ascent.max(metrics.baseline); + line_descent = line_descent.max(metrics.size.height - metrics.baseline); + line_width += metrics.size.width; + line_fragments.push(LineFragmentLayout { + item_ix, + kind: LineFragmentKind::Object(Box::new(object)), + size: metrics.size, + source_range: 0..IMAGE_LEN, + baseline: metrics.baseline, + }); + } + MeasureItem::Image { .. } => { + if line_range.start <= item_start && item_end <= line_range.end { + let size = image_sizes[item_ix] + .expect("image size should be measured before layout"); + line_width += size.width; + let baseline = (size.height / 2. + body_baseline - line_height / 2.) + .max(Pixels::ZERO) + .min(size.height); + line_ascent = line_ascent.max(baseline); + line_descent = line_descent.max(size.height - baseline); + line_fragments.push(LineFragmentLayout { + item_ix, + kind: LineFragmentKind::Image, + size, + source_range: 0..IMAGE_LEN, + baseline: baseline, + }); + } + } + } + + item_start = item_end; + } + + let mut x = Pixels::ZERO; + for mut fragment in line_fragments { + // Give a text run's glyph box equal leading on both sides, as + // much as the line allows: its glyphs are painted centered in the + // box, so this keeps them on the line's baseline, and a body run + // gets exactly the line box. The leading is negative where the + // glyphs overflow the line, as a plain text line's do. + let leading = match fragment.kind { + LineFragmentKind::Text { .. } => (line_ascent - fragment.baseline) + .min(line_descent - (fragment.size.height - fragment.baseline)) + .max(-fragment.size.height / 2.), + _ => Pixels::ZERO, + }; + fragment.size.height += leading * 2.; + fragment.baseline += leading; + let origin = point(x, y + line_ascent - fragment.baseline); + let selection_bounds = Bounds::new( + point(x, y), + size(fragment.size.width, line_ascent + line_descent), + ); + let positioned = match fragment.kind { + LineFragmentKind::Object(object) => PositionedFragment::Object { + item_ix: fragment.item_ix, + origin, + object, + selection_bounds, + }, + LineFragmentKind::Text { + font_size, + text, + links, + highlights, + code_background, + } => PositionedFragment::Text { + item_ix: fragment.item_ix, + origin, + size: fragment.size, + source_range: fragment.source_range, + selection_bounds, + font_size, + text, + links, + highlights, + code_background: code_background.map(|(background, color)| { + ( + Bounds::new( + origin + point(Pixels::ZERO, leading) + background.origin, + background.size, + ), + color, + ) + }), + }, + LineFragmentKind::Image => PositionedFragment::Image { + item_ix: fragment.item_ix, + origin, + size: fragment.size, + }, + }; + x += fragment.size.width; + fragments.push(positioned); + } + + max_width = max_width.max(line_width); + y += line_ascent + line_descent; + } + + InlineFlowLayout { + fragments, + size: size(max_width, y), + wrap_width, + } +} + +/// The rounded box behind a code span, relative to the fragment: centered on +/// the capital-height body of the text, with the descender room shared +/// between both sides instead of added only below. Takes the background +/// color out of `highlights`, so the text does not paint it a second time +/// at the full line height. +fn code_background( + shaped_line: &ShapedLine, + runs: &[TextRun], + font_size: Pixels, + highlights: &mut [(Range, InlineHighlight)], + fragment_size: Size, + baseline: Pixels, + window: &Window, +) -> Option<(Bounds, Hsla)> { + let cap_height = runs + .iter() + .map(|run| { + let font = window.text_system().resolve_font(&run.font); + window.text_system().cap_height(font, font_size) + }) + .fold(Pixels::ZERO, Pixels::max); + let vertical_padding = font_size * 0.125 + shaped_line.descent / 2.; + let color = highlights + .iter() + .find_map(|(_, h)| h.style.background_color); + for (_, highlight) in highlights.iter_mut() { + highlight.style.background_color = None; + } + color.map(|color| { + ( + Bounds::new( + point(Pixels::ZERO, baseline - cap_height - vertical_padding), + size(fragment_size.width, cap_height + vertical_padding * 2.), + ), + color, + ) + }) +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn measure_image_size( + ix: usize, + source: &ImageSource, + width: Option, + height: Option, + line_height: Pixels, + rem_size: Pixels, + window: &mut Window, + cx: &mut App, +) -> Size { + let intrinsic_size = if width.is_some() && height.is_some() { + None + } else { + intrinsic_image_size(ix, source, width, height, window, cx) + }; + image_size(width, height, intrinsic_size, line_height, rem_size) +} + +fn intrinsic_image_size( + ix: usize, + source: &ImageSource, + width: Option, + height: Option, + window: &mut Window, + cx: &mut App, +) -> Option> { + let mut element = img(source.clone()) + .id(ix) + .object_fit(ObjectFit::Contain) + .max_w(relative(1.)) + .when_some(width, |this, width| this.w(width)) + .when_some(height, |this, height| this.h(height)) + .into_any_element(); + let measured_size = element.layout_as_root(AvailableSpace::min_size(), window, cx); + + if measured_size.width <= Pixels::ZERO || measured_size.height <= Pixels::ZERO { + None + } else { + Some(measured_size) + } +} + +fn image_size( + width: Option, + height: Option, + intrinsic_size: Option>, + line_height: Pixels, + rem_size: Pixels, +) -> Size { + let base_size = AbsoluteLength::Pixels(line_height); + match (width, height) { + (Some(width), Some(height)) => size( + width.to_pixels(base_size, rem_size), + height.to_pixels(base_size, rem_size), + ), + (Some(width), None) => { + let width = width.to_pixels(base_size, rem_size); + let height = intrinsic_size + .and_then(|intrinsic_size| { + (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO) + .then(|| width * (intrinsic_size.height / intrinsic_size.width)) + }) + .unwrap_or(line_height); + size(width, height) + } + (None, Some(height)) => { + let height = height.to_pixels(base_size, rem_size); + let width = intrinsic_size + .and_then(|intrinsic_size| { + (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO) + .then(|| height * (intrinsic_size.width / intrinsic_size.height)) + }) + .unwrap_or(height); + size(width, height) + } + (None, None) => inline_image_size_for_line(intrinsic_size, line_height), + } +} + +pub(super) fn inline_image_size_for_line( + intrinsic_size: Option>, + line_height: Pixels, +) -> Size { + let height = line_height * 0.75; + let aspect_ratio = intrinsic_size + .and_then(|intrinsic_size| { + (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO) + .then(|| intrinsic_size.width / intrinsic_size.height) + }) + .unwrap_or(1.); + + size((height * aspect_ratio).max(px(1.)), height.max(px(1.))) +} + +pub(super) fn shape_line( + text: SharedString, + font_size: Pixels, + runs: &[TextRun], + window: &mut Window, +) -> ShapedLine { + window.text_system().shape_line(text, font_size, runs, None) +} + +/// The line height GPUI's text layout gives a plain line in `text_style`. +/// Unlike `Window::line_height`, it is not first rounded to a whole logical +/// pixel, which would make a flow line taller than a plain one. +pub(super) fn plain_line_height( + text_style: &TextStyle, + rem_size: Pixels, + window: &Window, +) -> Pixels { + window.pixel_snap( + text_style + .line_height + .to_pixels(text_style.font_size, rem_size), + ) +} + +/// Returns where GPUI text painting puts the baseline of `shaped_line` in a +/// box `line_height` tall: centered, even when the glyphs overflow the box. +/// `ShapedLine::descent` is positive; do not substitute the signed +/// `FontMetrics::descent` exposed by `TextSystem::baseline_offset` here. +fn centered_baseline(shaped_line: &ShapedLine, line_height: Pixels) -> Pixels { + (line_height - shaped_line.ascent - shaped_line.descent) / 2. + shaped_line.ascent +} diff --git a/vendor/gpui-base/src/text/inline_flow/layout/wrapping.rs b/vendor/gpui-base/src/text/inline_flow/layout/wrapping.rs new file mode 100644 index 00000000..454d7af2 --- /dev/null +++ b/vendor/gpui-base/src/text/inline_flow/layout/wrapping.rs @@ -0,0 +1,189 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use std::ops::Range; + +use gpui::{LineFragment, Pixels, Size, TextStyle, Window, px}; +use unicode_segmentation::UnicodeSegmentation as _; + +use crate::text::{ + inline::{InlineHighlight, highlights_in_range, text_runs}, + inline_object::MeasuredInlineObject, +}; + +use super::{IMAGE_LEN, INLINE_CODE_PADDING, MeasureItem}; + +pub(super) fn line_ranges( + items: &[MeasureItem], + image_sizes: &[Option>], + objects: &[Option], + text_style: &TextStyle, + wrap_width: Option, + window: &mut Window, +) -> Vec> { + let total_len = items.iter().map(MeasureItem::len).sum::(); + let mut hard_lines = Vec::new(); + let mut line_start = 0; + let mut item_start = 0; + + for item in items { + if let MeasureItem::Text { text, .. } = item { + for (newline, _) in text.match_indices('\n') { + let newline = item_start + newline; + hard_lines.push(line_start..newline); + line_start = newline + 1; + } + } + item_start += item.len(); + } + hard_lines.push(line_start..total_len); + + let Some(wrap_width) = wrap_width else { + return hard_lines; + }; + let rem_size = window.rem_size(); + let font_size = text_style.font_size.to_pixels(rem_size); + let mut wrapper = window + .text_system() + .line_wrapper(text_style.font(), font_size); + let mut ranges = Vec::new(); + + for hard_line in hard_lines { + let mut item_start = 0; + let mut wrap_fragments = Vec::new(); + for (ix, item) in items.iter().enumerate() { + let item_end = item_start + item.len(); + if item_end > hard_line.start && item_start < hard_line.end { + match item { + MeasureItem::Text { + text, highlights, .. + } => { + let start = hard_line.start.max(item_start) - item_start; + let end = hard_line.end.min(item_end) - item_start; + if start < end { + push_text_wrap_fragments( + &mut wrap_fragments, + text, + highlights, + start..end, + text_style, + wrap_width, + window, + ); + } + } + MeasureItem::Object { .. } => { + wrap_fragments.push(LineFragment::element( + objects[ix].as_ref().unwrap().metrics.size.width, + IMAGE_LEN, + )); + } + MeasureItem::Image { .. } => { + if hard_line.start <= item_start && item_end <= hard_line.end { + wrap_fragments.push(LineFragment::element( + image_sizes[ix] + .expect("image size should be measured before wrapping") + .width, + IMAGE_LEN, + )); + } + } + } + } + item_start = item_end; + } + + let boundaries = wrapper + .wrap_line(&wrap_fragments, wrap_width) + .map(|boundary| hard_line.start + boundary.ix.min(hard_line.len())) + .collect::>(); + let mut start = hard_line.start; + + for end in boundaries { + if start < end { + ranges.push(start..end); + } + start = end; + } + + if start < hard_line.end || hard_line.is_empty() { + ranges.push(start..hard_line.end); + } + } + + ranges +} + +/// Appends the wrap fragments for `range` of `text`. The line wrapper +/// measures text fragments in the body font, so a span whose highlight sets +/// another family is shaped with the same run the renderer uses and enters +/// the wrapper as measured elements. Oversized spans retain word boundaries; +/// oversized words can break at grapheme boundaries without splitting Unicode. +fn push_text_wrap_fragments<'a>( + fragments: &mut Vec>, + text: &'a str, + highlights: &[(Range, InlineHighlight)], + range: Range, + text_style: &TextStyle, + wrap_width: Pixels, + window: &mut Window, +) { + let font_size = text_style.font_size.to_pixels(window.rem_size()); + let mut cursor = range.start; + for (highlight_range, highlight) in highlights_in_range(highlights, &range) { + if highlight.font_family.is_none() { + continue; + } + let start = highlight_range.start.max(cursor); + let end = highlight_range.end.min(range.end); + if start >= end { + continue; + } + if cursor < start { + fragments.push(LineFragment::text(&text[cursor..start])); + } + let span = &text[start..end]; + let measure = |text: &str| { + let runs = text_runs( + text.len(), + text_style, + &[(0..text.len(), highlight.clone())], + ); + window + .text_system() + .layout_line( + text, + font_size * highlight.font_size_scale.unwrap_or(1.), + &runs, + None, + ) + .width + }; + let padding = if highlight.font_size_scale.is_some() { + px(INLINE_CODE_PADDING * 2.) + } else { + Pixels::ZERO + }; + let width = measure(span) + padding; + if width <= wrap_width { + fragments.push(LineFragment::element(width, span.len())); + } else { + for word in span.split_word_bounds() { + let width = measure(word) + padding; + if width <= wrap_width { + fragments.push(LineFragment::element(width, word.len())); + } else { + for grapheme in word.graphemes(true) { + fragments.push(LineFragment::element( + measure(grapheme) + padding, + grapheme.len(), + )); + } + } + } + } + cursor = end; + } + if cursor < range.end { + fragments.push(LineFragment::text(&text[cursor..range.end])); + } +} diff --git a/vendor/gpui-base/src/text/inline_flow/tests.rs b/vendor/gpui-base/src/text/inline_flow/tests.rs new file mode 100644 index 00000000..bbc0c1fa --- /dev/null +++ b/vendor/gpui-base/src/text/inline_flow/tests.rs @@ -0,0 +1,493 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use super::layout::{inline_image_size_for_line, layout_flow, plain_line_height, shape_line}; +use super::*; +use crate::text::inline::text_runs; +use gpui::{AbsoluteLength, SharedUri}; + +mod frames { + use super::super::layout::FLOW_LAYOUTS; + use crate::text::{TextView, TextViewState}; + use gpui::{ + AppContext as _, Context, Entity, IntoElement, ParentElement as _, Pixels, Render, + Styled as _, TestAppContext, VisualTestContext, Window, div, px, + }; + + struct Answer { + state: Entity, + width: Pixels, + } + + impl Render for Answer { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().w(self.width).child(TextView::new(&self.state)) + } + } + + fn draw(cx: &mut VisualTestContext) { + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + fn layouts() -> usize { + FLOW_LAYOUTS.with(|layouts| layouts.get()) + } + + /// Scrolling redraws every visible paragraph each frame; a flow whose + /// text, style and width are unchanged has nothing to wrap or shape. + #[gpui::test] + fn an_unchanged_flow_is_not_laid_out_again(cx: &mut TestAppContext) { + cx.update(crate::init); + let (_, cx) = cx.add_window_view(|_, cx| Answer { + state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), + width: px(300.), + }); + cx.run_until_parked(); + draw(cx); + let after_first_frame = layouts(); + assert!(after_first_frame >= 1, "the first frame lays the flow out"); + + for _ in 0..3 { + draw(cx); + } + + assert_eq!(layouts(), after_first_frame, "a frame that changes nothing"); + } + + #[gpui::test] + fn a_flow_is_laid_out_again_at_another_width(cx: &mut TestAppContext) { + cx.update(crate::init); + let (answer, cx) = cx.add_window_view(|_, cx| Answer { + state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), + width: px(300.), + }); + cx.run_until_parked(); + draw(cx); + let before = layouts(); + + answer.update(cx, |answer, _| answer.width = px(120.)); + draw(cx); + + assert!(layouts() > before, "a narrower flow wraps differently"); + } + + #[gpui::test] + fn a_flow_is_laid_out_again_when_its_text_changes(cx: &mut TestAppContext) { + cx.update(crate::init); + let (answer, cx) = cx.add_window_view(|_, cx| Answer { + state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)), + width: px(300.), + }); + cx.run_until_parked(); + draw(cx); + let before = layouts(); + + answer.update(cx, |answer, cx| { + answer.state.update(cx, |state, cx| { + state.set_text("Call `foo` and `bar` now.", cx); + }) + }); + cx.run_until_parked(); + draw(cx); + + assert!(layouts() > before, "a new text has a new layout"); + } +} + +#[test] +fn atomic_objects_wrap_and_share_a_baseline_at_multiple_font_sizes() { + use super::super::inline::test_draw::in_prepaint; + use super::super::inline::test_fonts::{BODY, WideMonoTextSystem}; + use gpui::TestApp; + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + in_prepaint(&mut app, |window, cx| { + for scale in [1., 1.5, 2.] { + let style = TextStyle { + font_family: BODY.into(), + font_size: px(16. * scale).into(), + ..Default::default() + }; + let items = vec![ + MeasureItem::Text { + text: "中文 ".into(), + links: vec![], + highlights: vec![], + }, + MeasureItem::Object { + text: "x²".into(), + id: 0, + renderer: Arc::new(|_, _, _| None), + style: Default::default(), + }, + MeasureItem::Object { + text: "y²".into(), + id: 1, + renderer: Arc::new(|_, _, _| None), + style: Default::default(), + }, + MeasureItem::Text { + text: " English".into(), + links: vec![], + highlights: vec![], + }, + ]; + for width in [1., 30., 80., 500.] { + let layout = layout_flow( + &items, + &[None, None, None, None], + &style, + Some(px(width)), + window, + cx, + ); + let objects: Vec<_> = layout + .fragments + .iter() + .filter_map(|fragment| match fragment { + PositionedFragment::Object { origin, object, .. } => Some((origin, object)), + _ => None, + }) + .collect(); + assert_eq!(objects.len(), 2); + for (origin, object) in &objects { + assert!(object.metrics.size.width <= px(width)); + assert!(origin.y >= px(0.)); + assert!(origin.y + object.metrics.size.height <= layout.size.height); + } + if width == 500. { + assert_eq!( + objects[0].0.y + objects[0].1.metrics.baseline, + objects[1].0.y + objects[1].1.metrics.baseline + ); + } + } + } + }); +} + +#[test] +fn inline_image_without_explicit_size_scales_intrinsic_ratio_to_line_height() { + let line_height = px(20.); + let intrinsic_size = size(px(160.), px(40.)); + + let measured = inline_image_size_for_line(Some(intrinsic_size), line_height); + + assert_eq!(measured, size(px(60.), px(15.))); +} + +#[test] +fn inline_image_without_intrinsic_size_uses_compact_square_fallback() { + let measured = inline_image_size_for_line(None, px(20.)); + + assert_eq!(measured, size(px(15.), px(15.))); +} + +/// Line breaking must see the width of an inline code span in its own +/// family. With a body-font-only wrapper the span below is measured at +/// half its shaped width, the line is kept whole, and the flow reports a +/// width past `wrap_width`. +#[test] +fn inline_code_near_the_wrap_width_does_not_overflow_the_flow() { + use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; + use gpui::{Empty, HighlightStyle, TestApp}; + + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + let mut window = app.open_window(|_, _| Empty); + + let font_size = px(10.); + let text_style = TextStyle { + font_family: SharedString::from(BODY), + font_size: AbsoluteLength::Pixels(font_size), + ..Default::default() + }; + let lead = SharedString::from("See "); + let tail_text = " with code_span_here end"; + let code = tail_text.find("code_span_here").unwrap(); + let code_range = code..code + "code_span_here".len(); + let code_highlight = InlineHighlight { + style: HighlightStyle::default(), + font_family: Some(SharedString::from(MONO)), + font_size_scale: None, + }; + let items = vec![ + MeasureItem::Text { + text: lead.clone(), + links: vec![], + highlights: vec![], + }, + MeasureItem::Image { + source: SharedUri::from("https://example.com/badge.png").into(), + width: None, + height: None, + }, + MeasureItem::Text { + text: SharedString::from(tail_text), + links: vec![], + highlights: vec![(code_range.clone(), code_highlight)], + }, + ]; + let image_size = size(px(10.), px(10.)); + let image_sizes = vec![None, Some(image_size), None]; + // Body text, the image and the mono span fill the wrap width exactly; + // the trailing "end" only fits if the span is under-measured. + let wrap_width = WideMonoTextSystem::width_of("See with ", BODY, font_size) + + image_size.width + + WideMonoTextSystem::width_of("code_span_here", MONO, font_size); + + let layout = window.update(|_, window, cx| { + layout_flow( + &items, + &image_sizes, + &text_style, + Some(wrap_width), + window, + cx, + ) + }); + + assert!( + layout.size.width <= wrap_width, + "flow width {:?} exceeds wrap width {:?}", + layout.size.width, + wrap_width + ); + let mono_fragment_width = layout + .fragments + .iter() + .find_map(|fragment| match fragment { + PositionedFragment::Text { text, size, .. } if text.contains("code_span_here") => { + Some(size.width) + } + _ => None, + }) + .expect("the code span is laid out as a text fragment"); + assert!( + mono_fragment_width >= WideMonoTextSystem::width_of("code_span_here", MONO, font_size), + "the code span fragment is shaped in the mono family" + ); + // The image sits vertically centred in its line, so line membership is + // read off the text fragments only. + let text_lines = layout + .fragments + .iter() + .filter_map(|fragment| match fragment { + PositionedFragment::Text { text, origin, .. } => Some((text.trim(), origin.y)), + PositionedFragment::Image { .. } | PositionedFragment::Object { .. } => None, + }) + .collect::>(); + let first_y = text_lines[0].1; + assert!( + text_lines + .iter() + .any(|(text, y)| text.contains("code_span_here") && *y == first_y), + "the span stays on the first line: {text_lines:?}" + ); + assert!( + text_lines + .iter() + .any(|(text, y)| *text == "end" && *y > first_y), + "the trailing word wraps to a second line: {text_lines:?}" + ); +} +#[test] +fn long_inline_code_wraps_in_mixed_flow() { + use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; + use gpui::{Empty, TestApp}; + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + let mut window = app.open_window(|_, _| Empty); + let style = TextStyle { + font_family: BODY.into(), + font_size: AbsoluteLength::Pixels(px(10.)), + ..Default::default() + }; + for text in [ + "one two three four five six", + "very_long_unbroken_identifier", + "你好世界你好世界你好世界", + "e\u{301}e\u{301}e\u{301}e\u{301}e\u{301}e\u{301}", + ] { + let items = vec![ + MeasureItem::Image { + source: SharedUri::from("https://example.com/icon.png").into(), + width: None, + height: None, + }, + MeasureItem::Text { + text: text.into(), + links: vec![], + highlights: vec![( + 0..text.len(), + InlineHighlight { + font_family: Some(MONO.into()), + ..Default::default() + }, + )], + }, + ]; + let image_sizes = vec![Some(size(px(10.), px(10.))), None]; + let layout = window.update(|_, window, cx| { + layout_flow(&items, &image_sizes, &style, Some(px(100.)), window, cx) + }); + assert!(layout.size.width <= px(100.), "{text:?}: {:?}", layout.size); + let reconstructed: String = layout + .fragments + .iter() + .filter_map(|fragment| match fragment { + PositionedFragment::Text { text, .. } => Some(text.as_ref()), + _ => None, + }) + .collect(); + assert_eq!(reconstructed, text); + } +} + +#[test] +fn inline_code_line_is_as_tall_as_a_plain_line_when_glyphs_overflow_it() { + use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; + use gpui::{Empty, TestApp}; + + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + let mut window = app.open_window(|_, _| Empty); + let style = TextStyle { + font_family: BODY.into(), + font_size: AbsoluteLength::Pixels(px(40.)), + line_height: px(30.).into(), + ..Default::default() + }; + let items = vec![MeasureItem::Text { + text: "a code z".into(), + links: vec![], + highlights: vec![( + 2..6, + InlineHighlight { + font_family: Some(MONO.into()), + font_size_scale: Some(0.875), + ..Default::default() + }, + )], + }]; + // The 40px glyphs are taller than the 30px line. A plain text line + // keeps the line height and lets them overflow, so a line with + // inline code must not grow to fit them. + window.update(|_, window, cx| { + let layout = layout_flow(&items, &[None], &style, None, window, cx); + assert_eq!(layout.size.height, window.pixel_snap(px(30.))); + }); +} + +#[test] +fn inline_code_size_is_relative_and_uses_the_native_body_baseline() { + use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem}; + use gpui::{Empty, TestApp}; + + let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem)); + let mut window = app.open_window(|_, _| Empty); + // These are the 16px body size and the example-markdown preview's + // 1.25x/1.5x inherited text-size zooms. + for body_size in [16., 20., 24.] { + let style = TextStyle { + font_family: BODY.into(), + font_size: AbsoluteLength::Pixels(px(body_size)), + ..Default::default() + }; + let items = vec![MeasureItem::Text { + text: "a code z".into(), + links: vec![], + highlights: vec![( + 2..6, + InlineHighlight { + font_family: Some(MONO.into()), + font_size_scale: Some(0.875), + ..Default::default() + }, + )], + }]; + window.update(|_, window, cx| { + let layout = layout_flow(&items, &[None], &style, None, window, cx); + let text_fragments = layout + .fragments + .iter() + .filter_map(|fragment| match fragment { + PositionedFragment::Text { + text, + font_size, + origin, + size, + .. + } => Some((text.as_ref(), *font_size, origin.y, *size)), + _ => None, + }) + .collect::>(); + assert_eq!(text_fragments.len(), 3); + assert_eq!(text_fragments[0].1, px(body_size)); + assert_eq!(text_fragments[1].0, "code"); + assert_eq!(text_fragments[1].1, px(body_size * 0.875)); + // The code run's box stays inside the line, so whatever it + // paints over its box cannot reach a neighboring line. + assert!(text_fragments[1].2 >= Pixels::ZERO); + assert!(text_fragments[1].2 + text_fragments[1].3.height <= layout.size.height); + assert_eq!( + text_fragments[1].3.width, + WideMonoTextSystem::width_of("code", MONO, px(body_size * 0.875)) + + px(INLINE_CODE_PADDING * 2.) + ); + + // GPUI paints shaped lines with positive `LineLayout::descent`. + // Derive the ordinary body glyph baseline directly from that + // native-compatible shaped line, rather than `baseline_offset`, + // whose FontMetrics descent is intentionally signed. + let body_runs = text_runs(1, &style, &[]); + let body_line = shape_line("a".into(), px(body_size), &body_runs, window); + let body_line_height = plain_line_height(&style, window.rem_size(), window); + let plain_body_baseline = + (body_line_height - body_line.ascent - body_line.descent) / 2. + body_line.ascent; + // The smaller code run fits inside the body line, so the + // line must be exactly as tall as a plain one. + assert_eq!( + layout.size.height, body_line_height, + "{body_size}px line height" + ); + let mut painted_glyph_baseline = |fragment: &(&str, Pixels, Pixels, Size)| { + let runs = if fragment.0 == "code" { + text_runs( + fragment.0.len(), + &style, + &[( + 0..fragment.0.len(), + InlineHighlight { + font_family: Some(MONO.into()), + font_size_scale: Some(0.875), + ..Default::default() + }, + )], + ) + } else { + text_runs(fragment.0.len(), &style, &[]) + }; + let shaped = shape_line(fragment.0.into(), fragment.1, &runs, window); + fragment.2 + + (fragment.3.height - shaped.ascent - shaped.descent) / 2. + + shaped.ascent + }; + + // `origin` is passed unchanged to the positioned Inline, so this + // checks the first body glyph's painted row position, not only + // the enclosing paragraph height. It must agree with a normal + // body line and with the adjacent inline-code glyph baseline. + assert_eq!( + text_fragments[0].2, + Pixels::ZERO, + "{body_size}px body origin" + ); + assert_eq!( + painted_glyph_baseline(&text_fragments[0]), + plain_body_baseline, + "{body_size}px body glyph baseline" + ); + assert_eq!( + painted_glyph_baseline(&text_fragments[1]), + plain_body_baseline, + "{body_size}px code glyph baseline" + ); + }); + } +} diff --git a/vendor/gpui-base/src/text/node.rs b/vendor/gpui-base/src/text/node.rs index 9fb6b37e..6be967de 100644 --- a/vendor/gpui-base/src/text/node.rs +++ b/vendor/gpui-base/src/text/node.rs @@ -12,6 +12,7 @@ use gpui::{ img, prelude::FluentBuilder as _, px, relative, rems, }; use markdown::mdast; +use smallvec::SmallVec; use crate::{ StyledExt, h_flex, @@ -21,8 +22,8 @@ use crate::{ MarkdownNode, TableActionsFn, document::NodeRenderOptions, inline::{ - Inline, InlineHighlight, InlineState, combine_highlights, fade_highlights, text_runs, - text_size_ranges, + Inline, InlineHighlight, InlineState, append_node_highlights, fade_highlights, + text_runs, text_size_ranges, }, inline_flow::{InlineFlow, InlineFlowItem, slice_ranges}, range_highlight::{RangeHighlightFrame, RevealAt, RevealRequest}, @@ -1198,7 +1199,7 @@ impl Paragraph { for inline_node in &self.children { let text_len = inline_node.text.len(); text.push_str(&inline_node.text); - let mut node_highlights = vec![]; + let mut node_highlights = SmallVec::new(); for (range, style) in &inline_node.marks { let inner_range = (offset + range.start)..(offset + range.end); let mut highlight = mark_highlight(style, node_cx, cx); @@ -1212,7 +1213,7 @@ impl Paragraph { } node_highlights.push((inner_range, highlight)); } - highlights = combine_highlights(highlights, node_highlights); + append_node_highlights(&mut highlights, node_highlights); offset += text_len; } let text = SharedString::from(text); @@ -2105,8 +2106,8 @@ impl Paragraph { mark_highlight(mark, node_cx, cx), ) }) - .collect::>(); - highlights = combine_highlights(highlights, node_highlights); + .collect(); + append_node_highlights(&mut highlights, node_highlights); offset += inline_node.text.len(); } highlights @@ -2118,6 +2119,7 @@ impl Paragraph { fn render( &self, fade_key: Option, + gap: Rems, node_cx: &NodeContext, _window: &mut Window, cx: &mut App, @@ -2127,12 +2129,15 @@ impl Paragraph { let backgrounds = node_cx.range_backgrounds(fade_key); if self.should_render_inline_flow() { - return InlineFlow::new( - leaf_element_id(fade_key), - self.inline_flow_items(fade_key, fades, backgrounds, node_cx, cx), - node_cx.link_click_handler.clone(), - ) - .into_any_element(); + return gapped( + InlineFlow::new( + leaf_element_id(fade_key), + self.inline_flow_items(fade_key, fades, backgrounds, node_cx, cx), + node_cx.link_click_handler.clone(), + ) + .into_any_element(), + gap, + ); } let has_image = children.iter().any(|child| child.image.is_some()); @@ -2141,7 +2146,7 @@ impl Paragraph { if !has_image { let (text, highlights, mut links) = self.plain_render(node_cx, cx); if text.is_empty() { - return div().into_any_element(); + return div().pb(gap).into_any_element(); } for (_, link_mark) in &mut links { if let Some(identifier) = link_mark.identifier.as_ref() @@ -2162,6 +2167,7 @@ impl Paragraph { highlights, node_cx.link_click_handler.clone(), ) + .bottom_padding(gap) .range_backgrounds(backgrounds) .reveal(reveal) .into_any_element(); @@ -2249,7 +2255,7 @@ impl Paragraph { highlights.clear(); offset = 0; } else { - let mut node_highlights = vec![]; + let mut node_highlights = SmallVec::new(); for (range, style) in &inline_node.marks { let inner_range = (offset + range.start)..(offset + range.end); let mut highlight = mark_highlight(style, node_cx, cx); @@ -2274,7 +2280,7 @@ impl Paragraph { node_highlights.push((inner_range, highlight)); } - highlights = combine_highlights(highlights, node_highlights); + append_node_highlights(&mut highlights, node_highlights); offset += text_len; } } @@ -2299,19 +2305,15 @@ impl Paragraph { ); } - // Text alone is one `Inline`, which needs no box of its own. Images - // keep an identified box: an image's element state is its animation, + // Images keep an identified box: its element state is the animation, // and the box scopes that state per paragraph. - if !has_image { - return child_nodes - .pop() - .unwrap_or_else(|| div().into_any_element()); - } - - div() - .id(leaf_element_id(fade_key)) - .children(child_nodes) - .into_any_element() + gapped( + div() + .id(leaf_element_id(fade_key)) + .children(child_nodes) + .into_any_element(), + gap, + ) } fn should_render_inline_flow(&self) -> bool { @@ -2437,7 +2439,7 @@ impl Paragraph { highlights.clear(); offset = 0; } else { - let mut node_highlights = vec![]; + let mut node_highlights = SmallVec::new(); for (range, style) in &inline_node.marks { let inner_range = (offset + range.start)..(offset + range.end); let mut highlight = mark_highlight(style, node_cx, cx); @@ -2461,7 +2463,7 @@ impl Paragraph { node_highlights.push((inner_range, highlight)); } - highlights = combine_highlights(highlights, node_highlights); + append_node_highlights(&mut highlights, node_highlights); offset += text_len; } } @@ -3129,7 +3131,10 @@ impl BlockNode { this.border_r_1().border_color(style.border()) }) .refine_style(&style.table_cell()) - .child(cell.children.render(fade_key, node_cx, window, cx)), + .child( + cell.children + .render(fade_key, Rems::ZERO, node_cx, window, cx), + ), ); } rows.push( @@ -3239,7 +3244,10 @@ impl BlockNode { this.border_r_1().border_color(style.border()) }) .refine_style(&style.table_cell()) - .child(cell.children.render(fade_key, node_cx, window, cx)), + .child( + cell.children + .render(fade_key, Rems::ZERO, node_cx, window, cx), + ), ); } @@ -3309,15 +3317,16 @@ impl BlockNode { node.render_block(NodeRenderOptions { ix, ..options }, node_cx, window, cx) })) .into_any_element(), - BlockNode::Paragraph(paragraph) => gapped( - paragraph.render( - paragraph.span.map(|span| TextLeafKey::block(span.start)), - node_cx, - window, - cx, - ), - mb, - ), + BlockNode::Paragraph(paragraph) => { + // Preserve the wrapper's behavior for non-CSS padding values. + let (gap, wrapper) = if mb.0.is_finite() && mb.0 >= 0.0 { + (mb, Rems::ZERO) + } else { + (Rems::ZERO, mb) + }; + let key = paragraph.span.map(|span| TextLeafKey::block(span.start)); + gapped(paragraph.render(key, gap, node_cx, window, cx), wrapper) + } BlockNode::Heading { level, children, @@ -3343,6 +3352,7 @@ impl BlockNode { .refine_style(&node_cx.style.heading(*level)) .child(children.render( span.map(|span| TextLeafKey::block(span.start)), + Rems::ZERO, node_cx, window, cx, diff --git a/vendor/gpui-base/src/text_selection.rs b/vendor/gpui-base/src/text_selection.rs index a7719ddd..af77aabe 100644 --- a/vendor/gpui-base/src/text_selection.rs +++ b/vendor/gpui-base/src/text_selection.rs @@ -1,8 +1,10 @@ +// Nocterm: avoid duplicate drag projections and updates to unchanged participants. use std::{ collections::HashMap, ops::Range, rc::Rc, sync::atomic::{AtomicU64, Ordering}, + time::Duration, }; use gpui::{ @@ -17,7 +19,7 @@ use crate::text_boundary::{line_range_at, word_range_at}; use crate::touch_selection::{ EdgeDrag, SelectionEdge, TouchHandle, TouchSelectionSnapshot, caret_in_view, }; -use crate::{AutoScroll, GlobalState}; +use crate::{AutoScroll, FrameLoop, GlobalState}; /// An opaque selection layer identifier. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] @@ -1094,6 +1096,29 @@ impl TouchSelection { } } +#[derive(Default)] +struct AncestorScroll { + frames: FrameLoop, + target: Option<(Pixels, Point)>, + geometry: Option<(Bounds, Point)>, + stalled: Duration, +} + +impl AncestorScroll { + fn stop(&mut self) { + *self = Self::default(); + } + + fn update(&mut self, delta: Option, position: Point) { + if let Some(delta) = delta { + self.target = Some((delta, position)); + self.stalled = Duration::ZERO; + } else { + self.stop(); + } + } +} + /// Window-local generic text-selection state. #[derive(Default)] struct WindowSelectionState { @@ -1108,12 +1133,7 @@ struct WindowSelectionState { finish_frame_scheduled: bool, refresh_held_cursor: bool, mouse_down_prepared: bool, - auto_scroll: AutoScroll, - /// Where the anchor's text was when the last synthetic wheel went out, - /// and how many went out without moving it. A container at its end - /// cannot scroll further; pushing it on would only make one that - /// bounces stretch and snap back on every tick. - auto_scroll_stall: (Option<(Bounds, Point)>, u8), + auto_scroll: AncestorScroll, touch: TouchSelection, /// This entity, so that touch changes can notify observers from paths that /// only hold an [`App`]. @@ -1287,7 +1307,6 @@ impl WindowSelectionState { registration: TextSelectionRegistration, cx: &mut App, ) { - self.prune_dead_participants(); if self.is_selecting && registration.self_scroll && self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) @@ -1904,15 +1923,19 @@ impl WindowSelectionState { if !self.is_selecting { return; } - let endpoint = self.endpoint(position, window, cx); - self.did_hit_text |= endpoint.inside_text; - self.cursor = Some(endpoint); + self.move_cursor(position, window, cx); if window.is_none() { self.update_participant_auto_scroll(position, cx); } self.publish_snapshots(cx); } + fn move_cursor(&mut self, position: Point, window: Option<&Window>, cx: &App) { + let endpoint = self.endpoint(position, window, cx); + self.did_hit_text |= endpoint.inside_text; + self.cursor = Some(endpoint); + } + fn endpoint( &mut self, position: Point, @@ -2027,78 +2050,48 @@ impl WindowSelectionState { fn publish_snapshots(&mut self, cx: &mut App) { self.prune_dead_participants(); - let snapshot = self.snapshot(); - let single_participant = self.single_participant(); + let projection = self.snapshot().and_then(|snapshot| { + let ordered = + |id: EntityId| Some((id, self.participants.get(&id)?.registration.document_order)); + Some(( + snapshot, + ordered(snapshot.anchor.entity_id()?)?, + ordered(snapshot.cursor.entity_id()?)?, + )) + }); for (id, registration) in &self.participants { let Some(participant) = registration.participant.upgrade() else { continue; }; - let participant_snapshot = (registration.registration.scope == self.active_scope - && self.participates(*id, registration) - && single_participant.is_none_or(|single| single == *id)) - .then_some(snapshot) - .flatten() - .map(|mut snapshot| { - snapshot.coverage = self.coverage_for(*id); - snapshot + let next = projection.and_then(|(mut snapshot, (anchor, start), (cursor, end))| { + if registration.registration.scope != self.active_scope { + return None; + } + snapshot.coverage = if anchor == cursor && *id == anchor { + TextSelectionCoverage::Bounded + } else if anchor == cursor { + return None; + } else if *id == anchor || *id == cursor { + if (*id == anchor) == (start < end) { + TextSelectionCoverage::ToEnd + } else { + TextSelectionCoverage::FromStart + } + } else if (start.min(end)..=start.max(end)) + .contains(®istration.registration.document_order) + { + TextSelectionCoverage::Full + } else { + return None; + }; + Some(snapshot) }); - participant.update(cx, |state, cx| state.set_snapshot(participant_snapshot, cx)); - } - } - - fn coverage_for(&self, id: EntityId) -> TextSelectionCoverage { - let Some(anchor) = self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) else { - return TextSelectionCoverage::Bounded; - }; - let Some(cursor) = self.cursor.as_ref().and_then(SelectionEndpoint::entity_id) else { - return TextSelectionCoverage::Bounded; - }; - if anchor == cursor { - return TextSelectionCoverage::Bounded; - } - let anchor_order = self.participants[&anchor].registration.document_order; - let cursor_order = self.participants[&cursor].registration.document_order; - if id != anchor && id != cursor { - TextSelectionCoverage::Full - } else if (id == anchor) == (anchor_order < cursor_order) { - TextSelectionCoverage::ToEnd - } else { - TextSelectionCoverage::FromStart + if participant.read(cx).snapshot != next { + participant.update(cx, |state, cx| state.set_snapshot(next, cx)); + } } } - fn single_participant(&self) -> Option { - let anchor = self.anchor.as_ref()?.entity_id()?; - let cursor = self.cursor.as_ref()?.entity_id()?; - (anchor == cursor).then_some(anchor) - } - - fn participates(&self, id: EntityId, registration: &ParticipantRegistration) -> bool { - let Some(anchor) = self.anchor.as_ref().and_then(SelectionEndpoint::entity_id) else { - return false; - }; - let Some(cursor) = self.cursor.as_ref().and_then(SelectionEndpoint::entity_id) else { - return false; - }; - let Some(anchor_registration) = self.participants.get(&anchor) else { - return false; - }; - let Some(cursor_registration) = self.participants.get(&cursor) else { - return false; - }; - let start = anchor_registration - .registration - .document_order - .min(cursor_registration.registration.document_order); - let end = anchor_registration - .registration - .document_order - .max(cursor_registration.registration.document_order); - (start..=end).contains(®istration.registration.document_order) - || id == anchor - || id == cursor - } - fn update_auto_scroll( &mut self, position: Point, @@ -2145,45 +2138,56 @@ impl WindowSelectionState { visible_bounds.bottom() - HIT_TEST_INSET, ), ); - self.auto_scroll.last_drag_position = Some(event_position); - self.auto_scroll_stall = (None, 0); - let window = window.window_handle(); - self.auto_scroll.set(delta, cx, move |delta, state, cx| { - let Some(position) = state.auto_scroll.last_drag_position else { - return; - }; - // Hold off once the container has shown, over a few ticks, that - // it has nowhere left to go; the next move of the finger asks - // again. - const STALLED_TICKS: u8 = 3; - let geometry = state - .anchor_registration() - .map(|(_, registration)| (registration.bounds, registration.scroll_offset)); - let (last, stalled) = &mut state.auto_scroll_stall; - if *last == geometry { - *stalled = stalled.saturating_add(1); - if *stalled >= STALLED_TICKS { - return; - } - } else { - *last = geometry; - *stalled = 0; + self.auto_scroll.update(delta, event_position); + if delta.is_some() { + self.auto_scroll + .frames + .start(window, cx, Self::scroll_ancestor); + } + } + + fn scroll_ancestor( + &mut self, + elapsed: Duration, + window: &mut Window, + cx: &mut Context, + ) -> bool { + let Some((delta, position)) = self.auto_scroll.target else { + return false; + }; + let geometry = self + .anchor_registration() + .map(|(_, registration)| (registration.bounds, registration.scroll_offset)); + if geometry.is_none() || !self.is_selecting { + return false; + } + // Once the ancestor stops moving, stop waking the frame clock. The next + // pointer move can restart it after a resize or after reversing direction. + if self.auto_scroll.geometry == geometry { + self.auto_scroll.stalled += elapsed; + if self.auto_scroll.stalled >= Duration::from_millis(50) { + return false; } - let window = window; - cx.defer(move |cx| { - _ = window.update(cx, |_, window, cx| { - window.dispatch_event( - ScrollWheelEvent { - position, - delta: ScrollDelta::Pixels(point(px(0.), -delta)), - ..Default::default() - } - .to_platform_input(), - cx, - ); - }); + } else { + self.auto_scroll.geometry = geometry; + self.auto_scroll.stalled = Duration::ZERO; + } + let frames = elapsed.as_secs_f32().min(0.032) / 0.016; + let window = window.window_handle(); + cx.defer(move |cx| { + _ = window.update(cx, |_, window, cx| { + window.dispatch_event( + ScrollWheelEvent { + position, + delta: ScrollDelta::Pixels(point(px(0.), -(delta * frames))), + ..Default::default() + } + .to_platform_input(), + cx, + ); }); }); + true } /// Drives the anchor participant's own scrolling, measured against the @@ -2815,19 +2819,22 @@ fn paint_text_selection(state: &Entity, window: &mut Windo let mouse_move_state = state.downgrade(); window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| { - if phase.bubble() - && let Some(state) = mouse_move_state.upgrade() - { - state.update(cx, |state, cx| { - // A handle drag maps the pointer through the handle's offset; - // the raw pointer must not fight it. - if state.touch.drag.is_some() { - return; - } - state.update_in_window(event.position, window, cx) - }); - WindowSelectionState::resolve_content_keys(&state, cx); + if !phase.bubble() || cx.has_active_drag() { + return; + } + let Some(state) = mouse_move_state.upgrade() else { + return; + }; + let selection = state.read(cx); + // Touch handles already apply their own pointer offset. + if !selection.is_selecting || selection.touch.drag.is_some() { + return; } + state.update(cx, |state, cx| { + state.move_cursor(event.position, Some(window), cx); + state.update_auto_scroll(event.position, window, cx); + }); + WindowSelectionState::resolve_content_keys(&state, cx); }); let mouse_up_state = state.downgrade(); @@ -4055,8 +4062,8 @@ mod tests { cx, ); state.update_in_window(point(px(1.), px(50.)), window, cx); - assert!(!state.auto_scroll.is_active()); - assert!(state.auto_scroll.last_drag_position.is_none()); + assert!(!state.auto_scroll.frames.is_active()); + assert!(state.auto_scroll.target.is_none()); }); }) .unwrap(); @@ -4079,7 +4086,7 @@ mod tests { assert!(state.anchor.is_some()); state.update_in_window(point(px(1.), px(50.)), window, cx); - assert!(!state.auto_scroll.is_active()); + assert!(!state.auto_scroll.frames.is_active()); }); }) .unwrap(); diff --git a/vendor/gpui-base/src/time_field.rs b/vendor/gpui-base/src/time_field.rs index f4572d96..284a244d 100644 --- a/vendor/gpui-base/src/time_field.rs +++ b/vendor/gpui-base/src/time_field.rs @@ -1,13 +1,14 @@ +// Modified by Nocterm: use Jiff civil time. use crate::TestSupportExt as _; use std::rc::Rc; -use chrono::{NaiveTime, Timelike as _}; use gpui::{ AnyElement, App, Context, ElementId, Empty, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent, MouseButton, MouseDownEvent, ParentElement, Render, RenderOnce, Role, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _, }; +use jiff::civil::Time; use crate::{ Decrement, Increment, StyledExt as _, @@ -41,7 +42,7 @@ pub enum TimePrecision { } impl TimePrecision { - /// The `chrono` format that displays a time at this precision and cycle. + /// The strftime format that displays a time at this precision and cycle. pub fn format(self, hour_cycle: HourCycle) -> &'static str { match (self, hour_cycle) { (Self::Minute, HourCycle::H23) => "%H:%M", @@ -52,12 +53,12 @@ impl TimePrecision { } /// Drop the components finer than this precision. - pub fn truncate(self, time: NaiveTime) -> NaiveTime { + pub fn truncate(self, time: Time) -> Time { let second = match self { Self::Minute => 0, Self::Second => time.second(), }; - NaiveTime::from_hms_opt(time.hour(), time.minute(), second).unwrap_or(time) + Time::new(time.hour(), time.minute(), second, 0).unwrap_or(time) } } @@ -98,14 +99,14 @@ impl TimeSegment { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TimeFieldEvent { /// Keyboard editing changed the time. - Change(NaiveTime), + Change(Time), } /// The pure editing rules of a [`TimeFieldState`], kept apart from focus so /// they can be tested without a window. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct SegmentEditor { - time: NaiveTime, + time: Time, precision: TimePrecision, hour_cycle: HourCycle, segment: TimeSegment, @@ -116,7 +117,7 @@ struct SegmentEditor { impl SegmentEditor { fn new() -> Self { Self { - time: NaiveTime::MIN, + time: Time::MIN, precision: TimePrecision::default(), hour_cycle: HourCycle::default(), segment: TimeSegment::Hour, @@ -148,12 +149,12 @@ impl SegmentEditor { /// The displayed value of a segment: the hour follows the cycle, and the /// period is `0` for AM and `1` for PM. fn value(&self, segment: TimeSegment) -> u32 { - let hour = self.time.hour(); + let hour = self.time.hour() as u32; match (segment, self.hour_cycle) { (TimeSegment::Hour, HourCycle::H23) => hour, (TimeSegment::Hour, HourCycle::H12) => (hour + 11) % 12 + 1, - (TimeSegment::Minute, _) => self.time.minute(), - (TimeSegment::Second, _) => self.time.second(), + (TimeSegment::Minute, _) => self.time.minute() as u32, + (TimeSegment::Second, _) => self.time.second() as u32, (TimeSegment::Period, _) => hour / 12, } } @@ -166,16 +167,19 @@ impl SegmentEditor { } } - fn with_value(&self, segment: TimeSegment, value: u32) -> NaiveTime { + fn with_value(&self, segment: TimeSegment, value: u32) -> Time { let time = self.time; let pm_offset = time.hour() / 12 * 12; + let Ok(value) = i8::try_from(value) else { + return time; + }; match (segment, self.hour_cycle) { - (TimeSegment::Hour, HourCycle::H23) => time.with_hour(value), + (TimeSegment::Hour, HourCycle::H23) => time.with().hour(value).build(), // 12 AM is midnight and 12 PM is noon. - (TimeSegment::Hour, HourCycle::H12) => time.with_hour(value % 12 + pm_offset), - (TimeSegment::Minute, _) => time.with_minute(value), - (TimeSegment::Second, _) => time.with_second(value), - (TimeSegment::Period, _) => time.with_hour(time.hour() % 12 + value * 12), + (TimeSegment::Hour, HourCycle::H12) => time.with().hour(value % 12 + pm_offset).build(), + (TimeSegment::Minute, _) => time.with().minute(value).build(), + (TimeSegment::Second, _) => time.with().second(value).build(), + (TimeSegment::Period, _) => time.with().hour(time.hour() % 12 + value * 12).build(), } .unwrap_or(time) } @@ -198,7 +202,7 @@ impl SegmentEditor { self.pending_digit = None; } - fn set_time(&mut self, time: NaiveTime) -> bool { + fn set_time(&mut self, time: Time) -> bool { let time = self.precision.truncate(time); if self.time == time { // Keep a half-typed segment when the owner echoes the same value back. @@ -348,12 +352,12 @@ impl TimeFieldState { } } - pub fn time(&self) -> NaiveTime { + pub fn time(&self) -> Time { self.editor.time } /// Replace the time without emitting [`TimeFieldEvent::Change`]. - pub fn set_time(&mut self, time: NaiveTime, _: &mut Window, cx: &mut Context) { + pub fn set_time(&mut self, time: Time, _: &mut Window, cx: &mut Context) { if self.editor.set_time(time) { cx.notify(); } @@ -585,7 +589,7 @@ impl RenderOnce for TimeField { .id(self.id.clone()) .test_support() .role(Role::TimeInput) - .aria_value(SharedString::from(editor.time.format(format).to_string())) + .aria_value(SharedString::from(editor.time.strftime(format).to_string())) .track_focus(&focus_handle.clone().tab_stop(!disabled)) .when(!disabled, |this| { this.key_context(CONTEXT) @@ -635,8 +639,8 @@ impl RenderOnce for TimeField { mod tests { use super::*; - fn hms(h: u32, m: u32, s: u32) -> NaiveTime { - NaiveTime::from_hms_opt(h, m, s).unwrap() + fn hms(h: u32, m: u32, s: u32) -> Time { + Time::new(h as i8, m as i8, s as i8, 0).unwrap() } fn editor(precision: TimePrecision, hour_cycle: HourCycle) -> SegmentEditor { diff --git a/vendor/gpui-base/tests/element_ext.rs b/vendor/gpui-base/tests/element_ext.rs index 7cfb21ad..6404aacd 100644 --- a/vendor/gpui-base/tests/element_ext.rs +++ b/vendor/gpui-base/tests/element_ext.rs @@ -1,8 +1,15 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. use std::{cell::RefCell, rc::Rc}; use gpui::{Context, IntoElement, Render, Styled as _, TestAppContext, Window, div, px}; use gpui_base::ElementExt as _; +mod flow_layout; +mod inline_layout_sweeps; +mod inline_pointer; +mod paragraph_layout; +mod selection_highlight; + struct PrepaintHarness { captured: Rc>>>, } diff --git a/vendor/gpui-base/tests/flow_layout.rs b/vendor/gpui-base/tests/flow_layout.rs new file mode 100644 index 00000000..8ad87684 --- /dev/null +++ b/vendor/gpui-base/tests/flow_layout.rs @@ -0,0 +1,91 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use gpui::{ + AppContext as _, Context, Entity, IntoElement, ParentElement as _, Pixels, Render, Styled as _, + TestAppContext, Window, div, px, +}; +use gpui_base::{TextView, TextViewState}; +use std::time::Instant; + +struct FlowDocument { + width: Pixels, + text: Entity, +} + +impl Render for FlowDocument { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .w(self.width) + .h(px(420.)) + .overflow_hidden() + .child(TextView::new(&self.text)) + } +} + +#[gpui::test] +fn reflow_keeps_hard_breaks_and_text_across_code_spans(cx: &mut TestAppContext) { + cx.update(gpui_base::init); + let source = "Prefix **bold** and `code with words` \nsecond *line* and `你好世界你好世界` \nfinal line"; + let (root, cx) = cx.add_window_view(|_, cx| FlowDocument { + width: px(360.), + text: cx.new(|cx| TextViewState::markdown(source, cx)), + }); + cx.run_until_parked(); + + let mut heights = Vec::new(); + for width in [360., 150., 360.] { + cx.update(|window, cx| { + root.update(cx, |root, cx| { + root.width = px(width); + cx.notify(); + }); + window.draw(cx).clear(cx); + }); + root.read_with(cx, |root, cx| { + let text = root.text.read(cx); + let rendered = text.rendered_text(); + assert_eq!( + rendered.as_str().trim(), + "Prefix bold and code with words\nsecond line and 你好世界你好世界\nfinal line" + ); + heights.push(text.bounds().size.height); + }); + } + assert!(heights[1] > heights[0]); + assert_eq!(heights[0], heights[2]); +} + +#[gpui::test] +#[ignore = "manual profile for one Markdown paragraph with explicit line breaks"] +fn measure_reflow_of_styled_hard_breaks(cx: &mut TestAppContext) { + cx.update(gpui_base::init); + for lines in [32, 256, 1024, 4096] { + let source: String = (0..lines) + .map(|line| format!("Row {line} with **bold** and `styled code` \n")) + .collect(); + let (root, cx) = cx.add_window_view(|_, cx| FlowDocument { + width: px(360.), + text: cx.new(|cx| TextViewState::markdown(&source, cx)), + }); + cx.run_until_parked(); + let text = root.read_with(cx, |root, cx| root.text.read(cx).rendered_text()); + assert!(text.as_str().contains(&format!("Row {}", lines - 1))); + assert!(text.as_str().lines().count() >= lines); + let mut elapsed = Vec::new(); + let mut heights = Vec::new(); + for width in [340., 440., 320., 460., 300., 400., 280., 420., 260.] { + let time = cx.update(|window, cx| { + root.update(cx, |root, cx| { + root.width = px(width); + cx.notify(); + }); + let start = Instant::now(); + window.draw(cx).clear(cx); + start.elapsed().as_micros() + }); + elapsed.push(time); + heights.push(root.read_with(cx, |root, cx| root.text.read(cx).bounds().size.height)); + } + println!("{lines} hard lines: draw_us {elapsed:?}; height {heights:?}"); + } +} diff --git a/vendor/gpui-base/tests/inline_layout_sweeps.rs b/vendor/gpui-base/tests/inline_layout_sweeps.rs new file mode 100644 index 00000000..8d8b9d4c --- /dev/null +++ b/vendor/gpui-base/tests/inline_layout_sweeps.rs @@ -0,0 +1,297 @@ +// SPDX-License-Identifier: Apache-2.0 + +use gpui::{ + AppContext, AvailableSpace, Bounds, Context, Element, Entity, IntoElement, Modifiers, + ParentElement, Render, Styled, StyledText, TestAppContext, TextOverflow, TextStyleRefinement, + WhiteSpace, Window, canvas, div, hsla, point, px, rems, size, +}; +use gpui_base::text::{RangeHighlight, TextView, TextViewState, TextViewStyle}; +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; +use std::time::Instant; + +struct Document { + state: Entity, +} + +impl Render for Document { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .w(px(520.)) + .h(px(640.)) + .overflow_hidden() + .child(TextView::new(&self.state).selectable(true)) + } +} + +fn source(paragraphs: usize) -> String { + (0..paragraphs) + .map(|row| format!("Row **{row}** with *styled inline content* and `code`.\n\n")) + .collect() +} + +#[gpui::test] +fn clipped_document_keeps_its_highlight_and_selection_after_replacement(cx: &mut TestAppContext) { + const PARAGRAPHS: usize = 1_500; + let dense = source(PARAGRAPHS); + cx.update(gpui_base::init); + let (view, cx) = cx.add_window_view(|_, cx| Document { + state: cx.new(|cx| TextViewState::markdown(&dense, cx)), + }); + cx.run_until_parked(); + let state = view.read_with(cx, |view, _| view.state.clone()); + let color = hsla(0.23, 1., 0.5, 1.); + for (index, rows) in [PARAGRAPHS, 2, PARAGRAPHS].into_iter().enumerate() { + if index > 0 { + state.update(cx, |state, cx| state.set_text(&source(rows), cx)); + cx.run_until_parked(); + } + state.update(cx, |state, cx| { + let rendered = state.rendered_text(); + let expected = format!("Row {} with styled inline content and code.", rows - 1); + assert!(rendered.as_str().contains(&expected)); + state + .set_range_highlights([RangeHighlight::new(0..3, color)], cx) + .unwrap(); + }); + for _ in 0..2 { + cx.update(|window, cx| { + window.refresh(); + window.draw(cx).clear(cx); + assert!( + window + .painted_quads() + .iter() + .any(|quad| quad.background == color.into()), + "visible first-word highlight must survive the handoff" + ); + }); + } + state.update(cx, |state, cx| { + state.select_all(cx); + assert_eq!(state.selected_text(), state.rendered_text().as_str()); + }); + } +} + +struct ParagraphSpacing { + state: Entity, + gap: gpui::Rems, + clicks: Arc, +} + +impl Render for ParagraphSpacing { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let clicks = self.clicks.clone(); + div().w(px(250.)).child( + TextView::new(&self.state) + .style(TextViewStyle::default().with_paragraph_gap(self.gap)) + .on_link_click(move |url, _, _, _| { + assert_eq!(url.as_str(), "https://example.org/target"); + clicks.fetch_add(1, Ordering::Relaxed); + }), + ) + } +} + +#[gpui::test] +fn paragraph_spacing_moves_following_text_without_extending_link_hitboxes(cx: &mut TestAppContext) { + let source = "[first](https://example.org/target)\n\nsecond `code`\n\nthird"; + let colors = [ + hsla(0.08, 1., 0.5, 1.), + hsla(0.17, 1., 0.5, 1.), + hsla(0.27, 1., 0.5, 1.), + ]; + let clicks = Arc::new(AtomicUsize::new(0)); + cx.update(gpui_base::init); + let (view, cx) = cx.add_window_view(|_, cx| ParagraphSpacing { + state: cx.new(|cx| TextViewState::markdown(source, cx)), + gap: rems(0.), + clicks: clicks.clone(), + }); + cx.run_until_parked(); + let state = view.read_with(cx, |view, _| view.state.clone()); + state.update(cx, |state, cx| { + let text = state.rendered_text(); + state + .set_range_highlights( + ["first", "second", "third"] + .into_iter() + .zip(colors) + .map(|(word, color)| { + let start = text.as_str().find(word).unwrap(); + RangeHighlight::new(start..start + word.len(), color) + }), + cx, + ) + .unwrap(); + }); + + let visible_rows = |window: &mut Window, cx: &mut gpui::App| { + window.refresh(); + window.draw(cx).clear(cx); + colors.map(|color| { + window + .painted_quads() + .iter() + .find(|quad| quad.background == color.into()) + .unwrap() + .bounds + .map(|coord| px(coord.0 / window.scale_factor())) + }) + }; + for scale in [1., 1.25, 1.5, 2.] { + cx.simulate_scale_factor_change(scale); + view.update(cx, |view, cx| { + view.gap = rems(0.); + cx.notify(); + }); + let before = cx.update(visible_rows); + view.update(cx, |view, cx| { + view.gap = rems(1.375); + cx.notify(); + }); + let (after, gap) = cx.update(|window, cx| { + ( + visible_rows(window, cx), + window.pixel_snap(view.read(cx).gap.to_pixels(window.rem_size())), + ) + }); + let tolerance = px(0.001); + assert_eq!(before[0], after[0]); + for (index, (before, after)) in before.into_iter().zip(after).enumerate().skip(1) { + assert_eq!(before.size, after.size); + assert_eq!(before.left(), after.left()); + assert!( + (after.top() - before.top() - gap * index as f32).abs() < tolerance, + "row {index} at scale {scale}" + ); + } + let count = clicks.load(Ordering::Relaxed); + cx.simulate_click( + point( + after[0].center().x, + (after[0].bottom() + after[1].top()) / 2., + ), + Modifiers::none(), + ); + assert_eq!(clicks.load(Ordering::Relaxed), count); + cx.simulate_click(after[0].center(), Modifiers::none()); + assert_eq!(clicks.load(Ordering::Relaxed), count + 1); + } +} + +#[gpui::test] +fn positioned_text_matches_standard_text_layout_at_fractional_scale(cx: &mut TestAppContext) { + let cx = cx.add_empty_window(); + let origin = point(px(14.25), px(9.6)); + let offered = size(px(96.37), px(43.8)); + for scale in [1., 1.25, 1.5, 2.] { + cx.simulate_scale_factor_change(scale); + cx.draw(origin, offered.map(AvailableSpace::Definite), |_, _| { + canvas( + move |bounds, window, cx| { + for truncate in [false, true] { + let style = TextStyleRefinement { + white_space: Some(if truncate { + WhiteSpace::Nowrap + } else { + WhiteSpace::Normal + }), + text_overflow: truncate.then(|| TextOverflow::Truncate("…".into())), + ..Default::default() + }; + window.with_text_style(Some(style), |window| { + let text = "office Λάμδα عَرَبِيّ and a later word"; + let standard = StyledText::new(text); + let expected = standard.layout().clone(); + standard.into_any_element().prepaint_as_root( + bounds.origin, + offered.map(AvailableSpace::Definite), + window, + cx, + ); + + let mut positioned = StyledText::new(text); + let measured = positioned.measure_as_block(offered, window, cx); + positioned.prepaint( + None, + None, + Bounds::new(bounds.origin, measured), + &mut (), + window, + cx, + ); + let actual = positioned.layout(); + assert_eq!(actual.bounds(), expected.bounds()); + assert_eq!(actual.line_height(), expected.line_height()); + for (index, _) in text.char_indices() { + let position = expected.position_for_index(index); + assert_eq!(actual.position_for_index(index), position); + if let Some(position) = position { + assert_eq!( + actual.index_for_position(position), + expected.index_for_position(position), + ); + } + } + }); + } + }, + |_, (), _, _| {}, + ) + }); + } +} + +#[gpui::test] +#[ignore = "manual dense Markdown redraw workload"] +fn measure_inline_layout_redraw(cx: &mut TestAppContext) { + let paragraphs = std::env::var("NOCTERM_MARKDOWN_PROBE_ROWS") + .map(|rows| rows.parse().expect("paragraph count")) + .unwrap_or(4_096); + let plain = std::env::var("NOCTERM_MARKDOWN_PROBE_FORMAT").as_deref() == Ok("plain"); + let text = if plain { + (0..paragraphs) + .map(|row| format!("Row {row} has a line of ordinary selectable text.\n\n")) + .collect() + } else { + source(paragraphs) + }; + cx.update(gpui_base::init); + let start = Instant::now(); + let (view, cx) = cx.add_window_view(|_, cx| Document { + state: cx.new(|cx| TextViewState::markdown(&text, cx)), + }); + cx.run_until_parked(); + let initial = start.elapsed(); + let visible = view.read_with(cx, |view, cx| view.state.read(cx).rendered_text()); + assert!( + visible + .as_str() + .contains(&format!("Row {}", paragraphs - 1)) + ); + let samples = std::env::var("NOCTERM_MARKDOWN_PROBE_REDRAWS") + .map(|count| count.parse().expect("redraw count")) + .unwrap_or(11); + assert!(samples > 0); + let mut redraw = vec![0; samples]; + for sample in &mut redraw { + let start = Instant::now(); + cx.update(|window, cx| { + window.refresh(); + window.draw(cx).clear(cx); + }); + *sample = start.elapsed().as_micros(); + } + redraw.sort_unstable(); + println!( + "{paragraphs} paragraphs initial_us={} redraw_count={samples} redraw_min_us={} redraw_median_us={} redraw_max_us={}", + initial.as_micros(), + redraw[0], + redraw[samples / 2], + redraw[samples - 1] + ); +} diff --git a/vendor/gpui-base/tests/inline_pointer.rs b/vendor/gpui-base/tests/inline_pointer.rs new file mode 100644 index 00000000..ea050d6a --- /dev/null +++ b/vendor/gpui-base/tests/inline_pointer.rs @@ -0,0 +1,119 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use gpui::{ + AppContext as _, Context, Entity, InputEvent as _, InteractiveElement as _, IntoElement, + Modifiers, MouseMoveEvent, ParentElement as _, Render, ScrollHandle, + StatefulInteractiveElement as _, Styled as _, TestAppContext, Window, div, point, px, +}; +use gpui_base::{TextSelectionLayer, TextView, TextViewState}; +use std::time::Instant; + +struct ScrollingLink { + scroll: ScrollHandle, + text: Entity, +} + +impl Render for ScrollingLink { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .id("scrolling-link") + .w(px(240.)) + .h(px(32.)) + .overflow_y_scroll() + .track_scroll(&self.scroll) + .child(div().h(px(100.))) + .child(TextView::new(&self.text)) + .child(div().h(px(100.))) + } +} + +#[gpui::test] +fn a_clipped_link_opens_once_scrolled_into_view(cx: &mut TestAppContext) { + check_scrolled_link(cx, "[open](https://example.com)", 100., 10.); +} + +#[gpui::test] +fn a_partially_clipped_link_in_positioned_text_still_opens(cx: &mut TestAppContext) { + check_scrolled_link(cx, "[open](https://example.com) next to `code`", 110., 4.); +} + +fn check_scrolled_link(cx: &mut TestAppContext, markdown: &str, offset: f32, click_y: f32) { + cx.update(gpui_base::init); + let scroll = ScrollHandle::new(); + let (_, cx) = cx.add_window_view(|_, cx| ScrollingLink { + scroll: scroll.clone(), + text: cx.new(|cx| TextViewState::markdown(markdown, cx)), + }); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + cx.simulate_click(point(px(10.), px(110.)), Modifiers::default()); + assert_eq!(cx.opened_url(), None); + + scroll.set_offset(point(px(0.), px(-offset))); + cx.update(|window, cx| { + window.refresh(); + window.draw(cx).clear(cx); + }); + cx.simulate_click(point(px(10.), px(click_y)), Modifiers::default()); + assert_eq!(cx.opened_url().as_deref(), Some("https://example.com")); +} + +struct ClippedTranscript(Entity); + +impl Render for ClippedTranscript { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().child(TextSelectionLayer).child( + div() + .w(px(470.)) + .h(px(420.)) + .overflow_hidden() + .child(TextView::new(&self.0).selectable(true)), + ) + } +} + +#[gpui::test] +#[ignore = "manual pointer benchmark for long, clipped Markdown"] +fn measure_pointer_dispatch_in_clipped_transcript(cx: &mut TestAppContext) { + cx.update(gpui_base::init); + let plain = "contains ordinary selectable text."; + let mixed = "contains **bold**, *italic* and `code` text."; + for (rows, body) in [(8, plain), (4_096, plain), (4_096, mixed)] { + let source: String = (0..rows) + .map(|row| format!("Row {row} {body}\n\n")) + .collect(); + let (view, cx) = cx.add_window_view(|_, cx| { + ClippedTranscript(cx.new(|cx| TextViewState::markdown(&source, cx))) + }); + cx.run_until_parked(); + assert!( + view.read_with(cx, |view, cx| view.0.read(cx).rendered_text()) + .as_str() + .contains(&format!("Row {}", rows - 1)) + ); + + let mut samples = [0; 11]; + for elapsed in &mut samples { + *elapsed = cx.update(|window, cx| { + window.refresh(); + window.draw(cx).clear(cx); + + let start = Instant::now(); + for dy in (0..32_i16).cycle().take(256) { + window.dispatch_event( + MouseMoveEvent { + position: point(px(62.), px(5. + f32::from(dy))), + ..Default::default() + } + .to_platform_input(), + cx, + ); + } + start.elapsed().as_micros() + }); + } + samples.sort_unstable(); + println!("{rows} paragraphs ({body}), 256 mouse moves: {samples:?} µs"); + } +} diff --git a/vendor/gpui-base/tests/paragraph_layout.rs b/vendor/gpui-base/tests/paragraph_layout.rs new file mode 100644 index 00000000..9871626c --- /dev/null +++ b/vendor/gpui-base/tests/paragraph_layout.rs @@ -0,0 +1,161 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use gpui::{ + AppContext as _, Context, Entity, IntoElement, Modifiers, MouseButton, ParentElement as _, + Pixels, Render, Styled as _, TestAppContext, Window, div, hsla, point, px, rems, size, +}; +use gpui_base::{ + TextSelectionLayer, TextView, TextViewState, TextViewStyle, + text::{RangeHighlight, SelectionFormat}, +}; + +struct Transcript { + text: Entity, + width: Option, +} + +impl Render for Transcript { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let text = TextView::new(&self.text) + .selectable(true) + .selection_format(SelectionFormat::Source) + .style(TextViewStyle::default().with_paragraph_gap(rems(0.125))); + let content = match self.width { + Some(width) => div().w(width).child(text), + None => div().flex().items_start().child(text.flex_none()), + }; + div() + .text_size(px(9.25)) + .line_height(px(12.375)) + .child(TextSelectionLayer) + .child(content) + } +} + +#[gpui::test] +fn long_markdown_preserves_wrapped_lines_and_drag_selection(cx: &mut TestAppContext) { + check_geometry_and_drag(cx, "with words."); +} + +#[gpui::test] +fn long_markdown_with_inline_code_preserves_wrapped_lines_and_drag_selection( + cx: &mut TestAppContext, +) { + check_geometry_and_drag(cx, "**with** `code words`"); +} + +fn check_geometry_and_drag(cx: &mut TestAppContext, ending: &str) { + cx.update(gpui_base::init); + let rows: Vec<_> = (0..257) + .map(|row| format!("Paragraph {row:03} {ending}")) + .collect(); + let source = rows.join("\n\n"); + let across_boundary = rows[31..33].join("\n\n"); + + for width in [Some(px(94.5)), Some(px(202.25)), None] { + let (view, cx) = cx.add_window_view(|_, cx| Transcript { + text: cx.new(|cx| TextViewState::markdown("", cx)), + width, + }); + cx.simulate_resize(size(px(450.), px(1200.))); + cx.simulate_scale_factor_change(1.25); + let text = view.read_with(cx, |view, _| view.text.clone()); + let colors = [hsla(0.17, 1., 0.5, 1.), hsla(0.53, 1., 0.5, 1.)]; + let mut paint = |source: &str| { + text.update(cx, |text, cx| text.set_text(source, cx)); + cx.run_until_parked(); + text.update(cx, |text, cx| { + let rendered = text.rendered_text(); + text.set_range_highlights( + rows[31..33].iter().zip(colors).map(|(row, color)| { + let visible = row.replace(['*', '`'], ""); + let start = rendered.as_str().find(&visible).unwrap(); + RangeHighlight::new(start..start + visible.len(), color) + }), + cx, + ) + .unwrap(); + }); + cx.update(|window, cx| { + window.draw(cx).clear(cx); + let quads = window.painted_quads(); + colors.map(|color| { + let mut lines: Vec<_> = quads + .iter() + .filter(|quad| quad.background == color.into()) + .map(|quad| quad.bounds.map(|value| px(value.0 / window.scale_factor()))) + .collect(); + lines.sort_by_key(|line| line.top()); + assert!(!lines.is_empty(), "missing highlight at width {width:?}"); + lines + }) + }) + }; + let flat = paint(&rows[..35].join("\n\n")); + let grouped = paint(&source); + assert_eq!(grouped, flat, "width {width:?}"); + + let first = grouped[0].first().unwrap(); + let last = grouped[1].last().unwrap(); + let start = point(first.left() + px(0.2), first.center().y); + let end = point(last.right() + px(0.5), last.center().y); + cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default()); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.simulate_mouse_move(end, Some(MouseButton::Left), Modifiers::default()); + cx.update(|window, cx| window.draw(cx).clear(cx)); + cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default()); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + let selected = text.read_with(cx, |text, _| text.selected_text()); + assert_eq!( + selected, across_boundary, + "width {width:?}, drag {start:?} to {end:?}" + ); + } +} + +#[gpui::test] +#[ignore = "manual timing for a warm frame of a long Markdown reply with inline code"] +fn measure_warm_redraw_with_inline_code(cx: &mut TestAppContext) { + use std::{io::Write as _, time::Instant}; + + cx.update(gpui_base::init); + for paragraphs in [32, 512, 4096] { + let source: String = (0..paragraphs) + .map(|row| format!("Paragraph {row} has **emphasis** and `inline code`.\n\n")) + .collect(); + let (view, cx) = cx.add_window_view(|_, cx| Transcript { + text: cx.new(|cx| TextViewState::markdown(&source, cx)), + width: Some(px(250.)), + }); + cx.simulate_resize(size(px(400.), px(600.))); + cx.run_until_parked(); + let text = view.read_with(cx, |view, _| view.text.clone()); + let final_row = format!("Paragraph {}", paragraphs - 1); + let expected_height = text.read_with(cx, |text, _| { + assert!(text.rendered_text().as_str().contains(&final_row)); + text.bounds().size.height + }); + let mut draws = [0; 11]; + for elapsed in &mut draws { + *elapsed = cx.update(|window, cx| { + let start = Instant::now(); + window.refresh(); + window.draw(cx).clear(cx); + start.elapsed().as_micros() + }); + assert_eq!( + text.read_with(cx, |text, _| text.bounds().size.height), + expected_height + ); + } + draws.sort_unstable(); + writeln!( + std::io::stdout().lock(), + "{paragraphs} paragraphs, warm draw median/max µs: {}/{}", + draws[draws.len() / 2], + draws[draws.len() - 1], + ) + .unwrap(); + } +} diff --git a/vendor/gpui-base/tests/selection_highlight.rs b/vendor/gpui-base/tests/selection_highlight.rs new file mode 100644 index 00000000..b3a3386a --- /dev/null +++ b/vendor/gpui-base/tests/selection_highlight.rs @@ -0,0 +1,148 @@ +// Nocterm modifications, licensed under the upstream Apache-2.0 license. + +use gpui::{ + AppContext, Context, Entity, IntoElement, KeyDownEvent, Keystroke, Modifiers, ParentElement, + Render, Styled, TestAppContext, Window, div, px, +}; +use gpui_base::{ + Theme, + input::{Input, InputEditorStyle, InputState, Textarea, TextareaState}, +}; +use std::{cell::Cell, rc::Rc}; + +struct SelectionField { + state: Entity, +} + +struct MultilineSelectionField { + state: Entity, +} + +impl Render for MultilineSelectionField { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + Textarea::new(&self.state) + } +} + +#[gpui::test] +fn multiline_selection_refreshes_for_changes_to_alt(cx: &mut TestAppContext) { + cx.update(gpui_base::init); + let (view, cx) = cx.add_window_view(|window, cx| MultilineSelectionField { + state: cx.new(|cx| TextareaState::new(window, cx).default_value("first\nsecond")), + }); + let state = view.read_with(cx, |view, _| view.state.clone()); + cx.update(|window, cx| { + window.activate_window(); + state.update(cx, |state, cx| state.focus(window, cx)); + window.draw(cx).clear(cx); + }); + cx.run_until_parked(); + let notifications = Rc::new(Cell::new(0)); + let _subscription = cx.update(|_, cx| { + let notifications = notifications.clone(); + cx.observe(&state, move |_, _| { + notifications.set(notifications.get() + 1) + }) + }); + + let control = Modifiers { + control: true, + ..Modifiers::none() + }; + cx.simulate_modifiers_change(control); + assert_eq!(notifications.get(), 0, "Ctrl press"); + cx.simulate_event(KeyDownEvent { + keystroke: Keystroke::parse("ctrl-f13").unwrap(), + is_held: false, + prefer_character_input: false, + }); + let before_release = notifications.get(); + cx.simulate_modifiers_change(Modifiers::none()); + assert_eq!(notifications.get(), before_release, "Ctrl release"); + + let alt = Modifiers { + alt: true, + ..Modifiers::none() + }; + cx.simulate_modifiers_change(alt); + assert_eq!(notifications.get(), before_release + 1); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let while_alt_held = notifications.get(); + cx.simulate_modifiers_change(Modifiers { + control: true, + ..alt + }); + assert_eq!(notifications.get(), while_alt_held); + cx.simulate_modifiers_change(Modifiers::none()); + assert_eq!(notifications.get(), while_alt_held + 1); +} + +impl Render for SelectionField { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .w(px(120.)) + .overflow_hidden() + .child(Input::new(&self.state)) + } +} + +#[gpui::test] +fn selected_text_paints_a_clipped_rectangle_and_clears_after_replacement(cx: &mut TestAppContext) { + cx.update(gpui_base::init); + for (value, masked, scale) in [ + ("Büro Ως", false, 1.), + ("שלום مرحبا", false, 1.5), + ("masked 🔑 password", true, 2.), + ( + "Long field value crossing the end of a narrow input field", + false, + 1.5, + ), + ] { + let (view, cx) = cx.add_window_view(move |window, cx| SelectionField { + state: cx.new(|cx| { + InputState::new(window, cx) + .default_value(value) + .masked(masked) + }), + }); + cx.simulate_scale_factor_change(scale); + let state = view.read_with(cx, |view, _| view.state.clone()); + cx.update(|window, cx| { + window.activate_window(); + state.update(cx, |state, cx| { + state.focus(window, cx); + state.select_all(window, cx); + }); + assert_eq!(state.read(cx).selected_range(), 0..value.len()); + }); + cx.run_until_parked(); + + cx.update(|window, cx| { + window.draw(cx).clear(cx); + let color = InputEditorStyle::default() + .resolved(&Theme::global(cx).tokens) + .selection; + let highlights: Vec<_> = window + .painted_quads() + .into_iter() + .filter(|quad| quad.background == color.into()) + .collect(); + assert_eq!(highlights.len(), 1, "{value}"); + let highlight = highlights[0]; + let visible = highlight.bounds.intersect(&highlight.content_mask.bounds); + assert!(!visible.is_empty(), "{value}"); + assert!(f64::from(visible.right()) <= 120. * f64::from(scale)); + + state.update(cx, |state, cx| state.replace_all("replacement", window, cx)); + window.draw(cx).clear(cx); + assert_eq!(state.read(cx).value().as_str(), "replacement"); + assert!( + window + .painted_quads() + .iter() + .all(|quad| quad.background != color.into()) + ); + }); + } +} diff --git a/vendor/gpui-component/Cargo.lock b/vendor/gpui-component/Cargo.lock index 03bd79d9..aa6001b8 100644 --- a/vendor/gpui-component/Cargo.lock +++ b/vendor/gpui-component/Cargo.lock @@ -67,15 +67,6 @@ dependencies = [ "equator", ] -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - [[package]] name = "annotate-snippets" version = "0.12.16" @@ -649,20 +640,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link 0.2.1", -] - [[package]] name = "clang-sys" version = "1.9.1" @@ -1051,7 +1028,7 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users 0.5.2", + "redox_users 0.5.3", "windows-sys 0.61.2", ] @@ -1713,14 +1690,11 @@ dependencies = [ [[package]] name = "gpui-base" version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64bb52b29a8dcdc8d3f595b8b0839c076f237572ab601ba4577d3da8ae085728" dependencies = [ "aho-corasick", "anyhow", "ashpd", "async-channel", - "chrono", "data-url", "futures", "gpui-pre", @@ -1729,6 +1703,7 @@ dependencies = [ "html5ever", "instant", "itertools 0.13.0", + "jiff", "lsp-types", "markdown", "markup5ever_rcdom", @@ -1756,7 +1731,6 @@ name = "gpui-component" version = "0.7.0" dependencies = [ "anyhow", - "chrono", "core-text", "enum-iterator", "gpui-base", @@ -1768,6 +1742,7 @@ dependencies = [ "indoc", "instant", "itertools 0.13.0", + "jiff", "log", "lsp-types", "markdown", @@ -1859,8 +1834,6 @@ dependencies = [ [[package]] name = "gpui-pre" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e87a42bb37c7cb4e76dd1ac0ce88851e46e976e0373a47ab3e0757abffee54d" dependencies = [ "accesskit", "anyhow", @@ -1869,7 +1842,6 @@ dependencies = [ "backtrace", "bindgen", "bitflags 2.13.1", - "chrono", "core-video", "ctor", "derive_more", @@ -1891,6 +1863,7 @@ dependencies = [ "image", "inventory", "itertools 0.14.0", + "jiff", "log", "lyon", "num_cpus", @@ -2057,14 +2030,12 @@ dependencies = [ [[package]] name = "gpui-pre-scheduler" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8049963b716df01b67b58f86000597f222d5b31b15b35069b23a3b07f3c68352" dependencies = [ "async-task", "backtrace", - "chrono", "flume", "futures", + "jiff", "parking_lot", "rand 0.9.5", "web-time", @@ -2119,12 +2090,10 @@ dependencies = [ [[package]] name = "gpui-pre-zlog" version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7506302091e66d7fb5e04a5b3480e90cff0bbe3157458d7df91a41c59238c48" dependencies = [ "anyhow", - "chrono", "gpui-pre-collections", + "jiff", "log", ] @@ -2348,30 +2317,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core 0.62.2", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" version = "2.3.0" @@ -2667,6 +2612,60 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "js-sys", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "wasm-bindgen", + "windows-link 0.2.1", +] + +[[package]] +name = "jiff-core" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "jiff-tzdb" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" + +[[package]] +name = "jiff-tzdb-platform" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jobserver" version = "0.1.35" @@ -2679,13 +2678,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", - "once_cell", "wasm-bindgen", ] @@ -2799,9 +2797,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.23" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d8f1ea3f21fd3405dcaf6c9b5c1630af9afc422d9073ea39c5f6d6c772e08ed" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ "libc", ] @@ -3707,6 +3705,21 @@ dependencies = [ "arrayvec", ] +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "postage" version = "0.5.0" @@ -4170,11 +4183,10 @@ dependencies = [ [[package]] name = "redox_users" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" dependencies = [ - "getrandom 0.2.17", "libredox", "thiserror 2.0.20", ] @@ -6306,12 +6318,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "serde", "wasm-bindgen-macro", @@ -6320,19 +6331,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.71" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -6340,22 +6352,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.4", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] @@ -6375,9 +6387,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -7426,3 +7438,15 @@ dependencies = [ "syn 3.0.4", "winnow 1.0.4", ] + +[[patch.unused]] +name = "gpui-pre-linux" +version = "0.3.7" + +[[patch.unused]] +name = "gpui-pre-wgpu" +version = "0.3.7" + +[[patch.unused]] +name = "gpui-pre-windows" +version = "0.3.7" diff --git a/vendor/gpui-component/Cargo.toml b/vendor/gpui-component/Cargo.toml index d1f3e727..8415ba08 100644 --- a/vendor/gpui-component/Cargo.toml +++ b/vendor/gpui-component/Cargo.toml @@ -269,8 +269,9 @@ path = "tests/theme_compat.rs" [dependencies.anyhow] version = "1" -[dependencies.chrono] -version = "0.4.38" +[dependencies.jiff] +version = "1.1" +features = ["js"] [dependencies.enum-iterator] version = "2.1.0" @@ -584,3 +585,12 @@ useless_conversion = "allow" [lints.clippy.style] level = "allow" priority = -1 + +[patch.crates-io] +gpui-base = { path = "../gpui-base" } +gpui-pre = { path = "../gpui-pre" } +gpui-pre-linux = { path = "../gpui-pre-linux" } +gpui-pre-scheduler = { path = "../gpui-pre-scheduler" } +gpui-pre-wgpu = { path = "../gpui-pre-wgpu" } +gpui-pre-windows = { path = "../gpui-pre-windows" } +gpui-pre-zlog = { path = "../gpui-pre-zlog" } diff --git a/vendor/gpui-component/NOCTERM.md b/vendor/gpui-component/NOCTERM.md index b572d429..b1c63060 100644 --- a/vendor/gpui-component/NOCTERM.md +++ b/vendor/gpui-component/NOCTERM.md @@ -11,6 +11,44 @@ commit `0c830f4d257e69fdd17200650533ab4ca9a40cc0`, path `crates/component`. The upstream source, copyright notices and Apache-2.0 license are retained. This is an internal Cargo patch; the crate is excluded from Nocterm's workspace. +`src/command` folds each search query once. When editing it keeps the same +built-in rows, the component reuses their measured heights. Custom rows +still measure their children, and changes to layout inputs or the installed +model still invalidate measurement. + +Hosts with fixed choices can install a `Command` before mounting its +`CommandState`. The dialog then renders the state directly for its lifetime. +Dynamic command builders continue to install their model through rendering. + +List search applies already-completed delegate queries without scheduling a +loading animation or a completion timer. Pending delegates keep their loading +indicator while running. Issuing another query cancels the current task, including +when the user returns to a previously completed query. The List element wrapper +and its tests live in separate modules from the list state. + +Shared plain-choice pickers can use viewport measurement for large result +sets. Offscreen row heights are estimated until the rows are laid out. +Small results still measure intrinsic height, and the unrestricted command +palette constructor keeps the exact layout path. The shared interaction +state continues to own filtering, keyboard navigation and the selected +index. Remove this option when upstream can bound initial row layout +without changing short-list sizing. + +`src/dock/tab_panel.rs` shares the current bar's interaction snapshot with all +tab handlers. Each click, close and drop callback retains the same snapshot, +keeping a full copy of the panel list out of each individual callback. + +`src/tooltip.rs` skips the slide transition when the previous and current +triggers share the same horizontal center. Hover delay and fades still use +the toolkit's existing transitions. + +`src/shimmer.rs` limits redraw requests for a repeating text shimmer to 60 per +second. The sweep follows the existing synchronized clock and one-shot timing +is unchanged. + +`src/spinner.rs` applies the same redraw limit to decorative loading spinners. +The rotation still follows the configured duration and easing. + `src/menu/app_menu_bar.rs` changes menu behavior. `AppMenuBar::set_menus` updates a closed menu bar's snapshot in place, retaining existing menu entities, button identities and keyboard focus. `is_open` lets the window preserve an open @@ -98,7 +136,36 @@ built-in jump-to-latest control keep their existing ownership. Remove this forwarder when upstream exposes an equivalent query. +`src/command/command.rs` exposes lazy row measurement for ungrouped command +palettes. Nocterm's workspace palette uses the same viewport measurement as +plain choice lists, including exact sizing for short search results. Remove +this constructor when upstream exposes equivalent sizing. + `Cargo.toml` lists `log` under `[package.metadata.cargo-machete] ignored`. Nocterm runs cargo-machete over the whole repository; the upstream dependency is kept unchanged so the manifest does not drift from upstream. Remove the entry when upstream drops or uses the dependency. + +Tab panels collect the visible logical tab indices once per strip and pass +the resulting tabs directly to the tab bar. Tab bars build overflow menu +metadata only when their menu is enabled. The content corner policy stops +counting once it knows whether the title is visible. + +Tabs resolve their variant colors from one borrowed theme and build semantic +style refinements only for the selected or disabled states they apply. The +variant geometry and color rules live in one module shared with the tab bar. + +Switch thumb travel keeps the theme's spring and full display cadence while +moving. Its settling criterion also allows a scale-aware half-physical-pixel +remaining displacement envelope, stopping otherwise unnecessary redraws of the +host. The final thumb position, early reversal momentum and reduced-motion +behavior are unchanged. Remove this patch when upstream uses equivalent +physical-pixel settling. + +Styled buttons resolve their variant colors from one borrowed theme and build +selected and disabled refinements only when those controlled states apply. +An interactive button also reuses its hover colors for group highlighting. +The variant and visual policy live together in `button/button/variant.rs`; +existing tests moved to `button/button/tests.rs`. The Base control still owns +semantic precedence, focus, interaction and accessibility. Remove this patch +when upstream prepares only the applied visual states. diff --git a/vendor/gpui-component/src/button/button.rs b/vendor/gpui-component/src/button/button.rs index 67e45779..753362e5 100644 --- a/vendor/gpui-component/src/button/button.rs +++ b/vendor/gpui-component/src/button/button.rs @@ -1,20 +1,20 @@ // Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. -use std::rc::Rc; use crate::ThemeStyled as _; use crate::{ - ActiveTheme, Colorize as _, Disableable, Icon, Placement, RoleOverride, Selectable, Sizable, - Size, StyleSized, StyledExt, + ActiveTheme, Disableable, Icon, Placement, RoleOverride, Selectable, Sizable, Size, StyleSized, + StyledExt, button::ButtonIcon, h_flex, select::Caret, tooltip::{ManagedTooltipExt as _, Tooltip}, }; use gpui::{ - AnyElement, App, Background, ClickEvent, Corners, Edges, ElementId, Hsla, InteractiveElement, - Interactivity, IntoElement, MouseButton, ParentElement, Pixels, RenderOnce, Role, SharedString, + AnyElement, App, ClickEvent, Corners, Edges, ElementId, InteractiveElement, Interactivity, + IntoElement, MouseButton, ParentElement, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div, - prelude::FluentBuilder as _, relative, transparent_white, + prelude::FluentBuilder as _, relative, }; +use std::rc::Rc; /// Product-wide button metrics. Installing this optional global changes only /// the size of standard buttons; variants and theme colours remain native. @@ -63,155 +63,6 @@ impl From for ButtonRounded { } } -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub struct ButtonCustomVariant { - color: Hsla, - foreground: Hsla, - shadow: bool, - hover: Hsla, - active: Hsla, -} - -pub trait ButtonVariants: Sized { - fn with_variant(self, variant: ButtonVariant) -> Self; - - /// With the primary style for the Button. - fn primary(self) -> Self { - self.with_variant(ButtonVariant::Primary) - } - - /// With the secondary style for the Button. - fn secondary(self) -> Self { - self.with_variant(ButtonVariant::Secondary) - } - - /// With the danger style for the Button. - fn danger(self) -> Self { - self.with_variant(ButtonVariant::Danger) - } - - /// With the warning style for the Button. - fn warning(self) -> Self { - self.with_variant(ButtonVariant::Warning) - } - - /// With the success style for the Button. - fn success(self) -> Self { - self.with_variant(ButtonVariant::Success) - } - - /// With the info style for the Button. - fn info(self) -> Self { - self.with_variant(ButtonVariant::Info) - } - - /// With the ghost style for the Button. - fn ghost(self) -> Self { - self.with_variant(ButtonVariant::Ghost) - } - - /// With the link style for the Button. - fn link(self) -> Self { - self.with_variant(ButtonVariant::Link) - } - - /// With the text style for the Button, it will no padding look like a normal text. - fn text(self) -> Self { - self.with_variant(ButtonVariant::Text) - } - - /// With the custom style for the Button. - fn custom(self, style: ButtonCustomVariant) -> Self { - self.with_variant(ButtonVariant::Custom(style)) - } -} - -impl ButtonCustomVariant { - pub fn new(cx: &App) -> Self { - Self { - color: cx.theme().transparent, - foreground: cx.theme().foreground, - hover: cx.theme().transparent, - active: cx.theme().transparent, - shadow: false, - } - } - - /// Set background color, default is transparent. - pub fn color(mut self, color: Hsla) -> Self { - self.color = color; - self - } - - /// Set foreground color, default is theme foreground. - pub fn foreground(mut self, color: Hsla) -> Self { - self.foreground = color; - self - } - - /// Set hover background color, default is transparent. - pub fn hover(mut self, color: Hsla) -> Self { - self.hover = color; - self - } - - /// Set active background color, default is transparent. - pub fn active(mut self, color: Hsla) -> Self { - self.active = color; - self - } - - /// Set shadow, default is false. - pub fn shadow(mut self, shadow: bool) -> Self { - self.shadow = shadow; - self - } -} - -/// The variant of the Button. -#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)] -pub enum ButtonVariant { - #[default] - Default, - Primary, - Secondary, - Danger, - Info, - Success, - Warning, - Ghost, - Link, - Text, - Custom(ButtonCustomVariant), -} - -impl ButtonVariant { - #[inline] - pub fn is_link(&self) -> bool { - matches!(self, Self::Link) - } - - #[inline] - pub fn is_text(&self) -> bool { - matches!(self, Self::Text) - } - - #[inline] - pub fn is_ghost(&self) -> bool { - matches!(self, Self::Ghost) - } - - #[inline] - fn no_padding(&self) -> bool { - self.is_link() || self.is_text() - } - - #[inline] - fn is_default(&self) -> bool { - matches!(self, Self::Default) - } -} - /// A Button element. #[derive(IntoElement)] pub struct Button { @@ -636,9 +487,6 @@ impl RenderOnce for Button { let mut base = self.base; let children = self.children; let instance_style = base.style().clone(); - let normal_style = style.normal(self.outline, cx); - let selected_style = style.selected(self.outline, cx); - let disabled_style = style.disabled(self.outline, cx); let icon_size = self.icon_size.unwrap_or_else(|| match self.size { Size::Size(v) => Size::Size(v * 0.75), _ => self.size, @@ -650,11 +498,13 @@ impl RenderOnce for Button { .read(cx) .clone(); let is_focused = focus_handle.is_focused(window); + let theme = cx.theme(); + let normal_style = style.normal(self.outline, theme); let rounding = match self.rounded { - ButtonRounded::Small => cx.theme().radius * 0.5, - ButtonRounded::Medium => cx.theme().radius, - ButtonRounded::Large => cx.theme().radius * 2.0, + ButtonRounded::Small => theme.radius * 0.5, + ButtonRounded::Medium => theme.radius, + ButtonRounded::Large => theme.radius * 2.0, ButtonRounded::Size(px) => px, ButtonRounded::None => Pixels::ZERO, }; @@ -672,10 +522,9 @@ impl RenderOnce for Button { interactive && (self.variant.is_link() || self.variant.is_text()), |this| this.cursor_pointer(), ) - .when( - !disabled && cx.theme().shadow && normal_style.shadow, - |this| this.shadow_xs(), - ) + .when(!disabled && theme.shadow && normal_style.shadow, |this| { + this.shadow_xs() + }) .when(!style.no_padding(), |this| { if self.label.is_none() && children.is_empty() { // Icon Button @@ -747,20 +596,20 @@ impl RenderOnce for Button { // A loading button keeps its normal colors, but must not react // to the pointer, it is not waiting for another click. .when(interactive, |this| { + let hover_style = style.hovered(self.outline, theme); this.hover(|this| { - let hover_style = style.hovered(self.outline, cx); this.bg(hover_style.bg) .border_color(hover_style.border) .text_color(hover_style.fg) }) .active(|this| { - let active_style = style.active(self.outline, cx); + let active_style = style.active(self.outline, theme); this.bg(active_style.bg) .border_color(active_style.border) .text_color(active_style.fg) }) .when_some(hover_group, |this, group| { - let idle_bg = style.hovered(self.outline, cx).bg.opacity(0.5); + let idle_bg = hover_style.bg.opacity(0.5); this.when(hover_group_held, |this| this.bg(idle_bg)) .group_hover(group, |this| this.bg(idle_bg)) }) @@ -823,23 +672,31 @@ impl RenderOnce for Button { .disabled(disabled) // Base layers semantic states over the builder chain, so the caller's // own style is replayed inside each state to keep it the closest layer. - .styles(|styles| { - styles - .selected(|style| { - style - .bg(selected_style.bg) - .border_color(selected_style.border) - .text_color(selected_style.fg) - .refine_style(&instance_style) - }) - .disabled(|style| { - style - .bg(disabled_style.bg) - .text_color(disabled_style.fg) - .border_color(disabled_style.border) - .shadow_none() - .refine_style(&instance_style) - }) + .when(selected || disabled, |this| { + this.styles(|mut styles| { + if selected { + let selected_style = style.selected(self.outline, theme); + styles = styles.selected(|style| { + style + .bg(selected_style.bg) + .border_color(selected_style.border) + .text_color(selected_style.fg) + .refine_style(&instance_style) + }); + } + if disabled { + let disabled_style = style.disabled(self.outline, theme); + styles = styles.disabled(|style| { + style + .bg(disabled_style.bg) + .text_color(disabled_style.fg) + .border_color(disabled_style.border) + .shadow_none() + .refine_style(&instance_style) + }); + } + styles + }) }) .when_some(accessibility_label, |this, label| { this.accessibility_label(label) @@ -919,1098 +776,10 @@ impl RenderOnce for Button { } } -struct ButtonVariantStyle { - bg: Background, - border: Hsla, - fg: Hsla, - underline: bool, - shadow: bool, -} - -#[derive(Clone, Copy)] -enum ButtonStyleState { - Normal, - Hovered, - Active, -} - -impl ButtonVariant { - fn outline_background(&self, state: ButtonStyleState, cx: &mut App) -> Background { - match (self, state) { - (Self::Default, ButtonStyleState::Normal) => cx.theme().input_background().into(), - (Self::Default, ButtonStyleState::Hovered) => cx - .theme() - .input - .mix_oklab(cx.theme().transparent, 0.5) - .into(), - (Self::Default, ButtonStyleState::Active) => cx - .theme() - .input - .mix_oklab(cx.theme().transparent, 0.7) - .into(), - (Self::Primary, ButtonStyleState::Normal) => { - cx.theme().tokens.primary.background.opacity(0.1) - } - (Self::Primary, ButtonStyleState::Hovered) => { - cx.theme().tokens.primary_hover.background.opacity(0.2) - } - (Self::Primary, ButtonStyleState::Active) => { - cx.theme().tokens.primary_active.background.opacity(0.4) - } - (Self::Secondary, ButtonStyleState::Normal) => { - cx.theme().tokens.secondary.background.opacity(0.1) - } - (Self::Secondary, ButtonStyleState::Hovered) => { - cx.theme().tokens.secondary_hover.background.opacity(0.2) - } - (Self::Secondary, ButtonStyleState::Active) => { - cx.theme().tokens.secondary_active.background.opacity(0.4) - } - (Self::Danger, ButtonStyleState::Normal) => { - cx.theme().tokens.danger.background.opacity(0.1) - } - (Self::Danger, ButtonStyleState::Hovered) => { - cx.theme().tokens.danger_hover.background.opacity(0.2) - } - (Self::Danger, ButtonStyleState::Active) => { - cx.theme().tokens.danger_active.background.opacity(0.4) - } - (Self::Warning, ButtonStyleState::Normal) => { - cx.theme().tokens.warning.background.opacity(0.1) - } - (Self::Warning, ButtonStyleState::Hovered) => { - cx.theme().tokens.warning_hover.background.opacity(0.2) - } - (Self::Warning, ButtonStyleState::Active) => { - cx.theme().tokens.warning_active.background.opacity(0.4) - } - (Self::Success, ButtonStyleState::Normal) => { - cx.theme().tokens.success.background.opacity(0.1) - } - (Self::Success, ButtonStyleState::Hovered) => { - cx.theme().tokens.success_hover.background.opacity(0.2) - } - (Self::Success, ButtonStyleState::Active) => { - cx.theme().tokens.success_active.background.opacity(0.4) - } - (Self::Info, ButtonStyleState::Normal) => { - cx.theme().tokens.info.background.opacity(0.1) - } - (Self::Info, ButtonStyleState::Hovered) => { - cx.theme().tokens.info_hover.background.opacity(0.2) - } - (Self::Info, ButtonStyleState::Active) => { - cx.theme().tokens.info_active.background.opacity(0.4) - } - (Self::Ghost | Self::Link | Self::Text, _) => cx.theme().transparent.into(), - (Self::Custom(colors), _) => colors.color.mix_oklab(cx.theme().transparent, 0.2).into(), - } - } - - fn bg_color(&self, outline: bool, cx: &mut App) -> Background { - if outline { - return self.outline_background(ButtonStyleState::Normal, cx); - } - - match self { - Self::Default => cx.theme().tokens.button.into(), - Self::Primary => cx.theme().tokens.button_primary.into(), - Self::Secondary => cx.theme().tokens.button_secondary.into(), - Self::Danger => cx.theme().tokens.button_danger.into(), - Self::Warning => cx.theme().tokens.button_warning.into(), - Self::Success => cx.theme().tokens.button_success.into(), - Self::Info => cx.theme().tokens.button_info.into(), - Self::Ghost | Self::Link | Self::Text => cx.theme().transparent.into(), - Self::Custom(colors) => colors.color.mix_oklab(cx.theme().transparent, 0.2).into(), - } - } - - fn text_color(&self, outline: bool, cx: &mut App) -> Hsla { - match self { - Self::Default => cx.theme().button_foreground, - Self::Primary => { - if outline { - cx.theme().primary - } else { - cx.theme().button_primary_foreground - } - } - Self::Secondary => { - if outline { - cx.theme().secondary_foreground - } else { - cx.theme().button_secondary_foreground - } - } - Self::Ghost => cx.theme().secondary_foreground, - Self::Danger => { - if outline { - cx.theme().danger - } else { - cx.theme().button_danger_foreground - } - } - Self::Warning => { - if outline { - cx.theme().warning - } else { - cx.theme().button_warning_foreground - } - } - Self::Success => { - if outline { - cx.theme().success - } else { - cx.theme().button_success_foreground - } - } - Self::Info => { - if outline { - cx.theme().info - } else { - cx.theme().button_info_foreground - } - } - Self::Link => cx.theme().link, - Self::Text => cx.theme().foreground.opacity(0.9), - Self::Custom(colors) => colors.foreground, - } - } - - fn border_color(&self, outline: bool, cx: &mut App) -> Hsla { - match self { - Self::Default => cx.theme().input, - Self::Secondary => cx.theme().border, - Self::Primary => cx.theme().primary, - Self::Danger => { - if outline { - cx.theme().danger.mix_oklab(transparent_white(), 0.4) - } else { - cx.theme().button_danger - } - } - Self::Info => { - if outline { - cx.theme().info.mix_oklab(transparent_white(), 0.4) - } else { - cx.theme().button_info - } - } - Self::Warning => { - if outline { - cx.theme().warning.mix_oklab(transparent_white(), 0.4) - } else { - cx.theme().button_warning - } - } - Self::Success => { - if outline { - cx.theme().success.mix_oklab(transparent_white(), 0.4) - } else { - cx.theme().button_success - } - } - Self::Ghost | Self::Link | Self::Text => cx.theme().transparent, - Self::Custom(colors) => { - if outline { - colors.color.mix_oklab(transparent_white(), 0.4) - } else { - colors.color - } - } - } - } - - fn underline(&self, _: &App) -> bool { - match self { - Self::Link => true, - _ => false, - } - } - - fn shadow(&self, _outline: bool, _: &App) -> bool { - match self { - Self::Custom(c) => c.shadow, - _ => false, - } - } - - fn normal(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle { - let bg = self.bg_color(outline, cx); - let border = self.border_color(outline, cx); - let fg = self.text_color(outline, cx); - let underline = self.underline(cx); - let shadow = self.shadow(outline, cx); - - ButtonVariantStyle { - bg, - border, - fg, - underline, - shadow, - } - } - - fn hovered(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle { - let bg: Background = match self { - Self::Default => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_hover.into() - } - } - Self::Primary => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_primary_hover.into() - } - } - Self::Secondary => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_secondary_hover.into() - } - } - Self::Danger => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_danger_hover.into() - } - } - Self::Warning => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_warning_hover.into() - } - } - Self::Success => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_success_hover.into() - } - } - Self::Info => { - if outline { - self.outline_background(ButtonStyleState::Hovered, cx) - } else { - cx.theme().tokens.button_info_hover.into() - } - } - Self::Custom(colors) => colors.hover.into(), - Self::Ghost => { - let accent: Background = cx.theme().tokens.accent.into(); - if cx.theme().mode.is_dark() { - accent.opacity(0.5) - } else { - accent - } - } - Self::Link => cx.theme().transparent.into(), - Self::Text => cx.theme().transparent.into(), - }; - - let border = self.border_color(outline, cx); - let fg = match self { - Self::Link => cx.theme().link_hover, - Self::Text => cx.theme().foreground, - Self::Ghost => cx.theme().accent_foreground, - _ => self.text_color(outline, cx), - }; - - let underline = self.underline(cx); - let shadow = self.shadow(outline, cx); - - ButtonVariantStyle { - bg, - border, - fg, - underline, - shadow, - } - } - - fn active(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle { - let bg = match self { - Self::Default => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_active.into() - } - } - Self::Primary => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_primary_active.into() - } - } - Self::Secondary => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_secondary_active.into() - } - } - Self::Ghost => cx.theme().tokens.button_active.into(), - Self::Danger => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_danger_active.into() - } - } - Self::Warning => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_warning_active.into() - } - } - Self::Success => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_success_active.into() - } - } - Self::Info => { - if outline { - self.outline_background(ButtonStyleState::Active, cx) - } else { - cx.theme().tokens.button_info_active.into() - } - } - Self::Custom(colors) => colors.active.into(), - Self::Link => cx.theme().transparent.into(), - Self::Text => cx.theme().transparent.into(), - }; - let border = self.border_color(outline, cx); - let fg = match self { - Self::Link => cx.theme().link_active, - Self::Text => cx.theme().foreground.opacity(0.7), - _ => self.text_color(outline, cx), - }; - let underline = self.underline(cx); - let shadow = self.shadow(outline, cx); - - ButtonVariantStyle { - bg, - border, - fg, - underline, - shadow, - } - } - - fn selected(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle { - if outline { - let active_style = self.active(outline, cx); - - return ButtonVariantStyle { - fg: self.text_color(outline, cx), - ..active_style - }; - } - - let bg = match self { - Self::Default => cx.theme().tokens.button_active.into(), - Self::Primary => cx.theme().tokens.button_primary_active.into(), - Self::Secondary => cx.theme().tokens.button_secondary_active.into(), - Self::Ghost => cx.theme().tokens.secondary_active.into(), - Self::Danger => cx.theme().tokens.button_danger_active.into(), - Self::Warning => cx.theme().tokens.button_warning_active.into(), - Self::Success => cx.theme().tokens.button_success_active.into(), - Self::Info => cx.theme().tokens.button_info_active.into(), - Self::Link => cx.theme().transparent.into(), - Self::Text => cx.theme().transparent.into(), - Self::Custom(colors) => colors.active.into(), - }; - - let border = self.border_color(outline, cx); - let fg = match self { - Self::Link => cx.theme().link_active, - Self::Text => cx.theme().foreground.opacity(0.7), - _ => self.text_color(false, cx), - }; - let underline = self.underline(cx); - let shadow = self.shadow(outline, cx); - - ButtonVariantStyle { - bg, - border, - fg, - underline, - shadow, - } - } - - fn disabled(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle { - let bg = match self { - Self::Default | Self::Link | Self::Ghost | Self::Text => cx.theme().transparent.into(), - Self::Primary => cx.theme().tokens.button_primary.background.opacity(0.15), - Self::Danger => cx.theme().tokens.button_danger.background.opacity(0.15), - Self::Warning => cx.theme().tokens.button_warning.background.opacity(0.15), - Self::Success => cx.theme().tokens.button_success.background.opacity(0.15), - Self::Info => cx.theme().tokens.button_info.background.opacity(0.15), - Self::Secondary => cx.theme().tokens.button_secondary.background.opacity(1.5), - Self::Custom(style) => style.color.opacity(0.15).into(), - }; - let fg = cx.theme().muted_foreground.opacity(0.5); - let (bg, border) = if outline { - ( - self.outline_background(ButtonStyleState::Normal, cx) - .opacity(0.5), - self.border_color(true, cx).opacity(0.5), - ) - } else if let Self::Default = self { - ( - cx.theme().input_background().opacity(0.5).into(), - cx.theme().input.opacity(0.5), - ) - } else { - let border = match self { - Self::Primary => cx.theme().button_primary.opacity(0.15), - Self::Secondary => cx.theme().button_secondary.opacity(1.5), - Self::Danger => cx.theme().button_danger.opacity(0.15), - Self::Warning => cx.theme().button_warning.opacity(0.15), - Self::Success => cx.theme().button_success.opacity(0.15), - Self::Info => cx.theme().button_info.opacity(0.15), - Self::Custom(style) => style.color.opacity(0.15), - Self::Default | Self::Link | Self::Ghost | Self::Text => cx.theme().transparent, - }; - (bg, border) - }; - - let underline = self.underline(cx); - let shadow = false; - - ButtonVariantStyle { - bg, - border, - fg, - underline, - shadow, - } - } -} +mod variant; +pub use variant::{ButtonCustomVariant, ButtonVariant, ButtonVariants}; #[cfg(test)] -mod tests { - use super::*; - use crate::IconName; - use gpui::{linear_color_stop, linear_gradient, px}; - - /// A button's announced name is its label, unless it was given one — which - /// is the case an icon-only button and a row-shaped button both need. - #[test] - fn an_explicit_accessibility_label_replaces_the_visible_one() { - let plain = Button::new("save").label("Save"); - assert_eq!(plain.accessibility_label, None); - assert_eq!(plain.label.as_deref(), Some("Save")); - - let named = Button::new("row") - .label("Save") - .accessibility_label("Save the current document"); - assert_eq!( - named.accessibility_label.as_deref(), - Some("Save the current document"), - "an explicit name must win over the visible label" - ); - assert_eq!( - named.label.as_deref(), - Some("Save"), - "and must not change what is drawn" - ); - } - - #[gpui::test] - fn disabled_legacy_button_keeps_existing_pointer_blocking(cx: &mut gpui::TestAppContext) { - use std::{cell::Cell, rc::Rc}; - - use gpui::{Context, Modifiers, Render, point}; - - struct Harness(Rc>, Rc>); - - impl Render for Harness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - let button_clicks = self.0.clone(); - let parent_clicks = self.1.clone(); - div() - .id("disabled-button-parent") - .tab_group() - .size(px(100.)) - .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1)) - .child( - Button::new("disabled-legacy") - .disabled(true) - .size_full() - .on_click(move |_, _, _| button_clicks.set(button_clicks.get() + 1)), - ) - } - } - - cx.update(crate::init); - let button_clicks = Rc::new(Cell::new(0)); - let parent_clicks = Rc::new(Cell::new(0)); - let (_, cx) = cx.add_window_view({ - let button_clicks = button_clicks.clone(); - let parent_clicks = parent_clicks.clone(); - move |_, _| Harness(button_clicks, parent_clicks) - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - cx.simulate_click(point(px(10.), px(10.)), Modifiers::default()); - cx.update(|window, cx| window.focus_next(cx)); - cx.simulate_keystrokes("enter space"); - - assert_eq!(button_clicks.get(), 0); - assert_eq!(parent_clicks.get(), 0); - cx.update(|window, cx| assert!(window.focused(cx).is_none())); - } - - #[gpui::test] - fn enabled_button_delegates_pointer_enter_and_space_once(cx: &mut gpui::TestAppContext) { - use std::{cell::Cell, rc::Rc}; - - use gpui::{ - ClickEvent, Context, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, point, - }; - - struct Harness(Rc>, Rc>); - - impl Render for Harness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - let clicks = self.0.clone(); - let keyboard_clicks = self.1.clone(); - div().tab_group().size(px(100.)).child( - Button::new("enabled-legacy") - .size_full() - .on_click(move |event, _, _| { - clicks.set(clicks.get() + 1); - if matches!(event, ClickEvent::Keyboard(_)) { - keyboard_clicks.set(keyboard_clicks.get() + 1); - } - }), - ) - } - } - - cx.update(crate::init); - let clicks = Rc::new(Cell::new(0)); - let keyboard_clicks = Rc::new(Cell::new(0)); - let (_, cx) = cx.add_window_view({ - let clicks = clicks.clone(); - let keyboard_clicks = keyboard_clicks.clone(); - move |_, _| Harness(clicks, keyboard_clicks) - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - cx.simulate_click(point(px(10.), px(10.)), Modifiers::default()); - cx.update(|window, cx| window.focus_next(cx)); - cx.update(|window, cx| { - assert!(window.focused(cx).is_some()); - window.draw(cx).clear(cx); - }); - for key in ["enter", "space"] { - let keystroke = Keystroke::parse(key).unwrap(); - cx.simulate_event(KeyDownEvent { - keystroke: keystroke.clone(), - is_held: false, - prefer_character_input: false, - }); - cx.simulate_event(KeyUpEvent { keystroke }); - } - - assert_eq!(clicks.get(), 3); - assert_eq!(keyboard_clicks.get(), 2); - } - - #[gpui::test] - fn loading_button_keeps_existing_pointer_blocking(cx: &mut gpui::TestAppContext) { - use std::{cell::Cell, rc::Rc}; - - use gpui::{Context, Modifiers, Render, point}; - - struct Harness(Rc>, Rc>); - - impl Render for Harness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - let button_clicks = self.0.clone(); - let parent_clicks = self.1.clone(); - div() - .id("loading-button-parent") - .tab_group() - .size(px(100.)) - .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1)) - .child( - Button::new("loading-legacy") - .loading(true) - .size_full() - .on_click(move |_, _, _| button_clicks.set(button_clicks.get() + 1)), - ) - } - } - - cx.update(crate::init); - let button_clicks = Rc::new(Cell::new(0)); - let parent_clicks = Rc::new(Cell::new(0)); - let (_, cx) = cx.add_window_view({ - let button_clicks = button_clicks.clone(); - let parent_clicks = parent_clicks.clone(); - move |_, _| Harness(button_clicks, parent_clicks) - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - cx.simulate_click(point(px(10.), px(10.)), Modifiers::default()); - cx.update(|window, cx| window.focus_next(cx)); - cx.simulate_keystrokes("enter space"); - - assert_eq!(button_clicks.get(), 0); - assert_eq!(parent_clicks.get(), 0); - cx.update(|window, cx| assert!(window.focused(cx).is_some())); - } - - #[gpui::test] - fn loading_button_without_callback_still_blocks_parent_activation( - cx: &mut gpui::TestAppContext, - ) { - use std::{cell::Cell, rc::Rc}; - - use gpui::{Context, Modifiers, Render, point}; - - struct Harness(Rc>); - - impl Render for Harness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - let parent_clicks = self.0.clone(); - div() - .id("loading-without-callback-parent") - .tab_group() - .size(px(100.)) - .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1)) - .child( - Button::new("loading-without-callback") - .loading(true) - .size_full(), - ) - } - } - - cx.update(crate::init); - let parent_clicks = Rc::new(Cell::new(0)); - let (_, cx) = cx.add_window_view({ - let parent_clicks = parent_clicks.clone(); - move |_, _| Harness(parent_clicks) - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - cx.simulate_click(point(px(10.), px(10.)), Modifiers::default()); - cx.update(|window, cx| window.focus_next(cx)); - cx.simulate_keystrokes("enter space"); - - assert_eq!(parent_clicks.get(), 0); - cx.update(|window, cx| assert!(window.focused(cx).is_some())); - } - - #[gpui::test] - fn base_activation_is_preserved_and_blocked_while_loading(cx: &mut gpui::TestAppContext) { - use gpui::{Context, Render, point}; - use std::{cell::Cell, rc::Rc}; - - struct Harness { - clicks: Rc>, - loading: bool, - } - impl Render for Harness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - let clicks = self.clicks.clone(); - div().tab_group().child( - Button::new("close") - .with_base( - gpui_base::Button::new("close") - .on_click(move |_, _, _| clicks.set(clicks.get() + 1)), - ) - .loading(self.loading) - .size(px(100.)), - ) - } - } - - cx.update(crate::init); - let clicks = Rc::new(Cell::new(0)); - let (view, cx) = cx.add_window_view({ - let clicks = clicks.clone(); - move |_, _| Harness { - clicks, - loading: false, - } - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - cx.simulate_click(point(px(10.), px(10.)), Default::default()); - assert_eq!(clicks.get(), 1); - - view.update(cx, |view, cx| { - view.loading = true; - cx.notify(); - }); - cx.update(|window, cx| window.draw(cx).clear(cx)); - cx.simulate_click(point(px(10.), px(10.)), Default::default()); - cx.update(|window, cx| window.focus_next(cx)); - cx.simulate_keystrokes("enter space"); - assert_eq!(clicks.get(), 1); - } - - #[gpui::test] - fn test_button_builder(_cx: &mut gpui::TestAppContext) { - let button = Button::new("complex-button") - .label("Save Changes") - .primary() - .outline() - .large() - .tooltip("Click to save") - .compact() - .loading(false) - .disabled(false) - .selected(false) - .tab_index(1) - .tab_stop(true) - .dropdown_caret(false) - .rounded(ButtonRounded::Medium) - .on_click(|_, _, _| {}); - - assert_eq!(button.label, Some("Save Changes".into())); - assert_eq!(button.variant, ButtonVariant::Primary); - assert!(button.outline); - assert_eq!(button.size, Size::Large); - assert!(button.tooltip.is_some()); - assert!(button.compact); - assert!(!button.loading); - assert!(!button.disabled); - assert!(!button.selected); - assert_eq!(button.toggled, None); - assert_eq!(button.tab_index, 1); - assert!(button.tab_stop); - assert!(!button.dropdown_caret); - assert!(matches!(button.rounded, ButtonRounded::Medium)); - } - - /// A button paints an open popup the way it paints a selection, but the - /// two states are stored apart, so a caller can read back which one it set - /// and a later design can tell them apart visually. - #[test] - fn an_open_trigger_is_stored_apart_from_a_selected_one() { - let open = Button::new("trigger").open(true); - assert!(open.is_open()); - assert!(!open.is_selected()); - assert!(open.shows_selected_style()); - - let selected = Button::new("trigger").selected(true); - assert!(selected.is_selected()); - assert!(!selected.is_open()); - assert!(selected.shows_selected_style()); - - assert!(!Button::new("trigger").shows_selected_style()); - } - - #[test] - fn selected_trigger_presentation_does_not_imply_toggled_accessibility() { - let selected = Button::new("menu-trigger").selected(true); - assert!(selected.selected); - assert_eq!(selected.toggled, None); - - let selected_toggle = Button::new("explicit-toggle").selected(true).toggled(true); - assert!(selected_toggle.selected); - assert_eq!(selected_toggle.toggled, Some(true)); - } - - /// A loading button must be as inert as a disabled one. `interactive` is what - /// gates the hover and active styling, the `cursor_pointer` of link buttons and - /// the `mouse_down` handler, none of which depend on a listener being set. - #[gpui::test] - fn test_button_loading_is_not_interactive(_cx: &mut gpui::TestAppContext) { - assert!(Button::new("test").interactive()); - assert!(!Button::new("test").loading(true).interactive()); - assert!(!Button::new("test").disabled(true).interactive()); - assert!( - !Button::new("test") - .loading(true) - .disabled(true) - .interactive() - ); - - // Loading gates hovering even when an `on_hover` listener is set. - let loading = Button::new("test").loading(true).on_hover(|_, _, _| {}); - assert!(!loading.hoverable()); - } - - /// `selected` is styling only; the toggle state must be opted into, so that - /// ordinary buttons are not announced as toggle buttons. - #[gpui::test] - fn test_button_variant_methods(_cx: &mut gpui::TestAppContext) { - // Test variant check methods - assert!(ButtonVariant::Link.is_link()); - assert!(ButtonVariant::Text.is_text()); - assert!(ButtonVariant::Ghost.is_ghost()); - - // Test no_padding logic - assert!(ButtonVariant::Link.no_padding()); - assert!(ButtonVariant::Text.no_padding()); - assert!(!ButtonVariant::Ghost.no_padding()); - } - - #[gpui::test] - fn link_button_prepaints_its_child(cx: &mut gpui::TestAppContext) { - use gpui::{Context, Render}; - - struct LinkButtonHarness; - - impl Render for LinkButtonHarness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - Button::new("link-button").link().child( - div() - .debug_selector(|| "link-button-child".into()) - .child("Visible link button"), - ) - } - } - - cx.update(crate::init); - let (_, cx) = cx.add_window_view(|_, _| LinkButtonHarness); - cx.update(|window, cx| window.draw(cx).clear(cx)); - - let bounds = cx - .debug_bounds("link-button-child") - .expect("link button child must participate in layout and prepaint"); - assert!(bounds.size.width > px(0.)); - assert!(bounds.size.height > px(0.)); - } - - #[gpui::test] - fn base_slot_prepaints_complete_button_content(cx: &mut gpui::TestAppContext) { - use gpui::{Context, Render}; - - struct CompleteButtonHarness; - - impl Render for CompleteButtonHarness { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div() - .child( - Button::new("complete-button") - .icon(IconName::Plus) - .label("Create") - .child( - div() - .debug_selector(|| "button-custom-content".into()) - .child("Details"), - ) - .dropdown_caret(true), - ) - .child( - Button::new("loading-button") - .icon(IconName::Plus) - .loading_icon(IconName::Loader) - .loading(true) - .label("Creating") - .dropdown_caret(true), - ) - } - } - - cx.update(crate::init); - let (_, cx) = cx.add_window_view(|_, _| CompleteButtonHarness); - cx.update(|window, cx| window.draw(cx).clear(cx)); - - let bounds = cx - .debug_bounds("button-custom-content") - .expect("application content must prepaint through the Base child seam"); - assert!(bounds.size.width > px(0.)); - assert!(bounds.size.height > px(0.)); - } - - #[gpui::test] - fn test_outline_selected_uses_outline_active_style(cx: &mut gpui::TestAppContext) { - cx.update(crate::init); - let window = cx.add_empty_window(); - window.update(|_, cx| { - let variant = ButtonVariant::Danger; - let active_style = variant.active(true, cx); - let selected_style = variant.selected(true, cx); - - assert_eq!(selected_style.bg, active_style.bg); - assert_eq!(selected_style.border, active_style.border); - assert_eq!(selected_style.fg, cx.theme().danger); - assert_ne!(selected_style.bg, cx.theme().tokens.danger_active.into()); - }); - } - - #[gpui::test] - fn test_primary_button_uses_gradient_background_tokens(cx: &mut gpui::TestAppContext) { - cx.update(crate::init); - let window = cx.add_empty_window(); - window.update(|_, cx| { - let config = serde_json::from_value::(serde_json::json!({ - "name": "Gradient", - "mode": "light", - "colors": { - "button.primary.background": "linear-gradient(135deg, #4F46E5, #06B6D4)", - "button.primary.hover.background": "linear-gradient(145deg, #4338CA, #0891B2)", - "button.primary.active.background": "linear-gradient(155deg, #3730A3, #0E7490)" - } - })) - .unwrap(); - crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config)); - - assert_eq!( - ButtonVariant::Primary.normal(false, cx).bg, - cx.theme().tokens.button_primary.into() - ); - assert_eq!( - ButtonVariant::Primary.hovered(false, cx).bg, - cx.theme().tokens.button_primary_hover.into() - ); - assert_eq!( - ButtonVariant::Primary.active(false, cx).bg, - cx.theme().tokens.button_primary_active.into() - ); - }); - } - - #[gpui::test] - fn test_outline_primary_keeps_original_depth(cx: &mut gpui::TestAppContext) { - cx.update(crate::init); - let window = cx.add_empty_window(); - window.update(|_, cx| { - let config = serde_json::from_value::(serde_json::json!({ - "name": "Outline Depth", - "mode": "light", - "colors": { - "primary.background": "linear-gradient(180deg, #111827, #020617)", - "primary.hover.background": "linear-gradient(180deg, #1F2937, #111827)", - "primary.active.background": "linear-gradient(180deg, #020617, #000000)" - } - })) - .unwrap(); - crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config)); - - assert_eq!( - ButtonVariant::Primary.normal(true, cx).bg, - cx.theme().tokens.primary.background.opacity(0.1) - ); - assert_eq!( - ButtonVariant::Primary.hovered(true, cx).bg, - cx.theme().tokens.primary_hover.background.opacity(0.2) - ); - assert_eq!( - ButtonVariant::Primary.active(true, cx).bg, - cx.theme().tokens.primary_active.background.opacity(0.4) - ); - }); - } - - #[gpui::test] - fn test_outline_buttons_use_semantic_gradient_tokens(cx: &mut gpui::TestAppContext) { - cx.update(crate::init); - let window = cx.add_empty_window(); - window.update(|_, cx| { - let config = serde_json::from_value::(serde_json::json!({ - "name": "Outline Gradient", - "mode": "light", - "colors": { - "primary.background": "linear-gradient(180deg, #111827, #020617)", - "primary.hover.background": "linear-gradient(180deg, #1F2937, #111827)", - "primary.active.background": "linear-gradient(180deg, #020617, #000000)", - "button.primary.background": "linear-gradient(180deg, #FFFFFF, #E5E7EB)", - "button.primary.hover.background": "linear-gradient(180deg, #F9FAFB, #E5E7EB)", - "button.primary.active.background": "linear-gradient(180deg, #E5E7EB, #D1D5DB)", - "danger.background": "linear-gradient(180deg, #EF4444, #DC2626)", - "danger.hover.background": "linear-gradient(180deg, #F87171, #EF4444)", - "danger.active.background": "linear-gradient(180deg, #DC2626, #B91C1C)", - "button.danger.background": "linear-gradient(180deg, #FEF2F2, #FEE2E2)", - "button.danger.hover.background": "linear-gradient(180deg, #FEE2E2, #FECACA)", - "button.danger.active.background": "linear-gradient(180deg, #FECACA, #FCA5A5)" - } - })) - .unwrap(); - crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config)); - - assert_eq!( - ButtonVariant::Primary.normal(true, cx).bg, - cx.theme().tokens.primary.background.opacity(0.1) - ); - assert_eq!( - ButtonVariant::Danger.normal(true, cx).bg, - cx.theme().tokens.danger.background.opacity(0.1) - ); - assert_eq!( - ButtonVariant::Danger.hovered(true, cx).bg, - cx.theme().tokens.danger_hover.background.opacity(0.2) - ); - assert_eq!( - ButtonVariant::Danger.active(true, cx).bg, - cx.theme().tokens.danger_active.background.opacity(0.4) - ); - assert_eq!( - ButtonVariant::Primary.normal(false, cx).bg, - cx.theme().tokens.button_primary.into() - ); - assert_eq!( - ButtonVariant::Danger.normal(false, cx).bg, - linear_gradient( - 180., - linear_color_stop(crate::try_parse_color("#FEF2F2").unwrap(), 0.), - linear_color_stop(crate::try_parse_color("#FEE2E2").unwrap(), 1.) - ) - ); - }); - } - - #[gpui::test] - fn test_disabled_outline_buttons_keep_semantic_backgrounds(cx: &mut gpui::TestAppContext) { - cx.update(crate::init); - let window = cx.add_empty_window(); - window.update(|_, cx| { - let config = serde_json::from_value::(serde_json::json!({ - "name": "Disabled Outline Gradient", - "mode": "light", - "colors": { - "primary.background": "linear-gradient(180deg, #111827, #020617)", - "button.primary.background": "linear-gradient(180deg, #FFFFFF, #E5E7EB)", - "danger.background": "linear-gradient(180deg, #EF4444, #DC2626)", - "button.danger.background": "linear-gradient(180deg, #E5E7EB, #D1D5DB)" - } - })) - .unwrap(); - crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config)); - - assert_eq!( - ButtonVariant::Primary.disabled(true, cx).bg, - cx.theme() - .tokens - .primary - .background - .opacity(0.1) - .opacity(0.5) - ); - assert_eq!( - ButtonVariant::Danger.disabled(true, cx).bg, - cx.theme() - .tokens - .danger - .background - .opacity(0.1) - .opacity(0.5) - ); - assert_ne!( - ButtonVariant::Danger.disabled(true, cx).bg, - cx.theme().input_background().opacity(0.5).into() - ); - assert_ne!( - ButtonVariant::Danger.disabled(true, cx).bg, - cx.theme().tokens.button_danger.background.opacity(0.15) - ); - }); - } -} +mod performance; +#[cfg(test)] +mod tests; diff --git a/vendor/gpui-component/src/button/button/performance.rs b/vendor/gpui-component/src/button/button/performance.rs new file mode 100644 index 00000000..2e0702f1 --- /dev/null +++ b/vendor/gpui-component/src/button/button/performance.rs @@ -0,0 +1,83 @@ +// Modified by Nocterm contributors; see NOCTERM.md. Licensed under Apache-2.0. +use std::{ + hash::{DefaultHasher, Hash, Hasher}, + time::Instant, +}; + +use gpui::{Context, Render, TestAppContext, px, size}; + +use super::*; + +struct Buttons { + count: usize, + mixed: bool, +} + +impl Render for Buttons { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .flex() + .flex_wrap() + .gap_1() + .children((0..self.count).map(|index| { + let variant = match index % 8 { + 0 => ButtonVariant::Default, + 1 => ButtonVariant::Primary, + 2 => ButtonVariant::Secondary, + 3 => ButtonVariant::Ghost, + 4 => ButtonVariant::Danger, + 5 => ButtonVariant::Warning, + 6 => ButtonVariant::Success, + _ => ButtonVariant::Info, + }; + Button::new(index) + .with_variant(variant) + .when(index % 3 == 0, Button::outline) + .label("Button") + .selected(self.mixed && index % 5 == 0) + .disabled(self.mixed && index % 7 == 0) + })) + } +} + +#[gpui::test] +#[ignore = "manual CPU and allocation workload"] +fn measure_button_render_preparation(cx: &mut TestAppContext) { + cx.update(crate::init); + eprintln!( + "base_button_bytes={} component_button_bytes={}", + std::mem::size_of::(), + std::mem::size_of::