mirror of
https://github.com/zed-industries/zed.git
synced 2026-11-19 06:59:22 +01:00
Merge origin/main into gpui-taffy-cache-v3
Bring the layout cache forward to 73ad8e3ed0, including the new path renderer, primitive batching, depth-buffer rendering, and scene sorting. Git merged the source changes without conflicts; the layout-cache engine and keyed text measurement implementation remain unchanged.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
# Sync GitHub project #87 to the current second-line triage shift's issues
|
||||
# Sync GitHub project #87 to the current triage shift's issues
|
||||
|
||||
name: Issue Triage Queue Board
|
||||
|
||||
|
||||
Generated
+550
-485
File diff suppressed because it is too large
Load Diff
+6
-6
@@ -535,7 +535,7 @@ accesskit = { version = "0.24.0", features = ["enumn"] }
|
||||
accesskit_macos = "0.26.0"
|
||||
accesskit_unix = "0.22"
|
||||
accesskit_windows = "0.34"
|
||||
agent-client-protocol = { version = "=5.1.0", features = ["schemars", "unstable", "unstable_protocol_v2"] }
|
||||
agent-client-protocol = { version = "=5.2.0", features = ["schemars", "unstable", "unstable_protocol_v2"] }
|
||||
aho-corasick = "1.1"
|
||||
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "4c129667ce56611becdc82de6e28218c80e2e88f" }
|
||||
any_vec = "0.14"
|
||||
@@ -684,8 +684,8 @@ itertools = "0.14.0"
|
||||
js-sys = "0.3"
|
||||
jsonschema = { version = "0.51", default-features = false }
|
||||
jsonwebtoken = { version = "10.0", default-features = false }
|
||||
jupyter-protocol = "1.4.0"
|
||||
jupyter-websocket-client = "1.1.0"
|
||||
jupyter-protocol = "2.0.3"
|
||||
jupyter-websocket-client = "3.0.0"
|
||||
libc = "0.2"
|
||||
libsqlite3-sys = { version = "0.30.1", features = ["bundled"] }
|
||||
libwebrtc = "0.3.26"
|
||||
@@ -697,12 +697,12 @@ lsp-types = { git = "https://github.com/zed-industries/lsp-types", rev = "82d7fc
|
||||
mach2 = "0.6"
|
||||
markup5ever_rcdom = "0.39"
|
||||
mdbook = { version = "=0.4.40", default-features = false, features = ["search"] }
|
||||
merman = { version = "=0.8.0-alpha.5", default-features = false }
|
||||
merman = { version = "=0.9.3", default-features = false }
|
||||
mime = "0.3.17"
|
||||
minidumper = "0.11"
|
||||
moka = { version = "0.12.10", features = ["sync"] }
|
||||
nanoid = "0.4"
|
||||
nbformat = "1.2.0"
|
||||
nbformat = "3.0.0"
|
||||
nix = "0.30"
|
||||
notify-rust = "4"
|
||||
nucleo = { package = "nucleo-matcher", version = "0.3" }
|
||||
@@ -882,7 +882,7 @@ resvg = { version = "0.46.0", default-features = false, features = [
|
||||
"raster-images",
|
||||
] }
|
||||
rsa = { version = "0.9", default-features = false, features = ["std", "u64_digit"] }
|
||||
runtimelib = { version = "1.4.0", default-features = false, features = [
|
||||
jupyter-zmq-client = { version = "3.0.0", default-features = false, features = [
|
||||
"async-dispatcher-runtime", "aws-lc-rs"
|
||||
] }
|
||||
rust-embed = { version = "8.11", features = ["include-exclude", "compression"] }
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
> [!IMPORTANT]
|
||||
> Remove this line to confirm you've reviewed this PR before submitting.
|
||||
# Zed
|
||||
|
||||
[](https://zed.dev)
|
||||
|
||||
@@ -618,6 +618,8 @@
|
||||
"fullscreen_mode": "native",
|
||||
// Titlebar related settings
|
||||
"title_bar": {
|
||||
// When to show the title bar: "always" | "never" | "hide_in_full_screen".
|
||||
"show": "always",
|
||||
// Whether to show git status indicators on the branch icon in the titlebar.
|
||||
"show_branch_status_icon": false,
|
||||
// Whether to show the branch name button in the titlebar.
|
||||
@@ -1621,8 +1623,8 @@
|
||||
// Whether to pre-fill the file finder's query with the text selected in the
|
||||
// focused item (e.g. an editor or a terminal) when it is opened.
|
||||
//
|
||||
// Default: true
|
||||
"prefill_query_from_selection": true,
|
||||
// Default: false
|
||||
"prefill_query_from_selection": false,
|
||||
},
|
||||
// Whether or not to remove any trailing whitespace from lines of a buffer
|
||||
// before saving it.
|
||||
|
||||
@@ -3199,6 +3199,7 @@ pub enum ToolCallContent {
|
||||
source: acp_v2::Diff,
|
||||
render: DiffPatch,
|
||||
},
|
||||
SessionReference(acp_v2::SessionReference),
|
||||
Other {
|
||||
source: acp_v2::ToolCallContent,
|
||||
markdown: Entity<Markdown>,
|
||||
@@ -3213,6 +3214,7 @@ enum PreparedToolCallContent {
|
||||
meta: Option<acp_v2::Meta>,
|
||||
},
|
||||
DiffPatch(acp_v2::Diff),
|
||||
SessionReference(acp_v2::SessionReference),
|
||||
Other(acp_v2::ToolCallContent),
|
||||
}
|
||||
|
||||
@@ -3235,6 +3237,13 @@ impl PreparedToolCallContent {
|
||||
terminal: terminals.resolve(&acp_v2::TerminalId::new(terminal_id.0), cx)?,
|
||||
meta,
|
||||
},
|
||||
acp_v1::ToolCallContent::Session(acp_v1::SessionReference {
|
||||
session_id,
|
||||
meta,
|
||||
..
|
||||
}) => {
|
||||
Self::SessionReference(acp_v2::SessionReference::new(session_id.0).meta(meta))
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
prepared.push(content);
|
||||
@@ -3265,6 +3274,7 @@ impl PreparedToolCallContent {
|
||||
terminal: terminals.resolve(&terminal.terminal_id, cx)?,
|
||||
meta: terminal.meta,
|
||||
}),
|
||||
acp_v2::ToolCallContent::Session(reference) => Ok(Self::SessionReference(reference)),
|
||||
other => Ok(Self::Other(other)),
|
||||
}
|
||||
}
|
||||
@@ -3314,6 +3324,9 @@ impl ToolCallContent {
|
||||
render: DiffPatch::new(&source, language_registry, cx),
|
||||
source,
|
||||
},
|
||||
PreparedToolCallContent::SessionReference(reference) => {
|
||||
Self::SessionReference(reference)
|
||||
}
|
||||
PreparedToolCallContent::Other(source) => Self::Other {
|
||||
source,
|
||||
markdown: ContentBlock::create_markdown(
|
||||
@@ -3371,6 +3384,10 @@ impl ToolCallContent {
|
||||
}
|
||||
*source = new_source;
|
||||
}
|
||||
(
|
||||
Self::SessionReference(reference),
|
||||
PreparedToolCallContent::SessionReference(new_reference),
|
||||
) => *reference = new_reference,
|
||||
(Self::Other { source, .. }, PreparedToolCallContent::Other(new_source)) => {
|
||||
*source = new_source;
|
||||
}
|
||||
@@ -3388,6 +3405,7 @@ impl ToolCallContent {
|
||||
source.changes.iter().map(diff_change_label).join("\n"),
|
||||
Self::patch_preview(source)
|
||||
),
|
||||
Self::SessionReference(reference) => format!("Session {}", reference.session_id),
|
||||
Self::Other { markdown, .. } => markdown.read(cx).source().to_string(),
|
||||
}
|
||||
}
|
||||
@@ -3397,7 +3415,10 @@ impl ToolCallContent {
|
||||
Self::ContentBlock { block, .. } => block.markdown(),
|
||||
Self::DiffPatch { render, .. } => render.fallback.as_ref(),
|
||||
Self::Other { markdown, .. } => Some(markdown),
|
||||
Self::Diff(_) | Self::LegacyDiff { .. } | Self::Terminal { .. } => None,
|
||||
Self::Diff(_)
|
||||
| Self::LegacyDiff { .. }
|
||||
| Self::Terminal { .. }
|
||||
| Self::SessionReference(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7313,10 +7334,15 @@ impl AcpThread {
|
||||
if self.plans.remove(&identity).is_none() {
|
||||
return;
|
||||
}
|
||||
// A user dismissal (no visible plan) stays in effect; only an agent removing the
|
||||
// plan on screen moves the panel to the next most recently changed plan. Empty plans
|
||||
// are skipped because the panel hides them, which would mask a non-empty one.
|
||||
if self.visible_plan.as_ref() == Some(&identity) {
|
||||
self.fall_back_from_visible_plan(&identity, cx);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// A user dismissal (no visible plan) stays in effect; only an agent removing or emptying
|
||||
/// the plan on screen moves the panel to the next most recently changed plan. Empty plans
|
||||
/// are skipped because the panel hides them, which would mask a non-empty one.
|
||||
fn fall_back_from_visible_plan(&mut self, identity: &PlanIdentity, cx: &App) {
|
||||
if self.visible_plan.as_ref() == Some(identity) {
|
||||
self.visible_plan = self
|
||||
.plans
|
||||
.iter()
|
||||
@@ -7324,7 +7350,6 @@ impl AcpThread {
|
||||
.max_by_key(|(_, plan)| plan.last_changed)
|
||||
.map(|(identity, _)| identity.clone());
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn replace_plan(
|
||||
@@ -7341,7 +7366,11 @@ impl AcpThread {
|
||||
if is_new || changed || identity == PlanIdentity::Legacy {
|
||||
self.plan_change_count += 1;
|
||||
plan.last_changed = self.plan_change_count;
|
||||
self.visible_plan = Some(identity);
|
||||
if plan.is_empty(cx) {
|
||||
self.fall_back_from_visible_plan(&identity, cx);
|
||||
} else {
|
||||
self.visible_plan = Some(identity);
|
||||
}
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
@@ -7355,6 +7384,9 @@ impl AcpThread {
|
||||
{
|
||||
entries
|
||||
.retain(|entry| !matches!(entry.source.status, acp_v2::PlanEntryStatus::Completed));
|
||||
if entries.is_empty() {
|
||||
self.fall_back_from_visible_plan(&PlanIdentity::Legacy, cx);
|
||||
}
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
@@ -9107,7 +9139,6 @@ mod tests {
|
||||
reordered,
|
||||
appended,
|
||||
vec![original[0].clone()],
|
||||
vec![],
|
||||
] {
|
||||
thread.upsert_plan_items(
|
||||
acp_v2::PlanItems::new("plan", original.clone()),
|
||||
@@ -9129,6 +9160,20 @@ mod tests {
|
||||
assert_eq!(first.content, markdown);
|
||||
}
|
||||
}
|
||||
|
||||
thread.clear_plan(cx);
|
||||
thread.upsert_plan_items(acp_v2::PlanItems::new("plan", vec![]), None, cx);
|
||||
assert!(
|
||||
thread.plan().is_none(),
|
||||
"emptying a plan does not reopen it"
|
||||
);
|
||||
assert!(
|
||||
thread
|
||||
.plan_by_id(&"plan".into())
|
||||
.expect("plan")
|
||||
.entries()
|
||||
.is_empty()
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9162,19 +9207,14 @@ mod tests {
|
||||
);
|
||||
assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("b".into())));
|
||||
thread.upsert_plan_items(acp_v2::PlanItems::new("empty", vec![]), None, cx);
|
||||
assert!(
|
||||
thread
|
||||
.plan()
|
||||
.expect("selected empty plan")
|
||||
.entries()
|
||||
.is_empty()
|
||||
);
|
||||
thread.upsert_plan_items(acp_v2::PlanItems::new("a", entries.clone()), None, cx);
|
||||
assert_eq!(
|
||||
thread.visible_plan,
|
||||
Some(PlanIdentity::Keyed("empty".into()))
|
||||
Some(PlanIdentity::Keyed("b".into())),
|
||||
"a new empty plan does not hide the visible one"
|
||||
);
|
||||
let mut changed = entries;
|
||||
thread.upsert_plan_items(acp_v2::PlanItems::new("a", entries.clone()), None, cx);
|
||||
assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("b".into())));
|
||||
let mut changed = entries.clone();
|
||||
changed[0].content = "Changed".into();
|
||||
thread.upsert_plan_items(acp_v2::PlanItems::new("a", changed), None, cx);
|
||||
assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("a".into())));
|
||||
@@ -9183,11 +9223,38 @@ mod tests {
|
||||
first_markdown
|
||||
);
|
||||
thread.upsert_plan_items(acp_v2::PlanItems::new("b", vec![]), None, cx);
|
||||
assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("b".into())));
|
||||
assert_eq!(
|
||||
thread.visible_plan,
|
||||
Some(PlanIdentity::Keyed("a".into())),
|
||||
"emptying a hidden plan does not select it"
|
||||
);
|
||||
thread.upsert_plan_items(acp_v2::PlanItems::new("c", entries.clone()), None, cx);
|
||||
assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("c".into())));
|
||||
thread.upsert_plan_items(acp_v2::PlanItems::new("c", vec![]), None, cx);
|
||||
assert_eq!(
|
||||
thread.visible_plan,
|
||||
Some(PlanIdentity::Keyed("a".into())),
|
||||
"emptying the visible plan falls back to the most recently changed non-empty plan"
|
||||
);
|
||||
assert!(
|
||||
thread
|
||||
.plan()
|
||||
.expect("clearing older B selects empty B")
|
||||
.plan_by_id(&"c".into())
|
||||
.expect("empty C retained")
|
||||
.entries()
|
||||
.is_empty(),
|
||||
"the empty update still replaces C's content"
|
||||
);
|
||||
thread.upsert_plan_items(acp_v2::PlanItems::new("c", entries), None, cx);
|
||||
assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("c".into())));
|
||||
assert_eq!(thread.plan().expect("C refilled").entries().len(), 1);
|
||||
thread.clear_plan(cx);
|
||||
thread.upsert_plan_items(acp_v2::PlanItems::new("b", vec![]), None, cx);
|
||||
thread.upsert_plan_items(acp_v2::PlanItems::new("d", vec![]), None, cx);
|
||||
assert!(thread.plan().is_none(), "empty plans do not undo dismissal");
|
||||
assert!(
|
||||
thread
|
||||
.plan_by_id(&"b".into())
|
||||
.expect("empty B retained")
|
||||
.entries()
|
||||
.is_empty()
|
||||
);
|
||||
@@ -10611,6 +10678,49 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_tool_content_session_references_are_kept_from_v1_and_v2(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
cx.update(|cx| {
|
||||
let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
|
||||
let meta = acp_v2::Meta::from_iter([("revision".into(), 1.into())]);
|
||||
let mut prepared = PreparedToolCallContent::prepare(
|
||||
vec![acp_v1::ToolCallContent::Session(
|
||||
acp_v1::SessionReference::new("from-v1").meta(meta.clone()),
|
||||
)],
|
||||
ToolTerminalResolver::registered(&HashMap::default()),
|
||||
cx,
|
||||
)
|
||||
.expect("prepare v1 content");
|
||||
prepared.extend(
|
||||
PreparedToolCallContent::prepare_v2(
|
||||
vec![acp_v2::ToolCallContent::Session(
|
||||
acp_v2::SessionReference::new("from-v2"),
|
||||
)],
|
||||
ToolTerminalResolver::registered(&HashMap::default()),
|
||||
cx,
|
||||
)
|
||||
.expect("prepare v2 content"),
|
||||
);
|
||||
let content: Vec<_> = prepared
|
||||
.into_iter()
|
||||
.map(|content| ToolCallContent::from_prepared(content, &languages, cx))
|
||||
.collect();
|
||||
let [
|
||||
ToolCallContent::SessionReference(from_v1),
|
||||
ToolCallContent::SessionReference(from_v2),
|
||||
] = content.as_slice()
|
||||
else {
|
||||
panic!("expected two session references, got {content:?}");
|
||||
};
|
||||
assert_eq!(
|
||||
from_v1,
|
||||
&acp_v2::SessionReference::new("from-v1").meta(meta)
|
||||
);
|
||||
assert_eq!(from_v2, &acp_v2::SessionReference::new("from-v2"));
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_tool_call_content_preserves_embedded_text_resource(
|
||||
cx: &mut gpui::TestAppContext,
|
||||
|
||||
@@ -267,7 +267,10 @@ impl SandboxWrap {
|
||||
.filter_map(|path| sandbox::HostFilesystemLocation::capture(path).ok())
|
||||
.collect::<Vec<_>>();
|
||||
let fs = if self.allow_fs_write {
|
||||
sandbox::SandboxFsPolicy::Unrestricted { protected_paths }
|
||||
sandbox::SandboxFsPolicy::Unrestricted {
|
||||
protected_paths,
|
||||
protected_file_names: Vec::new(),
|
||||
}
|
||||
} else {
|
||||
// Project worktree paths are captured fresh; user-approved grants are
|
||||
// rebuilt via the verifying reopen (or captured when legacy bare
|
||||
@@ -302,6 +305,7 @@ impl SandboxWrap {
|
||||
sandbox::SandboxFsPolicy::Restricted {
|
||||
writable_paths,
|
||||
protected_paths,
|
||||
protected_file_names: Vec::new(),
|
||||
}
|
||||
};
|
||||
let network = match &self.network {
|
||||
|
||||
@@ -161,6 +161,7 @@ pub fn settings_sandbox_policy(persistent: &SandboxPermissions) -> SandboxPolicy
|
||||
let fs = if persistent.allow_fs_write_all {
|
||||
SandboxFsPolicy::Unrestricted {
|
||||
protected_paths: Vec::new(),
|
||||
protected_file_names: Vec::new(),
|
||||
}
|
||||
} else {
|
||||
SandboxFsPolicy::Restricted {
|
||||
@@ -176,6 +177,7 @@ pub fn settings_sandbox_policy(persistent: &SandboxPermissions) -> SandboxPolicy
|
||||
.filter_map(acp_thread::granted_write_path_to_location_or_log),
|
||||
),
|
||||
protected_paths: Vec::new(),
|
||||
protected_file_names: Vec::new(),
|
||||
}
|
||||
};
|
||||
let network = if persistent.allow_all_hosts {
|
||||
@@ -439,6 +441,7 @@ impl ThreadSandboxGrants {
|
||||
let fs = if self.allow_fs_write_all {
|
||||
SandboxFsPolicy::Unrestricted {
|
||||
protected_paths: Vec::new(),
|
||||
protected_file_names: Vec::new(),
|
||||
}
|
||||
} else {
|
||||
SandboxFsPolicy::Restricted {
|
||||
@@ -454,6 +457,7 @@ impl ThreadSandboxGrants {
|
||||
.filter_map(acp_thread::granted_write_path_to_location_or_log),
|
||||
),
|
||||
protected_paths: Vec::new(),
|
||||
protected_file_names: Vec::new(),
|
||||
}
|
||||
};
|
||||
let network = if self.network_any_host {
|
||||
@@ -699,6 +703,7 @@ mod tests {
|
||||
.map(|p| HostFilesystemLocation::capture(p).expect("capture temp dir"))
|
||||
.collect(),
|
||||
protected_paths: Vec::new(),
|
||||
protected_file_names: Vec::new(),
|
||||
},
|
||||
network: if hosts.is_empty() {
|
||||
SandboxNetPolicy::Blocked
|
||||
@@ -813,6 +818,7 @@ mod tests {
|
||||
HostFilesystemLocation::capture(build_dir.path()).expect("capture temp dir")
|
||||
],
|
||||
protected_paths: Vec::new(),
|
||||
protected_file_names: Vec::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -829,6 +835,7 @@ mod tests {
|
||||
SandboxFsPolicy::Restricted {
|
||||
writable_paths: Vec::new(),
|
||||
protected_paths: Vec::new(),
|
||||
protected_file_names: Vec::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(empty.network, SandboxNetPolicy::Blocked);
|
||||
@@ -841,6 +848,7 @@ mod tests {
|
||||
policy.fs,
|
||||
SandboxFsPolicy::Unrestricted {
|
||||
protected_paths: Vec::new(),
|
||||
protected_file_names: Vec::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(policy.network, SandboxNetPolicy::Unrestricted);
|
||||
@@ -865,6 +873,7 @@ mod tests {
|
||||
HostFilesystemLocation::capture(log_dir.path()).expect("capture temp dir")
|
||||
],
|
||||
protected_paths: Vec::new(),
|
||||
protected_file_names: Vec::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -884,6 +893,7 @@ mod tests {
|
||||
policy.fs,
|
||||
SandboxFsPolicy::Unrestricted {
|
||||
protected_paths: Vec::new(),
|
||||
protected_file_names: Vec::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(policy.network, SandboxNetPolicy::Unrestricted);
|
||||
|
||||
@@ -3479,6 +3479,7 @@ impl Thread {
|
||||
| LanguageModelCompletionEvent::Thinking { .. }
|
||||
| LanguageModelCompletionEvent::RedactedThinking { .. }
|
||||
| LanguageModelCompletionEvent::ReasoningDetails(_)
|
||||
| LanguageModelCompletionEvent::InputTransformations(_)
|
||||
| LanguageModelCompletionEvent::ToolUse(_)
|
||||
| LanguageModelCompletionEvent::ToolUseJsonParseError { .. }
|
||||
| LanguageModelCompletionEvent::StartMessage { .. }
|
||||
@@ -3736,7 +3737,7 @@ impl Thread {
|
||||
Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
|
||||
Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
|
||||
Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
|
||||
Started | Queued { .. } | Compaction(_) => {}
|
||||
Started | Queued { .. } | Compaction(_) | InputTransformations(_) => {}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
|
||||
@@ -34,6 +34,9 @@ pub const fn default_context_lines() -> u32 {
|
||||
/// - Results are paginated with 20 matches per page. Use the optional 'offset' parameter to request subsequent pages.
|
||||
/// - DO NOT use HTML entities solely to escape characters in the tool parameters.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
// Reject unknown fields so that a mistyped scoping parameter (e.g. `path`) fails loudly instead
|
||||
// of being silently dropped, which would widen the search to the whole project.
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct GrepToolInput {
|
||||
/// A regex pattern to search for in the entire project. Note that the regex will be parsed by the Rust `regex` crate.
|
||||
///
|
||||
@@ -593,6 +596,41 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// An unknown input field must not be dropped silently: a mistyped scoping parameter
|
||||
// (here `path`) would otherwise turn a scoped search into a project-wide one.
|
||||
#[gpui::test]
|
||||
async fn test_grep_tool_rejects_unknown_input_fields(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
cx.executor().allow_parking();
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root"), json!({ "notes.md": "section 1.11\n" }))
|
||||
.await;
|
||||
|
||||
let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
|
||||
|
||||
let tool = Arc::new(GrepTool { project });
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::ready(json!({
|
||||
"regex": "1\\.11",
|
||||
"path": "/root/notes.md",
|
||||
"context_lines": 4,
|
||||
})),
|
||||
ToolCallEventStream::test().0,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let error = task
|
||||
.await
|
||||
.expect_err("grep input with unknown fields should be rejected");
|
||||
assert!(
|
||||
error.contains("unknown field `path`") && error.contains("include_pattern"),
|
||||
"unexpected error message: {error}"
|
||||
);
|
||||
}
|
||||
|
||||
// The grep tool streams a clickable `file://` ResourceLink and a tool-call
|
||||
// location for every match so each result opens the file at the matched line
|
||||
// in the agent panel. The model-facing text output stays link-free.
|
||||
|
||||
@@ -1158,32 +1158,35 @@ fn handle_v2_complete_elicitation(
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn set_acp_beta(enabled: bool, cx: &mut App) {
|
||||
use gpui::UpdateGlobal as _;
|
||||
|
||||
cx.update_flags(
|
||||
false,
|
||||
if enabled {
|
||||
vec!["acp-beta".into()]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
);
|
||||
settings::SettingsStore::update_global(cx, |store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings
|
||||
.feature_flags
|
||||
.get_or_insert_default()
|
||||
.insert("acp-beta".into(), if enabled { "on" } else { "off" }.into());
|
||||
});
|
||||
});
|
||||
assert_eq!(cx.has_flag::<AcpBetaFeatureFlag>(), enabled);
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod selection_tests {
|
||||
use super::*;
|
||||
use gpui::{TestAppContext, UpdateGlobal as _};
|
||||
use gpui::TestAppContext;
|
||||
use serde_json::json;
|
||||
|
||||
pub(super) fn set_beta(enabled: bool, cx: &mut App) {
|
||||
cx.update_flags(
|
||||
false,
|
||||
if enabled {
|
||||
vec!["acp-beta".into()]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
);
|
||||
settings::SettingsStore::update_global(cx, |store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings
|
||||
.feature_flags
|
||||
.get_or_insert_default()
|
||||
.insert("acp-beta".into(), if enabled { "on" } else { "off" }.into());
|
||||
});
|
||||
});
|
||||
assert_eq!(cx.has_flag::<AcpBetaFeatureFlag>(), enabled);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn beta_selection_uses_fresh_v1_fallback_only_for_version_mismatch(
|
||||
cx: &mut TestAppContext,
|
||||
@@ -1262,7 +1265,7 @@ mod selection_tests {
|
||||
(true, "", true, None, "2"),
|
||||
] {
|
||||
cx.update(|cx| {
|
||||
set_beta(beta, cx);
|
||||
set_acp_beta(beta, cx);
|
||||
});
|
||||
let trace = directory.path().join("connections");
|
||||
std::fs::write(&trace, "").expect("clear trace");
|
||||
@@ -1326,7 +1329,7 @@ done
|
||||
connection.clone().downcast::<AcpV2Connection>().is_some(),
|
||||
v2
|
||||
);
|
||||
cx.update(|cx| set_beta(false, cx));
|
||||
cx.update(|cx| set_acp_beta(false, cx));
|
||||
assert_eq!(
|
||||
connection.clone().downcast::<AcpV2Connection>().is_some(),
|
||||
v2
|
||||
@@ -1433,7 +1436,7 @@ done
|
||||
(true, true, true),
|
||||
(true, false, false),
|
||||
] {
|
||||
cx.update(|cx| set_beta(beta, cx));
|
||||
cx.update(|cx| set_acp_beta(beta, cx));
|
||||
let command = AgentServerCommand {
|
||||
path: "npx".into(),
|
||||
args: vec![
|
||||
|
||||
@@ -28,9 +28,7 @@ use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _};
|
||||
use futures::channel::mpsc;
|
||||
use futures::future::Shared;
|
||||
use futures::{Future, FutureExt as _};
|
||||
use project::agent_server_store::{
|
||||
AgentServerCommand, AgentServerStore, AllAgentServersSettings, CustomAgentServerSettings,
|
||||
};
|
||||
use project::agent_server_store::{AgentServerCommand, AgentServerStore, AllAgentServersSettings};
|
||||
use project::{AgentId, Project};
|
||||
use serde::Deserialize;
|
||||
use settings::{AgentConfigOptionValue, SettingsStore};
|
||||
@@ -120,6 +118,26 @@ impl AcpConnectionDefaults {
|
||||
self.config_options.borrow().get(config_id).cloned()
|
||||
}
|
||||
|
||||
fn initial_config_options(&self) -> Vec<acp::InitialSessionConfigOption> {
|
||||
let config_options = self.config_options.borrow();
|
||||
let mut entries = config_options.iter().collect::<Vec<_>>();
|
||||
entries.sort_by_key(|(config_id, _)| *config_id);
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|(config_id, value)| {
|
||||
let value = match value {
|
||||
AgentConfigOptionValue::ValueId(value_id) => {
|
||||
acp::SessionConfigOptionValue::value_id(value_id.clone())
|
||||
}
|
||||
AgentConfigOptionValue::Boolean(value) => {
|
||||
acp::SessionConfigOptionValue::boolean(*value)
|
||||
}
|
||||
};
|
||||
acp::InitialSessionConfigOption::new(config_id.clone(), value)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn set(
|
||||
&self,
|
||||
mode: Option<acp_v2::SessionConfigValueId>,
|
||||
@@ -140,21 +158,11 @@ impl AcpConnectionDefaults {
|
||||
return;
|
||||
};
|
||||
|
||||
let default_config_options = match agent_settings {
|
||||
CustomAgentServerSettings::Custom {
|
||||
default_config_options,
|
||||
..
|
||||
}
|
||||
| CustomAgentServerSettings::Registry {
|
||||
default_config_options,
|
||||
..
|
||||
} => default_config_options.clone(),
|
||||
};
|
||||
self.set(
|
||||
agent_settings
|
||||
.default_mode()
|
||||
.map(acp_v2::SessionConfigValueId::new),
|
||||
default_config_options,
|
||||
agent_settings.default_config_options().clone(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -913,6 +921,16 @@ impl AcpConnection {
|
||||
self.agent_capabilities.session_capabilities.close.is_some()
|
||||
}
|
||||
|
||||
/// `session/options` is still a draft, so Zed only uses it with the ACP beta flag.
|
||||
fn agent_supports_initial_config_options(&self, cx: &App) -> bool {
|
||||
cx.has_flag::<AcpBetaFeatureFlag>()
|
||||
&& self
|
||||
.agent_capabilities
|
||||
.session_capabilities
|
||||
.options
|
||||
.is_some()
|
||||
}
|
||||
|
||||
/// `rpc_call` gets a receiver that resolves once its response has been applied, and
|
||||
/// holds the agent's later messages until then (see `ordered_response`). With
|
||||
/// `replays_history`, the response ends a history replay.
|
||||
@@ -1326,13 +1344,18 @@ impl AgentConnection for AcpConnection {
|
||||
};
|
||||
let name = self.id.0.clone();
|
||||
let mcp_servers = mcp_servers_for_project(&project, cx);
|
||||
let sends_initial_config_options = self.agent_supports_initial_config_options(cx);
|
||||
|
||||
cx.spawn(async move |cx| {
|
||||
let (response_sender, response_received) = futures::channel::oneshot::channel();
|
||||
let (registered, registration_finished) = futures::channel::oneshot::channel();
|
||||
let request = self
|
||||
.connection
|
||||
.prepare_request(directories.into_new_session_request(mcp_servers));
|
||||
let mut request = directories.into_new_session_request(mcp_servers);
|
||||
if sends_initial_config_options {
|
||||
// The default-application pass below still runs, so defaults the agent ignored
|
||||
// here (for example, ones that depend on another option) get another chance.
|
||||
request = request.config_options(self.defaults.initial_config_options());
|
||||
}
|
||||
let request = self.connection.prepare_request(request);
|
||||
let cancellation = request.cancellation_handle();
|
||||
request
|
||||
.on_receiving_result({
|
||||
@@ -6426,6 +6449,27 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_config_options_are_sorted_and_typed() {
|
||||
let defaults = AcpConnectionDefaults::new(
|
||||
None,
|
||||
HashMap::from_iter([
|
||||
(
|
||||
"model".to_string(),
|
||||
AgentConfigOptionValue::ValueId("large".to_string()),
|
||||
),
|
||||
("fast".to_string(), AgentConfigOptionValue::Boolean(true)),
|
||||
]),
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(defaults.initial_config_options()).expect("serialize"),
|
||||
serde_json::json!([
|
||||
{"configId": "fast", "type": "boolean", "value": true},
|
||||
{"configId": "model", "value": "large"},
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn settings_changes_refresh_active_connection_defaults(cx: &mut gpui::TestAppContext) {
|
||||
cx.update(|cx| {
|
||||
@@ -7307,7 +7351,7 @@ exec cat >/dev/null
|
||||
);
|
||||
|
||||
for enabled in [false, true] {
|
||||
cx.update(|cx| crate::acp::selection_tests::set_beta(enabled, cx));
|
||||
cx.update(|cx| crate::acp::set_acp_beta(enabled, cx));
|
||||
let command = AgentServerCommand {
|
||||
path: "/bin/sh".into(),
|
||||
args: vec!["-c".into(), script.clone()],
|
||||
|
||||
@@ -20,6 +20,7 @@ use agent_client_protocol::{
|
||||
};
|
||||
use anyhow::{Context as _, Result, anyhow};
|
||||
use collections::HashMap;
|
||||
use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _};
|
||||
use futures::{
|
||||
FutureExt as _,
|
||||
channel::mpsc,
|
||||
@@ -30,7 +31,7 @@ use project::{
|
||||
AgentId, AgentServerStore, Project,
|
||||
agent_server_store::{AgentServerCommand, AllAgentServersSettings},
|
||||
};
|
||||
use settings::SettingsStore;
|
||||
use settings::{AgentConfigOptionValue, SettingsStore};
|
||||
use std::{any::Any, cell::RefCell, rc::Rc, sync::Arc};
|
||||
use task::SpawnInTerminal;
|
||||
use util::ResultExt as _;
|
||||
@@ -825,6 +826,45 @@ impl AcpV2Connection {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `session/options` is still a draft, so Zed only uses it with the ACP beta flag.
|
||||
fn supports_initial_config_options(&self, cx: &App) -> bool {
|
||||
cx.has_flag::<AcpBetaFeatureFlag>()
|
||||
&& self
|
||||
.initialize_response
|
||||
.capabilities
|
||||
.session
|
||||
.as_ref()
|
||||
.is_some_and(|session| session.options.is_some())
|
||||
}
|
||||
|
||||
fn initial_config_options(&self, cx: &App) -> Vec<acp::InitialSessionConfigOption> {
|
||||
let Some(settings_store) = cx.try_global::<SettingsStore>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(defaults) = settings_store
|
||||
.get::<AllAgentServersSettings>(None)
|
||||
.get(self.id.as_ref())
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut entries = defaults.default_config_options().iter().collect::<Vec<_>>();
|
||||
entries.sort_by_key(|(config_id, _)| *config_id);
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|(config_id, value)| {
|
||||
let value = match value {
|
||||
AgentConfigOptionValue::ValueId(value_id) => {
|
||||
acp::SessionConfigOptionValue::id(value_id.clone())
|
||||
}
|
||||
AgentConfigOptionValue::Boolean(value) => {
|
||||
acp::SessionConfigOptionValue::boolean(*value)
|
||||
}
|
||||
};
|
||||
acp::InitialSessionConfigOption::new(config_id.clone(), value)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn apply_new_session_defaults(
|
||||
&self,
|
||||
thread: &Entity<AcpThread>,
|
||||
@@ -1293,9 +1333,14 @@ impl AgentConnection for AcpV2Connection {
|
||||
Ok(context) => context,
|
||||
Err(error) => return Task::ready(Err(error)),
|
||||
};
|
||||
let request = acp::NewSessionRequest::new(context.cwd.clone())
|
||||
let mut request = acp::NewSessionRequest::new(context.cwd.clone())
|
||||
.additional_directories(context.additional_directories.clone())
|
||||
.mcp_servers(context.mcp_servers.clone());
|
||||
if self.supports_initial_config_options(cx) {
|
||||
// `apply_new_session_defaults` still runs after creation, so defaults the agent
|
||||
// ignored here (for example, ones that depend on another option) get another chance.
|
||||
request = request.config_options(self.initial_config_options(cx));
|
||||
}
|
||||
let request = self.connection.prepare_request(request);
|
||||
let request_id = request.id().clone();
|
||||
let (response, applied) = Self::ordered_prepared_response(
|
||||
@@ -2984,6 +3029,81 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn v2_new_session_sends_defaults_as_initial_config_options(cx: &mut TestAppContext) {
|
||||
use settings::AgentConfigOptionValue::{Boolean, ValueId};
|
||||
|
||||
let harness = SessionHarness::new(
|
||||
acp::AgentCapabilities::new().session(
|
||||
acp::SessionCapabilities::new().options(acp::SessionOptionsCapabilities::new()),
|
||||
),
|
||||
vec![],
|
||||
vec![],
|
||||
cx,
|
||||
)
|
||||
.await;
|
||||
// Toggling the flag rewrites user settings, which drops the overridden defaults.
|
||||
let set_beta_with_defaults = |enabled, cx: &mut TestAppContext| {
|
||||
cx.update(|cx| crate::acp::set_acp_beta(enabled, cx));
|
||||
set_startup_defaults(
|
||||
HashMap::from_iter([
|
||||
("model".into(), ValueId("large".into())),
|
||||
("enabled".into(), Boolean(true)),
|
||||
]),
|
||||
cx,
|
||||
);
|
||||
};
|
||||
set_beta_with_defaults(false, cx);
|
||||
let mut creation = harness.create(cx);
|
||||
let (request, _) = harness.new_request(&mut creation, cx).await;
|
||||
assert!(
|
||||
request.config_options.is_empty(),
|
||||
"initial config options require the ACP beta flag"
|
||||
);
|
||||
harness
|
||||
.new_responses
|
||||
.try_send(Ok(acp::NewSessionResponse::new("without-beta")))
|
||||
.expect("new response");
|
||||
bounded(creation, cx).await.expect("initialized");
|
||||
|
||||
set_beta_with_defaults(true, cx);
|
||||
let mut creation = harness.create(cx);
|
||||
let (request, _) = harness.new_request(&mut creation, cx).await;
|
||||
assert_eq!(
|
||||
request.config_options,
|
||||
vec![
|
||||
acp::InitialSessionConfigOption::new(
|
||||
"enabled",
|
||||
acp::SessionConfigOptionValue::boolean(true),
|
||||
),
|
||||
acp::InitialSessionConfigOption::new(
|
||||
"model",
|
||||
acp::SessionConfigOptionValue::id("large"),
|
||||
),
|
||||
]
|
||||
);
|
||||
harness
|
||||
.new_responses
|
||||
.try_send(Ok(initial_response().config_options(vec![
|
||||
acp::SessionConfigOption::select(
|
||||
"model",
|
||||
"Model",
|
||||
"large",
|
||||
vec![
|
||||
acp::SessionConfigSelectOption::new("small", "Small"),
|
||||
acp::SessionConfigSelectOption::new("large", "Large"),
|
||||
],
|
||||
),
|
||||
acp::SessionConfigOption::boolean("enabled", "Enabled", true),
|
||||
])))
|
||||
.expect("new response");
|
||||
bounded(creation, cx).await.expect("initialized");
|
||||
assert!(
|
||||
harness.config_requests.is_empty(),
|
||||
"defaults the agent applied are not sent again"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn v2_new_session_applies_defaults_before_delivery(cx: &mut TestAppContext) {
|
||||
use settings::AgentConfigOptionValue::{Boolean, ValueId};
|
||||
@@ -3020,7 +3140,11 @@ mod tests {
|
||||
),
|
||||
];
|
||||
let mut creation = harness.create(cx);
|
||||
harness.new_request(&mut creation, cx).await;
|
||||
let (request, _) = harness.new_request(&mut creation, cx).await;
|
||||
assert!(
|
||||
request.config_options.is_empty(),
|
||||
"initial config options require the options capability"
|
||||
);
|
||||
harness
|
||||
.new_responses
|
||||
.try_send(Ok(initial_response().config_options(offered.clone())))
|
||||
|
||||
@@ -1356,6 +1356,7 @@ impl CodegenAlternative {
|
||||
| LanguageModelCompletionEvent::Thinking { .. }
|
||||
| LanguageModelCompletionEvent::RedactedThinking { .. }
|
||||
| LanguageModelCompletionEvent::ReasoningDetails(_)
|
||||
| LanguageModelCompletionEvent::InputTransformations(_)
|
||||
| LanguageModelCompletionEvent::Compaction(_),
|
||||
) => {}
|
||||
Err(error) => {
|
||||
@@ -1431,6 +1432,7 @@ impl CodegenAlternative {
|
||||
| LanguageModelCompletionEvent::RedactedThinking { .. }
|
||||
| LanguageModelCompletionEvent::StartMessage { .. }
|
||||
| LanguageModelCompletionEvent::ReasoningDetails(_)
|
||||
| LanguageModelCompletionEvent::InputTransformations(_)
|
||||
| LanguageModelCompletionEvent::Compaction(_),
|
||||
) => None,
|
||||
Err(error) => Some(Err(error)),
|
||||
|
||||
@@ -9840,10 +9840,11 @@ pub(crate) mod tests {
|
||||
assert!(cx.debug_bounds("plan-status-All Done").is_none());
|
||||
thread.update(cx, |thread, cx| {
|
||||
thread.upsert_plan_items(acp_v2::PlanItems::new("status-plan", vec![]), None, cx);
|
||||
assert!(thread.plan().is_none());
|
||||
assert!(
|
||||
thread
|
||||
.plan()
|
||||
.expect("empty selected plan")
|
||||
.plan_by_id(&"status-plan".into())
|
||||
.expect("emptied plan")
|
||||
.entries()
|
||||
.is_empty()
|
||||
);
|
||||
@@ -20565,6 +20566,64 @@ pub(crate) mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_tool_call_session_reference_opens_its_session(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
let connection = StubAgentConnection::new();
|
||||
let (conversation_view, cx) =
|
||||
setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
|
||||
add_to_workspace_with_size(conversation_view.clone(), true, cx);
|
||||
let root =
|
||||
active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
|
||||
let root_session_id = root.read_with(cx, |thread, _| thread.session_id().clone());
|
||||
let child = conversation_view.update(cx, |view, cx| {
|
||||
create_test_acp_subagent(
|
||||
root_session_id.clone(),
|
||||
"child",
|
||||
Rc::new(connection.clone()),
|
||||
view.project.clone(),
|
||||
cx,
|
||||
)
|
||||
});
|
||||
child.update(cx, |child, cx| {
|
||||
child
|
||||
.update_subagent_association(
|
||||
&acp_v2::SubagentUpdate::new("child").title("Investigator"),
|
||||
cx,
|
||||
)
|
||||
.expect("ACP subagent")
|
||||
});
|
||||
root.update(cx, |root, cx| root.register_subagent(child.clone(), cx));
|
||||
root.update(cx, |root, cx| {
|
||||
root.upsert_wire_tool_call(
|
||||
acp_v2::ToolCallUpdate::new("delegate")
|
||||
.title("Delegate")
|
||||
.status(acp_v2::ToolCallStatus::Completed)
|
||||
.content(vec![
|
||||
acp_v2::SessionReference::new("child").into(),
|
||||
acp_v2::SessionReference::new("unknown").into(),
|
||||
]),
|
||||
cx,
|
||||
)
|
||||
})
|
||||
.expect("tool call");
|
||||
conversation_view.update(cx, |view, cx| view.expand_tool_call("delegate".into(), cx));
|
||||
cx.run_until_parked();
|
||||
|
||||
assert!(
|
||||
cx.debug_bounds("tool-call-session-reference-0-1").is_none(),
|
||||
"an unknown session is not a link"
|
||||
);
|
||||
let link = cx
|
||||
.debug_bounds("tool-call-session-reference-0-0")
|
||||
.expect("the reference links to its session");
|
||||
cx.simulate_click(link.center(), gpui::Modifiers::default());
|
||||
cx.run_until_parked();
|
||||
let active_session_id = active_thread(&conversation_view, cx)
|
||||
.read_with(cx, |view, cx| view.thread.read(cx).session_id().clone());
|
||||
assert_eq!(active_session_id, acp_v2::SessionId::new("child"));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_first_message_to_an_acp_subagent_shows_its_card(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
@@ -7710,6 +7710,7 @@ impl ThreadView {
|
||||
!markdown.read(cx).source().is_empty()
|
||||
})
|
||||
}
|
||||
ToolCallContent::SessionReference(_) => true,
|
||||
ToolCallContent::Other { markdown, .. } => {
|
||||
!markdown.read(cx).source().is_empty()
|
||||
}
|
||||
@@ -11922,6 +11923,9 @@ impl ThreadView {
|
||||
})
|
||||
.into_any_element()
|
||||
}
|
||||
ToolCallContent::SessionReference(reference) => {
|
||||
self.render_tool_call_session_reference(entry_ix, context_ix, reference, cx)
|
||||
}
|
||||
ToolCallContent::Other { markdown, .. } => self.render_markdown_output(
|
||||
markdown.clone(),
|
||||
entry_ix,
|
||||
@@ -11934,6 +11938,58 @@ impl ThreadView {
|
||||
}
|
||||
}
|
||||
|
||||
fn render_tool_call_session_reference(
|
||||
&self,
|
||||
entry_ix: usize,
|
||||
context_ix: usize,
|
||||
reference: &acp_v2::SessionReference,
|
||||
cx: &Context<Self>,
|
||||
) -> AnyElement {
|
||||
let element_id = format!("tool-call-session-reference-{entry_ix}-{context_ix}");
|
||||
let participant = match self.session_participant_label(&reference.session_id, cx) {
|
||||
Some(label) => div()
|
||||
.debug_selector({
|
||||
let element_id = element_id.clone();
|
||||
move || element_id
|
||||
})
|
||||
.child(
|
||||
Button::new(SharedString::from(element_id), label)
|
||||
.label_size(LabelSize::Small)
|
||||
.tooltip(Tooltip::text("Open Session"))
|
||||
.on_click(cx.listener({
|
||||
let session_id = reference.session_id.clone();
|
||||
move |this, _, window, cx| {
|
||||
let Some(server_view) = this.server_view.upgrade() else {
|
||||
return;
|
||||
};
|
||||
server_view.update(cx, |view, cx| {
|
||||
view.navigate_to_thread(session_id.clone(), window, cx)
|
||||
});
|
||||
}
|
||||
})),
|
||||
)
|
||||
.into_any_element(),
|
||||
// The reference is display-only, so a session this conversation has no thread for
|
||||
// is shown rather than loaded.
|
||||
None => Label::new("Unavailable Session")
|
||||
.size(LabelSize::Small)
|
||||
.color(Color::Muted)
|
||||
.into_any_element(),
|
||||
};
|
||||
|
||||
h_flex()
|
||||
.px_2()
|
||||
.py_1()
|
||||
.gap_1p5()
|
||||
.child(
|
||||
Icon::new(IconName::ForwardArrow)
|
||||
.size(IconSize::Small)
|
||||
.color(Color::Muted),
|
||||
)
|
||||
.child(participant)
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn render_output_content_block(
|
||||
&self,
|
||||
entry_ix: usize,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::cmp::Reverse;
|
||||
|
||||
use collections::HashSet;
|
||||
use fuzzy_nucleo::StringMatchCandidate;
|
||||
use fuzzy_nucleo::{Case, StringMatchCandidate, StringMatchOptions};
|
||||
use gpui::BackgroundExecutor;
|
||||
use ordered_float::OrderedFloat;
|
||||
|
||||
@@ -41,24 +41,23 @@ async fn match_names_with_metadata(
|
||||
query: &str,
|
||||
executor: BackgroundExecutor,
|
||||
) -> Vec<usize> {
|
||||
let cancel_flag = Default::default();
|
||||
let (mut name_matches, mut metadata_matches) = futures::join!(
|
||||
fuzzy_nucleo::match_strings_async(
|
||||
names,
|
||||
query,
|
||||
fuzzy_nucleo::Case::Ignore,
|
||||
fuzzy_nucleo::LengthPenalty::On,
|
||||
names.len(),
|
||||
&cancel_flag,
|
||||
StringMatchOptions {
|
||||
case: Case::Ignore,
|
||||
..Default::default()
|
||||
},
|
||||
executor.clone(),
|
||||
),
|
||||
fuzzy_nucleo::match_strings_async(
|
||||
candidates,
|
||||
query,
|
||||
fuzzy_nucleo::Case::Ignore,
|
||||
fuzzy_nucleo::LengthPenalty::On,
|
||||
candidates.len(),
|
||||
&cancel_flag,
|
||||
StringMatchOptions {
|
||||
case: Case::Ignore,
|
||||
..Default::default()
|
||||
},
|
||||
executor,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -28,7 +28,7 @@ use picker::{
|
||||
Picker, PickerDelegate,
|
||||
highlighted_match_with_paths::{HighlightedMatch, HighlightedMatchWithPaths},
|
||||
};
|
||||
use platform_title_bar::apply_title_bar_insets;
|
||||
use platform_title_bar::{SidebarWindowControls, TitleBarSettings, apply_title_bar_insets};
|
||||
use project::{AgentId, AgentServerStore};
|
||||
use settings::Settings as _;
|
||||
use theme::ActiveTheme;
|
||||
@@ -859,30 +859,36 @@ impl ThreadsArchiveView {
|
||||
|
||||
fn render_header(&self, window: &Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let has_query = !self.filter_editor.read(cx).text(cx).is_empty();
|
||||
let sidebar_on_left = matches!(
|
||||
AgentSettings::get_global(cx).sidebar_side(),
|
||||
settings::SidebarSide::Left
|
||||
);
|
||||
let sidebar_on_right = !sidebar_on_left;
|
||||
let not_fullscreen = !window.is_fullscreen() && !window.is_simple_fullscreen();
|
||||
let traffic_lights = cfg!(target_os = "macos") && not_fullscreen && sidebar_on_left;
|
||||
let left_window_controls = !cfg!(target_os = "macos") && not_fullscreen && sidebar_on_left;
|
||||
let right_window_controls =
|
||||
!cfg!(target_os = "macos") && not_fullscreen && sidebar_on_right;
|
||||
let header_height = platform_title_bar_height(window);
|
||||
let SidebarWindowControls {
|
||||
traffic_lights,
|
||||
left: left_window_controls,
|
||||
right: right_window_controls,
|
||||
} = SidebarWindowControls::new(AgentSettings::get_global(cx).sidebar_side(), window, cx);
|
||||
let title_bar_visible = TitleBarSettings::is_title_bar_visible(window, cx);
|
||||
let header_height = if title_bar_visible {
|
||||
platform_title_bar_height(window)
|
||||
} else {
|
||||
Tab::container_height(cx)
|
||||
};
|
||||
let show_focus_keybinding =
|
||||
self.selection.is_some() && !self.filter_editor.focus_handle(cx).is_focused(window);
|
||||
|
||||
h_flex()
|
||||
.debug_selector(|| "threads-archive-header".into())
|
||||
.h(header_height)
|
||||
.map(|header| match window.window_decorations() {
|
||||
Decorations::Client { .. } => apply_title_bar_insets(
|
||||
header,
|
||||
left_window_controls,
|
||||
right_window_controls,
|
||||
false,
|
||||
),
|
||||
Decorations::Server => header.mt_px().pb_px(),
|
||||
.map(|header| {
|
||||
if !title_bar_visible {
|
||||
return header.mt_px();
|
||||
}
|
||||
match window.window_decorations() {
|
||||
Decorations::Client { .. } => apply_title_bar_insets(
|
||||
header,
|
||||
left_window_controls,
|
||||
right_window_controls,
|
||||
false,
|
||||
),
|
||||
Decorations::Server => header.mt_px().pb_px(),
|
||||
}
|
||||
})
|
||||
.when(left_window_controls, |this| {
|
||||
this.children(Self::render_left_window_controls(window, cx))
|
||||
@@ -906,6 +912,7 @@ impl ThreadsArchiveView {
|
||||
})
|
||||
.child(
|
||||
h_flex()
|
||||
.debug_selector(|| "threads-archive-header-search".into())
|
||||
.ml_1()
|
||||
.min_w_0()
|
||||
.w_full()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::{cmp::Reverse, fmt, sync::Arc, time::Duration};
|
||||
|
||||
use collections::HashSet;
|
||||
use fuzzy_nucleo::{Case, LengthPenalty, StringMatch, StringMatchCandidate};
|
||||
use fuzzy_nucleo::{Case, StringMatch, StringMatchCandidate, StringMatchOptions};
|
||||
use gpui::{BenchAppContext, SharedString};
|
||||
use ordered_float::OrderedFloat;
|
||||
|
||||
@@ -118,20 +118,12 @@ fn expected_values(options: &[OptionValue], query: &str) -> Vec<SharedString> {
|
||||
.enumerate()
|
||||
.map(|(index, option)| candidates(index, option))
|
||||
.unzip();
|
||||
let mut names = fuzzy_nucleo::match_strings(
|
||||
&names,
|
||||
query,
|
||||
Case::Ignore,
|
||||
LengthPenalty::On,
|
||||
options.len(),
|
||||
);
|
||||
let mut metadata = fuzzy_nucleo::match_strings(
|
||||
&metadata,
|
||||
query,
|
||||
Case::Ignore,
|
||||
LengthPenalty::On,
|
||||
options.len(),
|
||||
);
|
||||
let match_options = StringMatchOptions {
|
||||
case: Case::Ignore,
|
||||
..Default::default()
|
||||
};
|
||||
let mut names = fuzzy_nucleo::match_strings(&names, query, match_options);
|
||||
let mut metadata = fuzzy_nucleo::match_strings(&metadata, query, match_options);
|
||||
let sorting_key =
|
||||
|matched: &StringMatch| (Reverse(OrderedFloat(matched.score)), matched.candidate_id);
|
||||
names.sort_unstable_by_key(sorting_key);
|
||||
|
||||
@@ -15,6 +15,8 @@ use serde::{Deserialize, Serialize};
|
||||
use strum::EnumString;
|
||||
use thiserror::Error;
|
||||
|
||||
pub use language_model_core::InputTransformation;
|
||||
|
||||
pub mod batches;
|
||||
pub mod completion;
|
||||
|
||||
@@ -1182,6 +1184,10 @@ pub struct Response {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub stop_sequence: Option<String>,
|
||||
pub usage: Usage,
|
||||
/// Changes the API made to the request before the model read it. Only sent
|
||||
/// with the [`THINKING_BINDING_CONTROLS_BETA_HEADER`] beta header.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub input_transformations: Vec<InputTransformation>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
|
||||
@@ -108,6 +108,7 @@ pub async fn collect_compaction_result(
|
||||
| LanguageModelCompletionEvent::ToolUseJsonParseError { .. }
|
||||
| LanguageModelCompletionEvent::StartMessage { .. }
|
||||
| LanguageModelCompletionEvent::ReasoningDetails(_)
|
||||
| LanguageModelCompletionEvent::InputTransformations(_)
|
||||
| LanguageModelCompletionEvent::Compaction(CompactionUpdate::Started)
|
||||
| LanguageModelCompletionEvent::Compaction(CompactionUpdate::SummaryDelta(_)) => {}
|
||||
}
|
||||
@@ -728,14 +729,20 @@ impl AnthropicEventMapper {
|
||||
}
|
||||
Event::MessageStart { message } => {
|
||||
update_usage(&mut self.usage, &message.usage);
|
||||
vec![
|
||||
let mut events = vec![
|
||||
Ok(LanguageModelCompletionEvent::UsageUpdate(convert_usage(
|
||||
&self.usage,
|
||||
))),
|
||||
Ok(LanguageModelCompletionEvent::StartMessage {
|
||||
message_id: message.id,
|
||||
}),
|
||||
]
|
||||
];
|
||||
if !message.input_transformations.is_empty() {
|
||||
events.push(Ok(LanguageModelCompletionEvent::InputTransformations(
|
||||
message.input_transformations,
|
||||
)));
|
||||
}
|
||||
events
|
||||
}
|
||||
Event::MessageDelta { delta, usage } => {
|
||||
update_usage(&mut self.usage, &usage);
|
||||
@@ -1852,6 +1859,67 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_event_mapper_preserves_all_input_transformations() {
|
||||
let mut mapper = AnthropicEventMapper::new(ANTHROPIC_PROVIDER_NAME, ANTHROPIC_PROVIDER_ID);
|
||||
let start_event: Event = serde_json::from_value(serde_json::json!({
|
||||
"type": "message_start",
|
||||
"message": {
|
||||
"id": "msg_1",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": [],
|
||||
"model": "claude-fable-5-1",
|
||||
"usage": { "input_tokens": 10, "output_tokens": 0 },
|
||||
"input_transformations": [
|
||||
{
|
||||
"type": "thinking_dropped",
|
||||
"path": "messages.1.content.0",
|
||||
"reason": "prefix_binding_mismatch"
|
||||
},
|
||||
{
|
||||
"type": "thinking_mismatch_allowed",
|
||||
"path": "messages.3.content.0",
|
||||
"reason": "prefix_binding_mismatch"
|
||||
},
|
||||
{
|
||||
"type": "some_future_transformation",
|
||||
"path": "messages.5.content.0",
|
||||
"reason": "some_future_reason"
|
||||
}
|
||||
]
|
||||
}
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
let events = mapper
|
||||
.map_event(start_event)
|
||||
.into_iter()
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
events.last(),
|
||||
Some(&LanguageModelCompletionEvent::InputTransformations(vec![
|
||||
crate::InputTransformation {
|
||||
kind: "thinking_dropped".into(),
|
||||
path: "messages.1.content.0".into(),
|
||||
reason: "prefix_binding_mismatch".into(),
|
||||
},
|
||||
crate::InputTransformation {
|
||||
kind: "thinking_mismatch_allowed".into(),
|
||||
path: "messages.3.content.0".into(),
|
||||
reason: "prefix_binding_mismatch".into(),
|
||||
},
|
||||
crate::InputTransformation {
|
||||
kind: "some_future_transformation".into(),
|
||||
path: "messages.5.content.0".into(),
|
||||
reason: "some_future_reason".into(),
|
||||
},
|
||||
]))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_event_mapper_rejects_compaction_delta_before_start() {
|
||||
let mut mapper = AnthropicEventMapper::new(ANTHROPIC_PROVIDER_NAME, ANTHROPIC_PROVIDER_ID);
|
||||
|
||||
@@ -72,6 +72,8 @@ pub enum CliRequest {
|
||||
SetOpenBehavior {
|
||||
behavior: CliBehaviorSetting,
|
||||
},
|
||||
/// Print a diagnostic snapshot of the app's GPUI and platform state.
|
||||
DebugState,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
|
||||
@@ -128,6 +128,10 @@ struct Args {
|
||||
/// Will attempt to give the correct command to run
|
||||
#[arg(long)]
|
||||
system_specs: bool,
|
||||
/// Print a JSON snapshot of the running Zed's GPUI and platform state
|
||||
/// (windows, displays, frame scheduling, cursor), for debugging.
|
||||
#[arg(long)]
|
||||
debug_state: bool,
|
||||
/// Open the project in a dev container.
|
||||
///
|
||||
/// Automatically triggers "Reopen in Dev Container" if a `.devcontainer/`
|
||||
@@ -684,7 +688,11 @@ fn run() -> Result<()> {
|
||||
cwd: env::current_dir().ok(),
|
||||
};
|
||||
|
||||
tx.send(open_request)?;
|
||||
tx.send(if args.debug_state {
|
||||
CliRequest::DebugState
|
||||
} else {
|
||||
open_request
|
||||
})?;
|
||||
|
||||
while let Ok(response) = rx.recv() {
|
||||
match response {
|
||||
|
||||
@@ -62,6 +62,7 @@ struct TelemetryState {
|
||||
worktrees_with_project_type_events_sent: HashSet<WorktreeId>,
|
||||
|
||||
os_name: String,
|
||||
desktop_environment: Option<String>,
|
||||
app_version: String,
|
||||
os_version: Option<String>,
|
||||
|
||||
@@ -106,7 +107,36 @@ static DOTNET_PROJECT_FILES_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(r"^(global\.json|Directory\.Build\.props|.*\.(csproj|fsproj|vbproj|sln))$").unwrap()
|
||||
});
|
||||
|
||||
pub fn os_name() -> String {
|
||||
/// Returns the OS name, including the display server the platform connected to.
|
||||
#[cfg_attr(
|
||||
not(any(target_os = "linux", target_os = "freebsd")),
|
||||
expect(unused_variables)
|
||||
)]
|
||||
pub fn os_name(cx: &App) -> String {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
"macOS".to_string()
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
format!("Linux {}", cx.compositor_name())
|
||||
}
|
||||
#[cfg(target_os = "freebsd")]
|
||||
{
|
||||
format!("FreeBSD {}", cx.compositor_name())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
"Windows".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the OS name, guessing the display server from the environment.
|
||||
///
|
||||
/// Prefer [`os_name`] once an [`App`] exists; the platform may connect to a
|
||||
/// different display server than the environment suggests.
|
||||
pub fn guessed_os_name() -> String {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
"macOS".to_string()
|
||||
@@ -206,7 +236,10 @@ impl Telemetry {
|
||||
worktrees_with_project_type_events_sent: HashSet::new(),
|
||||
|
||||
os_version: None,
|
||||
os_name: os_name(),
|
||||
os_name: os_name(cx),
|
||||
desktop_environment: cx
|
||||
.graphical_environment()
|
||||
.and_then(|environment| environment.desktop_environment()),
|
||||
app_version: release_channel::AppVersion::global(cx).to_string(),
|
||||
subscribers: Vec::new(),
|
||||
}));
|
||||
@@ -365,7 +398,7 @@ impl Telemetry {
|
||||
state.installation_id = installation_id.map(|id| id.into());
|
||||
state.session_id = Some(session_id);
|
||||
state.app_version = release_channel::AppVersion::global(cx).to_string();
|
||||
state.os_name = os_name();
|
||||
state.os_name = os_name(cx);
|
||||
}
|
||||
|
||||
pub fn metrics_enabled(self: &Arc<Self>) -> bool {
|
||||
@@ -688,6 +721,7 @@ impl Telemetry {
|
||||
is_staff: state.is_staff,
|
||||
app_version: state.app_version.clone(),
|
||||
os_name: state.os_name.clone(),
|
||||
desktop_environment: state.desktop_environment.clone(),
|
||||
os_version: state.os_version.clone(),
|
||||
architecture: state.architecture.to_string(),
|
||||
|
||||
|
||||
@@ -148,6 +148,12 @@ fn for_snowflake(
|
||||
map.insert("app_version".to_string(), body.app_version.clone().into());
|
||||
map.insert("os_name".to_string(), body.os_name.clone().into());
|
||||
map.insert("os_version".to_string(), body.os_version.clone().into());
|
||||
if let Some(desktop_environment) = body.desktop_environment.as_ref() {
|
||||
map.insert(
|
||||
"desktop_environment".to_string(),
|
||||
desktop_environment.clone().into(),
|
||||
);
|
||||
}
|
||||
map.insert("architecture".to_string(), body.architecture.clone().into());
|
||||
map.insert(
|
||||
"release_channel".to_string(),
|
||||
|
||||
@@ -618,10 +618,10 @@ impl PickerDelegate for CommandPaletteDelegate {
|
||||
let mut matches = fuzzy_nucleo::match_strings_async(
|
||||
&candidates,
|
||||
&query,
|
||||
fuzzy_nucleo::Case::Smart,
|
||||
fuzzy_nucleo::LengthPenalty::On,
|
||||
10000,
|
||||
&Default::default(),
|
||||
fuzzy_nucleo::StringMatchOptions {
|
||||
max_results: fuzzy_nucleo::MaxResults::limit::<10_000>(),
|
||||
..Default::default()
|
||||
},
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -25,7 +25,6 @@ pub(super) struct LspColorData {
|
||||
#[derive(Debug, Default)]
|
||||
struct BufferColors {
|
||||
colors: Vec<(Range<Anchor>, DocumentColor, InlayId)>,
|
||||
inlay_colors: HashMap<InlayId, usize>,
|
||||
}
|
||||
|
||||
impl LspColorData {
|
||||
@@ -40,52 +39,48 @@ impl LspColorData {
|
||||
&mut self,
|
||||
new_render_mode: DocumentColorsRenderMode,
|
||||
) -> Option<InlaySplice> {
|
||||
if self.render_mode == new_render_mode {
|
||||
let old_render_mode = self.render_mode;
|
||||
if old_render_mode == new_render_mode {
|
||||
return None;
|
||||
}
|
||||
self.render_mode = new_render_mode;
|
||||
match new_render_mode {
|
||||
DocumentColorsRenderMode::Inlay => Some(InlaySplice {
|
||||
to_remove: Vec::new(),
|
||||
to_insert: self
|
||||
.buffer_colors
|
||||
.values()
|
||||
.flat_map(|buffer_colors| buffer_colors.colors.iter())
|
||||
.map(|(range, color, id)| {
|
||||
Inlay::color(
|
||||
id.id(),
|
||||
range.start,
|
||||
Rgba {
|
||||
r: color.color.red,
|
||||
g: color.color.green,
|
||||
b: color.color.blue,
|
||||
a: color.color.alpha,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
}),
|
||||
DocumentColorsRenderMode::None => Some(InlaySplice {
|
||||
to_remove: self
|
||||
.buffer_colors
|
||||
.drain()
|
||||
.flat_map(|(_, buffer_colors)| buffer_colors.inlay_colors)
|
||||
.map(|(id, _)| id)
|
||||
.collect(),
|
||||
to_insert: Vec::new(),
|
||||
}),
|
||||
DocumentColorsRenderMode::Border | DocumentColorsRenderMode::Background => {
|
||||
Some(InlaySplice {
|
||||
to_remove: self
|
||||
.buffer_colors
|
||||
.iter_mut()
|
||||
.flat_map(|(_, buffer_colors)| buffer_colors.inlay_colors.drain())
|
||||
.map(|(id, _)| id)
|
||||
.collect(),
|
||||
to_insert: Vec::new(),
|
||||
let to_remove = if old_render_mode == DocumentColorsRenderMode::Inlay {
|
||||
self.buffer_colors
|
||||
.values()
|
||||
.flat_map(|buffer_colors| buffer_colors.colors.iter())
|
||||
.map(|(_, _, id)| *id)
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let to_insert = match new_render_mode {
|
||||
DocumentColorsRenderMode::Inlay => self
|
||||
.buffer_colors
|
||||
.values()
|
||||
.flat_map(|buffer_colors| buffer_colors.colors.iter())
|
||||
.map(|(range, color, id)| {
|
||||
Inlay::color(
|
||||
id.id(),
|
||||
range.start,
|
||||
Rgba {
|
||||
r: color.color.red,
|
||||
g: color.color.green,
|
||||
b: color.color.blue,
|
||||
a: color.color.alpha,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
DocumentColorsRenderMode::None => {
|
||||
self.buffer_colors.clear();
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
DocumentColorsRenderMode::Border | DocumentColorsRenderMode::Background => Vec::new(),
|
||||
};
|
||||
Some(InlaySplice {
|
||||
to_remove,
|
||||
to_insert,
|
||||
})
|
||||
}
|
||||
|
||||
fn set_colors(
|
||||
@@ -97,12 +92,6 @@ impl LspColorData {
|
||||
if buffer_colors.colors == colors {
|
||||
return false;
|
||||
}
|
||||
|
||||
buffer_colors.inlay_colors = colors
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (_, _, id))| (*id, i))
|
||||
.collect();
|
||||
buffer_colors.colors = colors;
|
||||
true
|
||||
}
|
||||
@@ -438,7 +427,7 @@ mod tests {
|
||||
};
|
||||
|
||||
use futures::StreamExt;
|
||||
use gpui::{Rgba, TestAppContext};
|
||||
use gpui::{Entity, Rgba, TestAppContext, VisualTestContext};
|
||||
use language::FakeLspAdapter;
|
||||
use languages::rust_lang;
|
||||
use project::{FakeFs, Project};
|
||||
@@ -450,18 +439,12 @@ mod tests {
|
||||
};
|
||||
|
||||
use crate::{
|
||||
Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT, actions::MoveToEnd, editor_tests::init_test,
|
||||
Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT,
|
||||
actions::MoveToEnd,
|
||||
editor_settings::DocumentColorsRenderMode,
|
||||
editor_tests::{init_test, update_test_editor_settings},
|
||||
};
|
||||
|
||||
fn extract_color_inlays(editor: &Editor, cx: &gpui::App) -> Vec<Rgba> {
|
||||
editor
|
||||
.all_inlays(cx)
|
||||
.into_iter()
|
||||
.filter_map(|inlay| inlay.get_color())
|
||||
.map(Rgba::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[gpui::test(iterations = 10)]
|
||||
async fn test_document_colors(cx: &mut TestAppContext) {
|
||||
let expected_color = Rgba {
|
||||
@@ -599,6 +582,7 @@ mod tests {
|
||||
"Should have an initial inlay"
|
||||
);
|
||||
});
|
||||
assert_color_render_modes(&editor, &[expected_color], cx);
|
||||
|
||||
// opening another file in a split should not influence the LSP query counter
|
||||
workspace.update_in(cx, |workspace, window, cx| {
|
||||
@@ -768,5 +752,72 @@ mod tests {
|
||||
"Should clear all colors when the server returns an empty response"
|
||||
);
|
||||
});
|
||||
assert_color_render_modes(&editor, &[], cx);
|
||||
}
|
||||
|
||||
fn assert_color_render_modes(
|
||||
editor: &Entity<Editor>,
|
||||
expected_colors: &[Rgba],
|
||||
cx: &mut VisualTestContext,
|
||||
) {
|
||||
for _ in 0..2 {
|
||||
for render_mode in [
|
||||
DocumentColorsRenderMode::Inlay,
|
||||
DocumentColorsRenderMode::Border,
|
||||
DocumentColorsRenderMode::Inlay,
|
||||
DocumentColorsRenderMode::Background,
|
||||
DocumentColorsRenderMode::Inlay,
|
||||
DocumentColorsRenderMode::None,
|
||||
DocumentColorsRenderMode::Inlay,
|
||||
] {
|
||||
update_test_editor_settings(cx, &|settings| {
|
||||
settings.lsp_document_colors = Some(render_mode);
|
||||
});
|
||||
cx.executor().advance_clock(LSP_REQUEST_DEBOUNCE_TIMEOUT);
|
||||
cx.run_until_parked();
|
||||
editor.update_in(cx, |editor, window, cx| {
|
||||
let expected_inlays = if render_mode == DocumentColorsRenderMode::Inlay {
|
||||
expected_colors
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
assert_eq!(
|
||||
extract_color_inlays(editor, cx),
|
||||
expected_inlays,
|
||||
"Unexpected inlays in {render_mode:?} mode",
|
||||
);
|
||||
let snapshot = editor.snapshot(window, cx);
|
||||
let (actual_mode, highlights) = editor
|
||||
.colors
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.editor_display_highlights(&snapshot);
|
||||
assert_eq!(actual_mode, render_mode);
|
||||
let expected_highlights = match render_mode {
|
||||
DocumentColorsRenderMode::Border | DocumentColorsRenderMode::Background => {
|
||||
expected_colors
|
||||
}
|
||||
DocumentColorsRenderMode::None | DocumentColorsRenderMode::Inlay => &[],
|
||||
};
|
||||
assert_eq!(
|
||||
highlights
|
||||
.into_iter()
|
||||
.map(|(_, color)| Rgba::from(color))
|
||||
.collect::<Vec<_>>(),
|
||||
expected_highlights,
|
||||
"Unexpected highlights in {render_mode:?} mode",
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_color_inlays(editor: &Editor, cx: &gpui::App) -> Vec<Rgba> {
|
||||
editor
|
||||
.all_inlays(cx)
|
||||
.into_iter()
|
||||
.filter_map(|inlay| inlay.get_color())
|
||||
.map(Rgba::from)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +80,7 @@ use workspace::{
|
||||
Pane, SplitDirection, ToolbarItemLocation, ViewId, Workspace,
|
||||
item::{FollowEvent, FollowableItem, Item, ItemHandle, SaveOptions},
|
||||
register_project_item,
|
||||
security_modal::SecurityModal,
|
||||
};
|
||||
|
||||
fn display_ranges(editor: &Editor, cx: &mut Context<'_, Editor>) -> Vec<Range<DisplayPoint>> {
|
||||
@@ -46902,6 +46903,80 @@ async fn test_tab_list_indent(cx: &mut TestAppContext) {
|
||||
cx.assert_editor_state(expected);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_stay_in_restricted_mode_is_remembered(cx: &mut TestAppContext) {
|
||||
init_test(cx, |_| {});
|
||||
cx.update(|cx| {
|
||||
cx.set_global(db::AppDatabase::test_new());
|
||||
project::trusted_worktrees::init(HashMap::default(), cx);
|
||||
});
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
path!("/projects"),
|
||||
json!({
|
||||
"declined": {"main.rs": "", "nested": {"lib.rs": ""}},
|
||||
"other": {"main.rs": ""},
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
for (project_path, expect_prompt) in [
|
||||
(path!("/projects/declined"), true),
|
||||
(path!("/projects/declined"), false),
|
||||
(path!("/projects/declined/nested"), true),
|
||||
(path!("/projects/other"), true),
|
||||
(path!("/projects/other"), false),
|
||||
] {
|
||||
let project =
|
||||
Project::test_with_worktree_trust(fs.clone(), [project_path.as_ref()], cx).await;
|
||||
let worktree_store = project.read_with(cx, |project, _| project.worktree_store());
|
||||
let worktree_id = project.read_with(cx, |project, cx| {
|
||||
project
|
||||
.worktrees(cx)
|
||||
.next()
|
||||
.expect("project should have a worktree")
|
||||
.read(cx)
|
||||
.id()
|
||||
});
|
||||
let trusted_worktrees = cx
|
||||
.update(|cx| TrustedWorktrees::try_get_global(cx).expect("trust global should exist"));
|
||||
assert!(!trusted_worktrees.update(cx, |store, cx| {
|
||||
store.can_trust(&worktree_store, worktree_id, cx)
|
||||
}));
|
||||
|
||||
let (multi_workspace, window_cx) =
|
||||
cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
|
||||
let workspace = multi_workspace.read_with(window_cx, |multi_workspace, _| {
|
||||
multi_workspace.workspace().clone()
|
||||
});
|
||||
let has_modal = |window_cx: &mut VisualTestContext| {
|
||||
workspace.read_with(window_cx, |workspace, cx| {
|
||||
workspace.active_modal::<SecurityModal>(cx).is_some()
|
||||
})
|
||||
};
|
||||
|
||||
workspace.update_in(window_cx, |workspace, window, cx| {
|
||||
workspace.show_worktree_trust_security_modal(false, window, cx);
|
||||
});
|
||||
window_cx.run_until_parked();
|
||||
assert_eq!(has_modal(window_cx), expect_prompt, "{project_path}");
|
||||
|
||||
if !expect_prompt {
|
||||
window_cx.dispatch_action(workspace::ToggleWorktreeSecurity);
|
||||
window_cx.run_until_parked();
|
||||
assert!(has_modal(window_cx), "{project_path}");
|
||||
}
|
||||
window_cx.dispatch_action(workspace::ToggleWorktreeSecurity);
|
||||
window_cx.run_until_parked();
|
||||
assert!(!has_modal(window_cx), "{project_path}");
|
||||
|
||||
assert!(!trusted_worktrees.update(window_cx, |store, cx| {
|
||||
store.can_trust(&worktree_store, worktree_id, cx)
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_local_worktree_trust(cx: &mut TestAppContext) {
|
||||
init_test(cx, |_| {});
|
||||
|
||||
@@ -5083,7 +5083,7 @@ impl EditorElement {
|
||||
}
|
||||
|
||||
fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
|
||||
window.paint_layer(layout.hitbox.bounds, |window| {
|
||||
window.paint_layer(|window| {
|
||||
let scroll_top = layout.position_map.scroll_position.y;
|
||||
let gutter_bg = cx.theme().colors().editor_gutter_background;
|
||||
window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
|
||||
@@ -5406,7 +5406,7 @@ impl EditorElement {
|
||||
}
|
||||
|
||||
let line_height = layout.position_map.line_height;
|
||||
window.paint_layer(layout.gutter_hitbox.bounds, |window| {
|
||||
window.paint_layer(|window| {
|
||||
for (hunk, hitbox) in &layout.display_hunks {
|
||||
let hunk_to_paint = match hunk {
|
||||
DisplayDiffHunk::Folded { .. } => {
|
||||
@@ -5619,35 +5619,33 @@ impl EditorElement {
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
window.paint_layer(layout.gutter_hitbox.bounds, |window| {
|
||||
window.with_element_namespace("crease_toggles", |window| {
|
||||
for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
|
||||
crease_toggle.paint(window, cx);
|
||||
}
|
||||
});
|
||||
|
||||
window.with_element_namespace("expand_toggles", |window| {
|
||||
for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
|
||||
expand_toggle.paint(window, cx);
|
||||
}
|
||||
});
|
||||
|
||||
for bookmark in layout.bookmarks.iter_mut() {
|
||||
bookmark.paint(window, cx);
|
||||
}
|
||||
|
||||
for breakpoint in layout.breakpoints.iter_mut() {
|
||||
breakpoint.paint(window, cx);
|
||||
}
|
||||
|
||||
for test_indicator in layout.test_indicators.iter_mut() {
|
||||
test_indicator.paint(window, cx);
|
||||
}
|
||||
|
||||
if let Some(diff_review_button) = layout.diff_review_button.as_mut() {
|
||||
diff_review_button.paint(window, cx);
|
||||
window.with_element_namespace("crease_toggles", |window| {
|
||||
for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
|
||||
crease_toggle.paint(window, cx);
|
||||
}
|
||||
});
|
||||
|
||||
window.with_element_namespace("expand_toggles", |window| {
|
||||
for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
|
||||
expand_toggle.paint(window, cx);
|
||||
}
|
||||
});
|
||||
|
||||
for bookmark in layout.bookmarks.iter_mut() {
|
||||
bookmark.paint(window, cx);
|
||||
}
|
||||
|
||||
for breakpoint in layout.breakpoints.iter_mut() {
|
||||
breakpoint.paint(window, cx);
|
||||
}
|
||||
|
||||
for test_indicator in layout.test_indicators.iter_mut() {
|
||||
test_indicator.paint(window, cx);
|
||||
}
|
||||
|
||||
if let Some(diff_review_button) = layout.diff_review_button.as_mut() {
|
||||
diff_review_button.paint(window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
fn paint_gutter_highlights(
|
||||
@@ -5685,7 +5683,7 @@ impl EditorElement {
|
||||
|
||||
let highlight_width = 0.275 * layout.position_map.line_height;
|
||||
let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
|
||||
window.paint_layer(layout.gutter_hitbox.bounds, |window| {
|
||||
window.paint_layer(|window| {
|
||||
for (range, color) in &layout.highlighted_gutter_ranges {
|
||||
let start_row = if range.start.row() < layout.visible_display_row_range.start {
|
||||
layout.visible_display_row_range.start - DisplayRow(1)
|
||||
@@ -5729,11 +5727,9 @@ impl EditorElement {
|
||||
return;
|
||||
};
|
||||
|
||||
window.paint_layer(layout.gutter_hitbox.bounds, |window| {
|
||||
for mut blame_element in blamed_display_rows.into_iter() {
|
||||
blame_element.paint(window, cx);
|
||||
}
|
||||
})
|
||||
for mut blame_element in blamed_display_rows.into_iter() {
|
||||
blame_element.paint(window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
fn populate_point_diagnostics(
|
||||
@@ -5975,7 +5971,7 @@ impl EditorElement {
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> SmallVec<[Range<DisplayPoint>; 32]> {
|
||||
window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
|
||||
window.paint_layer(|window| {
|
||||
let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
|
||||
let line_end_overshoot = 0.15 * layout.position_map.line_height;
|
||||
for (range, color) in &layout.highlighted_ranges {
|
||||
@@ -6072,7 +6068,7 @@ impl EditorElement {
|
||||
// A softer than perfect black
|
||||
let redaction_color = gpui::rgb(0x0e1111);
|
||||
|
||||
window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
|
||||
window.paint_layer(|window| {
|
||||
for range in layout.redacted_ranges.iter() {
|
||||
self.paint_highlighted_range(
|
||||
range.clone(),
|
||||
@@ -6173,7 +6169,7 @@ impl EditorElement {
|
||||
},
|
||||
};
|
||||
|
||||
window.paint_layer(hitbox.bounds, |window| {
|
||||
window.paint_layer(|window| {
|
||||
window.paint_quad(quad(
|
||||
hitbox.bounds,
|
||||
Corners::default(),
|
||||
@@ -6676,9 +6672,7 @@ impl EditorElement {
|
||||
|
||||
fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
|
||||
if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
|
||||
window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
|
||||
blame_layout.element.paint(window, cx);
|
||||
})
|
||||
blame_layout.element.paint(window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6689,9 +6683,7 @@ impl EditorElement {
|
||||
cx: &mut App,
|
||||
) {
|
||||
if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
|
||||
window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
|
||||
inline_code_actions.paint(window, cx);
|
||||
})
|
||||
inline_code_actions.paint(window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6711,54 +6703,48 @@ impl EditorElement {
|
||||
let minimap_hitbox = layout.thumb_layout.hitbox.clone();
|
||||
let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
|
||||
|
||||
window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
|
||||
window.with_element_namespace("minimap", |window| {
|
||||
layout.minimap.paint(window, cx);
|
||||
if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
|
||||
let minimap_thumb_color = match layout.thumb_layout.thumb_state {
|
||||
ScrollbarThumbState::Idle => {
|
||||
cx.theme().colors().minimap_thumb_background
|
||||
}
|
||||
ScrollbarThumbState::Hovered => {
|
||||
cx.theme().colors().minimap_thumb_hover_background
|
||||
}
|
||||
ScrollbarThumbState::Dragging => {
|
||||
cx.theme().colors().minimap_thumb_active_background
|
||||
}
|
||||
};
|
||||
let minimap_thumb_border = match layout.thumb_border_style {
|
||||
MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
|
||||
MinimapThumbBorder::LeftOnly => Edges {
|
||||
left: ScrollbarLayout::BORDER_WIDTH,
|
||||
..Default::default()
|
||||
},
|
||||
MinimapThumbBorder::LeftOpen => Edges {
|
||||
right: ScrollbarLayout::BORDER_WIDTH,
|
||||
top: ScrollbarLayout::BORDER_WIDTH,
|
||||
bottom: ScrollbarLayout::BORDER_WIDTH,
|
||||
..Default::default()
|
||||
},
|
||||
MinimapThumbBorder::RightOpen => Edges {
|
||||
left: ScrollbarLayout::BORDER_WIDTH,
|
||||
top: ScrollbarLayout::BORDER_WIDTH,
|
||||
bottom: ScrollbarLayout::BORDER_WIDTH,
|
||||
..Default::default()
|
||||
},
|
||||
MinimapThumbBorder::None => Default::default(),
|
||||
};
|
||||
window.with_element_namespace("minimap", |window| {
|
||||
layout.minimap.paint(window, cx);
|
||||
if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
|
||||
let minimap_thumb_color = match layout.thumb_layout.thumb_state {
|
||||
ScrollbarThumbState::Idle => cx.theme().colors().minimap_thumb_background,
|
||||
ScrollbarThumbState::Hovered => {
|
||||
cx.theme().colors().minimap_thumb_hover_background
|
||||
}
|
||||
ScrollbarThumbState::Dragging => {
|
||||
cx.theme().colors().minimap_thumb_active_background
|
||||
}
|
||||
};
|
||||
let minimap_thumb_border = match layout.thumb_border_style {
|
||||
MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
|
||||
MinimapThumbBorder::LeftOnly => Edges {
|
||||
left: ScrollbarLayout::BORDER_WIDTH,
|
||||
..Default::default()
|
||||
},
|
||||
MinimapThumbBorder::LeftOpen => Edges {
|
||||
right: ScrollbarLayout::BORDER_WIDTH,
|
||||
top: ScrollbarLayout::BORDER_WIDTH,
|
||||
bottom: ScrollbarLayout::BORDER_WIDTH,
|
||||
..Default::default()
|
||||
},
|
||||
MinimapThumbBorder::RightOpen => Edges {
|
||||
left: ScrollbarLayout::BORDER_WIDTH,
|
||||
top: ScrollbarLayout::BORDER_WIDTH,
|
||||
bottom: ScrollbarLayout::BORDER_WIDTH,
|
||||
..Default::default()
|
||||
},
|
||||
MinimapThumbBorder::None => Default::default(),
|
||||
};
|
||||
|
||||
window.paint_layer(minimap_hitbox.bounds, |window| {
|
||||
window.paint_quad(quad(
|
||||
thumb_bounds,
|
||||
Corners::default(),
|
||||
minimap_thumb_color,
|
||||
minimap_thumb_border,
|
||||
cx.theme().colors().minimap_thumb_border,
|
||||
BorderStyle::Solid,
|
||||
));
|
||||
});
|
||||
}
|
||||
});
|
||||
window.paint_quad(quad(
|
||||
thumb_bounds,
|
||||
Corners::default(),
|
||||
minimap_thumb_color,
|
||||
minimap_thumb_border,
|
||||
cx.theme().colors().minimap_thumb_border,
|
||||
BorderStyle::Solid,
|
||||
));
|
||||
}
|
||||
});
|
||||
|
||||
if dragging_minimap {
|
||||
|
||||
@@ -432,42 +432,36 @@ impl StickyHeaders {
|
||||
let line_height = layout.position_map.line_height;
|
||||
|
||||
for line in self.lines.iter_mut().rev() {
|
||||
window.paint_layer(
|
||||
Bounds::new(
|
||||
window.paint_layer(|window| {
|
||||
let gutter_bounds = Bounds::new(
|
||||
layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
|
||||
size(line.hitbox.size.width, line_height),
|
||||
),
|
||||
|window| {
|
||||
let gutter_bounds = Bounds::new(
|
||||
layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset),
|
||||
size(layout.gutter_hitbox.size.width, line_height),
|
||||
);
|
||||
window.paint_quad(fill(gutter_bounds, self.gutter_background));
|
||||
size(layout.gutter_hitbox.size.width, line_height),
|
||||
);
|
||||
window.paint_quad(fill(gutter_bounds, self.gutter_background));
|
||||
|
||||
let text_bounds = Bounds::new(
|
||||
layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
|
||||
size(line.available_text_width, line_height),
|
||||
);
|
||||
window.paint_quad(fill(text_bounds, self.content_background));
|
||||
let text_bounds = Bounds::new(
|
||||
layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset),
|
||||
size(line.available_text_width, line_height),
|
||||
);
|
||||
window.paint_quad(fill(text_bounds, self.content_background));
|
||||
|
||||
if line.hitbox.is_hovered(window) {
|
||||
let hover_overlay = cx.theme().colors().panel_overlay_hover;
|
||||
window.paint_quad(fill(gutter_bounds, hover_overlay));
|
||||
window.paint_quad(fill(text_bounds, hover_overlay));
|
||||
}
|
||||
if line.hitbox.is_hovered(window) {
|
||||
let hover_overlay = cx.theme().colors().panel_overlay_hover;
|
||||
window.paint_quad(fill(gutter_bounds, hover_overlay));
|
||||
window.paint_quad(fill(text_bounds, hover_overlay));
|
||||
}
|
||||
|
||||
line.paint(
|
||||
layout,
|
||||
self.gutter_right_padding,
|
||||
line.available_text_width,
|
||||
layout.content_origin,
|
||||
line_height,
|
||||
whitespace_setting,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
},
|
||||
);
|
||||
line.paint(
|
||||
layout,
|
||||
self.gutter_right_padding,
|
||||
line.available_text_width,
|
||||
layout.content_origin,
|
||||
line_height,
|
||||
whitespace_setting,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
});
|
||||
|
||||
window.set_cursor_style(CursorStyle::IBeam, &line.hitbox);
|
||||
}
|
||||
|
||||
@@ -49,8 +49,8 @@ pub fn init(cx: &mut App) {
|
||||
cx.observe_new(|workspace: &mut Workspace, _, _| {
|
||||
workspace
|
||||
.register_action(|_, _: &CopySystemSpecsIntoClipboard, window, cx| {
|
||||
let specs =
|
||||
SystemSpecs::new(window, cx, telemetry::os_name(), telemetry::os_version());
|
||||
let os_name = telemetry::os_name(cx);
|
||||
let specs = SystemSpecs::new(window, cx, os_name, telemetry::os_version());
|
||||
|
||||
cx.spawn_in(window, async move |_, cx| {
|
||||
let specs = specs.await.to_string();
|
||||
@@ -85,8 +85,8 @@ pub fn init(cx: &mut App) {
|
||||
cx.open_url(REQUEST_FEATURE_URL);
|
||||
})
|
||||
.register_action(move |_, _: &FileBugReport, window, cx| {
|
||||
let specs =
|
||||
SystemSpecs::new(window, cx, telemetry::os_name(), telemetry::os_version());
|
||||
let os_name = telemetry::os_name(cx);
|
||||
let specs = SystemSpecs::new(window, cx, os_name, telemetry::os_version());
|
||||
cx.spawn_in(window, async move |_, cx| {
|
||||
let specs = specs.await;
|
||||
cx.update(|_, cx| {
|
||||
@@ -97,8 +97,8 @@ pub fn init(cx: &mut App) {
|
||||
.detach();
|
||||
})
|
||||
.register_action(move |_, _: &EmailZed, window, cx| {
|
||||
let specs =
|
||||
SystemSpecs::new(window, cx, telemetry::os_name(), telemetry::os_version());
|
||||
let os_name = telemetry::os_name(cx);
|
||||
let specs = SystemSpecs::new(window, cx, os_name, telemetry::os_version());
|
||||
cx.spawn_in(window, async move |_, cx| {
|
||||
let specs = specs.await;
|
||||
cx.update(|_, cx| {
|
||||
|
||||
@@ -801,7 +801,6 @@ fn matching_history_items<'a>(
|
||||
);
|
||||
let mut matching_history_paths = HashMap::default();
|
||||
for (worktree, candidates) in history_items_by_worktrees {
|
||||
let max_results = candidates.len() + 1;
|
||||
let worktree_root_name = worktree_name_by_id
|
||||
.as_ref()
|
||||
.and_then(|w| w.get(&worktree).cloned());
|
||||
@@ -812,8 +811,7 @@ fn matching_history_items<'a>(
|
||||
worktree.to_usize(),
|
||||
worktree_root_name,
|
||||
query.path_query(),
|
||||
fuzzy_nucleo::Case::Ignore,
|
||||
max_results,
|
||||
Default::default(),
|
||||
path_style,
|
||||
)
|
||||
.into_iter()
|
||||
@@ -1358,9 +1356,11 @@ impl FileFinderDelegate {
|
||||
candidate_sets.as_slice(),
|
||||
query.path_query(),
|
||||
&relative_to,
|
||||
fuzzy_nucleo::Case::Ignore,
|
||||
100,
|
||||
&cancel_flag,
|
||||
fuzzy_nucleo::PathMatchOptions {
|
||||
max_results: fuzzy_nucleo::MaxResults::limit::<100>(),
|
||||
cancel_flag: Some(&cancel_flag),
|
||||
..Default::default()
|
||||
},
|
||||
cx.background_executor().clone(),
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -5734,6 +5734,17 @@ fn select_range_in_active_editor(
|
||||
async fn test_seed_query_from_editor_selection(cx: &mut TestAppContext) {
|
||||
let app_state = init_test(cx);
|
||||
|
||||
cx.update(|cx| {
|
||||
let settings = *FileFinderSettings::get_global(cx);
|
||||
FileFinderSettings::override_global(
|
||||
FileFinderSettings {
|
||||
prefill_query_from_selection: true,
|
||||
..settings
|
||||
},
|
||||
cx,
|
||||
);
|
||||
});
|
||||
|
||||
app_state
|
||||
.fs
|
||||
.as_fake()
|
||||
@@ -5773,6 +5784,17 @@ async fn test_seed_query_from_editor_selection(cx: &mut TestAppContext) {
|
||||
async fn test_no_seed_query_without_selection(cx: &mut TestAppContext) {
|
||||
let app_state = init_test(cx);
|
||||
|
||||
cx.update(|cx| {
|
||||
let settings = *FileFinderSettings::get_global(cx);
|
||||
FileFinderSettings::override_global(
|
||||
FileFinderSettings {
|
||||
prefill_query_from_selection: true,
|
||||
..settings
|
||||
},
|
||||
cx,
|
||||
);
|
||||
});
|
||||
|
||||
app_state
|
||||
.fs
|
||||
.as_fake()
|
||||
@@ -5808,6 +5830,17 @@ async fn test_no_seed_query_without_selection(cx: &mut TestAppContext) {
|
||||
async fn test_seed_query_flattens_multiline_selection(cx: &mut TestAppContext) {
|
||||
let app_state = init_test(cx);
|
||||
|
||||
cx.update(|cx| {
|
||||
let settings = *FileFinderSettings::get_global(cx);
|
||||
FileFinderSettings::override_global(
|
||||
FileFinderSettings {
|
||||
prefill_query_from_selection: true,
|
||||
..settings
|
||||
},
|
||||
cx,
|
||||
);
|
||||
});
|
||||
|
||||
app_state
|
||||
.fs
|
||||
.as_fake()
|
||||
|
||||
@@ -19,6 +19,8 @@ pub use diagnostics::{
|
||||
WatchDiagnosticEvent, WatchRecording, WatchRoot, WatchSnapshot, WatcherSnapshot,
|
||||
};
|
||||
|
||||
const MAX_DISPATCH_BATCH_SIZE: usize = 256;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
|
||||
pub enum OsWatcherKind {
|
||||
Native,
|
||||
@@ -964,6 +966,7 @@ impl OsWatcher {
|
||||
let mut rescan_history = diagnostics::RescanHistory::default();
|
||||
while let Ok(first) = event_rx.recv().await {
|
||||
dispatch_batch(kind, &state, &mut rescan_history, first, &event_rx);
|
||||
smol::future::yield_now().await;
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1454,7 +1457,12 @@ fn dispatch_batch(
|
||||
// all dispatched; ordinary events still run.
|
||||
let mut rescan_dispatched = false;
|
||||
|
||||
for event in std::iter::once(first).chain(std::iter::from_fn(|| event_rx.try_recv().ok())) {
|
||||
// The backend can keep producing events faster than we dispatch them, so
|
||||
// don't wait for an empty queue before giving other tasks a turn.
|
||||
for event in std::iter::once(first)
|
||||
.chain(std::iter::from_fn(|| event_rx.try_recv().ok()))
|
||||
.take(MAX_DISPATCH_BATCH_SIZE)
|
||||
{
|
||||
if event
|
||||
.as_ref()
|
||||
.is_ok_and(|event| event.need_rescan() && event.paths.is_empty())
|
||||
@@ -2255,6 +2263,43 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_batches_are_bounded_without_losing_or_reordering_events() {
|
||||
let (watcher, fired) = recording_watcher();
|
||||
let (event_tx, event_rx) = async_channel::unbounded();
|
||||
let rescan = || notify::Event::new(EventKind::Other).set_flag(notify::event::Flag::Rescan);
|
||||
for _ in 0..MAX_DISPATCH_BATCH_SIZE {
|
||||
event_tx.try_send(Ok(rescan())).expect("enqueue rescan");
|
||||
}
|
||||
let expected = (0..MAX_DISPATCH_BATCH_SIZE * 2 + 3)
|
||||
.map(|index| if index % 2 == 0 { "/repo/a" } else { "/repo/b" })
|
||||
.collect::<Vec<_>>();
|
||||
for path in &expected {
|
||||
event_tx
|
||||
.try_send(Ok(modify_event(&format!("{path}/file.txt"))))
|
||||
.expect("enqueue event");
|
||||
}
|
||||
|
||||
let first = event_rx.try_recv().expect("first rescan");
|
||||
watcher.dispatch_batch(first, &event_rx);
|
||||
assert_eq!(fired.lock().len(), 3);
|
||||
assert_eq!(event_rx.len(), expected.len());
|
||||
fired.lock().clear();
|
||||
|
||||
let first = event_rx.try_recv().expect("first event");
|
||||
watcher.dispatch_batch(first, &event_rx);
|
||||
assert_eq!(
|
||||
fired.lock().as_slice(),
|
||||
&expected[..MAX_DISPATCH_BATCH_SIZE]
|
||||
);
|
||||
assert_eq!(event_rx.len(), expected.len() - MAX_DISPATCH_BATCH_SIZE);
|
||||
|
||||
while let Ok(first) = event_rx.try_recv() {
|
||||
watcher.dispatch_batch(first, &event_rx);
|
||||
}
|
||||
assert_eq!(fired.lock().as_slice(), expected.as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_rescans_are_coalesced_without_dropping_normal_events() {
|
||||
let (watcher, fired) = recording_watcher();
|
||||
|
||||
@@ -178,10 +178,11 @@ fn bench_string_matching(criterion: &mut Criterion) {
|
||||
foreground_executor.block_on(fuzzy_nucleo::match_strings_async(
|
||||
&candidates,
|
||||
query,
|
||||
fuzzy_nucleo::Case::Ignore,
|
||||
fuzzy_nucleo::LengthPenalty::On,
|
||||
size,
|
||||
&cancel,
|
||||
fuzzy_nucleo::StringMatchOptions {
|
||||
cancel_flag: Some(&cancel),
|
||||
case: fuzzy_nucleo::Case::Ignore,
|
||||
..Default::default()
|
||||
},
|
||||
background_executor.clone(),
|
||||
))
|
||||
},
|
||||
@@ -304,8 +305,10 @@ fn bench_path_matching(criterion: &mut Criterion) {
|
||||
0,
|
||||
None,
|
||||
query,
|
||||
case,
|
||||
size,
|
||||
fuzzy_nucleo::PathMatchOptions {
|
||||
case,
|
||||
..Default::default()
|
||||
},
|
||||
PathStyle::Unix,
|
||||
)
|
||||
},
|
||||
|
||||
@@ -2,16 +2,29 @@ mod matcher;
|
||||
mod paths;
|
||||
mod strings;
|
||||
|
||||
use std::{
|
||||
num::NonZeroUsize,
|
||||
sync::atomic::{self, AtomicBool},
|
||||
};
|
||||
|
||||
use fuzzy::CharBag;
|
||||
use nucleo::pattern::{AtomKind, CaseMatching, Normalization, Pattern};
|
||||
|
||||
pub use paths::{
|
||||
PathMatch, PathMatchCandidate, PathMatchCandidateSet, match_fixed_path_set, match_path_sets,
|
||||
PathMatch, PathMatchCandidate, PathMatchCandidateSet, PathMatchOptions, match_fixed_path_set,
|
||||
match_path_sets,
|
||||
};
|
||||
pub use strings::{
|
||||
StringMatch, StringMatchCandidate, StringMatchOptions, match_strings, match_strings_async,
|
||||
};
|
||||
pub use strings::{StringMatch, StringMatchCandidate, match_strings, match_strings_async};
|
||||
|
||||
pub(crate) struct Cancelled;
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn is_cancelled(cancel_flag: Option<&AtomicBool>, ordering: atomic::Ordering) -> bool {
|
||||
cancel_flag.is_some_and(|flag| flag.load(ordering))
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Case {
|
||||
Smart,
|
||||
@@ -32,6 +45,29 @@ impl Case {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many of the best matches to return.
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub enum MaxResults {
|
||||
/// Every match.
|
||||
#[default]
|
||||
All,
|
||||
/// At most this many.
|
||||
Limit(NonZeroUsize),
|
||||
}
|
||||
|
||||
impl MaxResults {
|
||||
pub const fn limit<const LIMIT: usize>() -> Self {
|
||||
Self::Limit(const { NonZeroUsize::new(LIMIT).expect("limit must be non-zero") })
|
||||
}
|
||||
|
||||
pub(crate) fn resolve(self, candidate_count: usize) -> usize {
|
||||
match self {
|
||||
Self::All => candidate_count,
|
||||
Self::Limit(limit) => limit.get().min(candidate_count),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LengthPenalty {
|
||||
On,
|
||||
|
||||
@@ -14,7 +14,10 @@ use nucleo::pattern::Pattern;
|
||||
use fuzzy::CharBag;
|
||||
|
||||
use crate::matcher::{self, LENGTH_PENALTY};
|
||||
use crate::{Cancelled, Case, Query, case_penalty, count_case_mismatches, positions_from_sorted};
|
||||
use crate::{
|
||||
Cancelled, Case, MaxResults, Query, case_penalty, count_case_mismatches, is_cancelled,
|
||||
positions_from_sorted,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PathMatchCandidate<'a> {
|
||||
@@ -42,6 +45,27 @@ impl<'a> PathMatchCandidate<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Options for [`match_fixed_path_set`] and [`match_path_sets`].
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub struct PathMatchOptions<'a> {
|
||||
/// Defaults to all matches. Prefer a limit when matching whole worktrees.
|
||||
pub max_results: MaxResults,
|
||||
/// Return nothing if this gets set while matching.
|
||||
pub cancel_flag: Option<&'a AtomicBool>,
|
||||
/// Defaults to [`Case::Ignore`].
|
||||
pub case: Case,
|
||||
}
|
||||
|
||||
impl Default for PathMatchOptions<'_> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_results: MaxResults::All,
|
||||
cancel_flag: None,
|
||||
case: Case::Ignore,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PathMatch {
|
||||
pub score: f64,
|
||||
@@ -157,7 +181,7 @@ fn path_match_helper<'a>(
|
||||
root_is_file: bool,
|
||||
relative_to: &Option<Arc<RelPath>>,
|
||||
path_style: PathStyle,
|
||||
cancel_flag: &AtomicBool,
|
||||
cancel_flag: Option<&AtomicBool>,
|
||||
) -> Result<(), Cancelled> {
|
||||
let mut candidate_buf = if !path_prefix.is_empty() && !root_is_file {
|
||||
let mut s = path_prefix.display(path_style).to_string();
|
||||
@@ -173,7 +197,7 @@ fn path_match_helper<'a>(
|
||||
for candidate in candidates {
|
||||
buf.clear();
|
||||
matched_chars.clear();
|
||||
if cancel_flag.load(atomic::Ordering::Relaxed) {
|
||||
if is_cancelled(cancel_flag, atomic::Ordering::Relaxed) {
|
||||
return Err(Cancelled);
|
||||
}
|
||||
|
||||
@@ -240,10 +264,14 @@ pub fn match_fixed_path_set(
|
||||
worktree_id: usize,
|
||||
worktree_root_name: Option<Arc<RelPath>>,
|
||||
query: &str,
|
||||
case: Case,
|
||||
max_results: usize,
|
||||
options: PathMatchOptions<'_>,
|
||||
path_style: PathStyle,
|
||||
) -> Vec<PathMatch> {
|
||||
let PathMatchOptions {
|
||||
max_results,
|
||||
cancel_flag,
|
||||
case,
|
||||
} = options;
|
||||
let Some(query) = Query::build(query, case) else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -252,13 +280,14 @@ pub fn match_fixed_path_set(
|
||||
config.set_match_paths();
|
||||
let mut matcher = matcher::get_matcher(config);
|
||||
|
||||
let max_results = max_results.resolve(candidates.len());
|
||||
let root_is_file = worktree_root_name.is_some() && candidates.iter().all(|c| c.path.is_empty());
|
||||
|
||||
let path_prefix = worktree_root_name.unwrap_or_else(|| RelPath::empty_arc());
|
||||
|
||||
let mut results = Vec::new();
|
||||
|
||||
path_match_helper(
|
||||
let outcome = path_match_helper(
|
||||
&mut matcher,
|
||||
&query,
|
||||
candidates.into_iter(),
|
||||
@@ -268,11 +297,13 @@ pub fn match_fixed_path_set(
|
||||
root_is_file,
|
||||
&None,
|
||||
path_style,
|
||||
&AtomicBool::new(false),
|
||||
)
|
||||
.ok();
|
||||
gpui_util::truncate_to_bottom_n_sorted_by(&mut results, max_results, &|a, b| b.cmp(a));
|
||||
cancel_flag,
|
||||
);
|
||||
matcher::return_matcher(matcher);
|
||||
if outcome.is_err() || is_cancelled(cancel_flag, atomic::Ordering::Acquire) {
|
||||
return Vec::new();
|
||||
}
|
||||
gpui_util::truncate_to_bottom_n_sorted_by(&mut results, max_results, &|a, b| b.cmp(a));
|
||||
results
|
||||
}
|
||||
|
||||
@@ -280,11 +311,14 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>(
|
||||
candidate_sets: &'a [Set],
|
||||
query: &str,
|
||||
relative_to: &Option<Arc<RelPath>>,
|
||||
case: Case,
|
||||
max_results: usize,
|
||||
cancel_flag: &AtomicBool,
|
||||
options: PathMatchOptions<'_>,
|
||||
executor: BackgroundExecutor,
|
||||
) -> Vec<PathMatch> {
|
||||
let PathMatchOptions {
|
||||
max_results,
|
||||
cancel_flag,
|
||||
case,
|
||||
} = options;
|
||||
let path_count: usize = candidate_sets.iter().map(|s| s.len()).sum();
|
||||
if path_count == 0 {
|
||||
return Vec::new();
|
||||
@@ -302,10 +336,11 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>(
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let max_results = max_results.resolve(path_count);
|
||||
let num_cpus = executor.num_cpus().min(path_count);
|
||||
let segment_size = path_count.div_ceil(num_cpus);
|
||||
let mut segment_results = (0..num_cpus)
|
||||
.map(|_| Vec::with_capacity(max_results))
|
||||
.map(|_| Vec::with_capacity(max_results.min(segment_size)))
|
||||
.collect::<Vec<_>>();
|
||||
let mut config = nucleo::Config::DEFAULT;
|
||||
config.set_match_paths();
|
||||
@@ -361,7 +396,7 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>(
|
||||
.await;
|
||||
|
||||
matcher::return_matchers(matchers);
|
||||
if cancel_flag.load(atomic::Ordering::Acquire) {
|
||||
if is_cancelled(cancel_flag, atomic::Ordering::Acquire) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
@@ -369,3 +404,111 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>(
|
||||
gpui_util::truncate_to_bottom_n_sorted_by(&mut results, max_results, &|a, b| b.cmp(a));
|
||||
results
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct TestCandidateSet {
|
||||
candidates: Vec<PathMatchCandidate<'static>>,
|
||||
}
|
||||
|
||||
impl<'a> PathMatchCandidateSet<'a> for TestCandidateSet {
|
||||
type Candidates = std::iter::Cloned<std::slice::Iter<'a, PathMatchCandidate<'a>>>;
|
||||
|
||||
fn id(&self) -> usize {
|
||||
0
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.candidates.len()
|
||||
}
|
||||
|
||||
fn root_is_file(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn prefix(&self) -> Arc<RelPath> {
|
||||
RelPath::empty_arc()
|
||||
}
|
||||
|
||||
fn candidates(&'a self, start: usize) -> Self::Candidates {
|
||||
self.candidates
|
||||
.get(start..)
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn path_style(&self) -> PathStyle {
|
||||
PathStyle::Unix
|
||||
}
|
||||
}
|
||||
|
||||
fn candidates(paths: &[&'static str]) -> Vec<PathMatchCandidate<'static>> {
|
||||
paths
|
||||
.iter()
|
||||
.map(|&path| {
|
||||
PathMatchCandidate::new(RelPath::from_unix_str(path).unwrap(), false, None)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fixed_path_set_cancellation() {
|
||||
let paths = ["src/main.rs", "src/lib.rs"];
|
||||
let uncancelled = match_fixed_path_set(
|
||||
candidates(&paths),
|
||||
0,
|
||||
None,
|
||||
"main",
|
||||
Default::default(),
|
||||
PathStyle::Unix,
|
||||
);
|
||||
assert_eq!(uncancelled.len(), 1);
|
||||
|
||||
let cancel = AtomicBool::new(true);
|
||||
let cancelled = match_fixed_path_set(
|
||||
candidates(&paths),
|
||||
0,
|
||||
None,
|
||||
"main",
|
||||
PathMatchOptions {
|
||||
cancel_flag: Some(&cancel),
|
||||
..Default::default()
|
||||
},
|
||||
PathStyle::Unix,
|
||||
);
|
||||
assert!(cancelled.is_empty());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_path_sets_cancellation(executor: BackgroundExecutor) {
|
||||
let candidate_sets = [TestCandidateSet {
|
||||
candidates: candidates(&["src/main.rs", "src/lib.rs"]),
|
||||
}];
|
||||
let uncancelled = match_path_sets(
|
||||
&candidate_sets,
|
||||
"main",
|
||||
&None,
|
||||
Default::default(),
|
||||
executor.clone(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(uncancelled.len(), 1);
|
||||
|
||||
let cancel = AtomicBool::new(true);
|
||||
let cancelled = match_path_sets(
|
||||
&candidate_sets,
|
||||
"main",
|
||||
&None,
|
||||
PathMatchOptions {
|
||||
cancel_flag: Some(&cancel),
|
||||
..Default::default()
|
||||
},
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
assert!(cancelled.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
+162
-215
@@ -10,7 +10,8 @@ use gpui::{BackgroundExecutor, SharedString};
|
||||
use nucleo::Utf32Str;
|
||||
|
||||
use crate::{
|
||||
Cancelled, Case, LengthPenalty, Query, case_penalty, count_case_mismatches,
|
||||
Cancelled, Case, LengthPenalty, MaxResults, Query, case_penalty, count_case_mismatches,
|
||||
is_cancelled,
|
||||
matcher::{self, LENGTH_PENALTY},
|
||||
positions_from_sorted,
|
||||
};
|
||||
@@ -97,21 +98,49 @@ impl Ord for StringMatch {
|
||||
}
|
||||
}
|
||||
|
||||
/// Options for [`match_strings`] and [`match_strings_async`].
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub struct StringMatchOptions<'a> {
|
||||
/// Defaults to all matches.
|
||||
pub max_results: MaxResults,
|
||||
/// Return nothing if this gets set while matching. Empty queries ignore it.
|
||||
pub cancel_flag: Option<&'a AtomicBool>,
|
||||
/// Defaults to [`Case::Smart`].
|
||||
pub case: Case,
|
||||
/// Defaults to [`LengthPenalty::On`].
|
||||
pub length_penalty: LengthPenalty,
|
||||
}
|
||||
|
||||
impl Default for StringMatchOptions<'_> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_results: MaxResults::All,
|
||||
cancel_flag: None,
|
||||
case: Case::Smart,
|
||||
length_penalty: LengthPenalty::On,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn match_strings_async<T>(
|
||||
candidates: &[T],
|
||||
query: &str,
|
||||
case: Case,
|
||||
length_penalty: LengthPenalty,
|
||||
max_results: usize,
|
||||
cancel_flag: &AtomicBool,
|
||||
options: StringMatchOptions<'_>,
|
||||
executor: BackgroundExecutor,
|
||||
) -> Vec<StringMatch>
|
||||
where
|
||||
T: Borrow<StringMatchCandidate> + Sync,
|
||||
{
|
||||
if candidates.is_empty() || max_results == 0 {
|
||||
let StringMatchOptions {
|
||||
max_results,
|
||||
cancel_flag,
|
||||
case,
|
||||
length_penalty,
|
||||
} = options;
|
||||
if candidates.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let max_results = max_results.resolve(candidates.len());
|
||||
|
||||
let Some(query) = Query::build(query, case) else {
|
||||
return empty_query_results(candidates, max_results);
|
||||
@@ -120,8 +149,9 @@ where
|
||||
let num_cpus = executor.num_cpus().min(candidates.len());
|
||||
let base_size = candidates.len() / num_cpus;
|
||||
let remainder = candidates.len() % num_cpus;
|
||||
let segment_capacity = max_results.min(candidates.len().div_ceil(num_cpus));
|
||||
let mut segment_results = (0..num_cpus)
|
||||
.map(|_| Vec::with_capacity(max_results.min(candidates.len())))
|
||||
.map(|_| Vec::with_capacity(segment_capacity))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let config = nucleo::Config::DEFAULT;
|
||||
@@ -156,7 +186,7 @@ where
|
||||
|
||||
matcher::return_matchers(matchers);
|
||||
|
||||
if cancel_flag.load(atomic::Ordering::Acquire) {
|
||||
if is_cancelled(cancel_flag, atomic::Ordering::Acquire) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
@@ -168,16 +198,21 @@ where
|
||||
pub fn match_strings<T>(
|
||||
candidates: &[T],
|
||||
query: &str,
|
||||
case: Case,
|
||||
length_penalty: LengthPenalty,
|
||||
max_results: usize,
|
||||
options: StringMatchOptions<'_>,
|
||||
) -> Vec<StringMatch>
|
||||
where
|
||||
T: Borrow<StringMatchCandidate>,
|
||||
{
|
||||
if candidates.is_empty() || max_results == 0 {
|
||||
let StringMatchOptions {
|
||||
max_results,
|
||||
cancel_flag,
|
||||
case,
|
||||
length_penalty,
|
||||
} = options;
|
||||
if candidates.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let max_results = max_results.resolve(candidates.len());
|
||||
|
||||
let Some(query) = Query::build(query, case) else {
|
||||
return empty_query_results(candidates, max_results);
|
||||
@@ -185,19 +220,21 @@ where
|
||||
|
||||
let config = nucleo::Config::DEFAULT;
|
||||
let mut matcher = matcher::get_matcher(config);
|
||||
let mut results = Vec::with_capacity(max_results.min(candidates.len()));
|
||||
let mut results = Vec::with_capacity(max_results);
|
||||
|
||||
match_string_helper(
|
||||
let outcome = match_string_helper(
|
||||
candidates,
|
||||
&query,
|
||||
&mut matcher,
|
||||
length_penalty,
|
||||
&mut results,
|
||||
&AtomicBool::new(false),
|
||||
)
|
||||
.ok();
|
||||
cancel_flag,
|
||||
);
|
||||
|
||||
matcher::return_matcher(matcher);
|
||||
if outcome.is_err() || is_cancelled(cancel_flag, atomic::Ordering::Acquire) {
|
||||
return Vec::new();
|
||||
}
|
||||
gpui_util::truncate_to_bottom_n_sorted_by(&mut results, max_results, &|a, b| b.cmp(a));
|
||||
results
|
||||
}
|
||||
@@ -227,7 +264,7 @@ fn match_string_helper<T>(
|
||||
matcher: &mut nucleo::Matcher,
|
||||
length_penalty: LengthPenalty,
|
||||
results: &mut Vec<StringMatch>,
|
||||
cancel_flag: &AtomicBool,
|
||||
cancel_flag: Option<&AtomicBool>,
|
||||
) -> Result<(), Cancelled>
|
||||
where
|
||||
T: Borrow<StringMatchCandidate>,
|
||||
@@ -239,7 +276,7 @@ where
|
||||
for candidate in candidates {
|
||||
buf.clear();
|
||||
matched_chars.clear();
|
||||
if cancel_flag.load(atomic::Ordering::Relaxed) {
|
||||
if is_cancelled(cancel_flag, atomic::Ordering::Relaxed) {
|
||||
return Err(Cancelled);
|
||||
}
|
||||
|
||||
@@ -294,6 +331,15 @@ mod tests {
|
||||
use super::*;
|
||||
use gpui::BackgroundExecutor;
|
||||
|
||||
fn options() -> StringMatchOptions<'static> {
|
||||
StringMatchOptions {
|
||||
max_results: MaxResults::All,
|
||||
cancel_flag: None,
|
||||
case: Case::Ignore,
|
||||
length_penalty: LengthPenalty::Off,
|
||||
}
|
||||
}
|
||||
|
||||
fn candidates(strings: &[&str]) -> Vec<StringMatchCandidate> {
|
||||
strings
|
||||
.iter()
|
||||
@@ -305,17 +351,7 @@ mod tests {
|
||||
#[gpui::test]
|
||||
async fn test_basic_match(executor: BackgroundExecutor) {
|
||||
let cs = candidates(&["hello", "world", "help"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"hel",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "hel", options(), executor).await;
|
||||
let matched: Vec<&str> = results.iter().map(|m| m.string.as_ref()).collect();
|
||||
assert!(matched.contains(&"hello"));
|
||||
assert!(matched.contains(&"help"));
|
||||
@@ -329,17 +365,7 @@ mod tests {
|
||||
"src/bin/main.rs",
|
||||
"tests/parser_test.rs",
|
||||
]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"src parser",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "src parser", options(), executor).await;
|
||||
assert_eq!(results.len(), 1);
|
||||
assert_eq!(results[0].string, "src/lib/parser.rs");
|
||||
}
|
||||
@@ -347,17 +373,7 @@ mod tests {
|
||||
#[gpui::test]
|
||||
async fn test_empty_query_returns_all(executor: BackgroundExecutor) {
|
||||
let cs = candidates(&["alpha", "beta", "gamma"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "", options(), executor).await;
|
||||
assert_eq!(results.len(), 3);
|
||||
assert!(results.iter().all(|m| m.score == 0.0));
|
||||
}
|
||||
@@ -365,34 +381,14 @@ mod tests {
|
||||
#[gpui::test]
|
||||
async fn test_whitespace_only_query_returns_all(executor: BackgroundExecutor) {
|
||||
let cs = candidates(&["alpha", "beta", "gamma"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
" \t\n",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, " \t\n", options(), executor).await;
|
||||
assert_eq!(results.len(), 3);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_empty_candidates(executor: BackgroundExecutor) {
|
||||
let cs: Vec<StringMatchCandidate> = vec![];
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"query",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "query", options(), executor).await;
|
||||
assert!(results.is_empty());
|
||||
}
|
||||
|
||||
@@ -403,10 +399,10 @@ mod tests {
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"hel",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
StringMatchOptions {
|
||||
cancel_flag: Some(&cancel),
|
||||
..options()
|
||||
},
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
@@ -416,14 +412,13 @@ mod tests {
|
||||
#[gpui::test]
|
||||
async fn test_max_results_limit(executor: BackgroundExecutor) {
|
||||
let cs = candidates(&["ab", "abc", "abcd", "abcde"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"ab",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
2,
|
||||
&cancel,
|
||||
StringMatchOptions {
|
||||
max_results: MaxResults::limit::<2>(),
|
||||
..options()
|
||||
},
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
@@ -437,17 +432,7 @@ mod tests {
|
||||
"fuzzy",
|
||||
"a_fuzzy_thing",
|
||||
]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"fuzzy",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor.clone(),
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "fuzzy", options(), executor.clone()).await;
|
||||
|
||||
let ordered = matches!(
|
||||
(
|
||||
@@ -466,10 +451,10 @@ mod tests {
|
||||
let results_penalty = match_strings_async(
|
||||
&cs,
|
||||
"fuzzy",
|
||||
Case::Ignore,
|
||||
LengthPenalty::On,
|
||||
10,
|
||||
&cancel,
|
||||
StringMatchOptions {
|
||||
length_penalty: LengthPenalty::On,
|
||||
..options()
|
||||
},
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
@@ -480,17 +465,7 @@ mod tests {
|
||||
#[gpui::test]
|
||||
async fn test_utf8_positions(executor: BackgroundExecutor) {
|
||||
let cs = candidates(&["café"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"caf",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "caf", options(), executor).await;
|
||||
assert_eq!(results.len(), 1);
|
||||
let m = &results[0];
|
||||
assert_eq!(m.positions, vec![0, 1, 2]);
|
||||
@@ -502,27 +477,18 @@ mod tests {
|
||||
#[gpui::test]
|
||||
async fn test_smart_case(executor: BackgroundExecutor) {
|
||||
let cs = candidates(&["FooBar", "foobar", "FOOBAR"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
|
||||
let case_insensitive = match_strings_async(
|
||||
&cs,
|
||||
"foobar",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor.clone(),
|
||||
)
|
||||
.await;
|
||||
let case_insensitive =
|
||||
match_strings_async(&cs, "foobar", options(), executor.clone()).await;
|
||||
assert_eq!(case_insensitive.len(), 3);
|
||||
|
||||
let smart = match_strings_async(
|
||||
&cs,
|
||||
"FooBar",
|
||||
Case::Smart,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
StringMatchOptions {
|
||||
case: Case::Smart,
|
||||
..options()
|
||||
},
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
@@ -545,14 +511,14 @@ mod tests {
|
||||
"aaaaaaaaaaaaaaaaaaaaaaaaaaaa_FooBar",
|
||||
"aaaaaaaaaaaaaaaaaaaaaaaaaaaa_foobar",
|
||||
]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"FooBar",
|
||||
Case::Smart,
|
||||
LengthPenalty::On,
|
||||
10,
|
||||
&cancel,
|
||||
StringMatchOptions {
|
||||
case: Case::Smart,
|
||||
length_penalty: LengthPenalty::On,
|
||||
..options()
|
||||
},
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
@@ -575,17 +541,7 @@ mod tests {
|
||||
#[gpui::test]
|
||||
async fn test_char_bag_prefilter(executor: BackgroundExecutor) {
|
||||
let cs = candidates(&["abcdef", "abc", "def", "aabbcc"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"abc",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "abc", options(), executor).await;
|
||||
let matched: Vec<&str> = results.iter().map(|m| m.string.as_ref()).collect();
|
||||
assert!(matched.contains(&"abcdef"));
|
||||
assert!(matched.contains(&"abc"));
|
||||
@@ -596,7 +552,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_sync_basic_match() {
|
||||
let cs = candidates(&["hello", "world", "help"]);
|
||||
let results = match_strings(&cs, "hel", Case::Ignore, LengthPenalty::Off, 10);
|
||||
let results = match_strings(&cs, "hel", options());
|
||||
let matched: Vec<&str> = results.iter().map(|m| m.string.as_ref()).collect();
|
||||
assert!(matched.contains(&"hello"));
|
||||
assert!(matched.contains(&"help"));
|
||||
@@ -606,35 +562,86 @@ mod tests {
|
||||
#[test]
|
||||
fn test_sync_empty_query_returns_all() {
|
||||
let cs = candidates(&["alpha", "beta", "gamma"]);
|
||||
let results = match_strings(&cs, "", Case::Ignore, LengthPenalty::Off, 10);
|
||||
let results = match_strings(&cs, "", options());
|
||||
assert_eq!(results.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sync_whitespace_only_query_returns_all() {
|
||||
let cs = candidates(&["alpha", "beta", "gamma"]);
|
||||
let results = match_strings(&cs, " ", Case::Ignore, LengthPenalty::Off, 10);
|
||||
let results = match_strings(&cs, " ", options());
|
||||
assert_eq!(results.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sync_max_results() {
|
||||
let cs = candidates(&["ab", "abc", "abcd", "abcde"]);
|
||||
let results = match_strings(&cs, "ab", Case::Ignore, LengthPenalty::Off, 2);
|
||||
let results = match_strings(
|
||||
&cs,
|
||||
"ab",
|
||||
StringMatchOptions {
|
||||
max_results: MaxResults::limit::<2>(),
|
||||
..options()
|
||||
},
|
||||
);
|
||||
assert_eq!(results.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sync_cancellation() {
|
||||
let cs = candidates(&["hello", "world"]);
|
||||
let cancel = AtomicBool::new(true);
|
||||
let results = match_strings(
|
||||
&cs,
|
||||
"hel",
|
||||
StringMatchOptions {
|
||||
cancel_flag: Some(&cancel),
|
||||
..options()
|
||||
},
|
||||
);
|
||||
assert!(results.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sync_cancellation_during_last_candidate() {
|
||||
struct CancellingCandidate<'a> {
|
||||
candidate: StringMatchCandidate,
|
||||
cancel: &'a AtomicBool,
|
||||
}
|
||||
|
||||
impl Borrow<StringMatchCandidate> for CancellingCandidate<'_> {
|
||||
fn borrow(&self) -> &StringMatchCandidate {
|
||||
self.cancel.store(true, atomic::Ordering::Release);
|
||||
&self.candidate
|
||||
}
|
||||
}
|
||||
|
||||
let cancel = AtomicBool::new(false);
|
||||
let cs = [CancellingCandidate {
|
||||
candidate: StringMatchCandidate::new(0, "hello"),
|
||||
cancel: &cancel,
|
||||
}];
|
||||
let results = match_strings(
|
||||
&cs,
|
||||
"hel",
|
||||
StringMatchOptions {
|
||||
cancel_flag: Some(&cancel),
|
||||
..options()
|
||||
},
|
||||
);
|
||||
assert!(results.is_empty());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_empty_query_respects_max_results(executor: BackgroundExecutor) {
|
||||
let cs = candidates(&["alpha", "beta", "gamma", "delta"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
2,
|
||||
&cancel,
|
||||
StringMatchOptions {
|
||||
max_results: MaxResults::limit::<2>(),
|
||||
..options()
|
||||
},
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
@@ -644,17 +651,7 @@ mod tests {
|
||||
#[gpui::test]
|
||||
async fn test_multi_word_with_nonmatching_word(executor: BackgroundExecutor) {
|
||||
let cs = candidates(&["src/parser.rs", "src/main.rs"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"src xyzzy",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "src xyzzy", options(), executor).await;
|
||||
assert!(
|
||||
results.is_empty(),
|
||||
"no candidate contains 'xyzzy', so nothing should match"
|
||||
@@ -665,17 +662,7 @@ mod tests {
|
||||
async fn test_segment_size_not_divisible_by_cpus(executor: BackgroundExecutor) {
|
||||
executor.set_num_cpus(4);
|
||||
let cs = candidates(&["alpha", "beta", "gamma", "delta", "epsilon"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"a",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "a", options(), executor).await;
|
||||
let matched: Vec<&str> = results.iter().map(|m| m.string.as_ref()).collect();
|
||||
assert!(matched.contains(&"alpha"));
|
||||
assert!(matched.contains(&"gamma"));
|
||||
@@ -686,17 +673,7 @@ mod tests {
|
||||
async fn test_segment_size_with_many_cpus_few_candidates(executor: BackgroundExecutor) {
|
||||
executor.set_num_cpus(16);
|
||||
let cs = candidates(&["one", "two", "three"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"o",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "o", options(), executor).await;
|
||||
let matched: Vec<&str> = results.iter().map(|m| m.string.as_ref()).collect();
|
||||
assert!(matched.contains(&"one"));
|
||||
assert!(matched.contains(&"two"));
|
||||
@@ -706,17 +683,7 @@ mod tests {
|
||||
async fn test_segment_size_single_candidate(executor: BackgroundExecutor) {
|
||||
executor.set_num_cpus(8);
|
||||
let cs = candidates(&["lonely"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"lone",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "lone", options(), executor).await;
|
||||
assert_eq!(results.len(), 1);
|
||||
assert_eq!(results[0].string.as_ref(), "lonely");
|
||||
}
|
||||
@@ -725,17 +692,7 @@ mod tests {
|
||||
async fn test_segment_size_candidates_equal_cpus(executor: BackgroundExecutor) {
|
||||
executor.set_num_cpus(4);
|
||||
let cs = candidates(&["aaa", "bbb", "ccc", "ddd"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"a",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "a", options(), executor).await;
|
||||
assert_eq!(results.len(), 1);
|
||||
assert_eq!(results[0].string.as_ref(), "aaa");
|
||||
}
|
||||
@@ -744,17 +701,7 @@ mod tests {
|
||||
async fn test_segment_size_candidates_one_more_than_cpus(executor: BackgroundExecutor) {
|
||||
executor.set_num_cpus(3);
|
||||
let cs = candidates(&["ant", "ape", "dog", "axe"]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let results = match_strings_async(
|
||||
&cs,
|
||||
"a",
|
||||
Case::Ignore,
|
||||
LengthPenalty::Off,
|
||||
10,
|
||||
&cancel,
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
let results = match_strings_async(&cs, "a", options(), executor).await;
|
||||
let matched: Vec<&str> = results.iter().map(|m| m.string.as_ref()).collect();
|
||||
assert!(matched.contains(&"ant"));
|
||||
assert!(matched.contains(&"ape"));
|
||||
|
||||
@@ -162,6 +162,11 @@ pub struct RenameBranch {
|
||||
pub branch: Option<String>,
|
||||
}
|
||||
|
||||
/// Trim. Then replace ` ` with `-`.
|
||||
pub fn normalize_branch_name(query: &str) -> String {
|
||||
query.trim().replace(' ', "-")
|
||||
}
|
||||
|
||||
/// Restores a file to its last committed state, discarding local changes.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
|
||||
#[action(namespace = git, deprecated_aliases = ["editor::RevertFile"])]
|
||||
@@ -376,6 +381,13 @@ impl From<Oid> for usize {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_normalize_branch_name() {
|
||||
assert_eq!(normalize_branch_name(" branch-name "), "branch-name");
|
||||
assert_eq!(normalize_branch_name("branch name"), "branch-name");
|
||||
assert_eq!(normalize_branch_name(" branch name "), "branch--name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_short_sha1_oid_by_padding_trailing_nibbles() {
|
||||
let oid = "abc1234".parse::<Oid>().expect("failed to parse oid");
|
||||
|
||||
@@ -118,8 +118,8 @@ impl FileStatus {
|
||||
}
|
||||
.into(),
|
||||
[b'D', b'D'] => UnmergedStatus {
|
||||
first_head: UnmergedStatusCode::Added,
|
||||
second_head: UnmergedStatusCode::Added,
|
||||
first_head: UnmergedStatusCode::Deleted,
|
||||
second_head: UnmergedStatusCode::Deleted,
|
||||
}
|
||||
.into(),
|
||||
[x, b'U'] => UnmergedStatus {
|
||||
@@ -620,7 +620,9 @@ mod tests {
|
||||
|
||||
use crate::{
|
||||
repository::RepoPath,
|
||||
status::{FileStatus, GitStatus, TreeDiff, TreeDiffStatus},
|
||||
status::{
|
||||
FileStatus, GitStatus, TreeDiff, TreeDiffStatus, UnmergedStatus, UnmergedStatusCode,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{DiffStat, parse_numstat};
|
||||
@@ -716,6 +718,34 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_unmerged_status_codes() {
|
||||
use UnmergedStatusCode::{Added, Deleted, Updated};
|
||||
|
||||
let cases = [
|
||||
("DD", Deleted, Deleted),
|
||||
("AU", Added, Updated),
|
||||
("UD", Updated, Deleted),
|
||||
("UA", Updated, Added),
|
||||
("DU", Deleted, Updated),
|
||||
("AA", Added, Added),
|
||||
("UU", Updated, Updated),
|
||||
];
|
||||
|
||||
for (code, first_head, second_head) in cases {
|
||||
let status: GitStatus = format!("{code} conflicted.txt\0").parse().unwrap();
|
||||
assert_eq!(status.entries.len(), 1, "{code}");
|
||||
assert_eq!(
|
||||
status.entries[0].1,
|
||||
FileStatus::Unmerged(UnmergedStatus {
|
||||
first_head,
|
||||
second_head,
|
||||
}),
|
||||
"{code}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_duplicate_untracked_entries() {
|
||||
// Regression test for ZED-2XA: git can produce duplicate untracked entries
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
use anyhow::Context as _;
|
||||
use editor::Editor;
|
||||
use fuzzy_nucleo::StringMatchCandidate;
|
||||
|
||||
use collections::{HashMap, HashSet};
|
||||
use git::repository::{Branch, delete_branch_flag};
|
||||
use git::{GitHostingProviderRegistry, parse_git_remote_url};
|
||||
use git::{GitHostingProviderRegistry, normalize_branch_name, parse_git_remote_url};
|
||||
use gpui::http_client::Url;
|
||||
use gpui::{
|
||||
Action, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, Global,
|
||||
InteractiveElement, IntoElement, Modifiers, ModifiersChangedEvent, ParentElement, PromptLevel,
|
||||
Render, SharedString, Styled, Subscription, Task, TaskExt, WeakEntity, Window, actions, rems,
|
||||
Render, SharedString, Styled, Subscription, Task, WeakEntity, Window, actions, rems,
|
||||
};
|
||||
use picker::{Picker, PickerDelegate, PickerEditorPosition};
|
||||
use project::git_store::{Repository, RepositoryEvent};
|
||||
@@ -23,7 +22,7 @@ use ui::{
|
||||
ListItemSpacing, ListSubHeader, PopoverMenu, PopoverMenuHandle, Severity, Tooltip, prelude::*,
|
||||
};
|
||||
use ui_input::ErasedEditor;
|
||||
use util::ResultExt;
|
||||
use util::{ResultExt, maybe};
|
||||
use workspace::notifications::DetachAndPromptErr;
|
||||
use workspace::{ModalView, Workspace};
|
||||
|
||||
@@ -211,6 +210,8 @@ pub struct BranchList {
|
||||
pub picker: Entity<Picker<BranchListDelegate>>,
|
||||
picker_focus_handle: FocusHandle,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
_load_default_branch: Option<Task<()>>,
|
||||
_load_remote_provider_icons: Option<Task<()>>,
|
||||
embedded: bool,
|
||||
}
|
||||
|
||||
@@ -369,45 +370,46 @@ impl BranchList {
|
||||
));
|
||||
}
|
||||
|
||||
// Fetch default branch asynchronously since it requires a git operation
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
let default_branch = default_branch_request
|
||||
.context("No active repository")?
|
||||
let load_default_branch = default_branch_request.map(|default_branch_request| {
|
||||
cx.spawn(async move |this, cx| {
|
||||
let default_branch = default_branch_request
|
||||
.await
|
||||
.ok()
|
||||
.and_then(Result::ok)
|
||||
.flatten();
|
||||
this.update(cx, |this, cx| {
|
||||
this.picker.update(cx, |picker, _| {
|
||||
picker.delegate.default_branch = default_branch;
|
||||
});
|
||||
})
|
||||
.log_err();
|
||||
})
|
||||
});
|
||||
|
||||
let load_remote_provider_icons = remote_urls_request.map(|remote_urls_request| {
|
||||
cx.spawn(async move |this, cx| {
|
||||
maybe!(async move {
|
||||
let remote_urls = remote_urls_request.await??;
|
||||
let remote_provider_icons =
|
||||
cx.update(|cx| remote_provider_icons(&remote_urls, cx));
|
||||
this.update(cx, |this, cx| {
|
||||
this.picker.update(cx, |picker, cx| {
|
||||
picker.delegate.remote_provider_icons = remote_provider_icons;
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map(Result::ok)
|
||||
.ok()
|
||||
.flatten()
|
||||
.flatten();
|
||||
|
||||
let _ = this.update_in(cx, |this, _window, cx| {
|
||||
this.picker.update(cx, |picker, _cx| {
|
||||
picker.delegate.default_branch = default_branch;
|
||||
});
|
||||
});
|
||||
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.detach_and_log_err(cx);
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let remote_urls = remote_urls_request
|
||||
.context("No active repository")?
|
||||
.await??;
|
||||
let remote_provider_icons = cx.update(|cx| remote_provider_icons(&remote_urls, cx));
|
||||
this.update(cx, |this, cx| {
|
||||
this.picker.update(cx, |picker, cx| {
|
||||
picker.delegate.remote_provider_icons = remote_provider_icons;
|
||||
cx.notify();
|
||||
});
|
||||
})?;
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.detach_and_log_err(cx);
|
||||
.log_err();
|
||||
})
|
||||
});
|
||||
|
||||
Self {
|
||||
picker,
|
||||
picker_focus_handle,
|
||||
_subscriptions: subscriptions,
|
||||
_load_default_branch: load_default_branch,
|
||||
_load_remote_provider_icons: load_remote_provider_icons,
|
||||
embedded,
|
||||
}
|
||||
}
|
||||
@@ -946,13 +948,6 @@ fn branch_matches_ref(branch: &Branch, branch_ref: &SharedString) -> bool {
|
||||
branch.ref_name.as_ref() == branch_ref.as_ref() || branch.name() == branch_ref.as_ref()
|
||||
}
|
||||
|
||||
// Git branch names can't contain whitespace, so we replace spaces with dashes,
|
||||
// but we need to first trim because a branch name can't start or end with a
|
||||
// dash.
|
||||
fn normalize_branch_name(query: &str) -> String {
|
||||
query.trim().replace(' ', "-")
|
||||
}
|
||||
|
||||
fn branch_remote_name(branch: &Branch) -> Option<&str> {
|
||||
branch.remote_name().or_else(|| {
|
||||
branch
|
||||
@@ -1497,10 +1492,10 @@ impl PickerDelegate for BranchListDelegate {
|
||||
let mut matches: Vec<Entry> = fuzzy_nucleo::match_strings_async(
|
||||
&candidates,
|
||||
&query,
|
||||
fuzzy_nucleo::Case::Smart,
|
||||
fuzzy_nucleo::LengthPenalty::On,
|
||||
10000,
|
||||
&Default::default(),
|
||||
fuzzy_nucleo::StringMatchOptions {
|
||||
max_results: fuzzy_nucleo::MaxResults::limit::<10_000>(),
|
||||
..Default::default()
|
||||
},
|
||||
cx.background_executor().clone(),
|
||||
)
|
||||
.await
|
||||
@@ -2390,6 +2385,8 @@ mod tests {
|
||||
picker,
|
||||
picker_focus_handle,
|
||||
_subscriptions: vec![_subscription],
|
||||
_load_default_branch: None,
|
||||
_load_remote_provider_icons: None,
|
||||
embedded: false,
|
||||
}
|
||||
})
|
||||
@@ -3285,13 +3282,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_normalize_branch_name() {
|
||||
assert_eq!(normalize_branch_name(" branch-name "), "branch-name");
|
||||
assert_eq!(normalize_branch_name("branch name"), "branch-name");
|
||||
assert_eq!(normalize_branch_name(" branch name "), "branch--name");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_remote_url_detection_https(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
@@ -3631,7 +3631,7 @@ impl GitGraph {
|
||||
move |bounds: Bounds<Pixels>, _: (), window: &mut Window, cx: &mut App| {
|
||||
graph_canvas_bounds.set(Some(bounds));
|
||||
|
||||
window.paint_layer(bounds, |window| {
|
||||
window.paint_layer(|window| {
|
||||
let theme = cx.theme();
|
||||
let accent_colors = theme.accents();
|
||||
let background = theme.colors().editor_background;
|
||||
@@ -3670,6 +3670,48 @@ impl GitGraph {
|
||||
}
|
||||
}
|
||||
|
||||
// Commit nodes are painted before the lines, which are drawn
|
||||
// over the nodes' halos to meet their rings.
|
||||
for (row_idx, row) in rows.into_iter().enumerate() {
|
||||
let absolute_row_idx = first_visible_row + row_idx;
|
||||
let row_color = accent_colors.color_for_index(row.color_idx as u32);
|
||||
let row_y_center =
|
||||
bounds.origin.y + row_idx as f32 * row_height + row_height / 2.0
|
||||
- vertical_scroll_offset;
|
||||
|
||||
let commit_x = lane_center_x(bounds, row.lane as f32);
|
||||
|
||||
if paint_ref_connectors && !row.data.ref_names.is_empty() {
|
||||
paint_dashed_connector(
|
||||
bounds.origin.x,
|
||||
commit_x - COMMIT_CIRCLE_RADIUS,
|
||||
row_y_center,
|
||||
row_color.opacity(0.5),
|
||||
window,
|
||||
);
|
||||
}
|
||||
|
||||
// Match the node halo to the row's effective background so
|
||||
// the ring blends seamlessly on hovered/selected rows.
|
||||
let node_background = if selected_entry_idx == Some(absolute_row_idx)
|
||||
|| context_menu_target_index == Some(absolute_row_idx)
|
||||
{
|
||||
background.blend(selected_bg)
|
||||
} else if hovered_entry_idx == Some(absolute_row_idx) {
|
||||
background.blend(hover_bg)
|
||||
} else {
|
||||
background
|
||||
};
|
||||
|
||||
draw_commit_circle(
|
||||
commit_x,
|
||||
row_y_center,
|
||||
row_color,
|
||||
node_background,
|
||||
window,
|
||||
);
|
||||
}
|
||||
|
||||
for line in commit_lines {
|
||||
let Some((start_segment_idx, start_column)) =
|
||||
line.get_first_visible_segment_idx(first_visible_row)
|
||||
@@ -3825,56 +3867,10 @@ impl GitGraph {
|
||||
|
||||
for builder in builders {
|
||||
if let Ok(path) = builder.build() {
|
||||
// we paint each color on it's own layer to stop overlapping lines
|
||||
// of different colors changing the color of a line
|
||||
window.paint_layer(bounds, |window| {
|
||||
window.paint_path(path, line_color);
|
||||
});
|
||||
window.paint_path(path, line_color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Commit nodes are painted last so they sit on top of the
|
||||
// connector lines, keeping each commit a clear, distinct point.
|
||||
for (row_idx, row) in rows.into_iter().enumerate() {
|
||||
let absolute_row_idx = first_visible_row + row_idx;
|
||||
let row_color = accent_colors.color_for_index(row.color_idx as u32);
|
||||
let row_y_center =
|
||||
bounds.origin.y + row_idx as f32 * row_height + row_height / 2.0
|
||||
- vertical_scroll_offset;
|
||||
|
||||
let commit_x = lane_center_x(bounds, row.lane as f32);
|
||||
|
||||
if paint_ref_connectors && !row.data.ref_names.is_empty() {
|
||||
paint_dashed_connector(
|
||||
bounds.origin.x,
|
||||
commit_x - COMMIT_CIRCLE_RADIUS,
|
||||
row_y_center,
|
||||
row_color.opacity(0.5),
|
||||
window,
|
||||
);
|
||||
}
|
||||
|
||||
// Match the node halo to the row's effective background so
|
||||
// the ring blends seamlessly on hovered/selected rows.
|
||||
let node_background = if selected_entry_idx == Some(absolute_row_idx)
|
||||
|| context_menu_target_index == Some(absolute_row_idx)
|
||||
{
|
||||
background.blend(selected_bg)
|
||||
} else if hovered_entry_idx == Some(absolute_row_idx) {
|
||||
background.blend(hover_bg)
|
||||
} else {
|
||||
background
|
||||
};
|
||||
|
||||
draw_commit_circle(
|
||||
commit_x,
|
||||
row_y_center,
|
||||
row_color,
|
||||
node_background,
|
||||
window,
|
||||
);
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
@@ -1278,6 +1278,26 @@ struct GitPanelContextMenu {
|
||||
_subscription: Subscription,
|
||||
}
|
||||
|
||||
/// The label for `repository`, disambiguated against every other repository in
|
||||
/// the project.
|
||||
fn repository_display_name(
|
||||
repository: Option<&Entity<Repository>>,
|
||||
project: &Entity<Project>,
|
||||
cx: &App,
|
||||
) -> SharedString {
|
||||
let Some(repository) = repository else {
|
||||
return SharedString::default();
|
||||
};
|
||||
let id = repository.read(cx).id;
|
||||
project
|
||||
.read(cx)
|
||||
.git_store()
|
||||
.read(cx)
|
||||
.display_names(cx)
|
||||
.remove(&id)
|
||||
.unwrap_or_else(|| repository.read(cx).display_name())
|
||||
}
|
||||
|
||||
pub struct GitPanel {
|
||||
pub(crate) active_repository: Option<Entity<Repository>>,
|
||||
pub(crate) commit_editor: Entity<Editor>,
|
||||
@@ -7312,12 +7332,7 @@ impl GitPanel {
|
||||
let head_commit = active_repository.read(cx).head_commit.clone();
|
||||
|
||||
let git_panel = cx.entity();
|
||||
let display_name = SharedString::from(Arc::from(
|
||||
active_repository
|
||||
.read(cx)
|
||||
.display_name()
|
||||
.trim_end_matches("/"),
|
||||
));
|
||||
let display_name = repository_display_name(Some(&active_repository), &self.project, cx);
|
||||
let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
|
||||
editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@ mod blame_ui;
|
||||
pub mod clone;
|
||||
|
||||
use git::{
|
||||
Oid,
|
||||
Oid, normalize_branch_name,
|
||||
repository::{Branch, CommitDetails, Upstream, UpstreamTracking, UpstreamTrackingStatus},
|
||||
status::{FileStatus, StatusCode, UnmergedStatus, UnmergedStatusCode},
|
||||
};
|
||||
@@ -453,6 +453,7 @@ struct RenameBranchModal {
|
||||
current_branch: SharedString,
|
||||
editor: Entity<Editor>,
|
||||
repo: Entity<Repository>,
|
||||
_editor_subscription: Subscription,
|
||||
}
|
||||
|
||||
impl RenameBranchModal {
|
||||
@@ -467,10 +468,16 @@ impl RenameBranchModal {
|
||||
editor.set_text(current_branch.clone(), window, cx);
|
||||
editor
|
||||
});
|
||||
let editor_subscription = cx.subscribe(&editor, |_, _, event, cx| {
|
||||
if let editor::EditorEvent::BufferEdited = event {
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
Self {
|
||||
current_branch: current_branch.into(),
|
||||
editor,
|
||||
repo,
|
||||
_editor_subscription: editor_subscription,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -479,7 +486,7 @@ impl RenameBranchModal {
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let new_name = self.editor.read(cx).text(cx);
|
||||
let new_name = normalize_branch_name(&self.editor.read(cx).text(cx));
|
||||
if new_name.is_empty() || new_name == self.current_branch.as_ref() {
|
||||
cx.emit(DismissEvent);
|
||||
return;
|
||||
@@ -514,6 +521,7 @@ impl Focusable for RenameBranchModal {
|
||||
|
||||
impl Render for RenameBranchModal {
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let new_name = normalize_branch_name(&self.editor.read(cx).text(cx));
|
||||
v_flex()
|
||||
.key_context("RenameBranchModal")
|
||||
.on_action(cx.listener(Self::cancel))
|
||||
@@ -533,7 +541,21 @@ impl Render for RenameBranchModal {
|
||||
.size(HeadlineSize::XSmall),
|
||||
),
|
||||
)
|
||||
.child(div().px_3().pb_3().w_full().child(self.editor.clone()))
|
||||
.child(
|
||||
v_flex()
|
||||
.px_3()
|
||||
.pb_3()
|
||||
.w_full()
|
||||
.gap_2()
|
||||
.child(self.editor.clone())
|
||||
.child(
|
||||
Label::new(new_name)
|
||||
.size(LabelSize::Small)
|
||||
.color(Color::Muted)
|
||||
.single_line()
|
||||
.truncate(),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
use crate::git_status_icon;
|
||||
use collections::HashMap;
|
||||
use git::status::{FileStatus, StatusCode, TrackedStatus, UnmergedStatus, UnmergedStatusCode};
|
||||
use gpui::{App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, Task, WeakEntity};
|
||||
use picker::{Picker, PickerDelegate, PickerEditorPosition};
|
||||
use project::{Project, git_store::Repository};
|
||||
use project::{
|
||||
Project,
|
||||
git_store::{Repository, RepositoryId},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use ui::{ListItem, ListItemSpacing, prelude::*};
|
||||
use workspace::{ModalView, Workspace};
|
||||
@@ -35,17 +39,17 @@ impl RepositorySelector {
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let git_store = project_handle.read(cx).git_store().clone();
|
||||
let repository_entries = git_store.update(cx, |git_store, _cx| {
|
||||
let mut repos: Vec<_> = git_store.repositories().values().cloned().collect();
|
||||
|
||||
repos.sort_by(|a, b| {
|
||||
a.read(_cx)
|
||||
.display_name()
|
||||
.to_lowercase()
|
||||
.cmp(&b.read(_cx).display_name().to_lowercase())
|
||||
});
|
||||
|
||||
repos
|
||||
let display_names = git_store.read(cx).display_names(cx);
|
||||
let mut repository_entries: Vec<_> = git_store
|
||||
.read(cx)
|
||||
.repositories()
|
||||
.values()
|
||||
.cloned()
|
||||
.collect();
|
||||
repository_entries.sort_by(|a, b| {
|
||||
display_name_of(&display_names, a, cx)
|
||||
.to_lowercase()
|
||||
.cmp(&display_name_of(&display_names, b, cx).to_lowercase())
|
||||
});
|
||||
let filtered_repositories = repository_entries.clone();
|
||||
|
||||
@@ -60,6 +64,7 @@ impl RepositorySelector {
|
||||
filtered_repositories,
|
||||
active_repository,
|
||||
selected_index,
|
||||
display_names,
|
||||
};
|
||||
|
||||
let picker = cx.new(|cx| {
|
||||
@@ -127,6 +132,19 @@ pub struct RepositorySelectorDelegate {
|
||||
filtered_repositories: Vec<Entity<Repository>>,
|
||||
active_repository: Option<Entity<Repository>>,
|
||||
selected_index: usize,
|
||||
display_names: HashMap<RepositoryId, SharedString>,
|
||||
}
|
||||
|
||||
fn display_name_of(
|
||||
display_names: &HashMap<RepositoryId, SharedString>,
|
||||
repository: &Entity<Repository>,
|
||||
cx: &App,
|
||||
) -> SharedString {
|
||||
let repository = repository.read(cx);
|
||||
display_names
|
||||
.get(&repository.id)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| repository.display_name())
|
||||
}
|
||||
|
||||
impl RepositorySelectorDelegate {
|
||||
@@ -188,7 +206,12 @@ impl PickerDelegate for RepositorySelectorDelegate {
|
||||
|
||||
let repo_names: Vec<(Entity<Repository>, String)> = all_repositories
|
||||
.iter()
|
||||
.map(|repo| (repo.clone(), repo.read(cx).display_name().to_lowercase()))
|
||||
.map(|repo| {
|
||||
(
|
||||
repo.clone(),
|
||||
display_name_of(&self.display_names, repo, cx).to_lowercase(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
@@ -209,11 +232,11 @@ impl PickerDelegate for RepositorySelectorDelegate {
|
||||
|
||||
this.update_in(cx, |this, window, cx| {
|
||||
let mut sorted_repositories = filtered_repositories;
|
||||
let display_names = &this.delegate.display_names;
|
||||
sorted_repositories.sort_by(|a, b| {
|
||||
a.read(cx)
|
||||
.display_name()
|
||||
display_name_of(display_names, a, cx)
|
||||
.to_lowercase()
|
||||
.cmp(&b.read(cx).display_name().to_lowercase())
|
||||
.cmp(&display_name_of(display_names, b, cx).to_lowercase())
|
||||
});
|
||||
let selected_index = this
|
||||
.delegate
|
||||
@@ -253,8 +276,8 @@ impl PickerDelegate for RepositorySelectorDelegate {
|
||||
cx: &mut Context<Picker<Self>>,
|
||||
) -> Option<Self::ListItem> {
|
||||
let repo_info = self.filtered_repositories.get(ix)?;
|
||||
let display_name = display_name_of(&self.display_names, repo_info, cx);
|
||||
let repo = repo_info.read(cx);
|
||||
let display_name = repo.display_name();
|
||||
let summary = repo.status_summary();
|
||||
let is_active = self
|
||||
.active_repository
|
||||
@@ -267,8 +290,10 @@ impl PickerDelegate for RepositorySelectorDelegate {
|
||||
.toggle_state(selected)
|
||||
.child(
|
||||
h_flex()
|
||||
.w_full()
|
||||
.min_w_0()
|
||||
.gap_1()
|
||||
.child(Label::new(display_name))
|
||||
.child(Label::new(display_name).single_line().truncate().flex_1())
|
||||
.when(is_active, |this| {
|
||||
this.child(
|
||||
Icon::new(IconName::Check)
|
||||
|
||||
@@ -629,26 +629,26 @@ pub async fn await_and_rollback_on_failure(
|
||||
/// Propagates worktree trust from the source workspace to the new workspace.
|
||||
/// If the source project's worktrees are all trusted, the new worktree paths
|
||||
/// will also be trusted automatically.
|
||||
fn maybe_propagate_worktree_trust(
|
||||
async fn maybe_propagate_worktree_trust(
|
||||
source_workspace: &WeakEntity<Workspace>,
|
||||
new_workspace: &Entity<Workspace>,
|
||||
paths: &[PathBuf],
|
||||
cx: &mut AsyncWindowContext,
|
||||
) {
|
||||
cx.update(|_, cx| {
|
||||
let inherit_restriction = cx.update(|window, cx| {
|
||||
if ProjectSettings::get_global(cx).session.trust_all_worktrees {
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
let source_is_trusted = source_workspace
|
||||
.upgrade()
|
||||
.map(|workspace| {
|
||||
let source_worktree_store = workspace.read(cx).project().read(cx).worktree_store();
|
||||
!TrustedWorktrees::has_restricted_worktrees(&source_worktree_store, cx)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
|
||||
if !source_is_trusted {
|
||||
return;
|
||||
let source_workspace = source_workspace.upgrade()?;
|
||||
let source_worktree_store = source_workspace
|
||||
.read(cx)
|
||||
.project()
|
||||
.read(cx)
|
||||
.worktree_store();
|
||||
if TrustedWorktrees::has_restricted_worktrees(&source_worktree_store, cx) {
|
||||
return Some(new_workspace.update(cx, |new_workspace, cx| {
|
||||
new_workspace.inherit_restricted_worktrees(&source_workspace, window, cx)
|
||||
}));
|
||||
}
|
||||
|
||||
let worktree_store = new_workspace.read(cx).project().read(cx).worktree_store();
|
||||
@@ -667,8 +667,11 @@ fn maybe_propagate_worktree_trust(
|
||||
});
|
||||
}
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
None
|
||||
});
|
||||
if let Ok(Some(inherit_restriction)) = inherit_restriction {
|
||||
inherit_restriction.await;
|
||||
}
|
||||
|
||||
// After trust propagation, refresh the security modal on the new workspace
|
||||
// so it dismisses itself if there are no more restricted worktrees.
|
||||
@@ -1258,7 +1261,7 @@ async fn open_worktree_workspace(
|
||||
})
|
||||
.await;
|
||||
|
||||
maybe_propagate_worktree_trust(&workspace, &new_workspace, &all_paths, cx);
|
||||
maybe_propagate_worktree_trust(&workspace, &new_workspace, &all_paths, cx).await;
|
||||
|
||||
if transfer_state {
|
||||
window_handle.update(cx, |_multi_workspace, window, cx| {
|
||||
@@ -1709,6 +1712,100 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_linked_worktree_inherits_stay_in_restricted_mode(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
cx.update(|cx| {
|
||||
cx.set_global(db::AppDatabase::test_new());
|
||||
project::trusted_worktrees::init(collections::HashMap::default(), cx);
|
||||
});
|
||||
|
||||
let fs = FakeFs::new(cx.background_executor.clone());
|
||||
cx.update(|cx| <dyn Fs>::set_global(fs.clone(), cx));
|
||||
fs.insert_tree(
|
||||
"/root",
|
||||
json!({
|
||||
"project": {
|
||||
".git": {},
|
||||
"src": {
|
||||
"main.rs": "fn main() {}",
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let main_project_root = PathBuf::from(path!("/root/project"));
|
||||
|
||||
for (worktree_name, stay_restricted_in_source) in [("undecided", false), ("declined", true)]
|
||||
{
|
||||
let project =
|
||||
Project::test_with_worktree_trust(fs.clone(), [main_project_root.as_path()], cx)
|
||||
.await;
|
||||
project
|
||||
.update(cx, |project, cx| project.git_scans_complete(cx))
|
||||
.await;
|
||||
let (multi_workspace, window_cx) = cx.add_window_view(|window, cx| {
|
||||
MultiWorkspace::test_new(project.clone(), window, cx)
|
||||
});
|
||||
multi_workspace.update(window_cx, |multi_workspace, cx| {
|
||||
multi_workspace.retain_active_workspace(cx);
|
||||
});
|
||||
let main_workspace = multi_workspace.read_with(window_cx, |multi_workspace, _| {
|
||||
multi_workspace.workspace().clone()
|
||||
});
|
||||
|
||||
if stay_restricted_in_source {
|
||||
main_workspace.update_in(window_cx, |workspace, window, cx| {
|
||||
workspace.show_worktree_trust_security_modal(true, window, cx);
|
||||
});
|
||||
window_cx.run_until_parked();
|
||||
window_cx.dispatch_action(workspace::ToggleWorktreeSecurity);
|
||||
window_cx.run_until_parked();
|
||||
}
|
||||
|
||||
main_workspace.update_in(window_cx, |workspace, window, cx| {
|
||||
assert!(
|
||||
workspace
|
||||
.active_modal::<workspace::security_modal::SecurityModal>(cx)
|
||||
.is_none(),
|
||||
"{worktree_name}"
|
||||
);
|
||||
handle_create_worktree(
|
||||
workspace,
|
||||
&zed_actions::CreateWorktree {
|
||||
worktree_name: Some(worktree_name.to_string()),
|
||||
branch_target: NewWorktreeBranchTarget::CurrentBranch,
|
||||
},
|
||||
window,
|
||||
None,
|
||||
cx,
|
||||
);
|
||||
});
|
||||
window_cx.run_until_parked();
|
||||
|
||||
let new_workspace = multi_workspace.read_with(window_cx, |multi_workspace, _| {
|
||||
multi_workspace.workspace().clone()
|
||||
});
|
||||
assert_ne!(new_workspace, main_workspace, "{worktree_name}");
|
||||
new_workspace.read_with(window_cx, |workspace, cx| {
|
||||
assert!(
|
||||
project::trusted_worktrees::TrustedWorktrees::has_restricted_worktrees(
|
||||
&workspace.project().read(cx).worktree_store(),
|
||||
cx,
|
||||
),
|
||||
"{worktree_name}"
|
||||
);
|
||||
assert_eq!(
|
||||
workspace
|
||||
.active_modal::<workspace::security_modal::SecurityModal>(cx)
|
||||
.is_some(),
|
||||
!stay_restricted_in_source,
|
||||
"{worktree_name}"
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_remote_branch_name_parse() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -119,9 +119,10 @@ unicode-segmentation.workspace = true
|
||||
gpui_util.workspace = true
|
||||
hdrhistogram = { workspace = true, optional = true }
|
||||
waker-fn = "1.2.0"
|
||||
lyon = "1.0"
|
||||
lyon_path = "1.0.19"
|
||||
pin-project = "1.1.10"
|
||||
spin.workspace = true
|
||||
tiny-skia-path = "0.11"
|
||||
url.workspace = true
|
||||
uuid = { workspace = true, features = ["v4"] }
|
||||
web-time = { workspace = true, optional = true }
|
||||
@@ -181,7 +182,7 @@ postage = { workspace = true, features = ["blocking"] }
|
||||
web-time.workspace = true
|
||||
gpui_platform = { workspace = true, features = ["font-kit", "wayland", "x11"] }
|
||||
gpui_util.workspace = true
|
||||
lyon = { version = "1.0", features = ["extra"] }
|
||||
lyon_extra = "1.1.0"
|
||||
rand = { workspace = true, default-features = true }
|
||||
scheduler = { workspace = true, features = ["test-support"] }
|
||||
util_macros.workspace = true
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
mod example_support;
|
||||
|
||||
use gpui::{
|
||||
Background, Bounds, ColorSpace, Context, MouseDownEvent, Path, PathBuilder, PathStyle, Pixels,
|
||||
Point, Render, StrokeOptions, Window, WindowOptions, canvas, div, linear_color_stop,
|
||||
linear_gradient, point, prelude::*, px, quad, rgb, size,
|
||||
Background, Bounds, ColorSpace, Context, LineJoin, MouseDownEvent, Path, PathBuilder,
|
||||
PathStyle, Pixels, Point, Render, StrokeOptions, Window, WindowOptions, canvas, div,
|
||||
linear_color_stop, linear_gradient, point, prelude::*, px, quad, rgb, size,
|
||||
};
|
||||
use gpui_platform::application;
|
||||
|
||||
struct PaintingViewer {
|
||||
default_lines: Vec<(Path<Pixels>, Background)>,
|
||||
default_lines: Vec<(Path, Background)>,
|
||||
background_quads: Vec<(Bounds<Pixels>, Background)>,
|
||||
lines: Vec<Vec<Point<Pixels>>>,
|
||||
start: Point<Pixels>,
|
||||
@@ -154,8 +154,8 @@ impl PaintingViewer {
|
||||
lines.push((path, red2.into()));
|
||||
|
||||
// draw a Rust logo
|
||||
let mut builder = lyon::path::Path::svg_builder();
|
||||
lyon::extra::rust_logo::build_logo_path(&mut builder);
|
||||
let mut builder = lyon_path::Path::svg_builder();
|
||||
lyon_extra::rust_logo::build_logo_path(&mut builder);
|
||||
// move down the Path
|
||||
let mut builder: PathBuilder = builder.into();
|
||||
builder.translate(point(px(10.), px(200.)));
|
||||
@@ -273,9 +273,11 @@ impl PaintingViewer {
|
||||
}
|
||||
|
||||
// draw a wave
|
||||
let options = StrokeOptions::default()
|
||||
.with_line_width(1.)
|
||||
.with_line_join(lyon::path::LineJoin::Bevel);
|
||||
let options = StrokeOptions {
|
||||
line_width: 1.,
|
||||
line_join: LineJoin::Bevel,
|
||||
..Default::default()
|
||||
};
|
||||
let mut builder = PathBuilder::stroke(px(1.)).with_style(PathStyle::Stroke(options));
|
||||
builder.move_to(point(px(40.), px(420.)));
|
||||
for i in 1..50 {
|
||||
@@ -301,6 +303,57 @@ impl PaintingViewer {
|
||||
self.lines.clear();
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Fill the canvas with a deterministic scribble, for benchmarking.
|
||||
fn stress_scribble(&mut self, cx: &mut Context<Self>) {
|
||||
self.lines.clear();
|
||||
let mut state: u32 = 0x9E3779B9;
|
||||
let mut random = move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 17;
|
||||
state ^= state << 5;
|
||||
state as f32 / u32::MAX as f32
|
||||
};
|
||||
for _ in 0..30 {
|
||||
let mut x = 40.0 + random() * 860.0;
|
||||
let mut y = 80.0 + random() * 440.0;
|
||||
let mut angle = random() * std::f32::consts::TAU;
|
||||
let mut points = Vec::with_capacity(121);
|
||||
points.push(point(px(x), px(y)));
|
||||
for _ in 0..120 {
|
||||
angle += (random() - 0.5) * 1.2;
|
||||
x += angle.cos() * 12.0;
|
||||
y += angle.sin() * 12.0;
|
||||
if !(40.0..=900.0).contains(&x) {
|
||||
angle = std::f32::consts::PI - angle;
|
||||
x = x.clamp(40.0, 900.0);
|
||||
}
|
||||
if !(80.0..=520.0).contains(&y) {
|
||||
angle = -angle;
|
||||
y = y.clamp(80.0, 520.0);
|
||||
}
|
||||
points.push(point(px(x), px(y)));
|
||||
}
|
||||
self.lines.push(points);
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Fill the canvas with a grid of strokes, for benchmarking.
|
||||
fn stress_grid(&mut self, cx: &mut Context<Self>) {
|
||||
self.lines.clear();
|
||||
for i in 0..55 {
|
||||
let y = 80.0 + i as f32 * 8.0;
|
||||
self.lines
|
||||
.push(vec![point(px(40.0), px(y)), point(px(900.0), px(y))]);
|
||||
}
|
||||
for i in 0..108 {
|
||||
let x = 40.0 + i as f32 * 8.0;
|
||||
self.lines
|
||||
.push(vec![point(px(x), px(80.0)), point(px(x), px(520.0))]);
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
fn button(
|
||||
@@ -349,6 +402,8 @@ impl Render for PaintingViewer {
|
||||
cx,
|
||||
move |this, _| this.dashed = !dashed,
|
||||
))
|
||||
.child(button("Scribble", cx, |this, cx| this.stress_scribble(cx)))
|
||||
.child(button("Grid", cx, |this, cx| this.stress_grid(cx)))
|
||||
.child(button("Clear", cx, |this, cx| this.clear(cx))),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -14,7 +14,7 @@ const DEFAULT_WINDOW_WIDTH: Pixels = px(1024.0);
|
||||
const DEFAULT_WINDOW_HEIGHT: Pixels = px(768.0);
|
||||
|
||||
struct PaintingViewer {
|
||||
default_lines: Vec<(Path<Pixels>, Background)>,
|
||||
default_lines: Vec<(Path, Background)>,
|
||||
_painting: bool,
|
||||
}
|
||||
|
||||
|
||||
+115
-6
@@ -55,8 +55,8 @@ use crate::{
|
||||
PromptButton, PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle,
|
||||
Reservation, ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
|
||||
SystemNotification, SystemNotificationResponse, Task, TextRenderingMode, TextSystem,
|
||||
ThermalState, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId,
|
||||
WindowInvalidator, WindowingRequest,
|
||||
ThermalState, Window, WindowAppearance, WindowBounds, WindowButtonLayout, WindowHandle,
|
||||
WindowId, WindowInvalidator, WindowingRequest,
|
||||
colors::{Colors, GlobalColors},
|
||||
hash, init_app_menus,
|
||||
};
|
||||
@@ -971,7 +971,7 @@ pub struct App {
|
||||
pub(crate) name: Option<&'static str>,
|
||||
pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
|
||||
|
||||
pub(crate) window_update_stack: Vec<WindowId>,
|
||||
pub(crate) window_update_stack: Vec<WindowUpdateEntry>,
|
||||
pub(crate) mode: GpuiMode,
|
||||
pub(crate) cursor_hide_mode: CursorHideMode,
|
||||
pub(crate) reduce_motion: bool,
|
||||
@@ -991,6 +991,13 @@ pub struct App {
|
||||
_ref_counts: Arc<RwLock<EntityRefCounts>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct WindowUpdateEntry {
|
||||
window_id: WindowId,
|
||||
bounds: WindowBounds,
|
||||
display_id: Option<DisplayId>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
#[allow(clippy::new_ret_no_self)]
|
||||
pub(crate) fn new_app(
|
||||
@@ -1599,6 +1606,40 @@ impl App {
|
||||
self.platform.active_window()
|
||||
}
|
||||
|
||||
/// Returns the display containing the window that is currently focused at the platform level.
|
||||
pub fn active_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
|
||||
let (display_id, _) = self.active_window_placement()?;
|
||||
self.find_display(display_id?)
|
||||
}
|
||||
|
||||
pub(crate) fn active_window_placement(&self) -> Option<(Option<DisplayId>, WindowBounds)> {
|
||||
let window_id = self.active_window()?.window_id();
|
||||
|
||||
if let Some(state) = self
|
||||
.window_update_stack
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|state| state.window_id == window_id)
|
||||
{
|
||||
return Some((state.display_id, state.bounds));
|
||||
}
|
||||
|
||||
let window = self.windows.get(window_id)?.as_ref()?;
|
||||
Some((window.display_id(), window.last_window_bounds()))
|
||||
}
|
||||
|
||||
pub(crate) fn sync_window_update_entry(&mut self, window: &Window) {
|
||||
if let Some(state) = self
|
||||
.window_update_stack
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|state| state.window_id == window.handle.id)
|
||||
{
|
||||
state.bounds = window.last_window_bounds();
|
||||
state.display_id = window.display_id();
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a new window with the given option and the root view returned by the given function.
|
||||
/// The function is invoked with a `Window`, which can be used to interact with window-specific
|
||||
/// functionality.
|
||||
@@ -1612,7 +1653,11 @@ impl App {
|
||||
let handle = WindowHandle::new(id);
|
||||
match Window::new(handle.into(), options, cx) {
|
||||
Ok(mut window) => {
|
||||
cx.window_update_stack.push(id);
|
||||
cx.window_update_stack.push(WindowUpdateEntry {
|
||||
window_id: id,
|
||||
bounds: window.last_window_bounds(),
|
||||
display_id: window.display_id(),
|
||||
});
|
||||
let root_view = build_root_view(&mut window, cx);
|
||||
cx.window_update_stack.pop();
|
||||
window.root.replace(root_view.into());
|
||||
@@ -1687,6 +1732,66 @@ impl App {
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// Returns a diagnostic snapshot of app, display, and window state.
|
||||
///
|
||||
/// This is for inspecting a running app that is misbehaving in a way that
|
||||
/// is hard to reproduce. The layout is not stable and varies by platform;
|
||||
/// do not parse it for program logic. A window that is being updated when
|
||||
/// this is called is listed by ID only.
|
||||
pub fn debug_state(&self) -> serde_json::Value {
|
||||
let displays = self
|
||||
.platform
|
||||
.displays()
|
||||
.into_iter()
|
||||
.map(|display| {
|
||||
serde_json::json!({
|
||||
"id": u64::from(display.id()),
|
||||
"uuid": display.uuid().ok().map(|uuid| uuid.to_string()),
|
||||
"bounds": display.bounds(),
|
||||
"visible_bounds": display.visible_bounds(),
|
||||
"refresh_interval_seconds": display
|
||||
.refresh_interval()
|
||||
.map(|interval| interval.as_secs_f64()),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let windows = self
|
||||
.windows
|
||||
.iter()
|
||||
.map(|(window_id, window)| match window {
|
||||
Some(window) => window.debug_state(),
|
||||
None => serde_json::json!({ "id": window_id.as_u64(), "updating": true }),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
serde_json::json!({
|
||||
"compositor": self.platform.compositor_name(),
|
||||
"thermal_state": format!("{:?}", self.platform.thermal_state()),
|
||||
"power_mode": {
|
||||
"cached": format!("{:?}", self.power_mode),
|
||||
"platform": format!("{:?}", self.platform.power_mode()),
|
||||
},
|
||||
"window_appearance": format!("{:?}", self.platform.window_appearance()),
|
||||
"cursor_visible": self.platform.is_cursor_visible(),
|
||||
"active_window_id": self
|
||||
.platform
|
||||
.active_window()
|
||||
.map(|handle| handle.window_id().as_u64()),
|
||||
"window_stack": self.platform.window_stack().map(|stack| {
|
||||
stack
|
||||
.into_iter()
|
||||
.map(|handle| handle.window_id().as_u64())
|
||||
.collect::<Vec<_>>()
|
||||
}),
|
||||
"primary_display_id": self
|
||||
.platform
|
||||
.primary_display()
|
||||
.map(|display| u64::from(display.id())),
|
||||
"displays": displays,
|
||||
"windows": windows,
|
||||
"platform": self.platform.debug_state(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the current thermal state of the system.
|
||||
pub fn thermal_state(&self) -> ThermalState {
|
||||
self.platform.thermal_state()
|
||||
@@ -3264,7 +3369,11 @@ impl App {
|
||||
|
||||
let root_view = window.root.clone().unwrap();
|
||||
|
||||
cx.window_update_stack.push(window.handle.id);
|
||||
cx.window_update_stack.push(WindowUpdateEntry {
|
||||
window_id: window.handle.id,
|
||||
bounds: window.last_window_bounds(),
|
||||
display_id: window.display_id(),
|
||||
});
|
||||
update(Some((root_view, &mut window, cx)));
|
||||
fn trail(window_id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
|
||||
cx.window_update_stack.pop();
|
||||
@@ -3349,7 +3458,7 @@ impl AppContext for App {
|
||||
cx.push_effect(Effect::EntityCreated {
|
||||
entity: handle.into_any(),
|
||||
tid: TypeId::of::<T>(),
|
||||
window: cx.window_update_stack.last().cloned(),
|
||||
window: cx.window_update_stack.last().map(|state| state.window_id),
|
||||
});
|
||||
|
||||
cx.entities.insert(slot, entity)
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
use crate::{
|
||||
Action, AnyView, AnyWindowHandle, App, AppCell, AppContext, AsyncApp, AvailableSpace,
|
||||
BackgroundExecutor, BorrowAppContext, Bounds, Capslock, ClipboardItem, DisplayId, DrawPhase,
|
||||
Drawable, Element, Empty, EntityId, EventEmitter, ForegroundExecutor, Global, InputEvent,
|
||||
Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent,
|
||||
MouseUpEvent, Pixels, Platform, PlatformTextSystem, Point, Render, Result, SharedString, Size,
|
||||
SystemNotification, SystemNotificationResponse, Task, TestDispatcher, TestPlatform,
|
||||
TestScreenCaptureSource, TestWindow, TextSystem, VisualContext, Window, WindowBounds,
|
||||
WindowHandle, WindowOptions, WindowVisibility, app::GpuiMode, window::ElementArenaScope,
|
||||
BackgroundExecutor, BorrowAppContext, Bounds, Capslock, ClipboardItem, Decorations, DisplayId,
|
||||
DrawPhase, Drawable, Element, Empty, EntityId, EventEmitter, ForegroundExecutor, Global,
|
||||
InputEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent,
|
||||
MouseMoveEvent, MouseUpEvent, Pixels, Platform, PlatformTextSystem, Point, Render, Result,
|
||||
SharedString, Size, SystemNotification, SystemNotificationResponse, Task, TestDispatcher,
|
||||
TestPlatform, TestScreenCaptureSource, TestWindow, TextSystem, VisualContext, Window,
|
||||
WindowBounds, WindowHandle, WindowOptions, WindowVisibility, app::GpuiMode,
|
||||
window::ElementArenaScope,
|
||||
};
|
||||
use anyhow::{anyhow, bail};
|
||||
use futures::{Stream, StreamExt, channel::oneshot};
|
||||
@@ -477,6 +478,16 @@ impl TestAppContext {
|
||||
.simulate_visibility_change(visibility);
|
||||
}
|
||||
|
||||
/// Simulates the platform changing how the window is decorated.
|
||||
pub fn simulate_window_decorations_change(
|
||||
&self,
|
||||
window_handle: AnyWindowHandle,
|
||||
decorations: Decorations,
|
||||
) {
|
||||
self.test_window(window_handle)
|
||||
.simulate_decorations_change(decorations);
|
||||
}
|
||||
|
||||
/// Simulates connecting a display.
|
||||
pub fn simulate_display_added(
|
||||
&self,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{Bounds, Half};
|
||||
use crate::{Bounds, Half, scene::PrimitiveKind};
|
||||
use std::{
|
||||
cmp,
|
||||
fmt::Debug,
|
||||
@@ -13,10 +13,12 @@ const MAX_CHILDREN: usize = 12;
|
||||
/// A spatial tree optimized for finding maximum ordering among intersecting bounds.
|
||||
///
|
||||
/// This is an R-tree variant specifically designed for the use case of assigning
|
||||
/// z-order to overlapping UI elements. Key optimizations:
|
||||
/// - Tracks the leaf with global max ordering for O(1) fast-path queries
|
||||
/// z-order to overlapping UI elements. Each bounds has an ordering and a kind;
|
||||
/// bounds sharing an ordering are drawn in the order of their kinds. Key
|
||||
/// optimizations:
|
||||
/// - Tracks the leaf with global max key for O(1) fast-path queries
|
||||
/// - Uses higher branching factor (4) for lower tree height
|
||||
/// - Aggressive pruning during search based on max_order metadata
|
||||
/// - Aggressive pruning during search based on max_key metadata
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct BoundsTree<U>
|
||||
where
|
||||
@@ -26,7 +28,7 @@ where
|
||||
nodes: Vec<Node<U>>,
|
||||
/// Index of the root node, if any.
|
||||
root: Option<usize>,
|
||||
/// Index of the leaf with the highest ordering (for fast-path lookups).
|
||||
/// Index of the leaf with the highest key (for fast-path lookups).
|
||||
max_leaf: Option<usize>,
|
||||
/// Reusable stack for tree traversal during insertion.
|
||||
insert_path: Vec<usize>,
|
||||
@@ -42,19 +44,24 @@ where
|
||||
{
|
||||
/// Bounding box containing this node and all descendants.
|
||||
bounds: Bounds<U>,
|
||||
/// Maximum ordering value in this subtree.
|
||||
max_order: u32,
|
||||
/// Maximum key in this subtree.
|
||||
max_key: Key,
|
||||
/// Node-specific data.
|
||||
kind: NodeKind,
|
||||
}
|
||||
|
||||
/// The ordering of a bounds, then its kind, which orders the bounds that share
|
||||
/// an ordering.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
struct Key {
|
||||
ordering: u32,
|
||||
kind: PrimitiveKind,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum NodeKind {
|
||||
/// Leaf node containing actual bounds data.
|
||||
Leaf {
|
||||
/// The ordering assigned to this bounds.
|
||||
order: u32,
|
||||
},
|
||||
Leaf { key: Key },
|
||||
/// Internal node with children.
|
||||
Internal {
|
||||
/// Indices of child nodes (2 to MAX_CHILDREN).
|
||||
@@ -65,7 +72,7 @@ enum NodeKind {
|
||||
/// Fixed-size array for child indices, avoiding heap allocation.
|
||||
#[derive(Debug, Clone)]
|
||||
struct NodeChildren {
|
||||
// Keeps an invariant where the max order child is always at the end
|
||||
// Keeps an invariant where the max key child is always at the end
|
||||
indices: [usize; MAX_CHILDREN],
|
||||
len: u8,
|
||||
}
|
||||
@@ -113,39 +120,48 @@ where
|
||||
self.search_stack.clear();
|
||||
}
|
||||
|
||||
/// Inserts bounds into the tree and returns its assigned ordering.
|
||||
/// Inserts bounds of the given kind into the tree and returns its assigned
|
||||
/// ordering.
|
||||
///
|
||||
/// The ordering is one greater than the maximum ordering of any
|
||||
/// existing bounds that intersect with the new bounds.
|
||||
pub fn insert(&mut self, new_bounds: Bounds<U>) -> u32 {
|
||||
// Find maximum ordering among intersecting bounds
|
||||
let max_intersecting = self.find_max_ordering(&new_bounds);
|
||||
let ordering = max_intersecting + 1;
|
||||
/// The ordering is one greater than the maximum ordering of any existing
|
||||
/// bounds that intersect with the new bounds. The new bounds share that
|
||||
/// maximum ordering instead if every intersecting bounds there has a kind
|
||||
/// of at most `max_shared_kind`, since those are drawn first.
|
||||
pub fn insert(
|
||||
&mut self,
|
||||
new_bounds: Bounds<U>,
|
||||
kind: PrimitiveKind,
|
||||
max_shared_kind: PrimitiveKind,
|
||||
) -> u32 {
|
||||
let ordering = match self.find_max_key(&new_bounds) {
|
||||
None => 1,
|
||||
Some(max_key) if max_key.kind <= max_shared_kind => max_key.ordering,
|
||||
Some(max_key) => max_key.ordering + 1,
|
||||
};
|
||||
let key = Key { ordering, kind };
|
||||
|
||||
// Insert the new leaf
|
||||
let new_leaf_idx = self.insert_leaf(new_bounds, ordering);
|
||||
let new_leaf_idx = self.insert_leaf(new_bounds, key);
|
||||
|
||||
// Update max_leaf tracking
|
||||
self.max_leaf = match self.max_leaf {
|
||||
None => Some(new_leaf_idx),
|
||||
Some(old_idx) if self.nodes[old_idx].max_order < ordering => Some(new_leaf_idx),
|
||||
Some(old_idx) if self.nodes[old_idx].max_key < key => Some(new_leaf_idx),
|
||||
some => some,
|
||||
};
|
||||
|
||||
ordering
|
||||
}
|
||||
|
||||
/// Finds the maximum ordering among all bounds that intersect with the query.
|
||||
fn find_max_ordering(&mut self, query: &Bounds<U>) -> u32 {
|
||||
let Some(root_idx) = self.root else {
|
||||
return 0;
|
||||
};
|
||||
/// Finds the maximum key among all bounds that intersect with the query.
|
||||
fn find_max_key(&mut self, query: &Bounds<U>) -> Option<Key> {
|
||||
let root_idx = self.root?;
|
||||
|
||||
// Fast path: check if the max-ordering leaf intersects
|
||||
// Fast path: check if the max-key leaf intersects
|
||||
if let Some(max_idx) = self.max_leaf {
|
||||
let max_node = &self.nodes[max_idx];
|
||||
if query.intersects(&max_node.bounds) {
|
||||
return max_node.max_order;
|
||||
return Some(max_node.max_key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,7 +169,8 @@ where
|
||||
self.search_stack.clear();
|
||||
self.search_stack.push(NonNull::from(&self.nodes[root_idx]));
|
||||
|
||||
let mut max_found = 0u32;
|
||||
// `None` compares below every key.
|
||||
let mut max_found = None;
|
||||
|
||||
while let Some(node) = self.search_stack.pop() {
|
||||
// SAFETY: `node` is guaranteed to be valid as the `nodes` stack is unmodified in this function
|
||||
@@ -161,7 +178,7 @@ where
|
||||
let node = unsafe { node.as_ref() };
|
||||
|
||||
// Pruning: skip if this subtree can't improve our result
|
||||
if node.max_order <= max_found {
|
||||
if Some(node.max_key) <= max_found {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -171,18 +188,18 @@ where
|
||||
}
|
||||
|
||||
match &node.kind {
|
||||
NodeKind::Leaf { order } => {
|
||||
max_found = cmp::max(max_found, *order);
|
||||
NodeKind::Leaf { key } => {
|
||||
max_found = cmp::max(max_found, Some(*key));
|
||||
}
|
||||
NodeKind::Internal { children } => {
|
||||
// Children are maintained with highest max_order at the end.
|
||||
// Children are maintained with highest max_key at the end.
|
||||
// Push in forward order to highest (last) is popped first.
|
||||
self.search_stack.extend(
|
||||
children
|
||||
.as_slice()
|
||||
.iter()
|
||||
.map(|&child_idx| &self.nodes[child_idx])
|
||||
.filter(|node| node.max_order > max_found)
|
||||
.filter(|node| Some(node.max_key) > max_found)
|
||||
.map(NonNull::from),
|
||||
);
|
||||
}
|
||||
@@ -192,14 +209,14 @@ where
|
||||
max_found
|
||||
}
|
||||
|
||||
/// Inserts a leaf node with the given bounds and ordering.
|
||||
/// Inserts a leaf node with the given bounds and key.
|
||||
/// Returns the index of the new leaf.
|
||||
fn insert_leaf(&mut self, bounds: Bounds<U>, order: u32) -> usize {
|
||||
fn insert_leaf(&mut self, bounds: Bounds<U>, key: Key) -> usize {
|
||||
let new_leaf_idx = self.nodes.len();
|
||||
self.nodes.push(Node {
|
||||
bounds: bounds.clone(),
|
||||
max_order: order,
|
||||
kind: NodeKind::Leaf { order },
|
||||
max_key: key,
|
||||
kind: NodeKind::Leaf { key },
|
||||
});
|
||||
|
||||
let Some(root_idx) = self.root else {
|
||||
@@ -211,11 +228,11 @@ where
|
||||
// If root is a leaf, create internal node with both
|
||||
if matches!(self.nodes[root_idx].kind, NodeKind::Leaf { .. }) {
|
||||
let root_bounds = self.nodes[root_idx].bounds.clone();
|
||||
let root_order = self.nodes[root_idx].max_order;
|
||||
let root_key = self.nodes[root_idx].max_key;
|
||||
|
||||
let mut children = NodeChildren::new();
|
||||
// Max end invariant
|
||||
if order > root_order {
|
||||
if key > root_key {
|
||||
children.push(root_idx);
|
||||
children.push(new_leaf_idx);
|
||||
} else {
|
||||
@@ -226,7 +243,7 @@ where
|
||||
let new_root_idx = self.nodes.len();
|
||||
self.nodes.push(Node {
|
||||
bounds: root_bounds.union(&bounds),
|
||||
max_order: cmp::max(root_order, order),
|
||||
max_key: cmp::max(root_key, key),
|
||||
kind: NodeKind::Internal { children },
|
||||
});
|
||||
self.root = Some(new_root_idx);
|
||||
@@ -270,24 +287,24 @@ where
|
||||
|
||||
if let NodeKind::Internal { children } = &mut node.kind {
|
||||
children.push(new_leaf_idx);
|
||||
// Swap new leaf only if it has the highest max_order
|
||||
if order <= node.max_order {
|
||||
// Swap new leaf only if it has the highest max_key
|
||||
if key <= node.max_key {
|
||||
let last = children.len() - 1;
|
||||
children.indices.swap(last - 1, last);
|
||||
}
|
||||
}
|
||||
|
||||
node.bounds = node.bounds.union(&bounds);
|
||||
node.max_order = cmp::max(node.max_order, order);
|
||||
node.max_key = cmp::max(node.max_key, key);
|
||||
break;
|
||||
} else {
|
||||
// Node is full, create new internal with [best_leaf, new_leaf]
|
||||
let sibling_bounds = self.nodes[best_child_idx].bounds.clone();
|
||||
let sibling_order = self.nodes[best_child_idx].max_order;
|
||||
let sibling_key = self.nodes[best_child_idx].max_key;
|
||||
|
||||
let mut new_children = NodeChildren::new();
|
||||
// Max end invariant
|
||||
if order > sibling_order {
|
||||
if key > sibling_key {
|
||||
new_children.push(best_child_idx);
|
||||
new_children.push(new_leaf_idx);
|
||||
} else {
|
||||
@@ -296,10 +313,10 @@ where
|
||||
}
|
||||
|
||||
let new_internal_idx = self.nodes.len();
|
||||
let new_internal_max = cmp::max(sibling_order, order);
|
||||
let new_internal_max_key = cmp::max(sibling_key, key);
|
||||
self.nodes.push(Node {
|
||||
bounds: sibling_bounds.union(&bounds),
|
||||
max_order: new_internal_max,
|
||||
max_key: new_internal_max_key,
|
||||
kind: NodeKind::Internal {
|
||||
children: new_children,
|
||||
},
|
||||
@@ -312,9 +329,9 @@ where
|
||||
|
||||
children.indices[best_child_pos] = new_internal_idx;
|
||||
|
||||
// If new internal has highest max_order, swap it to the end
|
||||
// If new internal has highest max_key, swap it to the end
|
||||
// to maintain sorting invariant
|
||||
if new_internal_max > parent.max_order {
|
||||
if new_internal_max_key > parent.max_key {
|
||||
children.indices.swap(best_child_pos, children_len - 1);
|
||||
}
|
||||
}
|
||||
@@ -326,14 +343,14 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
// Propagate bounds and max_order updates up the tree
|
||||
// Propagate bounds and max_key updates up the tree
|
||||
let mut updated_child_idx = None;
|
||||
for &node_idx in self.insert_path.iter().rev() {
|
||||
let node = &mut self.nodes[node_idx];
|
||||
node.bounds = node.bounds.union(&bounds);
|
||||
|
||||
if node.max_order < order {
|
||||
node.max_order = order;
|
||||
if node.max_key < key {
|
||||
node.max_key = key;
|
||||
|
||||
// Swap updated child to end (skip first iteration since the invariant is already handled by previous cases)
|
||||
if let Some(child_idx) = updated_child_idx {
|
||||
@@ -380,6 +397,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_insert() {
|
||||
let mut tree = BoundsTree::<f32>::default();
|
||||
let (quad, shadow) = (PrimitiveKind::Quad, PrimitiveKind::Shadow);
|
||||
let bounds1 = Bounds {
|
||||
origin: Point { x: 0.0, y: 0.0 },
|
||||
size: Size {
|
||||
@@ -403,9 +421,9 @@ mod tests {
|
||||
};
|
||||
|
||||
// Insert the bounds into the tree and verify the order is correct
|
||||
assert_eq!(tree.insert(bounds1), 1);
|
||||
assert_eq!(tree.insert(bounds2), 2);
|
||||
assert_eq!(tree.insert(bounds3), 3);
|
||||
assert_eq!(tree.insert(bounds1, quad, shadow), 1);
|
||||
assert_eq!(tree.insert(bounds2, quad, shadow), 2);
|
||||
assert_eq!(tree.insert(bounds3, quad, shadow), 3);
|
||||
|
||||
// Insert non-overlapping bounds and verify they can reuse orders
|
||||
let bounds4 = Bounds {
|
||||
@@ -429,19 +447,24 @@ mod tests {
|
||||
height: 10.0,
|
||||
},
|
||||
};
|
||||
assert_eq!(tree.insert(bounds4), 1); // bounds4 does not overlap with bounds1, bounds2, or bounds3
|
||||
assert_eq!(tree.insert(bounds5), 1); // bounds5 does not overlap with any other bounds
|
||||
assert_eq!(tree.insert(bounds6), 2); // bounds6 overlaps with bounds4, so it should have a different order
|
||||
assert_eq!(tree.insert(bounds4, quad, shadow), 1); // bounds4 does not overlap with bounds1, bounds2, or bounds3
|
||||
assert_eq!(tree.insert(bounds5, quad, shadow), 1); // bounds5 does not overlap with any other bounds
|
||||
assert_eq!(tree.insert(bounds6, quad, shadow), 2); // bounds6 overlaps with bounds4, so it should have a different order
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_random_iterations() {
|
||||
let max_bounds = 100;
|
||||
for seed in 1..=1000 {
|
||||
// let seed = 44;
|
||||
let mut tree = BoundsTree::default();
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64);
|
||||
let mut expected_quads: Vec<(Bounds<f32>, u32)> = Vec::new();
|
||||
let mut expected_quads: Vec<(Bounds<f32>, u32, PrimitiveKind)> = Vec::new();
|
||||
let kinds = [
|
||||
PrimitiveKind::Shadow,
|
||||
PrimitiveKind::Quad,
|
||||
PrimitiveKind::Path,
|
||||
PrimitiveKind::Underline,
|
||||
];
|
||||
|
||||
// Insert a random number of random AABBs into the tree.
|
||||
let num_bounds = rng.random_range(1..=max_bounds);
|
||||
@@ -454,17 +477,22 @@ mod tests {
|
||||
origin: Point { x: min_x, y: min_y },
|
||||
size: Size { width, height },
|
||||
};
|
||||
let kind = kinds[rng.random_range(0..kinds.len())];
|
||||
let max_shared_kind = kinds[rng.random_range(0..kinds.len())];
|
||||
|
||||
let expected_ordering = expected_quads
|
||||
let max_intersecting = expected_quads
|
||||
.iter()
|
||||
.filter_map(|quad| quad.0.intersects(&bounds).then_some(quad.1))
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
+ 1;
|
||||
expected_quads.push((bounds, expected_ordering));
|
||||
.filter(|quad| quad.0.intersects(&bounds))
|
||||
.map(|quad| (quad.1, quad.2))
|
||||
.max();
|
||||
let expected_ordering = match max_intersecting {
|
||||
None => 1,
|
||||
Some((ordering, max_kind)) if max_kind <= max_shared_kind => ordering,
|
||||
Some((ordering, _)) => ordering + 1,
|
||||
};
|
||||
expected_quads.push((bounds, expected_ordering, kind));
|
||||
|
||||
// Insert the AABB into the tree and collect intersections.
|
||||
let actual_ordering = tree.insert(bounds);
|
||||
let actual_ordering = tree.insert(bounds, kind, max_shared_kind);
|
||||
assert_eq!(actual_ordering, expected_ordering);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1187,6 +1187,37 @@ impl<T: PartialOrd + Add<T, Output = T> + Sub<Output = T> + Clone + Debug + Defa
|
||||
let bottom_right = self.bottom_right().max(&other.bottom_right());
|
||||
Bounds::from_corners(top_left, bottom_right)
|
||||
}
|
||||
|
||||
/// Computes the smallest `Bounds` that covers the area of both `Bounds`.
|
||||
///
|
||||
/// Unlike [`Bounds::union`], an empty `Bounds` covers nothing, so joining with it returns
|
||||
/// the other `Bounds` unchanged.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # use gpui::{Bounds, Point, Size};
|
||||
/// let bounds = Bounds {
|
||||
/// origin: Point { x: 5, y: 5 },
|
||||
/// size: Size { width: 10, height: 10 },
|
||||
/// };
|
||||
/// let empty = Bounds {
|
||||
/// origin: Point { x: 0, y: 0 },
|
||||
/// size: Size { width: 0, height: 10 },
|
||||
/// };
|
||||
///
|
||||
/// assert_eq!(bounds.join(&empty), bounds);
|
||||
/// assert_eq!(empty.join(&bounds), bounds);
|
||||
/// ```
|
||||
pub fn join(&self, other: &Self) -> Self {
|
||||
if self.is_empty() {
|
||||
other.clone()
|
||||
} else if other.is_empty() {
|
||||
self.clone()
|
||||
} else {
|
||||
self.union(other)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Bounds<T>
|
||||
@@ -3135,7 +3166,7 @@ impl From<usize> for DevicePixels {
|
||||
/// a single logical pixel may correspond to multiple physical pixels. By using `ScaledPixels`,
|
||||
/// dimensions and positions can be specified in a way that scales appropriately across different
|
||||
/// display resolutions.
|
||||
#[derive(Clone, Copy, Default, Add, AddAssign, Sub, SubAssign, Div, DivAssign, PartialEq)]
|
||||
#[derive(Clone, Copy, Default, Add, AddAssign, Sub, SubAssign, Neg, Div, DivAssign, PartialEq)]
|
||||
#[repr(transparent)]
|
||||
pub struct ScaledPixels(pub f32);
|
||||
|
||||
@@ -3289,6 +3320,18 @@ impl MulAssign<f32> for ScaledPixels {
|
||||
}
|
||||
}
|
||||
|
||||
impl std::iter::Sum for ScaledPixels {
|
||||
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
|
||||
iter.fold(Self::default(), |a, b| a + b)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> std::iter::Sum<&'a ScaledPixels> for ScaledPixels {
|
||||
fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
|
||||
iter.fold(Self::default(), |a, b| a + *b)
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a length in rems, a unit based on the font-size of the window, which can be assigned with [`Window::set_rem_size`][set_rem_size].
|
||||
///
|
||||
/// Rems are used for defining lengths that are scalable and consistent across different UI elements.
|
||||
@@ -4052,6 +4095,37 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bounds_join() {
|
||||
let bounds = Bounds {
|
||||
origin: Point { x: 5.0, y: 5.0 },
|
||||
size: Size {
|
||||
width: 5.0,
|
||||
height: 5.0,
|
||||
},
|
||||
};
|
||||
let other = Bounds {
|
||||
origin: Point { x: 20.0, y: 0.0 },
|
||||
size: Size {
|
||||
width: 5.0,
|
||||
height: 5.0,
|
||||
},
|
||||
};
|
||||
assert_eq!(bounds.join(&other), bounds.union(&other));
|
||||
|
||||
let empty = Bounds {
|
||||
origin: Point { x: 0.0, y: 0.0 },
|
||||
size: Size {
|
||||
width: 0.0,
|
||||
height: 10.0,
|
||||
},
|
||||
};
|
||||
assert_eq!(bounds.join(&empty), bounds);
|
||||
assert_eq!(empty.join(&bounds), bounds);
|
||||
assert_eq!(Bounds::default().join(&bounds), bounds);
|
||||
assert_ne!(bounds.union(&empty), bounds);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bounds_intersects() {
|
||||
let bounds1 = Bounds {
|
||||
|
||||
@@ -44,6 +44,7 @@ mod interactive;
|
||||
mod key_dispatch;
|
||||
mod keymap;
|
||||
mod path_builder;
|
||||
mod path_winding;
|
||||
mod platform;
|
||||
mod platform_scheduler;
|
||||
mod scene;
|
||||
@@ -134,6 +135,7 @@ pub use inspector::*;
|
||||
pub use interactive::*;
|
||||
pub use keymap::*;
|
||||
pub use path_builder::*;
|
||||
pub(crate) use path_winding::*;
|
||||
pub use platform::*;
|
||||
pub use profiler::*;
|
||||
pub use refineable::*;
|
||||
|
||||
+342
-112
@@ -1,17 +1,15 @@
|
||||
use anyhow::Error;
|
||||
use anyhow::{Error, bail};
|
||||
use etagere::euclid::{Point2D, Vector2D};
|
||||
use lyon::geom::Angle;
|
||||
use lyon::math::{Vector, vector};
|
||||
use lyon::path::traits::SvgPathBuilder;
|
||||
use lyon::path::{ArcFlags, Polygon};
|
||||
use lyon::tessellation::{
|
||||
BuffersBuilder, FillTessellator, FillVertex, StrokeTessellator, StrokeVertex, VertexBuffers,
|
||||
};
|
||||
use lyon_path::geom::{Angle, CubicBezierSegment, QuadraticBezierSegment};
|
||||
use lyon_path::math::{Vector, vector};
|
||||
use lyon_path::traits::SvgPathBuilder;
|
||||
use lyon_path::{ArcFlags, Event, Polygon};
|
||||
|
||||
pub use lyon::math::Transform;
|
||||
pub use lyon::tessellation::{FillOptions, FillRule, StrokeOptions};
|
||||
pub use lyon_path::math::Transform;
|
||||
pub use lyon_path::{FillRule, LineCap, LineJoin};
|
||||
|
||||
use crate::{Path, Pixels, Point, point, px};
|
||||
use crate::{PathCurve, PathTiles, Pixels, Point, point, px};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Style of the PathBuilder
|
||||
pub enum PathStyle {
|
||||
@@ -21,17 +19,57 @@ pub enum PathStyle {
|
||||
Fill(FillOptions),
|
||||
}
|
||||
|
||||
/// How to stroke a path.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct StrokeOptions {
|
||||
/// Width of the stroke.
|
||||
pub line_width: f32,
|
||||
/// Shape of the ends of open subpaths and dashes.
|
||||
pub line_cap: LineCap,
|
||||
/// Shape of corners.
|
||||
pub line_join: LineJoin,
|
||||
/// How long a miter join may get, as a multiple of the line width,
|
||||
/// before it is beveled instead.
|
||||
pub miter_limit: f32,
|
||||
}
|
||||
|
||||
impl Default for StrokeOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
line_width: 1.0,
|
||||
line_cap: LineCap::Butt,
|
||||
line_join: LineJoin::Miter,
|
||||
miter_limit: 4.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How to fill a path.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FillOptions {
|
||||
/// How overlapping contours combine into the filled region.
|
||||
pub fill_rule: FillRule,
|
||||
}
|
||||
|
||||
impl Default for FillOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fill_rule: FillRule::EvenOdd,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`Path`] builder.
|
||||
pub struct PathBuilder {
|
||||
raw: lyon::path::builder::WithSvg<lyon::path::BuilderImpl>,
|
||||
transform: Option<lyon::math::Transform>,
|
||||
raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>,
|
||||
transform: Option<lyon_path::math::Transform>,
|
||||
/// PathStyle of the PathBuilder
|
||||
pub style: PathStyle,
|
||||
dash_array: Option<Vec<Pixels>>,
|
||||
}
|
||||
|
||||
impl From<lyon::path::Builder> for PathBuilder {
|
||||
fn from(builder: lyon::path::Builder) -> Self {
|
||||
impl From<lyon_path::Builder> for PathBuilder {
|
||||
fn from(builder: lyon_path::Builder) -> Self {
|
||||
Self {
|
||||
raw: builder.with_svg(),
|
||||
..Default::default()
|
||||
@@ -39,8 +77,8 @@ impl From<lyon::path::Builder> for PathBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<lyon::path::builder::WithSvg<lyon::path::BuilderImpl>> for PathBuilder {
|
||||
fn from(raw: lyon::path::builder::WithSvg<lyon::path::BuilderImpl>) -> Self {
|
||||
impl From<lyon_path::builder::WithSvg<lyon_path::BuilderImpl>> for PathBuilder {
|
||||
fn from(raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>) -> Self {
|
||||
Self {
|
||||
raw,
|
||||
..Default::default()
|
||||
@@ -48,15 +86,15 @@ impl From<lyon::path::builder::WithSvg<lyon::path::BuilderImpl>> for PathBuilder
|
||||
}
|
||||
}
|
||||
|
||||
impl From<lyon::math::Point> for Point<Pixels> {
|
||||
fn from(p: lyon::math::Point) -> Self {
|
||||
impl From<lyon_path::math::Point> for Point<Pixels> {
|
||||
fn from(p: lyon_path::math::Point) -> Self {
|
||||
point(px(p.x), px(p.y))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Point<Pixels>> for lyon::math::Point {
|
||||
impl From<Point<Pixels>> for lyon_path::math::Point {
|
||||
fn from(p: Point<Pixels>) -> Self {
|
||||
lyon::math::point(p.x.0, p.y.0)
|
||||
lyon_path::math::point(p.x.0, p.y.0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +113,7 @@ impl From<Point<Pixels>> for Point2D<f32, Pixels> {
|
||||
impl Default for PathBuilder {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
raw: lyon::path::Path::builder().with_svg(),
|
||||
raw: lyon_path::Path::builder().with_svg(),
|
||||
style: PathStyle::Fill(FillOptions::default()),
|
||||
transform: None,
|
||||
dash_array: None,
|
||||
@@ -87,7 +125,10 @@ impl PathBuilder {
|
||||
/// Creates a new [`PathBuilder`] to build a Stroke path.
|
||||
pub fn stroke(width: Pixels) -> Self {
|
||||
Self {
|
||||
style: PathStyle::Stroke(StrokeOptions::default().with_line_width(width.0)),
|
||||
style: PathStyle::Stroke(StrokeOptions {
|
||||
line_width: width.0,
|
||||
..Default::default()
|
||||
}),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
@@ -102,7 +143,7 @@ impl PathBuilder {
|
||||
Self { style, ..self }
|
||||
}
|
||||
|
||||
/// Sets the dash array of the [`PathBuilder`].
|
||||
/// Sets the dash array of the [`PathBuilder`]. Fills ignore it.
|
||||
///
|
||||
/// [MDN](https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Attribute/stroke-dasharray)
|
||||
pub fn dash_array(mut self, dash_array: &[Pixels]) -> Self {
|
||||
@@ -240,108 +281,297 @@ impl PathBuilder {
|
||||
}
|
||||
|
||||
/// Builds into a [`Path`].
|
||||
#[inline]
|
||||
pub fn build(self) -> Result<Path<Pixels>, Error> {
|
||||
pub fn build(self) -> Result<Path, Error> {
|
||||
let (curves, fill_rule) = self.outline()?;
|
||||
Ok(Path::from_curves(curves, fill_rule))
|
||||
}
|
||||
|
||||
/// The closed contours to fill, and the rule to fill them by.
|
||||
pub(crate) fn outline(self) -> Result<(Vec<PathCurve>, FillRule), Error> {
|
||||
let path = if let Some(transform) = self.transform {
|
||||
self.raw.build().transformed(&transform)
|
||||
} else {
|
||||
self.raw.build()
|
||||
};
|
||||
|
||||
match self.style {
|
||||
PathStyle::Stroke(options) => Self::tessellate_stroke(self.dash_array, &path, &options),
|
||||
PathStyle::Fill(options) => Self::tessellate_fill(&path, &options),
|
||||
}
|
||||
Ok(match self.style {
|
||||
PathStyle::Stroke(options) => (
|
||||
Self::stroke_outline(&path, &options, self.dash_array.as_deref())?,
|
||||
FillRule::NonZero,
|
||||
),
|
||||
PathStyle::Fill(options) => (Self::fill_outline(&path)?, options.fill_rule),
|
||||
})
|
||||
}
|
||||
|
||||
fn tessellate_fill(
|
||||
path: &lyon::path::Path,
|
||||
options: &FillOptions,
|
||||
) -> Result<Path<Pixels>, Error> {
|
||||
// Will contain the result of the tessellation.
|
||||
let mut buf: VertexBuffers<lyon::math::Point, u16> = VertexBuffers::new();
|
||||
let mut tessellator = FillTessellator::new();
|
||||
|
||||
// Compute the tessellation.
|
||||
tessellator.tessellate_path(
|
||||
path,
|
||||
options,
|
||||
&mut BuffersBuilder::new(&mut buf, |vertex: FillVertex| vertex.position()),
|
||||
)?;
|
||||
|
||||
Ok(Self::build_path(buf))
|
||||
}
|
||||
|
||||
fn tessellate_stroke(
|
||||
dash_array: Option<Vec<Pixels>>,
|
||||
path: &lyon::path::Path,
|
||||
fn stroke_outline(
|
||||
path: &lyon_path::Path,
|
||||
options: &StrokeOptions,
|
||||
) -> Result<Path<Pixels>, Error> {
|
||||
let path = if let Some(dash_array) = dash_array {
|
||||
let measurements = lyon::algorithms::measure::PathMeasurements::from_path(path, 0.01);
|
||||
let mut sampler = measurements
|
||||
.create_sampler(path, lyon::algorithms::measure::SampleType::Normalized);
|
||||
let mut builder = lyon::path::Path::builder();
|
||||
|
||||
let total_length = sampler.length();
|
||||
let dash_array_len = dash_array.len();
|
||||
let mut pos = 0.;
|
||||
let mut dash_index = 0;
|
||||
while pos < total_length {
|
||||
let dash_length = dash_array[dash_index % dash_array_len].0;
|
||||
let next_pos = (pos + dash_length).min(total_length);
|
||||
if dash_index % 2 == 0 {
|
||||
let start = pos / total_length;
|
||||
let end = next_pos / total_length;
|
||||
sampler.split_range(start..end, &mut builder);
|
||||
dash_array: Option<&[Pixels]>,
|
||||
) -> Result<Vec<PathCurve>, Error> {
|
||||
let outline = skia_path(path)
|
||||
.map(|skia_path| match dash_array {
|
||||
Some(dash_array) => {
|
||||
let array = dash_array.iter().map(|length| length.0).collect();
|
||||
match tiny_skia_path::StrokeDash::new(array, 0.0) {
|
||||
Some(dash) => skia_path
|
||||
.dash(&dash, STROKE_RESOLUTION_SCALE)
|
||||
.unwrap_or(skia_path),
|
||||
// An invalid dash array strokes undashed, as in SVG.
|
||||
None => skia_path,
|
||||
}
|
||||
}
|
||||
pos = next_pos;
|
||||
dash_index += 1;
|
||||
}
|
||||
|
||||
&builder.build()
|
||||
} else {
|
||||
path
|
||||
None => skia_path,
|
||||
})
|
||||
.and_then(|skia_path| {
|
||||
skia_path.stroke(
|
||||
&tiny_skia_path::Stroke {
|
||||
width: options.line_width,
|
||||
miter_limit: options.miter_limit,
|
||||
line_cap: match options.line_cap {
|
||||
LineCap::Butt => tiny_skia_path::LineCap::Butt,
|
||||
LineCap::Square => tiny_skia_path::LineCap::Square,
|
||||
LineCap::Round => tiny_skia_path::LineCap::Round,
|
||||
},
|
||||
line_join: match options.line_join {
|
||||
LineJoin::Miter => tiny_skia_path::LineJoin::Miter,
|
||||
LineJoin::MiterClip => tiny_skia_path::LineJoin::MiterClip,
|
||||
LineJoin::Round => tiny_skia_path::LineJoin::Round,
|
||||
LineJoin::Bevel => tiny_skia_path::LineJoin::Bevel,
|
||||
},
|
||||
dash: None,
|
||||
},
|
||||
STROKE_RESOLUTION_SCALE,
|
||||
)
|
||||
});
|
||||
let Some(outline) = outline else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
|
||||
// Will contain the result of the tessellation.
|
||||
let mut buf: VertexBuffers<lyon::math::Point, u16> = VertexBuffers::new();
|
||||
let mut tessellator = StrokeTessellator::new();
|
||||
|
||||
// Compute the tessellation.
|
||||
tessellator.tessellate_path(
|
||||
path,
|
||||
options,
|
||||
&mut BuffersBuilder::new(&mut buf, |vertex: StrokeVertex| vertex.position()),
|
||||
)?;
|
||||
|
||||
Ok(Self::build_path(buf))
|
||||
let mut output = Outline::default();
|
||||
let at = |p: tiny_skia_path::Point| point(p.x, p.y);
|
||||
for segment in outline.segments() {
|
||||
match segment {
|
||||
tiny_skia_path::PathSegment::MoveTo(p) => output.move_to(at(p)),
|
||||
tiny_skia_path::PathSegment::LineTo(p) => output.line_to(at(p)),
|
||||
tiny_skia_path::PathSegment::QuadTo(ctrl, p) => output.curve_to(at(p), at(ctrl)),
|
||||
tiny_skia_path::PathSegment::CubicTo(ctrl1, ctrl2, p) => {
|
||||
output.cubic_to(at(p), at(ctrl1), at(ctrl2))
|
||||
}
|
||||
tiny_skia_path::PathSegment::Close => output.close(),
|
||||
}
|
||||
}
|
||||
output.into_curves()
|
||||
}
|
||||
|
||||
/// Builds a [`Path`] from a [`lyon::tessellation::VertexBuffers`].
|
||||
pub fn build_path(buf: VertexBuffers<lyon::math::Point, u16>) -> Path<Pixels> {
|
||||
if buf.vertices.is_empty() {
|
||||
return Path::new(Point::default());
|
||||
/// Convert a lyon path into a fill, closing every subpath.
|
||||
fn fill_outline(path: &lyon_path::Path) -> Result<Vec<PathCurve>, Error> {
|
||||
let mut output = Outline::default();
|
||||
let at = |p: lyon_path::math::Point| point(p.x, p.y);
|
||||
for event in path.iter() {
|
||||
match event {
|
||||
Event::Begin { at: p } => output.move_to(at(p)),
|
||||
Event::Line { to, .. } => output.line_to(at(to)),
|
||||
Event::Quadratic { ctrl, to, .. } => output.curve_to(at(to), at(ctrl)),
|
||||
Event::Cubic {
|
||||
ctrl1, ctrl2, to, ..
|
||||
} => output.cubic_to(at(to), at(ctrl1), at(ctrl2)),
|
||||
Event::End { .. } => output.close(),
|
||||
}
|
||||
}
|
||||
|
||||
let first_point = buf.vertices[0];
|
||||
|
||||
let mut path = Path::new(first_point.into());
|
||||
for i in 0..buf.indices.len() / 3 {
|
||||
let i0 = buf.indices[i * 3] as usize;
|
||||
let i1 = buf.indices[i * 3 + 1] as usize;
|
||||
let i2 = buf.indices[i * 3 + 2] as usize;
|
||||
|
||||
let v0 = buf.vertices[i0];
|
||||
let v1 = buf.vertices[i1];
|
||||
let v2 = buf.vertices[i2];
|
||||
|
||||
path.push_triangle(
|
||||
(v0.into(), v1.into(), v2.into()),
|
||||
(point(0., 1.), point(0., 1.), point(0., 1.)),
|
||||
);
|
||||
}
|
||||
|
||||
path
|
||||
output.into_curves()
|
||||
}
|
||||
}
|
||||
|
||||
/// A filled path, ready to paint. Build one with [`PathBuilder`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Path {
|
||||
/// Closed contours of monotone curves, in logical pixels.
|
||||
curves: Arc<[PathCurve]>,
|
||||
even_odd: bool,
|
||||
}
|
||||
|
||||
impl Path {
|
||||
pub(crate) fn from_curves(curves: Vec<PathCurve>, fill_rule: FillRule) -> Self {
|
||||
Self {
|
||||
curves: curves.into(),
|
||||
even_odd: matches!(fill_rule, FillRule::EvenOdd),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn even_odd(&self) -> bool {
|
||||
self.even_odd
|
||||
}
|
||||
|
||||
/// Bin the curves into tiles in device pixels, for painting at the given
|
||||
/// display scale.
|
||||
pub(crate) fn bin(&self, scale: f32) -> PathTiles {
|
||||
crate::path_winding::bin(&self.curves, self.even_odd, scale)
|
||||
}
|
||||
}
|
||||
|
||||
/// A path's contours as monotone curves, collected by [`PathBuilder`].
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Outline {
|
||||
curves: Vec<PathCurve>,
|
||||
start: Point<f32>,
|
||||
current: Point<f32>,
|
||||
non_finite: bool,
|
||||
}
|
||||
|
||||
impl Outline {
|
||||
/// Whether segments through these points can be added.
|
||||
fn accepts(&mut self, points: &[Point<f32>]) -> bool {
|
||||
self.non_finite |= !points
|
||||
.iter()
|
||||
.all(|point| point.x.is_finite() && point.y.is_finite());
|
||||
!self.non_finite
|
||||
}
|
||||
|
||||
/// Close the current contour and start a new one at the given point.
|
||||
pub(crate) fn move_to(&mut self, to: Point<f32>) {
|
||||
if !self.accepts(&[to]) {
|
||||
return;
|
||||
}
|
||||
self.close();
|
||||
self.start = to;
|
||||
self.current = to;
|
||||
}
|
||||
|
||||
pub(crate) fn line_to(&mut self, to: Point<f32>) {
|
||||
if self.accepts(&[to]) && to != self.current {
|
||||
self.curves.push(PathCurve::line(self.current, to));
|
||||
self.current = to;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn curve_to(&mut self, to: Point<f32>, ctrl: Point<f32>) {
|
||||
if !self.accepts(&[to, ctrl]) || (to == self.current && ctrl == self.current) {
|
||||
return;
|
||||
}
|
||||
PathCurve::push_monotone(&mut self.curves, self.current, ctrl, to);
|
||||
self.current = to;
|
||||
}
|
||||
|
||||
pub(crate) fn cubic_to(&mut self, to: Point<f32>, ctrl1: Point<f32>, ctrl2: Point<f32>) {
|
||||
/// Maximum error, in logical pixels.
|
||||
const TOLERANCE: f32 = 0.25;
|
||||
if !self.accepts(&[to, ctrl1, ctrl2]) {
|
||||
return;
|
||||
}
|
||||
let lyon_point = |p: Point<f32>| lyon_path::math::point(p.x, p.y);
|
||||
let cubic = CubicBezierSegment {
|
||||
from: lyon_point(self.current),
|
||||
ctrl1: lyon_point(ctrl1),
|
||||
ctrl2: lyon_point(ctrl2),
|
||||
to: lyon_point(to),
|
||||
};
|
||||
cubic.for_each_quadratic_bezier(TOLERANCE, &mut |quadratic| {
|
||||
self.curve_to(
|
||||
point(quadratic.to.x, quadratic.to.y),
|
||||
point(quadratic.ctrl.x, quadratic.ctrl.y),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Close the current contour with a straight line back to its start.
|
||||
pub(crate) fn close(&mut self) {
|
||||
let start = self.start;
|
||||
self.line_to(start);
|
||||
}
|
||||
|
||||
/// The curves, with every contour closed.
|
||||
pub(crate) fn into_curves(mut self) -> Result<Vec<PathCurve>, Error> {
|
||||
if self.non_finite {
|
||||
bail!("path has a non-finite point");
|
||||
}
|
||||
self.close();
|
||||
Ok(self.curves)
|
||||
}
|
||||
}
|
||||
|
||||
impl PathCurve {
|
||||
fn new(p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>, sign: f32) -> Self {
|
||||
Self {
|
||||
p0,
|
||||
p1,
|
||||
a: point(p0.x - 2.0 * ctrl.x + p1.x, p0.y - 2.0 * ctrl.y + p1.y),
|
||||
b: point(2.0 * (ctrl.x - p0.x), 2.0 * (ctrl.y - p0.y)),
|
||||
sign,
|
||||
pad: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A line, with exactly zero quadratic terms.
|
||||
fn line(from: Point<f32>, to: Point<f32>) -> Self {
|
||||
let (p0, p1, sign) = downward(from, to);
|
||||
Self {
|
||||
p0,
|
||||
p1,
|
||||
a: point(0.0, 0.0),
|
||||
b: point(p1.x - p0.x, p1.y - p0.y),
|
||||
sign,
|
||||
pad: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Split a quadratic segment at its extrema into xy-monotone curves.
|
||||
fn push_monotone(curves: &mut Vec<Self>, p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>) {
|
||||
let curve = QuadraticBezierSegment {
|
||||
from: lyon_path::math::point(p0.x, p0.y),
|
||||
ctrl: lyon_path::math::point(ctrl.x, ctrl.y),
|
||||
to: lyon_path::math::point(p1.x, p1.y),
|
||||
};
|
||||
// Unlike `split_range`, this also clamps each piece's control point
|
||||
// back into its endpoint box when rounding pushes it out.
|
||||
curve.for_each_monotonic(&mut |monotone| {
|
||||
let from = point(monotone.from.x, monotone.from.y);
|
||||
let to = point(monotone.to.x, monotone.to.y);
|
||||
if from == to {
|
||||
return;
|
||||
}
|
||||
// Horizontal curves are kept: upward rays cross them.
|
||||
let (p0, p1, sign) = downward(from, to);
|
||||
let ctrl = point(
|
||||
monotone.ctrl.x.clamp(p0.x.min(p1.x), p0.x.max(p1.x)),
|
||||
monotone.ctrl.y.clamp(p0.y, p1.y),
|
||||
);
|
||||
curves.push(Self::new(p0, ctrl, p1, sign));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn downward(from: Point<f32>, to: Point<f32>) -> (Point<f32>, Point<f32>, f32) {
|
||||
if from.y > to.y {
|
||||
(to, from, -1.0)
|
||||
} else {
|
||||
(from, to, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Strokes are expanded in logical pixels. tiny-skia keeps offset curves
|
||||
/// within `0.25 / STROKE_RESOLUTION_SCALE` of exact, a quarter device pixel at
|
||||
/// 2x, and flattens curves to within `0.5 / STROKE_RESOLUTION_SCALE` to measure
|
||||
/// dashes. Round joins and caps ignore it: their arcs are approximated to 0.25
|
||||
/// logical pixels.
|
||||
const STROKE_RESOLUTION_SCALE: f32 = 2.0;
|
||||
|
||||
/// Returns [`None`] for empty geometry.
|
||||
fn skia_path(path: &lyon_path::Path) -> Option<tiny_skia_path::Path> {
|
||||
let mut builder = tiny_skia_path::PathBuilder::new();
|
||||
for event in path.iter() {
|
||||
match event {
|
||||
Event::Begin { at } => builder.move_to(at.x, at.y),
|
||||
Event::Line { to, .. } => builder.line_to(to.x, to.y),
|
||||
Event::Quadratic { ctrl, to, .. } => builder.quad_to(ctrl.x, ctrl.y, to.x, to.y),
|
||||
Event::Cubic {
|
||||
ctrl1, ctrl2, to, ..
|
||||
} => builder.cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y),
|
||||
Event::End { close, .. } => {
|
||||
if close {
|
||||
builder.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
builder.finish()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,842 @@
|
||||
//! Path fills by per-pixel winding.
|
||||
//!
|
||||
//! [`PathBuilder`](crate::PathBuilder) turns contours into closed chains of
|
||||
//! monotone quadratic curves. To paint the resulting [`Path`](crate::Path), we compute the
|
||||
//! winding number at each pixel on the GPU, as in Eric Lengyel's Slug: we
|
||||
//! cast rays leftward and upward from the pixel and count crossings with the
|
||||
//! path's curves. Crossings within the pixel contribute partial winding to
|
||||
//! approximate coverage across its area. Coverage is then determined by the
|
||||
//! fill rule.
|
||||
//!
|
||||
//! To reduce the number of curves tested against each ray, we preprocess the
|
||||
//! path on the CPU, binning its curves into square cells. Each cell lists the
|
||||
//! curves intersecting or near it. The cell size is chosen per path to balance
|
||||
//! the cost of binning against the cost of shading (see `cell_size`).
|
||||
//!
|
||||
//! Curves outside a cell's list cannot contribute partial winding, so the
|
||||
//! binner sums their winding contributions along a leftward ray from the
|
||||
//! cell's top-left corner into a *backdrop*. For each pixel, the shader starts
|
||||
//! with this backdrop and adds the contributions of the listed curves. It also
|
||||
//! corrects the backdrop to account for unlisted curves' contribution between the
|
||||
//! corner and the pixel.
|
||||
//!
|
||||
//! Neighboring cells with the same curve list and backdrop are merged into
|
||||
//! rectangular [`PathTile`]s, which are uploaded to and drawn by the GPU. For
|
||||
//! example, a large rectangle can become nine tiles: four corners, four edges,
|
||||
//! and an interior.
|
||||
|
||||
use crate::{Bounds, PathCurve, PathTile, Point, ScaledPixels, point};
|
||||
use std::cell::RefCell;
|
||||
|
||||
/// A tile lists every curve within this distance of its bounds. Any other curve
|
||||
/// is more than half a pixel away from the tile, so it cannot contribute partial winding.
|
||||
/// The extra 1/256 covers the rasterizer snapping tile edges to its subpixel grid.
|
||||
const MARGIN: f32 = 0.5 + 1.0 / 256.0;
|
||||
|
||||
/// `f32::min`, `max` and `clamp` without IEEE-compliant NaN handling, which costs a
|
||||
/// compare and blend per call on x86-64's baseline target.
|
||||
trait FastFloat {
|
||||
fn fast_min(self, other: f32) -> f32;
|
||||
fn fast_max(self, other: f32) -> f32;
|
||||
fn fast_clamp(self, min: f32, max: f32) -> f32;
|
||||
}
|
||||
|
||||
impl FastFloat for f32 {
|
||||
#[inline(always)]
|
||||
fn fast_min(self, other: f32) -> f32 {
|
||||
if self < other { self } else { other }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn fast_max(self, other: f32) -> f32 {
|
||||
if self > other { self } else { other }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn fast_clamp(self, min: f32, max: f32) -> f32 {
|
||||
self.fast_max(min).fast_min(max)
|
||||
}
|
||||
}
|
||||
|
||||
/// A path's curves binned into tiles for one display scale.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct PathTiles {
|
||||
bounds: Bounds<ScaledPixels>,
|
||||
tiles: Vec<PathTile>,
|
||||
/// Every tile's curve list, concatenated.
|
||||
curves: Vec<PathCurve>,
|
||||
}
|
||||
|
||||
impl PathTiles {
|
||||
pub(crate) fn bounds(&self) -> Bounds<ScaledPixels> {
|
||||
self.bounds
|
||||
}
|
||||
|
||||
pub(crate) fn painted_bounds(&self) -> Bounds<ScaledPixels> {
|
||||
if self.tiles.is_empty() {
|
||||
return self.bounds;
|
||||
}
|
||||
self.bounds.dilate(ScaledPixels(MARGIN))
|
||||
}
|
||||
|
||||
pub(crate) fn tiles(&self) -> &[PathTile] {
|
||||
&self.tiles
|
||||
}
|
||||
|
||||
pub(crate) fn curves(&self) -> &[PathCurve] {
|
||||
&self.curves
|
||||
}
|
||||
|
||||
/// Drops the tiles that lie entirely outside `mask`.
|
||||
pub(crate) fn retain_visible(&mut self, mask: Bounds<ScaledPixels>) {
|
||||
self.tiles.retain(|tile| {
|
||||
tile.top_left.x < mask.right().0
|
||||
&& tile.top_left.y < mask.bottom().0
|
||||
&& tile.bottom_right.x > mask.origin.x.0
|
||||
&& tile.bottom_right.y > mask.origin.y.0
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn bin(curves: &[PathCurve], even_odd: bool, scale: f32) -> PathTiles {
|
||||
debug_assert!(scale > 0.0 && scale.is_finite(), "invalid scale {scale}");
|
||||
if curves.is_empty() {
|
||||
return PathTiles::default();
|
||||
}
|
||||
BINNER.with_borrow_mut(|binner| {
|
||||
let (min, max, length) = binner.scale(curves, scale);
|
||||
let Some(grid) = Grid::covering(min, max, curves.len(), length) else {
|
||||
log::warn!("path spanning {min:?} to {max:?} device pixels overflows; skipping");
|
||||
return PathTiles::default();
|
||||
};
|
||||
binner.find_spans(&grid);
|
||||
binner.fill_cells();
|
||||
let (tiles, curves) = binner.merge_cells(&grid, even_odd);
|
||||
let device = |p: Point<f32>| point(ScaledPixels(p.x), ScaledPixels(p.y));
|
||||
PathTiles {
|
||||
bounds: Bounds::from_corners(device(min), device(max)),
|
||||
tiles,
|
||||
curves,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Picks the power-of-two cell size that minimizes the estimated time spent
|
||||
/// binning and shading. Smaller cells list each curve in more cells, which
|
||||
/// costs CPU time. Larger cells make the shader evaluate each listed curve at
|
||||
/// more pixels, which costs GPU time.
|
||||
///
|
||||
/// We estimate the binning and shading time by the following cost model,
|
||||
/// expressed in terms of shader evaluations of one curve at one pixel:
|
||||
///
|
||||
/// ```text
|
||||
/// cost = listings * (LISTING_CPU_COST + area) + empty_cells * EMPTY_CELL_CPU_COST
|
||||
/// ```
|
||||
fn cell_size(curves: f32, length: f32, size: Point<f32>) -> f32 {
|
||||
// The CPU time of a listing and an empty cell, in shader evaluations,
|
||||
// measured about 634 and 207 on a desktop (RX 6600) and 68 and 21 on an
|
||||
// integrated GPU (HD 4600). Of the values in between, these lost the least
|
||||
// on either machine, measuring CPU and GPU time on realistic paths. Walking
|
||||
// a cell that lists curves has no cost: giving it one made dashed lines use
|
||||
// larger cells, which cost far more GPU time than it saved on the CPU.
|
||||
const LISTING_CPU_COST: f32 = 320.0;
|
||||
const EMPTY_CELL_CPU_COST: f32 = 95.0;
|
||||
// Smaller cells save GPU time, but on realistic paths they measured
|
||||
// costing more CPU time than they saved, on both machines.
|
||||
const MIN_CELL_SIZE: f32 = 16.0;
|
||||
// Limits the grid's memory and walking time when the estimate undercounts
|
||||
// empty cells, as when most curves crowd into a few cells of a large path.
|
||||
const MAX_GRID_CELLS: f32 = 4096.0;
|
||||
|
||||
let grid_cells = |cell_size: f32| {
|
||||
((size.x / cell_size).floor() + 1.0) * ((size.y / cell_size).floor() + 1.0)
|
||||
};
|
||||
let extent = size.x.fast_max(size.y);
|
||||
let mut cell_size = MIN_CELL_SIZE;
|
||||
while grid_cells(cell_size) > MAX_GRID_CELLS {
|
||||
cell_size *= 2.0;
|
||||
}
|
||||
let mut best = (f32::INFINITY, cell_size);
|
||||
loop {
|
||||
let listings = if cell_size >= extent {
|
||||
curves
|
||||
} else {
|
||||
// Since curves are monotone, each crosses about `(w + h) / cell_size` grid lines.
|
||||
curves + length / cell_size
|
||||
};
|
||||
let area = cell_size.fast_min(size.x) * cell_size.fast_min(size.y) / 2.0;
|
||||
let empty_cells = (grid_cells(cell_size) - listings).fast_max(0.0);
|
||||
let cost = listings * (LISTING_CPU_COST + area) + empty_cells * EMPTY_CELL_CPU_COST;
|
||||
if cost < best.0 {
|
||||
best = (cost, cell_size);
|
||||
}
|
||||
if cell_size >= extent {
|
||||
return best.1;
|
||||
}
|
||||
cell_size *= 2.0;
|
||||
}
|
||||
}
|
||||
|
||||
fn fills(winding: i32, even_odd: bool) -> bool {
|
||||
if even_odd {
|
||||
winding % 2 != 0
|
||||
} else {
|
||||
winding != 0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Binner {
|
||||
/// The path's curves, scaled into device pixels.
|
||||
input: Vec<PathCurve>,
|
||||
spans: Vec<Span>,
|
||||
/// Per cell, where its list ends in `keys`. Reused while binning, as in a
|
||||
/// counting sort: `find_spans` stores each cell's count here, and
|
||||
/// `fill_cells` turns the counts into starts and advances them as it
|
||||
/// fills each list.
|
||||
cell_ends: Vec<usize>,
|
||||
/// Per cell, the winding steps of curves crossing its row's top to its
|
||||
/// left, other than those it lists.
|
||||
steps: Vec<i32>,
|
||||
/// Each cell's listings: a curve's leftmost x above its index.
|
||||
keys: Vec<u64>,
|
||||
/// The current row's runs.
|
||||
runs: Vec<Run>,
|
||||
/// The previous row's runs, whose tiles the current row can extend down.
|
||||
above: Vec<Run>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static BINNER: RefCell<Binner> = Default::default();
|
||||
}
|
||||
|
||||
/// A curve's run of consecutive cells within a row.
|
||||
struct Span {
|
||||
cell: usize,
|
||||
count: usize,
|
||||
key: u64,
|
||||
}
|
||||
|
||||
impl Binner {
|
||||
fn scale(&mut self, curves: &[PathCurve], scale: f32) -> (Point<f32>, Point<f32>, f32) {
|
||||
let mut min = point(f32::INFINITY, f32::INFINITY);
|
||||
let mut max = point(f32::NEG_INFINITY, f32::NEG_INFINITY);
|
||||
let mut length = 0.0;
|
||||
self.input.clear();
|
||||
self.input.extend(curves.iter().map(|curve| {
|
||||
let curve = curve.scaled(scale);
|
||||
// The extents of a monotone curve can be computed from its endpoints.
|
||||
min.x = min.x.fast_min(curve.min_x());
|
||||
max.x = max.x.fast_max(curve.max_x());
|
||||
min.y = min.y.fast_min(curve.p0.y);
|
||||
max.y = max.y.fast_max(curve.p1.y);
|
||||
length += curve.max_x() - curve.min_x() + curve.p1.y - curve.p0.y;
|
||||
curve
|
||||
}));
|
||||
(min, max, length)
|
||||
}
|
||||
|
||||
fn find_spans(&mut self, grid: &Grid) {
|
||||
let cells = grid.rows * grid.columns;
|
||||
self.spans.clear();
|
||||
self.cell_ends.clear();
|
||||
self.cell_ends.resize(cells, 0);
|
||||
self.steps.clear();
|
||||
self.steps.resize(cells, 0);
|
||||
for (index, curve) in self.input.iter().enumerate() {
|
||||
// This key sorts curves by leftmost x, which is used by the shader's early exit;
|
||||
// then by index, so that curves are totally ordered.
|
||||
let key = u64::from(ordered_bits(curve.min_x())) << 32 | index as u64;
|
||||
for row in grid.row_of(curve.p0.y - MARGIN)..=grid.row_of(curve.p1.y + MARGIN) {
|
||||
let row_top = grid.y(row);
|
||||
let (low, high) = curve.x_range(row_top - MARGIN, grid.y(row + 1) + MARGIN);
|
||||
let first = grid.column_of(low - MARGIN);
|
||||
let last = grid.column_of(high + MARGIN);
|
||||
let cell = row * grid.columns + first;
|
||||
let count = last + 1 - first;
|
||||
self.spans.push(Span { cell, count, key });
|
||||
for listings in self
|
||||
.cell_ends
|
||||
.get_mut(cell..cell + count)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
*listings += 1;
|
||||
}
|
||||
|
||||
// If this curve contributes to cell backdrops, record its contribution
|
||||
// in the first cell to the right of its span.
|
||||
if curve.crosses(row_top)
|
||||
&& last + 1 < grid.columns
|
||||
&& let Some(step) = self.steps.get_mut(cell + count)
|
||||
{
|
||||
*step += curve.step();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_cells(&mut self) {
|
||||
let mut total = 0;
|
||||
for end in self.cell_ends.iter_mut() {
|
||||
let count = *end;
|
||||
*end = total;
|
||||
total += count;
|
||||
}
|
||||
self.keys.clear();
|
||||
self.keys.resize(total, 0);
|
||||
for span in &self.spans {
|
||||
for cursor in self
|
||||
.cell_ends
|
||||
.get_mut(span.cell..span.cell + span.count)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
if let Some(key) = self.keys.get_mut(*cursor) {
|
||||
*key = span.key;
|
||||
}
|
||||
*cursor += 1;
|
||||
}
|
||||
}
|
||||
let mut start = 0;
|
||||
for &end in &self.cell_ends {
|
||||
self.keys
|
||||
.get_mut(start..end)
|
||||
.unwrap_or_default()
|
||||
.sort_unstable();
|
||||
start = end;
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_cells(&mut self, grid: &Grid, even_odd: bool) -> (Vec<PathTile>, Vec<PathCurve>) {
|
||||
let Binner {
|
||||
input,
|
||||
steps,
|
||||
cell_ends,
|
||||
keys,
|
||||
runs,
|
||||
above,
|
||||
..
|
||||
} = self;
|
||||
let mut tiles: Vec<PathTile> = Vec::new();
|
||||
// Each listing is copied at most once.
|
||||
let mut curves = Vec::with_capacity(keys.len());
|
||||
above.clear();
|
||||
let mut cell_start = 0;
|
||||
for row in 0..grid.rows {
|
||||
runs.clear();
|
||||
let mut backdrop = 0;
|
||||
for column in 0..grid.columns {
|
||||
let index = row * grid.columns + column;
|
||||
backdrop += steps.get(index).copied().unwrap_or(0);
|
||||
let cell_end = cell_ends.get(index).copied().unwrap_or(cell_start);
|
||||
let list = (cell_start, cell_end);
|
||||
cell_start = cell_end;
|
||||
|
||||
let cell = grid.cell(column, row);
|
||||
let quad = if list.0 == list.1 {
|
||||
fills(backdrop, even_odd).then(|| (cell.top_left(), cell.bottom_right()))
|
||||
} else {
|
||||
let mut measure = Measure::new(cell, backdrop);
|
||||
for curve in listed(keys, input, list) {
|
||||
measure.add(curve);
|
||||
}
|
||||
measure.quad(even_odd)
|
||||
};
|
||||
let Some((top_left, bottom_right)) = quad else {
|
||||
continue;
|
||||
};
|
||||
let run = Run {
|
||||
start: column,
|
||||
end: column + 1,
|
||||
backdrop,
|
||||
list,
|
||||
top_left,
|
||||
bottom_right,
|
||||
tile: 0,
|
||||
};
|
||||
match runs.last_mut() {
|
||||
Some(last) if last.end == run.start && last.shades_like(&run, keys) => {
|
||||
last.end = run.end;
|
||||
extend_quad(&mut last.top_left, &mut last.bottom_right, &run);
|
||||
}
|
||||
_ => runs.push(run),
|
||||
}
|
||||
}
|
||||
|
||||
// Both rows' runs are in column order.
|
||||
let mut above_runs = above.iter().peekable();
|
||||
for run in runs.iter_mut() {
|
||||
while above_runs
|
||||
.next_if(|other| other.start < run.start)
|
||||
.is_some()
|
||||
{}
|
||||
let matching = above_runs.next_if(|other| {
|
||||
other.start == run.start && other.end == run.end && other.shades_like(run, keys)
|
||||
});
|
||||
run.tile = match matching {
|
||||
Some(above_run) => {
|
||||
if let Some(tile) = tiles.get_mut(above_run.tile) {
|
||||
extend_quad(&mut tile.top_left, &mut tile.bottom_right, run);
|
||||
}
|
||||
above_run.tile
|
||||
}
|
||||
None => {
|
||||
let curve_start = curves.len();
|
||||
// Tiles are trimmed to their curves' extents, so the path is known to be
|
||||
// filled for pixels outside this box.
|
||||
let mut curves_top_left = point(f32::INFINITY, f32::INFINITY);
|
||||
let mut curves_bottom_right = point(f32::NEG_INFINITY, f32::NEG_INFINITY);
|
||||
for curve in listed(keys, input, run.list) {
|
||||
// The rasterizer snaps tile edges to its subpixel grid, so it can
|
||||
// shade a pixel just outside a tile. Where the tile is trimmed, that
|
||||
// pixel would also be outside the box, and be wrongly filled. Dilate
|
||||
// the box by more than the largest snapping error to prevent this.
|
||||
const BOX_MARGIN: f32 = MARGIN + 1.0 / 16.0;
|
||||
|
||||
curves_top_left.x =
|
||||
curves_top_left.x.fast_min(curve.min_x() - BOX_MARGIN);
|
||||
curves_top_left.y = curves_top_left.y.fast_min(curve.p0.y - BOX_MARGIN);
|
||||
curves_bottom_right.x =
|
||||
curves_bottom_right.x.fast_max(curve.max_x() + BOX_MARGIN);
|
||||
curves_bottom_right.y =
|
||||
curves_bottom_right.y.fast_max(curve.p1.y + BOX_MARGIN);
|
||||
curves.push(*curve);
|
||||
}
|
||||
tiles.push(PathTile {
|
||||
paint: 0,
|
||||
curve_start: curve_start as u32,
|
||||
curve_count: (curves.len() - curve_start) as u32,
|
||||
top_left: run.top_left,
|
||||
bottom_right: run.bottom_right,
|
||||
reference: grid.cell(run.start, row).top_left(),
|
||||
backdrop: run.backdrop,
|
||||
curves_top_left,
|
||||
curves_bottom_right,
|
||||
});
|
||||
tiles.len() - 1
|
||||
}
|
||||
};
|
||||
}
|
||||
std::mem::swap(above, runs);
|
||||
}
|
||||
(tiles, curves)
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps finite floats to integers in the same order.
|
||||
fn ordered_bits(x: f32) -> u32 {
|
||||
let bits = x.to_bits();
|
||||
if bits >> 31 == 1 {
|
||||
!bits
|
||||
} else {
|
||||
bits | 1 << 31
|
||||
}
|
||||
}
|
||||
|
||||
/// Consecutive cells in a row, over columns `start..end`, that would be
|
||||
/// shaded identically.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Run {
|
||||
start: usize,
|
||||
end: usize,
|
||||
backdrop: i32,
|
||||
/// The cells' list, as a range of `keys`.
|
||||
list: (usize, usize),
|
||||
top_left: Point<f32>,
|
||||
bottom_right: Point<f32>,
|
||||
tile: usize,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
/// Whether the two have the same backdrop and list the same curves.
|
||||
fn shades_like(&self, other: &Run, keys: &[u64]) -> bool {
|
||||
self.backdrop == other.backdrop
|
||||
&& keys.get(self.list.0..self.list.1) == keys.get(other.list.0..other.list.1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Grows a quad to cover a run's quad.
|
||||
fn extend_quad(top_left: &mut Point<f32>, bottom_right: &mut Point<f32>, run: &Run) {
|
||||
top_left.x = top_left.x.fast_min(run.top_left.x);
|
||||
top_left.y = top_left.y.fast_min(run.top_left.y);
|
||||
bottom_right.x = bottom_right.x.fast_max(run.bottom_right.x);
|
||||
bottom_right.y = bottom_right.y.fast_max(run.bottom_right.y);
|
||||
}
|
||||
|
||||
/// The curves in a range of `keys`.
|
||||
fn listed<'a>(
|
||||
keys: &'a [u64],
|
||||
input: &'a [PathCurve],
|
||||
list: (usize, usize),
|
||||
) -> impl Iterator<Item = &'a PathCurve> {
|
||||
keys.get(list.0..list.1)
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(move |&key| input.get(key as u32 as usize))
|
||||
}
|
||||
|
||||
struct Grid {
|
||||
left: f32,
|
||||
top: f32,
|
||||
cell_size: f32,
|
||||
columns: usize,
|
||||
rows: usize,
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
fn covering(min: Point<f32>, max: Point<f32>, curves: usize, length: f32) -> Option<Self> {
|
||||
let left = (min.x - MARGIN).floor();
|
||||
let top = (min.y - MARGIN).floor();
|
||||
let size = point(max.x + MARGIN - left, max.y + MARGIN - top);
|
||||
if !(size.x.is_finite() && size.y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let cell_size = cell_size(curves as f32, length, size);
|
||||
Some(Self {
|
||||
left,
|
||||
top,
|
||||
cell_size,
|
||||
columns: (size.x / cell_size) as usize + 1,
|
||||
rows: (size.y / cell_size) as usize + 1,
|
||||
})
|
||||
}
|
||||
|
||||
fn column_of(&self, x: f32) -> usize {
|
||||
let column = (x - self.left) / self.cell_size;
|
||||
column.fast_clamp(0.0, (self.columns - 1) as f32) as u32 as usize
|
||||
}
|
||||
|
||||
fn row_of(&self, y: f32) -> usize {
|
||||
let row = (y - self.top) / self.cell_size;
|
||||
row.fast_clamp(0.0, (self.rows - 1) as f32) as u32 as usize
|
||||
}
|
||||
|
||||
fn x(&self, column: usize) -> f32 {
|
||||
self.left + column as f32 * self.cell_size
|
||||
}
|
||||
|
||||
fn y(&self, row: usize) -> f32 {
|
||||
self.top + row as f32 * self.cell_size
|
||||
}
|
||||
|
||||
fn cell(&self, column: usize, row: usize) -> Cell {
|
||||
Cell {
|
||||
left: self.x(column),
|
||||
top: self.y(row),
|
||||
right: self.x(column + 1),
|
||||
bottom: self.y(row + 1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Cell {
|
||||
left: f32,
|
||||
top: f32,
|
||||
right: f32,
|
||||
bottom: f32,
|
||||
}
|
||||
|
||||
impl Cell {
|
||||
fn top_left(self) -> Point<f32> {
|
||||
point(self.left, self.top)
|
||||
}
|
||||
|
||||
fn bottom_right(self) -> Point<f32> {
|
||||
point(self.right, self.bottom)
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates the bounds and windings of a cell's curves, to trim its quad.
|
||||
struct Measure {
|
||||
cell: Cell,
|
||||
backdrop: i32,
|
||||
min: Point<f32>,
|
||||
max: Point<f32>,
|
||||
/// Left of and above every curve, no correction applies, so the winding
|
||||
/// is the backdrop. Right of every curve, it is the backdrop plus the
|
||||
/// curves crossing the cell's top; below every curve, the backdrop
|
||||
/// corrected for the endpoints beside the cell's left edge.
|
||||
right_winding: i32,
|
||||
bottom_winding: i32,
|
||||
}
|
||||
|
||||
impl Measure {
|
||||
fn new(cell: Cell, backdrop: i32) -> Self {
|
||||
Self {
|
||||
cell,
|
||||
backdrop,
|
||||
min: point(f32::INFINITY, f32::INFINITY),
|
||||
max: point(f32::NEG_INFINITY, f32::NEG_INFINITY),
|
||||
right_winding: backdrop,
|
||||
bottom_winding: backdrop,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn add(&mut self, curve: &PathCurve) {
|
||||
let cell = self.cell;
|
||||
self.min.x = self.min.x.fast_min(curve.min_x());
|
||||
self.max.x = self.max.x.fast_max(curve.max_x());
|
||||
self.min.y = self.min.y.fast_min(curve.p0.y);
|
||||
self.max.y = self.max.y.fast_max(curve.p1.y);
|
||||
if curve.crosses(cell.top) {
|
||||
self.right_winding += curve.step();
|
||||
}
|
||||
for (endpoint, step) in curve.endpoints() {
|
||||
if endpoint.x <= cell.left && endpoint.y > cell.top {
|
||||
self.bottom_winding -= step;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The top-left and bottom-right corners of the quad to shade, if any:
|
||||
/// the cell, trimmed to within `MARGIN` of the curves on each side where
|
||||
/// the winding beyond them leaves pixels unfilled.
|
||||
#[inline(always)]
|
||||
fn quad(&self, even_odd: bool) -> Option<(Point<f32>, Point<f32>)> {
|
||||
let cell = self.cell;
|
||||
let clamp_x = |x: f32| x.fast_clamp(cell.left, cell.right);
|
||||
let clamp_y = |y: f32| y.fast_clamp(cell.top, cell.bottom);
|
||||
let unfilled = !fills(self.backdrop, even_odd);
|
||||
let left = if unfilled {
|
||||
clamp_x(self.min.x - MARGIN)
|
||||
} else {
|
||||
cell.left
|
||||
};
|
||||
let top = if unfilled {
|
||||
clamp_y(self.min.y - MARGIN)
|
||||
} else {
|
||||
cell.top
|
||||
};
|
||||
let right = if fills(self.right_winding, even_odd) {
|
||||
cell.right
|
||||
} else {
|
||||
clamp_x(self.max.x + MARGIN)
|
||||
};
|
||||
let bottom = if fills(self.bottom_winding, even_odd) {
|
||||
cell.bottom
|
||||
} else {
|
||||
clamp_y(self.max.y + MARGIN)
|
||||
};
|
||||
(left < right && top < bottom).then(|| (point(left, top), point(right, bottom)))
|
||||
}
|
||||
}
|
||||
|
||||
impl PathCurve {
|
||||
fn scaled(&self, scale: f32) -> Self {
|
||||
let scale_point = |p: Point<f32>| point(p.x * scale, p.y * scale);
|
||||
Self {
|
||||
p0: scale_point(self.p0),
|
||||
p1: scale_point(self.p1),
|
||||
a: scale_point(self.a),
|
||||
b: scale_point(self.b),
|
||||
sign: self.sign,
|
||||
pad: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn min_x(&self) -> f32 {
|
||||
self.p0.x.fast_min(self.p1.x)
|
||||
}
|
||||
|
||||
fn max_x(&self) -> f32 {
|
||||
self.p0.x.fast_max(self.p1.x)
|
||||
}
|
||||
|
||||
fn step(&self) -> i32 {
|
||||
if self.sign < 0.0 { -1 } else { 1 }
|
||||
}
|
||||
|
||||
/// Whether the curve crosses the horizontal line at `y`. It's half-open,
|
||||
/// so where two curves meet on the line, exactly one of them crosses it.
|
||||
fn crosses(&self, y: f32) -> bool {
|
||||
self.p0.y <= y && y < self.p1.y
|
||||
}
|
||||
|
||||
/// Each endpoint with the step the shader corrects for it.
|
||||
fn endpoints(&self) -> [(Point<f32>, i32); 2] {
|
||||
[(self.p0, self.step()), (self.p1, -self.step())]
|
||||
}
|
||||
|
||||
/// The curve's x extent between two heights.
|
||||
fn x_range(&self, top: f32, bottom: f32) -> (f32, f32) {
|
||||
let top = top.fast_max(self.p0.y);
|
||||
let bottom = bottom.fast_min(self.p1.y);
|
||||
let x_top = if top <= self.p0.y {
|
||||
self.p0.x
|
||||
} else {
|
||||
self.x_at_y(top)
|
||||
};
|
||||
let x_bottom = if bottom >= self.p1.y {
|
||||
self.p1.x
|
||||
} else {
|
||||
self.x_at_y(bottom)
|
||||
};
|
||||
// Clamped so rounding can't carry the range past the curve's extent.
|
||||
(
|
||||
x_top.fast_min(x_bottom).fast_max(self.min_x()),
|
||||
x_top.fast_max(x_bottom).fast_min(self.max_x()),
|
||||
)
|
||||
}
|
||||
|
||||
fn x_at_y(&self, y: f32) -> f32 {
|
||||
if self.a.y == 0.0 {
|
||||
if self.b.y == 0.0 {
|
||||
return self.p0.x;
|
||||
}
|
||||
let t = ((y - self.p0.y) / self.b.y).fast_clamp(0.0, 1.0);
|
||||
return (self.a.x * t + self.b.x) * t + self.p0.x;
|
||||
}
|
||||
let t = monotone_quadratic_root(self.a.y, self.b.y, self.p0.y - y, 1.0);
|
||||
(self.a.x * t + self.b.x) * t + self.p0.x
|
||||
}
|
||||
}
|
||||
|
||||
/// Solves a*t^2 + b*t + c = 0 for the root in [0, 1] on a monotone piece.
|
||||
fn monotone_quadratic_root(a: f32, b: f32, c: f32, direction: f32) -> f32 {
|
||||
let discriminant = (b * b - 4.0 * a * c).fast_max(0.0);
|
||||
let denominator = b + direction * discriminant.sqrt();
|
||||
if denominator == 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
(-2.0 * c / denominator).fast_clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
ContentMask, Outline, PaintedPath, Path, PathBuilder, Pixels, Scene, black, px, size,
|
||||
};
|
||||
|
||||
/// A rectangle spanning many cells is four edge strips, four corners and
|
||||
/// one interior, however many cells it covers.
|
||||
#[test]
|
||||
fn rectangle_is_nine_tiles() {
|
||||
let path = square(100., 40., 900., 600.);
|
||||
assert_eq!(path.bin(1.25).tiles().len(), 9);
|
||||
}
|
||||
|
||||
/// A path far larger than the window is binned coarsely, and painting it
|
||||
/// keeps only the tiles its clip shows.
|
||||
#[test]
|
||||
fn huge_path_paints_only_visible_tiles() {
|
||||
let path = square(-20000., -20000., 20000., 20000.);
|
||||
let tile_count = path.bin(1.5).tiles().len();
|
||||
assert!(tile_count < 10_000, "{tile_count} tiles");
|
||||
|
||||
let mask = Bounds {
|
||||
origin: point(px(300.), px(200.)),
|
||||
size: size(px(120.), px(90.)),
|
||||
};
|
||||
let mut scene = Scene::default();
|
||||
scene.insert_primitive(PaintedPath::new(
|
||||
path,
|
||||
1.5,
|
||||
ContentMask { bounds: mask },
|
||||
black().into(),
|
||||
));
|
||||
scene.finish();
|
||||
let painted: usize = scene.paths.iter().map(PaintedPath::tile_count).sum();
|
||||
assert!(painted > 0 && painted < 20, "{painted} tiles");
|
||||
}
|
||||
|
||||
/// A path whose size overflows, at some scale or at any, is skipped.
|
||||
#[test]
|
||||
fn overflowing_paths_are_skipped() {
|
||||
let radius = f32::MAX / 4.0;
|
||||
let path = square(-radius, -radius, radius, radius);
|
||||
assert!(!path.bin(1.0).tiles().is_empty());
|
||||
assert!(path.bin(4.0).tiles().is_empty());
|
||||
let radius = f32::MAX * 0.75;
|
||||
let path = square(-radius, -radius, radius, radius);
|
||||
assert!(path.bin(1.0).tiles().is_empty());
|
||||
}
|
||||
|
||||
/// A non-finite point fails the whole path. Dropping only its segments
|
||||
/// would leave its contour open.
|
||||
#[test]
|
||||
fn non_finite_point_fails_path() {
|
||||
// Built directly, since lyon asserts its points are finite in debug
|
||||
// builds.
|
||||
let mut outline = Outline::default();
|
||||
outline.move_to(point(0., 0.));
|
||||
outline.line_to(point(10., 0.));
|
||||
outline.line_to(point(10., 10.));
|
||||
outline.move_to(point(20., 0.));
|
||||
outline.line_to(point(f32::NAN, 5.));
|
||||
outline.line_to(point(30., 10.));
|
||||
assert!(outline.into_curves().is_err());
|
||||
}
|
||||
|
||||
/// The shader's backdrop corrections need curves that meet to share
|
||||
/// bit-identical endpoints. A break shows up as streaks, not as a
|
||||
/// failure, so check it directly.
|
||||
#[test]
|
||||
fn endpoints_balance() {
|
||||
let mut curved_fill = PathBuilder::fill();
|
||||
curved_fill.move_to(point(px(450.3), px(280.7)));
|
||||
curved_fill.curve_to(point(px(530.3), px(230.7)), point(px(450.3), px(230.7)));
|
||||
curved_fill.arc_to(
|
||||
point(px(30.), px(30.)),
|
||||
px(0.),
|
||||
false,
|
||||
false,
|
||||
point(px(590.3), px(230.7)),
|
||||
);
|
||||
curved_fill.close();
|
||||
|
||||
let mut stroke = PathBuilder::stroke(px(2.));
|
||||
stroke.move_to(point(px(80.3), px(500.7)));
|
||||
stroke.cubic_bezier_to(
|
||||
point(px(900.), px(250.)),
|
||||
point(px(300.), px(50.)),
|
||||
point(px(700.), px(800.)),
|
||||
);
|
||||
|
||||
let mut dashed = PathBuilder::stroke(px(3.)).dash_array(&[px(9.), px(4.)]);
|
||||
dashed.move_to(point(px(50.3), px(10.7)));
|
||||
dashed.arc_to(
|
||||
point(px(40.), px(40.)),
|
||||
px(0.),
|
||||
false,
|
||||
true,
|
||||
point(px(90.3), px(50.7)),
|
||||
);
|
||||
|
||||
for (name, builder) in [
|
||||
("curved fill", curved_fill),
|
||||
("stroke", stroke),
|
||||
("dashed stroke", dashed),
|
||||
] {
|
||||
let (curves, _) = builder.outline().unwrap();
|
||||
let mut balance = collections::HashMap::<(u32, u32), i32>::default();
|
||||
for curve in &curves {
|
||||
for (endpoint, step) in curve.endpoints() {
|
||||
*balance
|
||||
.entry((endpoint.x.to_bits(), endpoint.y.to_bits()))
|
||||
.or_default() += step;
|
||||
}
|
||||
}
|
||||
assert!(!balance.is_empty(), "{name} produced no curves");
|
||||
for ((x, y), sum) in balance {
|
||||
assert_eq!(
|
||||
sum,
|
||||
0,
|
||||
"{name}: endpoints at ({}, {}) do not balance",
|
||||
f32::from_bits(x),
|
||||
f32::from_bits(y),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn square(left: f32, top: f32, right: f32, bottom: f32) -> Path {
|
||||
let mut builder = PathBuilder::fill();
|
||||
let corners = [(left, top), (right, top), (right, bottom), (left, bottom)];
|
||||
let points: Vec<Point<Pixels>> =
|
||||
corners.iter().map(|&(x, y)| point(px(x), px(y))).collect();
|
||||
builder.add_polygon(&points, true);
|
||||
builder.build().unwrap()
|
||||
}
|
||||
}
|
||||
@@ -209,7 +209,7 @@ impl ActivityGuard {
|
||||
#[inline]
|
||||
pub fn guess_compositor() -> &'static str {
|
||||
if std::env::var_os("ZED_HEADLESS").is_some() {
|
||||
return "Headless";
|
||||
return "headless";
|
||||
}
|
||||
GraphicalEnvironment::detect().guess_compositor()
|
||||
}
|
||||
@@ -231,6 +231,11 @@ pub struct GraphicalEnvironment {
|
||||
pub x11_display: Option<OsString>,
|
||||
/// `XDG_RUNTIME_DIR`: the directory containing Wayland sockets.
|
||||
pub xdg_runtime_dir: Option<OsString>,
|
||||
/// `XDG_CURRENT_DESKTOP`: the session's desktop environment, such as `ubuntu:GNOME`.
|
||||
///
|
||||
/// Only reported by [`GraphicalEnvironment::desktop_environment`]; [`GraphicalEnvironment::apply_to`]
|
||||
/// leaves it alone.
|
||||
pub current_desktop: Option<OsString>,
|
||||
/// `XDG_ACTIVATION_TOKEN`: lets the first window take focus on Wayland.
|
||||
///
|
||||
/// A platform takes this process's token from its environment when it's created, and uses
|
||||
@@ -272,6 +277,11 @@ impl GraphicalEnvironment {
|
||||
/// Does nothing on this platform: programs inherit the session of the process that
|
||||
/// starts them.
|
||||
pub fn apply_to(&self, _command: &mut std::process::Command) {}
|
||||
|
||||
/// Returns `None`: this platform has no desktop environments to tell apart.
|
||||
pub fn desktop_environment(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The graphical session to connect to. Carries nothing yet on this platform.
|
||||
@@ -288,6 +298,11 @@ impl GraphicalEnvironment {
|
||||
|
||||
/// Does nothing on this platform.
|
||||
pub fn apply_to(&self, _command: &mut std::process::Command) {}
|
||||
|
||||
/// Returns `None`: this platform has no desktop environments to tell apart.
|
||||
pub fn desktop_environment(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A display mode for [`App::request_windowing`] to switch to.
|
||||
@@ -310,6 +325,7 @@ impl GraphicalEnvironment {
|
||||
wayland_display: std::env::var_os("WAYLAND_DISPLAY"),
|
||||
x11_display: std::env::var_os("DISPLAY"),
|
||||
xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
|
||||
current_desktop: std::env::var_os("XDG_CURRENT_DESKTOP"),
|
||||
activation_token: None,
|
||||
}
|
||||
}
|
||||
@@ -330,6 +346,18 @@ impl GraphicalEnvironment {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the session's desktop environment, if `XDG_CURRENT_DESKTOP` names one.
|
||||
///
|
||||
/// The value is a colon-separated list ordered from most to least specific,
|
||||
/// such as `ubuntu:GNOME`.
|
||||
pub fn desktop_environment(&self) -> Option<String> {
|
||||
self.current_desktop
|
||||
.as_ref()
|
||||
.and_then(|desktop| desktop.to_str())
|
||||
.filter(|desktop| !desktop.is_empty())
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// Returns the compositor this environment selects: Wayland, then X11, then headless.
|
||||
///
|
||||
/// Does not attempt to connect to the compositor.
|
||||
@@ -341,7 +369,7 @@ impl GraphicalEnvironment {
|
||||
} else if cfg!(feature = "x11") && is_set(&self.x11_display) {
|
||||
"X11"
|
||||
} else {
|
||||
"Headless"
|
||||
"headless"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -510,6 +538,11 @@ pub trait Platform: 'static {
|
||||
fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
|
||||
fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
|
||||
|
||||
/// Platform-specific diagnostic state, for [`App::debug_state`].
|
||||
fn debug_state(&self) -> serde_json::Value {
|
||||
serde_json::Value::Null
|
||||
}
|
||||
|
||||
fn thermal_state(&self) -> ThermalState;
|
||||
fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
|
||||
fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
|
||||
@@ -1304,6 +1337,10 @@ pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
|
||||
fn zoom(&self);
|
||||
fn toggle_fullscreen(&self);
|
||||
fn is_fullscreen(&self) -> bool;
|
||||
/// Platform-specific diagnostic state, for [`App::debug_state`].
|
||||
fn debug_state(&self) -> serde_json::Value {
|
||||
serde_json::Value::Null
|
||||
}
|
||||
fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
|
||||
None
|
||||
}
|
||||
@@ -1349,6 +1386,8 @@ pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
|
||||
#[cfg(target_os = "macos")]
|
||||
fn set_native_titlebar_visibility(&self, _visible: bool) {}
|
||||
fn show_character_palette(&self) {}
|
||||
fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
|
||||
fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
|
||||
@@ -2659,8 +2698,8 @@ pub struct WindowOptions {
|
||||
/// Whether the window should be minimized by the user
|
||||
pub is_minimizable: bool,
|
||||
|
||||
/// The display to create the window on, if this is None,
|
||||
/// the window will be created on the main display
|
||||
/// The display to create the window on. If neither this nor `window_bounds` is set, the window
|
||||
/// is created on the active window's display. Otherwise, it falls back to the primary display.
|
||||
pub display_id: Option<DisplayId>,
|
||||
|
||||
/// The appearance of the window background.
|
||||
@@ -2783,9 +2822,10 @@ impl WindowBounds {
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new window bounds that centers the window on the screen.
|
||||
pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
|
||||
WindowBounds::Windowed(Bounds::centered(None, size, cx))
|
||||
/// Creates window bounds centered on the given display, or the primary display if none is
|
||||
/// provided.
|
||||
pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
|
||||
WindowBounds::Windowed(Bounds::centered(display_id, size, cx))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3010,7 +3050,9 @@ impl From<&str> for PromptButton {
|
||||
}
|
||||
|
||||
/// The style of the cursor (pointer)
|
||||
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
|
||||
#[derive(
|
||||
Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, EnumIter,
|
||||
)]
|
||||
pub enum CursorStyle {
|
||||
/// The default cursor
|
||||
#[default]
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use crate::{
|
||||
AnyWindowHandle, Bounds, DevicePixels, DispatchEventResult, DisplayId, GpuSpecs, HeadlessAtlas,
|
||||
Pixels, PlatformAtlas, PlatformDisplay, PlatformHeadlessRenderer, PlatformInput,
|
||||
PlatformInputHandler, PlatformWindow, Point, PromptButton, RequestFrameOptions, Scene, Size,
|
||||
TestDisplay, TestPlatform, TextInputConfiguration, TextInputStateChange, WindowAppearance,
|
||||
WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowInsets, WindowParams,
|
||||
WindowVisibility,
|
||||
AnyWindowHandle, Bounds, Decorations, DevicePixels, DispatchEventResult, DisplayId, GpuSpecs,
|
||||
HeadlessAtlas, Pixels, Platform, PlatformAtlas, PlatformDisplay, PlatformHeadlessRenderer,
|
||||
PlatformInput, PlatformInputHandler, PlatformWindow, Point, PromptButton, RequestFrameOptions,
|
||||
Scene, Size, TestDisplay, TestPlatform, TextInputConfiguration, TextInputStateChange,
|
||||
WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowInsets,
|
||||
WindowParams, WindowVisibility,
|
||||
};
|
||||
use gpui_util::ResultExt as _;
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
@@ -57,6 +57,7 @@ pub(crate) struct TestWindowState {
|
||||
is_fullscreen: bool,
|
||||
scale_factor: f32,
|
||||
appearance: WindowAppearance,
|
||||
decorations: Decorations,
|
||||
external_drag_files: Vec<(PathBuf, bool)>,
|
||||
start_external_drag_result: bool,
|
||||
}
|
||||
@@ -133,6 +134,7 @@ impl TestWindow {
|
||||
// Preserve the test platform's historical 2x default.
|
||||
scale_factor: 2.0,
|
||||
appearance: WindowAppearance::Light,
|
||||
decorations: Decorations::default(),
|
||||
external_drag_files: Vec::new(),
|
||||
start_external_drag_result: false,
|
||||
})))
|
||||
@@ -277,6 +279,17 @@ impl TestWindow {
|
||||
self.0.lock().appearance_change_callback = Some(callback);
|
||||
}
|
||||
|
||||
pub fn simulate_decorations_change(&self, decorations: Decorations) {
|
||||
let mut lock = self.0.lock();
|
||||
lock.decorations = decorations;
|
||||
let Some(mut callback) = lock.appearance_change_callback.take() else {
|
||||
return;
|
||||
};
|
||||
drop(lock);
|
||||
callback();
|
||||
self.0.lock().appearance_change_callback = Some(callback);
|
||||
}
|
||||
|
||||
/// Returns how many times this window's frame waker has been invoked.
|
||||
pub fn frame_wake_count(&self) -> usize {
|
||||
self.0.lock().frame_wake_count.get()
|
||||
@@ -478,8 +491,21 @@ impl PlatformWindow for TestWindow {
|
||||
}
|
||||
|
||||
fn toggle_fullscreen(&self) {
|
||||
let mut lock = self.0.lock();
|
||||
lock.is_fullscreen = !lock.is_fullscreen;
|
||||
let platform = {
|
||||
let mut lock = self.0.lock();
|
||||
lock.is_fullscreen = !lock.is_fullscreen;
|
||||
lock.platform.upgrade()
|
||||
};
|
||||
if let Some(platform) = platform {
|
||||
let mut window = self.clone();
|
||||
platform
|
||||
.foreground_executor()
|
||||
.spawn(async move {
|
||||
let size = window.0.lock().bounds.size;
|
||||
window.simulate_resize(size);
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
}
|
||||
|
||||
fn is_fullscreen(&self) -> bool {
|
||||
@@ -619,4 +645,8 @@ impl PlatformWindow for TestWindow {
|
||||
fn gpu_specs(&self) -> Option<GpuSpecs> {
|
||||
None
|
||||
}
|
||||
|
||||
fn window_decorations(&self) -> Decorations {
|
||||
self.0.lock().decorations
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1713,8 +1713,8 @@ mod tests {
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct SceneSnapshot {
|
||||
quads: Vec<QuadSnapshot>,
|
||||
/// Every other primitive kind, formatted without the per-window atlas tile and
|
||||
/// path IDs, which differ between two windows drawing the same scene.
|
||||
/// Every other primitive kind, formatted without the per-window atlas tile
|
||||
/// IDs, which differ between two windows drawing the same scene.
|
||||
other_primitives: Vec<String>,
|
||||
element_ids: BTreeSet<u64>,
|
||||
}
|
||||
@@ -1732,12 +1732,7 @@ mod tests {
|
||||
.iter()
|
||||
.map(|underline| format!("{underline:?}")),
|
||||
)
|
||||
.chain(scene.paths.iter().map(|path| {
|
||||
format!(
|
||||
"path {} {:?} {:?} {:?} {:?}",
|
||||
path.order, path.bounds, path.content_mask, path.color, path.vertices
|
||||
)
|
||||
}))
|
||||
.chain(scene.paths.iter().map(|path| format!("{path:?}")))
|
||||
.chain(scene.monochrome_sprites.iter().map(|sprite| {
|
||||
format!(
|
||||
"monochrome {} {:?} {:?} {:?} {:?}",
|
||||
|
||||
+430
-225
@@ -5,19 +5,11 @@ use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, Hsla, Pixels,
|
||||
Point, Radians, ScaledPixels, Size, bounds_tree::BoundsTree, point,
|
||||
AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, Hsla, Path,
|
||||
PathTiles, Pixels, Point, Radians, ScaledPixels, Size, bounds_tree::BoundsTree,
|
||||
};
|
||||
use std::{
|
||||
fmt::Debug,
|
||||
iter::Peekable,
|
||||
ops::{Add, Range, Sub},
|
||||
slice,
|
||||
};
|
||||
|
||||
#[allow(non_camel_case_types, unused)]
|
||||
#[expect(missing_docs)]
|
||||
pub type PathVertex_ScaledPixels = PathVertex<ScaledPixels>;
|
||||
use smallvec::SmallVec;
|
||||
use std::{collections::VecDeque, fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice};
|
||||
|
||||
#[expect(missing_docs)]
|
||||
pub type DrawOrder = u32;
|
||||
@@ -36,15 +28,30 @@ impl From<bool> for PaddedBool32 {
|
||||
}
|
||||
}
|
||||
|
||||
impl PaddedBool32 {
|
||||
/// The wrapped boolean.
|
||||
pub fn as_bool(self) -> bool {
|
||||
self.0 != 0
|
||||
}
|
||||
}
|
||||
|
||||
struct Layer {
|
||||
primitives: SmallVec<[Range<usize>; 1]>,
|
||||
bounds: Bounds<ScaledPixels>,
|
||||
max_kind: PrimitiveKind,
|
||||
max_shared_kind: PrimitiveKind,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
#[expect(missing_docs)]
|
||||
pub struct Scene {
|
||||
pub(crate) paint_operations: Vec<PaintOperation>,
|
||||
primitive_bounds: BoundsTree<ScaledPixels>,
|
||||
layer_stack: Vec<DrawOrder>,
|
||||
layer_stack: Vec<usize>,
|
||||
layers: VecDeque<Layer>,
|
||||
pub shadows: Vec<Shadow>,
|
||||
pub quads: Vec<Quad>,
|
||||
pub paths: Vec<Path<ScaledPixels>>,
|
||||
pub paths: Vec<PaintedPath>,
|
||||
pub underlines: Vec<Underline>,
|
||||
pub monochrome_sprites: Vec<MonochromeSprite>,
|
||||
pub subpixel_sprites: Vec<SubpixelSprite>,
|
||||
@@ -58,6 +65,7 @@ impl Scene {
|
||||
self.paint_operations.clear();
|
||||
self.primitive_bounds.clear();
|
||||
self.layer_stack.clear();
|
||||
self.layers.clear();
|
||||
self.paths.clear();
|
||||
self.shadows.clear();
|
||||
self.quads.clear();
|
||||
@@ -72,93 +80,124 @@ impl Scene {
|
||||
self.paint_operations.len()
|
||||
}
|
||||
|
||||
pub fn push_layer(&mut self, bounds: Bounds<ScaledPixels>) {
|
||||
let order = self.primitive_bounds.insert(bounds);
|
||||
self.layer_stack.push(order);
|
||||
self.paint_operations
|
||||
.push(PaintOperation::StartLayer(bounds));
|
||||
pub fn push_layer(&mut self) {
|
||||
self.layer_stack.push(self.layers.len());
|
||||
self.layers.push_back(Layer {
|
||||
primitives: SmallVec::new(),
|
||||
bounds: Bounds::default(),
|
||||
max_kind: PrimitiveKind::Shadow,
|
||||
max_shared_kind: PrimitiveKind::Surface,
|
||||
});
|
||||
self.paint_operations.push(PaintOperation::StartLayer);
|
||||
}
|
||||
|
||||
pub fn pop_layer(&mut self) {
|
||||
self.layer_stack.pop();
|
||||
if self.layer_stack.is_empty() {
|
||||
while let Some(layer) = self.layers.pop_front() {
|
||||
self.insert_layer(layer);
|
||||
}
|
||||
}
|
||||
self.paint_operations.push(PaintOperation::EndLayer);
|
||||
}
|
||||
|
||||
pub fn insert_primitive(&mut self, primitive: impl Into<Primitive>) {
|
||||
let mut primitive = primitive.into();
|
||||
let clipped_bounds = primitive
|
||||
.bounds()
|
||||
.intersect(&primitive.content_mask().bounds);
|
||||
fn insert_layer(&mut self, layer: Layer) {
|
||||
if layer.primitives.is_empty() {
|
||||
return;
|
||||
}
|
||||
let order =
|
||||
self.primitive_bounds
|
||||
.insert(layer.bounds, layer.max_kind, layer.max_shared_kind);
|
||||
for index in layer.primitives.into_iter().flatten() {
|
||||
if let PaintOperation::Primitive(primitive) = &self.paint_operations[index] {
|
||||
let primitive = primitive.clone();
|
||||
self.push_primitive(primitive, order);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert_primitive(&mut self, primitive: impl Into<Primitive>) {
|
||||
let primitive = primitive.into();
|
||||
let clipped_bounds = primitive.clipped_bounds();
|
||||
if clipped_bounds.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let order = self
|
||||
.layer_stack
|
||||
.last()
|
||||
.copied()
|
||||
.unwrap_or_else(|| self.primitive_bounds.insert(clipped_bounds));
|
||||
match &mut primitive {
|
||||
Primitive::Shadow(shadow) => {
|
||||
shadow.order = order;
|
||||
self.shadows.push(*shadow);
|
||||
}
|
||||
Primitive::Quad(quad) => {
|
||||
quad.order = order;
|
||||
self.quads.push(*quad);
|
||||
}
|
||||
Primitive::Path(path) => {
|
||||
path.order = order;
|
||||
path.id = PathId(self.paths.len());
|
||||
self.paths.push(path.clone());
|
||||
}
|
||||
Primitive::Underline(underline) => {
|
||||
underline.order = order;
|
||||
self.underlines.push(*underline);
|
||||
}
|
||||
Primitive::MonochromeSprite(sprite) => {
|
||||
sprite.order = order;
|
||||
self.monochrome_sprites.push(*sprite);
|
||||
}
|
||||
Primitive::SubpixelSprite(sprite) => {
|
||||
sprite.order = order;
|
||||
self.subpixel_sprites.push(*sprite);
|
||||
}
|
||||
Primitive::PolychromeSprite(sprite) => {
|
||||
sprite.order = order;
|
||||
self.polychrome_sprites.push(*sprite);
|
||||
}
|
||||
Primitive::Surface(surface) => {
|
||||
surface.order = order;
|
||||
self.surfaces.push(surface.clone());
|
||||
let kind = primitive.kind();
|
||||
if let Some(&layer) = self.layer_stack.last()
|
||||
&& let Some(layer) = self.layers.get_mut(layer)
|
||||
{
|
||||
layer.bounds = layer.bounds.join(&clipped_bounds);
|
||||
layer.max_kind = layer.max_kind.max(kind);
|
||||
layer.max_shared_kind = layer.max_shared_kind.min(kind.max_shared_kind());
|
||||
let index = self.paint_operations.len();
|
||||
match layer.primitives.last_mut() {
|
||||
Some(range) if range.end == index => range.end += 1,
|
||||
_ => layer.primitives.push(index..index + 1),
|
||||
}
|
||||
} else {
|
||||
let order = self
|
||||
.primitive_bounds
|
||||
.insert(clipped_bounds, kind, kind.max_shared_kind());
|
||||
self.push_primitive(primitive.clone(), order);
|
||||
}
|
||||
self.paint_operations
|
||||
.push(PaintOperation::Primitive(primitive));
|
||||
}
|
||||
|
||||
fn push_primitive(&mut self, primitive: Primitive, order: DrawOrder) {
|
||||
match primitive {
|
||||
Primitive::Shadow(shadow) => self.shadows.push(Shadow { order, ..shadow }),
|
||||
Primitive::Quad(quad) => self.quads.push(Quad { order, ..quad }),
|
||||
Primitive::Path(mut path) => {
|
||||
path.order = order;
|
||||
self.paths.push(path);
|
||||
}
|
||||
Primitive::Underline(underline) => {
|
||||
self.underlines.push(Underline { order, ..underline })
|
||||
}
|
||||
Primitive::MonochromeSprite(sprite) => self
|
||||
.monochrome_sprites
|
||||
.push(MonochromeSprite { order, ..sprite }),
|
||||
Primitive::SubpixelSprite(sprite) => self
|
||||
.subpixel_sprites
|
||||
.push(SubpixelSprite { order, ..sprite }),
|
||||
Primitive::PolychromeSprite(sprite) => self
|
||||
.polychrome_sprites
|
||||
.push(PolychromeSprite { order, ..sprite }),
|
||||
Primitive::Surface(mut surface) => {
|
||||
surface.order = order;
|
||||
self.surfaces.push(surface);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn replay(&mut self, range: Range<usize>, prev_scene: &Scene) {
|
||||
for operation in &prev_scene.paint_operations[range] {
|
||||
match operation {
|
||||
PaintOperation::Primitive(primitive) => self.insert_primitive(primitive.clone()),
|
||||
PaintOperation::StartLayer(bounds) => self.push_layer(*bounds),
|
||||
PaintOperation::StartLayer => self.push_layer(),
|
||||
PaintOperation::EndLayer => self.pop_layer(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finish(&mut self) {
|
||||
self.shadows.sort_by_key(|shadow| shadow.order);
|
||||
self.quads.sort_by_key(|quad| quad.order);
|
||||
debug_assert!(self.layer_stack.is_empty(), "unbalanced scene layers");
|
||||
let keys = &mut Vec::new();
|
||||
sort_in_place(&mut self.shadows, keys, |shadow| (shadow.order, 0));
|
||||
sort_in_place(&mut self.quads, keys, |quad| (quad.order, 0));
|
||||
self.paths.sort_by_key(|path| path.order);
|
||||
self.underlines.sort_by_key(|underline| underline.order);
|
||||
self.monochrome_sprites
|
||||
.sort_by_key(|sprite| (sprite.order, sprite.tile.texture_id.index));
|
||||
self.subpixel_sprites
|
||||
.sort_by_key(|sprite| (sprite.order, sprite.tile.texture_id.index));
|
||||
self.polychrome_sprites
|
||||
.sort_by_key(|sprite| (sprite.order, sprite.tile.texture_id.index));
|
||||
sort_in_place(&mut self.underlines, keys, |underline| (underline.order, 0));
|
||||
sort_in_place(&mut self.monochrome_sprites, keys, |sprite| {
|
||||
(sprite.order, sprite.tile.texture_id.index)
|
||||
});
|
||||
sort_in_place(&mut self.subpixel_sprites, keys, |sprite| {
|
||||
(sprite.order, sprite.tile.texture_id.index)
|
||||
});
|
||||
sort_in_place(&mut self.polychrome_sprites, keys, |sprite| {
|
||||
(sprite.order, sprite.tile.texture_id.index)
|
||||
});
|
||||
self.surfaces.sort_by_key(|surface| surface.order);
|
||||
}
|
||||
|
||||
@@ -191,6 +230,57 @@ impl Scene {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sorts small `(key, index)` pairs instead of the primitives themselves, then moves each
|
||||
/// primitive into place once. Primitives are large, so a comparison sort that shuffles them
|
||||
/// directly spends most of its time copying. Ties keep insertion order, as `sort_by_key`
|
||||
/// does, because the index is part of what is sorted.
|
||||
fn sort_in_place<T: Copy>(
|
||||
primitives: &mut [T],
|
||||
keys: &mut Vec<(u64, u32)>,
|
||||
key: impl Fn(&T) -> (u32, u32),
|
||||
) {
|
||||
if primitives.is_sorted_by_key(&key) {
|
||||
return;
|
||||
}
|
||||
keys.clear();
|
||||
keys.extend(primitives.iter().enumerate().map(|(index, primitive)| {
|
||||
let (major, minor) = key(primitive);
|
||||
((major as u64) << 32 | minor as u64, index as u32)
|
||||
}));
|
||||
keys.sort_unstable();
|
||||
|
||||
// `keys[target].1` is the source index for `target`. Follow each cycle of that
|
||||
// permutation, marking visited slots by pointing them at themselves.
|
||||
for start in 0..primitives.len() {
|
||||
if keys[start].1 as usize == start {
|
||||
continue;
|
||||
}
|
||||
let displaced = primitives[start];
|
||||
let mut target = start;
|
||||
loop {
|
||||
let source = keys[target].1 as usize;
|
||||
keys[target].1 = target as u32;
|
||||
if source == start {
|
||||
primitives[target] = displaced;
|
||||
break;
|
||||
}
|
||||
primitives[target] = primitives[source];
|
||||
target = source;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The depth step between consecutive quads in a frame with `quad_count` quads.
|
||||
pub fn quad_depth_scale(quad_count: usize) -> f32 {
|
||||
let denominator = (quad_count.min((1 << 24) - 1) + 1).next_power_of_two();
|
||||
1.0 / denominator as f32
|
||||
}
|
||||
|
||||
/// Maps a quad's index in [`Scene::quads`] to depth, with greater values closer.
|
||||
pub fn quad_depth(quad_id: u32, scale: f32) -> f32 {
|
||||
((quad_id + 1) as f32 * scale).min(1.0)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Default)]
|
||||
#[cfg_attr(
|
||||
all(
|
||||
@@ -211,9 +301,26 @@ pub(crate) enum PrimitiveKind {
|
||||
Surface,
|
||||
}
|
||||
|
||||
impl PrimitiveKind {
|
||||
/// We guarantee that overlapping primitives are drawn in paint order.
|
||||
/// But, to improve GPU draw batching, the renderer sorts primitives that
|
||||
/// share a draw order by kind, then by atlas texture, and only then in
|
||||
/// paint order. So, a primitive can only share the draw order of the
|
||||
/// topmost primitive it overlaps if that primitive's kind is at most the
|
||||
/// one returned here. Otherwise, it needs a new draw order.
|
||||
fn max_shared_kind(self) -> Self {
|
||||
match self {
|
||||
Self::MonochromeSprite => Self::Underline,
|
||||
Self::SubpixelSprite => Self::MonochromeSprite,
|
||||
Self::PolychromeSprite => Self::SubpixelSprite,
|
||||
kind => kind,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum PaintOperation {
|
||||
Primitive(Primitive),
|
||||
StartLayer(Bounds<ScaledPixels>),
|
||||
StartLayer,
|
||||
EndLayer,
|
||||
}
|
||||
|
||||
@@ -222,7 +329,7 @@ pub(crate) enum PaintOperation {
|
||||
pub enum Primitive {
|
||||
Shadow(Shadow),
|
||||
Quad(Quad),
|
||||
Path(Path<ScaledPixels>),
|
||||
Path(PaintedPath),
|
||||
Underline(Underline),
|
||||
MonochromeSprite(MonochromeSprite),
|
||||
SubpixelSprite(SubpixelSprite),
|
||||
@@ -232,6 +339,19 @@ pub enum Primitive {
|
||||
|
||||
#[expect(missing_docs)]
|
||||
impl Primitive {
|
||||
pub(crate) fn kind(&self) -> PrimitiveKind {
|
||||
match self {
|
||||
Primitive::Shadow(_) => PrimitiveKind::Shadow,
|
||||
Primitive::Quad(_) => PrimitiveKind::Quad,
|
||||
Primitive::Path(_) => PrimitiveKind::Path,
|
||||
Primitive::Underline(_) => PrimitiveKind::Underline,
|
||||
Primitive::MonochromeSprite(_) => PrimitiveKind::MonochromeSprite,
|
||||
Primitive::SubpixelSprite(_) => PrimitiveKind::SubpixelSprite,
|
||||
Primitive::PolychromeSprite(_) => PrimitiveKind::PolychromeSprite,
|
||||
Primitive::Surface(_) => PrimitiveKind::Surface,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bounds(&self) -> &Bounds<ScaledPixels> {
|
||||
match self {
|
||||
Primitive::Shadow(shadow) => &shadow.bounds,
|
||||
@@ -245,11 +365,25 @@ impl Primitive {
|
||||
}
|
||||
}
|
||||
|
||||
fn transformation(&self) -> TransformationMatrix {
|
||||
match self {
|
||||
Primitive::MonochromeSprite(sprite) => sprite.transformation,
|
||||
Primitive::SubpixelSprite(sprite) => sprite.transformation,
|
||||
_ => TransformationMatrix::unit(),
|
||||
}
|
||||
}
|
||||
|
||||
fn clipped_bounds(&self) -> Bounds<ScaledPixels> {
|
||||
self.transformation()
|
||||
.transform_bounds(*self.bounds())
|
||||
.intersect(&self.content_mask().bounds)
|
||||
}
|
||||
|
||||
pub fn content_mask(&self) -> &ContentMask<ScaledPixels> {
|
||||
match self {
|
||||
Primitive::Shadow(shadow) => &shadow.content_mask,
|
||||
Primitive::Quad(quad) => &quad.content_mask,
|
||||
Primitive::Path(path) => &path.content_mask,
|
||||
Primitive::Path(path) => &path.paint.content_mask,
|
||||
Primitive::Underline(underline) => &underline.content_mask,
|
||||
Primitive::MonochromeSprite(sprite) => &sprite.content_mask,
|
||||
Primitive::SubpixelSprite(sprite) => &sprite.content_mask,
|
||||
@@ -272,7 +406,7 @@ struct BatchIterator<'a> {
|
||||
quads_start: usize,
|
||||
quads_iter: Peekable<slice::Iter<'a, Quad>>,
|
||||
paths_start: usize,
|
||||
paths_iter: Peekable<slice::Iter<'a, Path<ScaledPixels>>>,
|
||||
paths_iter: Peekable<slice::Iter<'a, PaintedPath>>,
|
||||
underlines_start: usize,
|
||||
underlines_iter: Peekable<slice::Iter<'a, Underline>>,
|
||||
monochrome_sprites_start: usize,
|
||||
@@ -295,7 +429,10 @@ impl<'a> Iterator for BatchIterator<'a> {
|
||||
PrimitiveKind::Shadow,
|
||||
),
|
||||
(self.quads_iter.peek().map(|q| q.order), PrimitiveKind::Quad),
|
||||
(self.paths_iter.peek().map(|q| q.order), PrimitiveKind::Path),
|
||||
(
|
||||
self.paths_iter.peek().map(|path| path.order),
|
||||
PrimitiveKind::Path,
|
||||
),
|
||||
(
|
||||
self.underlines_iter.peek().map(|u| u.order),
|
||||
PrimitiveKind::Underline,
|
||||
@@ -578,10 +715,9 @@ pub struct Shadow {
|
||||
pub corner_radii: Corners<ScaledPixels>,
|
||||
pub content_mask: ContentMask<ScaledPixels>,
|
||||
pub color: Hsla,
|
||||
pub element_bounds: Bounds<ScaledPixels>,
|
||||
pub element_corner_radii: Corners<ScaledPixels>,
|
||||
/// 0 = drop shadow (rendered outside the element), 1 = inset shadow (rendered inside).
|
||||
pub inset: u32,
|
||||
pub shape_bounds: Bounds<ScaledPixels>,
|
||||
pub shape_corner_radii: Corners<ScaledPixels>,
|
||||
pub inset: PaddedBool32,
|
||||
pub pad: u32, // align to 8 bytes
|
||||
}
|
||||
|
||||
@@ -686,6 +822,31 @@ impl TransformationMatrix {
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest bounds that contain `bounds` once it is transformed.
|
||||
pub(crate) fn transform_bounds(&self, bounds: Bounds<ScaledPixels>) -> Bounds<ScaledPixels> {
|
||||
if *self == Self::unit() {
|
||||
return bounds;
|
||||
}
|
||||
let [[xx, xy], [yx, yy]] = self.rotation_scale;
|
||||
let [translate_x, translate_y] = self.translation;
|
||||
let corners = [
|
||||
bounds.origin,
|
||||
bounds.top_right(),
|
||||
bounds.bottom_left(),
|
||||
bounds.bottom_right(),
|
||||
]
|
||||
.map(|corner| {
|
||||
Point::new(
|
||||
ScaledPixels(xx * corner.x.0 + xy * corner.y.0 + translate_x),
|
||||
ScaledPixels(yx * corner.x.0 + yy * corner.y.0 + translate_y),
|
||||
)
|
||||
});
|
||||
let [first, rest @ ..] = corners;
|
||||
let top_left = rest.iter().fold(first, |min, corner| min.min(corner));
|
||||
let bottom_right = rest.iter().fold(first, |max, corner| max.max(corner));
|
||||
Bounds::from_corners(top_left, bottom_right)
|
||||
}
|
||||
|
||||
/// Apply transformation to a point, mainly useful for debugging
|
||||
pub fn apply(&self, point: Point<Pixels>) -> Point<Pixels> {
|
||||
let input = [point.x.0, point.y.0];
|
||||
@@ -779,171 +940,215 @@ impl From<PaintSurface> for Primitive {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[repr(C)]
|
||||
#[expect(missing_docs)]
|
||||
pub struct PathId(pub usize);
|
||||
pub struct PathCurve {
|
||||
pub p0: Point<f32>,
|
||||
pub p1: Point<f32>,
|
||||
pub a: Point<f32>,
|
||||
pub b: Point<f32>,
|
||||
pub sign: f32,
|
||||
pub pad: u32, // align to 8 bytes
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[repr(C)]
|
||||
#[expect(missing_docs)]
|
||||
pub struct PathPaint {
|
||||
/// The path's bounds, in device pixels.
|
||||
pub bounds: Bounds<ScaledPixels>,
|
||||
pub content_mask: ContentMask<ScaledPixels>,
|
||||
pub color: Background,
|
||||
pub even_odd: PaddedBool32,
|
||||
pub pad: u32, // align to 8 bytes
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[repr(C)]
|
||||
#[expect(missing_docs)]
|
||||
pub struct PathTile {
|
||||
pub paint: u32,
|
||||
pub curve_start: u32,
|
||||
pub curve_count: u32,
|
||||
pub backdrop: i32,
|
||||
pub top_left: Point<f32>,
|
||||
pub bottom_right: Point<f32>,
|
||||
pub reference: Point<f32>,
|
||||
pub curves_top_left: Point<f32>,
|
||||
pub curves_bottom_right: Point<f32>,
|
||||
}
|
||||
|
||||
/// A line made up of a series of vertices and control points.
|
||||
#[derive(Clone, Debug)]
|
||||
#[expect(missing_docs)]
|
||||
pub struct Path<P: Clone + Debug + Default + PartialEq> {
|
||||
pub id: PathId,
|
||||
pub order: DrawOrder,
|
||||
pub bounds: Bounds<P>,
|
||||
pub content_mask: ContentMask<P>,
|
||||
pub vertices: Vec<PathVertex<P>>,
|
||||
pub color: Background,
|
||||
start: Point<P>,
|
||||
current: Point<P>,
|
||||
contour_count: usize,
|
||||
pub struct PaintedPath {
|
||||
order: DrawOrder,
|
||||
bounds: Bounds<ScaledPixels>,
|
||||
tiles: Rc<PathTiles>,
|
||||
paint: PathPaint,
|
||||
}
|
||||
|
||||
impl Path<Pixels> {
|
||||
/// Create a new path with the given starting point.
|
||||
pub fn new(start: Point<Pixels>) -> Self {
|
||||
#[expect(missing_docs)]
|
||||
impl PaintedPath {
|
||||
/// Bins `path` into tiles, to be filled with `color` within `content_mask`.
|
||||
pub fn new(
|
||||
path: Path,
|
||||
scale_factor: f32,
|
||||
content_mask: ContentMask<Pixels>,
|
||||
color: Background,
|
||||
) -> Self {
|
||||
let content_mask = content_mask.scale(scale_factor);
|
||||
let mut tiles = path.bin(scale_factor);
|
||||
tiles.retain_visible(content_mask.bounds);
|
||||
let paint = PathPaint {
|
||||
bounds: tiles.bounds(),
|
||||
content_mask,
|
||||
color,
|
||||
even_odd: path.even_odd().into(),
|
||||
pad: 0,
|
||||
};
|
||||
Self {
|
||||
id: PathId(0),
|
||||
order: DrawOrder::default(),
|
||||
vertices: Vec::new(),
|
||||
start,
|
||||
current: start,
|
||||
bounds: Bounds {
|
||||
origin: start,
|
||||
size: Default::default(),
|
||||
},
|
||||
content_mask: Default::default(),
|
||||
color: Default::default(),
|
||||
contour_count: 0,
|
||||
order: 0,
|
||||
bounds: tiles.painted_bounds(),
|
||||
tiles: Rc::new(tiles),
|
||||
paint,
|
||||
}
|
||||
}
|
||||
|
||||
/// Scale this path by the given factor.
|
||||
pub fn scale(&self, factor: f32) -> Path<ScaledPixels> {
|
||||
Path {
|
||||
id: self.id,
|
||||
order: self.order,
|
||||
bounds: self.bounds.scale(factor),
|
||||
content_mask: self.content_mask.scale(factor),
|
||||
vertices: self
|
||||
.vertices
|
||||
.iter()
|
||||
.map(|vertex| vertex.scale(factor))
|
||||
.collect(),
|
||||
start: self.start.map(|start| start.scale(factor)),
|
||||
current: self.current.scale(factor),
|
||||
contour_count: self.contour_count,
|
||||
color: self.color,
|
||||
}
|
||||
pub fn tile_count(&self) -> usize {
|
||||
self.tiles.tiles().len()
|
||||
}
|
||||
|
||||
/// Move the start, current point to the given point.
|
||||
pub fn move_to(&mut self, to: Point<Pixels>) {
|
||||
self.contour_count += 1;
|
||||
self.start = to;
|
||||
self.current = to;
|
||||
}
|
||||
|
||||
/// Draw a straight line from the current point to the given point.
|
||||
pub fn line_to(&mut self, to: Point<Pixels>) {
|
||||
self.contour_count += 1;
|
||||
if self.contour_count > 1 {
|
||||
self.push_triangle(
|
||||
(self.start, self.current, to),
|
||||
(point(0., 1.), point(0., 1.), point(0., 1.)),
|
||||
);
|
||||
}
|
||||
self.current = to;
|
||||
}
|
||||
|
||||
/// Draw a curve from the current point to the given point, using the given control point.
|
||||
pub fn curve_to(&mut self, to: Point<Pixels>, ctrl: Point<Pixels>) {
|
||||
self.contour_count += 1;
|
||||
if self.contour_count > 1 {
|
||||
self.push_triangle(
|
||||
(self.start, self.current, to),
|
||||
(point(0., 1.), point(0., 1.), point(0., 1.)),
|
||||
);
|
||||
}
|
||||
|
||||
self.push_triangle(
|
||||
(self.current, ctrl, to),
|
||||
(point(0., 0.), point(0.5, 0.), point(1., 1.)),
|
||||
);
|
||||
self.current = to;
|
||||
}
|
||||
|
||||
/// Push a triangle to the Path.
|
||||
pub fn push_triangle(
|
||||
&mut self,
|
||||
xy: (Point<Pixels>, Point<Pixels>, Point<Pixels>),
|
||||
st: (Point<f32>, Point<f32>, Point<f32>),
|
||||
pub fn append_to(
|
||||
&self,
|
||||
paints: &mut Vec<PathPaint>,
|
||||
curves: &mut Vec<PathCurve>,
|
||||
tiles: &mut Vec<PathTile>,
|
||||
) {
|
||||
self.bounds = self
|
||||
.bounds
|
||||
.union(&Bounds {
|
||||
origin: xy.0,
|
||||
size: Default::default(),
|
||||
})
|
||||
.union(&Bounds {
|
||||
origin: xy.1,
|
||||
size: Default::default(),
|
||||
})
|
||||
.union(&Bounds {
|
||||
origin: xy.2,
|
||||
size: Default::default(),
|
||||
});
|
||||
|
||||
self.vertices.push(PathVertex {
|
||||
xy_position: xy.0,
|
||||
st_position: st.0,
|
||||
content_mask: Default::default(),
|
||||
});
|
||||
self.vertices.push(PathVertex {
|
||||
xy_position: xy.1,
|
||||
st_position: st.1,
|
||||
content_mask: Default::default(),
|
||||
});
|
||||
self.vertices.push(PathVertex {
|
||||
xy_position: xy.2,
|
||||
st_position: st.2,
|
||||
content_mask: Default::default(),
|
||||
});
|
||||
let paint_index = paints.len() as u32;
|
||||
let curve_start = curves.len() as u32;
|
||||
paints.push(self.paint);
|
||||
curves.extend_from_slice(self.tiles.curves());
|
||||
tiles.extend(self.tiles.tiles().iter().map(|tile| PathTile {
|
||||
paint: paint_index,
|
||||
curve_start: curve_start + tile.curve_start,
|
||||
..*tile
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Path<T>
|
||||
where
|
||||
T: Clone + Debug + Default + PartialEq + PartialOrd + Add<T, Output = T> + Sub<Output = T>,
|
||||
{
|
||||
#[allow(unused)]
|
||||
#[expect(missing_docs)]
|
||||
pub fn clipped_bounds(&self) -> Bounds<T> {
|
||||
self.bounds.intersect(&self.content_mask.bounds)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Path<ScaledPixels>> for Primitive {
|
||||
fn from(path: Path<ScaledPixels>) -> Self {
|
||||
impl From<PaintedPath> for Primitive {
|
||||
fn from(path: PaintedPath) -> Self {
|
||||
Primitive::Path(path)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[repr(C)]
|
||||
#[expect(missing_docs)]
|
||||
pub struct PathVertex<P: Clone + Debug + Default + PartialEq> {
|
||||
pub xy_position: Point<P>,
|
||||
pub st_position: Point<f32>,
|
||||
pub content_mask: ContentMask<P>,
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{point, size};
|
||||
|
||||
#[expect(missing_docs)]
|
||||
impl PathVertex<Pixels> {
|
||||
pub fn scale(&self, factor: f32) -> PathVertex<ScaledPixels> {
|
||||
PathVertex {
|
||||
xy_position: self.xy_position.scale(factor),
|
||||
st_position: self.st_position,
|
||||
content_mask: self.content_mask.scale(factor),
|
||||
fn square(x: f32) -> Bounds<ScaledPixels> {
|
||||
Bounds {
|
||||
origin: point(ScaledPixels(x), ScaledPixels(0.)),
|
||||
size: size(ScaledPixels(10.), ScaledPixels(10.)),
|
||||
}
|
||||
}
|
||||
|
||||
fn quad(x: f32) -> Quad {
|
||||
Quad {
|
||||
bounds: square(x),
|
||||
content_mask: ContentMask { bounds: square(x) },
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn underline(x: f32) -> Underline {
|
||||
Underline {
|
||||
order: 0,
|
||||
pad: 0,
|
||||
bounds: square(x),
|
||||
content_mask: ContentMask { bounds: square(x) },
|
||||
color: Hsla::default(),
|
||||
thickness: ScaledPixels(1.),
|
||||
wavy: false.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn batch_labels(scene: &mut Scene) -> Vec<String> {
|
||||
scene.finish();
|
||||
scene.batches().map(|batch| batch.label()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_are_drawn_in_paint_order() {
|
||||
// A quad painted after a layer goes above it.
|
||||
let mut scene = Scene::default();
|
||||
scene.insert_primitive(quad(0.));
|
||||
scene.push_layer();
|
||||
scene.insert_primitive(underline(0.));
|
||||
scene.insert_primitive(underline(5.));
|
||||
scene.pop_layer();
|
||||
scene.insert_primitive(quad(5.));
|
||||
assert_eq!(
|
||||
batch_labels(&mut scene),
|
||||
["quads (1)", "underlines (2)", "quads (1)"]
|
||||
);
|
||||
|
||||
// A layer goes above the layer painted before it.
|
||||
let mut scene = Scene::default();
|
||||
scene.push_layer();
|
||||
scene.insert_primitive(underline(0.));
|
||||
scene.pop_layer();
|
||||
scene.push_layer();
|
||||
scene.insert_primitive(quad(5.));
|
||||
scene.pop_layer();
|
||||
assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_layers_are_drawn_above_their_parents() {
|
||||
// A layer has one draw order, so what it paints after a nested layer
|
||||
// still goes below that layer.
|
||||
let mut scene = Scene::default();
|
||||
scene.push_layer();
|
||||
scene.insert_primitive(underline(0.));
|
||||
scene.push_layer();
|
||||
scene.insert_primitive(quad(5.));
|
||||
scene.pop_layer();
|
||||
scene.insert_primitive(underline(5.));
|
||||
scene.pop_layer();
|
||||
assert_eq!(batch_labels(&mut scene), ["underlines (2)", "quads (1)"]);
|
||||
|
||||
// The same holds when the nested layer shares its parent's order.
|
||||
let mut scene = Scene::default();
|
||||
scene.push_layer();
|
||||
scene.insert_primitive(quad(0.));
|
||||
scene.push_layer();
|
||||
scene.insert_primitive(quad(5.));
|
||||
scene.pop_layer();
|
||||
scene.insert_primitive(quad(8.));
|
||||
scene.pop_layer();
|
||||
assert_eq!(batch_labels(&mut scene), ["quads (3)"]);
|
||||
assert_eq!(
|
||||
scene
|
||||
.quads
|
||||
.iter()
|
||||
.map(|quad| quad.bounds)
|
||||
.collect::<Vec<_>>(),
|
||||
[square(0.), square(8.), square(5.)]
|
||||
);
|
||||
|
||||
// A layer goes above the layers nested in the layer before it.
|
||||
let mut scene = Scene::default();
|
||||
scene.push_layer();
|
||||
scene.push_layer();
|
||||
scene.insert_primitive(underline(0.));
|
||||
scene.pop_layer();
|
||||
scene.pop_layer();
|
||||
scene.push_layer();
|
||||
scene.insert_primitive(quad(5.));
|
||||
scene.pop_layer();
|
||||
assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]);
|
||||
}
|
||||
}
|
||||
|
||||
+354
-25
@@ -2,11 +2,14 @@ use crate::{
|
||||
AssetSource, DevicePixels, IsZero, RenderImage, Result, SharedString, Size,
|
||||
swap_rgba_pa_to_bgra,
|
||||
};
|
||||
use collections::HashMap;
|
||||
use image::Frame;
|
||||
use parking_lot::Mutex;
|
||||
use resvg::tiny_skia::Pixmap;
|
||||
use smallvec::SmallVec;
|
||||
use std::{
|
||||
hash::Hash,
|
||||
path::Path,
|
||||
sync::{Arc, LazyLock, OnceLock},
|
||||
};
|
||||
|
||||
@@ -102,6 +105,19 @@ pub struct SvgRenderer {
|
||||
/// scales should retain this value to avoid re-paying the parse cost.
|
||||
pub struct ParsedSvg(usvg::Tree);
|
||||
|
||||
/// The font of an SVG `<text>` element, as the values of its presentation attributes.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct SvgTextFont<'a> {
|
||||
/// The `font-family` list.
|
||||
pub family: &'a str,
|
||||
/// The `font-size`, in pixels.
|
||||
pub size: f32,
|
||||
/// The `font-weight`.
|
||||
pub weight: &'a str,
|
||||
/// The `font-style`.
|
||||
pub style: &'a str,
|
||||
}
|
||||
|
||||
/// The size in which to rasterize the SVG.
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum SvgSize {
|
||||
@@ -132,45 +148,64 @@ impl SvgRenderer {
|
||||
// eagerly at construction time. This avoids the expensive deep-clone
|
||||
// of the system font database for code paths that never render SVGs
|
||||
// (e.g. tests).
|
||||
let enriched_fontdb: Arc<OnceLock<Arc<usvg::fontdb::Database>>> = Arc::new(OnceLock::new());
|
||||
let enriched_fontdb = Arc::new(OnceLock::<Mutex<FontDatabase>>::new());
|
||||
|
||||
let default_font_resolver = usvg::FontResolver::default_font_selector();
|
||||
let font_resolver = Box::new({
|
||||
let asset_source = asset_source.clone();
|
||||
let enriched_fontdb = enriched_fontdb.clone();
|
||||
move |font: &usvg::Font, db: &mut Arc<usvg::fontdb::Database>| {
|
||||
let fontdb = enriched_fontdb.get_or_init(|| {
|
||||
let mut db = (**SYSTEM_FONT_DB).clone();
|
||||
load_bundled_fonts(&*asset_source, &mut db);
|
||||
fix_generic_font_families(&mut db);
|
||||
Mutex::new(FontDatabase {
|
||||
database: Arc::new(db),
|
||||
owned_faces: HashMap::default(),
|
||||
remaining_owned_bytes: MAX_OWNED_FONT_BYTES,
|
||||
fallback_faces: HashMap::default(),
|
||||
})
|
||||
});
|
||||
if db.is_empty() {
|
||||
let fontdb = enriched_fontdb.get_or_init(|| {
|
||||
let mut db = (**SYSTEM_FONT_DB).clone();
|
||||
load_bundled_fonts(&*asset_source, &mut db);
|
||||
fix_generic_font_families(&mut db);
|
||||
Arc::new(db)
|
||||
});
|
||||
*db = fontdb.clone();
|
||||
*db = fontdb.lock().database.clone();
|
||||
}
|
||||
if let Some(id) = default_font_resolver(font, db) {
|
||||
return Some(id);
|
||||
}
|
||||
// fontdb doesn't recognize CSS system font keywords like "system-ui"
|
||||
// or "ui-sans-serif", so fall back to sans-serif before any face.
|
||||
let sans_query = usvg::fontdb::Query {
|
||||
families: &[usvg::fontdb::Family::SansSerif],
|
||||
..Default::default()
|
||||
};
|
||||
db.query(&sans_query)
|
||||
.or_else(|| db.faces().next().map(|f| f.id))
|
||||
let id = default_font_resolver(font, db).or_else(|| {
|
||||
// fontdb doesn't recognize CSS system font keywords like "system-ui"
|
||||
// or "ui-sans-serif", so fall back to sans-serif before any face.
|
||||
let sans_query = usvg::fontdb::Query {
|
||||
families: &[usvg::fontdb::Family::SansSerif],
|
||||
..Default::default()
|
||||
};
|
||||
db.query(&sans_query)
|
||||
.or_else(|| db.faces().next().map(|f| f.id))
|
||||
})?;
|
||||
Some(fontdb.lock().owned_face(db, id))
|
||||
}
|
||||
});
|
||||
let default_fallback_selection = usvg::FontResolver::default_fallback_selector();
|
||||
let fallback_selection = Box::new(
|
||||
move |ch: char, fonts: &[usvg::fontdb::ID], db: &mut Arc<usvg::fontdb::Database>| {
|
||||
if is_emoji_presentation(ch) {
|
||||
if let Some(id) = select_emoji_font(ch, fonts, db.as_ref(), EMOJI_FONT_FAMILIES)
|
||||
{
|
||||
return Some(id);
|
||||
let mut select = |fonts: &[usvg::fontdb::ID]| {
|
||||
if is_emoji_presentation(ch) {
|
||||
if let Some(id) =
|
||||
select_emoji_font(ch, fonts, db.as_ref(), EMOJI_FONT_FAMILIES)
|
||||
{
|
||||
return Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
default_fallback_selection(ch, fonts, db)
|
||||
default_fallback_selection(ch, fonts, db)
|
||||
};
|
||||
let Some(fontdb) = enriched_fontdb.get() else {
|
||||
return select(fonts);
|
||||
};
|
||||
let face = cached_fallback_face(fontdb, ch, fonts, select)?;
|
||||
let owned_face = fontdb.lock().owned_face(db, face);
|
||||
Some(if fonts.contains(&owned_face) {
|
||||
face
|
||||
} else {
|
||||
owned_face
|
||||
})
|
||||
},
|
||||
);
|
||||
let options = usvg::Options {
|
||||
@@ -191,6 +226,29 @@ impl SvgRenderer {
|
||||
usvg::Tree::from_data(bytes, &self.usvg_options).map(ParsedSvg)
|
||||
}
|
||||
|
||||
/// Returns the advance of `text` drawn by this renderer as a single line of SVG `<text>`.
|
||||
pub fn measure_text_width(
|
||||
&self,
|
||||
text: &str,
|
||||
font: &SvgTextFont<'_>,
|
||||
) -> Result<f32, usvg::Error> {
|
||||
let mut svg = String::from(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg"><text xml:space="preserve" text-decoration="underline" font-family=""#,
|
||||
);
|
||||
push_xml_escaped(&mut svg, font.family);
|
||||
svg.push_str(r#"" font-weight=""#);
|
||||
push_xml_escaped(&mut svg, font.weight);
|
||||
svg.push_str(r#"" font-style=""#);
|
||||
push_xml_escaped(&mut svg, font.style);
|
||||
let size = font.size;
|
||||
svg.push_str(&format!(r#"" font-size="{size}">"#));
|
||||
push_xml_escaped(&mut svg, text);
|
||||
svg.push_str("</text></svg>");
|
||||
|
||||
let tree = usvg::Tree::from_str(&svg, &self.usvg_options)?;
|
||||
Ok(underline_width(tree.root()))
|
||||
}
|
||||
|
||||
/// Rasterizes a previously parsed SVG into an image buffer.
|
||||
pub fn render_parsed(
|
||||
&self,
|
||||
@@ -306,6 +364,139 @@ fn rasterize_tree(tree: &usvg::Tree, size: SvgSize) -> Result<Pixmap, usvg::Erro
|
||||
Ok(pixmap)
|
||||
}
|
||||
|
||||
const MAX_OWNED_FONT_BYTES: u64 = 64 * 1024 * 1024;
|
||||
|
||||
struct FontDatabase {
|
||||
database: Arc<usvg::fontdb::Database>,
|
||||
owned_faces: HashMap<usvg::fontdb::ID, usvg::fontdb::ID>,
|
||||
remaining_owned_bytes: u64,
|
||||
fallback_faces: HashMap<(usvg::fontdb::ID, char), Option<usvg::fontdb::ID>>,
|
||||
}
|
||||
|
||||
impl FontDatabase {
|
||||
fn owned_face(
|
||||
&mut self,
|
||||
db: &mut Arc<usvg::fontdb::Database>,
|
||||
id: usvg::fontdb::ID,
|
||||
) -> usvg::fontdb::ID {
|
||||
let Some(usvg::fontdb::Source::File(path)) = db.face(id).map(|face| face.source.clone())
|
||||
else {
|
||||
return id;
|
||||
};
|
||||
if !self.owned_faces.contains_key(&id) {
|
||||
self.own_font_file(&path);
|
||||
}
|
||||
*db = self.database.clone();
|
||||
self.owned_faces.get(&id).copied().unwrap_or(id)
|
||||
}
|
||||
|
||||
fn own_font_file(&mut self, path: &Path) {
|
||||
let file_faces = self
|
||||
.database
|
||||
.faces()
|
||||
.filter(|face| {
|
||||
matches!(&face.source, usvg::fontdb::Source::File(face_path) if face_path == path)
|
||||
})
|
||||
.map(|face| (face.id, face.index))
|
||||
.collect::<Vec<_>>();
|
||||
let remaining_owned_bytes = self.remaining_owned_bytes;
|
||||
let data = std::fs::metadata(path).and_then(|metadata| {
|
||||
(metadata.len() <= remaining_owned_bytes)
|
||||
.then(|| std::fs::read(path))
|
||||
.transpose()
|
||||
});
|
||||
let owned_ids = match data {
|
||||
Ok(Some(data)) if data.len() as u64 <= remaining_owned_bytes => {
|
||||
let size = data.len() as u64;
|
||||
let owned_ids = Arc::make_mut(&mut self.database)
|
||||
.load_font_source(usvg::fontdb::Source::Binary(Arc::new(data)));
|
||||
if !owned_ids.is_empty() {
|
||||
self.remaining_owned_bytes -= size;
|
||||
}
|
||||
owned_ids
|
||||
}
|
||||
Ok(_) => Default::default(),
|
||||
Err(error) => {
|
||||
log::warn!("Failed to read font {path:?}: {error}");
|
||||
Default::default()
|
||||
}
|
||||
};
|
||||
for (id, index) in file_faces {
|
||||
let owned_id = owned_ids
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|owned_id| {
|
||||
self.database
|
||||
.face(*owned_id)
|
||||
.is_some_and(|face| face.index == index)
|
||||
})
|
||||
.unwrap_or(id);
|
||||
self.owned_faces.insert(id, owned_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_CACHED_FALLBACK_FACES: usize = 16 * 1024;
|
||||
|
||||
fn cached_fallback_face(
|
||||
fontdb: &Mutex<FontDatabase>,
|
||||
ch: char,
|
||||
fonts: &[usvg::fontdb::ID],
|
||||
mut select: impl FnMut(&[usvg::fontdb::ID]) -> Option<usvg::fontdb::ID>,
|
||||
) -> Option<usvg::fontdb::ID> {
|
||||
let Some(base) = fonts.first() else {
|
||||
return select(fonts);
|
||||
};
|
||||
let key = (*base, ch);
|
||||
let cached_face = fontdb.lock().fallback_faces.get(&key).copied();
|
||||
let face = match cached_face {
|
||||
Some(face) => face,
|
||||
None => {
|
||||
let face = select(&fonts[..1]);
|
||||
let fallback_faces = &mut fontdb.lock().fallback_faces;
|
||||
if fallback_faces.len() < MAX_CACHED_FALLBACK_FACES {
|
||||
fallback_faces.insert(key, face);
|
||||
}
|
||||
face
|
||||
}
|
||||
};
|
||||
match face {
|
||||
Some(face) if fonts.contains(&face) => select(fonts),
|
||||
face => face,
|
||||
}
|
||||
}
|
||||
|
||||
fn underline_width(group: &usvg::Group) -> f32 {
|
||||
group.children().iter().fold(0., |width, node| {
|
||||
width
|
||||
+ match node {
|
||||
usvg::Node::Text(text) => text
|
||||
.layouted()
|
||||
.iter()
|
||||
.filter_map(|span| span.underline.as_ref())
|
||||
.fold(0., |width, underline| {
|
||||
width + underline.data().bounds().width()
|
||||
}),
|
||||
usvg::Node::Group(group) => underline_width(group),
|
||||
usvg::Node::Path(_) | usvg::Node::Image(_) => 0.,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn push_xml_escaped(xml: &mut String, text: &str) {
|
||||
for character in text.chars() {
|
||||
match character {
|
||||
'&' => xml.push_str("&"),
|
||||
'<' => xml.push_str("<"),
|
||||
'>' => xml.push_str(">"),
|
||||
'"' => xml.push_str("""),
|
||||
'\t' | '\n' | '\r' => xml.push(character),
|
||||
'\u{0}'..='\u{1f}' | '\u{fffe}' | '\u{ffff}' => {}
|
||||
_ => xml.push(character),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_bundled_fonts(asset_source: &dyn AssetSource, db: &mut usvg::fontdb::Database) {
|
||||
let font_paths = [
|
||||
"fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf",
|
||||
@@ -356,6 +547,7 @@ fn fix_generic_font_families(db: &mut usvg::fontdb::Database) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::{borrow::Cow, cell::Cell};
|
||||
use usvg::fontdb::{Database, Family, Query};
|
||||
|
||||
const IBM_PLEX_REGULAR: &[u8] =
|
||||
@@ -390,6 +582,103 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measured_text_width_matches_rasterized_advance() -> Result<()> {
|
||||
let renderer = SvgRenderer::new(Arc::new(BundledFonts));
|
||||
let font = SvgTextFont {
|
||||
family: "IBM Plex Sans",
|
||||
size: 40.,
|
||||
weight: "normal",
|
||||
style: "normal",
|
||||
};
|
||||
let frame_width = rasterized_text_width(&renderer, "MM")?;
|
||||
assert!(frame_width > 0.);
|
||||
|
||||
for text in ["MMMM", " ", " ", "\u{a0}", "\u{200b}", "M\u{200b}"] {
|
||||
let measured = renderer.measure_text_width(text, &font)?;
|
||||
let rasterized = rasterized_text_width(&renderer, &format!("M{text}M"))? - frame_width;
|
||||
assert!(
|
||||
(measured - rasterized).abs() <= 1.,
|
||||
"{text:?} measured {measured}px, rasterized {rasterized}px"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
renderer.measure_text_width("M\u{200b}", &font)?,
|
||||
renderer.measure_text_width("M", &font)?
|
||||
);
|
||||
assert!(renderer.measure_text_width("<&\"\u{1}>", &font)? > 0.);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owns_font_bytes_within_budget() -> Result<()> {
|
||||
let font_path = |name| {
|
||||
std::env::temp_dir().join(format!(
|
||||
"gpui-svg-renderer-{}-{name}.ttf",
|
||||
std::process::id()
|
||||
))
|
||||
};
|
||||
let (plex_path, lilex_path) = (font_path("plex"), font_path("lilex"));
|
||||
std::fs::write(&plex_path, IBM_PLEX_REGULAR)?;
|
||||
std::fs::write(&lilex_path, LILEX_REGULAR)?;
|
||||
let mut database = Database::new();
|
||||
database.load_font_file(&plex_path)?;
|
||||
database.load_font_file(&lilex_path)?;
|
||||
let mut fonts = FontDatabase {
|
||||
database: Arc::new(database),
|
||||
owned_faces: HashMap::default(),
|
||||
remaining_owned_bytes: IBM_PLEX_REGULAR.len() as u64,
|
||||
fallback_faces: HashMap::default(),
|
||||
};
|
||||
let mut db = fonts.database.clone();
|
||||
let face_ids = db.faces().map(|face| face.id).collect::<Vec<_>>();
|
||||
let (plex_id, lilex_id) = (face_ids[0], face_ids[1]);
|
||||
|
||||
let owned_plex_id = fonts.owned_face(&mut db, plex_id);
|
||||
let owned_lilex_id = fonts.owned_face(&mut db, lilex_id);
|
||||
std::fs::write(&plex_path, b"changed")?;
|
||||
let data_len = |id| db.with_face_data(id, |data, _| data.len());
|
||||
let data_lens = (data_len(plex_id), data_len(owned_plex_id));
|
||||
std::fs::remove_file(&plex_path)?;
|
||||
std::fs::remove_file(&lilex_path)?;
|
||||
|
||||
assert_eq!(data_lens, (Some(7), Some(IBM_PLEX_REGULAR.len())));
|
||||
assert_eq!(owned_lilex_id, lilex_id);
|
||||
assert_eq!(fonts.remaining_owned_bytes, 0);
|
||||
assert_eq!(fonts.owned_face(&mut db, plex_id), owned_plex_id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_faces_are_remembered_until_excluded() {
|
||||
let database = db_with_bundled_fonts();
|
||||
let face_ids = database.faces().map(|face| face.id).collect::<Vec<_>>();
|
||||
let (base, fallback) = (face_ids[0], face_ids[1]);
|
||||
let fontdb = Mutex::new(FontDatabase {
|
||||
database: Arc::new(database),
|
||||
owned_faces: HashMap::default(),
|
||||
remaining_owned_bytes: 0,
|
||||
fallback_faces: HashMap::default(),
|
||||
});
|
||||
let selections = Cell::new(0);
|
||||
let fallback_face = |ch, fonts: &[usvg::fontdb::ID]| {
|
||||
cached_fallback_face(&fontdb, ch, fonts, |excluded| {
|
||||
selections.set(selections.get() + 1);
|
||||
(!excluded.contains(&fallback)).then_some(fallback)
|
||||
})
|
||||
};
|
||||
|
||||
assert_eq!(fallback_face('x', &[base]), Some(fallback));
|
||||
assert_eq!(fallback_face('x', &[base]), Some(fallback));
|
||||
assert_eq!(selections.get(), 1);
|
||||
assert_eq!(fallback_face('x', &[base, fallback]), None);
|
||||
assert_eq!(selections.get(), 2);
|
||||
assert_eq!(fallback_face('y', &[base, fallback]), None);
|
||||
assert_eq!(selections.get(), 4);
|
||||
assert_eq!(fallback_face('y', &[base]), Some(fallback));
|
||||
assert_eq!(selections.get(), 4);
|
||||
}
|
||||
|
||||
fn db_with_bundled_fonts() -> Database {
|
||||
let mut db = Database::new();
|
||||
db.load_font_data(IBM_PLEX_REGULAR.to_vec());
|
||||
@@ -522,4 +811,44 @@ mod tests {
|
||||
face.families
|
||||
);
|
||||
}
|
||||
|
||||
struct BundledFonts;
|
||||
|
||||
impl AssetSource for BundledFonts {
|
||||
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
|
||||
Ok(match path {
|
||||
"fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf" => {
|
||||
Some(Cow::Borrowed(IBM_PLEX_REGULAR))
|
||||
}
|
||||
"fonts/lilex/Lilex-Regular.ttf" => Some(Cow::Borrowed(LILEX_REGULAR)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn list(&self, _path: &str) -> Result<Vec<SharedString>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
fn rasterized_text_width(renderer: &SvgRenderer, text: &str) -> Result<f32> {
|
||||
let svg = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="60"><text xml:space="preserve" x="10" y="45" font-family="IBM Plex Sans" font-size="40">{text}</text></svg>"#
|
||||
);
|
||||
let pixmap = renderer.render_pixmap(svg.as_bytes(), SvgSize::ScaleFactor(1.))?;
|
||||
let width = pixmap.width() as usize;
|
||||
let inked_columns = (0..width)
|
||||
.filter(|column| {
|
||||
pixmap
|
||||
.pixels()
|
||||
.iter()
|
||||
.skip(*column)
|
||||
.step_by(width)
|
||||
.any(|pixel| pixel.alpha() > 0)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(match (inked_columns.first(), inked_columns.last()) {
|
||||
(Some(first), Some(last)) => (last - first + 1) as f32,
|
||||
_ => 0.,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -545,15 +545,7 @@ fn paint_line(
|
||||
&mut Window,
|
||||
),
|
||||
) -> Result<()> {
|
||||
let line_bounds = line_paint_bounds(
|
||||
origin,
|
||||
layout,
|
||||
line_height,
|
||||
align,
|
||||
align_width,
|
||||
wrap_boundaries,
|
||||
);
|
||||
window.paint_layer(line_bounds, |window| {
|
||||
window.paint_layer(|window| {
|
||||
let padding_top = (line_height - layout.ascent - layout.descent) / 2.;
|
||||
let baseline_offset = point(px(0.), padding_top + layout.ascent);
|
||||
let underline_y_offset = underline_y_offset(line_height, layout.ascent, layout.descent);
|
||||
@@ -816,15 +808,7 @@ fn paint_line_background(
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Result<()> {
|
||||
let line_bounds = line_paint_bounds(
|
||||
origin,
|
||||
layout,
|
||||
line_height,
|
||||
align,
|
||||
align_width,
|
||||
wrap_boundaries,
|
||||
);
|
||||
window.paint_layer(line_bounds, |window| {
|
||||
window.paint_layer(|window| {
|
||||
let mut decoration_runs = decoration_runs.iter();
|
||||
let mut wraps = wrap_boundaries.iter().peekable();
|
||||
let mut run_end = 0;
|
||||
@@ -955,51 +939,6 @@ fn paint_line_background(
|
||||
})
|
||||
}
|
||||
|
||||
fn line_paint_bounds(
|
||||
origin: Point<Pixels>,
|
||||
layout: &LineLayout,
|
||||
line_height: Pixels,
|
||||
align: TextAlign,
|
||||
align_width: Option<Pixels>,
|
||||
wrap_boundaries: &[WrapBoundary],
|
||||
) -> Bounds<Pixels> {
|
||||
let mut bounds = Bounds::new(
|
||||
origin,
|
||||
size(
|
||||
layout.width,
|
||||
line_height * (wrap_boundaries.len() as f32 + 1.),
|
||||
),
|
||||
);
|
||||
if align == TextAlign::Left || layout.len == 0 {
|
||||
return bounds;
|
||||
}
|
||||
|
||||
let align_width = align_width.unwrap_or(layout.width);
|
||||
let mut row_start = Pixels::ZERO;
|
||||
let row_ends = wrap_boundaries
|
||||
.iter()
|
||||
.map(|boundary| {
|
||||
layout.runs[boundary.run_ix].glyphs[boundary.glyph_ix]
|
||||
.position
|
||||
.x
|
||||
})
|
||||
.chain([layout.width]);
|
||||
for (row, row_end) in row_ends.enumerate() {
|
||||
let width = row_end - row_start;
|
||||
let offset = match align {
|
||||
TextAlign::Left => Pixels::ZERO,
|
||||
TextAlign::Center => (align_width - width) / 2.,
|
||||
TextAlign::Right => align_width - width,
|
||||
};
|
||||
bounds = bounds.union(&Bounds::new(
|
||||
point(origin.x + offset, origin.y + line_height * row as f32),
|
||||
size(width, line_height),
|
||||
));
|
||||
row_start = row_end;
|
||||
}
|
||||
bounds
|
||||
}
|
||||
|
||||
fn aligned_origin_x(
|
||||
origin: Point<Pixels>,
|
||||
align_width: Pixels,
|
||||
@@ -1067,68 +1006,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_aligned_line_paint_bounds() {
|
||||
let line = make_shaped_line("abcd", &[(0, 0.), (1, 10.), (2, 20.), (3, 30.)], 40., &[]);
|
||||
let origin = point(px(10.), px(20.));
|
||||
let line_height = px(16.);
|
||||
for (wrapped, align_width, expected_edges) in [
|
||||
(false, None, [(10., 50.), (10., 50.), (10., 50.)]),
|
||||
(true, None, [(10., 50.), (10., 50.), (10., 50.)]),
|
||||
(false, Some(40.), [(10., 50.), (10., 50.), (10., 50.)]),
|
||||
(true, Some(40.), [(10., 50.), (10., 50.), (10., 50.)]),
|
||||
(false, Some(100.), [(10., 50.), (10., 80.), (10., 110.)]),
|
||||
(true, Some(100.), [(10., 50.), (10., 70.), (10., 110.)]),
|
||||
(false, Some(10.), [(10., 50.), (-5., 50.), (-20., 50.)]),
|
||||
(true, Some(10.), [(10., 50.), (5., 50.), (0., 50.)]),
|
||||
(false, Some(0.), [(10., 50.), (-10., 50.), (-30., 50.)]),
|
||||
(true, Some(0.), [(10., 50.), (0., 50.), (-10., 50.)]),
|
||||
] {
|
||||
let boundaries = if wrapped {
|
||||
vec![WrapBoundary {
|
||||
run_ix: 0,
|
||||
glyph_ix: 2,
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
for (align, (left, right)) in [TextAlign::Left, TextAlign::Center, TextAlign::Right]
|
||||
.into_iter()
|
||||
.zip(expected_edges)
|
||||
{
|
||||
assert_eq!(
|
||||
line_paint_bounds(
|
||||
origin,
|
||||
&line.layout,
|
||||
line_height,
|
||||
align,
|
||||
align_width.map(px),
|
||||
&boundaries,
|
||||
),
|
||||
Bounds::new(
|
||||
point(px(left), origin.y),
|
||||
size(px(right - left), px(if wrapped { 32. } else { 16. })),
|
||||
),
|
||||
"wrapped={wrapped}, align={align:?}, align_width={align_width:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
let empty = make_shaped_line("", &[], 0., &[]);
|
||||
for align in [TextAlign::Left, TextAlign::Center, TextAlign::Right] {
|
||||
assert_eq!(
|
||||
line_paint_bounds(
|
||||
origin,
|
||||
&empty.layout,
|
||||
line_height,
|
||||
align,
|
||||
Some(px(100.)),
|
||||
&[]
|
||||
),
|
||||
Bounds::new(origin, size(Pixels::ZERO, line_height)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_underline_handler_matches_default_paint(cx: &mut TestAppContext) {
|
||||
test_underline_handler_at_scales(cx, |window, cx| {
|
||||
|
||||
+348
-100
@@ -14,9 +14,9 @@ use crate::{
|
||||
EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
|
||||
Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent,
|
||||
Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent,
|
||||
MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels,
|
||||
PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,
|
||||
PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams,
|
||||
MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, PaintedPath, Path,
|
||||
Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow,
|
||||
Point, PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams,
|
||||
RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
|
||||
SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,
|
||||
StrikethroughStyle, Style, SubpixelSprite, Subscription, SystemWindowTab,
|
||||
@@ -633,6 +633,15 @@ impl FocusHandle {
|
||||
self.id.contains(other.id, window)
|
||||
}
|
||||
|
||||
/// Obtains whether the element associated with this handle is part of the most recently rendered frame.
|
||||
pub fn is_rendered(&self, window: &Window) -> bool {
|
||||
window
|
||||
.rendered_frame
|
||||
.dispatch_tree
|
||||
.focusable_node_id(self.id)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
/// Dispatch an action on the element that rendered this focus handle
|
||||
pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
|
||||
if let Some(node_id) = window
|
||||
@@ -1226,6 +1235,7 @@ pub struct Window {
|
||||
pub(crate) display_observers: SingleSubscriberSet<AnyObserver>,
|
||||
is_resizable: bool,
|
||||
is_minimizable: bool,
|
||||
last_window_bounds: WindowBounds,
|
||||
sprite_atlas: Arc<dyn PlatformAtlas>,
|
||||
text_system: Rc<WindowTextSystem>,
|
||||
text_rendering_mode: Rc<Cell<TextRenderingMode>>,
|
||||
@@ -1569,26 +1579,16 @@ pub(crate) struct ElementStateBox {
|
||||
pub(crate) type_name: &'static str,
|
||||
}
|
||||
|
||||
fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
|
||||
// TODO, BUG: if you open a window with the currently active window
|
||||
// on the stack, this will erroneously fallback to `None`
|
||||
//
|
||||
// TODO these should be the initial window bounds not considering maximized/fullscreen
|
||||
let active_window_bounds = cx
|
||||
.active_window()
|
||||
.and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
|
||||
|
||||
fn default_bounds(
|
||||
active_window_bounds: Option<WindowBounds>,
|
||||
display: Option<&dyn PlatformDisplay>,
|
||||
) -> WindowBounds {
|
||||
const CASCADE_OFFSET: f32 = 25.0;
|
||||
|
||||
let display = display_id
|
||||
.map(|id| cx.find_display(id))
|
||||
.unwrap_or_else(|| cx.primary_display());
|
||||
|
||||
let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
|
||||
|
||||
// Use visible_bounds to exclude taskbar/dock areas
|
||||
let display_bounds = display
|
||||
.as_ref()
|
||||
.map(|d| d.visible_bounds())
|
||||
.unwrap_or_else(default_placement);
|
||||
|
||||
@@ -1606,7 +1606,6 @@ fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
|
||||
},
|
||||
None => (
|
||||
display
|
||||
.as_ref()
|
||||
.map(|d| d.default_bounds())
|
||||
.unwrap_or_else(default_placement),
|
||||
WindowBounds::Windowed,
|
||||
@@ -1673,7 +1672,25 @@ impl Window {
|
||||
.as_ref()
|
||||
.and_then(|titlebar| titlebar.title.clone());
|
||||
|
||||
let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
|
||||
let active_window_placement = cx.active_window_placement();
|
||||
// Explicit bounds only make sense on the display they were computed for.
|
||||
let target_display_id = display_id.or_else(|| {
|
||||
active_window_placement
|
||||
.filter(|_| window_bounds.is_none())
|
||||
.and_then(|(display_id, _)| display_id)
|
||||
});
|
||||
let display = target_display_id
|
||||
.and_then(|display_id| cx.find_display(display_id))
|
||||
.or_else(|| cx.primary_display());
|
||||
let display_id = display
|
||||
.as_ref()
|
||||
.map(|display| display.id())
|
||||
.or(target_display_id);
|
||||
let active_window_bounds = active_window_placement
|
||||
.filter(|(active_display_id, _)| *active_display_id == display_id)
|
||||
.map(|(_, bounds)| bounds);
|
||||
let window_bounds = window_bounds
|
||||
.unwrap_or_else(|| default_bounds(active_window_bounds, display.as_deref()));
|
||||
let mut platform_window = cx.platform.open_window(
|
||||
handle,
|
||||
WindowParams {
|
||||
@@ -2357,6 +2374,7 @@ impl Window {
|
||||
display_observers: SingleSubscriberSet::new(),
|
||||
is_resizable,
|
||||
is_minimizable,
|
||||
last_window_bounds: window_bounds,
|
||||
sprite_atlas,
|
||||
text_system,
|
||||
text_rendering_mode: cx.text_rendering_mode.clone(),
|
||||
@@ -2506,6 +2524,65 @@ impl Window {
|
||||
}
|
||||
}
|
||||
|
||||
/// This window's part of [`App::debug_state`].
|
||||
///
|
||||
/// Values GPUI caches are reported next to what the platform reports now,
|
||||
/// so a stale cache shows up as a mismatch.
|
||||
pub(crate) fn debug_state(&self) -> serde_json::Value {
|
||||
let platform_window = &self.platform_window;
|
||||
serde_json::json!({
|
||||
"id": self.handle.window_id().as_u64(),
|
||||
"title": platform_window.get_title(),
|
||||
"bounds": platform_window.bounds(),
|
||||
"window_bounds": format!("{:?}", platform_window.window_bounds()),
|
||||
"content_size": platform_window.content_size(),
|
||||
"viewport_size": self.viewport_size,
|
||||
"scale_factor": {
|
||||
"cached": self.scale_factor,
|
||||
"platform": platform_window.scale_factor(),
|
||||
},
|
||||
"display_id": {
|
||||
"cached": self.display_id.map(u64::from),
|
||||
"platform": platform_window.display().map(|display| u64::from(display.id())),
|
||||
},
|
||||
"active": {
|
||||
"cached": self.active.get(),
|
||||
"platform": platform_window.is_active(),
|
||||
},
|
||||
"hovered": {
|
||||
"cached": self.hovered.get(),
|
||||
"platform": platform_window.is_hovered(),
|
||||
},
|
||||
"visibility": {
|
||||
"cached": format!("{:?}", self.visibility),
|
||||
"platform": format!("{:?}", platform_window.visibility()),
|
||||
},
|
||||
"appearance": {
|
||||
"cached": format!("{:?}", self.appearance),
|
||||
"platform": format!("{:?}", platform_window.appearance()),
|
||||
},
|
||||
"is_fullscreen": platform_window.is_fullscreen(),
|
||||
"is_maximized": platform_window.is_maximized(),
|
||||
"mouse_position": {
|
||||
"cached": self.mouse_position,
|
||||
"platform": platform_window.mouse_position(),
|
||||
},
|
||||
"modifiers": {
|
||||
"cached": self.modifiers,
|
||||
"platform": platform_window.modifiers(),
|
||||
},
|
||||
"cursor_style": self.rendered_frame.cursor_style(self),
|
||||
"frame": {
|
||||
"dirty": self.invalidator.is_dirty(),
|
||||
"needs_present": self.needs_present.get(),
|
||||
"refreshing": self.refreshing,
|
||||
"next_frame_callbacks": self.next_frame_callbacks.borrow().len(),
|
||||
},
|
||||
"gpu": platform_window.gpu_specs(),
|
||||
"platform": platform_window.debug_state(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the platform is presenting this window's frames (see
|
||||
/// [`WindowVisibility`]).
|
||||
pub fn visibility(&self) -> WindowVisibility {
|
||||
@@ -2740,6 +2817,14 @@ impl Window {
|
||||
self.platform_window.window_bounds()
|
||||
}
|
||||
|
||||
pub(crate) fn last_window_bounds(&self) -> WindowBounds {
|
||||
self.last_window_bounds
|
||||
}
|
||||
|
||||
pub(crate) fn display_id(&self) -> Option<DisplayId> {
|
||||
self.display_id
|
||||
}
|
||||
|
||||
/// Return the `WindowBounds` excluding insets (Wayland and X11)
|
||||
pub fn inner_window_bounds(&self) -> WindowBounds {
|
||||
self.platform_window.inner_window_bounds()
|
||||
@@ -3003,6 +3088,8 @@ impl Window {
|
||||
pub fn bounds_changed(&mut self, cx: &mut App) {
|
||||
self.scale_factor = self.platform_window.scale_factor();
|
||||
self.viewport_size = self.platform_window.content_size();
|
||||
self.last_window_bounds = self.platform_window.window_bounds();
|
||||
cx.sync_window_update_entry(self);
|
||||
self.mouse_position = self.platform_window.mouse_position();
|
||||
|
||||
self.refresh();
|
||||
@@ -3286,6 +3373,12 @@ impl Window {
|
||||
self.platform_window.set_traffic_light_position(position);
|
||||
}
|
||||
|
||||
/// Shows or hides the native macOS titlebar, including the traffic light buttons.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn set_native_titlebar_visibility(&self, visible: bool) {
|
||||
self.platform_window.set_native_titlebar_visibility(visible);
|
||||
}
|
||||
|
||||
/// Sets the application identifier.
|
||||
pub fn set_app_id(&mut self, app_id: &str) {
|
||||
self.platform_window.set_app_id(app_id);
|
||||
@@ -4775,28 +4868,20 @@ impl Window {
|
||||
});
|
||||
}
|
||||
|
||||
/// Creates a new painting layer for the specified bounds. A "layer" is a batch
|
||||
/// of geometry that are non-overlapping and have the same draw order. This is typically used
|
||||
/// Creates a new painting layer. A "layer" is a batch of geometry that are
|
||||
/// non-overlapping and have the same draw order. This is typically used
|
||||
/// for performance reasons.
|
||||
///
|
||||
/// Layers painted inside `f` are drawn above this layer, including above
|
||||
/// what `f` paints after them.
|
||||
///
|
||||
/// This method should only be called as part of the paint phase of element drawing.
|
||||
pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
|
||||
pub fn paint_layer<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
|
||||
self.invalidator.debug_assert_paint();
|
||||
|
||||
let content_mask = self.content_mask();
|
||||
let clipped_bounds = bounds.intersect(&content_mask.bounds);
|
||||
if !clipped_bounds.is_empty() {
|
||||
self.next_frame
|
||||
.scene
|
||||
.push_layer(self.cover_bounds(clipped_bounds));
|
||||
}
|
||||
|
||||
self.next_frame.scene.push_layer();
|
||||
let result = f(self);
|
||||
|
||||
if !clipped_bounds.is_empty() {
|
||||
self.next_frame.scene.pop_layer();
|
||||
}
|
||||
|
||||
self.next_frame.scene.pop_layer();
|
||||
result
|
||||
}
|
||||
|
||||
@@ -4816,23 +4901,27 @@ impl Window {
|
||||
let scale_factor = self.scale_factor();
|
||||
let content_mask = self.snapped_content_mask();
|
||||
let opacity = self.element_opacity();
|
||||
let element_bounds = self.cover_bounds(bounds);
|
||||
let element_corner_radii = corner_radii.scale(scale_factor);
|
||||
for shadow in shadows {
|
||||
if shadow.inset {
|
||||
continue;
|
||||
}
|
||||
let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
|
||||
let shape_bounds =
|
||||
self.cover_bounds((bounds + shadow.offset).dilate(shadow.spread_radius));
|
||||
if shape_bounds.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let blur_radius = shadow.blur_radius.scale(scale_factor);
|
||||
self.next_frame.scene.insert_primitive(Shadow {
|
||||
order: 0,
|
||||
blur_radius: shadow.blur_radius.scale(scale_factor),
|
||||
bounds: self.cover_bounds(shadow_bounds),
|
||||
blur_radius,
|
||||
// Leave room for the tail of the blur.
|
||||
bounds: shape_bounds.dilate(blur_radius * 3.),
|
||||
content_mask,
|
||||
corner_radii: corner_radii.scale(scale_factor),
|
||||
corner_radii: Corners::default(),
|
||||
color: shadow.color.opacity(opacity),
|
||||
element_bounds,
|
||||
element_corner_radii,
|
||||
inset: 0,
|
||||
shape_bounds,
|
||||
shape_corner_radii: corner_radii.scale(scale_factor),
|
||||
inset: false.into(),
|
||||
pad: 0,
|
||||
});
|
||||
}
|
||||
@@ -4871,55 +4960,58 @@ impl Window {
|
||||
self.next_frame.scene.insert_primitive(Shadow {
|
||||
order: 0,
|
||||
blur_radius: shadow.blur_radius.scale(scale_factor),
|
||||
bounds: self.cover_bounds(hole),
|
||||
bounds: element_bounds,
|
||||
content_mask,
|
||||
corner_radii: hole_corner_radii.scale(scale_factor),
|
||||
corner_radii: element_corner_radii,
|
||||
color: shadow.color.opacity(opacity),
|
||||
element_bounds,
|
||||
element_corner_radii,
|
||||
inset: 1,
|
||||
shape_bounds: self.cover_bounds(hole),
|
||||
shape_corner_radii: hole_corner_radii.scale(scale_factor),
|
||||
inset: true.into(),
|
||||
pad: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
|
||||
let radii = &quad.corner_radii;
|
||||
let widths = &quad.border_widths;
|
||||
let edge_radii = Edges {
|
||||
top: radii.top_left.max(radii.top_right),
|
||||
right: radii.top_right.max(radii.bottom_right),
|
||||
bottom: radii.bottom_left.max(radii.bottom_right),
|
||||
left: radii.top_left.max(radii.bottom_left),
|
||||
};
|
||||
let size = quad.bounds.size;
|
||||
let diagonal = (size.width.0 * size.width.0 + size.height.0 * size.height.0).sqrt();
|
||||
if diagonal == 0. {
|
||||
return Bounds::default();
|
||||
}
|
||||
// The interior's corners sit on the corner arcs. Taking the angle along
|
||||
// the arc whose tangent is the quad's aspect ratio stays within 1% of
|
||||
// the largest interior.
|
||||
let cos = size.height.0 / diagonal;
|
||||
let sin = size.width.0 / diagonal;
|
||||
|
||||
let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
|
||||
let inset_bounds = |top_left_inset, bottom_right_inset| {
|
||||
Bounds::from_corners(
|
||||
quad.bounds.origin + top_left_inset + antialias_inset,
|
||||
quad.bounds.bottom_right() - bottom_right_inset - antialias_inset,
|
||||
// A corner's inner border edge is a quarter ellipse around the
|
||||
// corner's center, with the border widths taken off its radius.
|
||||
let corner_inset = |radius: ScaledPixels, width_x: ScaledPixels, width_y: ScaledPixels| {
|
||||
point(
|
||||
width_x.max(radius - (radius - width_x) * cos),
|
||||
width_y.max(radius - (radius - width_y) * sin),
|
||||
)
|
||||
};
|
||||
|
||||
// Rounded corners need only be excluded on one axis. Either candidate
|
||||
// is empty of border pixels, so use the larger interior.
|
||||
let horizontal_band = inset_bounds(
|
||||
point(widths.left, widths.top.max(edge_radii.top)),
|
||||
point(widths.right, widths.bottom.max(edge_radii.bottom)),
|
||||
);
|
||||
let vertical_band = inset_bounds(
|
||||
point(widths.left.max(edge_radii.left), widths.top),
|
||||
point(widths.right.max(edge_radii.right), widths.bottom),
|
||||
);
|
||||
let radii = &quad.corner_radii;
|
||||
let widths = &quad.border_widths;
|
||||
let top_left = corner_inset(radii.top_left, widths.left, widths.top);
|
||||
let top_right = corner_inset(radii.top_right, widths.right, widths.top);
|
||||
let bottom_right = corner_inset(radii.bottom_right, widths.right, widths.bottom);
|
||||
let bottom_left = corner_inset(radii.bottom_left, widths.left, widths.bottom);
|
||||
|
||||
let area = |bounds: &Bounds<ScaledPixels>| {
|
||||
bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.)
|
||||
};
|
||||
if area(&horizontal_band) >= area(&vertical_band) {
|
||||
horizontal_band
|
||||
} else {
|
||||
vertical_band
|
||||
}
|
||||
let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
|
||||
Bounds::from_corners(
|
||||
quad.bounds.origin
|
||||
+ point(top_left.x.max(bottom_left.x), top_left.y.max(top_right.y))
|
||||
+ antialias_inset,
|
||||
quad.bounds.bottom_right()
|
||||
- point(
|
||||
top_right.x.max(bottom_right.x),
|
||||
bottom_left.y.max(bottom_right.y),
|
||||
)
|
||||
- antialias_inset,
|
||||
)
|
||||
}
|
||||
|
||||
/// Paint one or more quads into the scene for the next frame at the current stacking context.
|
||||
@@ -4947,22 +5039,66 @@ impl Window {
|
||||
border_widths: snapped_border_widths,
|
||||
border_style: quad.border_style,
|
||||
};
|
||||
self.insert_quad(quad);
|
||||
}
|
||||
|
||||
if !quad.background.is_transparent() {
|
||||
fn insert_quad(&mut self, quad: Quad) {
|
||||
let has_background = !quad.background.is_transparent();
|
||||
let has_border =
|
||||
quad.border_widths != Edges::default() && !quad.border_color.is_transparent();
|
||||
if !has_background && !has_border {
|
||||
return;
|
||||
}
|
||||
|
||||
let is_rectangle =
|
||||
quad.border_widths == Edges::default() && quad.corner_radii == Corners::default();
|
||||
if has_background && is_rectangle {
|
||||
self.next_frame.scene.insert_primitive(quad);
|
||||
return;
|
||||
}
|
||||
|
||||
// Splitting a border-only quad around its empty interior avoids shading
|
||||
// every transparent pixel inside large outlines.
|
||||
let plain_border = quad.corner_radii == Corners::default()
|
||||
&& quad.border_style == BorderStyle::Solid
|
||||
&& (!has_background || quad.border_color.is_opaque());
|
||||
|
||||
// Splitting off the interior leaves only the strips around it for the
|
||||
// border and corner shading.
|
||||
let outer_bounds = quad.bounds;
|
||||
let inner_bounds = Self::largest_border_interior(&quad);
|
||||
let inner_bounds = if plain_border {
|
||||
quad.bounds.extend(quad.border_widths.map(|width| -*width))
|
||||
} else {
|
||||
Self::largest_border_interior(&quad)
|
||||
};
|
||||
|
||||
// A plain border's strips can be plain rectangles of the border color.
|
||||
// Otherwise, each strip is the whole quad masked to the strip, so the
|
||||
// border, corners and gradients are still shaded relative to the full quad.
|
||||
let strip_quad = if plain_border {
|
||||
Quad {
|
||||
background: quad.border_color.into(),
|
||||
border_widths: Edges::default(),
|
||||
..quad
|
||||
}
|
||||
} else {
|
||||
quad
|
||||
};
|
||||
|
||||
if inner_bounds.is_empty() {
|
||||
self.next_frame.scene.insert_primitive(quad);
|
||||
self.next_frame.scene.insert_primitive(strip_quad);
|
||||
return;
|
||||
}
|
||||
|
||||
if has_background {
|
||||
self.next_frame.scene.insert_primitive(Quad {
|
||||
content_mask: ContentMask {
|
||||
bounds: quad.content_mask.bounds.intersect(&inner_bounds),
|
||||
},
|
||||
border_widths: Edges::default(),
|
||||
corner_radii: Corners::default(),
|
||||
..quad
|
||||
});
|
||||
}
|
||||
|
||||
let strips = [
|
||||
// Top
|
||||
Bounds::from_corners(
|
||||
@@ -4987,33 +5123,31 @@ impl Window {
|
||||
];
|
||||
|
||||
for strip in strips {
|
||||
let content_mask_bounds = quad.content_mask.bounds.intersect(&strip);
|
||||
if !content_mask_bounds.is_empty() {
|
||||
self.next_frame.scene.insert_primitive(Quad {
|
||||
content_mask: ContentMask {
|
||||
bounds: content_mask_bounds,
|
||||
},
|
||||
..quad
|
||||
});
|
||||
}
|
||||
self.next_frame.scene.insert_primitive(Quad {
|
||||
content_mask: ContentMask {
|
||||
bounds: quad.content_mask.bounds.intersect(&strip),
|
||||
},
|
||||
..strip_quad
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint the given `Path` into the scene for the next frame at the current z-index.
|
||||
///
|
||||
/// This method should only be called as part of the paint phase of element drawing.
|
||||
pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
|
||||
pub fn paint_path(&mut self, path: Path, color: impl Into<Background>) {
|
||||
self.invalidator.debug_assert_paint();
|
||||
|
||||
let scale_factor = self.scale_factor();
|
||||
let content_mask = self.content_mask();
|
||||
let opacity = self.element_opacity();
|
||||
path.content_mask = content_mask;
|
||||
let color: Background = color.into();
|
||||
path.color = color.opacity(opacity);
|
||||
self.next_frame
|
||||
.scene
|
||||
.insert_primitive(path.scale(scale_factor));
|
||||
self.next_frame.scene.insert_primitive(PaintedPath::new(
|
||||
path,
|
||||
scale_factor,
|
||||
content_mask,
|
||||
color.opacity(opacity),
|
||||
));
|
||||
}
|
||||
|
||||
/// Paint an underline into the scene for the next frame at the current z-index.
|
||||
@@ -8530,6 +8664,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A stale cache is only visible if the snapshot reports GPUI's cached
|
||||
/// value separately from what the platform reports now.
|
||||
#[gpui::test]
|
||||
fn test_debug_state_reports_cached_and_platform_values(cx: &mut TestAppContext) {
|
||||
use crate::WindowVisibility;
|
||||
|
||||
let window = cx.add_window(|_, _| EmptyView);
|
||||
let window_id = window.window_id().as_u64();
|
||||
let window_state = |cx: &mut TestAppContext| {
|
||||
let state = cx.update(|cx| cx.debug_state());
|
||||
state["windows"]
|
||||
.as_array()
|
||||
.and_then(|windows| windows.iter().find(|window| window["id"] == window_id))
|
||||
.cloned()
|
||||
.expect("the open window is listed")
|
||||
};
|
||||
|
||||
let state = window_state(cx);
|
||||
assert_eq!(state["visibility"]["cached"], "Visible");
|
||||
assert_eq!(state["visibility"]["platform"], "Visible");
|
||||
|
||||
cx.test_window(window.into())
|
||||
.simulate_visibility_change(WindowVisibility::Hidden);
|
||||
let state = window_state(cx);
|
||||
assert_eq!(state["visibility"]["cached"], "Hidden");
|
||||
assert_eq!(state["visibility"]["platform"], "Hidden");
|
||||
}
|
||||
|
||||
/// Visibility transitions reach observers exactly once each, with the new
|
||||
/// state already stored on the window, and never wake the platform for a
|
||||
/// frame: the platform requests one itself when it resumes presenting.
|
||||
@@ -8688,6 +8850,48 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_window_opened_from_bounds_observer_uses_new_bounds(cx: &mut TestAppContext) {
|
||||
use crate::Subscription;
|
||||
|
||||
struct BoundsObserver {
|
||||
_subscription: Subscription,
|
||||
}
|
||||
|
||||
impl Render for BoundsObserver {
|
||||
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
||||
Empty
|
||||
}
|
||||
}
|
||||
|
||||
let opened_window = Rc::new(Cell::new(None));
|
||||
let window = cx.add_window({
|
||||
let opened_window = opened_window.clone();
|
||||
move |window, cx| BoundsObserver {
|
||||
_subscription: cx.observe_window_bounds(window, move |_, _, cx| {
|
||||
let handle = cx
|
||||
.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
|
||||
.unwrap();
|
||||
opened_window.set(Some(AnyWindowHandle::from(handle)));
|
||||
}),
|
||||
}
|
||||
});
|
||||
window
|
||||
.update(cx, |_, window, _| window.activate_window())
|
||||
.unwrap();
|
||||
|
||||
let new_size = size(px(400.), px(300.));
|
||||
cx.simulate_window_resize(window.into(), new_size);
|
||||
|
||||
let opened_window = opened_window
|
||||
.take()
|
||||
.expect("bounds observer should have opened a window");
|
||||
let opened_size = opened_window
|
||||
.update(cx, |_, window, _| window.bounds().size)
|
||||
.unwrap();
|
||||
assert_eq!(opened_size, new_size);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
|
||||
let window = cx.add_window(|_, _| EmptyView);
|
||||
@@ -9001,6 +9205,50 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_fullscreen_toggle_reports_current_bounds(cx: &mut TestAppContext) {
|
||||
let window = cx.add_window(|_, _| EmptyView);
|
||||
let handle = AnyWindowHandle::from(window);
|
||||
let notifications = Rc::new(Cell::new(0));
|
||||
window
|
||||
.update(cx, {
|
||||
let notifications = notifications.clone();
|
||||
|_, window, cx| {
|
||||
cx.observe_window_bounds(window, move |_, _, _| {
|
||||
notifications.set(notifications.get() + 1)
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let window_state = |cx: &mut TestAppContext| {
|
||||
cx.update_window(handle, |_, window, _| {
|
||||
(
|
||||
window.is_fullscreen(),
|
||||
window.bounds().size,
|
||||
window.viewport_size(),
|
||||
)
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let initial_size = window_state(cx).1;
|
||||
|
||||
window
|
||||
.update(cx, |_, window, _| window.toggle_fullscreen())
|
||||
.unwrap();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(window_state(cx), (true, initial_size, initial_size));
|
||||
assert_eq!(notifications.get(), 1);
|
||||
|
||||
let resized_size = size(px(800.), px(600.));
|
||||
window
|
||||
.update(cx, |_, window, _| window.toggle_fullscreen())
|
||||
.unwrap();
|
||||
cx.simulate_window_resize(handle, resized_size);
|
||||
cx.run_until_parked();
|
||||
assert_eq!(window_state(cx), (false, resized_size, resized_size));
|
||||
}
|
||||
|
||||
/// Platforms that stop requesting frames for idle windows (currently web)
|
||||
/// rely on the frame waker firing whenever frame demand arises; a demand
|
||||
/// source that skips the waker shows up there as a window that silently
|
||||
|
||||
@@ -56,6 +56,7 @@ objc2-metal = { version = "0.3.2", default-features = false, features = [
|
||||
"MTLCommandBuffer",
|
||||
"MTLCommandEncoder",
|
||||
"MTLCommandQueue",
|
||||
"MTLDepthStencil",
|
||||
"MTLDevice",
|
||||
"MTLDrawable",
|
||||
"MTLLibrary",
|
||||
|
||||
@@ -42,14 +42,15 @@ mod apple_build {
|
||||
"Edges".into(),
|
||||
"Size".into(),
|
||||
"Pixels".into(),
|
||||
"PointF".into(),
|
||||
"Hsla".into(),
|
||||
"ContentMask".into(),
|
||||
"Uniforms".into(),
|
||||
"AtlasTile".into(),
|
||||
"PathRasterizationInputIndex".into(),
|
||||
"PathVertex_ScaledPixels".into(),
|
||||
"PathRasterizationVertex".into(),
|
||||
"GlobalInputIndex".into(),
|
||||
"PathTileInputIndex".into(),
|
||||
"PathTile".into(),
|
||||
"PathCurve".into(),
|
||||
"PathPaint".into(),
|
||||
"ShadowInputIndex".into(),
|
||||
"Shadow".into(),
|
||||
"QuadInputIndex".into(),
|
||||
@@ -60,7 +61,6 @@ mod apple_build {
|
||||
"SpriteInputIndex".into(),
|
||||
"MonochromeSprite".into(),
|
||||
"PolychromeSprite".into(),
|
||||
"PathSprite".into(),
|
||||
"SurfaceInputIndex".into(),
|
||||
"SurfaceBounds".into(),
|
||||
"TransformationMatrix".into(),
|
||||
|
||||
@@ -91,6 +91,10 @@ impl MetalFrameSource {
|
||||
pub fn set_paused(&self, paused: bool) {
|
||||
self.link.setPaused(paused);
|
||||
}
|
||||
|
||||
pub fn is_paused(&self) -> bool {
|
||||
self.link.isPaused()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MetalFrameSource {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+519
-461
File diff suppressed because it is too large
Load Diff
@@ -1697,47 +1697,14 @@ impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
|
||||
};
|
||||
drop(state);
|
||||
|
||||
if let wl_callback::Event::Done { callback_data } = event {
|
||||
window.frame_callback_fired(PlatformFrameSignal::capture(|| {
|
||||
frame_callback_signal_at(callback_data)
|
||||
}));
|
||||
// The callback's timestamp uses a clock the protocol leaves unspecified,
|
||||
// so frame timing measures from receipt, as the other platforms do.
|
||||
if let wl_callback::Event::Done { .. } = event {
|
||||
window.frame_callback_fired(PlatformFrameSignal::capture(Instant::now));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn frame_callback_signal_at(callback_data: u32) -> Instant {
|
||||
let mut monotonic = libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: 0,
|
||||
};
|
||||
// wl_surface.frame specifies an unspecified epoch. Mutter and Sway use
|
||||
// CLOCK_MONOTONIC, but reject implausible ages for other compositor clocks.
|
||||
let result = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut monotonic) };
|
||||
let received_at = Instant::now();
|
||||
if result != 0 || monotonic.tv_sec < 0 || !(0..1_000_000_000).contains(&monotonic.tv_nsec) {
|
||||
return received_at;
|
||||
}
|
||||
let monotonic_millis =
|
||||
(monotonic.tv_sec as u64 * 1_000 + monotonic.tv_nsec as u64 / 1_000_000) as u32;
|
||||
frame_callback_instant(callback_data, monotonic_millis, received_at)
|
||||
}
|
||||
|
||||
fn frame_callback_instant(
|
||||
callback_data: u32,
|
||||
monotonic_millis: u32,
|
||||
received_at: Instant,
|
||||
) -> Instant {
|
||||
// The wire timestamp wraps every ~49 days. A future timestamp also wraps
|
||||
// when subtracted, so the bound rejects it without guessing another epoch.
|
||||
let age_millis = monotonic_millis.wrapping_sub(callback_data);
|
||||
if age_millis > 60_000 {
|
||||
return received_at;
|
||||
}
|
||||
received_at
|
||||
.checked_sub(Duration::from_millis(u64::from(age_millis)))
|
||||
.unwrap_or(received_at)
|
||||
}
|
||||
|
||||
pub(crate) fn get_window(
|
||||
state: &mut RefMut<WaylandClientState>,
|
||||
surface_id: &ObjectId,
|
||||
@@ -3226,43 +3193,6 @@ mod tests {
|
||||
assert_eq!(wl_output_version(2).expect("minimum output version"), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_callback_timestamp_preserves_queue_delay() {
|
||||
let received_at = Instant::now();
|
||||
assert_eq!(
|
||||
frame_callback_instant(1_000, 1_025, received_at),
|
||||
received_at - Duration::from_millis(25),
|
||||
);
|
||||
assert_eq!(
|
||||
frame_callback_instant(1_000, 1_000, received_at),
|
||||
received_at,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_callback_timestamp_wraps() {
|
||||
let received_at = Instant::now();
|
||||
assert_eq!(
|
||||
frame_callback_instant(u32::MAX - 9, 15, received_at),
|
||||
received_at - Duration::from_millis(25),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_callback_timestamp_rejects_implausible_clock() {
|
||||
let received_at = Instant::now();
|
||||
for (callback_data, monotonic_millis) in [(1_001, 1_000), (0, 60_001), (0, u32::MAX)] {
|
||||
assert_eq!(
|
||||
frame_callback_instant(callback_data, monotonic_millis, received_at),
|
||||
received_at,
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
frame_callback_instant(0, 60_000, received_at),
|
||||
received_at - Duration::from_secs(60),
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FakeDataOffer {
|
||||
name: &'static str,
|
||||
|
||||
@@ -1114,6 +1114,8 @@ impl WaylandWindowStatePtr {
|
||||
|
||||
if let Some(mut configure) = state.in_progress_configure.take() {
|
||||
let got_unmaximized = state.maximized && !configure.maximized;
|
||||
let fullscreen_changed = state.fullscreen != configure.fullscreen;
|
||||
let mode_changed = fullscreen_changed || state.maximized != configure.maximized;
|
||||
state.fullscreen = configure.fullscreen;
|
||||
state.maximized = configure.maximized;
|
||||
state.tiling = configure.tiling;
|
||||
@@ -1141,15 +1143,27 @@ impl WaylandWindowStatePtr {
|
||||
}
|
||||
}
|
||||
}
|
||||
let resized = configure.size.is_some_and(|size| size != state.bounds.size);
|
||||
drop(state);
|
||||
if visibility_changed {
|
||||
self.report_visibility(configure.visibility);
|
||||
}
|
||||
if !throttled && let Some(size) = configure.size {
|
||||
self.resize(size);
|
||||
}
|
||||
if fullscreen_changed {
|
||||
self.notify_resize();
|
||||
}
|
||||
if throttled {
|
||||
return;
|
||||
}
|
||||
if let Some(size) = configure.size {
|
||||
self.resize(size);
|
||||
// Same-size mode changes skip the resize callback, so report them as a move.
|
||||
if mode_changed && !resized && !fullscreen_changed {
|
||||
let callback = self.callbacks.borrow_mut().moved.take();
|
||||
if let Some(mut fun) = callback {
|
||||
fun();
|
||||
self.callbacks.borrow_mut().moved = Some(fun);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1548,6 +1562,18 @@ impl WaylandWindowStatePtr {
|
||||
update_window(state);
|
||||
}
|
||||
|
||||
fn notify_resize(&self) {
|
||||
let (size, scale) = {
|
||||
let state = self.state.borrow();
|
||||
(state.bounds.size, state.scale)
|
||||
};
|
||||
let callback = self.callbacks.borrow_mut().resize.take();
|
||||
if let Some(mut fun) = callback {
|
||||
fun(size, scale);
|
||||
self.callbacks.borrow_mut().resize = Some(fun);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resize(&self, size: Size<Pixels>) {
|
||||
self.set_size_and_scale(Some(size), None);
|
||||
}
|
||||
|
||||
@@ -305,6 +305,11 @@ impl X11WindowState {
|
||||
renderer.update_transparency(is_transparent);
|
||||
}
|
||||
}
|
||||
|
||||
fn is_maximized(&self) -> bool {
|
||||
// A maximized window that gets minimized will still retain its maximized state.
|
||||
!self.hidden && self.maximized_vertical && self.maximized_horizontal
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -1063,7 +1068,11 @@ impl X11WindowStatePtr {
|
||||
pub fn property_notify(&self, event: xproto::PropertyNotifyEvent) -> anyhow::Result<()> {
|
||||
let state = self.state.borrow_mut();
|
||||
if event.atom == state.atoms._NET_WM_STATE {
|
||||
let was_fullscreen = state.fullscreen;
|
||||
self.set_wm_properties(state)?;
|
||||
if self.state.borrow().fullscreen != was_fullscreen {
|
||||
self.notify_resize();
|
||||
}
|
||||
} else if event.atom == state.atoms._GTK_EDGE_CONSTRAINTS {
|
||||
self.set_edge_constraints(state)?;
|
||||
}
|
||||
@@ -1121,6 +1130,7 @@ impl X11WindowStatePtr {
|
||||
.map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
|
||||
|
||||
let was_active = state.active;
|
||||
let was_maximized = state.maximized_vertical && state.maximized_horizontal;
|
||||
state.active = false;
|
||||
state.fullscreen = false;
|
||||
state.maximized_vertical = false;
|
||||
@@ -1147,6 +1157,19 @@ impl X11WindowStatePtr {
|
||||
set_wm_hints_urgency(&self.xcb, self.x_window, false);
|
||||
}
|
||||
|
||||
// Maximized changes without a geometry change get no ConfigureNotify, so report them as a move.
|
||||
// This ignores `hidden`, since minimizing shouldn't notify bounds observers.
|
||||
let maximized_changed =
|
||||
(state.maximized_vertical && state.maximized_horizontal) != was_maximized;
|
||||
drop(state);
|
||||
if maximized_changed {
|
||||
let callback = self.callbacks.borrow_mut().moved.take();
|
||||
if let Some(mut fun) = callback {
|
||||
fun();
|
||||
self.callbacks.borrow_mut().moved = Some(fun);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1332,6 +1355,18 @@ impl X11WindowStatePtr {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn notify_resize(&self) {
|
||||
let (content_size, scale_factor) = {
|
||||
let state = self.state.borrow();
|
||||
(state.content_size(), state.scale_factor)
|
||||
};
|
||||
let callback = self.callbacks.borrow_mut().resize.take();
|
||||
if let Some(mut fun) = callback {
|
||||
fun(content_size, scale_factor);
|
||||
self.callbacks.borrow_mut().resize = Some(fun);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_active(&self, focus: bool) {
|
||||
let callback = self.callbacks.borrow_mut().active_status_change.take();
|
||||
if let Some(mut fun) = callback {
|
||||
@@ -1390,10 +1425,7 @@ impl PlatformWindow for X11Window {
|
||||
}
|
||||
|
||||
fn is_maximized(&self) -> bool {
|
||||
let state = self.0.state.borrow();
|
||||
|
||||
// A maximized window that gets minimized will still retain its maximized state.
|
||||
!state.hidden && state.maximized_vertical && state.maximized_horizontal
|
||||
self.0.state.borrow().is_maximized()
|
||||
}
|
||||
|
||||
fn window_bounds(&self) -> WindowBounds {
|
||||
|
||||
@@ -55,6 +55,7 @@ parking_lot.workspace = true
|
||||
raw-window-handle.workspace = true
|
||||
scheduler.workspace = true
|
||||
semver.workspace = true
|
||||
serde_json.workspace = true
|
||||
smallvec.workspace = true
|
||||
strum.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
@@ -331,6 +331,20 @@ impl MetalFrames {
|
||||
self.woken.set(false);
|
||||
}
|
||||
|
||||
pub fn debug_state(&self) -> serde_json::Value {
|
||||
let paused = self
|
||||
.source
|
||||
.try_borrow()
|
||||
.ok()
|
||||
.and_then(|source| source.as_ref().map(MetalFrameSource::is_paused));
|
||||
serde_json::json!({
|
||||
"kind": "CAMetalDisplayLink",
|
||||
"attached": self.is_attached(),
|
||||
"paused": paused,
|
||||
"woken": self.woken.get(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Ends an update, pausing the link if GPUI neither used its drawable nor
|
||||
/// asked for another frame while it ran. Returns whether it paused.
|
||||
pub fn end_frame(&self, used_drawable: bool) -> bool {
|
||||
@@ -382,6 +396,14 @@ impl WindowFrameSource {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn debug_state(&self) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"kind": "CVDisplayLink",
|
||||
"attached": self.registration.is_some(),
|
||||
"display_id": self.registration.map(|(display_id, _)| display_id),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn take_signal(&self) -> Option<(Instant, FrameRequestSource)> {
|
||||
self.signal.take()
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ mod screen_capture;
|
||||
use gpui_apple::metal_renderer as renderer;
|
||||
|
||||
pub mod metal_renderer {
|
||||
pub use gpui_apple::metal_renderer::{PathRasterizationVertex, PathSprite, SurfaceBounds};
|
||||
pub use gpui_apple::metal_renderer::SurfaceBounds;
|
||||
|
||||
#[cfg(any(test, feature = "bench-support", feature = "test-support"))]
|
||||
pub use gpui_apple::metal_renderer::MetalHeadlessRenderer;
|
||||
|
||||
@@ -32,9 +32,10 @@ use objc2::{
|
||||
use objc2_app_kit::{
|
||||
NSAppearance, NSAppearanceNameAqua, NSAppearanceNameDarkAqua, NSAppearanceNameVibrantDark,
|
||||
NSAppearanceNameVibrantLight, NSApplication, NSApplicationActivationPolicy,
|
||||
NSControlStateValueOn, NSCursor, NSDocumentController, NSEventModifierFlags, NSMenu,
|
||||
NSMenuItem, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSSavePanel, NSScroller,
|
||||
NSScrollerStyle, NSWorkspace, NSWorkspaceDidWakeNotification, NSWorkspaceWillSleepNotification,
|
||||
NSApplicationOcclusionState, NSControlStateValueOn, NSCursor, NSDocumentController,
|
||||
NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSModalResponseOK, NSOpenPanel,
|
||||
NSSavePanel, NSScroller, NSScrollerStyle, NSWorkspace, NSWorkspaceDidWakeNotification,
|
||||
NSWorkspaceWillSleepNotification,
|
||||
};
|
||||
use objc2_foundation::{
|
||||
NSActivityOptions, NSArray, NSBundle, NSError, NSInteger, NSProcessInfo, NSString, NSURL,
|
||||
@@ -55,6 +56,7 @@ use std::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
use strum::IntoEnumIterator as _;
|
||||
|
||||
const MAC_PLATFORM_IVAR: &CStr = c"platform";
|
||||
static mut APP_CLASS: *const AnyClass = ptr::null();
|
||||
@@ -1081,6 +1083,34 @@ impl Platform for MacPlatform {
|
||||
self.ensure_system_power_observers();
|
||||
}
|
||||
|
||||
fn debug_state(&self) -> serde_json::Value {
|
||||
let app = NSApplication::sharedApplication(self.1);
|
||||
let key_window: *mut AnyObject = unsafe { msg_send![&*app, keyWindow] };
|
||||
let main_window: *mut AnyObject = unsafe { msg_send![&*app, mainWindow] };
|
||||
let window_number = |window: *mut AnyObject| -> Option<isize> {
|
||||
(!window.is_null()).then(|| unsafe { msg_send![window, windowNumber] })
|
||||
};
|
||||
// AppKit's cursor for this app, mapped back to the style GPUI would
|
||||
// have set it from. `None` when it is not one GPUI sets.
|
||||
let current_cursor = Retained::as_ptr(&NSCursor::currentCursor()).cast::<AnyObject>();
|
||||
let current_cursor_style = CursorStyle::iter().find(|style| {
|
||||
// SAFETY: The platform is only used on the main thread.
|
||||
let cursor = unsafe { crate::window::native_cursor(*style) };
|
||||
ptr::eq(cursor, current_cursor)
|
||||
});
|
||||
serde_json::json!({
|
||||
"current_cursor_style": current_cursor_style,
|
||||
"app_is_active": app.isActive(),
|
||||
"app_is_hidden": app.isHidden(),
|
||||
"app_occlusion_state_visible": app
|
||||
.occlusionState()
|
||||
.contains(NSApplicationOcclusionState::Visible),
|
||||
"key_window_number": window_number(key_window),
|
||||
"main_window_number": window_number(main_window),
|
||||
"low_power_mode": NSProcessInfo::processInfo().isLowPowerModeEnabled(),
|
||||
})
|
||||
}
|
||||
|
||||
fn thermal_state(&self) -> ThermalState {
|
||||
process_info::thermal_state()
|
||||
}
|
||||
|
||||
+139
-35
@@ -434,6 +434,10 @@ unsafe fn build_window_class(name: &CStr, superclass: &AnyClass) -> *const AnyCl
|
||||
sel!(windowWillEnterFullScreen:),
|
||||
window_will_enter_fullscreen as extern "C" fn(_, Sel, *mut AnyObject),
|
||||
);
|
||||
decl.add_method(
|
||||
sel!(windowDidFailToEnterFullScreen:),
|
||||
window_did_fail_to_enter_fullscreen as extern "C" fn(_, Sel, *mut AnyObject),
|
||||
);
|
||||
decl.add_method(
|
||||
sel!(windowWillExitFullScreen:),
|
||||
window_will_exit_fullscreen as extern "C" fn(_, Sel, *mut AnyObject),
|
||||
@@ -677,6 +681,7 @@ struct MacWindowState {
|
||||
last_left_mouse_down_event: Option<Retained<AnyObject>>,
|
||||
synthetic_drag_counter: usize,
|
||||
traffic_light_position: Option<Point<Pixels>>,
|
||||
native_titlebar_visible: bool,
|
||||
traffic_light_frames: Option<TrafficLightFrames>,
|
||||
pre_fullscreen_traffic_light_frames: Option<TrafficLightFrames>,
|
||||
transparent_titlebar: bool,
|
||||
@@ -708,6 +713,10 @@ struct MacWindowState {
|
||||
|
||||
impl MacWindowState {
|
||||
fn move_traffic_light(&mut self) {
|
||||
if !self.native_titlebar_visible {
|
||||
self.update_native_titlebar_visibility();
|
||||
}
|
||||
|
||||
if let Some(traffic_light_position) = self.traffic_light_position {
|
||||
if self.is_fullscreen() && !self.is_exiting_fullscreen {
|
||||
self.restore_traffic_light();
|
||||
@@ -767,6 +776,46 @@ impl MacWindowState {
|
||||
}
|
||||
}
|
||||
|
||||
fn update_native_titlebar_visibility(&self) {
|
||||
let Some(close_button) = self
|
||||
.native_window()
|
||||
.standardWindowButton(NSWindowButton::CloseButton)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if let Some(titlebar_container) = Self::titlebar_container(&close_button) {
|
||||
titlebar_container.setHidden(!self.native_titlebar_visible);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_fullscreen_titlebar_opacity(&self) {
|
||||
let min_version = NSOperatingSystemVersion {
|
||||
majorVersion: 15,
|
||||
minorVersion: 3,
|
||||
patchVersion: 0,
|
||||
};
|
||||
|
||||
if is_macos_version_at_least(min_version) {
|
||||
unsafe {
|
||||
let _: () = msg_send![self.native_window, setTitlebarAppearsTransparent: Bool::NO];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_windowed_titlebar_transparency(&self) {
|
||||
let min_version = NSOperatingSystemVersion {
|
||||
majorVersion: 15,
|
||||
minorVersion: 3,
|
||||
patchVersion: 0,
|
||||
};
|
||||
|
||||
if is_macos_version_at_least(min_version) && self.transparent_titlebar {
|
||||
unsafe {
|
||||
let _: () = msg_send![self.native_window, setTitlebarAppearsTransparent: Bool::YES];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn capture_traffic_light_frames(&self) -> Option<TrafficLightFrames> {
|
||||
let buttons = self.traffic_light_buttons()?;
|
||||
let titlebar_container = Self::titlebar_container(&buttons.close)?;
|
||||
@@ -1142,6 +1191,7 @@ impl MacWindow {
|
||||
traffic_light_position: titlebar
|
||||
.as_ref()
|
||||
.and_then(|titlebar| titlebar.traffic_light_position),
|
||||
native_titlebar_visible: true,
|
||||
traffic_light_frames: None,
|
||||
pre_fullscreen_traffic_light_frames: None,
|
||||
transparent_titlebar: titlebar
|
||||
@@ -1659,6 +1709,12 @@ impl PlatformWindow for MacWindow {
|
||||
}
|
||||
}
|
||||
|
||||
fn set_native_titlebar_visibility(&self, visible: bool) {
|
||||
let mut state = self.0.lock();
|
||||
state.native_titlebar_visible = visible;
|
||||
state.update_native_titlebar_visibility();
|
||||
}
|
||||
|
||||
fn set_traffic_light_position(&self, position: Point<Pixels>) {
|
||||
let mut state = self.0.lock();
|
||||
state.traffic_light_position = Some(position);
|
||||
@@ -2173,6 +2229,56 @@ impl PlatformWindow for MacWindow {
|
||||
None
|
||||
}
|
||||
|
||||
fn debug_state(&self) -> serde_json::Value {
|
||||
let state = self.0.lock();
|
||||
let window = state.native_window();
|
||||
let screen: *mut AnyObject = unsafe { msg_send![state.native_window, screen] };
|
||||
let frame = window.frame();
|
||||
let layer = state.renderer.layer().map(|layer| {
|
||||
let drawable_size = layer.drawableSize();
|
||||
serde_json::json!({
|
||||
"drawable_size": [drawable_size.width, drawable_size.height],
|
||||
"contents_scale": layer.contentsScale(),
|
||||
})
|
||||
});
|
||||
serde_json::json!({
|
||||
"window_number": window.windowNumber(),
|
||||
"occlusion_state_visible": window
|
||||
.occlusionState()
|
||||
.contains(NSWindowOcclusionState::Visible),
|
||||
"is_visible": window.isVisible(),
|
||||
"is_key_window": window.isKeyWindow(),
|
||||
"is_main_window": window.isMainWindow(),
|
||||
"is_miniaturized": window.isMiniaturized(),
|
||||
"is_on_active_space": window.isOnActiveSpace(),
|
||||
"screen_display_id": display_id_for_screen(screen),
|
||||
"frame": [frame.origin.x, frame.origin.y, frame.size.width, frame.size.height],
|
||||
"backing_scale_factor": window.backingScaleFactor(),
|
||||
"frame_source": match &state.frame_source {
|
||||
FrameSource::Metal(metal_frames) => metal_frames.debug_state(),
|
||||
FrameSource::DisplayLink(Some(frame_source)) => frame_source.debug_state(),
|
||||
FrameSource::DisplayLink(None) => serde_json::json!({
|
||||
"kind": "CVDisplayLink",
|
||||
"attached": false,
|
||||
}),
|
||||
},
|
||||
"renderer": {
|
||||
"display_link_attached": state.renderer.is_display_link_attached(),
|
||||
"presents_with_transaction": state.renderer.presents_with_transaction(),
|
||||
"layer": layer,
|
||||
},
|
||||
"request_frame_callback_installed": state.request_frame_callback.is_some(),
|
||||
"last_reported_visibility": state
|
||||
.last_visibility
|
||||
.map(|visibility| format!("{visibility:?}")),
|
||||
"activated_at_least_once": state.activated_least_once,
|
||||
"cursor": {
|
||||
"cached_style": state.cursor_style,
|
||||
"cached_visible": state.cursor_visible.load(Ordering::Relaxed),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn update_ime_position(&self, _bounds: Bounds<Pixels>) {
|
||||
let executor = self.0.lock().foreground_executor.clone();
|
||||
executor
|
||||
@@ -2565,17 +2671,13 @@ fn add_mouse_tracking_area(native_view: &NSView) {
|
||||
native_view.addTrackingArea(&tracking_area);
|
||||
}
|
||||
|
||||
extern "C" fn reset_cursor_rects(this: &AnyObject, _: Sel) {
|
||||
// SAFETY: AppKit invokes cursor-rect updates on the main thread for GPUIView instances,
|
||||
// whose WINDOW_STATE_IVAR is initialized when the view is created. The cursor registered
|
||||
// below is a valid NSCursor.
|
||||
/// # Safety
|
||||
///
|
||||
/// Must be called on the AppKit main thread.
|
||||
pub(crate) unsafe fn native_cursor(style: CursorStyle) -> *mut AnyObject {
|
||||
// SAFETY: Each selector is an `NSCursor` class method returning a cursor.
|
||||
unsafe {
|
||||
let _: () = msg_send![super(this, class!(NSView)), resetCursorRects];
|
||||
|
||||
let window_state = get_window_state(this);
|
||||
let cursor_style = window_state.lock().cursor_style;
|
||||
|
||||
let cursor: *mut AnyObject = match cursor_style {
|
||||
match style {
|
||||
CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
|
||||
CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
|
||||
CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
|
||||
@@ -2609,7 +2711,21 @@ extern "C" fn reset_cursor_rects(this: &AnyObject, _: Sel) {
|
||||
CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
|
||||
CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
|
||||
CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn reset_cursor_rects(this: &AnyObject, _: Sel) {
|
||||
// SAFETY: AppKit invokes cursor-rect updates on the main thread for GPUIView instances,
|
||||
// whose WINDOW_STATE_IVAR is initialized when the view is created. The cursor registered
|
||||
// below is a valid NSCursor.
|
||||
unsafe {
|
||||
let _: () = msg_send![super(this, class!(NSView)), resetCursorRects];
|
||||
|
||||
let window_state = get_window_state(this);
|
||||
let cursor_style = window_state.lock().cursor_style;
|
||||
|
||||
let cursor = native_cursor(cursor_style);
|
||||
|
||||
let bounds: NSRect = msg_send![this, bounds];
|
||||
let _: () = msg_send![this, addCursorRect: bounds, cursor: cursor];
|
||||
@@ -3083,37 +3199,22 @@ extern "C" fn window_will_enter_fullscreen(this: &AnyObject, _: Sel, _: *mut Any
|
||||
lock.is_exiting_fullscreen = false;
|
||||
lock.pre_fullscreen_traffic_light_frames = lock.traffic_light_frames;
|
||||
lock.restore_traffic_light();
|
||||
lock.apply_fullscreen_titlebar_opacity();
|
||||
}
|
||||
|
||||
let min_version = NSOperatingSystemVersion {
|
||||
majorVersion: 15,
|
||||
minorVersion: 3,
|
||||
patchVersion: 0,
|
||||
};
|
||||
|
||||
if is_macos_version_at_least(min_version) {
|
||||
unsafe {
|
||||
let _: () = msg_send![lock.native_window, setTitlebarAppearsTransparent: Bool::NO];
|
||||
}
|
||||
}
|
||||
extern "C" fn window_did_fail_to_enter_fullscreen(this: &AnyObject, _: Sel, _: *mut AnyObject) {
|
||||
let window_state = unsafe { get_window_state(this) };
|
||||
let mut lock = window_state.as_ref().lock();
|
||||
lock.restore_windowed_titlebar_transparency();
|
||||
lock.traffic_light_frames = lock.pre_fullscreen_traffic_light_frames.take();
|
||||
lock.move_traffic_light();
|
||||
}
|
||||
|
||||
extern "C" fn window_will_exit_fullscreen(this: &AnyObject, _: Sel, _: *mut AnyObject) {
|
||||
let window_state = unsafe { get_window_state(this) };
|
||||
let mut lock = window_state.as_ref().lock();
|
||||
lock.is_exiting_fullscreen = true;
|
||||
|
||||
let min_version = NSOperatingSystemVersion {
|
||||
majorVersion: 15,
|
||||
minorVersion: 3,
|
||||
patchVersion: 0,
|
||||
};
|
||||
|
||||
if is_macos_version_at_least(min_version) && lock.transparent_titlebar {
|
||||
unsafe {
|
||||
let _: () = msg_send![lock.native_window, setTitlebarAppearsTransparent: Bool::YES];
|
||||
}
|
||||
}
|
||||
|
||||
lock.restore_windowed_titlebar_transparency();
|
||||
lock.move_traffic_light();
|
||||
}
|
||||
|
||||
@@ -3121,6 +3222,9 @@ extern "C" fn window_did_fail_to_exit_fullscreen(this: &AnyObject, _: Sel, _: *m
|
||||
let window_state = unsafe { get_window_state(this) };
|
||||
let mut lock = window_state.as_ref().lock();
|
||||
lock.is_exiting_fullscreen = false;
|
||||
if lock.is_fullscreen() {
|
||||
lock.apply_fullscreen_titlebar_opacity();
|
||||
}
|
||||
lock.restore_traffic_light();
|
||||
}
|
||||
|
||||
|
||||
@@ -12,9 +12,9 @@ use std::{fmt, rc::Rc, time::Duration};
|
||||
|
||||
use gpui::{
|
||||
App, AtlasTextureId, AtlasTextureKind, AtlasTile, Background, BenchAppContext, Bounds,
|
||||
BoxShadow, Context, Corners, DevicePixels, Hsla, IntoElement, Path, PathBuilder, Pixels,
|
||||
Render, Scene, SharedString, Styled, TextAlign, TextRun, TileId, TransformationMatrix,
|
||||
UnderlineStyle, Window, canvas, fill, hsla, point,
|
||||
BoxShadow, ContentMask, Context, Corners, DevicePixels, Hsla, IntoElement, PaintedPath, Path,
|
||||
PathBuilder, Pixels, Render, Scene, SharedString, Styled, TextAlign, TextRun, TileId,
|
||||
TransformationMatrix, UnderlineStyle, Window, canvas, fill, hsla, point,
|
||||
private::rand::{Rng as _, SeedableRng as _, rngs::StdRng},
|
||||
px, size,
|
||||
};
|
||||
@@ -80,9 +80,12 @@ enum Kind {
|
||||
Quad,
|
||||
Shadow,
|
||||
Underline,
|
||||
/// Tessellated before timing: path tessellation is measured by the tree benchmarks,
|
||||
/// and would otherwise dominate what these cases are for.
|
||||
Path(Path<Pixels>),
|
||||
/// Built and binned before timing, since binning would otherwise dominate what these
|
||||
/// cases are for. The window paints `path`, and the scene takes a copy of `painted`.
|
||||
Path {
|
||||
path: Path,
|
||||
painted: PaintedPath,
|
||||
},
|
||||
Text(SharedString),
|
||||
}
|
||||
|
||||
@@ -113,7 +116,10 @@ fn random_rectangles(seed: u64, count: usize, extent: f32) -> Rc<[Rectangle]> {
|
||||
0..9 => Kind::Quad,
|
||||
9..11 => Kind::Shadow,
|
||||
11..13 => Kind::Underline,
|
||||
13..16 => triangle(bounds).map_or(Kind::Quad, Kind::Path),
|
||||
13..16 => triangle(bounds).map_or(Kind::Quad, |path| Kind::Path {
|
||||
painted: PaintedPath::new(path.clone(), 1., scene_content_mask(), color.into()),
|
||||
path,
|
||||
}),
|
||||
_ => {
|
||||
let length = rng.random_range(1..12);
|
||||
Kind::Text("Ag3 Wq7 fixture"[..length].to_string().into())
|
||||
@@ -130,7 +136,7 @@ fn random_rectangles(seed: u64, count: usize, extent: f32) -> Rc<[Rectangle]> {
|
||||
.into()
|
||||
}
|
||||
|
||||
fn triangle(bounds: Bounds<Pixels>) -> Option<Path<Pixels>> {
|
||||
fn triangle(bounds: Bounds<Pixels>) -> Option<Path> {
|
||||
let mut path = PathBuilder::fill();
|
||||
path.move_to(bounds.origin);
|
||||
path.line_to(bounds.top_right());
|
||||
@@ -236,7 +242,7 @@ fn paint(rectangle: &Rectangle, window: &mut Window, cx: &mut App) {
|
||||
wavy: false,
|
||||
},
|
||||
),
|
||||
Kind::Path(path) => window.paint_path(path.clone(), rectangle.color),
|
||||
Kind::Path { path, .. } => window.paint_path(path.clone(), rectangle.color),
|
||||
// Shaped every frame, as the text element does; the line layout cache makes
|
||||
// repeated shaping a lookup.
|
||||
Kind::Text(text) => {
|
||||
@@ -283,11 +289,20 @@ fn glyph_tile(index: usize) -> AtlasTile {
|
||||
}
|
||||
}
|
||||
|
||||
fn scene_content_mask() -> ContentMask<Pixels> {
|
||||
ContentMask {
|
||||
bounds: Bounds::new(point(px(0.), px(0.)), size(px(1_024.), px(1_024.))),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) {
|
||||
insert_primitives(scene, rectangles);
|
||||
scene.finish();
|
||||
}
|
||||
|
||||
fn insert_primitives(scene: &mut Scene, rectangles: &[Rectangle]) {
|
||||
scene.clear();
|
||||
let content_mask = gpui::ContentMask {
|
||||
bounds: Bounds::new(point(px(0.), px(0.)), size(px(1_024.), px(1_024.))).scale(1.),
|
||||
};
|
||||
let content_mask = scene_content_mask().scale(1.);
|
||||
for (index, rectangle) in rectangles.iter().enumerate() {
|
||||
let bounds = rectangle.bounds.scale(1.);
|
||||
match &rectangle.kind {
|
||||
@@ -304,13 +319,13 @@ fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) {
|
||||
Kind::Shadow => scene.insert_primitive(gpui::Shadow {
|
||||
order: 0,
|
||||
blur_radius: gpui::ScaledPixels(6.),
|
||||
bounds,
|
||||
corner_radii: Corners::all(gpui::ScaledPixels(4.)),
|
||||
bounds: bounds.dilate(gpui::ScaledPixels(18.)),
|
||||
corner_radii: Corners::default(),
|
||||
content_mask,
|
||||
color: rectangle.color,
|
||||
element_bounds: bounds,
|
||||
element_corner_radii: Corners::all(gpui::ScaledPixels(4.)),
|
||||
inset: 0,
|
||||
shape_bounds: bounds,
|
||||
shape_corner_radii: Corners::all(gpui::ScaledPixels(4.)),
|
||||
inset: false.into(),
|
||||
pad: 0,
|
||||
}),
|
||||
Kind::Underline => scene.insert_primitive(gpui::Underline {
|
||||
@@ -322,12 +337,7 @@ fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) {
|
||||
thickness: bounds.size.height.min(gpui::ScaledPixels(4.)),
|
||||
wavy: Default::default(),
|
||||
}),
|
||||
Kind::Path(path) => {
|
||||
let mut path = path.scale(1.);
|
||||
path.content_mask = content_mask;
|
||||
path.color = rectangle.background;
|
||||
scene.insert_primitive(path);
|
||||
}
|
||||
Kind::Path { painted, .. } => scene.insert_primitive(painted.clone()),
|
||||
Kind::Text(text) => {
|
||||
let glyph_size = bounds.size.height.min(gpui::ScaledPixels(32.));
|
||||
for glyph in 0..text.len() {
|
||||
@@ -346,7 +356,26 @@ fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) {
|
||||
}
|
||||
}
|
||||
}
|
||||
scene.finish();
|
||||
}
|
||||
|
||||
fn scene_finish(criterion: &mut criterion::Criterion<gpui::BenchMeasurement>) {
|
||||
let mut group = criterion.benchmark_group("Primitives/finish");
|
||||
for case in cases() {
|
||||
let mut fixture = None;
|
||||
group.bench_function(case.to_string(), |bencher| {
|
||||
let rectangles = fixture.get_or_insert_with(|| rectangles(&case, 512.));
|
||||
bencher.iter_batched_ref(
|
||||
|| {
|
||||
let mut scene = Scene::default();
|
||||
insert_primitives(&mut scene, rectangles);
|
||||
scene
|
||||
},
|
||||
|scene| scene.finish(),
|
||||
criterion::BatchSize::LargeInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
group.finish();
|
||||
}
|
||||
|
||||
fn scene_ordering(criterion: &mut criterion::Criterion<gpui::BenchMeasurement>) {
|
||||
@@ -409,6 +438,6 @@ gpui::bench_group!(
|
||||
.warm_up_time(Duration::from_millis(500))
|
||||
.measurement_time(Duration::from_secs(1))
|
||||
.sample_size(20);
|
||||
targets = paint_rectangles, scene_ordering
|
||||
targets = paint_rectangles, scene_ordering, scene_finish
|
||||
);
|
||||
gpui::bench_main!(benches);
|
||||
|
||||
@@ -48,6 +48,7 @@ wgpu = { workspace = true, features = ["std", "metal", "gles", "vulkan", "wgsl",
|
||||
wgpu = { workspace = true, default-features = true }
|
||||
|
||||
[target.'cfg(target_family = "wasm")'.dependencies]
|
||||
js-sys.workspace = true
|
||||
web-sys = { workspace = true, features = ["HtmlCanvasElement"] }
|
||||
wgpu = { workspace = true, features = ["webgl"] }
|
||||
|
||||
|
||||
@@ -816,7 +816,10 @@ impl CosmicTextSystemState {
|
||||
|
||||
let shaped_glyph = ShapedGlyph {
|
||||
id: GlyphId(glyph.glyph_id as u32),
|
||||
position: point(glyph.x.into(), glyph.y.into()),
|
||||
position: point(
|
||||
(glyph.x + glyph.x_offset * f32::from(font_size)).into(),
|
||||
(glyph.y - glyph.y_offset * f32::from(font_size)).into(),
|
||||
),
|
||||
index: glyph.start,
|
||||
is_emoji,
|
||||
};
|
||||
@@ -1369,6 +1372,29 @@ mod tests {
|
||||
Ok(text_system.layout_line(text, gpui::px(14.0), &runs))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combining_marks_are_positioned_over_their_base() -> Result<()> {
|
||||
let text_system = text_system()?;
|
||||
let layout = layout_text(&text_system, "v\u{0304}v")?;
|
||||
let glyphs = layout
|
||||
.runs
|
||||
.iter()
|
||||
.flat_map(|run| run.glyphs.iter())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(glyphs.len(), 3);
|
||||
let base = glyphs[0].position;
|
||||
let mark = glyphs[1].position;
|
||||
let next = glyphs[2].position;
|
||||
assert!(mark.x > base.x);
|
||||
assert!(
|
||||
mark.x < next.x,
|
||||
"combining mark positioned after its base: mark.x={:?}, next.x={:?}",
|
||||
mark.x,
|
||||
next.x
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Mirrors the original crash: mixed-direction text reaching the shaper
|
||||
/// through `shape_text`, which only splits lines on `\n`.
|
||||
#[test]
|
||||
|
||||
+461
-312
File diff suppressed because it is too large
Load Diff
@@ -7,8 +7,6 @@
|
||||
|
||||
@group(1) @binding(0) var<storage, read> b_quads: array<Quad>;
|
||||
@group(1) @binding(0) var<storage, read> b_shadows: array<Shadow>;
|
||||
@group(1) @binding(0) var<storage, read> b_path_vertices: array<PathRasterizationVertex>;
|
||||
@group(1) @binding(0) var<storage, read> b_path_sprites: array<PathSprite>;
|
||||
@group(1) @binding(0) var<storage, read> b_underlines: array<Underline>;
|
||||
@group(1) @binding(0) var<storage, read> b_mono_sprites: array<MonochromeSprite>;
|
||||
@group(1) @binding(0) var<storage, read> b_poly_sprites: array<PolychromeSprite>;
|
||||
@@ -21,12 +19,20 @@ fn load_shadow(instance_id: u32) -> Shadow {
|
||||
return b_shadows[instance_id];
|
||||
}
|
||||
|
||||
fn load_path_vertex(vertex_id: u32) -> PathRasterizationVertex {
|
||||
return b_path_vertices[vertex_id];
|
||||
@group(1) @binding(0) var<storage, read> b_path_tiles: array<PathTile>;
|
||||
@group(1) @binding(1) var<storage, read> b_path_curves: array<PathCurve>;
|
||||
@group(1) @binding(2) var<storage, read> b_path_paints: array<PathPaint>;
|
||||
|
||||
fn load_path_tile(instance_id: u32) -> PathTile {
|
||||
return b_path_tiles[instance_id];
|
||||
}
|
||||
|
||||
fn load_path_sprite(instance_id: u32) -> PathSprite {
|
||||
return b_path_sprites[instance_id];
|
||||
fn load_path_curve(index: u32) -> PathCurve {
|
||||
return b_path_curves[index];
|
||||
}
|
||||
|
||||
fn load_path_paint(index: u32) -> PathPaint {
|
||||
return b_path_paints[index];
|
||||
}
|
||||
|
||||
fn load_underline(instance_id: u32) -> Underline {
|
||||
|
||||
@@ -206,19 +206,43 @@ fn load_shadow(instance_id: u32) -> Shadow {
|
||||
);
|
||||
}
|
||||
|
||||
fn load_path_vertex(vertex_id: u32) -> PathRasterizationVertex {
|
||||
var cursor = instance_cursor(vertex_id * 26u);
|
||||
return PathRasterizationVertex(
|
||||
fn load_path_tile(instance_id: u32) -> PathTile {
|
||||
var cursor = instance_cursor(instance_id * 14u);
|
||||
return PathTile(
|
||||
read_word(&cursor),
|
||||
read_word(&cursor),
|
||||
read_word(&cursor),
|
||||
read_i32(&cursor),
|
||||
read_vec2_f32(&cursor),
|
||||
read_vec2_f32(&cursor),
|
||||
read_vec2_f32(&cursor),
|
||||
read_vec2_f32(&cursor),
|
||||
read_vec2_f32(&cursor),
|
||||
read_background(&cursor),
|
||||
read_bounds(&cursor),
|
||||
);
|
||||
}
|
||||
|
||||
fn load_path_sprite(instance_id: u32) -> PathSprite {
|
||||
var cursor = instance_cursor(instance_id * 4u);
|
||||
return PathSprite(read_bounds(&cursor));
|
||||
// Tiles index this frame's paint and curve arrays, which start at the bases in `globals`.
|
||||
fn load_path_curve(index: u32) -> PathCurve {
|
||||
var cursor = instance_cursor((globals.path_curve_base + index) * 10u);
|
||||
return PathCurve(
|
||||
read_vec2_f32(&cursor),
|
||||
read_vec2_f32(&cursor),
|
||||
read_vec2_f32(&cursor),
|
||||
read_vec2_f32(&cursor),
|
||||
read_f32(&cursor),
|
||||
read_word(&cursor),
|
||||
);
|
||||
}
|
||||
|
||||
fn load_path_paint(index: u32) -> PathPaint {
|
||||
var cursor = instance_cursor((globals.path_paint_base + index) * 28u);
|
||||
return PathPaint(
|
||||
read_bounds(&cursor),
|
||||
read_bounds(&cursor),
|
||||
read_background(&cursor),
|
||||
read_word(&cursor),
|
||||
read_word(&cursor),
|
||||
);
|
||||
}
|
||||
|
||||
fn load_underline(instance_id: u32) -> Underline {
|
||||
|
||||
@@ -338,6 +338,18 @@ impl WgpuContext {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn supports_transient_attachments(&self) -> bool {
|
||||
#[cfg(target_family = "wasm")]
|
||||
if self.backend == WgpuBackend::BrowserWebGpu {
|
||||
// wgpu passes usage bits straight to the browser without knowing
|
||||
// whether it recognizes this one.
|
||||
return js_sys::Reflect::get(&js_sys::global(), &"GPUTextureUsage".into())
|
||||
.and_then(|usage| js_sys::Reflect::has(&usage, &"TRANSIENT_ATTACHMENT".into()))
|
||||
.unwrap_or(false);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub async fn new_web(
|
||||
canvas: &web_sys::HtmlCanvasElement,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -33,9 +33,9 @@ mod shader_compilation {
|
||||
// Define all modules
|
||||
let modules = [
|
||||
"quad",
|
||||
"opaque_quad",
|
||||
"shadow",
|
||||
"path_rasterization",
|
||||
"path_sprite",
|
||||
"path_tile",
|
||||
"underline",
|
||||
"monochrome_sprite",
|
||||
"subpixel_sprite",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -169,7 +169,7 @@ impl WindowsWindowInner {
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_move_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
|
||||
fn handle_move_msg(self: &Rc<Self>, handle: HWND, lparam: LPARAM) -> Option<isize> {
|
||||
let origin = logical_point(
|
||||
lparam.signed_loword() as f32,
|
||||
lparam.signed_hiword() as f32,
|
||||
@@ -944,7 +944,7 @@ impl WindowsWindowInner {
|
||||
Some(0)
|
||||
}
|
||||
|
||||
fn handle_display_change_msg(&self, handle: HWND) -> Option<isize> {
|
||||
fn handle_display_change_msg(self: &Rc<Self>, handle: HWND) -> Option<isize> {
|
||||
let new_monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
|
||||
if new_monitor.is_invalid() {
|
||||
log::error!("No monitor detected!");
|
||||
@@ -955,12 +955,20 @@ impl WindowsWindowInner {
|
||||
Some(0)
|
||||
}
|
||||
|
||||
fn set_display(&self, display: WindowsDisplay) {
|
||||
// Windows can deliver `WM_DISPLAYCHANGE` and `WM_MOVE` while GPUI is
|
||||
// updating a window (e.g. a clipboard read during a draw pumps sent
|
||||
// messages), so report the change after that update completes.
|
||||
fn set_display(self: &Rc<Self>, display: WindowsDisplay) {
|
||||
self.state.display.set(display);
|
||||
if let Some(mut callback) = self.state.callbacks.display_changed.take() {
|
||||
callback();
|
||||
self.state.callbacks.display_changed.set(Some(callback));
|
||||
}
|
||||
let this = self.clone();
|
||||
self.executor
|
||||
.spawn(async move {
|
||||
if let Some(mut callback) = this.state.callbacks.display_changed.take() {
|
||||
callback();
|
||||
this.state.callbacks.display_changed.set(Some(callback));
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn handle_hit_test_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
use crate::{BufferSnapshot, Language, Point, ToPoint, ToTreeSitterPoint};
|
||||
use fuzzy_nucleo::{Case, LengthPenalty, StringMatch, StringMatchCandidate};
|
||||
use fuzzy_nucleo::{MaxResults, StringMatch, StringMatchCandidate, StringMatchOptions};
|
||||
use gpui::{BackgroundExecutor, HighlightStyle, SharedString};
|
||||
use std::{ops::Range, sync::Arc};
|
||||
use theme::SyntaxTheme;
|
||||
@@ -215,10 +215,10 @@ impl<T> Outline<T> {
|
||||
let mut matches = fuzzy_nucleo::match_strings_async(
|
||||
&self.candidates,
|
||||
query,
|
||||
Case::Smart,
|
||||
LengthPenalty::On,
|
||||
100,
|
||||
&Default::default(),
|
||||
StringMatchOptions {
|
||||
max_results: MaxResults::limit::<100>(),
|
||||
..Default::default()
|
||||
},
|
||||
executor,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -468,6 +468,7 @@ pub trait LanguageModelClient: 'static {
|
||||
Ok(LanguageModelCompletionEvent::Thinking { .. }) => None,
|
||||
Ok(LanguageModelCompletionEvent::RedactedThinking { .. }) => None,
|
||||
Ok(LanguageModelCompletionEvent::ReasoningDetails(_)) => None,
|
||||
Ok(LanguageModelCompletionEvent::InputTransformations(_)) => None,
|
||||
Ok(LanguageModelCompletionEvent::Stop(_)) => None,
|
||||
Ok(LanguageModelCompletionEvent::ToolUse(_)) => None,
|
||||
Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
|
||||
|
||||
@@ -66,6 +66,20 @@ pub enum LanguageModelCompletionEvent {
|
||||
ReasoningDetails(serde_json::Value),
|
||||
UsageUpdate(TokenUsage),
|
||||
Compaction(CompactionUpdate),
|
||||
/// Transformations the provider applied or flagged while processing the request.
|
||||
InputTransformations(Vec<InputTransformation>),
|
||||
}
|
||||
|
||||
/// A provider-reported transformation or mismatch affecting request content.
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
|
||||
pub struct InputTransformation {
|
||||
/// Provider-specific transformation type, including unrecognized future types.
|
||||
#[serde(rename = "type")]
|
||||
pub kind: String,
|
||||
/// Provider-specific location, such as `messages.1.content.0`.
|
||||
pub path: String,
|
||||
/// Provider-specific reason, such as `prefix_binding_mismatch`.
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
|
||||
|
||||
@@ -133,7 +133,7 @@ impl State {
|
||||
log::warn!("failed to load llama.cpp API key: {error}");
|
||||
}
|
||||
}
|
||||
let fetch_models_task = this.update(cx, |this, cx| this.fetch_models(cx))?;
|
||||
let fetch_models_task = this.update(cx, |this, cx| this.start_fetch_models(cx))?;
|
||||
match fetch_models_task.await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) => {
|
||||
@@ -267,6 +267,12 @@ impl State {
|
||||
|
||||
self.model_event_task = Some(cx.spawn(async move |this, cx| {
|
||||
loop {
|
||||
if this
|
||||
.update(cx, |_, cx| crate::ai_disabled(cx))
|
||||
.unwrap_or(true)
|
||||
{
|
||||
return;
|
||||
}
|
||||
match stream_model_events(
|
||||
http_client.as_ref(),
|
||||
&api_url,
|
||||
@@ -327,15 +333,19 @@ impl State {
|
||||
cx.background_executor()
|
||||
.timer(MODEL_EVENT_RECONNECT_INTERVAL)
|
||||
.await;
|
||||
if this.update(cx, |_, _| ()).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
fn restart_fetch_models_task(&mut self, cx: &mut Context<Self>) {
|
||||
fn start_fetch_models(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
|
||||
if crate::ai_disabled(cx) {
|
||||
self.fetch_model_task = None;
|
||||
self.model_event_task = None;
|
||||
return Task::ready(Ok(()));
|
||||
}
|
||||
|
||||
let fetch_task = self.fetch_models(cx);
|
||||
let (result_tx, result_rx) = futures::channel::oneshot::channel();
|
||||
let task = cx.spawn(async move |this, cx| {
|
||||
let result = fetch_task.await;
|
||||
this.update(cx, |this, _cx| {
|
||||
@@ -343,9 +353,19 @@ impl State {
|
||||
result.as_ref().err().map(|error| format!("{error:#}"));
|
||||
})
|
||||
.ok();
|
||||
result.log_err();
|
||||
if let Err(result) = result_tx.send(result) {
|
||||
result.log_err();
|
||||
}
|
||||
});
|
||||
self.fetch_model_task.replace(task);
|
||||
|
||||
cx.spawn(async move |_this, _cx| result_rx.await.unwrap_or(Ok(())))
|
||||
}
|
||||
|
||||
fn restart_fetch_models_task(&mut self, cx: &mut Context<Self>) {
|
||||
let result = self.start_fetch_models(cx);
|
||||
cx.spawn(async move |_this, _cx| result.await.log_err())
|
||||
.detach();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,6 +496,7 @@ impl LlamaCppLanguageModelProvider {
|
||||
state: cx.new(|cx| {
|
||||
cx.observe_global::<SettingsStore>({
|
||||
let mut last_settings = LlamaCppLanguageModelProvider::settings(cx).clone();
|
||||
let mut last_disable_ai = crate::ai_disabled(cx);
|
||||
move |this: &mut State, cx| {
|
||||
let current_settings = LlamaCppLanguageModelProvider::settings(cx);
|
||||
let settings_changed = current_settings != &last_settings;
|
||||
@@ -500,6 +521,11 @@ impl LlamaCppLanguageModelProvider {
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
let disable_ai = crate::ai_disabled(cx);
|
||||
if disable_ai != last_disable_ai {
|
||||
last_disable_ai = disable_ai;
|
||||
this.restart_fetch_models_task(cx);
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
@@ -1924,6 +1950,242 @@ mod tests {
|
||||
assert!(pending_credentials.is_canceled());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn does_not_fetch_models_when_ai_is_disabled(cx: &mut TestAppContext) {
|
||||
cx.update(|cx| {
|
||||
let mut store = SettingsStore::test(cx);
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(true.into());
|
||||
});
|
||||
cx.set_global(store);
|
||||
});
|
||||
|
||||
let request_count = Arc::new(AtomicUsize::new(0));
|
||||
let (release_first_fetch, first_fetch_released) = futures::channel::oneshot::channel();
|
||||
let first_fetch_released = Arc::new(Mutex::new(Some(first_fetch_released)));
|
||||
let http_client = FakeHttpClient::create({
|
||||
let request_count = request_count.clone();
|
||||
move |request| {
|
||||
request_count.fetch_add(1, Ordering::SeqCst);
|
||||
let first_fetch_released = first_fetch_released.clone();
|
||||
async move {
|
||||
let first_fetch_released = first_fetch_released.lock().take();
|
||||
if let Some(first_fetch_released) = first_fetch_released {
|
||||
first_fetch_released.await.ok();
|
||||
}
|
||||
let (status, body) = match request.uri().path() {
|
||||
"/v1/models" => (200, r#"{"data":[{"id":"test-model"}]}"#),
|
||||
"/props" => (200, "{}"),
|
||||
path => anyhow::bail!("unexpected request: {path}"),
|
||||
};
|
||||
Ok(http_client::Response::builder()
|
||||
.status(status)
|
||||
.body(http_client::AsyncBody::from(body))?)
|
||||
}
|
||||
}
|
||||
});
|
||||
let provider = cx.update(|cx| {
|
||||
LlamaCppLanguageModelProvider::new(
|
||||
http_client,
|
||||
Arc::new(FakeCredentialsProvider::default()),
|
||||
cx,
|
||||
)
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 0);
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(false.into());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 1);
|
||||
assert!(cx.update(|cx| provider.provided_models(cx)).is_empty());
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(true.into());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
release_first_fetch.send(()).ok();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 1);
|
||||
assert!(cx.update(|cx| provider.provided_models(cx)).is_empty());
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(false.into());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 3);
|
||||
assert_eq!(
|
||||
cx.update(|cx| provider
|
||||
.provided_models(cx)
|
||||
.into_iter()
|
||||
.map(|model| model.id.0.to_string())
|
||||
.collect::<Vec<_>>()),
|
||||
["test-model"]
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn disables_model_event_stream_when_ai_is_disabled(cx: &mut TestAppContext) {
|
||||
cx.update(|cx| {
|
||||
let store = SettingsStore::test(cx);
|
||||
cx.set_global(store);
|
||||
});
|
||||
|
||||
let model_event_request_count = Arc::new(AtomicUsize::new(0));
|
||||
let (release_event_stream, event_stream_released) = futures::channel::oneshot::channel();
|
||||
let event_stream_released = Arc::new(Mutex::new(Some(event_stream_released)));
|
||||
let http_client = FakeHttpClient::create({
|
||||
let model_event_request_count = model_event_request_count.clone();
|
||||
move |request| {
|
||||
let model_event_request_count = model_event_request_count.clone();
|
||||
let event_stream_released = event_stream_released.clone();
|
||||
async move {
|
||||
if request.uri().path() == "/models/sse" {
|
||||
model_event_request_count.fetch_add(1, Ordering::SeqCst);
|
||||
let event_stream_released = event_stream_released.lock().take();
|
||||
if let Some(event_stream_released) = event_stream_released {
|
||||
event_stream_released.await.ok();
|
||||
}
|
||||
}
|
||||
let (status, body) = match request.uri().path() {
|
||||
"/v1/models" => (
|
||||
200,
|
||||
r#"{"data":[{"id":"test-model","status":{"value":"loaded"}}]}"#,
|
||||
),
|
||||
"/props" => (200, "{}"),
|
||||
"/models/sse" => (200, ""),
|
||||
path => anyhow::bail!("unexpected request: {path}"),
|
||||
};
|
||||
Ok(http_client::Response::builder()
|
||||
.status(status)
|
||||
.body(http_client::AsyncBody::from(body))?)
|
||||
}
|
||||
}
|
||||
});
|
||||
let provider = cx.update(|cx| {
|
||||
LlamaCppLanguageModelProvider::new(
|
||||
http_client,
|
||||
Arc::new(FakeCredentialsProvider::default()),
|
||||
cx,
|
||||
)
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert_eq!(
|
||||
cx.update(|cx| provider
|
||||
.provided_models(cx)
|
||||
.into_iter()
|
||||
.map(|model| model.id.0.to_string())
|
||||
.collect::<Vec<_>>()),
|
||||
["test-model"]
|
||||
);
|
||||
assert_eq!(model_event_request_count.load(Ordering::SeqCst), 1);
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(true.into());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
release_event_stream.send(()).ok();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(model_event_request_count.load(Ordering::SeqCst), 1);
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(false.into());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert_eq!(model_event_request_count.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn authenticate_does_not_fetch_models_when_ai_is_disabled(cx: &mut TestAppContext) {
|
||||
cx.update(|cx| {
|
||||
let mut store = SettingsStore::test(cx);
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(true.into());
|
||||
});
|
||||
cx.set_global(store);
|
||||
});
|
||||
|
||||
let request_count = Arc::new(AtomicUsize::new(0));
|
||||
let (release_fetch, fetch_released) = futures::channel::oneshot::channel();
|
||||
let fetch_released = Arc::new(Mutex::new(Some(fetch_released)));
|
||||
let http_client = FakeHttpClient::create({
|
||||
let request_count = request_count.clone();
|
||||
move |request| {
|
||||
request_count.fetch_add(1, Ordering::SeqCst);
|
||||
let fetch_released = fetch_released.clone();
|
||||
async move {
|
||||
let fetch_released = fetch_released.lock().take();
|
||||
if let Some(fetch_released) = fetch_released {
|
||||
fetch_released.await.ok();
|
||||
}
|
||||
let (status, body) = match request.uri().path() {
|
||||
"/v1/models" => (200, r#"{"data":[{"id":"test-model"}]}"#),
|
||||
"/props" => (200, "{}"),
|
||||
path => anyhow::bail!("unexpected request: {path}"),
|
||||
};
|
||||
Ok(http_client::Response::builder()
|
||||
.status(status)
|
||||
.body(http_client::AsyncBody::from(body))?)
|
||||
}
|
||||
}
|
||||
});
|
||||
let credentials_provider = Arc::new(FakeCredentialsProvider::default());
|
||||
credentials_provider
|
||||
.state
|
||||
.lock()
|
||||
.keys
|
||||
.insert(LLAMA_CPP_API_URL.to_string(), b"loaded-key".to_vec());
|
||||
let provider = cx
|
||||
.update(|cx| LlamaCppLanguageModelProvider::new(http_client, credentials_provider, cx));
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 0);
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings
|
||||
.language_models
|
||||
.get_or_insert_default()
|
||||
.llama_cpp
|
||||
.get_or_insert_default()
|
||||
.api_url = Some("http://localhost:9999".to_string());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
cx.update(|cx| provider.authenticate(cx)).await.ok();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 0);
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(false.into());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 1);
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(true.into());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
release_fetch.send(()).ok();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 1);
|
||||
assert!(cx.update(|cx| provider.provided_models(cx)).is_empty());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn authenticate_fetches_models_after_loading_api_key(cx: &mut TestAppContext) {
|
||||
cx.update(|cx| {
|
||||
|
||||
@@ -123,8 +123,14 @@ impl State {
|
||||
})
|
||||
}
|
||||
|
||||
fn restart_fetch_models_task(&mut self, cx: &mut Context<Self>) {
|
||||
fn start_fetch_models(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
|
||||
if crate::ai_disabled(cx) {
|
||||
self.fetch_model_task = None;
|
||||
return Task::ready(Ok(()));
|
||||
}
|
||||
|
||||
let fetch_task = self.fetch_models(cx);
|
||||
let (result_tx, result_rx) = futures::channel::oneshot::channel();
|
||||
let task = cx.spawn(async move |this, cx| {
|
||||
let result = fetch_task.await;
|
||||
this.update(cx, |this, _cx| {
|
||||
@@ -132,9 +138,19 @@ impl State {
|
||||
result.as_ref().err().map(|error| format!("{error:#}"));
|
||||
})
|
||||
.ok();
|
||||
result.log_err();
|
||||
if let Err(result) = result_tx.send(result) {
|
||||
result.log_err();
|
||||
}
|
||||
});
|
||||
self.fetch_model_task.replace(task);
|
||||
|
||||
cx.spawn(async move |_this, _cx| result_rx.await.unwrap_or(Ok(())))
|
||||
}
|
||||
|
||||
fn restart_fetch_models_task(&mut self, cx: &mut Context<Self>) {
|
||||
let result = self.start_fetch_models(cx);
|
||||
cx.spawn(async move |_this, _cx| result.await.log_err())
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
|
||||
@@ -153,7 +169,7 @@ impl State {
|
||||
|
||||
cx.spawn(async move |state, cx| {
|
||||
load_key.await?;
|
||||
let fetch_models_task = state.update(cx, |state, cx| state.fetch_models(cx))?;
|
||||
let fetch_models_task = state.update(cx, |state, cx| state.start_fetch_models(cx))?;
|
||||
match fetch_models_task.await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) => {
|
||||
@@ -191,6 +207,7 @@ impl LmStudioLanguageModelProvider {
|
||||
state: cx.new(|cx| {
|
||||
let subscription = cx.observe_global::<SettingsStore>({
|
||||
let mut settings = AllLanguageModelSettings::get_global(cx).lmstudio.clone();
|
||||
let mut old_disable_ai = crate::ai_disabled(cx);
|
||||
move |this: &mut State, cx| {
|
||||
let new_settings =
|
||||
AllLanguageModelSettings::get_global(cx).lmstudio.clone();
|
||||
@@ -207,6 +224,11 @@ impl LmStudioLanguageModelProvider {
|
||||
this.restart_fetch_models_task(cx);
|
||||
cx.notify();
|
||||
}
|
||||
let new_disable_ai = crate::ai_disabled(cx);
|
||||
if new_disable_ai != old_disable_ai {
|
||||
old_disable_ai = new_disable_ai;
|
||||
this.restart_fetch_models_task(cx);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -920,6 +942,8 @@ mod tests {
|
||||
use credentials_provider::test_support::FakeCredentialsProvider;
|
||||
use gpui::TestAppContext;
|
||||
use http_client::{AsyncBody, FakeHttpClient, Response};
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
#[gpui::test]
|
||||
async fn enabling_ai_discovers_models_with_stored_credentials(cx: &mut TestAppContext) {
|
||||
@@ -985,6 +1009,146 @@ mod tests {
|
||||
credentials.assert_reads(&[LMSTUDIO_API_URL]);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn authenticate_does_not_fetch_models_when_ai_is_disabled(cx: &mut TestAppContext) {
|
||||
cx.update(|cx| {
|
||||
let mut store = SettingsStore::test(cx);
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(true.into());
|
||||
});
|
||||
cx.set_global(store);
|
||||
});
|
||||
|
||||
let request_count = Arc::new(AtomicUsize::new(0));
|
||||
let (release_fetch, fetch_released) = futures::channel::oneshot::channel();
|
||||
let fetch_released = Arc::new(Mutex::new(Some(fetch_released)));
|
||||
let http_client = FakeHttpClient::create({
|
||||
let request_count = request_count.clone();
|
||||
move |_request| {
|
||||
request_count.fetch_add(1, Ordering::SeqCst);
|
||||
let fetch_released = fetch_released.clone();
|
||||
async move {
|
||||
let fetch_released = fetch_released.lock().take();
|
||||
if let Some(fetch_released) = fetch_released {
|
||||
fetch_released.await.ok();
|
||||
}
|
||||
Ok(Response::builder().status(200).body(AsyncBody::from(
|
||||
r#"{"data":[{"id":"test-model","object":"model","type":"llm","publisher":"test","compatibility_type":"gguf","state":"loaded"}]}"#,
|
||||
))?)
|
||||
}
|
||||
}
|
||||
});
|
||||
let credentials_provider = Arc::new(FakeCredentialsProvider::default());
|
||||
credentials_provider
|
||||
.state
|
||||
.lock()
|
||||
.keys
|
||||
.insert(LMSTUDIO_API_URL.to_string(), b"stored-key".to_vec());
|
||||
let provider = cx
|
||||
.update(|cx| LmStudioLanguageModelProvider::new(http_client, credentials_provider, cx));
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 0);
|
||||
|
||||
cx.update(|cx| provider.authenticate(cx)).await.ok();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 0);
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(false.into());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 1);
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(true.into());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
release_fetch.send(()).ok();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 1);
|
||||
assert!(cx.update(|cx| provider.provided_models(cx)).is_empty());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn does_not_fetch_models_when_ai_is_disabled(cx: &mut TestAppContext) {
|
||||
cx.update(|cx| {
|
||||
let mut store = SettingsStore::test(cx);
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(true.into());
|
||||
});
|
||||
cx.set_global(store);
|
||||
});
|
||||
|
||||
let request_count = Arc::new(AtomicUsize::new(0));
|
||||
let (release_first_fetch, first_fetch_released) = futures::channel::oneshot::channel();
|
||||
let first_fetch_released = Arc::new(Mutex::new(Some(first_fetch_released)));
|
||||
let http_client = FakeHttpClient::create({
|
||||
let request_count = request_count.clone();
|
||||
move |_request| {
|
||||
request_count.fetch_add(1, Ordering::SeqCst);
|
||||
let first_fetch_released = first_fetch_released.clone();
|
||||
async move {
|
||||
let first_fetch_released = first_fetch_released.lock().take();
|
||||
if let Some(first_fetch_released) = first_fetch_released {
|
||||
first_fetch_released.await.ok();
|
||||
}
|
||||
Ok(Response::builder().status(200).body(AsyncBody::from(
|
||||
r#"{"data":[{"id":"test-model","object":"model","type":"llm","publisher":"test","compatibility_type":"gguf","state":"loaded"}]}"#,
|
||||
))?)
|
||||
}
|
||||
}
|
||||
});
|
||||
let provider = cx.update(|cx| {
|
||||
LmStudioLanguageModelProvider::new(
|
||||
http_client,
|
||||
Arc::new(FakeCredentialsProvider::default()),
|
||||
cx,
|
||||
)
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 0);
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(false.into());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 1);
|
||||
assert!(cx.update(|cx| provider.provided_models(cx)).is_empty());
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(true.into());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
release_first_fetch.send(()).ok();
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 1);
|
||||
assert!(cx.update(|cx| provider.provided_models(cx)).is_empty());
|
||||
|
||||
cx.update_global::<SettingsStore, _>(|store, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings.project.disable_ai = Some(false.into());
|
||||
});
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert_eq!(request_count.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(
|
||||
cx.update(|cx| provider
|
||||
.provided_models(cx)
|
||||
.into_iter()
|
||||
.map(|model| model.id.0.to_string())
|
||||
.collect::<Vec<_>>()),
|
||||
["test-model"]
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn restart_fetch_models_task_records_error_on_failure(cx: &mut TestAppContext) {
|
||||
cx.update(|cx| {
|
||||
|
||||
@@ -464,7 +464,8 @@ pub fn into_open_router(
|
||||
// we need this distinction, we're just using this less invasive check instead.
|
||||
// If we ever have a more formal distionction between the models in the future,
|
||||
// we should revise this to use that instead.
|
||||
let is_anthropic_model = model.id().starts_with("anthropic/");
|
||||
// OpenRouter aliases are prefixed with `~` (e.g. `~anthropic/claude-sonnet-latest`).
|
||||
let is_anthropic_model = model.id().trim_start_matches('~').starts_with("anthropic/");
|
||||
let session_id = open_router_session_id(request.thread_id);
|
||||
|
||||
let mut messages = Vec::new();
|
||||
@@ -1111,6 +1112,83 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_anthropic_alias_model_uses_anthropic_request_handling() {
|
||||
let model = open_router::Model::new(
|
||||
"~anthropic/claude-sonnet-latest",
|
||||
None,
|
||||
Some(200000),
|
||||
Some(true),
|
||||
Some(false),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
None,
|
||||
);
|
||||
|
||||
let request = LanguageModelRequest {
|
||||
messages: vec![
|
||||
language_model::LanguageModelRequestMessage {
|
||||
role: Role::System,
|
||||
content: vec![MessageContent::Text("You are helpful.".to_string())],
|
||||
cache: false,
|
||||
reasoning_details: None,
|
||||
},
|
||||
language_model::LanguageModelRequestMessage {
|
||||
role: Role::Assistant,
|
||||
content: vec![MessageContent::Text("Hi there!".to_string())],
|
||||
cache: false,
|
||||
reasoning_details: Some(Arc::new(serde_json::json!([{
|
||||
"type": "reasoning.text"
|
||||
}]))),
|
||||
},
|
||||
language_model::LanguageModelRequestMessage {
|
||||
role: Role::User,
|
||||
content: vec![MessageContent::Text("What is 2+2?".to_string())],
|
||||
cache: true,
|
||||
reasoning_details: None,
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let result = into_open_router(request, &model, None).unwrap();
|
||||
|
||||
let has_cache_control = result.messages.iter().any(|message| match message {
|
||||
open_router::RequestMessage::System {
|
||||
content: open_router::MessageContent::Multipart(parts),
|
||||
}
|
||||
| open_router::RequestMessage::User {
|
||||
content: open_router::MessageContent::Multipart(parts),
|
||||
} => parts.iter().any(|part| {
|
||||
matches!(
|
||||
part,
|
||||
open_router::MessagePart::Text {
|
||||
cache_control: Some(_),
|
||||
..
|
||||
}
|
||||
)
|
||||
}),
|
||||
_ => false,
|
||||
});
|
||||
assert!(has_cache_control, "Alias should get cache_control");
|
||||
|
||||
let echoes_reasoning_details = result.messages.iter().any(|message| {
|
||||
matches!(
|
||||
message,
|
||||
open_router::RequestMessage::Assistant {
|
||||
reasoning_details: Some(_),
|
||||
..
|
||||
}
|
||||
)
|
||||
});
|
||||
assert!(
|
||||
!echoes_reasoning_details,
|
||||
"Alias should not echo reasoning_details back"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_into_open_router_sends_requested_effort() {
|
||||
let model = open_router::Model::new(
|
||||
|
||||
@@ -8189,37 +8189,43 @@ mod tests {
|
||||
});
|
||||
cx.run_until_parked();
|
||||
cx.update(|window, cx| {
|
||||
// Quads are drawn in this order: by draw order, then in paint
|
||||
// order. At an equal draw order, quads are drawn before underlines.
|
||||
let quads = window.painted_quads();
|
||||
let selection_bounds = quads
|
||||
.iter()
|
||||
.find(|quad| quad.background == Background::from(gpui::red()))
|
||||
.expect("selection is painted")
|
||||
.bounds;
|
||||
let order_for_color = |color| {
|
||||
let orders = quads
|
||||
// A quad can be painted as several pieces.
|
||||
let positions_for_color = |color| {
|
||||
let positions = quads
|
||||
.iter()
|
||||
.filter(|quad| {
|
||||
.enumerate()
|
||||
.filter(|(_, quad)| {
|
||||
quad.background == Background::from(color)
|
||||
&& quad.bounds.intersects(&selection_bounds)
|
||||
})
|
||||
.map(|quad| quad.order)
|
||||
.map(|(position, _)| position)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(orders.len(), 1);
|
||||
orders[0]
|
||||
let first = *positions.first().expect("quad is painted");
|
||||
let last = *positions.last().expect("quad is painted");
|
||||
first..=last
|
||||
};
|
||||
let chip_order = order_for_color(gpui::green());
|
||||
let search_order = order_for_color(cx.theme().colors().search_match_background);
|
||||
let selection_order = order_for_color(gpui::red());
|
||||
let chip = positions_for_color(gpui::green());
|
||||
let search = positions_for_color(cx.theme().colors().search_match_background);
|
||||
let selection = positions_for_color(gpui::red());
|
||||
let selection_order = quads[*selection.end()].order;
|
||||
let text_order = window
|
||||
.painted_underlines()
|
||||
.iter()
|
||||
.map(|underline| underline.order)
|
||||
.min()
|
||||
.expect("strikethrough is painted");
|
||||
assert!(chip_order < search_order);
|
||||
assert!(search_order < selection_order);
|
||||
assert!(chip.end() < search.start());
|
||||
assert!(search.end() < selection.start());
|
||||
assert!(
|
||||
selection_order < text_order,
|
||||
selection_order <= text_order,
|
||||
"alignment={alignment}, text={text}, selection={selection_order}, glyphs={text_order}",
|
||||
);
|
||||
});
|
||||
@@ -8259,17 +8265,22 @@ mod tests {
|
||||
|
||||
let highlight_color = cx.update(|_, cx| cx.theme().colors().search_match_background);
|
||||
cx.update(|window, _| {
|
||||
// Quads are drawn in this order: by draw order, then in paint order.
|
||||
// At an equal draw order, quads are drawn before underlines.
|
||||
let quads = window.painted_quads();
|
||||
let order_of_quad_with = |color: Hsla| {
|
||||
quads
|
||||
.iter()
|
||||
.find(|quad| quad.background == color.into())
|
||||
.map(|quad| quad.order)
|
||||
};
|
||||
let run_background_order =
|
||||
order_of_quad_with(run_background_color).expect("link background should be painted");
|
||||
let highlight_order =
|
||||
order_of_quad_with(highlight_color).expect("search highlight should be painted");
|
||||
let has_color = |color: Hsla| move |quad: &gpui::Quad| quad.background == color.into();
|
||||
let last_run_background = quads
|
||||
.iter()
|
||||
.rposition(has_color(run_background_color))
|
||||
.expect("link background should be painted");
|
||||
let first_highlight = quads
|
||||
.iter()
|
||||
.position(has_color(highlight_color))
|
||||
.expect("search highlight should be painted");
|
||||
let last_highlight = quads
|
||||
.iter()
|
||||
.rposition(has_color(highlight_color))
|
||||
.expect("search highlight should be painted");
|
||||
// Strikethroughs are painted in the same layer as the glyphs
|
||||
let text_order = window
|
||||
.painted_underlines()
|
||||
@@ -8278,11 +8289,11 @@ mod tests {
|
||||
.min()
|
||||
.expect("strikethrough should be painted");
|
||||
assert!(
|
||||
run_background_order < highlight_order,
|
||||
last_run_background < first_highlight,
|
||||
"text run backgrounds must not cover search highlights"
|
||||
);
|
||||
assert!(
|
||||
highlight_order < text_order,
|
||||
quads[last_highlight].order <= text_order,
|
||||
"search highlight must be drawn below the text, otherwise opaque theme colors hide it"
|
||||
);
|
||||
});
|
||||
|
||||
@@ -224,8 +224,11 @@ impl CachedMermaidDiagram {
|
||||
async move |this, cx| {
|
||||
let value = cx
|
||||
.background_spawn(async move {
|
||||
let svg_string =
|
||||
mermaid_render::render_to_svg(&contents.contents, &mermaid_theme)?;
|
||||
let svg_string = mermaid_render::render_to_svg(
|
||||
&contents.contents,
|
||||
&mermaid_theme,
|
||||
&svg_renderer,
|
||||
)?;
|
||||
let tree = svg_renderer
|
||||
.parse_svg(svg_string.as_bytes())
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||
@@ -344,27 +347,6 @@ impl CachedMermaidDiagram {
|
||||
}
|
||||
}
|
||||
|
||||
/// Merman has somewhat limited text measurement capabilities.
|
||||
///
|
||||
/// When it doesn't have metrics for any of the specified fonts, it chooses a
|
||||
/// fairly narrow width, which causes visible overflow. Adding `sans-serif`
|
||||
/// allows it to fall back to a more conservative (i.e. wider) measurement.
|
||||
///
|
||||
/// This isn't perfect - very wide fonts will likely still cause overflow. A
|
||||
/// proper fix would involve somehow piping `resvg`'s actual measurements into
|
||||
/// `merman`, but that is a lot of work for a fairly uncommon edge case.
|
||||
fn mermaid_font_family(font_family: &str) -> String {
|
||||
let font_family = gpui::font_name_with_fallbacks(font_family, "system-ui");
|
||||
if font_family
|
||||
.split(',')
|
||||
.any(|family| family.trim().eq_ignore_ascii_case("sans-serif"))
|
||||
{
|
||||
font_family.to_string()
|
||||
} else {
|
||||
format!("{font_family}, sans-serif")
|
||||
}
|
||||
}
|
||||
|
||||
fn build_mermaid_theme(cx: &Context<Markdown>) -> mermaid_render::MermaidTheme {
|
||||
let colors = cx.theme().colors();
|
||||
let theme_settings = ThemeSettings::get_global(cx);
|
||||
@@ -376,7 +358,11 @@ fn build_mermaid_theme(cx: &Context<Markdown>) -> mermaid_render::MermaidTheme {
|
||||
|
||||
mermaid_render::MermaidTheme {
|
||||
dark_mode: is_dark,
|
||||
font_family: mermaid_font_family(theme_settings.mermaid_font_family().as_ref()),
|
||||
font_family: gpui::font_name_with_fallbacks(
|
||||
theme_settings.mermaid_font_family().as_ref(),
|
||||
"system-ui",
|
||||
)
|
||||
.to_string(),
|
||||
background: colors.editor_background,
|
||||
primary_color: colors.surface_background,
|
||||
primary_text_color: colors.text,
|
||||
@@ -1117,31 +1103,6 @@ mod tests {
|
||||
.map(|(image, _)| image)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mermaid_font_family_resolves_zed_virtual_fonts() {
|
||||
assert_eq!(
|
||||
super::mermaid_font_family(".ZedSans"),
|
||||
"IBM Plex Sans, sans-serif"
|
||||
);
|
||||
assert_eq!(
|
||||
super::mermaid_font_family("Zed Plex Sans"),
|
||||
"IBM Plex Sans, sans-serif"
|
||||
);
|
||||
assert_eq!(super::mermaid_font_family(".ZedMono"), "Lilex, sans-serif");
|
||||
assert_eq!(
|
||||
super::mermaid_font_family(".SystemUIFont"),
|
||||
"system-ui, sans-serif"
|
||||
);
|
||||
assert_eq!(
|
||||
super::mermaid_font_family("Custom Font"),
|
||||
"Custom Font, sans-serif"
|
||||
);
|
||||
assert_eq!(
|
||||
super::mermaid_font_family("Custom Font, sans-serif"),
|
||||
"Custom Font, sans-serif"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_mermaid_info() {
|
||||
assert_eq!(parse_mermaid_info("mermaid"), Some(100));
|
||||
|
||||
@@ -19,6 +19,19 @@ test-support = []
|
||||
anyhow.workspace = true
|
||||
gpui.workspace = true
|
||||
merman = { workspace = true, features = [
|
||||
"diagram-class",
|
||||
"diagram-er",
|
||||
"diagram-flowchart",
|
||||
"diagram-gantt",
|
||||
"diagram-git-graph",
|
||||
"diagram-journey",
|
||||
"diagram-mindmap",
|
||||
"diagram-pie",
|
||||
"diagram-quadrant-chart",
|
||||
"diagram-sequence",
|
||||
"diagram-state",
|
||||
"diagram-timeline",
|
||||
"diagram-xychart",
|
||||
"layout-cytoscape",
|
||||
"svg",
|
||||
] }
|
||||
@@ -28,6 +41,7 @@ tracing.workspace = true
|
||||
ztracing.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
assets.workspace = true
|
||||
gpui = { workspace = true, features = ["test-support"] }
|
||||
mermaid_render = { workspace = true, features = ["test-support"] }
|
||||
usvg.workspace = true
|
||||
|
||||
@@ -23,8 +23,7 @@
|
||||
//! `<foreignObject>` and CSS/attribute forms that rasterizers do not handle.
|
||||
//! Since merman 0.6, that generic cleanup is exposed as merman's raster-safe SVG
|
||||
//! pipeline. Zed opts into that pipeline during rendering, then keeps
|
||||
//! editor-specific theme and accent color rules in this crate. The [`gpui`]
|
||||
//! dependency is only needed for the [`Hsla`] and [`Rgba`] color types.
|
||||
//! editor-specific theme and accent color rules in this crate.
|
||||
//!
|
||||
//! The [`render_to_svg`] function operates in two stages:
|
||||
//! - [`render`] the mermaid text to raster-safe SVG using [`merman`].
|
||||
@@ -67,7 +66,7 @@ mod postprocess;
|
||||
mod render;
|
||||
|
||||
use anyhow::Result;
|
||||
use gpui::{Hsla, Rgba};
|
||||
use gpui::{Hsla, Rgba, SvgRenderer};
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct AccentColor {
|
||||
@@ -176,8 +175,12 @@ pub use postprocess::util::text_color_for_background;
|
||||
|
||||
/// See the [module-level docs][crate] for more info.
|
||||
#[ztracing::instrument(skip_all)]
|
||||
pub fn render_to_svg(source: &str, theme: &MermaidTheme) -> Result<String> {
|
||||
let svg = render::render_mermaid(source, theme)?;
|
||||
pub fn render_to_svg(
|
||||
source: &str,
|
||||
theme: &MermaidTheme,
|
||||
svg_renderer: &SvgRenderer,
|
||||
) -> Result<String> {
|
||||
let svg = render::render_mermaid(source, theme, svg_renderer)?;
|
||||
let svg = postprocess::postprocess(&svg, theme)?;
|
||||
Ok(svg)
|
||||
}
|
||||
@@ -195,7 +198,7 @@ mod tests {
|
||||
|
||||
let zalgo = "Ne\u{0301}\u{0302}\u{0303}\u{0304}\u{0306}\u{0307}\u{0308}\u{030a}d";
|
||||
let source = format!("flowchart TD\n A[\"**{zalgo}** {zalgo}\"]");
|
||||
let svg = render_to_svg(&source, &MermaidTheme::default())
|
||||
let svg = render_to_svg(&source, &MermaidTheme::default(), &svg_renderer())
|
||||
.expect("mermaid diagram should render to SVG");
|
||||
|
||||
let mut db = usvg::fontdb::Database::new();
|
||||
@@ -217,7 +220,7 @@ mod tests {
|
||||
#[test]
|
||||
fn er_multibyte_attribute_does_not_crash() {
|
||||
let source = "erDiagram\n顧客 {\n 文字列 名前\n}";
|
||||
let _ = render_to_svg(source, &MermaidTheme::default());
|
||||
let _ = render_to_svg(source, &MermaidTheme::default(), &svg_renderer());
|
||||
}
|
||||
|
||||
/// A flowchart with mutually nested subgraphs (`A` contains `B` and `B`
|
||||
@@ -226,7 +229,7 @@ mod tests {
|
||||
#[test]
|
||||
fn cyclic_subgraphs_do_not_crash() {
|
||||
let source = "flowchart TD\n subgraph A\n B\n end\n subgraph B\n A\n end";
|
||||
let result = render_to_svg(source, &MermaidTheme::default());
|
||||
let result = render_to_svg(source, &MermaidTheme::default(), &svg_renderer());
|
||||
if let Err(err) = result {
|
||||
let message = format!("{err:#}");
|
||||
assert!(
|
||||
@@ -235,4 +238,8 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn svg_renderer() -> SvgRenderer {
|
||||
SvgRenderer::new(std::sync::Arc::new(()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,7 +231,7 @@ fn detect_diagram_type(e: &BytesStart<'_>) -> DiagramType {
|
||||
for token in class.split_whitespace() {
|
||||
match token {
|
||||
"flowchart" => return DiagramType::Flowchart,
|
||||
"mindmap" => return DiagramType::Mindmap,
|
||||
"mindmap" | "mindmapDiagram" => return DiagramType::Mindmap,
|
||||
"classDiagram" => return DiagramType::ClassDiagram,
|
||||
"statediagram" => return DiagramType::StateDiagram,
|
||||
"journey" => return DiagramType::Unhandled,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::Result;
|
||||
use quick_xml::XmlVersion;
|
||||
use quick_xml::events::Event;
|
||||
@@ -13,6 +15,8 @@ pub(crate) struct ClassDiagramAccents {
|
||||
node_counter: usize,
|
||||
nodes: NodeTracker,
|
||||
current_text_accent: Option<usize>,
|
||||
label_accents: HashMap<String, Option<usize>>,
|
||||
label_definition_depth: Option<usize>,
|
||||
}
|
||||
|
||||
impl ClassDiagramAccents {
|
||||
@@ -23,6 +27,8 @@ impl ClassDiagramAccents {
|
||||
node_counter: 0,
|
||||
nodes: NodeTracker::default(),
|
||||
current_text_accent: None,
|
||||
label_accents: HashMap::new(),
|
||||
label_definition_depth: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +44,21 @@ impl ClassDiagramAccents {
|
||||
return Ok(event);
|
||||
}
|
||||
|
||||
let label_accent = match e.try_get_attribute("id")? {
|
||||
Some(id) => self
|
||||
.label_accents
|
||||
.remove(id.normalized_value(XmlVersion::Implicit1_0)?.as_ref()),
|
||||
None => None,
|
||||
};
|
||||
if let Some(label_accent) = label_accent {
|
||||
self.accent_g_stack.push(match label_accent {
|
||||
Some(accent_idx) => AccentStackEntry::accent(accent_idx, false),
|
||||
None => AccentStackEntry::none(),
|
||||
});
|
||||
self.label_definition_depth = Some(self.accent_g_stack.len());
|
||||
return Ok(event);
|
||||
}
|
||||
|
||||
let is_node = if let Some(class_attr) = e.try_get_attribute("class")? {
|
||||
let class = class_attr.normalized_value(XmlVersion::Implicit1_0)?;
|
||||
class
|
||||
@@ -69,6 +90,9 @@ impl ClassDiagramAccents {
|
||||
}
|
||||
|
||||
Event::End(e) if e.name().as_ref() == b"g" => {
|
||||
if self.label_definition_depth == Some(self.accent_g_stack.len()) {
|
||||
self.label_definition_depth = None;
|
||||
}
|
||||
if let Some(entry) = self.accent_g_stack.pop() {
|
||||
if entry.tracks_node() {
|
||||
self.nodes.maybe_finish_node();
|
||||
@@ -77,6 +101,19 @@ impl ClassDiagramAccents {
|
||||
Ok(event)
|
||||
}
|
||||
|
||||
Event::Start(e) | Event::Empty(e) if e.name().as_ref() == b"use" => {
|
||||
if let Some(href) = e.try_get_attribute("href")? {
|
||||
let href = href.normalized_value(XmlVersion::Implicit1_0)?;
|
||||
if let Some(id) = href.strip_prefix('#') {
|
||||
self.label_accents.insert(
|
||||
id.to_string(),
|
||||
super::current_stack_accent(&self.accent_g_stack),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(event)
|
||||
}
|
||||
|
||||
Event::Start(e) | Event::Empty(e)
|
||||
if matches!(
|
||||
e.name().as_ref(),
|
||||
@@ -96,12 +133,14 @@ impl ClassDiagramAccents {
|
||||
let is_start = matches!(event, Event::Start(_));
|
||||
let is_text = e.name().as_ref() == b"text";
|
||||
|
||||
let accent_idx = if is_text {
|
||||
let accent_idx = if !is_text {
|
||||
self.current_text_accent
|
||||
} else if self.label_definition_depth.is_some() {
|
||||
super::current_stack_accent(&self.accent_g_stack)
|
||||
} else {
|
||||
self.nodes
|
||||
.lookup_accent(e)
|
||||
.or_else(|| super::current_stack_accent(&self.accent_g_stack))
|
||||
} else {
|
||||
self.current_text_accent
|
||||
};
|
||||
|
||||
if let Some(idx) = accent_idx {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user